branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>pragya32/task<file_sep>/src/App.js import Data from "./data.json"; import React from "react"; import "./App.css"; function App() { return ( <div> {Data.map((data) => { return ( <div className="card-container"> <div className="image-container">{data.days}</div> <div className="card-title"></div> </div> ); })} </div> ); } export default App;
c715aa5fc3a5bc342d981fb4740437efc281c96b
[ "JavaScript" ]
1
JavaScript
pragya32/task
b939471232f137d2ee13be2519596eb7839485ca
982c7c15e5cad17c1973194b1a086b97595ccb7f
refs/heads/master
<repo_name>pitikay/raspberry-websocket-streamer<file_sep>/vendor/dist/controller.js class Controller { constructor(url) { this.url = url; console.log("Trying to Connect"); // Websocket initialization if (this.ws != undefined) { this.ws.close(); delete this.ws; } this.ws = new WebSocket(url); this.ws.binaryType = "arraybuffer"; this.ws.onopen = () => { console.log("Connected to " + url); }; } SteerLeft() { var message = "S0"; this.ws.send(message); } SteerRight() { var message = "S100"; this.ws.send(message); } SteerMiddle() { var message = "S50"; this.ws.send(message); } Gas(amount) { var message = "A"+amount; this.ws.send(message); } Reverse(amount) { var message = "R"+amount; this.ws.send(message); } Brake() { var message = "B0"; this.ws.send(message); } Emergency() { var message = "E0"; this.ws.send(message); } } <file_sep>/lib/_server.js "use strict"; const WebSocketServer = require('ws').Server; const Splitter = require('stream-split'); const merge = require('mout/object/merge'); const util = require('util'); const spawn = require('child_process').spawn; const Controller = require('./_controller'); const NALseparator = new Buffer([0,0,0,1]);//NAL break class _Server { constructor(server, options) { this.options = merge({ width : 960, height: 540, fps: 30, }, options); this.broadcasting = false; this.wss = new WebSocketServer({ server: server, clientTracking: true }); this.new_client = this.new_client.bind(this); this.start_feed = this.start_feed.bind(this); this.broadcast = this.broadcast.bind(this); this.wss.on('connection', this.new_client); this.start_feed(); } start_feed() { if(!this.broadcasting) { var readStream = this.get_feed(); this.readStream = readStream; this.readStream = readStream.pipe(new Splitter(NALseparator)); this.readStream.on("data", this.broadcast); } } get_feed() { var msk = "raspivid -rot 90 -t 0 -o - -w %d -h %d -fps %d"; var cmd = util.format(msk, this.options.width, this.options.height, this.options.fps); console.log(cmd); var streamer = spawn('raspivid', ['-rot', '90', '-t', '0', '-o', '-', '-w', this.options.width, '-h', this.options.height, '-fps', this.options.fps, '-pf', 'baseline']); streamer.on("exit", function(code){ console.log("Failure", code); }); this.broadcasting = true; return streamer.stdout; } broadcast(data) { this.wss.clients.forEach(function(socket) { if(socket.buzy) return; socket.buzy = true; socket.buzy = false; socket.send(Buffer.concat([NALseparator, data]), { binary: true}, function ack(error) { socket.buzy = false; }); }); } new_client(socket) { var self = this; console.log('new stream client connected'); socket.send(JSON.stringify({ action : "init", width : this.options.width, height : this.options.height, })); this.broadcasting = false; this.readStream.end(); const execSync = require('child_process').execSync; execSync('killall raspivid'); // a little dirty, but should be failsafe this.start_feed(); socket.on('close', function() { console.log('client disconnected'); }); } }; module.exports = _Server; <file_sep>/README.md # Motivation For my Raspberry RC-Car project, I needed a streaming protocol that does not send raw frames for bandwith reasons, has a really low latency (< 200ms) and the client should be as portable as possible. After countless hours of searching for the perfect protocol, I stumbled upon [h264-live-player](https://www.npmjs.com/package/h264-live-player), which is a work-in-progress h264 streamer using websockets! I noticed really really low latency with this, so I'm starting to rework this piece of art (< 200ms h264 streaming from a raspberry to multiple browsers!!) into a raspicam-only streaming service. Since a websocket connection is open anyway, I will use this also to control the RC Car. [![License](https://img.shields.io/badge/license-MIT-blue.svg)](http://opensource.org/licenses/MIT) # Installation/demo ``` git clone https://github.com/pitikay/raspberry-websocket-streamer.git cd raspberry-websocket-streamer npm install node server-rpi.js # run on a rpi for a webcam demo # browse to http://<raspberry-ip>:8080/ for a demo player ``` #TODO * Implement controlling of ESC and Servo * Implement authentication for controller / viewer * Implement limit of one controller # Recommendations (from h264-live-player) * Broadway h264 Decoder can only work with **h264 baseline profile** * [**Use a SANE birate**](https://www.dr-lex.be/info-stuff/videocalc.html) * Browserify FTW * Once you understand how to integrate the server-side, feel free to use [h264-live-player](https://www.npmjs.com/package/h264-live-player) npm package in your client side app (see vendor/) * Use [uws](https://github.com/uWebSockets/uWebSockets) (instead of ws) as websocket server # Credits * [131](mailto:<EMAIL>) * [Broadway](https://github.com/mbebenita/Broadway) * [urbenlegend/WebStreamer](https://github.com/urbenlegend/WebStreamer)
864a07f5c8ee7175cd29ef2cdfb8dc9ec7b0d7b7
[ "JavaScript", "Markdown" ]
3
JavaScript
pitikay/raspberry-websocket-streamer
9af00fb73bd088269602fe931edacaeca8dd7f92
0b37a662fea0f17c7bacff32fd7be65f775b9434
refs/heads/master
<repo_name>DanielJochem/Final-Project-Prototypes<file_sep>/Final Project Level Creation Tool/Assets/Scripts/LevelLoader.cs using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.UI; public class LevelLoader : MonoBehaviour { private UIRelatedStuff uiRelatedStuff; private CameraBehaviour cameraBehaviour; private TilePlacer tilePlacer; private int xTilesCSV, yTilesCSV, objectsPerRow, amountOfRows; private string[] loadedCSVString; [SerializeField] private GameObject wallObj, floorObj, doorObj, doorKeyObj, chestObj, chestKeyObj, playerObj, enemyObj, bossObj, armourObj, weaponObj, potionObj; [SerializeField] private GameObject placementTile; [HideInInspector] public List<GameObject> placementTilesGridList; private Vector3 currPos; [HideInInspector] public bool firstTime, isFromLevelLoader, alreadyCheckedFileExists; private bool fileExists; [HideInInspector] public bool loadLevel, canOverwriteLevel; [HideInInspector] public string currentLoadedLevel = "iAmSomeTempText"; void Start() { uiRelatedStuff = FindObjectOfType<UIRelatedStuff>(); cameraBehaviour = FindObjectOfType<CameraBehaviour>(); tilePlacer = FindObjectOfType<TilePlacer>(); } public void LoadLevel() { if(!alreadyCheckedFileExists) { fileExists = (System.IO.File.Exists(Application.dataPath + "/Saved Levels/" + uiRelatedStuff.levelName + ".csv") == true) ? true : false; alreadyCheckedFileExists = true; if(currentLoadedLevel == uiRelatedStuff.levelName) { uiRelatedStuff.EnableSameLevelErrorText(); fileExists = false; } else if(fileExists && uiRelatedStuff.xySaved) { uiRelatedStuff.EnableOverwriteProgressErrorText(); fileExists = false; } else if(fileExists) { loadLevel = true; currentLoadedLevel = uiRelatedStuff.levelName; fileExists = false; } else { uiRelatedStuff.EnableLevelDoesNotExistErrorText(); } } if(canOverwriteLevel) { currentLoadedLevel = uiRelatedStuff.levelName; canOverwriteLevel = false; } if(loadLevel) { uiRelatedStuff.levelLoaded = false; if(uiRelatedStuff.xySaved) { uiRelatedStuff.xySaved = false; uiRelatedStuff.xTilesIF.interactable = false; uiRelatedStuff.yTilesIF.interactable = false; foreach(GameObject tile in placementTilesGridList) { Destroy(tile.gameObject); } placementTilesGridList.Clear(); } uiRelatedStuff.levelLoaded = false; loadedCSVString = ReadCSV(uiRelatedStuff.levelName); firstTime = true; CSVLevelLoader(); firstTime = false; uiRelatedStuff.xTiles = xTilesCSV; uiRelatedStuff.xTilesIF.text = uiRelatedStuff.xTiles.ToString(); uiRelatedStuff.yTiles = yTilesCSV; uiRelatedStuff.yTilesIF.text = uiRelatedStuff.yTiles.ToString(); cameraBehaviour.cameraHeightMax = 0; cameraBehaviour.cameraZooming(); uiRelatedStuff.thisIsACSVLoadedLevel = true; isFromLevelLoader = true; uiRelatedStuff.LoadTheLevel(); CSVLevelLoader(); loadLevel = false; alreadyCheckedFileExists = false; } } public string[] ReadCSV(string levelNameCSV) { string getCSV = System.IO.File.ReadAllText(Application.dataPath + "/Saved Levels/" + uiRelatedStuff.levelName + ".csv"); return getCSV.Split(new char[] { '\n', '\r', ',' }, System.StringSplitOptions.RemoveEmptyEntries); } void CSVLevelLoader() { int currentTile = 0; if(firstTime) { for(int i = 0; i < 3; ++i) { switch(i) { case 0: continue; case 1: xTilesCSV = int.Parse(loadedCSVString[i]); break; case 2: yTilesCSV = int.Parse(loadedCSVString[i]); break; } } } else { for(int j = 0; j < loadedCSVString.Length; ++j) { switch(j) { case 0: continue; case 1: continue; case 2: continue; default: placementTilesGridList[currentTile].gameObject.transform.GetChild(0).gameObject.GetComponent<SpriteRenderer>().sprite = (loadedCSVString[j] == "Wall" ? wallObj : loadedCSVString[j] == "Floor" ? floorObj : loadedCSVString[j] == "Door" ? doorObj : loadedCSVString[j] == "Door Key" ? doorKeyObj : loadedCSVString[j] == "Chest" ? chestObj : loadedCSVString[j] == "Chest Key" ? chestKeyObj : loadedCSVString[j] == "Player" ? playerObj : loadedCSVString[j] == "Enemy" ? enemyObj : loadedCSVString[j] == "Boss" ? bossObj : loadedCSVString[j] == "Armour" ? armourObj : loadedCSVString[j] == "Weapon" ? weaponObj : potionObj).GetComponent<SpriteRenderer>().sprite; if(loadedCSVString[j] == "Player") { tilePlacer.playerTilePlaced = placementTilesGridList[currentTile].gameObject.transform.GetChild(0).gameObject; } currentTile++; break; } } foreach(GameObject tile in placementTilesGridList) { tile.transform.GetChild(0).gameObject.GetComponent<PlacementTileListNumber>().isBlank = false; } } } }<file_sep>/Level Creating Tool 5.5 - DO NOT USE/Assets/Scripts/TilePlacer.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; using System.Text; public class TilePlacer : MonoBehaviour { public GameObject selectedTile, placementTile; public Sprite selectedTileSprite, placementTileSprite, voidTileSprite; public GameObject backdrop; /**/ private GameObject playerTilePlaced; public int tileSize; public List<GameObject> tiles; [SerializeField] private Text fileExistsText; [SerializeField] private Text saveErrorText; private bool levelLoaded, canSave; public InputField xTilesIF, yTilesIF, levelNameIF; public EventSystem eventSystem; public bool xySaved; public List<string> saveErrorArray; public int xTiles, yTiles; public string levelName; void Awake() { xTiles = yTiles = 0; eventSystem.firstSelectedGameObject = xTilesIF.gameObject; //Just in case. eventSystem.SetSelectedGameObject(xTilesIF.gameObject); } void Update () { //Switching between the X and Y amount input fields at the start of the game. if(Input.GetKeyDown(KeyCode.Tab)) { //I think I am addicted to ternary operators... eventSystem.SetSelectedGameObject(eventSystem.currentSelectedGameObject == xTilesIF.gameObject ? yTilesIF.gameObject : xTilesIF.gameObject); } //Saving the X and Y Input fields, we can now load the level. if(Input.GetKeyDown(KeyCode.Return) && xTiles > 0 && yTiles > 0 && !xySaved) { xTilesIF.interactable = false; yTilesIF.interactable = false; xySaved = true; } //Loading the level if(!levelLoaded) { if(xySaved) { float xStartPos = -((xTiles * tileSize) / 2) + ((tileSize / 2) + 0.5f); float yStartPos = ((yTiles * tileSize) / 2) - ((tileSize / 2) + 0.5f); Vector3 currPos = new Vector3(xStartPos, yStartPos, 2); for(int y = 0; y < yTiles; ++y) { for(int x = 0; x < xTiles; ++x) { GameObject tempObj; tempObj = Instantiate(placementTile, currPos, Quaternion.Euler(270.0f, 0.0f, 0.0f)); tiles.Add(tempObj); tempObj.transform.GetChild(0).GetComponent<PlacementTileListNumber>().listNum = tiles.Count; //Next X position currPos.x += tileSize; } //End of a row? Next Y positionand start form first X position again. currPos = new Vector3(xStartPos, currPos.y -= tileSize, 2); } //Backdrop re-scaling based on how many tiles x and y was entered. //The '+ 0.1f' is so there is a 0.1 boarder around the tiles. backdrop.transform.localScale = new Vector3((0.5f * xTiles) + 0.1f, 0, (0.5f * yTiles) + 0.1f); //If x or y or both were an odd number, fix up the position of the backdrop by 0.5. if(xTiles % 2 == 1 && yTiles % 2 == 0) { backdrop.transform.position = new Vector3(backdrop.transform.position.x + 0.5f, backdrop.transform.position.y, 2); } else if(xTiles % 2 == 0 && yTiles % 2 == 1) { backdrop.transform.position = new Vector3(backdrop.transform.position.x, backdrop.transform.position.y - 0.5f, 2); } else if(xTiles % 2 == 1 && yTiles % 2 == 1) { backdrop.transform.position = new Vector3(backdrop.transform.position.x + 0.5f, backdrop.transform.position.y - 0.5f, 2); } levelLoaded = true; } } } void EnableSaveErrorText() { saveErrorText.gameObject.SetActive(true); } public void DisableSaveErrorText() { saveErrorText.gameObject.SetActive(false); } void EnableFileExistsText() { fileExistsText.gameObject.SetActive(true); } public void OverrideFileExists() { DisableFileExistsText(); SaveLevel(); } public void DisableFileExistsText() { fileExistsText.gameObject.SetActive(false); } public void SetXTiles(InputField inputField) { xTiles = int.Parse(inputField.text); } public void SetYTiles(InputField inputField) { yTiles = int.Parse(inputField.text); } public void SetLevelName(InputField inputField) { levelName = inputField.text; } public void OnTileClicked(GameObject tile) { if(selectedTile != null) { if(selectedTile.name == "Player") { //If there is already a Player tile somewhere on the gid of tiles, get rid of it. if(playerTilePlaced != null) { playerTilePlaced.GetComponent<SpriteRenderer>().sprite = placementTileSprite; playerTilePlaced.GetComponent<PlacementTileListNumber>().isBlank = true; } //If you are clicking on the same tile as there is already a Player tile on, you obviously want to get rid of it. if(playerTilePlaced == tile) { playerTilePlaced.GetComponent<SpriteRenderer>().sprite = placementTileSprite; playerTilePlaced.GetComponent<PlacementTileListNumber>().isBlank = true; playerTilePlaced = null; } else { //Place the Player tile here tile.GetComponent<SpriteRenderer>().sprite = selectedTileSprite; tile.GetComponent<PlacementTileListNumber>().isBlank = false; playerTilePlaced = tile; } } else { //Don't worry about the Player tile logic, just place the selected tile here. if(tile.GetComponent<SpriteRenderer>().sprite == selectedTileSprite) { tile.GetComponent<SpriteRenderer>().sprite = placementTileSprite; tile.GetComponent<PlacementTileListNumber>().isBlank = true; } else { tile.GetComponent<SpriteRenderer>().sprite = selectedTileSprite; tile.GetComponent<PlacementTileListNumber>().isBlank = false; } } } } public void GetRidOfSelectedTile() { //Just some safety for if the save button is just about to be pressed, as we don'w want to place a sneaky, un-wanted tile before it saves to CSV. selectedTile = null; selectedTileSprite = null; } public void TestForErrorOnSave() { StringBuilder saveCheckSB = new StringBuilder(); //if there are places that havent been filled with void for(int i = 0; i < tiles.Count; ++i) { if(tiles[i].transform.GetChild(0).GetComponent<PlacementTileListNumber>().isBlank) { saveCheckSB.Append("Not all tiles have an object, try doing a Void Fill.").AppendLine(); break; } } if(levelNameIF.text.Length == 0) { saveCheckSB.Append("There is no input for Level Name.").AppendLine(); } if(xTilesIF.text.Length == 0 && yTilesIF.text.Length == 0) { saveCheckSB.Append("There are no inputs for both X Amount and Y Amount.").AppendLine(); } else if(int.Parse(xTilesIF.text) <= 0 && int.Parse(yTilesIF.text) <= 0) { saveCheckSB.Append("Both X Amount and Y Amount are less than or equal to 0.").AppendLine(); } else { if(xTilesIF.text.Length == 0) { saveCheckSB.Append("There is no input for X Amount.").AppendLine(); } else if(int.Parse(xTilesIF.text) <= 0) { saveCheckSB.Append("X Amount is less than or equal to 0.").AppendLine(); } if(yTilesIF.text.Length == 0) { saveCheckSB.Append("There is no input for Y AMount.").AppendLine(); } else if(int.Parse(yTilesIF.text) <= 0) { saveCheckSB.Append("Y Amount is less than or equal to 0.").AppendLine(); } if(playerTilePlaced == null) { saveCheckSB.Append("There is no Player tile placed on the grid.").AppendLine(); } } if(saveCheckSB.Length > 0) { saveCheckSB.Remove(saveCheckSB.Length - 1, 1); saveErrorText.text = "Can not save because:\n" + saveCheckSB.ToString(); EnableSaveErrorText(); saveCheckSB.Remove(0, saveCheckSB.Length - 1); } else { if(System.IO.File.Exists(Application.dataPath + "/Saved Levels/" + levelName + ".csv")) { EnableFileExistsText(); } else { //Can Save! SaveLevel(); } } } void SaveLevel() { StringBuilder saveSB = new StringBuilder(); saveSB.Append(levelName).Append(", "); saveSB.Append(xTiles).Append(", "); saveSB.Append(yTiles).Append(", "); saveSB.AppendLine(); for(int i = 0; i < tiles.Count; ++i) { saveSB.Append(tiles[i].transform.GetChild(0).GetComponent<SpriteRenderer>().sprite.name).Append(", "); if((i + 1) % xTiles == 0) { saveSB.AppendLine(); } } System.IO.File.WriteAllText(Application.dataPath + "/Saved Levels/" + levelName + ".csv", saveSB.ToString()); Debug.Log("Saved Successfully!"); } public void VoidFillLevel() { for(int i = 0; i < tiles.Count; ++i) { if(tiles[i].transform.GetChild(0).GetComponent<PlacementTileListNumber>().isBlank) { tiles[i].transform.GetChild(0).GetComponent<SpriteRenderer>().sprite = voidTileSprite; tiles[i].transform.GetChild(0).GetComponent<PlacementTileListNumber>().isBlank = false; } } } }<file_sep>/Final Project Level Creation Tool/Assets/Scripts/PlacementTileListNumber.cs using UnityEngine; public class PlacementTileListNumber : MonoBehaviour { [HideInInspector] public int listNum; //[HideInInspector] public bool isBlank; private bool tileSet; private TilePlacer tilePlacer; private LevelLoader levelLoader; void Awake() { tilePlacer = FindObjectOfType<TilePlacer>(); levelLoader = FindObjectOfType<LevelLoader>(); if(!levelLoader.isFromLevelLoader) { isBlank = true; } } void OnMouseOver() { if((Input.GetMouseButton(0) || Input.GetMouseButton(1)) && !tileSet) { tileSet = true; tilePlacer.OnTileClicked(gameObject); } } void OnMouseExit() { tileSet = false; } void OnMouseUp() { tileSet = false; } } <file_sep>/Final Project Level Creation Tool/Assets/Scripts/UIRelatedStuff.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; using System.Text; public class UIRelatedStuff : MonoBehaviour { private TilePlacer tilePlacer; private LevelLoader levelLoader; private UIRelatedStuff uiRelatedStuff; private GameObject backdrop; [HideInInspector] public int tileSize; [HideInInspector] public List<GameObject> tiles; [SerializeField] private Text fileExistsText, saveErrorText, levelDoesNotExistErrorText, overwriteProgressErrorText, sameLevelErrorText; [HideInInspector] public bool levelLoaded, xySaved, thisIsACSVLoadedLevel, cameFromLoadingLevel; private bool canSave, cameFromIF, firstTimeLoadingALevel, goodNowBad; public InputField xTilesIF, yTilesIF, levelNameIF; public EventSystem eventSystem; private List<string> saveErrorArray; [HideInInspector] public int xTiles, yTiles; [HideInInspector] public string levelName; void Awake() { tilePlacer = FindObjectOfType<TilePlacer>(); levelLoader = FindObjectOfType<LevelLoader>(); uiRelatedStuff = FindObjectOfType<UIRelatedStuff>(); backdrop = GameObject.Find("Backdrop"); tileSize = 5; xTiles = yTiles = 0; eventSystem.firstSelectedGameObject = xTilesIF.gameObject; } void Update() { //Switching between the X and Y amount input fields at the start of the game. if(Input.GetKeyDown(KeyCode.Tab)) { //I think I am addicted to ternary operators... eventSystem.SetSelectedGameObject(eventSystem.currentSelectedGameObject == xTilesIF.gameObject ? yTilesIF.gameObject : xTilesIF.gameObject); } LoadTheLevel(); } public void LoadTheLevel() { //Saving the X and Y Input fields, we can now load the level. if((Input.GetKeyDown(KeyCode.Return) && xTiles > 0 && yTiles > 0 && !xySaved) || thisIsACSVLoadedLevel) { xTilesIF.interactable = false; yTilesIF.interactable = false; tiles.Clear(); xySaved = true; thisIsACSVLoadedLevel = false; } //Loading the level if(!levelLoaded) { if(xySaved) { float xStartPos = -((xTiles * tileSize) / 2) + ((tileSize / 2) + 0.5f); float yStartPos = ((yTiles * tileSize) / 2) - ((tileSize / 2) + 0.5f); Vector3 currPos = new Vector3(xStartPos, yStartPos, 2); for(int y = 0; y < yTiles; ++y) { for(int x = 0; x < xTiles; ++x) { GameObject tempObj; tempObj = Instantiate(tilePlacer.placementTile, currPos, Quaternion.Euler(270.0f, 0.0f, 0.0f)) as GameObject; levelLoader.placementTilesGridList.Add(tempObj); tiles.Add(tempObj); tempObj.transform.GetChild(0).GetComponent<PlacementTileListNumber>().listNum = tiles.Count; //Next X position currPos.x += tileSize; } //End of a row? Next Y position and start form first X position again. currPos = new Vector3(xStartPos, currPos.y -= tileSize, 2); } levelLoader.isFromLevelLoader = false; //Backdrop re-scaling based on how many tiles x and y was entered. //The '+ 0.1f' is so there is a 0.1 boarder around the tiles. backdrop.transform.localScale = new Vector3((0.5f * xTiles) + 0.1f, 0, (0.5f * yTiles) + 0.1f); //If x or y or both were an odd number, fix up the position of the backdrop by 0.5. if(xTiles % 2 == 1 && yTiles % 2 == 0) { backdrop.transform.position = new Vector3(backdrop.transform.position.x + 0.5f, backdrop.transform.position.y, 2); } else if(xTiles % 2 == 0 && yTiles % 2 == 1) { backdrop.transform.position = new Vector3(backdrop.transform.position.x, backdrop.transform.position.y - 0.5f, 2); } else if(xTiles % 2 == 1 && yTiles % 2 == 1) { if(firstTimeLoadingALevel || goodNowBad) { backdrop.transform.position = new Vector3(backdrop.transform.position.x + 0.5f, backdrop.transform.position.y - 0.5f, 2); goodNowBad = false; } } if(!firstTimeLoadingALevel) { if(xTiles % 2 == 0 && yTiles % 2 == 0) { backdrop.transform.position = new Vector3(0, 0, 2); goodNowBad = true; } } firstTimeLoadingALevel = false; levelLoaded = true; } } } void EnableSaveErrorText() { saveErrorText.gameObject.SetActive(true); } public void DisableSaveErrorText() { saveErrorText.gameObject.SetActive(false); } void EnableFileExistsText() { fileExistsText.gameObject.SetActive(true); } public void OverrideFileExists() { DisableFileExistsText(); SaveLevel(); } public void DisableFileExistsText() { fileExistsText.gameObject.SetActive(false); } public void EnableSameLevelErrorText() { sameLevelErrorText.gameObject.SetActive(true); } public void DisableSameLevelErrorText() { sameLevelErrorText.gameObject.SetActive(false); } public void EnableLevelDoesNotExistErrorText() { levelDoesNotExistErrorText.gameObject.SetActive(true); } public void DisableLevelDoesNotExistErrorText() { levelDoesNotExistErrorText.gameObject.SetActive(false); levelLoader.alreadyCheckedFileExists = false; } public void EnableOverwriteProgressErrorText() { overwriteProgressErrorText.gameObject.SetActive(true); } public void DisableOverwriteProgressErrorText() { overwriteProgressErrorText.gameObject.SetActive(false); } public void OverwriteProgress() { DisableOverwriteProgressErrorText(); DisableSameLevelErrorText(); levelLoader.canOverwriteLevel = true; levelLoader.loadLevel = true; levelLoader.LoadLevel(); } public void SetXTiles(InputField inputField) { xTiles = int.Parse(inputField.text); } public void SetYTiles(InputField inputField) { yTiles = int.Parse(inputField.text); } public void SetLevelName(InputField inputField) { levelName = inputField.text; } public void GetRidOfSelectedTile() { //Just some safety for if the save button is just about to be pressed, as we don't want to place a sneaky, un-wanted tile before it saves to CSV. tilePlacer.selectedTile = null; tilePlacer.selectedTileSprite = null; } public void TestForErrorOnSave() { StringBuilder saveCheckSB = new StringBuilder(); int chestsPlaced = 0, chestKeysPlaced = 0, doorsPlaced = 0, doorKeysPlaced = 0; for(int i = 0; i < FindObjectsOfType<SpriteRenderer>().Length; ++i) { if(FindObjectsOfType<SpriteRenderer>()[i].sprite.name == "Chest") { chestsPlaced++; } if(FindObjectsOfType<SpriteRenderer>()[i].sprite.name == "Chest Key") { chestKeysPlaced++; } if(FindObjectsOfType<SpriteRenderer>()[i].sprite.name == "Door") { doorsPlaced++; } if(FindObjectsOfType<SpriteRenderer>()[i].sprite.name == "Door Key") { doorKeysPlaced++; } } if(chestsPlaced != chestKeysPlaced) { saveCheckSB.Append("The amount of Chests and Chest Keys do not match.").AppendLine(); } if(doorsPlaced != doorKeysPlaced) { saveCheckSB.Append("The amount of Doors and Door Keys do not match.").AppendLine(); } //If there are places that haven't been filled with void for(int i = 0; i < tiles.Count; ++i) { if(tiles[i].transform.GetChild(0).GetComponent<PlacementTileListNumber>().isBlank) { saveCheckSB.Append("Not all tiles have an object, try doing a Void Fill.").AppendLine(); break; } } if(levelNameIF.text.Length == 0) { saveCheckSB.Append("There is no input for Level Name.").AppendLine(); } if(xTilesIF.text.Length == 0 && yTilesIF.text.Length == 0) { saveCheckSB.Append("There are no inputs for both X Amount and Y Amount.").AppendLine(); } else if(int.Parse(xTilesIF.text) <= 0 && int.Parse(yTilesIF.text) <= 0) { saveCheckSB.Append("Both X Amount and Y Amount are less than or equal to 0.").AppendLine(); } else { if(xTilesIF.text.Length == 0) { saveCheckSB.Append("There is no input for X Amount.").AppendLine(); } else if(int.Parse(xTilesIF.text) <= 0) { saveCheckSB.Append("X Amount is less than or equal to 0.").AppendLine(); } if(yTilesIF.text.Length == 0) { saveCheckSB.Append("There is no input for Y Amount.").AppendLine(); } else if(int.Parse(yTilesIF.text) <= 0) { saveCheckSB.Append("Y Amount is less than or equal to 0.").AppendLine(); } if(tilePlacer.playerTilePlaced == null) { saveCheckSB.Append("There is no Player tile placed on the grid.").AppendLine(); } } if(saveCheckSB.Length > 0) { saveCheckSB.Remove(saveCheckSB.Length - 1, 1); saveErrorText.text = "Can not save because:\n" + saveCheckSB.ToString(); EnableSaveErrorText(); saveCheckSB.Remove(0, saveCheckSB.Length - 1); } else { if(System.IO.File.Exists(Application.dataPath + "/Saved Levels/" + levelName + ".csv")) { EnableFileExistsText(); } else { //Can Save! SaveLevel(); } } } void SaveLevel() { StringBuilder saveSB = new StringBuilder(); saveSB.Append(levelName).Append(","); saveSB.Append(xTiles).Append(","); saveSB.Append(yTiles).Append(","); saveSB.AppendLine(); for(int i = 0; i < tiles.Count; ++i) { saveSB.Append(tiles[i].transform.GetChild(0).GetComponent<SpriteRenderer>().sprite.name).Append(","); if((i + 1) % xTiles == 0) { saveSB.AppendLine(); } } System.IO.File.WriteAllText(Application.dataPath + "/Saved Levels/" + levelName + ".csv", saveSB.ToString()); Debug.Log("Saved Successfully!"); } public void VoidFillLevel() { for(int i = 0; i < tiles.Count; ++i) { if(tiles[i].transform.GetChild(0).GetComponent<PlacementTileListNumber>().isBlank) { tiles[i].transform.GetChild(0).GetComponent<SpriteRenderer>().sprite = tilePlacer.voidTileSprite; tiles[i].transform.GetChild(0).GetComponent<PlacementTileListNumber>().isBlank = false; } } } }<file_sep>/Level Creating Tool 5.5 - DO NOT USE/Assets/Scripts/CameraBehaviour.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraBehaviour : MonoBehaviour { public GameObject cameraGameObject; private Vector3 cameraPos; private string sizeByXY; private TilePlacer tilePlacer; public float cameraMovementSpeed = 30.0f; public float cameraHeightCurrent; public bool invertMovement; //Mouse zoom public float cameraHeightIncrement; private float cameraHeightMin = 20; private float cameraHeightMax = 0; // Use this for initialization void Start() { cameraPos = transform.position; cameraHeightCurrent = Camera.main.orthographicSize; tilePlacer = FindObjectOfType<TilePlacer>(); } // Update is called once per frame void Update() { if(tilePlacer.xySaved) { moveCamera(); cameraZooming(); if(cameraHeightCurrent < cameraHeightMin) cameraHeightCurrent = cameraHeightMin; if(cameraHeightCurrent > cameraHeightMax) { cameraHeightCurrent = cameraHeightMax; //Move the camera a little bit so that the fully zoomed out level is centered! (Makes things beautifully centered). cameraPos.y = (sizeByXY == "X") ? -(tilePlacer.xTiles / 8) : -(tilePlacer.yTiles / 4); transform.position = cameraPos; } cameraMovementSpeed = cameraHeightCurrent * 2; } } //Controls affecting the zoom and placement of the camera void cameraZooming() { if(cameraHeightMax == 0) { cameraHeightMax = SetZoomLimit(); cameraHeightCurrent = cameraHeightMax; //Move the camera a little bit so that the zoomed out blank level is centered! (It looks beautiful, trust me). cameraPos.y = (sizeByXY == "X") ? -(tilePlacer.xTiles / 8) : -(tilePlacer.yTiles / 4); transform.position = cameraPos; } //Move camera focus and height based on raycast from maincamera RaycastHit hit; Vector2 direction = (transform.position - cameraGameObject.transform.position).normalized; if(Physics.Raycast(cameraGameObject.transform.position, direction, out hit, 1000.0f)) { Debug.DrawLine(cameraGameObject.transform.position, hit.point); //Adjust height of the cameraHeight based on difference from focus point if(Vector2.Distance(transform.position, cameraGameObject.transform.position) != cameraHeightCurrent) { Vector2 newPos = cameraGameObject.transform.position; Camera.main.orthographicSize = cameraHeightCurrent; cameraGameObject.transform.position = newPos; } } cameraHeightIncrement = cameraHeightCurrent / tilePlacer.tileSize; //Adjust Camera Height - Scrollwheel if(Input.GetAxis("Mouse ScrollWheel") > 0 && cameraHeightCurrent > cameraHeightMin) { cameraHeightCurrent -= cameraHeightIncrement; } else if(Input.GetAxis("Mouse ScrollWheel") < 0 && cameraHeightCurrent < cameraHeightMax) { cameraHeightCurrent += cameraHeightIncrement; } Camera.main.orthographicSize = cameraHeightCurrent; } //Move Camera using mouse void moveCamera() { if(!FindObjectOfType<TilePlacer>().levelNameIF.isFocused) { cameraMovementSpeed = invertMovement ? Mathf.Abs(cameraMovementSpeed) : -Mathf.Abs(cameraMovementSpeed); if(Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A)) { transform.Translate(Vector2.right * cameraMovementSpeed * Time.deltaTime); } if(Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D)) { transform.Translate(Vector2.right * -cameraMovementSpeed * Time.deltaTime); } if(Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S)) { transform.Translate(transform.up * cameraMovementSpeed * Time.deltaTime); } if(Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W)) { transform.Translate(transform.up * -cameraMovementSpeed * Time.deltaTime); } } } float SetZoomLimit() { float temp; if(((float)tilePlacer.xTiles / (float)tilePlacer.yTiles) >= 2.5f) { temp = tilePlacer.xTiles * 1.25f; sizeByXY = "X"; } else { temp = tilePlacer.yTiles * 3.5f; sizeByXY = "Y"; } return temp; } }<file_sep>/Final Project Level Creation Tool/Assets/Scripts/EventManager/ChooseTile.cs using UnityEngine; using UnityEngine.UI; using System.Collections; using System.Collections.Generic; public class ChooseTile : MonoBehaviour { private TilePlacer tilePlacer; private TileSwapper tileSwapper; private UIRelatedStuff uiRelatedStuff; public List<GameObject> UITiles; public Sprite placeSprite, swapSprite; void Awake () { EventManager.AddListener<KeyPressedEvent>(OnKeyPressed); tilePlacer = FindObjectOfType<TilePlacer>(); tileSwapper = FindObjectOfType<TileSwapper>(); uiRelatedStuff = FindObjectOfType<UIRelatedStuff>(); } void OnDestroy() { EventManager.RemoveListener<KeyPressedEvent>(OnKeyPressed); } void OnKeyPressed(KeyPressedEvent a_event) { if(uiRelatedStuff.xySaved && !uiRelatedStuff.levelNameIF.isFocused) { switch(a_event.PressedKeyCode.ToString()) { case "Alpha1": case "Keypad1": if(Input.GetKey(KeyCode.LeftShift)) { UITiles[0].GetComponent<Image>().sprite = swapSprite; tileSwapper.ToSwap(UITiles[0].transform.GetChild(0).gameObject); } else { UITiles[0].GetComponent<Image>().sprite = placeSprite; tilePlacer.selectedTile = UITiles[0].transform.GetChild(0).gameObject; tilePlacer.selectedTileSprite = UITiles[0].transform.GetChild(0).gameObject.GetComponent<Image>().sprite; } break; case "Alpha2": case "Keypad2": if(Input.GetKey(KeyCode.LeftShift)) { UITiles[1].GetComponent<Image>().sprite = swapSprite; tileSwapper.ToSwap(UITiles[1].transform.GetChild(0).gameObject); } else { UITiles[1].GetComponent<Image>().sprite = placeSprite; tilePlacer.selectedTile = UITiles[1].transform.GetChild(0).gameObject; tilePlacer.selectedTileSprite = UITiles[1].transform.GetChild(0).gameObject.GetComponent<Image>().sprite; } break; case "Alpha3": case "Keypad3": if(Input.GetKey(KeyCode.LeftShift)) { UITiles[2].GetComponent<Image>().sprite = swapSprite; tileSwapper.ToSwap(UITiles[2].transform.GetChild(0).gameObject); } else { UITiles[2].GetComponent<Image>().sprite = placeSprite; tilePlacer.selectedTile = UITiles[2].transform.GetChild(0).gameObject; tilePlacer.selectedTileSprite = UITiles[2].transform.GetChild(0).gameObject.GetComponent<Image>().sprite; } break; case "Alpha4": case "Keypad4": if(Input.GetKey(KeyCode.LeftShift)) { UITiles[3].GetComponent<Image>().sprite = swapSprite; tileSwapper.ToSwap(UITiles[3].transform.GetChild(0).gameObject); } else { UITiles[3].GetComponent<Image>().sprite = placeSprite; tilePlacer.selectedTile = UITiles[3].transform.GetChild(0).gameObject; tilePlacer.selectedTileSprite = UITiles[3].transform.GetChild(0).gameObject.GetComponent<Image>().sprite; } break; case "Alpha5": case "Keypad5": if(Input.GetKey(KeyCode.LeftShift)) { UITiles[4].GetComponent<Image>().sprite = swapSprite; tileSwapper.ToSwap(UITiles[4].transform.GetChild(0).gameObject); } else { UITiles[4].GetComponent<Image>().sprite = placeSprite; tilePlacer.selectedTile = UITiles[4].transform.GetChild(0).gameObject; tilePlacer.selectedTileSprite = UITiles[4].transform.GetChild(0).gameObject.GetComponent<Image>().sprite; } break; case "Alpha6": case "Keypad6": if(Input.GetKey(KeyCode.LeftShift)) { UITiles[5].GetComponent<Image>().sprite = swapSprite; tileSwapper.ToSwap(UITiles[5].transform.GetChild(0).gameObject); } else { UITiles[5].GetComponent<Image>().sprite = placeSprite; tilePlacer.selectedTile = UITiles[5].transform.GetChild(0).gameObject; tilePlacer.selectedTileSprite = UITiles[5].transform.GetChild(0).gameObject.GetComponent<Image>().sprite; } break; case "Alpha7": case "Keypad7": if(Input.GetKey(KeyCode.LeftShift)) { UITiles[6].GetComponent<Image>().sprite = swapSprite; tileSwapper.ToSwap(UITiles[6].transform.GetChild(0).gameObject); } else { UITiles[6].GetComponent<Image>().sprite = placeSprite; tilePlacer.selectedTile = UITiles[6].transform.GetChild(0).gameObject; tilePlacer.selectedTileSprite = UITiles[6].transform.GetChild(0).gameObject.GetComponent<Image>().sprite; } break; case "Alpha8": case "Keypad8": if(Input.GetKey(KeyCode.LeftShift)) { UITiles[7].GetComponent<Image>().sprite = swapSprite; tileSwapper.ToSwap(UITiles[7].transform.GetChild(0).gameObject); } else { UITiles[7].GetComponent<Image>().sprite = placeSprite; tilePlacer.selectedTile = UITiles[7].transform.GetChild(0).gameObject; tilePlacer.selectedTileSprite = UITiles[7].transform.GetChild(0).gameObject.GetComponent<Image>().sprite; } break; case "Alpha9": case "Keypad9": if(Input.GetKey(KeyCode.LeftShift)) { UITiles[8].GetComponent<Image>().sprite = swapSprite; tileSwapper.ToSwap(UITiles[8].transform.GetChild(0).gameObject); } else { UITiles[8].GetComponent<Image>().sprite = placeSprite; tilePlacer.selectedTile = UITiles[8].transform.GetChild(0).gameObject; tilePlacer.selectedTileSprite = UITiles[8].transform.GetChild(0).gameObject.GetComponent<Image>().sprite; } break; case "Alpha0": case "KeypadDivide": if(Input.GetKey(KeyCode.LeftShift)) { UITiles[9].GetComponent<Image>().sprite = swapSprite; tileSwapper.ToSwap(UITiles[9].transform.GetChild(0).gameObject); } else { UITiles[9].GetComponent<Image>().sprite = placeSprite; tilePlacer.selectedTile = UITiles[9].transform.GetChild(0).gameObject; tilePlacer.selectedTileSprite = UITiles[9].transform.GetChild(0).gameObject.GetComponent<Image>().sprite; } break; case "Minus": case "KeypadMultiply": if(Input.GetKey(KeyCode.LeftShift)) { UITiles[10].GetComponent<Image>().sprite = swapSprite; tileSwapper.ToSwap(UITiles[10].transform.GetChild(0).gameObject); } else { UITiles[10].GetComponent<Image>().sprite = placeSprite; tilePlacer.selectedTile = UITiles[10].transform.GetChild(0).gameObject; tilePlacer.selectedTileSprite = UITiles[10].transform.GetChild(0).gameObject.GetComponent<Image>().sprite; } break; case "Equals": case "KeypadMinus": if(Input.GetKey(KeyCode.LeftShift)) { UITiles[11].GetComponent<Image>().sprite = swapSprite; tileSwapper.ToSwap(UITiles[11].transform.GetChild(0).gameObject); } else { UITiles[11].GetComponent<Image>().sprite = placeSprite; tilePlacer.selectedTile = UITiles[11].transform.GetChild(0).gameObject; tilePlacer.selectedTileSprite = UITiles[11].transform.GetChild(0).gameObject.GetComponent<Image>().sprite; } break; } } } }<file_sep>/Level Creating Tool 5.5 - DO NOT USE/Assets/Scripts/EventManager/KeyPressedEvent.cs using UnityEngine; using System.Collections; public class KeyPressedEvent : GameEvent { public KeyCode PressedKeyCode { get; private set; } public KeyPressedEvent(KeyCode a_keyCodePressed) { PressedKeyCode = a_keyCodePressed; } } <file_sep>/Level Creating Tool 5.5 - DO NOT USE/Assets/Scripts/EventManager/KeyListener.cs using UnityEngine; using System.Collections; public class KeyListener : MonoBehaviour { [SerializeField] private KeyCode[] m_keys; // Update is called once per frame void Update () { for (int i = 0; i < m_keys.Length; i++) { DetectKeyDown(m_keys[i]); } } void DetectKeyDown(KeyCode a_keyCode) { if (Input.GetKeyDown(a_keyCode)) { EventManager.Raise(new KeyPressedEvent(a_keyCode)); } } } <file_sep>/Final Project Level Creation Tool/Assets/Scripts/TilePlacer.cs using System.Collections; using UnityEngine; public class TilePlacer : MonoBehaviour { [HideInInspector] public GameObject selectedTile; [HideInInspector] public Sprite selectedTileSprite; [HideInInspector] public GameObject playerTilePlaced; public GameObject placementTile; public Sprite placementTileSprite, voidTileSprite; public void OnTileClicked(GameObject tile) { if(selectedTile != null) { if(selectedTile.name == "Player") { //If there is already a Player tile somewhere on the gid of tiles, get rid of it. if(playerTilePlaced != null) { playerTilePlaced.GetComponent<SpriteRenderer>().sprite = placementTileSprite; playerTilePlaced.GetComponent<PlacementTileListNumber>().isBlank = true; } //If you are clicking on the same tile as there is already a Player tile on, you obviously want to get rid of it. if(playerTilePlaced == tile) { playerTilePlaced.GetComponent<SpriteRenderer>().sprite = placementTileSprite; playerTilePlaced.GetComponent<PlacementTileListNumber>().isBlank = true; playerTilePlaced = null; } else { //Place the Player tile here tile.GetComponent<SpriteRenderer>().sprite = selectedTileSprite; tile.GetComponent<PlacementTileListNumber>().isBlank = false; playerTilePlaced = tile; } } else { //Don't worry about the Player tile logic, just place the selected tile here. if(Input.GetMouseButton(1)) { if(tile.GetComponent<SpriteRenderer>().sprite != placementTileSprite) { tile.GetComponent<SpriteRenderer>().sprite = placementTileSprite; tile.GetComponent<PlacementTileListNumber>().isBlank = true; } } else { tile.GetComponent<SpriteRenderer>().sprite = selectedTileSprite; tile.GetComponent<PlacementTileListNumber>().isBlank = false; } } } } }<file_sep>/Final Project Level Creation Tool/Assets/Scripts/TileSwapper.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class TileSwapper : MonoBehaviour { public TilePlacer tilePlacer; public UITile uiTile; public GameObject swapperTileA; public GameObject swapperTileB; private GameObject tileA; private GameObject tileB; private GameObject tileAParent; private GameObject tileBParent; // Update is called once per frame void Update () { if(tileA != null && tileB != null) { SwapTiles(); } } public void ToSwap(GameObject tile) { if(tileA == null) { tileA = tile; tileAParent = tile.transform.parent.gameObject; } else { tileB = tile; tileBParent = tile.transform.parent.gameObject; } } void SwapTiles() { swapperTileA.transform.position = tileAParent.transform.position; swapperTileB.transform.position = tileBParent.transform.position; tileA.transform.position = swapperTileB.transform.position; tileB.transform.position = swapperTileA.transform.position; swapperTileA.transform.position = new Vector2(10000, 10000); swapperTileB.transform.position = new Vector2(10000, 10000); tileA.GetComponent<UITile>().BackToBaseSprite(); tileB.GetComponent<UITile>().BackToBaseSprite(); tileA.transform.parent.DetachChildren(); tileB.transform.parent.DetachChildren(); tileA.transform.SetParent(tileBParent.transform); tileB.transform.SetParent(tileAParent.transform); tilePlacer.selectedTile = uiTile.tempTile; tileA = tileB = null; } } <file_sep>/Final Project Game/Assets/Scripts/Enemy/EnemyAttack.cs using UnityEngine; using UnityEditor; using UnityEngine.UI; using System.Collections; using System.Collections.Generic; public class EnemyAttack : MonoBehaviour { private Player player; //This is a reference to the Enemy script that all enemies reference from. private Enemy enemy; [HideInInspector] public int currentTileNumber, xTilesAmount, yTilesAmount; public List<EnemyAttackPositions> enemyAttackablePositions; public List<GameObject> enemyAttackableTiles; private Color purple = new Color(0.5568f, 0.0156f, 0.8902f); private Color red = Color.red; [HideInInspector] public bool tilesShown; //Has to be Awake() otherwise xTilesAmount isn't set before CalculateAttackableTiles() is run. private void Awake() { player = GameObject.FindGameObjectWithTag("Player").GetComponent<Player>(); enemy = FindObjectOfType<Enemy>(); xTilesAmount = enemy.xTilesAmount; yTilesAmount = enemy.yTilesAmount; } //Just for debug showing which enemy you clicked on. //public void ClickedEnemy() { // Debug.Log(gameObject.name); //} public bool CheckCanAttackPlayer() { foreach(GameObject attackableTile in enemyAttackableTiles) { if(player.movement.currentTileNumber == attackableTile.GetComponent<Tile>().listNum) { //If the player moves into a tile the enemy can attack on, disable showing which tiles the enmy can attack on if they were shown prior to the player moving. //EnemyRemoveAttackableTiles(); <<------------------------------------------------------------------------------------------------------------------------------------------------------- return true; } } return false; } //This is fired when it is detected that the player is in a tile that the enemy can attack in. public void EnemyAttackLogic() { player.health.UpdateHealth(-player.health.looseHealthAmount); } public void EnemyDisplayAttackableTiles() { //For debug, show what enemy was clicked on. //ClickedEnemy(); foreach(GameObject attackableTile in enemyAttackableTiles) { attackableTile.GetComponent<SpriteRenderer>().color = red; } tilesShown = true; } public void EnemyRemoveAttackableTiles() { foreach(GameObject attackableTile in enemyAttackableTiles) { attackableTile.GetComponent<SpriteRenderer>().color = purple; } tilesShown = false; } public void CalculateAttackableTiles() { currentTileNumber = GetComponent<EnemyMovement>().currentTileNumber; foreach(EnemyAttackPositions position in enemyAttackablePositions) { if(position.positions != Vector2.zero) { GameObject tempTile; //For some unknown reason, it starts calculating enemy attackable tiles one tile to the right of the enemy, so I had to go "currentTileNumber - 1". if(((currentTileNumber - 1) + ((int)position.positions.x + ((int)position.positions.y * xTilesAmount)) < (1 - 1)) //If the calculated tile number is less than 1 (handles Up tiles). || ((currentTileNumber - 1) + ((int)position.positions.x + ((int)position.positions.y * xTilesAmount)) > (xTilesAmount * yTilesAmount) - 1) //If the calculated tile number is greater than the last tile (handles Down tiles). || Mathf.CeilToInt(((currentTileNumber - 1) + (int)position.positions.x) / xTilesAmount) != Mathf.CeilToInt((currentTileNumber - 1) / xTilesAmount)) //If the calculated tile number is not on the same row as the enemy (handles Left and Right tiles). { continue; } else { tempTile = enemy.gridOfTiles[(currentTileNumber - 1) + ((int)position.positions.x + ((int)position.positions.y * xTilesAmount))].gameObject; enemyAttackableTiles.Add(tempTile); } //Show which tiles the enemy can attack on in Console. //Debug.Log((currentTileNumber - 1) + ((int)position.positions.x + ((int)position.positions.y * xTilesAmount))); } } } } [System.Serializable] public class EnemyAttackPositions { public Vector2 positions; } [CustomPropertyDrawer(typeof(EnemyAttackPositions))] public class ChangeInspector : PropertyDrawer { public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { label = EditorGUI.BeginProperty(position, GUIContent.none, property); Rect contentPosition = EditorGUI.PrefixLabel(position, label); EditorGUI.indentLevel = 0; EditorGUI.PropertyField(contentPosition, property.FindPropertyRelative("positions"), GUIContent.none); contentPosition.x += contentPosition.width; contentPosition.width /= 10f; EditorGUIUtility.labelWidth = 14f; EditorGUI.EndProperty(); } }<file_sep>/Final Project Level Creation Tool/Assets/Scripts/CameraBehaviour.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraBehaviour : MonoBehaviour { [SerializeField] private GameObject cameraGameObject; private Vector3 cameraPos; private string sizeByXY; private UIRelatedStuff uiRelatedStuff; [SerializeField] private float cameraMovementSpeed = 30.0f, cameraHeightCurrent; [SerializeField] private bool invertMovement; //Mouse zoom [SerializeField] private float cameraHeightIncrement, cameraHeightMin = 20; [HideInInspector] public float cameraHeightMax = 0; // Use this for initialization void Start() { cameraPos = transform.position; cameraHeightCurrent = Camera.main.orthographicSize; uiRelatedStuff = FindObjectOfType<UIRelatedStuff>(); } void Update() { if(uiRelatedStuff.xySaved) { moveCamera(); cameraZooming(); if(cameraHeightCurrent < cameraHeightMin) cameraHeightCurrent = cameraHeightMin; if(cameraHeightCurrent > cameraHeightMax) { cameraHeightCurrent = cameraHeightMax; //Move the camera a little bit so that the fully zoomed out level is centered! (Makes things beautifully centered). cameraPos.y = (sizeByXY == "X") ? -(uiRelatedStuff.xTiles / 8) : -(uiRelatedStuff.yTiles / 4); transform.position = cameraPos; } cameraMovementSpeed = cameraHeightCurrent * 2; } } //Controls affecting the zoom and placement of the camera public void cameraZooming() { if(cameraHeightMax == 0) { cameraHeightMax = SetZoomLimit(); cameraHeightCurrent = cameraHeightMax; //Move the camera a little bit so that the zoomed out blank level is centered! (It looks beautiful, trust me). cameraPos.y = (sizeByXY == "X") ? -(uiRelatedStuff.xTiles / 8) : -(uiRelatedStuff.yTiles / 4); transform.position = cameraPos; } cameraHeightIncrement = cameraHeightCurrent / uiRelatedStuff.tileSize; //Adjust Camera Height - Scrollwheel if(Input.GetAxis("Mouse ScrollWheel") > 0 && cameraHeightCurrent > cameraHeightMin) { cameraHeightCurrent -= cameraHeightIncrement; } else if(Input.GetAxis("Mouse ScrollWheel") < 0 && cameraHeightCurrent < cameraHeightMax) { cameraHeightCurrent += cameraHeightIncrement; } Camera.main.orthographicSize = cameraHeightCurrent; } //Move Camera using mouse void moveCamera() { if(!uiRelatedStuff.levelNameIF.isFocused) { cameraMovementSpeed = invertMovement ? Mathf.Abs(cameraMovementSpeed) : -Mathf.Abs(cameraMovementSpeed); if(Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A)) { transform.Translate(Vector2.right * cameraMovementSpeed * Time.deltaTime); } if(Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D)) { transform.Translate(Vector2.right * -cameraMovementSpeed * Time.deltaTime); } if(Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S)) { transform.Translate(transform.up * cameraMovementSpeed * Time.deltaTime); } if(Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W)) { transform.Translate(transform.up * -cameraMovementSpeed * Time.deltaTime); } } } float SetZoomLimit() { float temp; if(((float)uiRelatedStuff.xTiles / (float)uiRelatedStuff.yTiles) >= 2.5f) { //or 0.86f temp = uiRelatedStuff.xTiles * 1.25f; //or 5f sizeByXY = "X"; } else { temp = uiRelatedStuff.yTiles * 3.5f; sizeByXY = "Y"; } return temp; } }<file_sep>/Final Project Game/Assets/Scripts/Misc/TurnHandler.cs using UnityEngine; using System.Collections; using System.Collections.Generic; public class TurnHandler : MonoBehaviour { public Player player; public TilePlacer tilePlacer; //For if we want delayed movement when moving 2 tiles in one turn with leather armour. //public float timeDelay; public int turnNumber; private int turnNumberSAVED; public GameObject wonGameUI, lostGameUI; [HideInInspector] public bool levelSet, playerAttackInsteadOfMove, gameRestarted, movementInProgress, wasEnemyOnTile; [HideInInspector] public List<GameObject> enemyList; [HideInInspector] public GameObject enemyToAttack; void Update() { //If all tiles have been placed, Player has been placed, and all enemies have been placed, if(levelSet) { //If there was no enemy on the tile clicked on, we want to move, not attack. if(!playerAttackInsteadOfMove && player.movement.wantedTileNumber != -1 && !movementInProgress && !wasEnemyOnTile) { //The four references to this 'movementInProgress' thing in this script (it is the only script that has it) is to limit the amount of times player.Movement() is tried. movementInProgress = true; player.Movement(); movementInProgress = false; } //Turn logic for enemies. if(turnNumber > turnNumberSAVED && enemyList.Count > 0) { foreach(GameObject enemy in enemyList) { enemy.GetComponent<EnemyMovement>().EnemyTurnLogic(); } //Once all the enemies alive have moved and attacked, the current turn is over. Onto the next turn! turnNumberSAVED++; } } //Exit the game if you press the Escape key or the back button on an Android device. if(Input.GetKeyDown(KeyCode.Escape)) { QuitGame(); } } public void TilesBackToPurple() { foreach(GameObject tile in tilePlacer.tiles) { if(tile.GetComponent<SpriteRenderer>().color == Color.red) { tile.GetComponent<SpriteRenderer>().color = new Color(0.5568f, 0.0156f, 0.8902f); } } } //Player chose to restart the game (because they lost) or to move onto the next level, so reset everything. public void RestartGame() { wonGameUI.SetActive(false); lostGameUI.SetActive(false); turnNumber = turnNumberSAVED = 0; player.health.health = player.health.maxHealth; player.health.healthBar.value = player.health.maxHealth; player.movement.direction = ""; tilePlacer.RestartGame(); } //Self-explainatory. public void QuitGame() { wonGameUI.SetActive(false); lostGameUI.SetActive(false); Application.Quit(); } } <file_sep>/Level Creating Tool 5.5 - DO NOT USE/Assets/Scripts/EventManager/ChooseTile.cs using UnityEngine; using UnityEngine.UI; using System.Collections; using System.Collections.Generic; public class ChooseTile : MonoBehaviour { public List<GameObject> UITiles; public Sprite placeSprite, swapSprite; public TilePlacer tilePlacer; public TileSwapper tileSwapper; public InputField xTilesIF; public InputField yTilesIF; public InputField levelNameIF; void Awake () { EventManager.AddListener<KeyPressedEvent>(OnKeyPressed); } void OnDestroy() { EventManager.RemoveListener<KeyPressedEvent>(OnKeyPressed); } void OnKeyPressed(KeyPressedEvent a_event) { if(!xTilesIF.isFocused && !yTilesIF.isFocused && !levelNameIF.isFocused) { switch(a_event.PressedKeyCode.ToString()) { case "Alpha1": if(Input.GetKey(KeyCode.LeftShift)) { UITiles[0].GetComponent<Image>().sprite = swapSprite; tileSwapper.ToSwap(UITiles[0].transform.GetChild(0).gameObject); } else { UITiles[0].GetComponent<Image>().sprite = placeSprite; tilePlacer.selectedTile = UITiles[0].transform.GetChild(0).gameObject; tilePlacer.selectedTileSprite = UITiles[0].transform.GetChild(0).gameObject.GetComponent<Image>().sprite; } break; case "Alpha2": if(Input.GetKey(KeyCode.LeftShift)) { UITiles[1].GetComponent<Image>().sprite = swapSprite; tileSwapper.ToSwap(UITiles[1].transform.GetChild(0).gameObject); } else { UITiles[1].GetComponent<Image>().sprite = placeSprite; tilePlacer.selectedTile = UITiles[1].transform.GetChild(0).gameObject; tilePlacer.selectedTileSprite = UITiles[1].transform.GetChild(0).gameObject.GetComponent<Image>().sprite; } break; case "Alpha3": if(Input.GetKey(KeyCode.LeftShift)) { UITiles[2].GetComponent<Image>().sprite = swapSprite; tileSwapper.ToSwap(UITiles[2].transform.GetChild(0).gameObject); } else { UITiles[2].GetComponent<Image>().sprite = placeSprite; tilePlacer.selectedTile = UITiles[2].transform.GetChild(0).gameObject; tilePlacer.selectedTileSprite = UITiles[2].transform.GetChild(0).gameObject.GetComponent<Image>().sprite; } break; case "Alpha4": if(Input.GetKey(KeyCode.LeftShift)) { UITiles[3].GetComponent<Image>().sprite = swapSprite; tileSwapper.ToSwap(UITiles[3].transform.GetChild(0).gameObject); } else { UITiles[3].GetComponent<Image>().sprite = placeSprite; tilePlacer.selectedTile = UITiles[3].transform.GetChild(0).gameObject; tilePlacer.selectedTileSprite = UITiles[3].transform.GetChild(0).gameObject.GetComponent<Image>().sprite; } break; case "Alpha5": if(Input.GetKey(KeyCode.LeftShift)) { UITiles[4].GetComponent<Image>().sprite = swapSprite; tileSwapper.ToSwap(UITiles[4].transform.GetChild(0).gameObject); } else { UITiles[4].GetComponent<Image>().sprite = placeSprite; tilePlacer.selectedTile = UITiles[4].transform.GetChild(0).gameObject; tilePlacer.selectedTileSprite = UITiles[4].transform.GetChild(0).gameObject.GetComponent<Image>().sprite; } break; case "Alpha6": if(Input.GetKey(KeyCode.LeftShift)) { UITiles[5].GetComponent<Image>().sprite = swapSprite; tileSwapper.ToSwap(UITiles[5].transform.GetChild(0).gameObject); } else { UITiles[5].GetComponent<Image>().sprite = placeSprite; tilePlacer.selectedTile = UITiles[5].transform.GetChild(0).gameObject; tilePlacer.selectedTileSprite = UITiles[5].transform.GetChild(0).gameObject.GetComponent<Image>().sprite; } break; case "Alpha7": if(Input.GetKey(KeyCode.LeftShift)) { UITiles[6].GetComponent<Image>().sprite = swapSprite; tileSwapper.ToSwap(UITiles[6].transform.GetChild(0).gameObject); } else { UITiles[6].GetComponent<Image>().sprite = placeSprite; tilePlacer.selectedTile = UITiles[6].transform.GetChild(0).gameObject; tilePlacer.selectedTileSprite = UITiles[6].transform.GetChild(0).gameObject.GetComponent<Image>().sprite; } break; case "Alpha8": if(Input.GetKey(KeyCode.LeftShift)) { UITiles[7].GetComponent<Image>().sprite = swapSprite; tileSwapper.ToSwap(UITiles[7].transform.GetChild(0).gameObject); } else { UITiles[7].GetComponent<Image>().sprite = placeSprite; tilePlacer.selectedTile = UITiles[7].transform.GetChild(0).gameObject; tilePlacer.selectedTileSprite = UITiles[7].transform.GetChild(0).gameObject.GetComponent<Image>().sprite; } break; case "Alpha9": if(Input.GetKey(KeyCode.LeftShift)) { UITiles[8].GetComponent<Image>().sprite = swapSprite; tileSwapper.ToSwap(UITiles[8].transform.GetChild(0).gameObject); } else { UITiles[8].GetComponent<Image>().sprite = placeSprite; tilePlacer.selectedTile = UITiles[8].transform.GetChild(0).gameObject; tilePlacer.selectedTileSprite = UITiles[8].transform.GetChild(0).gameObject.GetComponent<Image>().sprite; } break; case "Alpha0": if(Input.GetKey(KeyCode.LeftShift)) { UITiles[9].GetComponent<Image>().sprite = swapSprite; tileSwapper.ToSwap(UITiles[9].transform.GetChild(0).gameObject); } else { UITiles[9].GetComponent<Image>().sprite = placeSprite; tilePlacer.selectedTile = UITiles[9].transform.GetChild(0).gameObject; tilePlacer.selectedTileSprite = UITiles[9].transform.GetChild(0).gameObject.GetComponent<Image>().sprite; } break; case "Minus": if(Input.GetKey(KeyCode.LeftShift)) { UITiles[10].GetComponent<Image>().sprite = swapSprite; tileSwapper.ToSwap(UITiles[10].transform.GetChild(0).gameObject); } else { UITiles[10].GetComponent<Image>().sprite = placeSprite; tilePlacer.selectedTile = UITiles[10].transform.GetChild(0).gameObject; tilePlacer.selectedTileSprite = UITiles[10].transform.GetChild(0).gameObject.GetComponent<Image>().sprite; } break; case "Equals": if(Input.GetKey(KeyCode.LeftShift)) { UITiles[11].GetComponent<Image>().sprite = swapSprite; tileSwapper.ToSwap(UITiles[11].transform.GetChild(0).gameObject); } else { UITiles[11].GetComponent<Image>().sprite = placeSprite; tilePlacer.selectedTile = UITiles[11].transform.GetChild(0).gameObject; tilePlacer.selectedTileSprite = UITiles[11].transform.GetChild(0).gameObject.GetComponent<Image>().sprite; } break; } } } }<file_sep>/Final Project Game/Assets/Scripts/Misc/Tile.cs using UnityEngine; public class Tile : MonoBehaviour { private Player player; private Enemy enemyRef; private TurnHandler turnHandler; //What number am I in the tileList? public int listNum; private bool activeTimer; public float timer; private float timerSAVED; void Start() { player = FindObjectOfType<Player>(); turnHandler = FindObjectOfType<TurnHandler>(); enemyRef = FindObjectOfType<Enemy>(); timerSAVED = timer; } private void Update() { //If the selected enemy (for displaying their attackable tiles) has changed if(enemyRef.enemySwapped) { timer = timerSAVED; activeTimer = true; enemyRef.enemySwapped = false; } if(activeTimer) { timer -= Time.deltaTime; if(enemyRef.currentSelectedEnemyIsDead || turnHandler.gameRestarted) { timer = 0.0f; activeTimer = false; enemyRef.currentSelectedEnemyIsDead = false; turnHandler.gameRestarted = false; } //Second check for activeTimer because of the above if statement, if died. if(timer <= 0.0f && activeTimer) { enemyRef.currentlySelectedEnemy.gameObject.GetComponent<EnemyAttack>().EnemyRemoveAttackableTiles(); enemyRef.currentlySelectedEnemy = null; activeTimer = false; } } } //If an enemy was clicked on to see it's attackable tiles, show those tiles, if the same enemy is clicked again, attack if in range. public void OnMouseDown() { turnHandler.wasEnemyOnTile = false; foreach(GameObject enemy in turnHandler.enemyList) { if(enemy.GetComponent<EnemyMovement>().currentTileNumber == listNum) { turnHandler.wasEnemyOnTile = true; //If you clicked on a Goblin, skip all the showing of attackable tiles logic, as the Goblin doesn't have any attackable tiles. Just attack it instead. if(enemy.gameObject.name == "E_Goblin(Clone)") { if(enemyRef.currentlySelectedEnemy != null) { enemyRef.currentlySelectedEnemy.GetComponent<EnemyAttack>().EnemyRemoveAttackableTiles(); } enemyRef.currentlySelectedEnemy = enemy; AttackEnemy(); break; } else { if(enemyRef.currentlySelectedEnemy != null) { //If it is the same enemy as the currentlySelectedEnemy if(enemy.GetComponent<EnemyMovement>().currentTileNumber == enemyRef.currentlySelectedEnemy.GetComponent<EnemyMovement>().currentTileNumber) { AttackEnemy(); break; } else { //A new enemy has been selected, so remove the previously selected enemy's attackable tiles. enemyRef.currentlySelectedEnemy.GetComponent<EnemyAttack>().EnemyRemoveAttackableTiles(); } } //Set the new enemy as the currentlySelectedEnemy and display it's tiles. enemyRef.currentlySelectedEnemy = enemy; enemy.GetComponent<EnemyAttack>().EnemyDisplayAttackableTiles(); enemyRef.enemySwapped = true; //Reset the currentlySelectedEnemy timer. timer = timerSAVED; break; } } } } //When tile is clicked on, public void OnMouseUp() { //If there was no enemy on the clicked tile, if(!turnHandler.playerAttackInsteadOfMove && !turnHandler.wasEnemyOnTile) { if(player.movement.direction == "") { //Debug.Log("I am List Number: " + listNum + ". My Position is: " + gameObject.transform.GetChild(0).GetChild(0).transform.position); //Set the clicked tile as the wantedTile. player.movement.wantedTileNumber = listNum; } } else { //Some cleanup turnHandler.wasEnemyOnTile = false; } } public void AttackEnemy() { //Make sure we can't click ANY enemy on the board to attack (this long IF statement will only allow for closest tile in all 8 directions). Need to change for longer range attacks. if((player.movement.currentTileNumber - player.movement.xTilesAmount) == listNum //Up || (player.movement.currentTileNumber - (player.movement.xTilesAmount - 1)) == listNum //UpRight || (player.movement.currentTileNumber + 1) == listNum //Right || (player.movement.currentTileNumber + (player.movement.xTilesAmount + 1)) == listNum //DownRight || (player.movement.currentTileNumber + player.movement.xTilesAmount) == listNum //Down || (player.movement.currentTileNumber + (player.movement.xTilesAmount - 1)) == listNum //DownLeft || (player.movement.currentTileNumber - 1) == listNum //Left || (player.movement.currentTileNumber - (player.movement.xTilesAmount + 1)) == listNum) { //UpLeft //If there is an enemy on the tile we are clicking on, target the enemy and set the player mode to Attack instead of Move. foreach(GameObject enemy in turnHandler.enemyList) { if(enemy.GetComponent<EnemyMovement>().currentTileNumber == listNum) { turnHandler.enemyToAttack = enemy; turnHandler.playerAttackInsteadOfMove = true; break; } } //Attack player.Attack(enemyRef.currentlySelectedEnemy); } } } <file_sep>/Final Project Level Creation Tool/Assets/Scripts/UITile.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class UITile : MonoBehaviour { //Swap Variables private TileSwapper tileSwapper; //Place Variables private TilePlacer tilePlacer; [SerializeField] private Sprite baseSprite; [SerializeField] private Sprite swapSprite; [SerializeField] private Sprite placeSprite; [HideInInspector] public GameObject tempTile; void Awake() { tileSwapper = FindObjectOfType<TileSwapper>(); tilePlacer = FindObjectOfType<TilePlacer>(); } void Update() { if(tilePlacer.selectedTile == gameObject) { if(gameObject.transform.parent.gameObject.GetComponent<Image>().sprite != placeSprite) { gameObject.transform.parent.gameObject.GetComponent<Image>().sprite = placeSprite; } } else { if(gameObject.transform.parent.gameObject.GetComponent<Image>().sprite != swapSprite) { BackToBaseSprite(); } } } public void OnTileClick() { //Swapping if(Input.GetKey(KeyCode.LeftShift)) { if(gameObject.transform.parent.gameObject.GetComponent<Image>().sprite == placeSprite) { tempTile = tilePlacer.selectedTile; tilePlacer.selectedTile = null; } gameObject.transform.parent.gameObject.GetComponent<Image>().sprite = swapSprite; tileSwapper.ToSwap(gameObject); //Placing } else { gameObject.transform.parent.gameObject.GetComponent<Image>().sprite = placeSprite; tilePlacer.selectedTile = gameObject; tilePlacer.selectedTileSprite = gameObject.GetComponent<Image>().sprite; } } public void BackToBaseSprite() { gameObject.transform.parent.gameObject.GetComponent<Image>().sprite = baseSprite; } }<file_sep>/Final Project Game/Assets/Scripts/Player/Player.cs using UnityEngine; using System.Collections; public class Player : MonoBehaviour { public PlayerMovement movement; public PlayerAttack attack; public PlayerHealth health; [SerializeField] private TurnHandler turnHandler; public void Movement() { movement.PlayerMovementLogic(); } public void Attack(GameObject enemyToAttack) { attack.PlayerAttackLogic(enemyToAttack); //In case the Player chose to attack instead of move, set it back to the default of moving next turn. turnHandler.playerAttackInsteadOfMove = false; } } <file_sep>/Final Project Game/Assets/Scripts/Enemy/EnemyHealth.cs using UnityEngine; using System.Collections; using UnityEngine.UI; public class EnemyHealth : MonoBehaviour { public Slider healthBar; private TurnHandler turnHandler; private Player player; private Enemy enemy; public int health, looseHealthAmount, maxHealth; void Start() { turnHandler = FindObjectOfType<TurnHandler>(); player = FindObjectOfType<Player>(); enemy = FindObjectOfType<Enemy>(); } public void UpdateHealth(int healthAmount) { //If the given parameter is negative, if(healthAmount < 0) { //If enemy is alive, negate health. if(health > 0) { health -= looseHealthAmount; } //If negating health made the enemy have less than 0 health, set it back to 0. (For a split second before the enemy dies, this is helpful for the visual aspect). if(health < 0) { health = 0; } } /*else { //THIS IS FOR IF YOU WANT ENEMIES TO GAIN HEALTH FROM SOMETHING (else add health if parameter given was not less than 0). if(health < maxHealth) { health += healthAmount; } if(health > maxHealth) { health = maxHealth; } }*/ if(health == 0) { //Debug.Log("Enemy Died"); //Add health to the player. player.health.UpdateHealth(5); enemy.currentlySelectedEnemy.GetComponent<EnemyAttack>().EnemyRemoveAttackableTiles(); enemy.currentSelectedEnemyIsDead = true; //Find the now-dead enemy from the list of enemies and remove it. for(int i = 0; i < turnHandler.enemyList.Count; ++i) { if(gameObject.GetComponent<EnemyMovement>().currentTileNumber == turnHandler.enemyList[i].GetComponent<EnemyMovement>().currentTileNumber) { turnHandler.enemyList.Remove(turnHandler.enemyList[i]); } } //Destory the enemy. Destroy(gameObject); } else { //Enemy is not dead yet, update health bar. healthBar.value = health; } } }<file_sep>/Final Project Game/Assets/Scripts/Player/PlayerMovement.cs using UnityEngine; using System.Collections; using System.Collections.Generic; public class PlayerMovement : MonoBehaviour { private TurnHandler turnHandler; #region Armour Fields public enum ArmourType { plate = 1, leather } public ArmourType armourType; private int armourTypeValue; #endregion #region Misc Fields [HideInInspector] public int xTilesAmount; //[HideInInspector] public int currentTileNumber = -1, wantedTileNumber = -1; private bool moveDelay; private float timeDelay; [HideInInspector] public string direction = ""; private bool canMoveTwoChoseToMoveOne; #endregion void Start() { turnHandler = FindObjectOfType<TurnHandler>(); //timeDelay = turnHandler.timeDelay; //armourType = ArmourType.leather; armourTypeValue = (int)armourType; //Debug.Log("The current armour worn is: " + System.Enum.GetName(typeof(ArmourType), armourType)); } public void PlayerMovementLogic() { //If the tile currently on is the wantedTile, reset the wantedTileNumber and the direction. if(currentTileNumber == wantedTileNumber) { wantedTileNumber = -1; direction = ""; } //If the Player has clicked on a tile they want to move to, if(wantedTileNumber != -1) { /***** NOTE: The stuff commented out with '/*' is for if we want to have delayed movement when moving two tiles in one turn (when wearing leather armour).*****/ //If the time delay between moves counted down to 0, /*if(!moveDelay) {*/ //If the Player is not currently on the wantedTile, if(currentTileNumber != wantedTileNumber) { bool enemyInWantedPosition = false; if(turnHandler.enemyList.Count > 0) { foreach(GameObject enemyCheck in turnHandler.enemyList) { if(enemyCheck.GetComponent<EnemyMovement>().currentTileNumber == wantedTileNumber) { enemyInWantedPosition = true; break; } } } if(!enemyInWantedPosition) { //Move. Move(); /*moveDelay = true;*/ } } else { wantedTileNumber = -1; } /*}*/ /*if(direction != "") { if(timeDelay > 0.0f) { timeDelay -= Time.deltaTime; } else { moveDelay = false; timeDelay = turnHandler.timeDelay; } } else { moveDelay = false; } } else { timeDelay = turnHandler.timeDelay; */ } } public void Move() { //If no current direction has been determined. if(direction == "") { //Up //Player can move two in one turn but they choose to move only one. if(wantedTileNumber == (currentTileNumber - (xTilesAmount * armourTypeValue)) || (armourType == ArmourType.leather && wantedTileNumber == (currentTileNumber - xTilesAmount)) /*&& ((currentTileNumber - wantedTileNumber) % xTilesAmount == 0)*/) { //Debug.Log("Up"); direction = "Up"; //Chose to move only one tile with leather armour on. if(armourType == ArmourType.leather && wantedTileNumber == (currentTileNumber - xTilesAmount)) { canMoveTwoChoseToMoveOne = true; } //Left //Player can move two in one turn but they choose to move only one. } else if((wantedTileNumber == (currentTileNumber - (1 * armourTypeValue)) || (armourType == ArmourType.leather && wantedTileNumber == (currentTileNumber - 1))) && (Mathf.CeilToInt((float)currentTileNumber / (float)xTilesAmount) == (Mathf.CeilToInt((float)wantedTileNumber / (float)xTilesAmount))) /*&& !(wantedTileNumber % xTilesAmount == 0)*/) { //Debug.Log("Left"); direction = "Left"; //Chose to move only one tile with leather armour on. if(armourType == ArmourType.leather && wantedTileNumber == (currentTileNumber - 1)) { canMoveTwoChoseToMoveOne = true; } //Right //Player can move two in one turn but they choose to move only one. } else if((wantedTileNumber == (currentTileNumber + (1 * armourTypeValue)) || (armourType == ArmourType.leather && wantedTileNumber == (currentTileNumber + 1))) && (Mathf.CeilToInt((float)currentTileNumber / (float)xTilesAmount) == (Mathf.CeilToInt((float)wantedTileNumber / (float)xTilesAmount))) /*&& !((wantedTileNumber - 1.0f) % xTilesAmount == 0)*/) { //Debug.Log("Right"); direction = "Right"; //Chose to move only one tile with leather armour on. if(armourType == ArmourType.leather && wantedTileNumber == (currentTileNumber + 1)) { canMoveTwoChoseToMoveOne = true; } //Down //Player can move two in one turn but they choose to move only one. } else if(wantedTileNumber == (currentTileNumber + (xTilesAmount * armourTypeValue)) || (armourType == ArmourType.leather && wantedTileNumber == (currentTileNumber + xTilesAmount)) /*&& ((wantedTileNumber - currentTileNumber) % xTilesAmount == 0)*/) { //Debug.Log("Down"); direction = "Down"; //Chose to move only one tile with leather armour on. if(armourType == ArmourType.leather && wantedTileNumber == (currentTileNumber + xTilesAmount)) { canMoveTwoChoseToMoveOne = true; } //DownRight //Player can move two in one turn but they choose to move only one. //<-- Up to this point uncommented, the problem is with DR and UL 3 //<-- Up to this point uncommented, the problem is with DL and UR 4 //The rest uncommented, the problem is with DR and UL 4 (I think) } else if(wantedTileNumber == (currentTileNumber + ((xTilesAmount + 1) * armourTypeValue)) || (armourType == ArmourType.leather && wantedTileNumber == (currentTileNumber + (xTilesAmount + 1))) /*&& ((wantedTileNumber - currentTileNumber) % (xTilesAmount + 1) == 0) && (wantedTileNumber - currentTileNumber != ((xTilesAmount - 1) * 4))*/) { // || wantedTileNumber - currentTileNumber != ((xTilesAmount + 1) * 4))) { //&& wantedTileNumber - currentTileNumber != ((xTilesAmount - 1) * 4) || wantedTileNumber - currentTileNumber != ((xTilesAmount - 1) * 4)) { //Debug.Log("DownRight"); direction = "DownRight"; //Chose to move only one tile with leather armour on. if(armourType == ArmourType.leather && wantedTileNumber == (currentTileNumber + (xTilesAmount + 1))) { canMoveTwoChoseToMoveOne = true; } //DownLeft //Player can move two in one turn but they choose to move only one. } else if(wantedTileNumber == (currentTileNumber + ((xTilesAmount - 1) * armourTypeValue)) || (armourType == ArmourType.leather && wantedTileNumber == (currentTileNumber + (xTilesAmount - 1))) /*&& ((wantedTileNumber - currentTileNumber) % (xTilesAmount - 1) == 0)*/) { //Debug.Log("DownLeft"); direction = "DownLeft"; //Chose to move only one tile with leather armour on. if(armourType == ArmourType.leather && wantedTileNumber == (currentTileNumber + (xTilesAmount - 1))) { canMoveTwoChoseToMoveOne = true; } //UpLeft //Player can move two in one turn but they choose to move only one. //<-- Up to this point uncommented, the problem is with DR and UL 3 //<-- Up to this point uncommented, the problem is with DL and UR 4 //The rest uncommented, the problem is with DR and UL 4 (I think) } else if(wantedTileNumber == (currentTileNumber - ((xTilesAmount + 1) * armourTypeValue)) || (armourType == ArmourType.leather && wantedTileNumber == (currentTileNumber - (xTilesAmount + 1))) /*&& ((currentTileNumber - wantedTileNumber) % (xTilesAmount + 1) == 0) && (currentTileNumber - wantedTileNumber != ((xTilesAmount + 1) * 3))*/) { // || currentTileNumber - wantedTileNumber != ((xTilesAmount - 1) * 3))) { //&& currentTileNumber - wantedTileNumber != ((xTilesAmount + 1) * 3) || currentTileNumber - wantedTileNumber != ((xTilesAmount + 1) * 4)) { //Debug.Log("UpLeft"); direction = "UpLeft"; //Chose to move only one tile with leather armour on. if(armourType == ArmourType.leather && wantedTileNumber == (currentTileNumber - (xTilesAmount + 1))) { canMoveTwoChoseToMoveOne = true; } //UpRight //Player can move two in one turn but they choose to move only one. } else if(wantedTileNumber == (currentTileNumber - ((xTilesAmount - 1) * armourTypeValue)) || (armourType == ArmourType.leather && wantedTileNumber == (currentTileNumber - (xTilesAmount - 1))) /*&& ((currentTileNumber - wantedTileNumber) % (xTilesAmount - 1) == 0)*/) { //Debug.Log("UpRight"); direction = "UpRight"; //Chose to move only one tile with leather armour on. if(armourType == ArmourType.leather && wantedTileNumber == (currentTileNumber - (xTilesAmount - 1))) { canMoveTwoChoseToMoveOne = true; } } else { wantedTileNumber = currentTileNumber; direction = ""; } } //This is the logic to actually move in the chosen direction. if(direction == "Up") { //If chose to move only one tile with leather armour on. if(canMoveTwoChoseToMoveOne) { currentTileNumber -= xTilesAmount; gameObject.transform.position += new Vector3(0, 1, 0); canMoveTwoChoseToMoveOne = false; } else { //Move the amount the currently worn armour type allows you to move. currentTileNumber -= xTilesAmount * armourTypeValue; gameObject.transform.position += new Vector3(0, 1 * armourTypeValue, 0); } turnHandler.turnNumber++; } else if(direction == "UpRight") { //If chose to move only one tile with leather armour on. if(canMoveTwoChoseToMoveOne) { currentTileNumber -= xTilesAmount - 1; gameObject.transform.position += new Vector3(1, 1, 0); canMoveTwoChoseToMoveOne = false; } else { //Move the amount the currently worn armour type allows you to move. currentTileNumber -= (xTilesAmount - 1) * armourTypeValue; gameObject.transform.position += new Vector3(1 * armourTypeValue, 1 * armourTypeValue, 0); } turnHandler.turnNumber++; } else if(direction == "Right") { //If chose to move only one tile with leather armour on. if(canMoveTwoChoseToMoveOne) { currentTileNumber += 1; gameObject.transform.position += new Vector3(1, 0, 0); canMoveTwoChoseToMoveOne = false; } else { //Move the amount the currently worn armour type allows you to move. currentTileNumber += 1 * armourTypeValue; gameObject.transform.position += new Vector3(1 * armourTypeValue, 0, 0); } turnHandler.turnNumber++; } else if(direction == "DownRight") { //If chose to move only one tile with leather armour on. if(canMoveTwoChoseToMoveOne) { currentTileNumber += (xTilesAmount + 1); gameObject.transform.position += new Vector3(1, -1, 0); canMoveTwoChoseToMoveOne = false; } else { //Move the amount the currently worn armour type allows you to move. currentTileNumber += (xTilesAmount + 1) * armourTypeValue; gameObject.transform.position += new Vector3(1 * armourTypeValue, -1 * armourTypeValue, 0); } turnHandler.turnNumber++; } else if(direction == "Down") { //If chose to move only one tile with leather armour on. if(canMoveTwoChoseToMoveOne) { currentTileNumber += xTilesAmount; gameObject.transform.position += new Vector3(0, -1, 0); canMoveTwoChoseToMoveOne = false; } else { //Move the amount the currently worn armour type allows you to move. currentTileNumber += xTilesAmount * armourTypeValue; gameObject.transform.position += new Vector3(0, -1 * armourTypeValue, 0); } turnHandler.turnNumber++; } else if(direction == "DownLeft") { //If chose to move only one tile with leather armour on. if(canMoveTwoChoseToMoveOne) { currentTileNumber += (xTilesAmount - 1); gameObject.transform.position += new Vector3(-1, -1, 0); canMoveTwoChoseToMoveOne = false; } else { //Move the amount the currently worn armour type allows you to move. currentTileNumber += (xTilesAmount - 1) * armourTypeValue; gameObject.transform.position += new Vector3(-1 * armourTypeValue, -1 * armourTypeValue, 0); } turnHandler.turnNumber++; } else if(direction == "Left") { //If chose to move only one tile with leather armour on. if(canMoveTwoChoseToMoveOne) { currentTileNumber -= 1; gameObject.transform.position += new Vector3(-1, 0, 0); canMoveTwoChoseToMoveOne = false; } else { //Move the amount the currently worn armour type allows you to move. currentTileNumber -= 1 * armourTypeValue; gameObject.transform.position += new Vector3(-1 * armourTypeValue, 0, 0); } turnHandler.turnNumber++; } else if(direction == "UpLeft") { //If chose to move only one tile with leather armour on. if(canMoveTwoChoseToMoveOne) { currentTileNumber -= (xTilesAmount + 1); gameObject.transform.position += new Vector3(-1, 1, 0); canMoveTwoChoseToMoveOne = false; } else { //Move the amount the currently worn armour type allows you to move. currentTileNumber -= (xTilesAmount + 1) * armourTypeValue; gameObject.transform.position += new Vector3(-1 * armourTypeValue, 1 * armourTypeValue, 0); } turnHandler.turnNumber++; } } //If the armour type is changed, this is a nice little method to call. int ChangeArmourTypeTo(ArmourType armour) { return (int)armour; } }<file_sep>/Final Project Game/Assets/Scripts/Misc/TilePlacer.cs using UnityEngine; using System.Collections; using System.Collections.Generic; //This is kind of a GameManager script, but only for the setup for each level. public class TilePlacer : MonoBehaviour { private Player player; private Enemy enemy; private TurnHandler turnHandler; private GameObject tileGridParent, enemiesParent; [Header("Manually Dragged-In")] [SerializeField] private GameObject tilePrefab; //[Space(5)] [SerializeField] private int xTiles, yTiles, tileSize; [Space(5)] [Header("Enemies To Spawn")] [SerializeField] private List<EnemySpawner> enemiesWanted; [HideInInspector] public List<GameObject> tiles, enemyList; private float xStartPos, yStartPos; private int randomTileToSpawnOnEnemyX, randomTileToSpawnOnEnemyY; void Start() { player = FindObjectOfType<Player>(); enemy = FindObjectOfType<Enemy>(); turnHandler = FindObjectOfType<TurnHandler>(); tileGridParent = GameObject.FindGameObjectWithTag("TileGrid"); enemiesParent = GameObject.FindGameObjectWithTag("EnemiesParent"); enemy.GetComponent<Enemy>().xTilesAmount = xTiles; enemy.GetComponent<Enemy>().yTilesAmount = yTiles; PlaceTiles(); SetUpPlayer(); SetUpEnemies(); //Give the xTilesAmount to the PlayerMovement script. player.movement.xTilesAmount = xTiles; //Everything is now set up, the game may now begin. turnHandler.levelSet = true; } void PlaceTiles() { //Centre the gid of tiles on the screen. if(xTiles % 2 == 0) { xStartPos = -((xTiles * tileSize) / 2) + ((tileSize / 2) + 0.5f); } else { xStartPos = -((xTiles * tileSize) / 2) + ((tileSize / 2)); } if(yTiles % 2 == 0) { yStartPos = ((yTiles * tileSize) / 2) + ((tileSize / 2) - 0.5f); } else { yStartPos = ((yTiles * tileSize) / 2) + ((tileSize / 2)); } Vector3 currPos = new Vector3(xStartPos, yStartPos, 2); //Place all the tiles. for(int y = 0; y < yTiles; ++y) { for(int x = 0; x < xTiles; ++x) { GameObject tempObj; tempObj = Instantiate(tilePrefab, currPos, Quaternion.Euler(0.0f, 0.0f, 0.0f)) as GameObject; //Add the tile to the tiles list. tiles.Add(tempObj); //Set it's own special list number. tempObj.GetComponent<Tile>().listNum = tiles.Count; //Give it a parent to go to, to cry at night. tempObj.transform.SetParent(tileGridParent.transform); //Set the next X position for the next tile. currPos.x += tileSize; } //End of a row? Next Y position and start form first X position again. currPos = new Vector3(xStartPos, currPos.y -= tileSize, 2); } enemy.gridOfTiles = tiles; } void SetUpPlayer() { //Choose a random tile to start on. int randomTileToSpawnOnPlayerX = Random.Range(1, xTiles); int randomTileToSpawnOnPlayerY = Random.Range(1, yTiles); //Actually place the Player on that tile's position. player.gameObject.transform.position = tiles[(randomTileToSpawnOnPlayerX * randomTileToSpawnOnPlayerY) - 1].transform.position; player.gameObject.transform.position = new Vector3(player.gameObject.transform.position.x, player.gameObject.transform.position.y, 1.5f); //Give the Player the currentTileNumber they are on, and give them no current wantedTile. player.movement.currentTileNumber = randomTileToSpawnOnPlayerX * randomTileToSpawnOnPlayerY; player.movement.wantedTileNumber = -1; } void SetUpEnemies() { //For every type of enemy wanted, for(int i = 0; i < enemiesWanted.Count; ++i) { //For all of that type of enemy, for(int j = 0; j < enemiesWanted[i].enemyAmount; j++) { //Check conditions for if the tile is available or not. Keep checking until the chosen tile is available. bool checkForSpawnPosition = true; while(checkForSpawnPosition) { //Pick a random tile to be placed on. randomTileToSpawnOnEnemyX = Random.Range(1, xTiles); randomTileToSpawnOnEnemyY = Random.Range(1, yTiles); //We don't want to spawn enemies in any of the 4 corners, trust me, its gross, so this if statement checks if the current X and Y to spawn an enemy is in any of the 4 devilish corners. if(!((randomTileToSpawnOnEnemyX * randomTileToSpawnOnEnemyY) == 1) && !((randomTileToSpawnOnEnemyX * randomTileToSpawnOnEnemyY) == xTiles) && !((randomTileToSpawnOnEnemyX * randomTileToSpawnOnEnemyY) == (xTiles * yTiles)) && !((randomTileToSpawnOnEnemyX * randomTileToSpawnOnEnemyY) == ((xTiles * yTiles) - (xTiles - 1)))) { //Check to see if the current X and Y to spawn an enemy at would spawnn the enemy on top of the character. if((randomTileToSpawnOnEnemyX * randomTileToSpawnOnEnemyY) != player.movement.currentTileNumber) { //Debug.Log("Checking for Enemy number " + (i + 1) + "..."); //Now start checking if any other enemy is on that tile. if(enemyList.Count > 0) { checkForSpawnPosition = false; foreach(GameObject enemyCheckPos in enemyList) { //If the current enemy checked from the enemyList ISN'T on the tile, check the next enemy in the enemyList. if((randomTileToSpawnOnEnemyX * randomTileToSpawnOnEnemyY) != enemyCheckPos.GetComponent<EnemyMovement>().currentTileNumber) { continue; } else { //An enemy from the enemyList IS on the tile. //Debug.Log("Enemy already at wanted position."); checkForSpawnPosition = true; break; } } } else {//Tile is clear, can place Enemy. //Debug.Log("No Enemies in enemyList, place Enemy."); checkForSpawnPosition = false; } } } } //Spawn the enemy type, GameObject enemy = Instantiate(enemiesWanted[i].enemyType, tiles[(randomTileToSpawnOnEnemyX * randomTileToSpawnOnEnemyY) - 1].transform.position, Quaternion.Euler(135f, 90f, -90f)) as GameObject; //Set the position of the enemy onto the tile, enemy.gameObject.transform.position = new Vector3(enemy.gameObject.transform.position.x, enemy.gameObject.transform.position.y, 1.5f); //Give the enemy it's currentTileNumber, enemy.GetComponent<EnemyMovement>().currentTileNumber = randomTileToSpawnOnEnemyX * randomTileToSpawnOnEnemyY; //Add the enemy to the enemyList. enemyList.Add(enemy); //Give the enemy a parent to go and cry to at night. enemy.transform.SetParent(enemiesParent.transform); //Calculate the enemy's attackable tiles. enemy.GetComponent<EnemyAttack>().CalculateAttackableTiles(); } } //All enemies have been spawned and set, give the list of enemies to the turnHandler. turnHandler.enemyList = enemyList; } public void RestartGame() { SetUpPlayer(); SetUpEnemies(); } } //Pick what type of enemies and how many of each enemy type you want to spawn into the current level. [System.Serializable] public class EnemySpawner { public GameObject enemyType; public int enemyAmount; } <file_sep>/Final Project Game/Assets/Scripts/Player/PlayerHealth.cs using UnityEngine; using System.Collections; using UnityEngine.UI; public class PlayerHealth : MonoBehaviour { public Slider healthBar; [SerializeField] private TurnHandler turnHandler; public int health, looseHealthAmount, maxHealth; public void UpdateHealth(int healthAmount) { //If the given parameter is negative, if(healthAmount < 0) { //If the Player is alive, negate health. if(health > 0) { health -= looseHealthAmount; } //If negating health made the Player have less than 0 health, set it back to 0. (For a split second before the game is over, this is helpful for the visual aspect). if(health < 0) { health = 0; } } else { //add health if parameter given was not less than 0. if(health < maxHealth) { health += healthAmount; } if(health > maxHealth) { health = maxHealth; } } if(health == 0) { healthBar.value = 0; //Tried to fix the "InvalidOperationException: Collection was modified" error, failed, it has been added to the Backlog on Hack n Plan. //turnHandler.levelSet = false; //Destory every enemy on the board for(int i = 0; i < turnHandler.enemyList.Count; ++i) { Destroy(turnHandler.enemyList[i].gameObject); } //Clear the list of enemies. turnHandler.enemyList.Clear(); //You lost, display the loser screen. turnHandler.lostGameUI.SetActive(true); turnHandler.gameRestarted = true; turnHandler.TilesBackToPurple(); } else {//Player is not dead yet, update health bar. healthBar.value = health; } } } <file_sep>/Final Project Game/Assets/Scripts/Enemy/EnemyMovement.cs using UnityEngine; using System.Collections; using System.Collections.Generic; public class EnemyMovement : MonoBehaviour { private TurnHandler turnHandler; private Player player; private Enemy enemy; [HideInInspector] //References to the horizontal and vertical tile amounts. public int xTilesAmount, yTilesAmount; //The tile the enemy spawns on. public int currentTileNumber; //For checking what moves are vallid and invalid each turn. public List<string> illegalMoves, acceptableMoves; [SerializeField] //The 8 total directions. private List<string> directions; //For checking if player is in a tile the enemy can attack in. private bool attackThisTurn; void Start() { player = FindObjectOfType<Player>(); enemy = FindObjectOfType<Enemy>(); turnHandler = enemy.turnHandler; xTilesAmount = enemy.xTilesAmount; yTilesAmount = enemy.yTilesAmount; } public void EnemyTurnLogic() { //Check for the player's and all other enemy's current tile. This prevents enemies stacking on top of each other and/or the player. PlayerAndEnemyLocationChecker(); attackThisTurn = gameObject.GetComponent<EnemyAttack>().CheckCanAttackPlayer(); //If player is in a tile the enemy can attack in, if(attackThisTurn) { //Don't move, instead attack! enemy.Attack(); attackThisTurn = false; } else { //Continue checking for movement directions CheckBoundaries(); //All checks are done, now the Enemy can pick a direction to move in! MovementCheckerAndMove(); } illegalMoves.Clear(); acceptableMoves.Clear(); } //Checks to see if the Player or any other enemies are in the tile the current enemy wants to move to. void PlayerAndEnemyLocationChecker() { //Up //If Player is not in the enemy's wantedPosition, if(player.movement.currentTileNumber != currentTileNumber - xTilesAmount) { //Check all other enemy's positions, foreach(GameObject enemy in turnHandler.enemyList) { //If another enemy is in that position, if(enemy.GetComponent<EnemyMovement>().currentTileNumber == currentTileNumber - xTilesAmount) { //It is an illegal movement (no stacking enemies on top of each other). illegalMoves.Add("Up"); } } } else { //Player is in the current enemy's wantedPosition, illegalMoves.Add("Up"); } //UpRight //If Player is not in the enemy's wantedPosition, if(player.movement.currentTileNumber != currentTileNumber - (xTilesAmount - 1)) { //Check all other enemy's positions, foreach(GameObject enemy in turnHandler.enemyList) { //If another enemy is in that position, if(enemy.GetComponent<EnemyMovement>().currentTileNumber == currentTileNumber - (xTilesAmount - 1)) { //It is an illegal movement (no stacking enemies on top of each other). illegalMoves.Add("UpRight"); } } } else { illegalMoves.Add("UpRight"); } //Right //If Player is not in the enemy's wantedPosition, if(player.movement.currentTileNumber != currentTileNumber + 1) { //Check all other enemy's positions, foreach(GameObject enemy in turnHandler.enemyList) { //If another enemy is in that position, if(enemy.GetComponent<EnemyMovement>().currentTileNumber == currentTileNumber + 1) { //It is an illegal movement (no stacking enemies on top of each other). illegalMoves.Add("Right"); } } } else { illegalMoves.Add("Right"); } //DownRight //If Player is not in the enemy's wantedPosition, if(player.movement.currentTileNumber != currentTileNumber + (xTilesAmount + 1)) { //Check all other enemy's positions, foreach(GameObject enemy in turnHandler.enemyList) { //If another enemy is in that position, if(enemy.GetComponent<EnemyMovement>().currentTileNumber == currentTileNumber + (xTilesAmount + 1)) { //It is an illegal movement (no stacking enemies on top of each other). illegalMoves.Add("DownRight"); } } } else { illegalMoves.Add("DownRight"); } //Down //If Player is not in the enemy's wantedPosition, if(player.movement.currentTileNumber != currentTileNumber + xTilesAmount) { //Check all other enemy's positions, foreach(GameObject enemy in turnHandler.enemyList) { //If another enemy is in that position, if(enemy.GetComponent<EnemyMovement>().currentTileNumber == currentTileNumber + xTilesAmount) { //It is an illegal movement (no stacking enemies on top of each other). illegalMoves.Add("Down"); } } } else { illegalMoves.Add("Down"); } //DownLeft //If Player is not in the enemy's wantedPosition, if(player.movement.currentTileNumber != currentTileNumber + (xTilesAmount - 1)) { //Check all other enemy's positions, foreach(GameObject enemy in turnHandler.enemyList) { //If another enemy is in that position, if(enemy.GetComponent<EnemyMovement>().currentTileNumber == currentTileNumber + (xTilesAmount - 1)) { //It is an illegal movement (no stacking enemies on top of each other). illegalMoves.Add("DownLeft"); } } } else { illegalMoves.Add("DownLeft"); } //Left //If Player is not in the enemy's wantedPosition, if(player.movement.currentTileNumber != currentTileNumber - 1) { //Check all other enemy's positions, foreach(GameObject enemy in turnHandler.enemyList) { //If another enemy is in that position, if(enemy.GetComponent<EnemyMovement>().currentTileNumber == currentTileNumber - 1) { //It is an illegal movement (no stacking enemies on top of each other). illegalMoves.Add("Left"); } } } else { illegalMoves.Add("Left"); } //UpLeft //If Player is not in the enemy's wantedPosition, if(player.movement.currentTileNumber != currentTileNumber - (xTilesAmount + 1)) { //Check all other enemy's positions, foreach(GameObject enemy in turnHandler.enemyList) { //If another enemy is in that position, if(enemy.GetComponent<EnemyMovement>().currentTileNumber == currentTileNumber - (xTilesAmount + 1)) { //It is an illegal movement (no stacking enemies on top of each other). illegalMoves.Add("UpLeft"); } } } else { illegalMoves.Add("UpLeft"); } //Final Check for Top-Left tile (It is a very gross tile, never want to move there. if(currentTileNumber - xTilesAmount == 1) { illegalMoves.Add("Up"); } else if(currentTileNumber - (xTilesAmount - 1) == 1) { illegalMoves.Add("UpLeft"); } else if (currentTileNumber - 1 == 1) { illegalMoves.Add("Left"); } } //We do not want enemies to go outside the boundaries of the map, so make moves illegal if they would put the enemy outside the tiles. void CheckBoundaries() { //Up if(currentTileNumber - xTilesAmount <= 0) { illegalMoves.Add("Up"); } //UpRight if(currentTileNumber - (xTilesAmount - 1) < 2 || (currentTileNumber - (xTilesAmount - 1)) % xTilesAmount == 1) { illegalMoves.Add("UpRight"); } //Right if(currentTileNumber % xTilesAmount == 0) { illegalMoves.Add("Right"); } //DownRight if(currentTileNumber + (xTilesAmount + 1) > xTilesAmount * yTilesAmount || (currentTileNumber + (xTilesAmount + 1)) % xTilesAmount == 1) { illegalMoves.Add("DownRight"); } //Down if(currentTileNumber + xTilesAmount > xTilesAmount * yTilesAmount) { illegalMoves.Add("Down"); } //DownLeft if(currentTileNumber + (xTilesAmount - 1) > (xTilesAmount * yTilesAmount) - 1 || (currentTileNumber + (xTilesAmount - 1)) % xTilesAmount == 0) { illegalMoves.Add("DownLeft"); } //Left if(currentTileNumber % xTilesAmount == 1) { illegalMoves.Add("Left"); } //UpLeft if(currentTileNumber - (xTilesAmount + 1) <= 0 || (currentTileNumber - (xTilesAmount + 1)) % xTilesAmount == 0) { illegalMoves.Add("UpLeft"); } } string RandomDirection() { int directionChoice = Random.Range(0, acceptableMoves.Count); //DEBUG STUFF //string[] tempArray = acceptableMoves.ToArray(); //string tempString = string.Join(", ", tempArray); //print("List of Available Moves: " + tempString); //print("Direction Chosen: " + acceptableMoves[directionChoice]); return acceptableMoves[directionChoice]; } void MovementCheckerAndMove() { string moveDirection = ""; //This is slight fsckery, but it basically checks all possible moves against the illegalMoves //and if it doesn't find the direction it is currently checking from the list of all possibe directions in the illegalMoves list, //it must be an acceptable movement, so add it to the acceptableMoves list. foreach(string directionToCheck in directions) { bool directionFound = false; foreach(string badDirection in illegalMoves) { if(badDirection == directionToCheck) { directionFound = true; break; } } if(!directionFound) { acceptableMoves.Add(directionToCheck); } } //If after that, the acceptableMoves list has at least 1 item (direction), if(acceptableMoves.Count > 0) { //Pick a random direction from the list. moveDirection = RandomDirection(); } //If the acceptableMoves list had at least 1 item (direction) in it, it chose a random direction from thelist to move in, if(moveDirection != "") { //Clear the previous attackeable tiles if they were visible. if(gameObject.GetComponent<EnemyAttack>().tilesShown) { gameObject.GetComponent<EnemyAttack>().EnemyRemoveAttackableTiles(); } //So move in that direction. Move(moveDirection); } } //Movement logic for enemies. void Move(string direction) { //print("Enemy Moved"); //The direction that was randomly chosen from the list of acceptableMoves. switch(direction) { case "Up": //Move Up gameObject.transform.position += new Vector3(0, 1, 0); currentTileNumber -= xTilesAmount; break; case "UpRight": //Move UpRight gameObject.transform.position += new Vector3(1, 1, 0); currentTileNumber -= (xTilesAmount - 1); break; case "Right": //Move Right gameObject.transform.position += new Vector3(1, 0, 0); currentTileNumber += 1; break; case "DownRight": //Move DownRight gameObject.transform.position += new Vector3(1, -1, 0); currentTileNumber += (xTilesAmount + 1); break; case "Down": //Move Down gameObject.transform.position += new Vector3(0, -1, 0); currentTileNumber += xTilesAmount; break; case "DownLeft": //Move DownLeft gameObject.transform.position += new Vector3(-1, -1, 0); currentTileNumber += (xTilesAmount - 1); break; case "Left": //Move Left gameObject.transform.position += new Vector3(-1, 0, 0); currentTileNumber -= 1; break; case "UpLeft": //Move UpLeft gameObject.transform.position += new Vector3(-1, 1, 0); currentTileNumber -= (xTilesAmount + 1); break; } //A new move has been made, which means the attackable tiles are now different, so clear the previous list of attackable tiles. gameObject.GetComponent<EnemyAttack>().enemyAttackableTiles.Clear(); //Now we can calculate the new attackable tiles. gameObject.GetComponent<EnemyAttack>().CalculateAttackableTiles(); } }<file_sep>/Final Project Game/Assets/Scripts/Misc/RotationFix.cs using System.Collections; using System.Collections.Generic; using UnityEngine; //Fix sprite rotations so that they face the camera, making the world look 3D. public class RotationFix : MonoBehaviour { private void Start() { transform.rotation = Quaternion.LookRotation(Camera.main.transform.forward) * Quaternion.Euler(0f, 0f, -45f); } }<file_sep>/Procedural Generation Prototype/Assets/Scripts/Player.cs using UnityEngine; using System.Collections; public class Player : MonoBehaviour { Rigidbody rb; Vector3 velocity; public float speed; private Vector3 rot; void Start() { rb = GetComponent<Rigidbody>(); rot = rot; } void Update() { velocity = new Vector3 (0, 0, Input.GetAxisRaw ("Vertical")).normalized * 10; } void FixedUpdate() { //rb.MovePosition(rb.position + velocity * Time.fixedDeltaTime); //transform.position = (transform.position + velocity) * Time.fixedDeltaTime; transform.Translate(velocity * Time.fixedDeltaTime); //if(rot.y > 178 && rot.y < 182 || rot.y > 358 || rot.y < 2) { // rot.y = rot.y - 3; //} if(Input.GetAxisRaw("Horizontal") != 0) { transform.Rotate(new Vector3(0, rot.y + Input.GetAxisRaw("Horizontal"), 0).normalized * 2 * speed); } // rot *= Quaternion.Euler(0, (Input.GetAxisRaw("Horizontal") * speed * Time.fixedDeltaTime), 0); //} } }<file_sep>/Final Project Level Creation Tool/Assets/Scripts/EventManager/EventManager.cs using UnityEngine; using System.Collections; using System.Collections.Generic; public class EventManager : MonoBehaviour { static Dictionary<System.Type, System.Delegate> dict = new Dictionary<System.Type, System.Delegate>(); public delegate void EventDelegate<T>(T a) where T : GameEvent; public static void AddListener<T>(EventDelegate<T> del) where T : GameEvent { //registerObserver if(dict.ContainsKey(typeof(T))) { dict[typeof(T)] = System.Delegate.Combine(dict[typeof(T)], del); } else { dict.Add(typeof(T), del); } } public static void RemoveListener<T>(EventDelegate<T> del) where T : GameEvent { //unregisterObserver dict[typeof(T)] = System.Delegate.Remove(dict[typeof(T)], del); } public static void Raise(GameEvent e) { //notify if(dict.ContainsKey(e.GetType())) { dict[e.GetType()].DynamicInvoke(e); } } } <file_sep>/Procedural Generation Prototype/Assets/CameraController2D.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraController2D : MonoBehaviour { public Transform target; //The Distance and Height from the object. public float distance = 20.0f; public float height = 5.0f; public Vector3 lookAtVector; // Use this for initialization void Start () { Camera.main.orthographicSize = 10; } // Update is called once per frame void Update () { transform.position = new Vector3(target.position.x, target.position.y, -10); } } <file_sep>/Final Project Game/Assets/Scripts/Enemy/Enemy.cs using UnityEngine; using System.Collections; using System.Collections.Generic; public class Enemy : MonoBehaviour { [HideInInspector] public EnemyAttack attack; [HideInInspector] public EnemyMovement movement; [HideInInspector] public TurnHandler turnHandler; [HideInInspector] public List<GameObject> gridOfTiles; #region Reference Holders for other Enemy scripts. [HideInInspector] public int xTilesAmount, yTilesAmount; [HideInInspector] public GameObject currentlySelectedEnemy; public bool enemySwapped, currentSelectedEnemyIsDead; #endregion void Start() { turnHandler = FindObjectOfType<TurnHandler>(); attack = FindObjectOfType<EnemyAttack>(); movement = FindObjectOfType<EnemyMovement>(); currentlySelectedEnemy = null; } public void Attack() { attack.EnemyAttackLogic(); } } <file_sep>/Final Project Game/Assets/Scripts/Player/PlayerAttack.cs using UnityEngine; using System.Collections; public class PlayerAttack : MonoBehaviour { public TurnHandler turnHandler; public void PlayerAttackLogic(GameObject enemyToAttack) { //Negate the enemy's health enemyToAttack.GetComponent<EnemyHealth>().UpdateHealth(-enemyToAttack.GetComponent<EnemyHealth>().looseHealthAmount); //If the attack killed the last enemy, if(turnHandler.enemyList.Count == 0) { //You won this room! Congrats! turnHandler.wonGameUI.SetActive(true); turnHandler.gameRestarted = true; } gameObject.GetComponent<PlayerMovement>().wantedTileNumber = gameObject.GetComponent<PlayerMovement>().currentTileNumber; turnHandler.turnNumber++; } } <file_sep>/Level Creating Tool 5.5 - DO NOT USE/Assets/Scripts/PlacementTileListNumber.cs using UnityEngine; public class PlacementTileListNumber : MonoBehaviour { public int listNum; private bool tileSet; public bool isBlank; private TilePlacer tilePlacer; void Start() { tilePlacer = FindObjectOfType<TilePlacer>(); isBlank = true; } void OnMouseOver() { if(Input.GetMouseButton(0) && !tileSet) { tileSet = true; tilePlacer.OnTileClicked(gameObject); } } void OnMouseExit() { tileSet = false; } void OnMouseUp() { tileSet = false; } }
822e8ef620d75a406a74ca84bb2efae7fcb4705d
[ "C#" ]
29
C#
DanielJochem/Final-Project-Prototypes
b9db97f04fa7c4e5f8933b8efffe1cad89723c02
9ad3cd70ba3691fe0e37e986622cc9269d7c43f1
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Essentials; namespace EssentialsDemo { // Learn more about making custom code visible in the Xamarin.Forms previewer // by visiting https://aka.ms/xamarinforms-previewer [DesignTimeVisible(false)] public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); } private void ReadDescription(object sender, EventArgs e) { TextToSpeech.SpeakAsync(description.Text, default); } private void CallContactNumber(object sender, EventArgs e) { PhoneDialer.Open(contactNumber.Text); } private async void SeeDirections(object sender, EventArgs e) { var location = await Geocoding.GetLocationsAsync(storeAddress.Text); await Map.OpenAsync(location.FirstOrDefault(), new MapLaunchOptions { NavigationMode = NavigationMode.Driving }); } } }
11afcdec72b64502ca4a272a561c1f7c207e3787
[ "C#" ]
1
C#
mindofai/DemoEssentials
967863a1c4573f8fc0ff08a01e65953d1fe6a684
660705d30ce2fbdd3024967782ed08a280e02e82
refs/heads/master
<file_sep>import React, { useState, useContext } from 'react'; import { Paper, Typography, Button, MenuItem, TextField, Modal, } from '@material-ui/core/'; import { makeStyles } from '@material-ui/core/styles'; import { FormattedMessage } from 'react-intl'; import AlertContext from '../context/alert/alertContext'; import Alert from '../components/layout/Alert'; const useStyles = makeStyles((theme) => ({ 'root': { height: '40vh', width: '100%', display: 'flex', justifyContent: 'center', }, 'form': { width: '40vw', backgroundColor: theme.palette.primary.main, display: 'flex', justifyContent: 'center', alignItems: 'center', flexDirection: 'column', marginBottom: '5rem', position: 'relative', animationName: '$fadeInLeft', animationDuration: '2s', }, 'formItem': { margin: theme.spacing(2), width: '80%', }, 'modal': { width: '20vw', minWidth: '400px', padding: theme.spacing(2), backgroundColor: theme.palette.primary.main, display: 'flex', justifyContent: 'center', alignItems: 'center', flexDirection: 'column', marginBottom: '5rem', }, 'modalRoot': { height: '100%', width: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center', }, 'modalItem': { textAlign: 'center', }, 'modalBottom': { marginTop: theme.spacing(), }, 'textInput': { '& .MuiOutlinedInput-root': { '& fieldset': { borderColor: theme.palette.secondary.main, }, '&:hover fieldset': { borderColor: theme.palette.secondary.main, }, }, '& .MuiInputBase-input': { color: theme.palette.secondary.main, }, '& .MuiInputLabel-root': { color: theme.palette.secondary.main, }, 'margin': theme.spacing(2), 'width': '80%', }, 'submit': { marginBottom: theme.spacing(2), width: '40%', }, '@keyframes fadeInLeft': { from: { opacity: 0, right: '30vw' }, to: { opacity: 1, right: '0vw' }, }, })); const Signup = () => { // state const classes = useStyles(); const [firstName, setFirstName] = useState(''); const [lastName, setLastName] = useState(''); const [studentNumber, setStudentNumber] = useState(''); const [email, setEmail] = useState(''); const [phone, setPhone] = useState(''); const [nationality, setNationality] = useState(''); const [studentType, setStudentType] = useState(''); const [japanese, setJapanese] = useState(''); const [open, setOpen] = useState(''); // context const alertContext = useContext(AlertContext); const { setAlert, clearAlert } = alertContext; //Todo: add debounce if have time const onSubmit = () => { const user = { firstName, lastName, studentNumber, email, phone, nationality, studentType, japanese, }; registerMember(user); }; const registerMember = (formData) => { let status = null; let errorArr = []; fetch('/api/members', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(formData), }) .then((res) => { status = res.status; return res.json(); }) .then((data) => { if (status >= 200 && status <= 300) { setOpen(true); } else { if (Array.isArray(data.errors)) { for (let error of data.errors) { errorArr.push(error.msg); } throw new Error(); } else { errorArr.push(data.msg); throw new Error(); } } }) .catch((error) => { setAlert(errorArr.length > 0 ? errorArr : error, 'danger'); window.scrollTo({ top: 0, behavior: 'smooth', }); }); }; const handleClose = () => { setOpen(false); setFirstName(''); setLastName(''); setStudentNumber(''); setEmail(''); setPhone(''); setNationality(''); setStudentType(''); setJapanese(''); clearAlert(); }; return ( <div className={classes.root}> <div> <Paper className={classes.form} elevation={5}> <Typography color='secondary' variant='h4' className={classes.formItem} > <FormattedMessage id='signup.title' defaultMessage='Signup' /> </Typography> <Typography color='secondary' variant='h5' className={classes.formItem} > <FormattedMessage id='signup.instruction' defaultMessage='Signup' /> </Typography> <Alert /> <TextField label='First Name' variant='outlined' color='secondary' className={classes.textInput} value={firstName} autoComplete='no' autoFocus onChange={(e) => setFirstName(e.target.value)} required /> <TextField label='Last Name' variant='outlined' color='secondary' autoComplete='no' className={classes.textInput} value={lastName} onChange={(e) => setLastName(e.target.value)} required /> <TextField label='Stundent Number' variant='outlined' color='secondary' className={classes.textInput} value={studentNumber} autoComplete='no' onChange={(e) => setStudentNumber(e.target.value)} required /> <TextField label='Phone' variant='outlined' color='secondary' value={phone} onChange={(e) => setPhone(e.target.value)} className={classes.textInput} autoComplete='no' required /> <TextField label='Email' variant='outlined' color='secondary' className={classes.textInput} value={email} autoComplete='no' onChange={(e) => setEmail(e.target.value)} required /> <TextField label='Nationality' variant='outlined' color='secondary' value={nationality} onChange={(e) => setNationality(e.target.value)} className={classes.textInput} autoComplete='no' /> <TextField label='Student Type' variant='outlined' color='secondary' className={classes.textInput} value={studentType} onChange={(e) => setStudentType(e.target.value)} select autoComplete='no' > <MenuItem value={'international'}> <FormattedMessage id='signup.international' /> </MenuItem> <MenuItem value={'domestic'}> <FormattedMessage id='signup.domestic' /> </MenuItem> <MenuItem value={'other'}> <FormattedMessage id='signup.other' /> </MenuItem> </TextField> <TextField id='fluency' label='Japanese Fluency' variant='outlined' color='secondary' className={classes.textInput} value={japanese} onChange={(e) => setJapanese(e.target.value)} select autoComplete='no' > <MenuItem value={'beginner'}> <FormattedMessage id='signup.beginner' /> </MenuItem> <MenuItem value={'intermediate'}> <FormattedMessage id='signup.intermediate' /> </MenuItem> <MenuItem value={'advanced'}> <FormattedMessage id='signup.advanced' /> </MenuItem> <MenuItem value={'native'}> <FormattedMessage id='signup.native' /> </MenuItem> </TextField> <Typography color='secondary' variant='h5' className={classes.formItem} > <FormattedMessage id='signup.reminder' defaultMessage='Signup' /> </Typography> <Button className={classes.submit} color='primary' variant='contained' onClick={onSubmit} > <Typography color='secondary'> <FormattedMessage id='signup.register' defaultMessage='Welcome' /> </Typography> </Button> </Paper> <Modal open={open} onClose={handleClose} aria-labelledby='simple-modal-title' aria-describedby='simple-modal-description' className={classes.modalRoot} > <Paper className={classes.modal} elevation={5}> <Typography color='secondary' className={classes.modalItem} >{`Dear ${lastName},`}</Typography> <Typography color='secondary' className={classes.modalItem}> <FormattedMessage id='signup.success' defaultMessage='You have succesfully registered to UQJX ' /> </Typography> <Typography color='secondary' className={classes.modalItem}> <FormattedMessage id='signup.success2' defaultMessage='' /> </Typography> <Button className={classes.modalBottom} color='primary' variant='contained' onClick={() => { setOpen(false); handleClose(); window.scrollTo({ top: 0, behavior: 'smooth', }); }} > <Typography color='secondary'> <FormattedMessage id='signup.close' defaultMessage='close' /> </Typography> </Button> </Paper> </Modal> </div> </div> ); }; export default Signup; <file_sep>import React from 'react'; import { Typography } from '@material-ui/core/'; import { makeStyles } from '@material-ui/core/styles'; import { FormattedMessage } from 'react-intl'; const useStyles = makeStyles(theme => ({ root: { display: 'flex', width: '35vw', minWidth: '250px', borderBottomStyle: 'ridge', borderWidth: '1px' }, leftSection: { borderRightStyle: 'ridge', minWidth: '35%', borderWidth: '1px' }, leftTopSection: { height: '10vh', display: 'flex', justifyContent: 'center', alignItems: 'center', flexDirection: 'column' }, leftBottomSection: { borderTopStyle: 'ridge', height: '5vh', borderWidth: '1px', display: 'flex', textAlign: 'center', justifyContent: 'center', alignItems: 'center', flexDirection: 'column', paddingTop: '2rem', paddingBottom: '2rem' }, rightSection: { display: 'flex', alignItems: 'center', paddingLeft: theme.spacing() } })); const EventItem = ({ date, type, content }) => { const classes = useStyles(); return ( <div className={classes.root}> <div className={classes.leftSection}> <div className={classes.leftTopSection}> <Typography variant='h4' color='secondary'> {date.month} </Typography> <Typography variant='h5' color='secondary'> {date.day} </Typography> </div> <div className={classes.leftBottomSection}> <Typography variant='h6' color='secondary'> {type} </Typography> </div> </div> <div className={classes.rightSection}> <Typography variant='h6' color='secondary'> {content} </Typography> </div> </div> ); }; export default EventItem; <file_sep># UQJX Website This site is intended to be used as welcome page for UQJX society with addition of membership management and registration [UQJX_Website](https://uqjx.herokuapp.com/) <file_sep>import React from 'react'; import { FormattedMessage } from 'react-intl'; import { Paper, Typography } from '@material-ui/core/'; import { makeStyles } from '@material-ui/core/styles'; import groupImage from '../assets/img/UQJX_Group.png'; const useStyles = makeStyles(theme => ({ root: { height: '40vh', width: '100%', display: 'flex', justifyContent: 'center' }, form: { width: '40vw', minWidth: '300px', backgroundColor: theme.palette.primary.main, marginBottom: theme.spacing(3), padding: theme.spacing(), display: 'flex', alignItems: 'center', flexDirection: 'column' }, formItem: { margin: theme.spacing(2), marginBottom: theme.spacing(3) }, image: { marginTop: theme.spacing(2), marginBottom: theme.spacing(2), objectFIt: 'contain', width: '90%' } })); const About = () => { const classes = useStyles(); return ( <div className={classes.root}> <div> <Paper className={classes.form} elevation={5}> <Typography color='secondary' variant='h4' className={classes.formItem} gutterBottom > <FormattedMessage id='about.title' defaultMessage='Signup' /> </Typography> <Typography color='secondary' variant='body1' className={classes.formItem} > <FormattedMessage id='about.content' defaultMessage='Signup' /> </Typography> <Typography color='secondary' variant='body1' className={classes.formItem} > <FormattedMessage id='about.content2' defaultMessage='Signup' /> </Typography> <Typography color='secondary' variant='body1' className={classes.formItem} > <FormattedMessage id='about.content3' defaultMessage='Signup' /> </Typography> <img src={groupImage} alt='UQJX Group' className={classes.image} /> </Paper> </div> </div> ); }; export default About; <file_sep>// Dependencies import React, { Fragment } from 'react'; import { makeStyles } from '@material-ui/core/styles'; import { Box, Grid } from '@material-ui/core'; import logo from '../assets/img/UQJX_Logo_White.png'; // UI import WelcomeMenu from '../components/layout/HomeWelcomeMenu'; const useStyles = makeStyles((theme) => ({ 'root': { height: '90vh', }, 'content': { height: '90vh', width: '100vw', }, 'welcomeMenu': { position: 'relative', animationName: '$fadeInLeft', animationDuration: '2s', }, 'logo': { height: '40vw', width: '40vw', position: 'relative', borderRadius: '400px', animationName: '$fadeInRight', animationDuration: '2s', }, '@keyframes fadeInLeft': { from: { opacity: 0, right: '30vw' }, to: { opacity: 1, right: '0vw' }, }, '@keyframes fadeInRight': { from: { opacity: 0, left: '30vw' }, to: { opacity: 1, left: '0vw' }, }, })); const Home = () => { const classes = useStyles(); return ( <Fragment> <Box className={classes.root}> <Grid className={classes.content} container spacing={3} justify='space-around' alignItems='center' > <Grid item className={classes.welcomeMenu}> <WelcomeMenu /> </Grid> <Grid item> <img className={classes.logo} src={logo} alt='UQJX_Logo' /> </Grid> </Grid> </Box> </Fragment> ); }; export default Home; <file_sep>import React from 'react'; import BuildIcon from '@material-ui/icons/Build'; const Sponsors = () => { return ( <div style={{ display: 'flex', justifyContent: 'center' }} > <BuildIcon style={{ fontSize: 100 }} />{' '} <h1>We are still building this part. Sorry for this</h1> </div> ); }; export default Sponsors; <file_sep>// Dependencies import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import { Button, Grid, Typography, ButtonGroup } from '@material-ui/core'; import { FormattedMessage } from 'react-intl'; import { PersonAdd, LocalLibrary } from '@material-ui/icons'; import { Link } from 'react-router-dom'; const useStyles = makeStyles(theme => ({ welcomeMessage: { marginBottom: '3rem' }, buttonGroup: { display: 'flex', justifyContent: 'space-evenly' }, button: { minWidth: '13vw', padding: '1rem', textDecoration: 'none' }, buttonItem: { marginRight: '0.6rem' } })); const HomeWelcomeMenu = () => { const classes = useStyles(); return ( <div> <Grid container direction='column' justify='space-around'> <Typography className={classes.welcomeMessage} variant='h4' color='secondary' > <FormattedMessage id='home.welcome' defaultMessage='Welcome' /> </Typography> <ButtonGroup className={classes.buttonGroup} color='primary' size='large' > <Button color='primary' className={classes.button} variant='contained' component={Link} to='/signup' > <PersonAdd className={classes.buttonItem} /> <Typography color='secondary'> <FormattedMessage id='home.join' defaultMessage='Welcome' /> </Typography> </Button> <Button className={classes.button} variant='contained' component={Link} to='/intro' > <LocalLibrary className={classes.buttonItem} /> <Typography color='secondary'> <FormattedMessage id='home.know' defaultMessage='Welcome' /> </Typography> </Button> </ButtonGroup> </Grid> </div> ); }; export default HomeWelcomeMenu; <file_sep>const mongoose = require('mongoose'); const MemberSchema = mongoose.Schema({ studentNumber: { type: Number, required: true, unique: true, }, firstName: { type: String, required: true, }, lastName: { type: String, required: true, }, phone: { type: String, required: true, }, email: { type: String, required: true, }, nationality: { type: String, }, studentType: { type: String, }, fluency: { type: String, }, }); module.exports = mongoose.model('member', MemberSchema);
0f13726109212e1d100c1730ec8bc51c781f02b5
[ "JavaScript", "Markdown" ]
8
JavaScript
liweyeh/uqjx_react
54477ea6fd2731f6e88cc6243a0c58158e02299d
3a630ad6e18da14455b26f65395b20e23303894a
refs/heads/master
<file_sep># WakeLockService * Version: 0.0.4 # History * Version 0.0.4 + *Release: July 20th, 2015* + `WakeLockService`: add protected method `shouldUseWakeLock()`. * Version 0.0.3 + *Release: July 15th, 2015* + `WakeLockService`: shutdown all tasks in `onDestroy()`. * Version 0.0.2 + *Release: July 6th, 2015* + Lower max idle time to 10 seconds instead of 1 minute. * Version 0.0.1 + *Release: June 17th, 2015* + First release. * Version 0.0.1b + *Initialize: June 17th, 2015* <file_sep>/* * Copyright (c) 2015 <NAME> * * See the file LICENSE at the root directory of this project for copying permission. */ include ':app' <file_sep>/* * Copyright (c) 2015 <NAME> * * See the file LICENSE at the root directory of this project for copying permission. */ package haibison.android.wake_lock_service; import android.Manifest; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.IBinder; import android.os.PowerManager; import android.os.RemoteCallbackList; import android.os.RemoteException; import android.util.Log; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static android.text.format.DateUtils.SECOND_IN_MILLIS; /** * Base service which uses {@link android.os.PowerManager.WakeLock} for its entire life time. * <p/> * <strong>Notes</strong> <ul><li>Use of {@link android.os.PowerManager.WakeLock} is optional. If you don't declare * permission {@link android.Manifest.permission#WAKE_LOCK} in your manifest, the service still works.</li><li>We * recommend to put this service on a separate process.</li> <li>{@link #onStartCommand(Intent, int, int)} returns * {@link #START_NOT_STICKY} by default. If you don't handle incoming intents from clients, you should always pass them * to super method. If you want the super method return other result, override {@link * #getResultForOnStartCommand()}.</li> </ul> */ public class WakeLockService extends Service { /** * The library name. */ public static final String LIB_NAME = "WakeLockService"; /** * The library version name. */ public static final String LIB_VERSION_NAME = "0.0.4"; private static final String CLASSNAME = WakeLockService.class.getName(); /** * Use this action to stop this service. */ public static final String ACTION_STOP_SELF = CLASSNAME + ".STOP_SELF"; /** * This extra holds a {@link PendingIntent} which will be called when your main action is done. * <p/> * Type: {@link PendingIntent}. */ public static final String EXTRA_POST_PENDING_INTENT = CLASSNAME + ".POST_PENDING_INTENT"; /** * Maximum idle time, in milliseconds. */ public static final long MAX_IDLE_TIME = SECOND_IN_MILLIS * 10; /** * The service is idle. */ public static final int SERVICE_STATE_IDLE = -1; /** * The service is working. */ public static final int SERVICE_STATE_WORKING = -2; /** * Extended-classes' service states can be defined starting from this value (and go upward). */ protected static final int SERVICE_STATE_FIRST_EXTENDER = 0; /** * Extended-classes' messages can be defined starting from this value (and go upward). */ protected static final int MSG_FIRST_EXTENDER = 0; /** * Message finished. */ public static final int MSG_FINISHED = -1; /** * Message cancelled. */ public static final int MSG_CANCELLED = -2; /** * Message error. */ public static final int MSG_ERROR = -3; private final RemoteCallbackList<IWakeLockServiceEventListener> mEventListeners = new RemoteCallbackList<IWakeLockServiceEventListener>(); private PowerManager mPowerManager; private PowerManager.WakeLock mWakeLock; private int mServiceState = SERVICE_STATE_IDLE; private final BlockingQueue<Runnable> mWorkerQueue = new LinkedBlockingQueue<Runnable>(); private ThreadPoolExecutor mThreadPoolExecutor; /** * Will be called by this service to confirm using wake lock or not. Default implementation returns {@code true}. * * @return {@code true} or {@code false}. */ protected boolean shouldUseWakeLock() { return true; }//shouldUseWakeLock() @Override public void onCreate() { super.onCreate(); // Get PowerManager mPowerManager = (PowerManager) getSystemService(POWER_SERVICE); // Acquire new wake lock. if (shouldUseWakeLock() && checkPermission(Manifest.permission.WAKE_LOCK, android.os.Process.myPid(), android.os.Process.myUid()) == PackageManager.PERMISSION_GRANTED) { mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, CLASSNAME); mWakeLock.acquire(); }//if // Create thread pool executor mThreadPoolExecutor = new ThreadPoolExecutor(1, Runtime.getRuntime() .availableProcessors(), MAX_IDLE_TIME, TimeUnit.MILLISECONDS, mWorkerQueue) { @Override protected void beforeExecute(Thread t, Runnable r) { cancelScheduleToStopSelf(); super.beforeExecute(t, r); }// beforeExecute() @Override protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); scheduleToStopSelf(); }// afterExecute() }; }//onCreate() @Override public IBinder onBind(Intent intent) { return mServiceBinder; }//onBind() /** * The service binder, */ private final IWakeLockService.Stub mServiceBinder = new IWakeLockService.Stub() { @Override public void registerEventListener(IWakeLockServiceEventListener listener) throws RemoteException { if (listener != null) { mEventListeners.register(listener); notifyServiceStateChanged(listener); }// if }//registerEventListener() @Override public void unregisterEventListener(IWakeLockServiceEventListener listener) throws RemoteException { if (listener != null) mEventListeners.unregister(listener); }//unregisterEventListener() @Override public int getServiceState() throws RemoteException { return mServiceState; }//getServiceState() @Override public boolean getBooleanValue(int id) throws RemoteException { return WakeLockService.this.getBooleanValue(id); }//getBooleanValue() @Override public float getFloatValue(int id) throws RemoteException { return WakeLockService.this.getFloatValue(id); }//getFloatValue() @Override public double getDoubleValue(int id) throws RemoteException { return WakeLockService.this.getDoubleValue(id); }//getDoubleValue() @Override public int getIntValue(int id) throws RemoteException { return WakeLockService.this.getIntValue(id); }//getIntValue() @Override public long getLongValue(int id) throws RemoteException { return WakeLockService.this.getLongValue(id); }//getLongValue() @Override public CharSequence getCharSequenceValue(int id) throws RemoteException { return WakeLockService.this.getCharSequenceValue(id); }//getCharSequenceValue() @Override public String getStringValue(int id) throws RemoteException { return WakeLockService.this.getStringValue(id); }//getStringValue() @Override public Bundle getBundleValue(int id) throws RemoteException { return WakeLockService.this.getBundleValue(id); }//getBundleValue };//mServiceBinder @Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent == null) { if (getServiceState() != SERVICE_STATE_WORKING) scheduleToStopSelf(); return getResultForOnStartCommand(); }//if if (ACTION_STOP_SELF.equals(intent.getAction())) { stopSelf(); }//ACTION_STOP_SELF else if (getServiceState() != SERVICE_STATE_WORKING) scheduleToStopSelf(); return getResultForOnStartCommand(); }//onStartCommand() /** * Gets result for {@link #onStartCommand(Intent, int, int)}. * * @return the result. Default is {@link #START_NOT_STICKY}. */ protected int getResultForOnStartCommand() { return START_NOT_STICKY; }//getResultForOnStartCommand() @Override public void onDestroy() { // Release wake lock. try { if (mWakeLock != null && mWakeLock.isHeld()) mWakeLock.release(); } catch (Throwable t) { Log.e(CLASSNAME, t.getMessage(), t); } // Cancel schedule to stop self, if any. cancelScheduleToStopSelf(); // Shutdown all tasks mThreadPoolExecutor.shutdownNow(); super.onDestroy(); }// onDestroy() /** * Gets worker queue. * * @return the worker queue. */ protected BlockingQueue<Runnable> getWorkerQueue() { return mWorkerQueue; }//getWorkerQueue() /** * Gets the instance of {@link PowerManager}. * * @return the instance of {@link PowerManager}. */ protected PowerManager getPowerManager() { return mPowerManager; }//getPowerManager() /** * Sets service state. * * @param newState new state. */ protected void setServiceState(int newState) { if (mServiceState == newState) return; mServiceState = newState; notifyServiceStateChanged(); }//setServiceState() /** * Gets service state. * * @return service state. */ protected int getServiceState() { return mServiceState; }//getServiceState() /** * Notifies all listeners that service state has changed. */ protected void notifyServiceStateChanged() { notifyServiceStateChanged(null); }//notifyServiceStateChanged() /** * Notifies listener(s) that service state has changed. * * @param listener the listener. If {@code null}, all listeners will be notified. If not {@code null}, it must be * one of existing listeners. */ protected void notifyServiceStateChanged(IWakeLockServiceEventListener listener) { final int state = mServiceState; final int count = mEventListeners.beginBroadcast(); for (int i = 0; i < count; i++) { try { IWakeLockServiceEventListener l = mEventListeners.getBroadcastItem(i); if (listener == null || listener == l) l.onStateChanged(state); if (listener == l) break; } catch (RemoteException e) { // Ignore it. RemoteCallbackList will handle this exception for us. } }// for mEventListeners.finishBroadcast(); }//notifyServiceStateChanged() /** * Will be called by {@link IWakeLockService#getBooleanValue(int)}. * * @param id the ID. * @return the value. Default implementation returns {@code false}. */ protected boolean getBooleanValue(int id) { return false; }//getBooleanValue() /** * Will be called by {@link IWakeLockService#getFloatValue(int)}. * * @param id the ID. * @return the value. Default implementation returns {@code 0}. */ protected float getFloatValue(int id) { return 0; }//getFloatValue() /** * Will be called by {@link IWakeLockService#getDoubleValue(int)}. * * @param id the ID. * @return the value. Default implementation returns {@code 0}. */ protected double getDoubleValue(int id) { return 0; }//getDoubleValue() /** * Will be called by {@link IWakeLockService#getIntValue(int)}. * * @param id the ID. * @return the value. Default implementation returns {@code 0}. */ protected int getIntValue(int id) { return 0; }//getIntValue() /** * Will be called by {@link IWakeLockService#getLongValue(int)}. * * @param id the ID. * @return the value. Default implementation returns {@code 0}. */ protected long getLongValue(int id) { return 0; }//getLongValue() /** * Will be called by {@link IWakeLockService#getCharSequenceValue(int)}. * * @param id the ID. * @return the value. Default implementation returns {@code null}. */ protected CharSequence getCharSequenceValue(int id) { return null; }//getCharSequenceValue() /** * Will be called by {@link IWakeLockService#getStringValue(int)}. * * @param id the ID. * @return the value. Default implementation returns {@code null}. */ protected String getStringValue(int id) { return null; }//getStringValue() /** * Will be called by {@link IWakeLockService#getBundleValue(int)}. * * @param id the ID. * @return the value. Default implementation returns {@code null}. */ protected Bundle getBundleValue(int id) { return null; }//getBundleValue() /** * Sends simple message to all listeners. * * @param msgId message ID. */ protected void sendSimpleMessage(int msgId) { sendSimpleMessage(msgId, null); }//sendSimpleMessage() /** * Sends simple message to all listeners. * * @param msgId message ID. * @param msg message (optional). */ protected void sendSimpleMessage(int msgId, Bundle msg) { sendSimpleMessage(msgId, msg, null); }//sendSimpleMessage() /** * Sends simple message to listener(s). * * @param msgId message ID. * @param msg message (optional). * @param listener the listener. If {@code null}, the message will be sent to all listeners. If not {@code null}, it * must be one of existing listeners. */ protected void sendSimpleMessage(int msgId, Bundle msg, IWakeLockServiceEventListener listener) { final int count = mEventListeners.beginBroadcast(); for (int i = 0; i < count; i++) { try { IWakeLockServiceEventListener l = mEventListeners.getBroadcastItem(i); if (listener == null || listener == l) l.onMessage(msgId, msg); if (listener == l) break; } catch (RemoteException e) { // Ignore it. RemoteCallbackList will handle this exception for us. } }// for mEventListeners.finishBroadcast(); }//sendSimpleMessage() /** * Executes given command. * * @param command the command. */ protected void executeCommand(Runnable command) { mThreadPoolExecutor.execute(command); }// executeCommand() /** * Submits given command. * * @param command the command. * @return the future task. */ protected Future<?> submitCommand(Runnable command) { return mThreadPoolExecutor.submit(command); }//submitCommand() /** * Schedules to stop this service. */ protected void scheduleToStopSelf() { Intent command = new Intent(ACTION_STOP_SELF, null, this, WakeLockService.this.getClass()); PendingIntent pendingIntent = PendingIntent.getService(this, 0, command, PendingIntent.FLAG_CANCEL_CURRENT); AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + MAX_IDLE_TIME, pendingIntent); }// scheduleToStopSelf() /** * Cancels schedule to stop this service. */ protected void cancelScheduleToStopSelf() { Intent command = new Intent(ACTION_STOP_SELF, null, this, WakeLockService.this.getClass()); PendingIntent pendingIntent = PendingIntent.getService(this, 0, command, PendingIntent.FLAG_CANCEL_CURRENT); AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); alarmManager.cancel(pendingIntent); }// cancelScheduleToStopSelf() /** * Executes post pending intent via {@link #EXTRA_POST_PENDING_INTENT}. This method just logs {@link * android.app.PendingIntent.CanceledException} if it raises, and ignores it. * * @param intent incoming intent from client. * @return {@code true} if there was post pending intent and it was executed successfully. {@code false} otherwise. */ protected boolean executePostPendingIntent(Intent intent) { PendingIntent pendingIntent = intent.getParcelableExtra(EXTRA_POST_PENDING_INTENT); if (pendingIntent == null) return false; try { pendingIntent.send(); return true; } catch (PendingIntent.CanceledException e) { Log.e(CLASSNAME, e.getMessage(), e); return false; } }//executePostPendingIntent() }
090d3703558d70bdb7b0d284466e780f60ca0a95
[ "Markdown", "Java", "Gradle" ]
3
Markdown
zengqiang041/WakeLockService
b7093539ea07bb3865237e7f5bc96b4d5d0b6bf8
731a28c7769f61b17f532b2be79c7aa258a7385b
refs/heads/main
<repo_name>LucasF22/qm-backend-java<file_sep>/src/br/com/qeepm/pojo/Cidade.java package br.com.qeepm.pojo; public class Cidade { private int ddd; private String nome; private int nroHabitantes; private float rendaPerCapita; private boolean capital; private String estado; private String nomePrefeito; public Cidade(int ddd, String nome, int nroHabitantes, float rendaPerCapita, boolean capital, String estado, String nomePrefeito) { this.ddd = ddd; this.nome = nome; this.nroHabitantes = nroHabitantes; this.rendaPerCapita = rendaPerCapita; this.capital = capital; this.estado = estado; this.nomePrefeito = nomePrefeito; } public Cidade() { // TODO Auto-generated constructor stub } public int getDdd() { return ddd; } public void setDdd(int ddd) { this.ddd = ddd; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public int getNroHabitantes() { return nroHabitantes; } public void setNroHabitantes(int nroHabitantes) { this.nroHabitantes = nroHabitantes; } public float getRendaPerCapita() { return rendaPerCapita; } public void setRendaPerCapita(float rendaPerCapita) { this.rendaPerCapita = rendaPerCapita; } public boolean isCapital() { return capital; } public void setCapital(boolean capital) { this.capital = capital; } public String getEstado() { return estado; } public void setEstado(String estado) { this.estado = estado; } public String getNomePrefeito() { return nomePrefeito; } public void setNomePrefeito(String nomePrefeito) { this.nomePrefeito = nomePrefeito; } @Override public String toString() { return "Cidade \nDDD = " + ddd + " | Nome = " + nome + " | Nš Habitante = " + nroHabitantes + "\nRenda-per-Capita = " + rendaPerCapita + " | Capital = " + capital+ " | Estado = "+ estado+" | Prefeito = "+nomePrefeito; } } <file_sep>/src/br/com/Piloto/Exemplo.java package br.com.Piloto; import java.io.IOException; import java.sql.SQLException; import java.util.List; import br.com.Piloto.dao.*; import br.com.Piloto.pojo.*; public class Exemplo { public static void main(String[] args) throws SQLException, IOException, InterruptedException { PilotoDAO pilotoDao = new PilotoDAO(); Piloto pilotoExemplo = new Piloto("Lucas", 1, 406.4F, 5, 10000F); pilotoDao.inserePiloto(pilotoExemplo); List<Piloto> pilotos = pilotoDao.listaPilotos(); for (Piloto piloto : pilotos) { System.out.println(piloto); } pilotoDao.removePiloto(1); pilotos = pilotoDao.listaPilotos(); for (Piloto piloto : pilotos) { System.out.println(piloto); } } } <file_sep>/src/br/com/qeepm/ProgramaPrincipal.java package br.com.qeepm; import java.sql.SQLException; import java.util.List; //import java.sql.Connection; //import java.sql.DriverManager; //import java.sql.SQLException; import java.util.Scanner; import br.com.qeepm.cidadeDAO.CidadeDAO; import br.com.qeepm.pojo.Cidade; public class ProgramaPrincipal { public static void cadastrarCidade(CidadeDAO cidadeDAO, Scanner teclado) { System.out.println("░░░░░░░░ Cadastrar Cidade ░░░░░░░░"); teclado.nextLine(); System.out.println("Digite o DDD: "); int ddd = teclado.nextInt(); System.out.println("Digite o Cidade: "); String nomeCidade = teclado.nextLine(); System.out.println("Digite o Nº de habitantes: "); int habitantes = teclado.nextInt(); System.out.println("Digite o Renda per Capita: "); float perCapita = teclado.nextFloat(); System.out.println("Digite se é Capital\nDigite true para capital e false para cidade que não é uma capital: "); boolean Capital = teclado.nextBoolean(); System.out.println("Digite o Estado (Sigla): "); String estado = teclado.next(); System.out.println("Digite o Prefeito: "); String prefeito = teclado.nextLine(); Cidade cidade = new Cidade(ddd, nomeCidade, habitantes, perCapita, Capital, estado, prefeito); try { cidadeDAO.insereCidade(cidade); System.out.println("Cidade inserida com sucesso!"); }catch(SQLException e) { System.err.println("Erro ao inserir cidade!"); System.err.println(e.getMessage()); } } public static void listarCidades(CidadeDAO cidadeDAO) { System.out.println("░░░░░░░░ Listar Cidades ░░░░░░░░"); List<Cidade> cidades = cidadeDAO.listaCidades(); for(Cidade cidade: cidades) { System.out.println(cidade); } } public static void consultarCidadeDDD(CidadeDAO cidadeDAO, Scanner teclado) { System.out.println("░░░░░░░░ Consultar Cidades por DDD░░░░░░░░"); System.out.println("Digite o DDD: "); int ddd = teclado.nextInt(); System.out.println(cidadeDAO.consultaCidade(ddd)); } public static void consultarCidadePorNome(CidadeDAO cidadeDAO, Scanner teclado) { teclado.nextLine(); System.out.println("░░░░░░░░ Consultar Cidades por Nome░░░░░░░░"); System.out.println("Consulte a Cidade: "); String nomeCidade = teclado.nextLine(); List<Cidade> cidades = cidadeDAO.listaCidadesPorTexto(nomeCidade); for(Cidade cidade : cidades) { System.out.println(cidade); } } public static void consultarCidadePorEstado(CidadeDAO cidadeDAO, Scanner teclado) { teclado.nextLine(); System.out.println("░░░░░░░░ Consultar Cidades por Nome░░░░░░░░"); System.out.println("Digite o Estado(Sigla): "); String estadoSigla = teclado.next(); List<Cidade> estado = cidadeDAO.listaCidadesPorSigla(estadoSigla); for(Cidade cidade : estado) { System.out.println(cidade); } } public static void totalCidadesPorEstado(CidadeDAO cidadeDAO, Scanner teclado) { teclado.nextLine(); System.out.println("░░░░░░░░ Total de Cidade por Estado░░░░░░░░"); System.out.println("Digite o Estado(Sigla): "); String estadoSigla = teclado.next(); int totalCidade = cidadeDAO.quantidadeCidadesPorEstado(estadoSigla); System.out.println("O total de cidades do Estado do " + estadoSigla +": "+ totalCidade); } public static void listarCapitais(CidadeDAO cidadeDAO) { System.out.println("░░░░░░░░ Capitais ░░░░░░░░"); List<Cidade> capitais = cidadeDAO.listaFiltroCapital(true); for (Cidade cidade: capitais) { System.out.println(cidade); } } public static void main (String[] args) /*throws SQLEception8*/ { CidadeDAO cidadeDAO = new CidadeDAO(); Scanner teclado = new Scanner(System.in); int opcao = 0; do { System.out.println("┌───────────────────────────────────────┐"); System.out.println("│░░░░░░░░ Gerenciador de Cidade ░░░░░░░░│"); System.out.println("│ 1 - Cadastrar Cidade │"); System.out.println("│ 2 - Listar Cidades │"); System.out.println("│ 3 - Consultar Cidade por DDD │"); System.out.println("│ 4 - Consultar Cidade por nome │"); System.out.println("│ 5 - Consultar Cidade por Estado │"); System.out.println("│ 6 - Total cidades por Estado │"); System.out.println("│ 7 - Listar capitais │"); System.out.println("│ 0 - Sair │"); System.out.println("└───────────────────────────────────────┘"); System.out.println("Digite o número da opção desejada: "); opcao = teclado.nextInt(); for (int i = 0; i < 50; ++i) { System.out.println ();} switch (opcao) { case 1:{ int fechar = 0; do { cadastrarCidade(cidadeDAO, teclado); System.out.println("Deseja finalizar a Cadastro:\n Digite 0- Fechar ou 1- Continuar Cadastrando"); fechar = teclado.nextInt(); }while(fechar != 0); System.out.println("Cadastro Fechado!"); break; } case 2:{ int fechar = 0; do { listarCidades(cidadeDAO); System.out.println("Deseja finalizar a Consulta:\n Digite 0- Fechar ou 1- Continuar Consulta"); fechar = teclado.nextInt(); }while(fechar != 0); System.out.println("Consulta Fechada!"); break; } case 3:{ int fechar = 0; do { consultarCidadeDDD(cidadeDAO, teclado); System.out.println("Deseja finalizar a Consulta:\n Digite 0- Fechar ou 1- Continuar Consulta"); fechar = teclado.nextInt(); }while(fechar != 0); System.out.println("Consulta Fechada!"); break; } case 4:{ int fechar = 0; do { consultarCidadePorNome(cidadeDAO, teclado); System.out.println("Deseja finalizar a Consulta:\n Digite 0- Fechar ou 1- Continuar Consulta"); fechar = teclado.nextInt(); }while(fechar != 0); System.out.println("Consulta Fechada!"); break; } case 5:{ int fechar = 0; do { consultarCidadePorEstado(cidadeDAO, teclado); System.out.println("Deseja finalizar a Consulta:\n Digite 0- Fechar ou 1- Continuar Consulta"); fechar = teclado.nextInt(); }while(fechar != 0); System.out.println("Consulta Fechada!"); break; } case 6:{ int fechar = 0; do { totalCidadesPorEstado(cidadeDAO, teclado); System.out.println("Deseja finalizar a Consulta:\n Digite 0- Fechar ou 1- Continuar Consulta"); fechar = teclado.nextInt(); }while(fechar != 0); System.out.println("Consulta Fechada!"); break; } case 7:{ int fechar = 0; do { listarCapitais(cidadeDAO); System.out.println("Deseja finalizar a Consulta:\n Digite 0- Fechar ou 1- Continuar Consulta"); fechar = teclado.nextInt(); }while(fechar != 0); System.out.println("Consulta Fechada!"); break; } default: System.err.println("Opção invalida digite novamente!"); break; } }while(opcao !=0); System.out.println("Programa fechado!"); teclado.close(); } } <file_sep>/src/br/com/qeepm/cidadeDAO/CidadeDAO.java package br.com.qeepm.cidadeDAO; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import br.com.qeepm.Factory.*; import br.com.qeepm.pojo.Cidade; public class CidadeDAO { private Connection conn; public CidadeDAO() { this.conn = new ConnectionFactory().getConnetion(); } public void insereCidade(Cidade Cidade) throws SQLException { String sql = "INSERT INTO cidades.cidade" + "(ddd, nome, nro_habitantes, renda_per_capita, capital, estado, nome_prefeito) " + "VALUES (?, ?, ?, ?, ?, ?, ?)"; PreparedStatement stmt = conn.prepareStatement(sql); stmt.setInt(1, Cidade.getDdd()); stmt.setString(2, Cidade.getNome()); stmt.setInt(3, Cidade.getNroHabitantes()); stmt.setFloat(4, Cidade.getRendaPerCapita()); stmt.setBoolean(5, Cidade.isCapital()); stmt.setString(6, Cidade.getEstado()); stmt.setString(7, Cidade.getNomePrefeito()); stmt.executeUpdate(); stmt.close(); } private void mapeiaLista(List<Cidade> cidades, ResultSet rs) throws SQLException { while (rs.next()) { Cidade cidade = new Cidade(); cidade.setDdd(rs.getInt("ddd")); cidade.setNome(rs.getString("nome")); cidade.setNroHabitantes(rs.getInt("nro_habitantes")); cidade.setRendaPerCapita(rs.getFloat("renda_per_capita")); cidade.setCapital(rs.getBoolean("capital")); cidade.setEstado(rs.getString("estado")); cidade.setNomePrefeito(rs.getString("nome_prefeito")); cidades.add(cidade); } } public List<Cidade> listaCidades() { List<Cidade> cidades = new ArrayList<Cidade>(); String sql = "select * from cidades.cidade"; try { PreparedStatement stmt = conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); mapeiaLista(cidades, rs); } catch (SQLException e) { System.err.println("Erro ao listar cidades"); System.err.println(e.getMessage()); } return cidades; } public Cidade consultaCidade(int ddd) { String sql = "select * from cidades.cidade " + "where ddd = ?"; try { PreparedStatement stmt = conn.prepareStatement(sql); stmt.setInt(1, ddd); ResultSet rs = stmt.executeQuery(); if (rs.next()) { Cidade cidade = new Cidade(); cidade.setDdd(rs.getInt("ddd")); cidade.setNome(rs.getString("nome")); cidade.setNroHabitantes(rs.getInt("nro_habitantes")); cidade.setRendaPerCapita(rs.getFloat("renda_per_capita")); cidade.setCapital(rs.getBoolean("capital")); cidade.setEstado(rs.getString("estado")); cidade.setNomePrefeito(rs.getString("nome_prefeito")); return cidade; } } catch (SQLException e) { System.err.println("Erro ao consultar cidade"); System.err.println(e.getMessage()); } return null; // Pesquisem sobre o Optional. } public int quantidadeCidadesPorEstado(String sigla) { String sql = "select count(*) as qtdCidades from cidades.cidade " + "where estado = ?"; try { PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, sigla); ResultSet rs = stmt.executeQuery(); rs.next(); return rs.getInt(1); } catch (SQLException e) { System.err.println("Erro ao quantificar cidades"); System.err.println(e.getMessage()); } return 0; } public List<Cidade> listaCidadesPorSigla(String sigla) { List<Cidade> cidades = new ArrayList<Cidade>(); String sql = "select * from cidades.cidade " + "where estado = ?"; try { PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, sigla); ResultSet rs = stmt.executeQuery(); mapeiaLista(cidades, rs); } catch (SQLException e) { System.err.println("Erro ao listar cidades por sigla"); System.err.println(e.getMessage()); } return cidades; } public List<Cidade> listaCidadesPorTexto(String inicio) { List<Cidade> cidades = new ArrayList<Cidade>(); String sql = "select * from cidades.cidade where nome ilike ?"; try { PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, inicio + "%"); ResultSet rs = stmt.executeQuery(); mapeiaLista(cidades, rs); } catch (SQLException e) { System.err.println("Erro ao listar cidades que comešam com: " + inicio); System.err.println(e.getMessage()); } return cidades; } public List<Cidade> listaFiltroCapital(boolean capital) { List<Cidade> cidades = new ArrayList<Cidade>(); String sql = "select * from cidades.cidade " + "where capital = ?"; PreparedStatement stmt; try { stmt = conn.prepareStatement(sql); stmt.setBoolean(1, capital); ResultSet rs = stmt.executeQuery(); mapeiaLista(cidades, rs); } catch (SQLException e) { System.err.println("Erro ao listar cidades pelo filtro de capital."); System.err.println(e.getMessage()); } return cidades; } } <file_sep>/src/br/com/Piloto/dao/PilotoDAO.java package br.com.Piloto.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import br.com.Piloto.Factory.Conection; import br.com.Piloto.pojo.*; public class PilotoDAO { private Connection conn; public PilotoDAO() { this.conn = new Conection().getConnection(); System.out.println("Conectado!"); } public boolean inserePiloto(Piloto piloto) throws SQLException { String sql = "INSERT INTO piloto" + "(nome, matricula, horas_voo, num_aeronave, salario) " + "VALUES (?, ?, ?, ?, ?)"; PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, piloto.getNome()); stmt.setInt(2, piloto.getMatricula()); stmt.setFloat(3, piloto.getHorasVoo()); stmt.setInt(4, piloto.getNumAeronave()); stmt.setFloat(5, piloto.getSalario()); stmt.executeUpdate(); stmt.close(); return true; } public List<Piloto> listaPilotos() throws SQLException { List<Piloto> pilotos = new ArrayList<Piloto>(); String sql = "SELECT * FROM piloto"; PreparedStatement stmt = conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); while (rs.next()) { Piloto piloto = new Piloto(); piloto.setMatricula(rs.getInt("matricula")); piloto.setNome(rs.getString("nome")); piloto.setHorasVoo(rs.getFloat("horas_voo")); piloto.setNumAeronave(rs.getInt("num_aeronave")); piloto.setSalario(rs.getFloat("salario")); pilotos.add(piloto); } return pilotos; } public List<Piloto> listaPilotosPorHoraDeVooMaior(Float horasVoo) throws SQLException { List<Piloto> pilotos = new ArrayList<Piloto>(); String sql = "SELECT * FROM piloto " + "WHERE horas_voo > ?"; PreparedStatement stmt = conn.prepareStatement(sql); stmt.setFloat(1, horasVoo); ResultSet rs = stmt.executeQuery(); while (rs.next()) { Piloto piloto = new Piloto(); piloto.setMatricula(rs.getInt("matricula")); piloto.setNome(rs.getString("nome")); piloto.setHorasVoo(rs.getFloat("horas_voo")); piloto.setNumAeronave(rs.getInt("num_aeronave")); piloto.setSalario(rs.getFloat("salario")); pilotos.add(piloto); } return pilotos; } public boolean removePiloto(int matricula) throws SQLException { String sql = "delete from piloto " + "where matricula = ?"; PreparedStatement stmt = conn.prepareStatement(sql); stmt.setInt(1, matricula); if (stmt.executeUpdate() > 0) { return true; } return false; } }
c26239f40f139b5b691b3b29fe1e30e56573bdcd
[ "Java" ]
5
Java
LucasF22/qm-backend-java
cc98df1564c5d7d09577ec07b4d9702e29d7d1b1
5c4d5f96aa95b12f7bef0338b61fecefb85289bd
refs/heads/master
<file_sep>// Compiled by ClojureScript 1.9.946 {:static-fns true, :optimize-constants true, :elide-asserts true} goog.provide('no.en.core'); goog.require('cljs.core'); goog.require('cljs.core.constants'); goog.require('clojure.string'); goog.require('cljs.reader'); goog.require('goog.crypt.base64'); no.en.core.port_number = new cljs.core.PersistentArrayMap(null, 7, [cljs.core.cst$kw$amqp,(5672),cljs.core.cst$kw$http,(80),cljs.core.cst$kw$https,(443),cljs.core.cst$kw$mysql,(3306),cljs.core.cst$kw$postgresql,(5432),cljs.core.cst$kw$rabbitmq,(5672),cljs.core.cst$kw$zookeeper,(2181)], null); no.en.core.url_regex = /([^:]+):\/\/(([^:]+):([^@\/]+)@)?(([^:\/]+)(:([0-9]+))?((\/[^?#]*)(\?([^#]*))?)?)(\#(.*))?/; /** * Split the string `s` by the regex `pattern`. */ no.en.core.split_by_regex = (function no$en$core$split_by_regex(s,pattern){ if(cljs.core.sequential_QMARK_(s)){ return s; } else { if(!(clojure.string.blank_QMARK_(s))){ return clojure.string.split.cljs$core$IFn$_invoke$arity$2(s,pattern); } else { return null; } } }); /** * Split the string `s` by comma. */ no.en.core.split_by_comma = (function no$en$core$split_by_comma(s){ return no.en.core.split_by_regex(s,/\s*,\s*/); }); /** * Returns `bytes` as an UTF-8 encoded string. */ no.en.core.utf8_string = (function no$en$core$utf8_string(bytes){ throw cljs.core.ex_info.cljs$core$IFn$_invoke$arity$2("utf8-string not implemented yet",bytes); }); /** * Returns `s` as a Base64 encoded string. */ no.en.core.base64_encode = (function no$en$core$base64_encode(bytes){ if(cljs.core.truth_(bytes)){ return goog.crypt.base64.encodeString(bytes,false); } else { return null; } }); /** * Returns `s` as a Base64 decoded string. */ no.en.core.base64_decode = (function no$en$core$base64_decode(s){ if(cljs.core.truth_(s)){ return goog.crypt.base64.decodeString(s,false); } else { return null; } }); /** * Removes all map entries where the value of the entry is empty. */ no.en.core.compact_map = (function no$en$core$compact_map(m){ return cljs.core.reduce.cljs$core$IFn$_invoke$arity$3((function (m__$1,k){ var v = cljs.core.get.cljs$core$IFn$_invoke$arity$2(m__$1,k); if(((v == null)) || (((cljs.core.map_QMARK_(v)) || (cljs.core.sequential_QMARK_(v))) && (cljs.core.empty_QMARK_(v)))){ return cljs.core.dissoc.cljs$core$IFn$_invoke$arity$2(m__$1,k); } else { return m__$1; } }),m,cljs.core.keys(m)); }); /** * Returns `s` as an URL encoded string. */ no.en.core.url_encode = (function no$en$core$url_encode(var_args){ var args__8835__auto__ = []; var len__8828__auto___13664 = arguments.length; var i__8829__auto___13665 = (0); while(true){ if((i__8829__auto___13665 < len__8828__auto___13664)){ args__8835__auto__.push((arguments[i__8829__auto___13665])); var G__13666 = (i__8829__auto___13665 + (1)); i__8829__auto___13665 = G__13666; continue; } else { } break; } var argseq__8836__auto__ = ((((1) < args__8835__auto__.length))?(new cljs.core.IndexedSeq(args__8835__auto__.slice((1)),(0),null)):null); return no.en.core.url_encode.cljs$core$IFn$_invoke$arity$variadic((arguments[(0)]),argseq__8836__auto__); }); no.en.core.url_encode.cljs$core$IFn$_invoke$arity$variadic = (function (s,p__13659){ var vec__13660 = p__13659; var encoding = cljs.core.nth.cljs$core$IFn$_invoke$arity$3(vec__13660,(0),null); if(cljs.core.truth_(s)){ return clojure.string.replace((function (){var G__13663 = [cljs.core.str.cljs$core$IFn$_invoke$arity$1(s)].join(''); return encodeURIComponent(G__13663); })(),"*","%2A"); } else { return null; } }); no.en.core.url_encode.cljs$lang$maxFixedArity = (1); no.en.core.url_encode.cljs$lang$applyTo = (function (seq13657){ var G__13658 = cljs.core.first(seq13657); var seq13657__$1 = cljs.core.next(seq13657); return no.en.core.url_encode.cljs$core$IFn$_invoke$arity$variadic(G__13658,seq13657__$1); }); /** * Returns `s` as an URL decoded string. */ no.en.core.url_decode = (function no$en$core$url_decode(var_args){ var args__8835__auto__ = []; var len__8828__auto___13673 = arguments.length; var i__8829__auto___13674 = (0); while(true){ if((i__8829__auto___13674 < len__8828__auto___13673)){ args__8835__auto__.push((arguments[i__8829__auto___13674])); var G__13675 = (i__8829__auto___13674 + (1)); i__8829__auto___13674 = G__13675; continue; } else { } break; } var argseq__8836__auto__ = ((((1) < args__8835__auto__.length))?(new cljs.core.IndexedSeq(args__8835__auto__.slice((1)),(0),null)):null); return no.en.core.url_decode.cljs$core$IFn$_invoke$arity$variadic((arguments[(0)]),argseq__8836__auto__); }); no.en.core.url_decode.cljs$core$IFn$_invoke$arity$variadic = (function (s,p__13669){ var vec__13670 = p__13669; var encoding = cljs.core.nth.cljs$core$IFn$_invoke$arity$3(vec__13670,(0),null); if(cljs.core.truth_(s)){ return decodeURIComponent(s); } else { return null; } }); no.en.core.url_decode.cljs$lang$maxFixedArity = (1); no.en.core.url_decode.cljs$lang$applyTo = (function (seq13667){ var G__13668 = cljs.core.first(seq13667); var seq13667__$1 = cljs.core.next(seq13667); return no.en.core.url_decode.cljs$core$IFn$_invoke$arity$variadic(G__13668,seq13667__$1); }); no.en.core.pow = (function no$en$core$pow(n,x){ return Math.pow(n,x); }); no.en.core.byte_scale = cljs.core.PersistentHashMap.fromArrays(["T","K","G","M","Y","Z","E","B","P"],[no.en.core.pow((1024),(4)),no.en.core.pow((1024),(1)),no.en.core.pow((1024),(3)),no.en.core.pow((1024),(2)),no.en.core.pow((1024),(8)),no.en.core.pow((1024),(7)),no.en.core.pow((1024),(6)),no.en.core.pow((1024),(0)),no.en.core.pow((1024),(5))]); no.en.core.apply_unit = (function no$en$core$apply_unit(number,unit){ if(typeof unit === 'string'){ var G__13676 = clojure.string.upper_case(unit); switch (G__13676) { default: var G__13677 = unit; switch (G__13677) { case "M": return (number * (1000000)); break; case "B": return (number * (1000000000)); break; default: throw (new Error(["No matching clause: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(G__13677)].join(''))); } } } else { return number; } }); no.en.core.parse_number = (function no$en$core$parse_number(s,parse_fn){ var temp__4655__auto__ = cljs.core.re_matches(/\s*([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)(M|B)?.*/,[cljs.core.str.cljs$core$IFn$_invoke$arity$1(s)].join('')); if(cljs.core.truth_(temp__4655__auto__)){ var matches = temp__4655__auto__; var number = (function (){var G__13680 = cljs.core.nth.cljs$core$IFn$_invoke$arity$2(matches,(1)); return (parse_fn.cljs$core$IFn$_invoke$arity$1 ? parse_fn.cljs$core$IFn$_invoke$arity$1(G__13680) : parse_fn.call(null,G__13680)); })(); var unit = cljs.core.nth.cljs$core$IFn$_invoke$arity$2(matches,(3)); if(cljs.core.not(isNaN(number))){ return no.en.core.apply_unit(number,unit); } else { return null; } } else { return null; } }); no.en.core.parse_bytes = (function no$en$core$parse_bytes(s){ var temp__4655__auto__ = cljs.core.re_matches(/\s*([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)(B|K|M|G|T|P|E|Z|Y)?.*/,[cljs.core.str.cljs$core$IFn$_invoke$arity$1(s)].join('')); if(cljs.core.truth_(temp__4655__auto__)){ var matches = temp__4655__auto__; var number = cljs.reader.read_string.cljs$core$IFn$_invoke$arity$1(cljs.core.nth.cljs$core$IFn$_invoke$arity$2(matches,(1))); var unit = cljs.core.nth.cljs$core$IFn$_invoke$arity$2(matches,(3)); return cljs.core.long$((cljs.core.long$(cljs.reader.read_string.cljs$core$IFn$_invoke$arity$1([cljs.core.str.cljs$core$IFn$_invoke$arity$1(cljs.core.nth.cljs$core$IFn$_invoke$arity$2(matches,(1)))].join(''))) * cljs.core.get.cljs$core$IFn$_invoke$arity$3(no.en.core.byte_scale,clojure.string.upper_case((function (){var or__7668__auto__ = unit; if(cljs.core.truth_(or__7668__auto__)){ return or__7668__auto__; } else { return ""; } })()),(1)))); } else { return null; } }); /** * Parse `s` as a integer number. */ no.en.core.parse_integer = (function no$en$core$parse_integer(s){ return no.en.core.parse_number(s,(function (p1__13681_SHARP_){ return parseInt(p1__13681_SHARP_); })); }); /** * Parse `s` as a long number. */ no.en.core.parse_long = (function no$en$core$parse_long(s){ return no.en.core.parse_number(s,(function (p1__13682_SHARP_){ return parseInt(p1__13682_SHARP_); })); }); /** * Parse `s` as a double number. */ no.en.core.parse_double = (function no$en$core$parse_double(s){ return no.en.core.parse_number(s,(function (p1__13683_SHARP_){ return parseFloat(p1__13683_SHARP_); })); }); /** * Parse `s` as a float number. */ no.en.core.parse_float = (function no$en$core$parse_float(s){ return no.en.core.parse_number(s,(function (p1__13684_SHARP_){ return parseFloat(p1__13684_SHARP_); })); }); /** * Format the map `m` into a query parameter string. */ no.en.core.format_query_params = (function no$en$core$format_query_params(m){ var params = clojure.string.join.cljs$core$IFn$_invoke$arity$2("&",cljs.core.map.cljs$core$IFn$_invoke$arity$2((function (p1__13687_SHARP_){ return clojure.string.join.cljs$core$IFn$_invoke$arity$2("=",p1__13687_SHARP_); }),cljs.core.map.cljs$core$IFn$_invoke$arity$2((function (p1__13686_SHARP_){ return (new cljs.core.PersistentVector(null,2,(5),cljs.core.PersistentVector.EMPTY_NODE,[no.en.core.url_encode(cljs.core.name(cljs.core.first(p1__13686_SHARP_))),no.en.core.url_encode(cljs.core.second(p1__13686_SHARP_))],null)); }),cljs.core.remove.cljs$core$IFn$_invoke$arity$2((function (p1__13685_SHARP_){ return clojure.string.blank_QMARK_([cljs.core.str.cljs$core$IFn$_invoke$arity$1(cljs.core.second(p1__13685_SHARP_))].join('')); }),cljs.core.sort_by.cljs$core$IFn$_invoke$arity$2(cljs.core.first,cljs.core.seq(m)))))); if(!(clojure.string.blank_QMARK_(params))){ return params; } else { return null; } }); /** * Format the Ring map as an url. */ no.en.core.format_url = (function no$en$core$format_url(m){ if(!(cljs.core.empty_QMARK_(m))){ var query_params = cljs.core.cst$kw$query_DASH_params.cljs$core$IFn$_invoke$arity$1(m); return [cljs.core.str.cljs$core$IFn$_invoke$arity$1((cljs.core.truth_(cljs.core.cst$kw$scheme.cljs$core$IFn$_invoke$arity$1(m))?[cljs.core.str.cljs$core$IFn$_invoke$arity$1(cljs.core.name(cljs.core.cst$kw$scheme.cljs$core$IFn$_invoke$arity$1(m))),"://"].join(''):null)),cljs.core.str.cljs$core$IFn$_invoke$arity$1((function (){var map__13688 = m; var map__13688__$1 = ((((!((map__13688 == null)))?((((map__13688.cljs$lang$protocol_mask$partition0$ & (64))) || ((cljs.core.PROTOCOL_SENTINEL === map__13688.cljs$core$ISeq$)))?true:false):false))?cljs.core.apply.cljs$core$IFn$_invoke$arity$2(cljs.core.hash_map,map__13688):map__13688); var username = cljs.core.get.cljs$core$IFn$_invoke$arity$2(map__13688__$1,cljs.core.cst$kw$username); var password = cljs.core.get.cljs$core$IFn$_invoke$arity$2(map__13688__$1,cljs.core.cst$kw$password); if(cljs.core.truth_(username)){ return [cljs.core.str.cljs$core$IFn$_invoke$arity$1(username),cljs.core.str.cljs$core$IFn$_invoke$arity$1((cljs.core.truth_(password)?[":",cljs.core.str.cljs$core$IFn$_invoke$arity$1(password)].join(''):null)),"@"].join(''); } else { return null; } })()),cljs.core.str.cljs$core$IFn$_invoke$arity$1(cljs.core.cst$kw$server_DASH_name.cljs$core$IFn$_invoke$arity$1(m)),cljs.core.str.cljs$core$IFn$_invoke$arity$1((function (){var temp__4655__auto__ = cljs.core.cst$kw$server_DASH_port.cljs$core$IFn$_invoke$arity$1(m); if(cljs.core.truth_(temp__4655__auto__)){ var port = temp__4655__auto__; if(!(cljs.core._EQ_.cljs$core$IFn$_invoke$arity$2(port,(function (){var G__13690 = cljs.core.cst$kw$scheme.cljs$core$IFn$_invoke$arity$1(m); return (no.en.core.port_number.cljs$core$IFn$_invoke$arity$1 ? no.en.core.port_number.cljs$core$IFn$_invoke$arity$1(G__13690) : no.en.core.port_number.call(null,G__13690)); })()))){ return [":",cljs.core.str.cljs$core$IFn$_invoke$arity$1(port)].join(''); } else { return null; } } else { return null; } })()),cljs.core.str.cljs$core$IFn$_invoke$arity$1(((((cljs.core.cst$kw$uri.cljs$core$IFn$_invoke$arity$1(m) == null)) && (!(cljs.core.empty_QMARK_(query_params))))?"/":cljs.core.cst$kw$uri.cljs$core$IFn$_invoke$arity$1(m))),cljs.core.str.cljs$core$IFn$_invoke$arity$1(((!(cljs.core.empty_QMARK_(query_params)))?["?",cljs.core.str.cljs$core$IFn$_invoke$arity$1(no.en.core.format_query_params(query_params))].join(''):null)),cljs.core.str.cljs$core$IFn$_invoke$arity$1(((!(clojure.string.blank_QMARK_(cljs.core.cst$kw$fragment.cljs$core$IFn$_invoke$arity$1(m))))?["#",cljs.core.str.cljs$core$IFn$_invoke$arity$1(cljs.core.cst$kw$fragment.cljs$core$IFn$_invoke$arity$1(m))].join(''):null))].join(''); } else { return null; } }); /** * Return the formatted `url` without password as a string. */ no.en.core.public_url = (function no$en$core$public_url(url){ return no.en.core.format_url(cljs.core.dissoc.cljs$core$IFn$_invoke$arity$2(url,cljs.core.cst$kw$password)); }); /** * Parse `s` as a percentage. */ no.en.core.parse_percent = (function no$en$core$parse_percent(s){ return no.en.core.parse_double(clojure.string.replace(s,"%","")); }); /** * Quote the special characters in `s` that are used in regular expressions. */ no.en.core.pattern_quote = (function no$en$core$pattern_quote(s){ return clojure.string.replace(cljs.core.name(s),/([\[\]\^\$\|\(\)\\\+\*\?\{\}\=\!.])/,"\\\\$1"); }); /** * Returns the first string that separates the components in `s`. */ no.en.core.separator = (function no$en$core$separator(s){ var temp__4655__auto__ = cljs.core.re_matches(/([a-z0-9_-]+)([^a-z0-9_-]+).*/i,s); if(cljs.core.truth_(temp__4655__auto__)){ var matches = temp__4655__auto__; return cljs.core.nth.cljs$core$IFn$_invoke$arity$2(matches,(2)); } else { return null; } }); /** * Parse the query parameter string `s` and return a map. */ no.en.core.parse_query_params = (function no$en$core$parse_query_params(s){ if(cljs.core.truth_(s)){ return cljs.core.apply.cljs$core$IFn$_invoke$arity$2(cljs.core.hash_map,cljs.core.mapcat.cljs$core$IFn$_invoke$arity$variadic((function (p1__13693_SHARP_){ return (new cljs.core.PersistentVector(null,2,(5),cljs.core.PersistentVector.EMPTY_NODE,[cljs.core.keyword.cljs$core$IFn$_invoke$arity$1(no.en.core.url_decode(cljs.core.first(p1__13693_SHARP_))),no.en.core.url_decode(cljs.core.second(p1__13693_SHARP_))],null)); }),cljs.core.prim_seq.cljs$core$IFn$_invoke$arity$2([cljs.core.filter.cljs$core$IFn$_invoke$arity$2((function (p1__13692_SHARP_){ return cljs.core._EQ_.cljs$core$IFn$_invoke$arity$2((2),cljs.core.count(p1__13692_SHARP_)); }),cljs.core.map.cljs$core$IFn$_invoke$arity$2((function (p1__13691_SHARP_){ return clojure.string.split.cljs$core$IFn$_invoke$arity$2(p1__13691_SHARP_,/=/); }),clojure.string.split.cljs$core$IFn$_invoke$arity$2([cljs.core.str.cljs$core$IFn$_invoke$arity$1(s)].join(''),/&/)))], 0))); } else { return null; } }); /** * Parse the url `s` and return a Ring compatible map. */ no.en.core.parse_url = (function no$en$core$parse_url(s){ var temp__4655__auto__ = cljs.core.re_matches(no.en.core.url_regex,[cljs.core.str.cljs$core$IFn$_invoke$arity$1(s)].join('')); if(cljs.core.truth_(temp__4655__auto__)){ var matches = temp__4655__auto__; var scheme = cljs.core.keyword.cljs$core$IFn$_invoke$arity$1(cljs.core.nth.cljs$core$IFn$_invoke$arity$2(matches,(1))); return no.en.core.compact_map(cljs.core.PersistentHashMap.fromArrays([cljs.core.cst$kw$password,cljs.core.cst$kw$fragment,cljs.core.cst$kw$username,cljs.core.cst$kw$server_DASH_port,cljs.core.cst$kw$query_DASH_params,cljs.core.cst$kw$uri,cljs.core.cst$kw$server_DASH_name,cljs.core.cst$kw$query_DASH_string,cljs.core.cst$kw$scheme],[cljs.core.nth.cljs$core$IFn$_invoke$arity$2(matches,(4)),cljs.core.nth.cljs$core$IFn$_invoke$arity$2(matches,(14)),cljs.core.nth.cljs$core$IFn$_invoke$arity$2(matches,(3)),(function (){var or__7668__auto__ = no.en.core.parse_integer(cljs.core.nth.cljs$core$IFn$_invoke$arity$2(matches,(8))); if(cljs.core.truth_(or__7668__auto__)){ return or__7668__auto__; } else { return (no.en.core.port_number.cljs$core$IFn$_invoke$arity$1 ? no.en.core.port_number.cljs$core$IFn$_invoke$arity$1(scheme) : no.en.core.port_number.call(null,scheme)); } })(),no.en.core.parse_query_params(cljs.core.nth.cljs$core$IFn$_invoke$arity$2(matches,(12))),cljs.core.nth.cljs$core$IFn$_invoke$arity$2(matches,(10)),cljs.core.nth.cljs$core$IFn$_invoke$arity$2(matches,(6)),cljs.core.nth.cljs$core$IFn$_invoke$arity$2(matches,(12)),scheme])); } else { return null; } }); var ret__8868__auto___13698 = (function (){ no.en.core.prog1 = (function no$en$core$prog1(var_args){ var args__8835__auto__ = []; var len__8828__auto___13699 = arguments.length; var i__8829__auto___13700 = (0); while(true){ if((i__8829__auto___13700 < len__8828__auto___13699)){ args__8835__auto__.push((arguments[i__8829__auto___13700])); var G__13701 = (i__8829__auto___13700 + (1)); i__8829__auto___13700 = G__13701; continue; } else { } break; } var argseq__8836__auto__ = ((((2) < args__8835__auto__.length))?(new cljs.core.IndexedSeq(args__8835__auto__.slice((2)),(0),null)):null); return no.en.core.prog1.cljs$core$IFn$_invoke$arity$variadic((arguments[(0)]),(arguments[(1)]),argseq__8836__auto__); }); no.en.core.prog1.cljs$core$IFn$_invoke$arity$variadic = (function (_AMPERSAND_form,_AMPERSAND_env,body){ return cljs.core.sequence.cljs$core$IFn$_invoke$arity$1(cljs.core.seq(cljs.core.concat.cljs$core$IFn$_invoke$arity$variadic(cljs.core._conj(cljs.core.List.EMPTY,cljs.core.cst$sym$cljs$core_SLASH_let),(function (){var x__8530__auto__ = cljs.core.vec(cljs.core.sequence.cljs$core$IFn$_invoke$arity$1(cljs.core.seq(cljs.core.concat.cljs$core$IFn$_invoke$arity$2(cljs.core._conj(cljs.core.List.EMPTY,cljs.core.cst$sym$result__13694__auto__),(function (){var x__8530__auto__ = cljs.core.first(body); return cljs.core._conj(cljs.core.List.EMPTY,x__8530__auto__); })())))); return cljs.core._conj(cljs.core.List.EMPTY,x__8530__auto__); })(),cljs.core.prim_seq.cljs$core$IFn$_invoke$arity$2([cljs.core.rest(body),cljs.core._conj(cljs.core.List.EMPTY,cljs.core.cst$sym$result__13694__auto__)], 0)))); }); no.en.core.prog1.cljs$lang$maxFixedArity = (2); no.en.core.prog1.cljs$lang$applyTo = (function (seq13695){ var G__13696 = cljs.core.first(seq13695); var seq13695__$1 = cljs.core.next(seq13695); var G__13697 = cljs.core.first(seq13695__$1); var seq13695__$2 = cljs.core.next(seq13695__$1); return no.en.core.prog1.cljs$core$IFn$_invoke$arity$variadic(G__13696,G__13697,seq13695__$2); }); return null; })() ; no.en.core.prog1.cljs$lang$macro = true; /** * Executes thunk. If an exception is thrown, will retry. At most n retries * are done. If still some exception is thrown it is bubbled upwards in * the call chain. */ no.en.core.with_retries_STAR_ = (function no$en$core$with_retries_STAR_(n,thunk){ var n__$1 = n; while(true){ var temp__4655__auto__ = (function (){try{return new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [(thunk.cljs$core$IFn$_invoke$arity$0 ? thunk.cljs$core$IFn$_invoke$arity$0() : thunk.call(null))], null); }catch (e13702){if((e13702 instanceof Error)){ var e = e13702; if((n__$1 === (0))){ throw e; } else { return null; } } else { throw e13702; } }})(); if(cljs.core.truth_(temp__4655__auto__)){ var result = temp__4655__auto__; return (result.cljs$core$IFn$_invoke$arity$1 ? result.cljs$core$IFn$_invoke$arity$1((0)) : result.call(null,(0))); } else { var G__13703 = (n__$1 - (1)); n__$1 = G__13703; continue; } break; } }); var ret__8868__auto___13708 = (function (){ /** * Executes body. If an exception is thrown, will retry. At most n retries * are done. If still some exception is thrown it is bubbled upwards in * the call chain. */ no.en.core.with_retries = (function no$en$core$with_retries(var_args){ var args__8835__auto__ = []; var len__8828__auto___13709 = arguments.length; var i__8829__auto___13710 = (0); while(true){ if((i__8829__auto___13710 < len__8828__auto___13709)){ args__8835__auto__.push((arguments[i__8829__auto___13710])); var G__13711 = (i__8829__auto___13710 + (1)); i__8829__auto___13710 = G__13711; continue; } else { } break; } var argseq__8836__auto__ = ((((3) < args__8835__auto__.length))?(new cljs.core.IndexedSeq(args__8835__auto__.slice((3)),(0),null)):null); return no.en.core.with_retries.cljs$core$IFn$_invoke$arity$variadic((arguments[(0)]),(arguments[(1)]),(arguments[(2)]),argseq__8836__auto__); }); no.en.core.with_retries.cljs$core$IFn$_invoke$arity$variadic = (function (_AMPERSAND_form,_AMPERSAND_env,n,body){ return cljs.core.sequence.cljs$core$IFn$_invoke$arity$1(cljs.core.seq(cljs.core.concat.cljs$core$IFn$_invoke$arity$variadic(cljs.core._conj(cljs.core.List.EMPTY,cljs.core.cst$sym$no$en$core_SLASH_with_DASH_retries_STAR_),(function (){var x__8530__auto__ = n; return cljs.core._conj(cljs.core.List.EMPTY,x__8530__auto__); })(),cljs.core.prim_seq.cljs$core$IFn$_invoke$arity$2([(function (){var x__8530__auto__ = cljs.core.sequence.cljs$core$IFn$_invoke$arity$1(cljs.core.seq(cljs.core.concat.cljs$core$IFn$_invoke$arity$variadic(cljs.core._conj(cljs.core.List.EMPTY,cljs.core.cst$sym$cljs$core_SLASH_fn),(function (){var x__8530__auto__ = cljs.core.vec(cljs.core.sequence.cljs$core$IFn$_invoke$arity$1(cljs.core.seq(cljs.core.concat.cljs$core$IFn$_invoke$arity$0()))); return cljs.core._conj(cljs.core.List.EMPTY,x__8530__auto__); })(),cljs.core.prim_seq.cljs$core$IFn$_invoke$arity$2([body], 0)))); return cljs.core._conj(cljs.core.List.EMPTY,x__8530__auto__); })()], 0)))); }); no.en.core.with_retries.cljs$lang$maxFixedArity = (3); no.en.core.with_retries.cljs$lang$applyTo = (function (seq13704){ var G__13705 = cljs.core.first(seq13704); var seq13704__$1 = cljs.core.next(seq13704); var G__13706 = cljs.core.first(seq13704__$1); var seq13704__$2 = cljs.core.next(seq13704__$1); var G__13707 = cljs.core.first(seq13704__$2); var seq13704__$3 = cljs.core.next(seq13704__$2); return no.en.core.with_retries.cljs$core$IFn$_invoke$arity$variadic(G__13705,G__13706,G__13707,seq13704__$3); }); return null; })() ; no.en.core.with_retries.cljs$lang$macro = true; no.en.core.editable_QMARK_ = (function no$en$core$editable_QMARK_(coll){ if(!((coll == null))){ if((false) || ((cljs.core.PROTOCOL_SENTINEL === coll.cljs$core$IEditableCollection$))){ return true; } else { if((!coll.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_(cljs.core.IEditableCollection,coll); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_(cljs.core.IEditableCollection,coll); } }); no.en.core.reduce_map = (function no$en$core$reduce_map(f,coll){ if(cljs.core.truth_(no.en.core.editable_QMARK_(coll))){ return cljs.core.persistent_BANG_(cljs.core.reduce_kv((f.cljs$core$IFn$_invoke$arity$1 ? f.cljs$core$IFn$_invoke$arity$1(cljs.core.assoc_BANG_) : f.call(null,cljs.core.assoc_BANG_)),cljs.core.transient$(cljs.core.empty(coll)),coll)); } else { return cljs.core.reduce_kv((f.cljs$core$IFn$_invoke$arity$1 ? f.cljs$core$IFn$_invoke$arity$1(cljs.core.assoc) : f.call(null,cljs.core.assoc)),cljs.core.empty(coll),coll); } }); /** * Maps a function over the keys of an associative collection. */ no.en.core.map_keys = (function no$en$core$map_keys(f,coll){ return no.en.core.reduce_map((function (xf){ return (function (m,k,v){ var G__13713 = m; var G__13714 = (f.cljs$core$IFn$_invoke$arity$1 ? f.cljs$core$IFn$_invoke$arity$1(k) : f.call(null,k)); var G__13715 = v; return (xf.cljs$core$IFn$_invoke$arity$3 ? xf.cljs$core$IFn$_invoke$arity$3(G__13713,G__13714,G__13715) : xf.call(null,G__13713,G__13714,G__13715)); }); }),coll); }); /** * Maps a function over the values of an associative collection. */ no.en.core.map_vals = (function no$en$core$map_vals(f,coll){ return no.en.core.reduce_map((function (xf){ return (function (m,k,v){ var G__13716 = m; var G__13717 = k; var G__13718 = (f.cljs$core$IFn$_invoke$arity$1 ? f.cljs$core$IFn$_invoke$arity$1(v) : f.call(null,v)); return (xf.cljs$core$IFn$_invoke$arity$3 ? xf.cljs$core$IFn$_invoke$arity$3(G__13716,G__13717,G__13718) : xf.call(null,G__13716,G__13717,G__13718)); }); }),coll); }); /** * Like merge, but merges maps recursively. */ no.en.core.deep_merge = (function no$en$core$deep_merge(var_args){ var args__8835__auto__ = []; var len__8828__auto___13720 = arguments.length; var i__8829__auto___13721 = (0); while(true){ if((i__8829__auto___13721 < len__8828__auto___13720)){ args__8835__auto__.push((arguments[i__8829__auto___13721])); var G__13722 = (i__8829__auto___13721 + (1)); i__8829__auto___13721 = G__13722; continue; } else { } break; } var argseq__8836__auto__ = ((((0) < args__8835__auto__.length))?(new cljs.core.IndexedSeq(args__8835__auto__.slice((0)),(0),null)):null); return no.en.core.deep_merge.cljs$core$IFn$_invoke$arity$variadic(argseq__8836__auto__); }); no.en.core.deep_merge.cljs$core$IFn$_invoke$arity$variadic = (function (maps){ if(cljs.core.every_QMARK_(cljs.core.map_QMARK_,maps)){ return cljs.core.apply.cljs$core$IFn$_invoke$arity$3(cljs.core.merge_with,no.en.core.deep_merge,maps); } else { return cljs.core.last(maps); } }); no.en.core.deep_merge.cljs$lang$maxFixedArity = (0); no.en.core.deep_merge.cljs$lang$applyTo = (function (seq13719){ return no.en.core.deep_merge.cljs$core$IFn$_invoke$arity$variadic(cljs.core.seq(seq13719)); }); /** * Like merge-with, but merges maps recursively, applying the given fn * only when there's a non-map at a particular level. */ no.en.core.deep_merge_with = (function no$en$core$deep_merge_with(var_args){ var args__8835__auto__ = []; var len__8828__auto___13725 = arguments.length; var i__8829__auto___13726 = (0); while(true){ if((i__8829__auto___13726 < len__8828__auto___13725)){ args__8835__auto__.push((arguments[i__8829__auto___13726])); var G__13727 = (i__8829__auto___13726 + (1)); i__8829__auto___13726 = G__13727; continue; } else { } break; } var argseq__8836__auto__ = ((((1) < args__8835__auto__.length))?(new cljs.core.IndexedSeq(args__8835__auto__.slice((1)),(0),null)):null); return no.en.core.deep_merge_with.cljs$core$IFn$_invoke$arity$variadic((arguments[(0)]),argseq__8836__auto__); }); no.en.core.deep_merge_with.cljs$core$IFn$_invoke$arity$variadic = (function (f,maps){ return cljs.core.apply.cljs$core$IFn$_invoke$arity$2((function() { var no$en$core$m__delegate = function (maps__$1){ if(cljs.core.every_QMARK_(cljs.core.map_QMARK_,maps__$1)){ return cljs.core.apply.cljs$core$IFn$_invoke$arity$3(cljs.core.merge_with,no$en$core$m,maps__$1); } else { return cljs.core.apply.cljs$core$IFn$_invoke$arity$2(f,maps__$1); } }; var no$en$core$m = function (var_args){ var maps__$1 = null; if (arguments.length > 0) { var G__13728__i = 0, G__13728__a = new Array(arguments.length - 0); while (G__13728__i < G__13728__a.length) {G__13728__a[G__13728__i] = arguments[G__13728__i + 0]; ++G__13728__i;} maps__$1 = new cljs.core.IndexedSeq(G__13728__a,0,null); } return no$en$core$m__delegate.call(this,maps__$1);}; no$en$core$m.cljs$lang$maxFixedArity = 0; no$en$core$m.cljs$lang$applyTo = (function (arglist__13729){ var maps__$1 = cljs.core.seq(arglist__13729); return no$en$core$m__delegate(maps__$1); }); no$en$core$m.cljs$core$IFn$_invoke$arity$variadic = no$en$core$m__delegate; return no$en$core$m; })() ,maps); }); no.en.core.deep_merge_with.cljs$lang$maxFixedArity = (1); no.en.core.deep_merge_with.cljs$lang$applyTo = (function (seq13723){ var G__13724 = cljs.core.first(seq13723); var seq13723__$1 = cljs.core.next(seq13723); return no.en.core.deep_merge_with.cljs$core$IFn$_invoke$arity$variadic(G__13724,seq13723__$1); }); <file_sep>// Compiled by ClojureScript 1.9.946 {:static-fns true, :optimize-constants true, :elide-asserts true} goog.provide('reagent.impl.template'); goog.require('cljs.core'); goog.require('cljs.core.constants'); goog.require('clojure.string'); goog.require('clojure.walk'); goog.require('reagent.impl.util'); goog.require('reagent.impl.component'); goog.require('reagent.impl.batching'); goog.require('reagent.ratom'); goog.require('reagent.interop'); goog.require('reagent.debug'); /** * Regular expression that parses a CSS-style id and class * from a tag name. */ reagent.impl.template.re_tag = /([^\s\.#]+)(?:#([^\s\.#]+))?(?:\.([^\s#]+))?/; /** * @constructor */ reagent.impl.template.NativeWrapper = (function (){ }); reagent.impl.template.NativeWrapper.getBasis = (function (){ return cljs.core.PersistentVector.EMPTY; }); reagent.impl.template.NativeWrapper.cljs$lang$type = true; reagent.impl.template.NativeWrapper.cljs$lang$ctorStr = "reagent.impl.template/NativeWrapper"; reagent.impl.template.NativeWrapper.cljs$lang$ctorPrWriter = (function (this__8293__auto__,writer__8294__auto__,opt__8295__auto__){ return cljs.core._write(writer__8294__auto__,"reagent.impl.template/NativeWrapper"); }); reagent.impl.template.__GT_NativeWrapper = (function reagent$impl$template$__GT_NativeWrapper(){ return (new reagent.impl.template.NativeWrapper()); }); reagent.impl.template.named_QMARK_ = (function reagent$impl$template$named_QMARK_(x){ return ((x instanceof cljs.core.Keyword)) || ((x instanceof cljs.core.Symbol)); }); reagent.impl.template.hiccup_tag_QMARK_ = (function reagent$impl$template$hiccup_tag_QMARK_(x){ return (reagent.impl.template.named_QMARK_(x)) || (typeof x === 'string'); }); reagent.impl.template.valid_tag_QMARK_ = (function reagent$impl$template$valid_tag_QMARK_(x){ return (reagent.impl.template.hiccup_tag_QMARK_(x)) || (cljs.core.ifn_QMARK_(x)) || ((x instanceof reagent.impl.template.NativeWrapper)); }); reagent.impl.template.prop_name_cache = ({"class": "className", "for": "htmlFor", "charset": "charSet"}); reagent.impl.template.cache_get = (function reagent$impl$template$cache_get(o,k){ if(o.hasOwnProperty(k)){ return (o[k]); } else { return null; } }); reagent.impl.template.cached_prop_name = (function reagent$impl$template$cached_prop_name(k){ if(reagent.impl.template.named_QMARK_(k)){ var temp__4659__auto__ = reagent.impl.template.cache_get(reagent.impl.template.prop_name_cache,cljs.core.name(k)); if((temp__4659__auto__ == null)){ return (reagent.impl.template.prop_name_cache[cljs.core.name(k)] = reagent.impl.util.dash_to_camel(k)); } else { var k_SINGLEQUOTE_ = temp__4659__auto__; return k_SINGLEQUOTE_; } } else { return k; } }); reagent.impl.template.js_val_QMARK_ = (function reagent$impl$template$js_val_QMARK_(x){ return !(("object" === goog.typeOf(x))); }); reagent.impl.template.kv_conv = (function reagent$impl$template$kv_conv(o,k,v){ var G__17731 = o; (G__17731[reagent.impl.template.cached_prop_name(k)] = (reagent.impl.template.convert_prop_value.cljs$core$IFn$_invoke$arity$1 ? reagent.impl.template.convert_prop_value.cljs$core$IFn$_invoke$arity$1(v) : reagent.impl.template.convert_prop_value.call(null,v))); return G__17731; }); reagent.impl.template.convert_prop_value = (function reagent$impl$template$convert_prop_value(x){ if(reagent.impl.template.js_val_QMARK_(x)){ return x; } else { if(reagent.impl.template.named_QMARK_(x)){ return cljs.core.name(x); } else { if(cljs.core.map_QMARK_(x)){ return cljs.core.reduce_kv(reagent.impl.template.kv_conv,({}),x); } else { if(cljs.core.coll_QMARK_(x)){ return cljs.core.clj__GT_js(x); } else { if(cljs.core.ifn_QMARK_(x)){ return (function() { var G__17732__delegate = function (args){ return cljs.core.apply.cljs$core$IFn$_invoke$arity$2(x,args); }; var G__17732 = function (var_args){ var args = null; if (arguments.length > 0) { var G__17733__i = 0, G__17733__a = new Array(arguments.length - 0); while (G__17733__i < G__17733__a.length) {G__17733__a[G__17733__i] = arguments[G__17733__i + 0]; ++G__17733__i;} args = new cljs.core.IndexedSeq(G__17733__a,0,null); } return G__17732__delegate.call(this,args);}; G__17732.cljs$lang$maxFixedArity = 0; G__17732.cljs$lang$applyTo = (function (arglist__17734){ var args = cljs.core.seq(arglist__17734); return G__17732__delegate(args); }); G__17732.cljs$core$IFn$_invoke$arity$variadic = G__17732__delegate; return G__17732; })() ; } else { return cljs.core.clj__GT_js(x); } } } } } }); reagent.impl.template.oset = (function reagent$impl$template$oset(o,k,v){ var G__17735 = (((o == null))?({}):o); (G__17735[k] = v); return G__17735; }); reagent.impl.template.oget = (function reagent$impl$template$oget(o,k){ if((o == null)){ return null; } else { return (o[k]); } }); reagent.impl.template.set_id_class = (function reagent$impl$template$set_id_class(p,id_class){ var id = (id_class["id"]); var p__$1 = (((!((id == null))) && ((reagent.impl.template.oget(p,"id") == null)))?reagent.impl.template.oset(p,"id",id):p); var temp__4659__auto__ = (id_class["className"]); if((temp__4659__auto__ == null)){ return p__$1; } else { var class$ = temp__4659__auto__; var old = reagent.impl.template.oget(p__$1,"className"); return reagent.impl.template.oset(p__$1,"className",(((old == null))?class$:[cljs.core.str.cljs$core$IFn$_invoke$arity$1(class$)," ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(old)].join(''))); } }); reagent.impl.template.convert_props = (function reagent$impl$template$convert_props(props,id_class){ return reagent.impl.template.set_id_class(reagent.impl.template.convert_prop_value(props),id_class); }); if(typeof reagent.impl.template.find_dom_node !== 'undefined'){ } else { reagent.impl.template.find_dom_node = null; } reagent.impl.template.these_inputs_have_selection_api = new cljs.core.PersistentHashSet(null, new cljs.core.PersistentArrayMap(null, 6, ["url",null,"tel",null,"text",null,"textarea",null,"password",null,"search",null], null), null); reagent.impl.template.has_selection_api_QMARK_ = (function reagent$impl$template$has_selection_api_QMARK_(input_type){ return cljs.core.contains_QMARK_(reagent.impl.template.these_inputs_have_selection_api,input_type); }); reagent.impl.template.input_set_value = (function reagent$impl$template$input_set_value(this$){ if(cljs.core.truth_((this$["cljsInputLive"]))){ (this$["cljsInputDirty"] = false); var rendered_value = (this$["cljsRenderedValue"]); var dom_value = (this$["cljsDOMValue"]); var node = (reagent.impl.template.find_dom_node.cljs$core$IFn$_invoke$arity$1 ? reagent.impl.template.find_dom_node.cljs$core$IFn$_invoke$arity$1(this$) : reagent.impl.template.find_dom_node.call(null,this$)); if(cljs.core.not_EQ_.cljs$core$IFn$_invoke$arity$2(rendered_value,dom_value)){ if(!(((node === (document["activeElement"]))) && (reagent.impl.template.has_selection_api_QMARK_((node["type"]))) && (typeof rendered_value === 'string') && (typeof dom_value === 'string'))){ (this$["cljsDOMValue"] = rendered_value); return (node["value"] = rendered_value); } else { var node_value = (node["value"]); if(cljs.core.not_EQ_.cljs$core$IFn$_invoke$arity$2(node_value,dom_value)){ return reagent.impl.batching.do_after_render(((function (node_value,rendered_value,dom_value,node){ return (function (){ return (reagent.impl.template.input_set_value.cljs$core$IFn$_invoke$arity$1 ? reagent.impl.template.input_set_value.cljs$core$IFn$_invoke$arity$1(this$) : reagent.impl.template.input_set_value.call(null,this$)); });})(node_value,rendered_value,dom_value,node)) ); } else { var existing_offset_from_end = (cljs.core.count(node_value) - (node["selectionStart"])); var new_cursor_offset = (cljs.core.count(rendered_value) - existing_offset_from_end); (this$["cljsDOMValue"] = rendered_value); (node["value"] = rendered_value); (node["selectionStart"] = new_cursor_offset); return (node["selectionEnd"] = new_cursor_offset); } } } else { return null; } } else { return null; } }); reagent.impl.template.input_handle_change = (function reagent$impl$template$input_handle_change(this$,on_change,e){ (this$["cljsDOMValue"] = e.target.value); if(cljs.core.truth_((this$["cljsInputDirty"]))){ } else { (this$["cljsInputDirty"] = true); reagent.impl.batching.do_after_render((function (){ return reagent.impl.template.input_set_value(this$); })); } return (on_change.cljs$core$IFn$_invoke$arity$1 ? on_change.cljs$core$IFn$_invoke$arity$1(e) : on_change.call(null,e)); }); reagent.impl.template.input_render_setup = (function reagent$impl$template$input_render_setup(this$,jsprops){ if(cljs.core.truth_((function (){var and__7656__auto__ = !((jsprops == null)); if(and__7656__auto__){ var and__7656__auto____$1 = jsprops.hasOwnProperty("onChange"); if(cljs.core.truth_(and__7656__auto____$1)){ return jsprops.hasOwnProperty("value"); } else { return and__7656__auto____$1; } } else { return and__7656__auto__; } })())){ var v = (jsprops["value"]); var value = (((v == null))?"":v); var on_change = (jsprops["onChange"]); if(cljs.core.truth_((this$["cljsInputLive"]))){ } else { (this$["cljsInputLive"] = true); (this$["cljsDOMValue"] = value); } (this$["cljsRenderedValue"] = value); delete jsprops["value"]; var G__17737 = jsprops; (G__17737["defaultValue"] = value); (G__17737["onChange"] = ((function (G__17737,v,value,on_change){ return (function (p1__17736_SHARP_){ return reagent.impl.template.input_handle_change(this$,on_change,p1__17736_SHARP_); });})(G__17737,v,value,on_change)) ); return G__17737; } else { return null; } }); reagent.impl.template.input_unmount = (function reagent$impl$template$input_unmount(this$){ return (this$["cljsInputLive"] = null); }); reagent.impl.template.input_component_QMARK_ = (function reagent$impl$template$input_component_QMARK_(x){ var G__17738 = x; switch (G__17738) { case "input": case "textarea": return true; break; default: return false; } }); reagent.impl.template.reagent_input_class = null; reagent.impl.template.input_spec = new cljs.core.PersistentArrayMap(null, 4, [cljs.core.cst$kw$display_DASH_name,"ReagentInput",cljs.core.cst$kw$component_DASH_did_DASH_update,reagent.impl.template.input_set_value,cljs.core.cst$kw$component_DASH_will_DASH_unmount,reagent.impl.template.input_unmount,cljs.core.cst$kw$reagent_DASH_render,(function (argv,comp,jsprops,first_child){ var this$ = reagent.impl.component._STAR_current_component_STAR_; reagent.impl.template.input_render_setup(this$,jsprops); return (reagent.impl.template.make_element.cljs$core$IFn$_invoke$arity$4 ? reagent.impl.template.make_element.cljs$core$IFn$_invoke$arity$4(argv,comp,jsprops,first_child) : reagent.impl.template.make_element.call(null,argv,comp,jsprops,first_child)); })], null); reagent.impl.template.reagent_input = (function reagent$impl$template$reagent_input(){ if((reagent.impl.template.reagent_input_class == null)){ reagent.impl.template.reagent_input_class = reagent.impl.component.create_class(reagent.impl.template.input_spec); } else { } return reagent.impl.template.reagent_input_class; }); reagent.impl.template.parse_tag = (function reagent$impl$template$parse_tag(hiccup_tag){ var vec__17740 = cljs.core.next(cljs.core.re_matches(reagent.impl.template.re_tag,cljs.core.name(hiccup_tag))); var tag = cljs.core.nth.cljs$core$IFn$_invoke$arity$3(vec__17740,(0),null); var id = cljs.core.nth.cljs$core$IFn$_invoke$arity$3(vec__17740,(1),null); var class$ = cljs.core.nth.cljs$core$IFn$_invoke$arity$3(vec__17740,(2),null); var class$__$1 = (((class$ == null))?null:clojure.string.replace(class$,/\./," ")); return ({"name": tag, "id": id, "className": class$__$1}); }); reagent.impl.template.try_get_key = (function reagent$impl$template$try_get_key(x){ try{return cljs.core.get.cljs$core$IFn$_invoke$arity$2(x,cljs.core.cst$kw$key); }catch (e17743){var e = e17743; return null; }}); reagent.impl.template.get_key = (function reagent$impl$template$get_key(x){ if(cljs.core.map_QMARK_(x)){ return reagent.impl.template.try_get_key(x); } else { return null; } }); reagent.impl.template.key_from_vec = (function reagent$impl$template$key_from_vec(v){ var temp__4659__auto__ = reagent.impl.template.get_key(cljs.core.meta(v)); if((temp__4659__auto__ == null)){ return reagent.impl.template.get_key(cljs.core.nth.cljs$core$IFn$_invoke$arity$3(v,(1),null)); } else { var k = temp__4659__auto__; return k; } }); reagent.impl.template.reag_element = (function reagent$impl$template$reag_element(tag,v){ var c = reagent.impl.component.as_class(tag); var jsprops = ({"argv": v}); var temp__4661__auto___17744 = reagent.impl.template.key_from_vec(v); if((temp__4661__auto___17744 == null)){ } else { var key_17745 = temp__4661__auto___17744; (jsprops["key"] = key_17745); } return (reagent.impl.util.react["createElement"])(c,jsprops); }); reagent.impl.template.adapt_react_class = (function reagent$impl$template$adapt_react_class(c){ var G__17746 = reagent.impl.template.__GT_NativeWrapper(); (G__17746["name"] = c); (G__17746["id"] = null); (G__17746["class"] = null); return G__17746; }); reagent.impl.template.tag_name_cache = ({}); reagent.impl.template.cached_parse = (function reagent$impl$template$cached_parse(x){ var temp__4659__auto__ = reagent.impl.template.cache_get(reagent.impl.template.tag_name_cache,x); if((temp__4659__auto__ == null)){ return (reagent.impl.template.tag_name_cache[x] = reagent.impl.template.parse_tag(x)); } else { var s = temp__4659__auto__; return s; } }); reagent.impl.template.native_element = (function reagent$impl$template$native_element(parsed,argv,first){ var comp = (parsed["name"]); var props = cljs.core.nth.cljs$core$IFn$_invoke$arity$3(argv,first,null); var hasprops = ((props == null)) || (cljs.core.map_QMARK_(props)); var jsprops = reagent.impl.template.convert_props(((hasprops)?props:null),parsed); var first_child = (first + ((hasprops)?(1):(0))); if(reagent.impl.template.input_component_QMARK_(comp)){ var G__17747 = cljs.core.with_meta(new cljs.core.PersistentVector(null, 5, 5, cljs.core.PersistentVector.EMPTY_NODE, [reagent.impl.template.reagent_input(),argv,comp,jsprops,first_child], null),cljs.core.meta(argv)); return (reagent.impl.template.as_element.cljs$core$IFn$_invoke$arity$1 ? reagent.impl.template.as_element.cljs$core$IFn$_invoke$arity$1(G__17747) : reagent.impl.template.as_element.call(null,G__17747)); } else { var key = reagent.impl.template.get_key(cljs.core.meta(argv)); var p = (((key == null))?jsprops:reagent.impl.template.oset(jsprops,"key",key)); return (reagent.impl.template.make_element.cljs$core$IFn$_invoke$arity$4 ? reagent.impl.template.make_element.cljs$core$IFn$_invoke$arity$4(argv,comp,p,first_child) : reagent.impl.template.make_element.call(null,argv,comp,p,first_child)); } }); reagent.impl.template.str_coll = (function reagent$impl$template$str_coll(coll){ return [cljs.core.str.cljs$core$IFn$_invoke$arity$1(coll)].join(''); }); reagent.impl.template.hiccup_err = (function reagent$impl$template$hiccup_err(var_args){ var args__8835__auto__ = []; var len__8828__auto___17751 = arguments.length; var i__8829__auto___17752 = (0); while(true){ if((i__8829__auto___17752 < len__8828__auto___17751)){ args__8835__auto__.push((arguments[i__8829__auto___17752])); var G__17753 = (i__8829__auto___17752 + (1)); i__8829__auto___17752 = G__17753; continue; } else { } break; } var argseq__8836__auto__ = ((((1) < args__8835__auto__.length))?(new cljs.core.IndexedSeq(args__8835__auto__.slice((1)),(0),null)):null); return reagent.impl.template.hiccup_err.cljs$core$IFn$_invoke$arity$variadic((arguments[(0)]),argseq__8836__auto__); }); reagent.impl.template.hiccup_err.cljs$core$IFn$_invoke$arity$variadic = (function (v,msg){ return [cljs.core.str.cljs$core$IFn$_invoke$arity$1(cljs.core.apply.cljs$core$IFn$_invoke$arity$2(cljs.core.str,msg)),": ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(reagent.impl.template.str_coll(v)),"\n",cljs.core.str.cljs$core$IFn$_invoke$arity$1(reagent.impl.component.comp_name())].join(''); }); reagent.impl.template.hiccup_err.cljs$lang$maxFixedArity = (1); reagent.impl.template.hiccup_err.cljs$lang$applyTo = (function (seq17749){ var G__17750 = cljs.core.first(seq17749); var seq17749__$1 = cljs.core.next(seq17749); return reagent.impl.template.hiccup_err.cljs$core$IFn$_invoke$arity$variadic(G__17750,seq17749__$1); }); reagent.impl.template.vec_to_elem = (function reagent$impl$template$vec_to_elem(v){ while(true){ var tag = cljs.core.nth.cljs$core$IFn$_invoke$arity$3(v,(0),null); if(reagent.impl.template.hiccup_tag_QMARK_(tag)){ var n = cljs.core.name(tag); var pos = n.indexOf(">"); var G__17754 = pos; switch (G__17754) { case (-1): return reagent.impl.template.native_element(reagent.impl.template.cached_parse(n),v,(1)); break; case (0): var comp = cljs.core.nth.cljs$core$IFn$_invoke$arity$3(v,(1),null); return reagent.impl.template.native_element(({"name": comp}),v,(2)); break; default: var G__17756 = new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.subs.cljs$core$IFn$_invoke$arity$3(n,(0),pos),cljs.core.assoc.cljs$core$IFn$_invoke$arity$3(v,(0),cljs.core.subs.cljs$core$IFn$_invoke$arity$2(n,(pos + (1))))], null); v = G__17756; continue; } } else { if((tag instanceof reagent.impl.template.NativeWrapper)){ return reagent.impl.template.native_element(tag,v,(1)); } else { return reagent.impl.template.reag_element(tag,v); } } break; } }); reagent.impl.template.as_element = (function reagent$impl$template$as_element(x){ if(reagent.impl.template.js_val_QMARK_(x)){ return x; } else { if(cljs.core.vector_QMARK_(x)){ return reagent.impl.template.vec_to_elem(x); } else { if(cljs.core.seq_QMARK_(x)){ return (reagent.impl.template.expand_seq.cljs$core$IFn$_invoke$arity$1 ? reagent.impl.template.expand_seq.cljs$core$IFn$_invoke$arity$1(x) : reagent.impl.template.expand_seq.call(null,x)); } else { if(reagent.impl.template.named_QMARK_(x)){ return cljs.core.name(x); } else { if(((!((x == null)))?((((x.cljs$lang$protocol_mask$partition0$ & (2147483648))) || ((cljs.core.PROTOCOL_SENTINEL === x.cljs$core$IPrintWithWriter$)))?true:(((!x.cljs$lang$protocol_mask$partition0$))?cljs.core.native_satisfies_QMARK_(cljs.core.IPrintWithWriter,x):false)):cljs.core.native_satisfies_QMARK_(cljs.core.IPrintWithWriter,x))){ return cljs.core.pr_str.cljs$core$IFn$_invoke$arity$variadic(cljs.core.prim_seq.cljs$core$IFn$_invoke$arity$2([x], 0)); } else { return x; } } } } } }); reagent.impl.component.as_element = reagent.impl.template.as_element; reagent.impl.template.expand_seq = (function reagent$impl$template$expand_seq(s){ var a = cljs.core.into_array.cljs$core$IFn$_invoke$arity$1(s); var n__8615__auto___17758 = a.length; var i_17759 = (0); while(true){ if((i_17759 < n__8615__auto___17758)){ (a[i_17759] = reagent.impl.template.as_element((a[i_17759]))); var G__17760 = (i_17759 + (1)); i_17759 = G__17760; continue; } else { } break; } return a; }); reagent.impl.template.expand_seq_dev = (function reagent$impl$template$expand_seq_dev(s,o){ var a = cljs.core.into_array.cljs$core$IFn$_invoke$arity$1(s); var n__8615__auto___17761 = a.length; var i_17762 = (0); while(true){ if((i_17762 < n__8615__auto___17761)){ var val_17763 = (a[i_17762]); if((cljs.core.vector_QMARK_(val_17763)) && ((reagent.impl.template.key_from_vec(val_17763) == null))){ (o["no-key"] = true); } else { } (a[i_17762] = reagent.impl.template.as_element(val_17763)); var G__17764 = (i_17762 + (1)); i_17762 = G__17764; continue; } else { } break; } return a; }); reagent.impl.template.expand_seq_check = (function reagent$impl$template$expand_seq_check(x){ var ctx = ({}); var vec__17765 = reagent.ratom.check_derefs(((function (ctx){ return (function (){ return reagent.impl.template.expand_seq_dev(x,ctx); });})(ctx)) ); var res = cljs.core.nth.cljs$core$IFn$_invoke$arity$3(vec__17765,(0),null); var derefed = cljs.core.nth.cljs$core$IFn$_invoke$arity$3(vec__17765,(1),null); if(cljs.core.truth_(derefed)){ } else { } if(cljs.core.truth_((ctx["no-key"]))){ } else { } return res; }); reagent.impl.template.make_element = (function reagent$impl$template$make_element(argv,comp,jsprops,first_child){ var G__17768 = (cljs.core.count(argv) - first_child); switch (G__17768) { case (0): return (reagent.impl.util.react["createElement"])(comp,jsprops); break; case (1): return (reagent.impl.util.react["createElement"])(comp,jsprops,reagent.impl.template.as_element(cljs.core.nth.cljs$core$IFn$_invoke$arity$3(argv,first_child,null))); break; default: return (reagent.impl.util.react["createElement"]).apply(null,cljs.core.reduce_kv(((function (G__17768){ return (function (a,k,v){ if((k >= first_child)){ a.push(reagent.impl.template.as_element(v)); } else { } return a; });})(G__17768)) ,[comp,jsprops],argv)); } }); <file_sep>// Compiled by ClojureScript 1.9.946 {:static-fns true, :optimize-constants true, :elide-asserts true} goog.provide('cljs.core.async.impl.channels'); goog.require('cljs.core'); goog.require('cljs.core.constants'); goog.require('cljs.core.async.impl.protocols'); goog.require('cljs.core.async.impl.dispatch'); goog.require('cljs.core.async.impl.buffers'); cljs.core.async.impl.channels.box = (function cljs$core$async$impl$channels$box(val){ if(typeof cljs.core.async.impl.channels.t_cljs$core$async$impl$channels13877 !== 'undefined'){ } else { /** * @constructor * @implements {cljs.core.IMeta} * @implements {cljs.core.IDeref} * @implements {cljs.core.IWithMeta} */ cljs.core.async.impl.channels.t_cljs$core$async$impl$channels13877 = (function (val,meta13878){ this.val = val; this.meta13878 = meta13878; this.cljs$lang$protocol_mask$partition0$ = 425984; this.cljs$lang$protocol_mask$partition1$ = 0; }); cljs.core.async.impl.channels.t_cljs$core$async$impl$channels13877.prototype.cljs$core$IWithMeta$_with_meta$arity$2 = (function (_13879,meta13878__$1){ var self__ = this; var _13879__$1 = this; return (new cljs.core.async.impl.channels.t_cljs$core$async$impl$channels13877(self__.val,meta13878__$1)); }); cljs.core.async.impl.channels.t_cljs$core$async$impl$channels13877.prototype.cljs$core$IMeta$_meta$arity$1 = (function (_13879){ var self__ = this; var _13879__$1 = this; return self__.meta13878; }); cljs.core.async.impl.channels.t_cljs$core$async$impl$channels13877.prototype.cljs$core$IDeref$_deref$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return self__.val; }); cljs.core.async.impl.channels.t_cljs$core$async$impl$channels13877.getBasis = (function (){ return new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.cst$sym$val,cljs.core.cst$sym$meta13878], null); }); cljs.core.async.impl.channels.t_cljs$core$async$impl$channels13877.cljs$lang$type = true; cljs.core.async.impl.channels.t_cljs$core$async$impl$channels13877.cljs$lang$ctorStr = "cljs.core.async.impl.channels/t_cljs$core$async$impl$channels13877"; cljs.core.async.impl.channels.t_cljs$core$async$impl$channels13877.cljs$lang$ctorPrWriter = (function (this__8293__auto__,writer__8294__auto__,opt__8295__auto__){ return cljs.core._write(writer__8294__auto__,"cljs.core.async.impl.channels/t_cljs$core$async$impl$channels13877"); }); cljs.core.async.impl.channels.__GT_t_cljs$core$async$impl$channels13877 = (function cljs$core$async$impl$channels$box_$___GT_t_cljs$core$async$impl$channels13877(val__$1,meta13878){ return (new cljs.core.async.impl.channels.t_cljs$core$async$impl$channels13877(val__$1,meta13878)); }); } return (new cljs.core.async.impl.channels.t_cljs$core$async$impl$channels13877(val,cljs.core.PersistentArrayMap.EMPTY)); }); /** * @constructor */ cljs.core.async.impl.channels.PutBox = (function (handler,val){ this.handler = handler; this.val = val; }); cljs.core.async.impl.channels.PutBox.getBasis = (function (){ return new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.cst$sym$handler,cljs.core.cst$sym$val], null); }); cljs.core.async.impl.channels.PutBox.cljs$lang$type = true; cljs.core.async.impl.channels.PutBox.cljs$lang$ctorStr = "cljs.core.async.impl.channels/PutBox"; cljs.core.async.impl.channels.PutBox.cljs$lang$ctorPrWriter = (function (this__8293__auto__,writer__8294__auto__,opt__8295__auto__){ return cljs.core._write(writer__8294__auto__,"cljs.core.async.impl.channels/PutBox"); }); cljs.core.async.impl.channels.__GT_PutBox = (function cljs$core$async$impl$channels$__GT_PutBox(handler,val){ return (new cljs.core.async.impl.channels.PutBox(handler,val)); }); cljs.core.async.impl.channels.put_active_QMARK_ = (function cljs$core$async$impl$channels$put_active_QMARK_(box){ return cljs.core.async.impl.protocols.active_QMARK_(box.handler); }); cljs.core.async.impl.channels.MAX_DIRTY = (64); /** * @interface */ cljs.core.async.impl.channels.MMC = function(){}; cljs.core.async.impl.channels.abort = (function cljs$core$async$impl$channels$abort(this$){ if((!((this$ == null))) && (!((this$.cljs$core$async$impl$channels$MMC$abort$arity$1 == null)))){ return this$.cljs$core$async$impl$channels$MMC$abort$arity$1(this$); } else { var x__8351__auto__ = (((this$ == null))?null:this$); var m__8352__auto__ = (cljs.core.async.impl.channels.abort[goog.typeOf(x__8351__auto__)]); if(!((m__8352__auto__ == null))){ return (m__8352__auto__.cljs$core$IFn$_invoke$arity$1 ? m__8352__auto__.cljs$core$IFn$_invoke$arity$1(this$) : m__8352__auto__.call(null,this$)); } else { var m__8352__auto____$1 = (cljs.core.async.impl.channels.abort["_"]); if(!((m__8352__auto____$1 == null))){ return (m__8352__auto____$1.cljs$core$IFn$_invoke$arity$1 ? m__8352__auto____$1.cljs$core$IFn$_invoke$arity$1(this$) : m__8352__auto____$1.call(null,this$)); } else { throw cljs.core.missing_protocol("MMC.abort",this$); } } } }); /** * @constructor * @implements {cljs.core.async.impl.channels.MMC} * @implements {cljs.core.async.impl.protocols.Channel} * @implements {cljs.core.async.impl.protocols.WritePort} * @implements {cljs.core.async.impl.protocols.ReadPort} */ cljs.core.async.impl.channels.ManyToManyChannel = (function (takes,dirty_takes,puts,dirty_puts,buf,closed,add_BANG_){ this.takes = takes; this.dirty_takes = dirty_takes; this.puts = puts; this.dirty_puts = dirty_puts; this.buf = buf; this.closed = closed; this.add_BANG_ = add_BANG_; }); cljs.core.async.impl.channels.ManyToManyChannel.prototype.cljs$core$async$impl$channels$MMC$ = cljs.core.PROTOCOL_SENTINEL; cljs.core.async.impl.channels.ManyToManyChannel.prototype.cljs$core$async$impl$channels$MMC$abort$arity$1 = (function (this$){ var self__ = this; var this$__$1 = this; while(true){ var putter_13891 = self__.puts.pop(); if((putter_13891 == null)){ } else { var put_handler_13892 = putter_13891.handler; var val_13893 = putter_13891.val; if(put_handler_13892.cljs$core$async$impl$protocols$Handler$active_QMARK_$arity$1(null)){ var put_cb_13894 = put_handler_13892.cljs$core$async$impl$protocols$Handler$commit$arity$1(null); cljs.core.async.impl.dispatch.run(((function (put_cb_13894,put_handler_13892,val_13893,putter_13891,this$__$1){ return (function (){ return (put_cb_13894.cljs$core$IFn$_invoke$arity$1 ? put_cb_13894.cljs$core$IFn$_invoke$arity$1(true) : put_cb_13894.call(null,true)); });})(put_cb_13894,put_handler_13892,val_13893,putter_13891,this$__$1)) ); } else { continue; } } break; } self__.puts.cleanup(cljs.core.constantly(false)); return this$__$1.cljs$core$async$impl$protocols$Channel$close_BANG_$arity$1(null); }); cljs.core.async.impl.channels.ManyToManyChannel.prototype.cljs$core$async$impl$protocols$WritePort$ = cljs.core.PROTOCOL_SENTINEL; cljs.core.async.impl.channels.ManyToManyChannel.prototype.cljs$core$async$impl$protocols$WritePort$put_BANG_$arity$3 = (function (this$,val,handler){ var self__ = this; var this$__$1 = this; var closed__$1 = self__.closed; if((closed__$1) || (!(handler.cljs$core$async$impl$protocols$Handler$active_QMARK_$arity$1(null)))){ return cljs.core.async.impl.channels.box(!(closed__$1)); } else { if(cljs.core.truth_((function (){var and__7656__auto__ = self__.buf; if(cljs.core.truth_(and__7656__auto__)){ return cljs.core.not(self__.buf.cljs$core$async$impl$protocols$Buffer$full_QMARK_$arity$1(null)); } else { return and__7656__auto__; } })())){ handler.cljs$core$async$impl$protocols$Handler$commit$arity$1(null); var done_QMARK_ = cljs.core.reduced_QMARK_((self__.add_BANG_.cljs$core$IFn$_invoke$arity$2 ? self__.add_BANG_.cljs$core$IFn$_invoke$arity$2(self__.buf,val) : self__.add_BANG_.call(null,self__.buf,val))); var take_cbs = (function (){var takers = cljs.core.PersistentVector.EMPTY; while(true){ if(((self__.takes.length > (0))) && ((cljs.core.count(self__.buf) > (0)))){ var taker = self__.takes.pop(); if(taker.cljs$core$async$impl$protocols$Handler$active_QMARK_$arity$1(null)){ var ret = taker.cljs$core$async$impl$protocols$Handler$commit$arity$1(null); var val__$1 = self__.buf.cljs$core$async$impl$protocols$Buffer$remove_BANG_$arity$1(null); var G__13895 = cljs.core.conj.cljs$core$IFn$_invoke$arity$2(takers,((function (takers,ret,val__$1,taker,done_QMARK_,closed__$1,this$__$1){ return (function (){ return (ret.cljs$core$IFn$_invoke$arity$1 ? ret.cljs$core$IFn$_invoke$arity$1(val__$1) : ret.call(null,val__$1)); });})(takers,ret,val__$1,taker,done_QMARK_,closed__$1,this$__$1)) ); takers = G__13895; continue; } else { var G__13896 = takers; takers = G__13896; continue; } } else { return takers; } break; } })(); if(done_QMARK_){ this$__$1.cljs$core$async$impl$channels$MMC$abort$arity$1(null); } else { } if(cljs.core.seq(take_cbs)){ var seq__13880_13897 = cljs.core.seq(take_cbs); var chunk__13881_13898 = null; var count__13882_13899 = (0); var i__13883_13900 = (0); while(true){ if((i__13883_13900 < count__13882_13899)){ var f_13901 = chunk__13881_13898.cljs$core$IIndexed$_nth$arity$2(null,i__13883_13900); cljs.core.async.impl.dispatch.run(f_13901); var G__13902 = seq__13880_13897; var G__13903 = chunk__13881_13898; var G__13904 = count__13882_13899; var G__13905 = (i__13883_13900 + (1)); seq__13880_13897 = G__13902; chunk__13881_13898 = G__13903; count__13882_13899 = G__13904; i__13883_13900 = G__13905; continue; } else { var temp__4657__auto___13906 = cljs.core.seq(seq__13880_13897); if(temp__4657__auto___13906){ var seq__13880_13907__$1 = temp__4657__auto___13906; if(cljs.core.chunked_seq_QMARK_(seq__13880_13907__$1)){ var c__8507__auto___13908 = cljs.core.chunk_first(seq__13880_13907__$1); var G__13909 = cljs.core.chunk_rest(seq__13880_13907__$1); var G__13910 = c__8507__auto___13908; var G__13911 = cljs.core.count(c__8507__auto___13908); var G__13912 = (0); seq__13880_13897 = G__13909; chunk__13881_13898 = G__13910; count__13882_13899 = G__13911; i__13883_13900 = G__13912; continue; } else { var f_13913 = cljs.core.first(seq__13880_13907__$1); cljs.core.async.impl.dispatch.run(f_13913); var G__13914 = cljs.core.next(seq__13880_13907__$1); var G__13915 = null; var G__13916 = (0); var G__13917 = (0); seq__13880_13897 = G__13914; chunk__13881_13898 = G__13915; count__13882_13899 = G__13916; i__13883_13900 = G__13917; continue; } } else { } } break; } } else { } return cljs.core.async.impl.channels.box(true); } else { var taker = (function (){while(true){ var taker = self__.takes.pop(); if(cljs.core.truth_(taker)){ if(cljs.core.truth_(taker.cljs$core$async$impl$protocols$Handler$active_QMARK_$arity$1(null))){ return taker; } else { continue; } } else { return null; } break; } })(); if(cljs.core.truth_(taker)){ var take_cb = cljs.core.async.impl.protocols.commit(taker); handler.cljs$core$async$impl$protocols$Handler$commit$arity$1(null); cljs.core.async.impl.dispatch.run(((function (take_cb,taker,closed__$1,this$__$1){ return (function (){ return (take_cb.cljs$core$IFn$_invoke$arity$1 ? take_cb.cljs$core$IFn$_invoke$arity$1(val) : take_cb.call(null,val)); });})(take_cb,taker,closed__$1,this$__$1)) ); return cljs.core.async.impl.channels.box(true); } else { if((self__.dirty_puts > (64))){ self__.dirty_puts = (0); self__.puts.cleanup(cljs.core.async.impl.channels.put_active_QMARK_); } else { self__.dirty_puts = (self__.dirty_puts + (1)); } if(cljs.core.truth_(handler.cljs$core$async$impl$protocols$Handler$blockable_QMARK_$arity$1(null))){ self__.puts.unbounded_unshift((new cljs.core.async.impl.channels.PutBox(handler,val))); } else { } return null; } } } }); cljs.core.async.impl.channels.ManyToManyChannel.prototype.cljs$core$async$impl$protocols$ReadPort$ = cljs.core.PROTOCOL_SENTINEL; cljs.core.async.impl.channels.ManyToManyChannel.prototype.cljs$core$async$impl$protocols$ReadPort$take_BANG_$arity$2 = (function (this$,handler){ var self__ = this; var this$__$1 = this; if(!(handler.cljs$core$async$impl$protocols$Handler$active_QMARK_$arity$1(null))){ return null; } else { if((!((self__.buf == null))) && ((cljs.core.count(self__.buf) > (0)))){ var temp__4655__auto__ = handler.cljs$core$async$impl$protocols$Handler$commit$arity$1(null); if(cljs.core.truth_(temp__4655__auto__)){ var take_cb = temp__4655__auto__; var val = self__.buf.cljs$core$async$impl$protocols$Buffer$remove_BANG_$arity$1(null); var vec__13884 = (((self__.puts.length > (0)))?(function (){var cbs = cljs.core.PersistentVector.EMPTY; while(true){ var putter = self__.puts.pop(); var put_handler = putter.handler; var val__$1 = putter.val; var cb = (function (){var and__7656__auto__ = put_handler.cljs$core$async$impl$protocols$Handler$active_QMARK_$arity$1(null); if(and__7656__auto__){ return put_handler.cljs$core$async$impl$protocols$Handler$commit$arity$1(null); } else { return and__7656__auto__; } })(); var cbs__$1 = (cljs.core.truth_(cb)?cljs.core.conj.cljs$core$IFn$_invoke$arity$2(cbs,cb):cbs); var done_QMARK_ = (cljs.core.truth_(cb)?cljs.core.reduced_QMARK_((self__.add_BANG_.cljs$core$IFn$_invoke$arity$2 ? self__.add_BANG_.cljs$core$IFn$_invoke$arity$2(self__.buf,val__$1) : self__.add_BANG_.call(null,self__.buf,val__$1))):null); if((cljs.core.not(done_QMARK_)) && (cljs.core.not(self__.buf.cljs$core$async$impl$protocols$Buffer$full_QMARK_$arity$1(null))) && ((self__.puts.length > (0)))){ var G__13918 = cbs__$1; cbs = G__13918; continue; } else { return new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [done_QMARK_,cbs__$1], null); } break; } })():null); var done_QMARK_ = cljs.core.nth.cljs$core$IFn$_invoke$arity$3(vec__13884,(0),null); var cbs = cljs.core.nth.cljs$core$IFn$_invoke$arity$3(vec__13884,(1),null); if(cljs.core.truth_(done_QMARK_)){ this$__$1.cljs$core$async$impl$channels$MMC$abort$arity$1(null); } else { } var seq__13887_13919 = cljs.core.seq(cbs); var chunk__13888_13920 = null; var count__13889_13921 = (0); var i__13890_13922 = (0); while(true){ if((i__13890_13922 < count__13889_13921)){ var cb_13923 = chunk__13888_13920.cljs$core$IIndexed$_nth$arity$2(null,i__13890_13922); cljs.core.async.impl.dispatch.run(((function (seq__13887_13919,chunk__13888_13920,count__13889_13921,i__13890_13922,cb_13923,val,vec__13884,done_QMARK_,cbs,take_cb,temp__4655__auto__,this$__$1){ return (function (){ return (cb_13923.cljs$core$IFn$_invoke$arity$1 ? cb_13923.cljs$core$IFn$_invoke$arity$1(true) : cb_13923.call(null,true)); });})(seq__13887_13919,chunk__13888_13920,count__13889_13921,i__13890_13922,cb_13923,val,vec__13884,done_QMARK_,cbs,take_cb,temp__4655__auto__,this$__$1)) ); var G__13924 = seq__13887_13919; var G__13925 = chunk__13888_13920; var G__13926 = count__13889_13921; var G__13927 = (i__13890_13922 + (1)); seq__13887_13919 = G__13924; chunk__13888_13920 = G__13925; count__13889_13921 = G__13926; i__13890_13922 = G__13927; continue; } else { var temp__4657__auto___13928 = cljs.core.seq(seq__13887_13919); if(temp__4657__auto___13928){ var seq__13887_13929__$1 = temp__4657__auto___13928; if(cljs.core.chunked_seq_QMARK_(seq__13887_13929__$1)){ var c__8507__auto___13930 = cljs.core.chunk_first(seq__13887_13929__$1); var G__13931 = cljs.core.chunk_rest(seq__13887_13929__$1); var G__13932 = c__8507__auto___13930; var G__13933 = cljs.core.count(c__8507__auto___13930); var G__13934 = (0); seq__13887_13919 = G__13931; chunk__13888_13920 = G__13932; count__13889_13921 = G__13933; i__13890_13922 = G__13934; continue; } else { var cb_13935 = cljs.core.first(seq__13887_13929__$1); cljs.core.async.impl.dispatch.run(((function (seq__13887_13919,chunk__13888_13920,count__13889_13921,i__13890_13922,cb_13935,seq__13887_13929__$1,temp__4657__auto___13928,val,vec__13884,done_QMARK_,cbs,take_cb,temp__4655__auto__,this$__$1){ return (function (){ return (cb_13935.cljs$core$IFn$_invoke$arity$1 ? cb_13935.cljs$core$IFn$_invoke$arity$1(true) : cb_13935.call(null,true)); });})(seq__13887_13919,chunk__13888_13920,count__13889_13921,i__13890_13922,cb_13935,seq__13887_13929__$1,temp__4657__auto___13928,val,vec__13884,done_QMARK_,cbs,take_cb,temp__4655__auto__,this$__$1)) ); var G__13936 = cljs.core.next(seq__13887_13929__$1); var G__13937 = null; var G__13938 = (0); var G__13939 = (0); seq__13887_13919 = G__13936; chunk__13888_13920 = G__13937; count__13889_13921 = G__13938; i__13890_13922 = G__13939; continue; } } else { } } break; } return cljs.core.async.impl.channels.box(val); } else { return null; } } else { var putter = (function (){while(true){ var putter = self__.puts.pop(); if(cljs.core.truth_(putter)){ if(cljs.core.async.impl.protocols.active_QMARK_(putter.handler)){ return putter; } else { continue; } } else { return null; } break; } })(); if(cljs.core.truth_(putter)){ var put_cb = cljs.core.async.impl.protocols.commit(putter.handler); handler.cljs$core$async$impl$protocols$Handler$commit$arity$1(null); cljs.core.async.impl.dispatch.run(((function (put_cb,putter,this$__$1){ return (function (){ return (put_cb.cljs$core$IFn$_invoke$arity$1 ? put_cb.cljs$core$IFn$_invoke$arity$1(true) : put_cb.call(null,true)); });})(put_cb,putter,this$__$1)) ); return cljs.core.async.impl.channels.box(putter.val); } else { if(cljs.core.truth_(self__.closed)){ if(cljs.core.truth_(self__.buf)){ (self__.add_BANG_.cljs$core$IFn$_invoke$arity$1 ? self__.add_BANG_.cljs$core$IFn$_invoke$arity$1(self__.buf) : self__.add_BANG_.call(null,self__.buf)); } else { } if(cljs.core.truth_((function (){var and__7656__auto__ = handler.cljs$core$async$impl$protocols$Handler$active_QMARK_$arity$1(null); if(cljs.core.truth_(and__7656__auto__)){ return handler.cljs$core$async$impl$protocols$Handler$commit$arity$1(null); } else { return and__7656__auto__; } })())){ var has_val = (function (){var and__7656__auto__ = self__.buf; if(cljs.core.truth_(and__7656__auto__)){ return (cljs.core.count(self__.buf) > (0)); } else { return and__7656__auto__; } })(); var val = (cljs.core.truth_(has_val)?self__.buf.cljs$core$async$impl$protocols$Buffer$remove_BANG_$arity$1(null):null); return cljs.core.async.impl.channels.box(val); } else { return null; } } else { if((self__.dirty_takes > (64))){ self__.dirty_takes = (0); self__.takes.cleanup(cljs.core.async.impl.protocols.active_QMARK_); } else { self__.dirty_takes = (self__.dirty_takes + (1)); } if(cljs.core.truth_(handler.cljs$core$async$impl$protocols$Handler$blockable_QMARK_$arity$1(null))){ self__.takes.unbounded_unshift(handler); } else { } return null; } } } } }); cljs.core.async.impl.channels.ManyToManyChannel.prototype.cljs$core$async$impl$protocols$Channel$ = cljs.core.PROTOCOL_SENTINEL; cljs.core.async.impl.channels.ManyToManyChannel.prototype.cljs$core$async$impl$protocols$Channel$closed_QMARK_$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return self__.closed; }); cljs.core.async.impl.channels.ManyToManyChannel.prototype.cljs$core$async$impl$protocols$Channel$close_BANG_$arity$1 = (function (this$){ var self__ = this; var this$__$1 = this; if(self__.closed){ return null; } else { self__.closed = true; if(cljs.core.truth_((function (){var and__7656__auto__ = self__.buf; if(cljs.core.truth_(and__7656__auto__)){ return (self__.puts.length === (0)); } else { return and__7656__auto__; } })())){ (self__.add_BANG_.cljs$core$IFn$_invoke$arity$1 ? self__.add_BANG_.cljs$core$IFn$_invoke$arity$1(self__.buf) : self__.add_BANG_.call(null,self__.buf)); } else { } while(true){ var taker_13940 = self__.takes.pop(); if((taker_13940 == null)){ } else { if(taker_13940.cljs$core$async$impl$protocols$Handler$active_QMARK_$arity$1(null)){ var take_cb_13941 = taker_13940.cljs$core$async$impl$protocols$Handler$commit$arity$1(null); var val_13942 = (cljs.core.truth_((function (){var and__7656__auto__ = self__.buf; if(cljs.core.truth_(and__7656__auto__)){ return (cljs.core.count(self__.buf) > (0)); } else { return and__7656__auto__; } })())?self__.buf.cljs$core$async$impl$protocols$Buffer$remove_BANG_$arity$1(null):null); cljs.core.async.impl.dispatch.run(((function (take_cb_13941,val_13942,taker_13940,this$__$1){ return (function (){ return (take_cb_13941.cljs$core$IFn$_invoke$arity$1 ? take_cb_13941.cljs$core$IFn$_invoke$arity$1(val_13942) : take_cb_13941.call(null,val_13942)); });})(take_cb_13941,val_13942,taker_13940,this$__$1)) ); } else { } continue; } break; } if(cljs.core.truth_(self__.buf)){ self__.buf.cljs$core$async$impl$protocols$Buffer$close_buf_BANG_$arity$1(null); } else { } return null; } }); cljs.core.async.impl.channels.ManyToManyChannel.getBasis = (function (){ return new cljs.core.PersistentVector(null, 7, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.cst$sym$takes,cljs.core.with_meta(cljs.core.cst$sym$dirty_DASH_takes,new cljs.core.PersistentArrayMap(null, 1, [cljs.core.cst$kw$mutable,true], null)),cljs.core.cst$sym$puts,cljs.core.with_meta(cljs.core.cst$sym$dirty_DASH_puts,new cljs.core.PersistentArrayMap(null, 1, [cljs.core.cst$kw$mutable,true], null)),cljs.core.with_meta(cljs.core.cst$sym$buf,new cljs.core.PersistentArrayMap(null, 1, [cljs.core.cst$kw$tag,cljs.core.cst$sym$not_DASH_native], null)),cljs.core.with_meta(cljs.core.cst$sym$closed,new cljs.core.PersistentArrayMap(null, 1, [cljs.core.cst$kw$mutable,true], null)),cljs.core.cst$sym$add_BANG_], null); }); cljs.core.async.impl.channels.ManyToManyChannel.cljs$lang$type = true; cljs.core.async.impl.channels.ManyToManyChannel.cljs$lang$ctorStr = "cljs.core.async.impl.channels/ManyToManyChannel"; cljs.core.async.impl.channels.ManyToManyChannel.cljs$lang$ctorPrWriter = (function (this__8293__auto__,writer__8294__auto__,opt__8295__auto__){ return cljs.core._write(writer__8294__auto__,"cljs.core.async.impl.channels/ManyToManyChannel"); }); cljs.core.async.impl.channels.__GT_ManyToManyChannel = (function cljs$core$async$impl$channels$__GT_ManyToManyChannel(takes,dirty_takes,puts,dirty_puts,buf,closed,add_BANG_){ return (new cljs.core.async.impl.channels.ManyToManyChannel(takes,dirty_takes,puts,dirty_puts,buf,closed,add_BANG_)); }); cljs.core.async.impl.channels.ex_handler = (function cljs$core$async$impl$channels$ex_handler(ex){ console.log(ex); return null; }); cljs.core.async.impl.channels.handle = (function cljs$core$async$impl$channels$handle(buf,exh,t){ var else$ = (function (){var fexpr__13943 = (function (){var or__7668__auto__ = exh; if(cljs.core.truth_(or__7668__auto__)){ return or__7668__auto__; } else { return cljs.core.async.impl.channels.ex_handler; } })(); return (fexpr__13943.cljs$core$IFn$_invoke$arity$1 ? fexpr__13943.cljs$core$IFn$_invoke$arity$1(t) : fexpr__13943.call(null,t)); })(); if((else$ == null)){ return buf; } else { return cljs.core.async.impl.protocols.add_BANG_.cljs$core$IFn$_invoke$arity$2(buf,else$); } }); cljs.core.async.impl.channels.chan = (function cljs$core$async$impl$channels$chan(var_args){ var G__13945 = arguments.length; switch (G__13945) { case 1: return cljs.core.async.impl.channels.chan.cljs$core$IFn$_invoke$arity$1((arguments[(0)])); break; case 2: return cljs.core.async.impl.channels.chan.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; case 3: return cljs.core.async.impl.channels.chan.cljs$core$IFn$_invoke$arity$3((arguments[(0)]),(arguments[(1)]),(arguments[(2)])); break; default: throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join(''))); } }); cljs.core.async.impl.channels.chan.cljs$core$IFn$_invoke$arity$1 = (function (buf){ return cljs.core.async.impl.channels.chan.cljs$core$IFn$_invoke$arity$2(buf,null); }); cljs.core.async.impl.channels.chan.cljs$core$IFn$_invoke$arity$2 = (function (buf,xform){ return cljs.core.async.impl.channels.chan.cljs$core$IFn$_invoke$arity$3(buf,xform,null); }); cljs.core.async.impl.channels.chan.cljs$core$IFn$_invoke$arity$3 = (function (buf,xform,exh){ return (new cljs.core.async.impl.channels.ManyToManyChannel(cljs.core.async.impl.buffers.ring_buffer((32)),(0),cljs.core.async.impl.buffers.ring_buffer((32)),(0),buf,false,(function (){var add_BANG_ = (cljs.core.truth_(xform)?(xform.cljs$core$IFn$_invoke$arity$1 ? xform.cljs$core$IFn$_invoke$arity$1(cljs.core.async.impl.protocols.add_BANG_) : xform.call(null,cljs.core.async.impl.protocols.add_BANG_)):cljs.core.async.impl.protocols.add_BANG_); return ((function (add_BANG_){ return (function() { var G__13949 = null; var G__13949__1 = (function (buf__$1){ try{return (add_BANG_.cljs$core$IFn$_invoke$arity$1 ? add_BANG_.cljs$core$IFn$_invoke$arity$1(buf__$1) : add_BANG_.call(null,buf__$1)); }catch (e13946){var t = e13946; return cljs.core.async.impl.channels.handle(buf__$1,exh,t); }}); var G__13949__2 = (function (buf__$1,val){ try{return (add_BANG_.cljs$core$IFn$_invoke$arity$2 ? add_BANG_.cljs$core$IFn$_invoke$arity$2(buf__$1,val) : add_BANG_.call(null,buf__$1,val)); }catch (e13947){var t = e13947; return cljs.core.async.impl.channels.handle(buf__$1,exh,t); }}); G__13949 = function(buf__$1,val){ switch(arguments.length){ case 1: return G__13949__1.call(this,buf__$1); case 2: return G__13949__2.call(this,buf__$1,val); } throw(new Error('Invalid arity: ' + (arguments.length - 1))); }; G__13949.cljs$core$IFn$_invoke$arity$1 = G__13949__1; G__13949.cljs$core$IFn$_invoke$arity$2 = G__13949__2; return G__13949; })() ;})(add_BANG_)) })())); }); cljs.core.async.impl.channels.chan.cljs$lang$maxFixedArity = 3; <file_sep>// Compiled by ClojureScript 1.9.946 {:static-fns true, :optimize-constants true, :elide-asserts true} goog.provide('reagent.debug'); goog.require('cljs.core'); goog.require('cljs.core.constants'); reagent.debug.has_console = typeof console !== 'undefined'; reagent.debug.tracking = false; if(typeof reagent.debug.warnings !== 'undefined'){ } else { reagent.debug.warnings = cljs.core.atom.cljs$core$IFn$_invoke$arity$1(null); } if(typeof reagent.debug.track_console !== 'undefined'){ } else { reagent.debug.track_console = (function (){var o = ({}); o.warn = ((function (o){ return (function() { var G__13842__delegate = function (args){ return cljs.core.swap_BANG_.cljs$core$IFn$_invoke$arity$variadic(reagent.debug.warnings,cljs.core.update_in,new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.cst$kw$warn], null),cljs.core.conj,cljs.core.prim_seq.cljs$core$IFn$_invoke$arity$2([cljs.core.apply.cljs$core$IFn$_invoke$arity$2(cljs.core.str,args)], 0)); }; var G__13842 = function (var_args){ var args = null; if (arguments.length > 0) { var G__13843__i = 0, G__13843__a = new Array(arguments.length - 0); while (G__13843__i < G__13843__a.length) {G__13843__a[G__13843__i] = arguments[G__13843__i + 0]; ++G__13843__i;} args = new cljs.core.IndexedSeq(G__13843__a,0,null); } return G__13842__delegate.call(this,args);}; G__13842.cljs$lang$maxFixedArity = 0; G__13842.cljs$lang$applyTo = (function (arglist__13844){ var args = cljs.core.seq(arglist__13844); return G__13842__delegate(args); }); G__13842.cljs$core$IFn$_invoke$arity$variadic = G__13842__delegate; return G__13842; })() ;})(o)) ; o.error = ((function (o){ return (function() { var G__13845__delegate = function (args){ return cljs.core.swap_BANG_.cljs$core$IFn$_invoke$arity$variadic(reagent.debug.warnings,cljs.core.update_in,new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.cst$kw$error], null),cljs.core.conj,cljs.core.prim_seq.cljs$core$IFn$_invoke$arity$2([cljs.core.apply.cljs$core$IFn$_invoke$arity$2(cljs.core.str,args)], 0)); }; var G__13845 = function (var_args){ var args = null; if (arguments.length > 0) { var G__13846__i = 0, G__13846__a = new Array(arguments.length - 0); while (G__13846__i < G__13846__a.length) {G__13846__a[G__13846__i] = arguments[G__13846__i + 0]; ++G__13846__i;} args = new cljs.core.IndexedSeq(G__13846__a,0,null); } return G__13845__delegate.call(this,args);}; G__13845.cljs$lang$maxFixedArity = 0; G__13845.cljs$lang$applyTo = (function (arglist__13847){ var args = cljs.core.seq(arglist__13847); return G__13845__delegate(args); }); G__13845.cljs$core$IFn$_invoke$arity$variadic = G__13845__delegate; return G__13845; })() ;})(o)) ; return o; })(); } reagent.debug.track_warnings = (function reagent$debug$track_warnings(f){ reagent.debug.tracking = true; cljs.core.reset_BANG_(reagent.debug.warnings,null); (f.cljs$core$IFn$_invoke$arity$0 ? f.cljs$core$IFn$_invoke$arity$0() : f.call(null)); var warns = cljs.core.deref(reagent.debug.warnings); cljs.core.reset_BANG_(reagent.debug.warnings,null); reagent.debug.tracking = false; return warns; }); <file_sep>// Compiled by ClojureScript 1.9.946 {:static-fns true, :optimize-constants true, :elide-asserts true} goog.provide('cljs.core.async'); goog.require('cljs.core'); goog.require('cljs.core.constants'); goog.require('cljs.core.async.impl.protocols'); goog.require('cljs.core.async.impl.channels'); goog.require('cljs.core.async.impl.buffers'); goog.require('cljs.core.async.impl.timers'); goog.require('cljs.core.async.impl.dispatch'); goog.require('cljs.core.async.impl.ioc_helpers'); cljs.core.async.fn_handler = (function cljs$core$async$fn_handler(var_args){ var G__15483 = arguments.length; switch (G__15483) { case 1: return cljs.core.async.fn_handler.cljs$core$IFn$_invoke$arity$1((arguments[(0)])); break; case 2: return cljs.core.async.fn_handler.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; default: throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join(''))); } }); cljs.core.async.fn_handler.cljs$core$IFn$_invoke$arity$1 = (function (f){ return cljs.core.async.fn_handler.cljs$core$IFn$_invoke$arity$2(f,true); }); cljs.core.async.fn_handler.cljs$core$IFn$_invoke$arity$2 = (function (f,blockable){ if(typeof cljs.core.async.t_cljs$core$async15484 !== 'undefined'){ } else { /** * @constructor * @implements {cljs.core.async.impl.protocols.Handler} * @implements {cljs.core.IMeta} * @implements {cljs.core.IWithMeta} */ cljs.core.async.t_cljs$core$async15484 = (function (f,blockable,meta15485){ this.f = f; this.blockable = blockable; this.meta15485 = meta15485; this.cljs$lang$protocol_mask$partition0$ = 393216; this.cljs$lang$protocol_mask$partition1$ = 0; }); cljs.core.async.t_cljs$core$async15484.prototype.cljs$core$IWithMeta$_with_meta$arity$2 = (function (_15486,meta15485__$1){ var self__ = this; var _15486__$1 = this; return (new cljs.core.async.t_cljs$core$async15484(self__.f,self__.blockable,meta15485__$1)); }); cljs.core.async.t_cljs$core$async15484.prototype.cljs$core$IMeta$_meta$arity$1 = (function (_15486){ var self__ = this; var _15486__$1 = this; return self__.meta15485; }); cljs.core.async.t_cljs$core$async15484.prototype.cljs$core$async$impl$protocols$Handler$ = cljs.core.PROTOCOL_SENTINEL; cljs.core.async.t_cljs$core$async15484.prototype.cljs$core$async$impl$protocols$Handler$active_QMARK_$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return true; }); cljs.core.async.t_cljs$core$async15484.prototype.cljs$core$async$impl$protocols$Handler$blockable_QMARK_$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return self__.blockable; }); cljs.core.async.t_cljs$core$async15484.prototype.cljs$core$async$impl$protocols$Handler$commit$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return self__.f; }); cljs.core.async.t_cljs$core$async15484.getBasis = (function (){ return new cljs.core.PersistentVector(null, 3, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.cst$sym$f,cljs.core.cst$sym$blockable,cljs.core.cst$sym$meta15485], null); }); cljs.core.async.t_cljs$core$async15484.cljs$lang$type = true; cljs.core.async.t_cljs$core$async15484.cljs$lang$ctorStr = "cljs.core.async/t_cljs$core$async15484"; cljs.core.async.t_cljs$core$async15484.cljs$lang$ctorPrWriter = (function (this__8293__auto__,writer__8294__auto__,opt__8295__auto__){ return cljs.core._write(writer__8294__auto__,"cljs.core.async/t_cljs$core$async15484"); }); cljs.core.async.__GT_t_cljs$core$async15484 = (function cljs$core$async$__GT_t_cljs$core$async15484(f__$1,blockable__$1,meta15485){ return (new cljs.core.async.t_cljs$core$async15484(f__$1,blockable__$1,meta15485)); }); } return (new cljs.core.async.t_cljs$core$async15484(f,blockable,cljs.core.PersistentArrayMap.EMPTY)); }); cljs.core.async.fn_handler.cljs$lang$maxFixedArity = 2; /** * Returns a fixed buffer of size n. When full, puts will block/park. */ cljs.core.async.buffer = (function cljs$core$async$buffer(n){ return cljs.core.async.impl.buffers.fixed_buffer(n); }); /** * Returns a buffer of size n. When full, puts will complete but * val will be dropped (no transfer). */ cljs.core.async.dropping_buffer = (function cljs$core$async$dropping_buffer(n){ return cljs.core.async.impl.buffers.dropping_buffer(n); }); /** * Returns a buffer of size n. When full, puts will complete, and be * buffered, but oldest elements in buffer will be dropped (not * transferred). */ cljs.core.async.sliding_buffer = (function cljs$core$async$sliding_buffer(n){ return cljs.core.async.impl.buffers.sliding_buffer(n); }); /** * Returns true if a channel created with buff will never block. That is to say, * puts into this buffer will never cause the buffer to be full. */ cljs.core.async.unblocking_buffer_QMARK_ = (function cljs$core$async$unblocking_buffer_QMARK_(buff){ if(!((buff == null))){ if((false) || ((cljs.core.PROTOCOL_SENTINEL === buff.cljs$core$async$impl$protocols$UnblockingBuffer$))){ return true; } else { if((!buff.cljs$lang$protocol_mask$partition$)){ return cljs.core.native_satisfies_QMARK_(cljs.core.async.impl.protocols.UnblockingBuffer,buff); } else { return false; } } } else { return cljs.core.native_satisfies_QMARK_(cljs.core.async.impl.protocols.UnblockingBuffer,buff); } }); /** * Creates a channel with an optional buffer, an optional transducer (like (map f), * (filter p) etc or a composition thereof), and an optional exception handler. * If buf-or-n is a number, will create and use a fixed buffer of that size. If a * transducer is supplied a buffer must be specified. ex-handler must be a * fn of one argument - if an exception occurs during transformation it will be called * with the thrown value as an argument, and any non-nil return value will be placed * in the channel. */ cljs.core.async.chan = (function cljs$core$async$chan(var_args){ var G__15490 = arguments.length; switch (G__15490) { case 0: return cljs.core.async.chan.cljs$core$IFn$_invoke$arity$0(); break; case 1: return cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1((arguments[(0)])); break; case 2: return cljs.core.async.chan.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; case 3: return cljs.core.async.chan.cljs$core$IFn$_invoke$arity$3((arguments[(0)]),(arguments[(1)]),(arguments[(2)])); break; default: throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join(''))); } }); cljs.core.async.chan.cljs$core$IFn$_invoke$arity$0 = (function (){ return cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1(null); }); cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1 = (function (buf_or_n){ return cljs.core.async.chan.cljs$core$IFn$_invoke$arity$3(buf_or_n,null,null); }); cljs.core.async.chan.cljs$core$IFn$_invoke$arity$2 = (function (buf_or_n,xform){ return cljs.core.async.chan.cljs$core$IFn$_invoke$arity$3(buf_or_n,xform,null); }); cljs.core.async.chan.cljs$core$IFn$_invoke$arity$3 = (function (buf_or_n,xform,ex_handler){ var buf_or_n__$1 = ((cljs.core._EQ_.cljs$core$IFn$_invoke$arity$2(buf_or_n,(0)))?null:buf_or_n); if(cljs.core.truth_(xform)){ } else { } return cljs.core.async.impl.channels.chan.cljs$core$IFn$_invoke$arity$3(((typeof buf_or_n__$1 === 'number')?cljs.core.async.buffer(buf_or_n__$1):buf_or_n__$1),xform,ex_handler); }); cljs.core.async.chan.cljs$lang$maxFixedArity = 3; /** * Creates a promise channel with an optional transducer, and an optional * exception-handler. A promise channel can take exactly one value that consumers * will receive. Once full, puts complete but val is dropped (no transfer). * Consumers will block until either a value is placed in the channel or the * channel is closed. See chan for the semantics of xform and ex-handler. */ cljs.core.async.promise_chan = (function cljs$core$async$promise_chan(var_args){ var G__15493 = arguments.length; switch (G__15493) { case 0: return cljs.core.async.promise_chan.cljs$core$IFn$_invoke$arity$0(); break; case 1: return cljs.core.async.promise_chan.cljs$core$IFn$_invoke$arity$1((arguments[(0)])); break; case 2: return cljs.core.async.promise_chan.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; default: throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join(''))); } }); cljs.core.async.promise_chan.cljs$core$IFn$_invoke$arity$0 = (function (){ return cljs.core.async.promise_chan.cljs$core$IFn$_invoke$arity$1(null); }); cljs.core.async.promise_chan.cljs$core$IFn$_invoke$arity$1 = (function (xform){ return cljs.core.async.promise_chan.cljs$core$IFn$_invoke$arity$2(xform,null); }); cljs.core.async.promise_chan.cljs$core$IFn$_invoke$arity$2 = (function (xform,ex_handler){ return cljs.core.async.chan.cljs$core$IFn$_invoke$arity$3(cljs.core.async.impl.buffers.promise_buffer(),xform,ex_handler); }); cljs.core.async.promise_chan.cljs$lang$maxFixedArity = 2; /** * Returns a channel that will close after msecs */ cljs.core.async.timeout = (function cljs$core$async$timeout(msecs){ return cljs.core.async.impl.timers.timeout(msecs); }); /** * takes a val from port. Must be called inside a (go ...) block. Will * return nil if closed. Will park if nothing is available. * Returns true unless port is already closed */ cljs.core.async._LT__BANG_ = (function cljs$core$async$_LT__BANG_(port){ throw (new Error("<! used not in (go ...) block")); }); /** * Asynchronously takes a val from port, passing to fn1. Will pass nil * if closed. If on-caller? (default true) is true, and value is * immediately available, will call fn1 on calling thread. * Returns nil. */ cljs.core.async.take_BANG_ = (function cljs$core$async$take_BANG_(var_args){ var G__15496 = arguments.length; switch (G__15496) { case 2: return cljs.core.async.take_BANG_.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; case 3: return cljs.core.async.take_BANG_.cljs$core$IFn$_invoke$arity$3((arguments[(0)]),(arguments[(1)]),(arguments[(2)])); break; default: throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join(''))); } }); cljs.core.async.take_BANG_.cljs$core$IFn$_invoke$arity$2 = (function (port,fn1){ return cljs.core.async.take_BANG_.cljs$core$IFn$_invoke$arity$3(port,fn1,true); }); cljs.core.async.take_BANG_.cljs$core$IFn$_invoke$arity$3 = (function (port,fn1,on_caller_QMARK_){ var ret = cljs.core.async.impl.protocols.take_BANG_(port,cljs.core.async.fn_handler.cljs$core$IFn$_invoke$arity$1(fn1)); if(cljs.core.truth_(ret)){ var val_15498 = cljs.core.deref(ret); if(cljs.core.truth_(on_caller_QMARK_)){ (fn1.cljs$core$IFn$_invoke$arity$1 ? fn1.cljs$core$IFn$_invoke$arity$1(val_15498) : fn1.call(null,val_15498)); } else { cljs.core.async.impl.dispatch.run(((function (val_15498,ret){ return (function (){ return (fn1.cljs$core$IFn$_invoke$arity$1 ? fn1.cljs$core$IFn$_invoke$arity$1(val_15498) : fn1.call(null,val_15498)); });})(val_15498,ret)) ); } } else { } return null; }); cljs.core.async.take_BANG_.cljs$lang$maxFixedArity = 3; cljs.core.async.nop = (function cljs$core$async$nop(_){ return null; }); cljs.core.async.fhnop = cljs.core.async.fn_handler.cljs$core$IFn$_invoke$arity$1(cljs.core.async.nop); /** * puts a val into port. nil values are not allowed. Must be called * inside a (go ...) block. Will park if no buffer space is available. * Returns true unless port is already closed. */ cljs.core.async._GT__BANG_ = (function cljs$core$async$_GT__BANG_(port,val){ throw (new Error(">! used not in (go ...) block")); }); /** * Asynchronously puts a val into port, calling fn0 (if supplied) when * complete. nil values are not allowed. Will throw if closed. If * on-caller? (default true) is true, and the put is immediately * accepted, will call fn0 on calling thread. Returns nil. */ cljs.core.async.put_BANG_ = (function cljs$core$async$put_BANG_(var_args){ var G__15500 = arguments.length; switch (G__15500) { case 2: return cljs.core.async.put_BANG_.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; case 3: return cljs.core.async.put_BANG_.cljs$core$IFn$_invoke$arity$3((arguments[(0)]),(arguments[(1)]),(arguments[(2)])); break; case 4: return cljs.core.async.put_BANG_.cljs$core$IFn$_invoke$arity$4((arguments[(0)]),(arguments[(1)]),(arguments[(2)]),(arguments[(3)])); break; default: throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join(''))); } }); cljs.core.async.put_BANG_.cljs$core$IFn$_invoke$arity$2 = (function (port,val){ var temp__4655__auto__ = cljs.core.async.impl.protocols.put_BANG_(port,val,cljs.core.async.fhnop); if(cljs.core.truth_(temp__4655__auto__)){ var ret = temp__4655__auto__; return cljs.core.deref(ret); } else { return true; } }); cljs.core.async.put_BANG_.cljs$core$IFn$_invoke$arity$3 = (function (port,val,fn1){ return cljs.core.async.put_BANG_.cljs$core$IFn$_invoke$arity$4(port,val,fn1,true); }); cljs.core.async.put_BANG_.cljs$core$IFn$_invoke$arity$4 = (function (port,val,fn1,on_caller_QMARK_){ var temp__4655__auto__ = cljs.core.async.impl.protocols.put_BANG_(port,val,cljs.core.async.fn_handler.cljs$core$IFn$_invoke$arity$1(fn1)); if(cljs.core.truth_(temp__4655__auto__)){ var retb = temp__4655__auto__; var ret = cljs.core.deref(retb); if(cljs.core.truth_(on_caller_QMARK_)){ (fn1.cljs$core$IFn$_invoke$arity$1 ? fn1.cljs$core$IFn$_invoke$arity$1(ret) : fn1.call(null,ret)); } else { cljs.core.async.impl.dispatch.run(((function (ret,retb,temp__4655__auto__){ return (function (){ return (fn1.cljs$core$IFn$_invoke$arity$1 ? fn1.cljs$core$IFn$_invoke$arity$1(ret) : fn1.call(null,ret)); });})(ret,retb,temp__4655__auto__)) ); } return ret; } else { return true; } }); cljs.core.async.put_BANG_.cljs$lang$maxFixedArity = 4; cljs.core.async.close_BANG_ = (function cljs$core$async$close_BANG_(port){ return cljs.core.async.impl.protocols.close_BANG_(port); }); cljs.core.async.random_array = (function cljs$core$async$random_array(n){ var a = (new Array(n)); var n__8615__auto___15502 = n; var x_15503 = (0); while(true){ if((x_15503 < n__8615__auto___15502)){ (a[x_15503] = (0)); var G__15504 = (x_15503 + (1)); x_15503 = G__15504; continue; } else { } break; } var i = (1); while(true){ if(cljs.core._EQ_.cljs$core$IFn$_invoke$arity$2(i,n)){ return a; } else { var j = cljs.core.rand_int(i); (a[i] = (a[j])); (a[j] = i); var G__15505 = (i + (1)); i = G__15505; continue; } break; } }); cljs.core.async.alt_flag = (function cljs$core$async$alt_flag(){ var flag = cljs.core.atom.cljs$core$IFn$_invoke$arity$1(true); if(typeof cljs.core.async.t_cljs$core$async15506 !== 'undefined'){ } else { /** * @constructor * @implements {cljs.core.async.impl.protocols.Handler} * @implements {cljs.core.IMeta} * @implements {cljs.core.IWithMeta} */ cljs.core.async.t_cljs$core$async15506 = (function (flag,meta15507){ this.flag = flag; this.meta15507 = meta15507; this.cljs$lang$protocol_mask$partition0$ = 393216; this.cljs$lang$protocol_mask$partition1$ = 0; }); cljs.core.async.t_cljs$core$async15506.prototype.cljs$core$IWithMeta$_with_meta$arity$2 = ((function (flag){ return (function (_15508,meta15507__$1){ var self__ = this; var _15508__$1 = this; return (new cljs.core.async.t_cljs$core$async15506(self__.flag,meta15507__$1)); });})(flag)) ; cljs.core.async.t_cljs$core$async15506.prototype.cljs$core$IMeta$_meta$arity$1 = ((function (flag){ return (function (_15508){ var self__ = this; var _15508__$1 = this; return self__.meta15507; });})(flag)) ; cljs.core.async.t_cljs$core$async15506.prototype.cljs$core$async$impl$protocols$Handler$ = cljs.core.PROTOCOL_SENTINEL; cljs.core.async.t_cljs$core$async15506.prototype.cljs$core$async$impl$protocols$Handler$active_QMARK_$arity$1 = ((function (flag){ return (function (_){ var self__ = this; var ___$1 = this; return cljs.core.deref(self__.flag); });})(flag)) ; cljs.core.async.t_cljs$core$async15506.prototype.cljs$core$async$impl$protocols$Handler$blockable_QMARK_$arity$1 = ((function (flag){ return (function (_){ var self__ = this; var ___$1 = this; return true; });})(flag)) ; cljs.core.async.t_cljs$core$async15506.prototype.cljs$core$async$impl$protocols$Handler$commit$arity$1 = ((function (flag){ return (function (_){ var self__ = this; var ___$1 = this; cljs.core.reset_BANG_(self__.flag,null); return true; });})(flag)) ; cljs.core.async.t_cljs$core$async15506.getBasis = ((function (flag){ return (function (){ return new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.cst$sym$flag,cljs.core.cst$sym$meta15507], null); });})(flag)) ; cljs.core.async.t_cljs$core$async15506.cljs$lang$type = true; cljs.core.async.t_cljs$core$async15506.cljs$lang$ctorStr = "cljs.core.async/t_cljs$core$async15506"; cljs.core.async.t_cljs$core$async15506.cljs$lang$ctorPrWriter = ((function (flag){ return (function (this__8293__auto__,writer__8294__auto__,opt__8295__auto__){ return cljs.core._write(writer__8294__auto__,"cljs.core.async/t_cljs$core$async15506"); });})(flag)) ; cljs.core.async.__GT_t_cljs$core$async15506 = ((function (flag){ return (function cljs$core$async$alt_flag_$___GT_t_cljs$core$async15506(flag__$1,meta15507){ return (new cljs.core.async.t_cljs$core$async15506(flag__$1,meta15507)); });})(flag)) ; } return (new cljs.core.async.t_cljs$core$async15506(flag,cljs.core.PersistentArrayMap.EMPTY)); }); cljs.core.async.alt_handler = (function cljs$core$async$alt_handler(flag,cb){ if(typeof cljs.core.async.t_cljs$core$async15509 !== 'undefined'){ } else { /** * @constructor * @implements {cljs.core.async.impl.protocols.Handler} * @implements {cljs.core.IMeta} * @implements {cljs.core.IWithMeta} */ cljs.core.async.t_cljs$core$async15509 = (function (flag,cb,meta15510){ this.flag = flag; this.cb = cb; this.meta15510 = meta15510; this.cljs$lang$protocol_mask$partition0$ = 393216; this.cljs$lang$protocol_mask$partition1$ = 0; }); cljs.core.async.t_cljs$core$async15509.prototype.cljs$core$IWithMeta$_with_meta$arity$2 = (function (_15511,meta15510__$1){ var self__ = this; var _15511__$1 = this; return (new cljs.core.async.t_cljs$core$async15509(self__.flag,self__.cb,meta15510__$1)); }); cljs.core.async.t_cljs$core$async15509.prototype.cljs$core$IMeta$_meta$arity$1 = (function (_15511){ var self__ = this; var _15511__$1 = this; return self__.meta15510; }); cljs.core.async.t_cljs$core$async15509.prototype.cljs$core$async$impl$protocols$Handler$ = cljs.core.PROTOCOL_SENTINEL; cljs.core.async.t_cljs$core$async15509.prototype.cljs$core$async$impl$protocols$Handler$active_QMARK_$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return cljs.core.async.impl.protocols.active_QMARK_(self__.flag); }); cljs.core.async.t_cljs$core$async15509.prototype.cljs$core$async$impl$protocols$Handler$blockable_QMARK_$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return true; }); cljs.core.async.t_cljs$core$async15509.prototype.cljs$core$async$impl$protocols$Handler$commit$arity$1 = (function (_){ var self__ = this; var ___$1 = this; cljs.core.async.impl.protocols.commit(self__.flag); return self__.cb; }); cljs.core.async.t_cljs$core$async15509.getBasis = (function (){ return new cljs.core.PersistentVector(null, 3, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.cst$sym$flag,cljs.core.cst$sym$cb,cljs.core.cst$sym$meta15510], null); }); cljs.core.async.t_cljs$core$async15509.cljs$lang$type = true; cljs.core.async.t_cljs$core$async15509.cljs$lang$ctorStr = "cljs.core.async/t_cljs$core$async15509"; cljs.core.async.t_cljs$core$async15509.cljs$lang$ctorPrWriter = (function (this__8293__auto__,writer__8294__auto__,opt__8295__auto__){ return cljs.core._write(writer__8294__auto__,"cljs.core.async/t_cljs$core$async15509"); }); cljs.core.async.__GT_t_cljs$core$async15509 = (function cljs$core$async$alt_handler_$___GT_t_cljs$core$async15509(flag__$1,cb__$1,meta15510){ return (new cljs.core.async.t_cljs$core$async15509(flag__$1,cb__$1,meta15510)); }); } return (new cljs.core.async.t_cljs$core$async15509(flag,cb,cljs.core.PersistentArrayMap.EMPTY)); }); /** * returns derefable [val port] if immediate, nil if enqueued */ cljs.core.async.do_alts = (function cljs$core$async$do_alts(fret,ports,opts){ var flag = cljs.core.async.alt_flag(); var n = cljs.core.count(ports); var idxs = cljs.core.async.random_array(n); var priority = cljs.core.cst$kw$priority.cljs$core$IFn$_invoke$arity$1(opts); var ret = (function (){var i = (0); while(true){ if((i < n)){ var idx = (cljs.core.truth_(priority)?i:(idxs[i])); var port = cljs.core.nth.cljs$core$IFn$_invoke$arity$2(ports,idx); var wport = ((cljs.core.vector_QMARK_(port))?(port.cljs$core$IFn$_invoke$arity$1 ? port.cljs$core$IFn$_invoke$arity$1((0)) : port.call(null,(0))):null); var vbox = (cljs.core.truth_(wport)?(function (){var val = (port.cljs$core$IFn$_invoke$arity$1 ? port.cljs$core$IFn$_invoke$arity$1((1)) : port.call(null,(1))); return cljs.core.async.impl.protocols.put_BANG_(wport,val,cljs.core.async.alt_handler(flag,((function (i,val,idx,port,wport,flag,n,idxs,priority){ return (function (p1__15512_SHARP_){ var G__15514 = new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [p1__15512_SHARP_,wport], null); return (fret.cljs$core$IFn$_invoke$arity$1 ? fret.cljs$core$IFn$_invoke$arity$1(G__15514) : fret.call(null,G__15514)); });})(i,val,idx,port,wport,flag,n,idxs,priority)) )); })():cljs.core.async.impl.protocols.take_BANG_(port,cljs.core.async.alt_handler(flag,((function (i,idx,port,wport,flag,n,idxs,priority){ return (function (p1__15513_SHARP_){ var G__15515 = new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [p1__15513_SHARP_,port], null); return (fret.cljs$core$IFn$_invoke$arity$1 ? fret.cljs$core$IFn$_invoke$arity$1(G__15515) : fret.call(null,G__15515)); });})(i,idx,port,wport,flag,n,idxs,priority)) ))); if(cljs.core.truth_(vbox)){ return cljs.core.async.impl.channels.box(new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.deref(vbox),(function (){var or__7668__auto__ = wport; if(cljs.core.truth_(or__7668__auto__)){ return or__7668__auto__; } else { return port; } })()], null)); } else { var G__15516 = (i + (1)); i = G__15516; continue; } } else { return null; } break; } })(); var or__7668__auto__ = ret; if(cljs.core.truth_(or__7668__auto__)){ return or__7668__auto__; } else { if(cljs.core.contains_QMARK_(opts,cljs.core.cst$kw$default)){ var temp__4657__auto__ = (function (){var and__7656__auto__ = cljs.core.async.impl.protocols.active_QMARK_(flag); if(cljs.core.truth_(and__7656__auto__)){ return cljs.core.async.impl.protocols.commit(flag); } else { return and__7656__auto__; } })(); if(cljs.core.truth_(temp__4657__auto__)){ var got = temp__4657__auto__; return cljs.core.async.impl.channels.box(new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.cst$kw$default.cljs$core$IFn$_invoke$arity$1(opts),cljs.core.cst$kw$default], null)); } else { return null; } } else { return null; } } }); /** * Completes at most one of several channel operations. Must be called * inside a (go ...) block. ports is a vector of channel endpoints, * which can be either a channel to take from or a vector of * [channel-to-put-to val-to-put], in any combination. Takes will be * made as if by <!, and puts will be made as if by >!. Unless * the :priority option is true, if more than one port operation is * ready a non-deterministic choice will be made. If no operation is * ready and a :default value is supplied, [default-val :default] will * be returned, otherwise alts! will park until the first operation to * become ready completes. Returns [val port] of the completed * operation, where val is the value taken for takes, and a * boolean (true unless already closed, as per put!) for puts. * * opts are passed as :key val ... Supported options: * * :default val - the value to use if none of the operations are immediately ready * :priority true - (default nil) when true, the operations will be tried in order. * * Note: there is no guarantee that the port exps or val exprs will be * used, nor in what order should they be, so they should not be * depended upon for side effects. */ cljs.core.async.alts_BANG_ = (function cljs$core$async$alts_BANG_(var_args){ var args__8835__auto__ = []; var len__8828__auto___15522 = arguments.length; var i__8829__auto___15523 = (0); while(true){ if((i__8829__auto___15523 < len__8828__auto___15522)){ args__8835__auto__.push((arguments[i__8829__auto___15523])); var G__15524 = (i__8829__auto___15523 + (1)); i__8829__auto___15523 = G__15524; continue; } else { } break; } var argseq__8836__auto__ = ((((1) < args__8835__auto__.length))?(new cljs.core.IndexedSeq(args__8835__auto__.slice((1)),(0),null)):null); return cljs.core.async.alts_BANG_.cljs$core$IFn$_invoke$arity$variadic((arguments[(0)]),argseq__8836__auto__); }); cljs.core.async.alts_BANG_.cljs$core$IFn$_invoke$arity$variadic = (function (ports,p__15519){ var map__15520 = p__15519; var map__15520__$1 = ((((!((map__15520 == null)))?((((map__15520.cljs$lang$protocol_mask$partition0$ & (64))) || ((cljs.core.PROTOCOL_SENTINEL === map__15520.cljs$core$ISeq$)))?true:false):false))?cljs.core.apply.cljs$core$IFn$_invoke$arity$2(cljs.core.hash_map,map__15520):map__15520); var opts = map__15520__$1; throw (new Error("alts! used not in (go ...) block")); }); cljs.core.async.alts_BANG_.cljs$lang$maxFixedArity = (1); cljs.core.async.alts_BANG_.cljs$lang$applyTo = (function (seq15517){ var G__15518 = cljs.core.first(seq15517); var seq15517__$1 = cljs.core.next(seq15517); return cljs.core.async.alts_BANG_.cljs$core$IFn$_invoke$arity$variadic(G__15518,seq15517__$1); }); /** * Puts a val into port if it's possible to do so immediately. * nil values are not allowed. Never blocks. Returns true if offer succeeds. */ cljs.core.async.offer_BANG_ = (function cljs$core$async$offer_BANG_(port,val){ var ret = cljs.core.async.impl.protocols.put_BANG_(port,val,cljs.core.async.fn_handler.cljs$core$IFn$_invoke$arity$2(cljs.core.async.nop,false)); if(cljs.core.truth_(ret)){ return cljs.core.deref(ret); } else { return null; } }); /** * Takes a val from port if it's possible to do so immediately. * Never blocks. Returns value if successful, nil otherwise. */ cljs.core.async.poll_BANG_ = (function cljs$core$async$poll_BANG_(port){ var ret = cljs.core.async.impl.protocols.take_BANG_(port,cljs.core.async.fn_handler.cljs$core$IFn$_invoke$arity$2(cljs.core.async.nop,false)); if(cljs.core.truth_(ret)){ return cljs.core.deref(ret); } else { return null; } }); /** * Takes elements from the from channel and supplies them to the to * channel. By default, the to channel will be closed when the from * channel closes, but can be determined by the close? parameter. Will * stop consuming the from channel if the to channel closes */ cljs.core.async.pipe = (function cljs$core$async$pipe(var_args){ var G__15526 = arguments.length; switch (G__15526) { case 2: return cljs.core.async.pipe.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; case 3: return cljs.core.async.pipe.cljs$core$IFn$_invoke$arity$3((arguments[(0)]),(arguments[(1)]),(arguments[(2)])); break; default: throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join(''))); } }); cljs.core.async.pipe.cljs$core$IFn$_invoke$arity$2 = (function (from,to){ return cljs.core.async.pipe.cljs$core$IFn$_invoke$arity$3(from,to,true); }); cljs.core.async.pipe.cljs$core$IFn$_invoke$arity$3 = (function (from,to,close_QMARK_){ var c__15437__auto___15572 = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1((1)); cljs.core.async.impl.dispatch.run(((function (c__15437__auto___15572){ return (function (){ var f__15438__auto__ = (function (){var switch__15337__auto__ = ((function (c__15437__auto___15572){ return (function (state_15550){ var state_val_15551 = (state_15550[(1)]); if((state_val_15551 === (7))){ var inst_15546 = (state_15550[(2)]); var state_15550__$1 = state_15550; var statearr_15552_15573 = state_15550__$1; (statearr_15552_15573[(2)] = inst_15546); (statearr_15552_15573[(1)] = (3)); return cljs.core.cst$kw$recur; } else { if((state_val_15551 === (1))){ var state_15550__$1 = state_15550; var statearr_15553_15574 = state_15550__$1; (statearr_15553_15574[(2)] = null); (statearr_15553_15574[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_15551 === (4))){ var inst_15529 = (state_15550[(7)]); var inst_15529__$1 = (state_15550[(2)]); var inst_15530 = (inst_15529__$1 == null); var state_15550__$1 = (function (){var statearr_15554 = state_15550; (statearr_15554[(7)] = inst_15529__$1); return statearr_15554; })(); if(cljs.core.truth_(inst_15530)){ var statearr_15555_15575 = state_15550__$1; (statearr_15555_15575[(1)] = (5)); } else { var statearr_15556_15576 = state_15550__$1; (statearr_15556_15576[(1)] = (6)); } return cljs.core.cst$kw$recur; } else { if((state_val_15551 === (13))){ var state_15550__$1 = state_15550; var statearr_15557_15577 = state_15550__$1; (statearr_15557_15577[(2)] = null); (statearr_15557_15577[(1)] = (14)); return cljs.core.cst$kw$recur; } else { if((state_val_15551 === (6))){ var inst_15529 = (state_15550[(7)]); var state_15550__$1 = state_15550; return cljs.core.async.impl.ioc_helpers.put_BANG_(state_15550__$1,(11),to,inst_15529); } else { if((state_val_15551 === (3))){ var inst_15548 = (state_15550[(2)]); var state_15550__$1 = state_15550; return cljs.core.async.impl.ioc_helpers.return_chan(state_15550__$1,inst_15548); } else { if((state_val_15551 === (12))){ var state_15550__$1 = state_15550; var statearr_15558_15578 = state_15550__$1; (statearr_15558_15578[(2)] = null); (statearr_15558_15578[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_15551 === (2))){ var state_15550__$1 = state_15550; return cljs.core.async.impl.ioc_helpers.take_BANG_(state_15550__$1,(4),from); } else { if((state_val_15551 === (11))){ var inst_15539 = (state_15550[(2)]); var state_15550__$1 = state_15550; if(cljs.core.truth_(inst_15539)){ var statearr_15559_15579 = state_15550__$1; (statearr_15559_15579[(1)] = (12)); } else { var statearr_15560_15580 = state_15550__$1; (statearr_15560_15580[(1)] = (13)); } return cljs.core.cst$kw$recur; } else { if((state_val_15551 === (9))){ var state_15550__$1 = state_15550; var statearr_15561_15581 = state_15550__$1; (statearr_15561_15581[(2)] = null); (statearr_15561_15581[(1)] = (10)); return cljs.core.cst$kw$recur; } else { if((state_val_15551 === (5))){ var state_15550__$1 = state_15550; if(cljs.core.truth_(close_QMARK_)){ var statearr_15562_15582 = state_15550__$1; (statearr_15562_15582[(1)] = (8)); } else { var statearr_15563_15583 = state_15550__$1; (statearr_15563_15583[(1)] = (9)); } return cljs.core.cst$kw$recur; } else { if((state_val_15551 === (14))){ var inst_15544 = (state_15550[(2)]); var state_15550__$1 = state_15550; var statearr_15564_15584 = state_15550__$1; (statearr_15564_15584[(2)] = inst_15544); (statearr_15564_15584[(1)] = (7)); return cljs.core.cst$kw$recur; } else { if((state_val_15551 === (10))){ var inst_15536 = (state_15550[(2)]); var state_15550__$1 = state_15550; var statearr_15565_15585 = state_15550__$1; (statearr_15565_15585[(2)] = inst_15536); (statearr_15565_15585[(1)] = (7)); return cljs.core.cst$kw$recur; } else { if((state_val_15551 === (8))){ var inst_15533 = cljs.core.async.close_BANG_(to); var state_15550__$1 = state_15550; var statearr_15566_15586 = state_15550__$1; (statearr_15566_15586[(2)] = inst_15533); (statearr_15566_15586[(1)] = (10)); return cljs.core.cst$kw$recur; } else { return null; } } } } } } } } } } } } } } });})(c__15437__auto___15572)) ; return ((function (switch__15337__auto__,c__15437__auto___15572){ return (function() { var cljs$core$async$state_machine__15338__auto__ = null; var cljs$core$async$state_machine__15338__auto____0 = (function (){ var statearr_15567 = [null,null,null,null,null,null,null,null]; (statearr_15567[(0)] = cljs$core$async$state_machine__15338__auto__); (statearr_15567[(1)] = (1)); return statearr_15567; }); var cljs$core$async$state_machine__15338__auto____1 = (function (state_15550){ while(true){ var ret_value__15339__auto__ = (function (){try{while(true){ var result__15340__auto__ = switch__15337__auto__(state_15550); if(cljs.core.keyword_identical_QMARK_(result__15340__auto__,cljs.core.cst$kw$recur)){ continue; } else { return result__15340__auto__; } break; } }catch (e15568){if((e15568 instanceof Object)){ var ex__15341__auto__ = e15568; var statearr_15569_15587 = state_15550; (statearr_15569_15587[(5)] = ex__15341__auto__); cljs.core.async.impl.ioc_helpers.process_exception(state_15550); return cljs.core.cst$kw$recur; } else { throw e15568; } }})(); if(cljs.core.keyword_identical_QMARK_(ret_value__15339__auto__,cljs.core.cst$kw$recur)){ var G__15588 = state_15550; state_15550 = G__15588; continue; } else { return ret_value__15339__auto__; } break; } }); cljs$core$async$state_machine__15338__auto__ = function(state_15550){ switch(arguments.length){ case 0: return cljs$core$async$state_machine__15338__auto____0.call(this); case 1: return cljs$core$async$state_machine__15338__auto____1.call(this,state_15550); } throw(new Error('Invalid arity: ' + (arguments.length - 1))); }; cljs$core$async$state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$0 = cljs$core$async$state_machine__15338__auto____0; cljs$core$async$state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$1 = cljs$core$async$state_machine__15338__auto____1; return cljs$core$async$state_machine__15338__auto__; })() ;})(switch__15337__auto__,c__15437__auto___15572)) })(); var state__15439__auto__ = (function (){var statearr_15570 = (f__15438__auto__.cljs$core$IFn$_invoke$arity$0 ? f__15438__auto__.cljs$core$IFn$_invoke$arity$0() : f__15438__auto__.call(null)); (statearr_15570[(6)] = c__15437__auto___15572); return statearr_15570; })(); return cljs.core.async.impl.ioc_helpers.run_state_machine_wrapped(state__15439__auto__); });})(c__15437__auto___15572)) ); return to; }); cljs.core.async.pipe.cljs$lang$maxFixedArity = 3; cljs.core.async.pipeline_STAR_ = (function cljs$core$async$pipeline_STAR_(n,to,xf,from,close_QMARK_,ex_handler,type){ var jobs = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1(n); var results = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1(n); var process = ((function (jobs,results){ return (function (p__15589){ var vec__15590 = p__15589; var v = cljs.core.nth.cljs$core$IFn$_invoke$arity$3(vec__15590,(0),null); var p = cljs.core.nth.cljs$core$IFn$_invoke$arity$3(vec__15590,(1),null); var job = vec__15590; if((job == null)){ cljs.core.async.close_BANG_(results); return null; } else { var res = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$3((1),xf,ex_handler); var c__15437__auto___15761 = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1((1)); cljs.core.async.impl.dispatch.run(((function (c__15437__auto___15761,res,vec__15590,v,p,job,jobs,results){ return (function (){ var f__15438__auto__ = (function (){var switch__15337__auto__ = ((function (c__15437__auto___15761,res,vec__15590,v,p,job,jobs,results){ return (function (state_15597){ var state_val_15598 = (state_15597[(1)]); if((state_val_15598 === (1))){ var state_15597__$1 = state_15597; return cljs.core.async.impl.ioc_helpers.put_BANG_(state_15597__$1,(2),res,v); } else { if((state_val_15598 === (2))){ var inst_15594 = (state_15597[(2)]); var inst_15595 = cljs.core.async.close_BANG_(res); var state_15597__$1 = (function (){var statearr_15599 = state_15597; (statearr_15599[(7)] = inst_15594); return statearr_15599; })(); return cljs.core.async.impl.ioc_helpers.return_chan(state_15597__$1,inst_15595); } else { return null; } } });})(c__15437__auto___15761,res,vec__15590,v,p,job,jobs,results)) ; return ((function (switch__15337__auto__,c__15437__auto___15761,res,vec__15590,v,p,job,jobs,results){ return (function() { var cljs$core$async$pipeline_STAR__$_state_machine__15338__auto__ = null; var cljs$core$async$pipeline_STAR__$_state_machine__15338__auto____0 = (function (){ var statearr_15600 = [null,null,null,null,null,null,null,null]; (statearr_15600[(0)] = cljs$core$async$pipeline_STAR__$_state_machine__15338__auto__); (statearr_15600[(1)] = (1)); return statearr_15600; }); var cljs$core$async$pipeline_STAR__$_state_machine__15338__auto____1 = (function (state_15597){ while(true){ var ret_value__15339__auto__ = (function (){try{while(true){ var result__15340__auto__ = switch__15337__auto__(state_15597); if(cljs.core.keyword_identical_QMARK_(result__15340__auto__,cljs.core.cst$kw$recur)){ continue; } else { return result__15340__auto__; } break; } }catch (e15601){if((e15601 instanceof Object)){ var ex__15341__auto__ = e15601; var statearr_15602_15762 = state_15597; (statearr_15602_15762[(5)] = ex__15341__auto__); cljs.core.async.impl.ioc_helpers.process_exception(state_15597); return cljs.core.cst$kw$recur; } else { throw e15601; } }})(); if(cljs.core.keyword_identical_QMARK_(ret_value__15339__auto__,cljs.core.cst$kw$recur)){ var G__15763 = state_15597; state_15597 = G__15763; continue; } else { return ret_value__15339__auto__; } break; } }); cljs$core$async$pipeline_STAR__$_state_machine__15338__auto__ = function(state_15597){ switch(arguments.length){ case 0: return cljs$core$async$pipeline_STAR__$_state_machine__15338__auto____0.call(this); case 1: return cljs$core$async$pipeline_STAR__$_state_machine__15338__auto____1.call(this,state_15597); } throw(new Error('Invalid arity: ' + (arguments.length - 1))); }; cljs$core$async$pipeline_STAR__$_state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$0 = cljs$core$async$pipeline_STAR__$_state_machine__15338__auto____0; cljs$core$async$pipeline_STAR__$_state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$1 = cljs$core$async$pipeline_STAR__$_state_machine__15338__auto____1; return cljs$core$async$pipeline_STAR__$_state_machine__15338__auto__; })() ;})(switch__15337__auto__,c__15437__auto___15761,res,vec__15590,v,p,job,jobs,results)) })(); var state__15439__auto__ = (function (){var statearr_15603 = (f__15438__auto__.cljs$core$IFn$_invoke$arity$0 ? f__15438__auto__.cljs$core$IFn$_invoke$arity$0() : f__15438__auto__.call(null)); (statearr_15603[(6)] = c__15437__auto___15761); return statearr_15603; })(); return cljs.core.async.impl.ioc_helpers.run_state_machine_wrapped(state__15439__auto__); });})(c__15437__auto___15761,res,vec__15590,v,p,job,jobs,results)) ); cljs.core.async.put_BANG_.cljs$core$IFn$_invoke$arity$2(p,res); return true; } });})(jobs,results)) ; var async = ((function (jobs,results,process){ return (function (p__15604){ var vec__15605 = p__15604; var v = cljs.core.nth.cljs$core$IFn$_invoke$arity$3(vec__15605,(0),null); var p = cljs.core.nth.cljs$core$IFn$_invoke$arity$3(vec__15605,(1),null); var job = vec__15605; if((job == null)){ cljs.core.async.close_BANG_(results); return null; } else { var res = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1((1)); (xf.cljs$core$IFn$_invoke$arity$2 ? xf.cljs$core$IFn$_invoke$arity$2(v,res) : xf.call(null,v,res)); cljs.core.async.put_BANG_.cljs$core$IFn$_invoke$arity$2(p,res); return true; } });})(jobs,results,process)) ; var n__8615__auto___15764 = n; var __15765 = (0); while(true){ if((__15765 < n__8615__auto___15764)){ var G__15608_15766 = type; var G__15608_15767__$1 = (((G__15608_15766 instanceof cljs.core.Keyword))?G__15608_15766.fqn:null); switch (G__15608_15767__$1) { case "compute": var c__15437__auto___15769 = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1((1)); cljs.core.async.impl.dispatch.run(((function (__15765,c__15437__auto___15769,G__15608_15766,G__15608_15767__$1,n__8615__auto___15764,jobs,results,process,async){ return (function (){ var f__15438__auto__ = (function (){var switch__15337__auto__ = ((function (__15765,c__15437__auto___15769,G__15608_15766,G__15608_15767__$1,n__8615__auto___15764,jobs,results,process,async){ return (function (state_15621){ var state_val_15622 = (state_15621[(1)]); if((state_val_15622 === (1))){ var state_15621__$1 = state_15621; var statearr_15623_15770 = state_15621__$1; (statearr_15623_15770[(2)] = null); (statearr_15623_15770[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_15622 === (2))){ var state_15621__$1 = state_15621; return cljs.core.async.impl.ioc_helpers.take_BANG_(state_15621__$1,(4),jobs); } else { if((state_val_15622 === (3))){ var inst_15619 = (state_15621[(2)]); var state_15621__$1 = state_15621; return cljs.core.async.impl.ioc_helpers.return_chan(state_15621__$1,inst_15619); } else { if((state_val_15622 === (4))){ var inst_15611 = (state_15621[(2)]); var inst_15612 = process(inst_15611); var state_15621__$1 = state_15621; if(cljs.core.truth_(inst_15612)){ var statearr_15624_15771 = state_15621__$1; (statearr_15624_15771[(1)] = (5)); } else { var statearr_15625_15772 = state_15621__$1; (statearr_15625_15772[(1)] = (6)); } return cljs.core.cst$kw$recur; } else { if((state_val_15622 === (5))){ var state_15621__$1 = state_15621; var statearr_15626_15773 = state_15621__$1; (statearr_15626_15773[(2)] = null); (statearr_15626_15773[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_15622 === (6))){ var state_15621__$1 = state_15621; var statearr_15627_15774 = state_15621__$1; (statearr_15627_15774[(2)] = null); (statearr_15627_15774[(1)] = (7)); return cljs.core.cst$kw$recur; } else { if((state_val_15622 === (7))){ var inst_15617 = (state_15621[(2)]); var state_15621__$1 = state_15621; var statearr_15628_15775 = state_15621__$1; (statearr_15628_15775[(2)] = inst_15617); (statearr_15628_15775[(1)] = (3)); return cljs.core.cst$kw$recur; } else { return null; } } } } } } } });})(__15765,c__15437__auto___15769,G__15608_15766,G__15608_15767__$1,n__8615__auto___15764,jobs,results,process,async)) ; return ((function (__15765,switch__15337__auto__,c__15437__auto___15769,G__15608_15766,G__15608_15767__$1,n__8615__auto___15764,jobs,results,process,async){ return (function() { var cljs$core$async$pipeline_STAR__$_state_machine__15338__auto__ = null; var cljs$core$async$pipeline_STAR__$_state_machine__15338__auto____0 = (function (){ var statearr_15629 = [null,null,null,null,null,null,null]; (statearr_15629[(0)] = cljs$core$async$pipeline_STAR__$_state_machine__15338__auto__); (statearr_15629[(1)] = (1)); return statearr_15629; }); var cljs$core$async$pipeline_STAR__$_state_machine__15338__auto____1 = (function (state_15621){ while(true){ var ret_value__15339__auto__ = (function (){try{while(true){ var result__15340__auto__ = switch__15337__auto__(state_15621); if(cljs.core.keyword_identical_QMARK_(result__15340__auto__,cljs.core.cst$kw$recur)){ continue; } else { return result__15340__auto__; } break; } }catch (e15630){if((e15630 instanceof Object)){ var ex__15341__auto__ = e15630; var statearr_15631_15776 = state_15621; (statearr_15631_15776[(5)] = ex__15341__auto__); cljs.core.async.impl.ioc_helpers.process_exception(state_15621); return cljs.core.cst$kw$recur; } else { throw e15630; } }})(); if(cljs.core.keyword_identical_QMARK_(ret_value__15339__auto__,cljs.core.cst$kw$recur)){ var G__15777 = state_15621; state_15621 = G__15777; continue; } else { return ret_value__15339__auto__; } break; } }); cljs$core$async$pipeline_STAR__$_state_machine__15338__auto__ = function(state_15621){ switch(arguments.length){ case 0: return cljs$core$async$pipeline_STAR__$_state_machine__15338__auto____0.call(this); case 1: return cljs$core$async$pipeline_STAR__$_state_machine__15338__auto____1.call(this,state_15621); } throw(new Error('Invalid arity: ' + (arguments.length - 1))); }; cljs$core$async$pipeline_STAR__$_state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$0 = cljs$core$async$pipeline_STAR__$_state_machine__15338__auto____0; cljs$core$async$pipeline_STAR__$_state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$1 = cljs$core$async$pipeline_STAR__$_state_machine__15338__auto____1; return cljs$core$async$pipeline_STAR__$_state_machine__15338__auto__; })() ;})(__15765,switch__15337__auto__,c__15437__auto___15769,G__15608_15766,G__15608_15767__$1,n__8615__auto___15764,jobs,results,process,async)) })(); var state__15439__auto__ = (function (){var statearr_15632 = (f__15438__auto__.cljs$core$IFn$_invoke$arity$0 ? f__15438__auto__.cljs$core$IFn$_invoke$arity$0() : f__15438__auto__.call(null)); (statearr_15632[(6)] = c__15437__auto___15769); return statearr_15632; })(); return cljs.core.async.impl.ioc_helpers.run_state_machine_wrapped(state__15439__auto__); });})(__15765,c__15437__auto___15769,G__15608_15766,G__15608_15767__$1,n__8615__auto___15764,jobs,results,process,async)) ); break; case "async": var c__15437__auto___15778 = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1((1)); cljs.core.async.impl.dispatch.run(((function (__15765,c__15437__auto___15778,G__15608_15766,G__15608_15767__$1,n__8615__auto___15764,jobs,results,process,async){ return (function (){ var f__15438__auto__ = (function (){var switch__15337__auto__ = ((function (__15765,c__15437__auto___15778,G__15608_15766,G__15608_15767__$1,n__8615__auto___15764,jobs,results,process,async){ return (function (state_15645){ var state_val_15646 = (state_15645[(1)]); if((state_val_15646 === (1))){ var state_15645__$1 = state_15645; var statearr_15647_15779 = state_15645__$1; (statearr_15647_15779[(2)] = null); (statearr_15647_15779[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_15646 === (2))){ var state_15645__$1 = state_15645; return cljs.core.async.impl.ioc_helpers.take_BANG_(state_15645__$1,(4),jobs); } else { if((state_val_15646 === (3))){ var inst_15643 = (state_15645[(2)]); var state_15645__$1 = state_15645; return cljs.core.async.impl.ioc_helpers.return_chan(state_15645__$1,inst_15643); } else { if((state_val_15646 === (4))){ var inst_15635 = (state_15645[(2)]); var inst_15636 = async(inst_15635); var state_15645__$1 = state_15645; if(cljs.core.truth_(inst_15636)){ var statearr_15648_15780 = state_15645__$1; (statearr_15648_15780[(1)] = (5)); } else { var statearr_15649_15781 = state_15645__$1; (statearr_15649_15781[(1)] = (6)); } return cljs.core.cst$kw$recur; } else { if((state_val_15646 === (5))){ var state_15645__$1 = state_15645; var statearr_15650_15782 = state_15645__$1; (statearr_15650_15782[(2)] = null); (statearr_15650_15782[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_15646 === (6))){ var state_15645__$1 = state_15645; var statearr_15651_15783 = state_15645__$1; (statearr_15651_15783[(2)] = null); (statearr_15651_15783[(1)] = (7)); return cljs.core.cst$kw$recur; } else { if((state_val_15646 === (7))){ var inst_15641 = (state_15645[(2)]); var state_15645__$1 = state_15645; var statearr_15652_15784 = state_15645__$1; (statearr_15652_15784[(2)] = inst_15641); (statearr_15652_15784[(1)] = (3)); return cljs.core.cst$kw$recur; } else { return null; } } } } } } } });})(__15765,c__15437__auto___15778,G__15608_15766,G__15608_15767__$1,n__8615__auto___15764,jobs,results,process,async)) ; return ((function (__15765,switch__15337__auto__,c__15437__auto___15778,G__15608_15766,G__15608_15767__$1,n__8615__auto___15764,jobs,results,process,async){ return (function() { var cljs$core$async$pipeline_STAR__$_state_machine__15338__auto__ = null; var cljs$core$async$pipeline_STAR__$_state_machine__15338__auto____0 = (function (){ var statearr_15653 = [null,null,null,null,null,null,null]; (statearr_15653[(0)] = cljs$core$async$pipeline_STAR__$_state_machine__15338__auto__); (statearr_15653[(1)] = (1)); return statearr_15653; }); var cljs$core$async$pipeline_STAR__$_state_machine__15338__auto____1 = (function (state_15645){ while(true){ var ret_value__15339__auto__ = (function (){try{while(true){ var result__15340__auto__ = switch__15337__auto__(state_15645); if(cljs.core.keyword_identical_QMARK_(result__15340__auto__,cljs.core.cst$kw$recur)){ continue; } else { return result__15340__auto__; } break; } }catch (e15654){if((e15654 instanceof Object)){ var ex__15341__auto__ = e15654; var statearr_15655_15785 = state_15645; (statearr_15655_15785[(5)] = ex__15341__auto__); cljs.core.async.impl.ioc_helpers.process_exception(state_15645); return cljs.core.cst$kw$recur; } else { throw e15654; } }})(); if(cljs.core.keyword_identical_QMARK_(ret_value__15339__auto__,cljs.core.cst$kw$recur)){ var G__15786 = state_15645; state_15645 = G__15786; continue; } else { return ret_value__15339__auto__; } break; } }); cljs$core$async$pipeline_STAR__$_state_machine__15338__auto__ = function(state_15645){ switch(arguments.length){ case 0: return cljs$core$async$pipeline_STAR__$_state_machine__15338__auto____0.call(this); case 1: return cljs$core$async$pipeline_STAR__$_state_machine__15338__auto____1.call(this,state_15645); } throw(new Error('Invalid arity: ' + (arguments.length - 1))); }; cljs$core$async$pipeline_STAR__$_state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$0 = cljs$core$async$pipeline_STAR__$_state_machine__15338__auto____0; cljs$core$async$pipeline_STAR__$_state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$1 = cljs$core$async$pipeline_STAR__$_state_machine__15338__auto____1; return cljs$core$async$pipeline_STAR__$_state_machine__15338__auto__; })() ;})(__15765,switch__15337__auto__,c__15437__auto___15778,G__15608_15766,G__15608_15767__$1,n__8615__auto___15764,jobs,results,process,async)) })(); var state__15439__auto__ = (function (){var statearr_15656 = (f__15438__auto__.cljs$core$IFn$_invoke$arity$0 ? f__15438__auto__.cljs$core$IFn$_invoke$arity$0() : f__15438__auto__.call(null)); (statearr_15656[(6)] = c__15437__auto___15778); return statearr_15656; })(); return cljs.core.async.impl.ioc_helpers.run_state_machine_wrapped(state__15439__auto__); });})(__15765,c__15437__auto___15778,G__15608_15766,G__15608_15767__$1,n__8615__auto___15764,jobs,results,process,async)) ); break; default: throw (new Error(["No matching clause: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(G__15608_15767__$1)].join(''))); } var G__15787 = (__15765 + (1)); __15765 = G__15787; continue; } else { } break; } var c__15437__auto___15788 = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1((1)); cljs.core.async.impl.dispatch.run(((function (c__15437__auto___15788,jobs,results,process,async){ return (function (){ var f__15438__auto__ = (function (){var switch__15337__auto__ = ((function (c__15437__auto___15788,jobs,results,process,async){ return (function (state_15678){ var state_val_15679 = (state_15678[(1)]); if((state_val_15679 === (1))){ var state_15678__$1 = state_15678; var statearr_15680_15789 = state_15678__$1; (statearr_15680_15789[(2)] = null); (statearr_15680_15789[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_15679 === (2))){ var state_15678__$1 = state_15678; return cljs.core.async.impl.ioc_helpers.take_BANG_(state_15678__$1,(4),from); } else { if((state_val_15679 === (3))){ var inst_15676 = (state_15678[(2)]); var state_15678__$1 = state_15678; return cljs.core.async.impl.ioc_helpers.return_chan(state_15678__$1,inst_15676); } else { if((state_val_15679 === (4))){ var inst_15659 = (state_15678[(7)]); var inst_15659__$1 = (state_15678[(2)]); var inst_15660 = (inst_15659__$1 == null); var state_15678__$1 = (function (){var statearr_15681 = state_15678; (statearr_15681[(7)] = inst_15659__$1); return statearr_15681; })(); if(cljs.core.truth_(inst_15660)){ var statearr_15682_15790 = state_15678__$1; (statearr_15682_15790[(1)] = (5)); } else { var statearr_15683_15791 = state_15678__$1; (statearr_15683_15791[(1)] = (6)); } return cljs.core.cst$kw$recur; } else { if((state_val_15679 === (5))){ var inst_15662 = cljs.core.async.close_BANG_(jobs); var state_15678__$1 = state_15678; var statearr_15684_15792 = state_15678__$1; (statearr_15684_15792[(2)] = inst_15662); (statearr_15684_15792[(1)] = (7)); return cljs.core.cst$kw$recur; } else { if((state_val_15679 === (6))){ var inst_15659 = (state_15678[(7)]); var inst_15664 = (state_15678[(8)]); var inst_15664__$1 = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1((1)); var inst_15665 = cljs.core.PersistentVector.EMPTY_NODE; var inst_15666 = [inst_15659,inst_15664__$1]; var inst_15667 = (new cljs.core.PersistentVector(null,2,(5),inst_15665,inst_15666,null)); var state_15678__$1 = (function (){var statearr_15685 = state_15678; (statearr_15685[(8)] = inst_15664__$1); return statearr_15685; })(); return cljs.core.async.impl.ioc_helpers.put_BANG_(state_15678__$1,(8),jobs,inst_15667); } else { if((state_val_15679 === (7))){ var inst_15674 = (state_15678[(2)]); var state_15678__$1 = state_15678; var statearr_15686_15793 = state_15678__$1; (statearr_15686_15793[(2)] = inst_15674); (statearr_15686_15793[(1)] = (3)); return cljs.core.cst$kw$recur; } else { if((state_val_15679 === (8))){ var inst_15664 = (state_15678[(8)]); var inst_15669 = (state_15678[(2)]); var state_15678__$1 = (function (){var statearr_15687 = state_15678; (statearr_15687[(9)] = inst_15669); return statearr_15687; })(); return cljs.core.async.impl.ioc_helpers.put_BANG_(state_15678__$1,(9),results,inst_15664); } else { if((state_val_15679 === (9))){ var inst_15671 = (state_15678[(2)]); var state_15678__$1 = (function (){var statearr_15688 = state_15678; (statearr_15688[(10)] = inst_15671); return statearr_15688; })(); var statearr_15689_15794 = state_15678__$1; (statearr_15689_15794[(2)] = null); (statearr_15689_15794[(1)] = (2)); return cljs.core.cst$kw$recur; } else { return null; } } } } } } } } } });})(c__15437__auto___15788,jobs,results,process,async)) ; return ((function (switch__15337__auto__,c__15437__auto___15788,jobs,results,process,async){ return (function() { var cljs$core$async$pipeline_STAR__$_state_machine__15338__auto__ = null; var cljs$core$async$pipeline_STAR__$_state_machine__15338__auto____0 = (function (){ var statearr_15690 = [null,null,null,null,null,null,null,null,null,null,null]; (statearr_15690[(0)] = cljs$core$async$pipeline_STAR__$_state_machine__15338__auto__); (statearr_15690[(1)] = (1)); return statearr_15690; }); var cljs$core$async$pipeline_STAR__$_state_machine__15338__auto____1 = (function (state_15678){ while(true){ var ret_value__15339__auto__ = (function (){try{while(true){ var result__15340__auto__ = switch__15337__auto__(state_15678); if(cljs.core.keyword_identical_QMARK_(result__15340__auto__,cljs.core.cst$kw$recur)){ continue; } else { return result__15340__auto__; } break; } }catch (e15691){if((e15691 instanceof Object)){ var ex__15341__auto__ = e15691; var statearr_15692_15795 = state_15678; (statearr_15692_15795[(5)] = ex__15341__auto__); cljs.core.async.impl.ioc_helpers.process_exception(state_15678); return cljs.core.cst$kw$recur; } else { throw e15691; } }})(); if(cljs.core.keyword_identical_QMARK_(ret_value__15339__auto__,cljs.core.cst$kw$recur)){ var G__15796 = state_15678; state_15678 = G__15796; continue; } else { return ret_value__15339__auto__; } break; } }); cljs$core$async$pipeline_STAR__$_state_machine__15338__auto__ = function(state_15678){ switch(arguments.length){ case 0: return cljs$core$async$pipeline_STAR__$_state_machine__15338__auto____0.call(this); case 1: return cljs$core$async$pipeline_STAR__$_state_machine__15338__auto____1.call(this,state_15678); } throw(new Error('Invalid arity: ' + (arguments.length - 1))); }; cljs$core$async$pipeline_STAR__$_state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$0 = cljs$core$async$pipeline_STAR__$_state_machine__15338__auto____0; cljs$core$async$pipeline_STAR__$_state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$1 = cljs$core$async$pipeline_STAR__$_state_machine__15338__auto____1; return cljs$core$async$pipeline_STAR__$_state_machine__15338__auto__; })() ;})(switch__15337__auto__,c__15437__auto___15788,jobs,results,process,async)) })(); var state__15439__auto__ = (function (){var statearr_15693 = (f__15438__auto__.cljs$core$IFn$_invoke$arity$0 ? f__15438__auto__.cljs$core$IFn$_invoke$arity$0() : f__15438__auto__.call(null)); (statearr_15693[(6)] = c__15437__auto___15788); return statearr_15693; })(); return cljs.core.async.impl.ioc_helpers.run_state_machine_wrapped(state__15439__auto__); });})(c__15437__auto___15788,jobs,results,process,async)) ); var c__15437__auto__ = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1((1)); cljs.core.async.impl.dispatch.run(((function (c__15437__auto__,jobs,results,process,async){ return (function (){ var f__15438__auto__ = (function (){var switch__15337__auto__ = ((function (c__15437__auto__,jobs,results,process,async){ return (function (state_15731){ var state_val_15732 = (state_15731[(1)]); if((state_val_15732 === (7))){ var inst_15727 = (state_15731[(2)]); var state_15731__$1 = state_15731; var statearr_15733_15797 = state_15731__$1; (statearr_15733_15797[(2)] = inst_15727); (statearr_15733_15797[(1)] = (3)); return cljs.core.cst$kw$recur; } else { if((state_val_15732 === (20))){ var state_15731__$1 = state_15731; var statearr_15734_15798 = state_15731__$1; (statearr_15734_15798[(2)] = null); (statearr_15734_15798[(1)] = (21)); return cljs.core.cst$kw$recur; } else { if((state_val_15732 === (1))){ var state_15731__$1 = state_15731; var statearr_15735_15799 = state_15731__$1; (statearr_15735_15799[(2)] = null); (statearr_15735_15799[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_15732 === (4))){ var inst_15696 = (state_15731[(7)]); var inst_15696__$1 = (state_15731[(2)]); var inst_15697 = (inst_15696__$1 == null); var state_15731__$1 = (function (){var statearr_15736 = state_15731; (statearr_15736[(7)] = inst_15696__$1); return statearr_15736; })(); if(cljs.core.truth_(inst_15697)){ var statearr_15737_15800 = state_15731__$1; (statearr_15737_15800[(1)] = (5)); } else { var statearr_15738_15801 = state_15731__$1; (statearr_15738_15801[(1)] = (6)); } return cljs.core.cst$kw$recur; } else { if((state_val_15732 === (15))){ var inst_15709 = (state_15731[(8)]); var state_15731__$1 = state_15731; return cljs.core.async.impl.ioc_helpers.put_BANG_(state_15731__$1,(18),to,inst_15709); } else { if((state_val_15732 === (21))){ var inst_15722 = (state_15731[(2)]); var state_15731__$1 = state_15731; var statearr_15739_15802 = state_15731__$1; (statearr_15739_15802[(2)] = inst_15722); (statearr_15739_15802[(1)] = (13)); return cljs.core.cst$kw$recur; } else { if((state_val_15732 === (13))){ var inst_15724 = (state_15731[(2)]); var state_15731__$1 = (function (){var statearr_15740 = state_15731; (statearr_15740[(9)] = inst_15724); return statearr_15740; })(); var statearr_15741_15803 = state_15731__$1; (statearr_15741_15803[(2)] = null); (statearr_15741_15803[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_15732 === (6))){ var inst_15696 = (state_15731[(7)]); var state_15731__$1 = state_15731; return cljs.core.async.impl.ioc_helpers.take_BANG_(state_15731__$1,(11),inst_15696); } else { if((state_val_15732 === (17))){ var inst_15717 = (state_15731[(2)]); var state_15731__$1 = state_15731; if(cljs.core.truth_(inst_15717)){ var statearr_15742_15804 = state_15731__$1; (statearr_15742_15804[(1)] = (19)); } else { var statearr_15743_15805 = state_15731__$1; (statearr_15743_15805[(1)] = (20)); } return cljs.core.cst$kw$recur; } else { if((state_val_15732 === (3))){ var inst_15729 = (state_15731[(2)]); var state_15731__$1 = state_15731; return cljs.core.async.impl.ioc_helpers.return_chan(state_15731__$1,inst_15729); } else { if((state_val_15732 === (12))){ var inst_15706 = (state_15731[(10)]); var state_15731__$1 = state_15731; return cljs.core.async.impl.ioc_helpers.take_BANG_(state_15731__$1,(14),inst_15706); } else { if((state_val_15732 === (2))){ var state_15731__$1 = state_15731; return cljs.core.async.impl.ioc_helpers.take_BANG_(state_15731__$1,(4),results); } else { if((state_val_15732 === (19))){ var state_15731__$1 = state_15731; var statearr_15744_15806 = state_15731__$1; (statearr_15744_15806[(2)] = null); (statearr_15744_15806[(1)] = (12)); return cljs.core.cst$kw$recur; } else { if((state_val_15732 === (11))){ var inst_15706 = (state_15731[(2)]); var state_15731__$1 = (function (){var statearr_15745 = state_15731; (statearr_15745[(10)] = inst_15706); return statearr_15745; })(); var statearr_15746_15807 = state_15731__$1; (statearr_15746_15807[(2)] = null); (statearr_15746_15807[(1)] = (12)); return cljs.core.cst$kw$recur; } else { if((state_val_15732 === (9))){ var state_15731__$1 = state_15731; var statearr_15747_15808 = state_15731__$1; (statearr_15747_15808[(2)] = null); (statearr_15747_15808[(1)] = (10)); return cljs.core.cst$kw$recur; } else { if((state_val_15732 === (5))){ var state_15731__$1 = state_15731; if(cljs.core.truth_(close_QMARK_)){ var statearr_15748_15809 = state_15731__$1; (statearr_15748_15809[(1)] = (8)); } else { var statearr_15749_15810 = state_15731__$1; (statearr_15749_15810[(1)] = (9)); } return cljs.core.cst$kw$recur; } else { if((state_val_15732 === (14))){ var inst_15711 = (state_15731[(11)]); var inst_15709 = (state_15731[(8)]); var inst_15709__$1 = (state_15731[(2)]); var inst_15710 = (inst_15709__$1 == null); var inst_15711__$1 = cljs.core.not(inst_15710); var state_15731__$1 = (function (){var statearr_15750 = state_15731; (statearr_15750[(11)] = inst_15711__$1); (statearr_15750[(8)] = inst_15709__$1); return statearr_15750; })(); if(inst_15711__$1){ var statearr_15751_15811 = state_15731__$1; (statearr_15751_15811[(1)] = (15)); } else { var statearr_15752_15812 = state_15731__$1; (statearr_15752_15812[(1)] = (16)); } return cljs.core.cst$kw$recur; } else { if((state_val_15732 === (16))){ var inst_15711 = (state_15731[(11)]); var state_15731__$1 = state_15731; var statearr_15753_15813 = state_15731__$1; (statearr_15753_15813[(2)] = inst_15711); (statearr_15753_15813[(1)] = (17)); return cljs.core.cst$kw$recur; } else { if((state_val_15732 === (10))){ var inst_15703 = (state_15731[(2)]); var state_15731__$1 = state_15731; var statearr_15754_15814 = state_15731__$1; (statearr_15754_15814[(2)] = inst_15703); (statearr_15754_15814[(1)] = (7)); return cljs.core.cst$kw$recur; } else { if((state_val_15732 === (18))){ var inst_15714 = (state_15731[(2)]); var state_15731__$1 = state_15731; var statearr_15755_15815 = state_15731__$1; (statearr_15755_15815[(2)] = inst_15714); (statearr_15755_15815[(1)] = (17)); return cljs.core.cst$kw$recur; } else { if((state_val_15732 === (8))){ var inst_15700 = cljs.core.async.close_BANG_(to); var state_15731__$1 = state_15731; var statearr_15756_15816 = state_15731__$1; (statearr_15756_15816[(2)] = inst_15700); (statearr_15756_15816[(1)] = (10)); return cljs.core.cst$kw$recur; } else { return null; } } } } } } } } } } } } } } } } } } } } } });})(c__15437__auto__,jobs,results,process,async)) ; return ((function (switch__15337__auto__,c__15437__auto__,jobs,results,process,async){ return (function() { var cljs$core$async$pipeline_STAR__$_state_machine__15338__auto__ = null; var cljs$core$async$pipeline_STAR__$_state_machine__15338__auto____0 = (function (){ var statearr_15757 = [null,null,null,null,null,null,null,null,null,null,null,null]; (statearr_15757[(0)] = cljs$core$async$pipeline_STAR__$_state_machine__15338__auto__); (statearr_15757[(1)] = (1)); return statearr_15757; }); var cljs$core$async$pipeline_STAR__$_state_machine__15338__auto____1 = (function (state_15731){ while(true){ var ret_value__15339__auto__ = (function (){try{while(true){ var result__15340__auto__ = switch__15337__auto__(state_15731); if(cljs.core.keyword_identical_QMARK_(result__15340__auto__,cljs.core.cst$kw$recur)){ continue; } else { return result__15340__auto__; } break; } }catch (e15758){if((e15758 instanceof Object)){ var ex__15341__auto__ = e15758; var statearr_15759_15817 = state_15731; (statearr_15759_15817[(5)] = ex__15341__auto__); cljs.core.async.impl.ioc_helpers.process_exception(state_15731); return cljs.core.cst$kw$recur; } else { throw e15758; } }})(); if(cljs.core.keyword_identical_QMARK_(ret_value__15339__auto__,cljs.core.cst$kw$recur)){ var G__15818 = state_15731; state_15731 = G__15818; continue; } else { return ret_value__15339__auto__; } break; } }); cljs$core$async$pipeline_STAR__$_state_machine__15338__auto__ = function(state_15731){ switch(arguments.length){ case 0: return cljs$core$async$pipeline_STAR__$_state_machine__15338__auto____0.call(this); case 1: return cljs$core$async$pipeline_STAR__$_state_machine__15338__auto____1.call(this,state_15731); } throw(new Error('Invalid arity: ' + (arguments.length - 1))); }; cljs$core$async$pipeline_STAR__$_state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$0 = cljs$core$async$pipeline_STAR__$_state_machine__15338__auto____0; cljs$core$async$pipeline_STAR__$_state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$1 = cljs$core$async$pipeline_STAR__$_state_machine__15338__auto____1; return cljs$core$async$pipeline_STAR__$_state_machine__15338__auto__; })() ;})(switch__15337__auto__,c__15437__auto__,jobs,results,process,async)) })(); var state__15439__auto__ = (function (){var statearr_15760 = (f__15438__auto__.cljs$core$IFn$_invoke$arity$0 ? f__15438__auto__.cljs$core$IFn$_invoke$arity$0() : f__15438__auto__.call(null)); (statearr_15760[(6)] = c__15437__auto__); return statearr_15760; })(); return cljs.core.async.impl.ioc_helpers.run_state_machine_wrapped(state__15439__auto__); });})(c__15437__auto__,jobs,results,process,async)) ); return c__15437__auto__; }); /** * Takes elements from the from channel and supplies them to the to * channel, subject to the async function af, with parallelism n. af * must be a function of two arguments, the first an input value and * the second a channel on which to place the result(s). af must close! * the channel before returning. The presumption is that af will * return immediately, having launched some asynchronous operation * whose completion/callback will manipulate the result channel. Outputs * will be returned in order relative to the inputs. By default, the to * channel will be closed when the from channel closes, but can be * determined by the close? parameter. Will stop consuming the from * channel if the to channel closes. */ cljs.core.async.pipeline_async = (function cljs$core$async$pipeline_async(var_args){ var G__15820 = arguments.length; switch (G__15820) { case 4: return cljs.core.async.pipeline_async.cljs$core$IFn$_invoke$arity$4((arguments[(0)]),(arguments[(1)]),(arguments[(2)]),(arguments[(3)])); break; case 5: return cljs.core.async.pipeline_async.cljs$core$IFn$_invoke$arity$5((arguments[(0)]),(arguments[(1)]),(arguments[(2)]),(arguments[(3)]),(arguments[(4)])); break; default: throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join(''))); } }); cljs.core.async.pipeline_async.cljs$core$IFn$_invoke$arity$4 = (function (n,to,af,from){ return cljs.core.async.pipeline_async.cljs$core$IFn$_invoke$arity$5(n,to,af,from,true); }); cljs.core.async.pipeline_async.cljs$core$IFn$_invoke$arity$5 = (function (n,to,af,from,close_QMARK_){ return cljs.core.async.pipeline_STAR_(n,to,af,from,close_QMARK_,null,cljs.core.cst$kw$async); }); cljs.core.async.pipeline_async.cljs$lang$maxFixedArity = 5; /** * Takes elements from the from channel and supplies them to the to * channel, subject to the transducer xf, with parallelism n. Because * it is parallel, the transducer will be applied independently to each * element, not across elements, and may produce zero or more outputs * per input. Outputs will be returned in order relative to the * inputs. By default, the to channel will be closed when the from * channel closes, but can be determined by the close? parameter. Will * stop consuming the from channel if the to channel closes. * * Note this is supplied for API compatibility with the Clojure version. * Values of N > 1 will not result in actual concurrency in a * single-threaded runtime. */ cljs.core.async.pipeline = (function cljs$core$async$pipeline(var_args){ var G__15823 = arguments.length; switch (G__15823) { case 4: return cljs.core.async.pipeline.cljs$core$IFn$_invoke$arity$4((arguments[(0)]),(arguments[(1)]),(arguments[(2)]),(arguments[(3)])); break; case 5: return cljs.core.async.pipeline.cljs$core$IFn$_invoke$arity$5((arguments[(0)]),(arguments[(1)]),(arguments[(2)]),(arguments[(3)]),(arguments[(4)])); break; case 6: return cljs.core.async.pipeline.cljs$core$IFn$_invoke$arity$6((arguments[(0)]),(arguments[(1)]),(arguments[(2)]),(arguments[(3)]),(arguments[(4)]),(arguments[(5)])); break; default: throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join(''))); } }); cljs.core.async.pipeline.cljs$core$IFn$_invoke$arity$4 = (function (n,to,xf,from){ return cljs.core.async.pipeline.cljs$core$IFn$_invoke$arity$5(n,to,xf,from,true); }); cljs.core.async.pipeline.cljs$core$IFn$_invoke$arity$5 = (function (n,to,xf,from,close_QMARK_){ return cljs.core.async.pipeline.cljs$core$IFn$_invoke$arity$6(n,to,xf,from,close_QMARK_,null); }); cljs.core.async.pipeline.cljs$core$IFn$_invoke$arity$6 = (function (n,to,xf,from,close_QMARK_,ex_handler){ return cljs.core.async.pipeline_STAR_(n,to,xf,from,close_QMARK_,ex_handler,cljs.core.cst$kw$compute); }); cljs.core.async.pipeline.cljs$lang$maxFixedArity = 6; /** * Takes a predicate and a source channel and returns a vector of two * channels, the first of which will contain the values for which the * predicate returned true, the second those for which it returned * false. * * The out channels will be unbuffered by default, or two buf-or-ns can * be supplied. The channels will close after the source channel has * closed. */ cljs.core.async.split = (function cljs$core$async$split(var_args){ var G__15826 = arguments.length; switch (G__15826) { case 2: return cljs.core.async.split.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; case 4: return cljs.core.async.split.cljs$core$IFn$_invoke$arity$4((arguments[(0)]),(arguments[(1)]),(arguments[(2)]),(arguments[(3)])); break; default: throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join(''))); } }); cljs.core.async.split.cljs$core$IFn$_invoke$arity$2 = (function (p,ch){ return cljs.core.async.split.cljs$core$IFn$_invoke$arity$4(p,ch,null,null); }); cljs.core.async.split.cljs$core$IFn$_invoke$arity$4 = (function (p,ch,t_buf_or_n,f_buf_or_n){ var tc = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1(t_buf_or_n); var fc = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1(f_buf_or_n); var c__15437__auto___15875 = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1((1)); cljs.core.async.impl.dispatch.run(((function (c__15437__auto___15875,tc,fc){ return (function (){ var f__15438__auto__ = (function (){var switch__15337__auto__ = ((function (c__15437__auto___15875,tc,fc){ return (function (state_15852){ var state_val_15853 = (state_15852[(1)]); if((state_val_15853 === (7))){ var inst_15848 = (state_15852[(2)]); var state_15852__$1 = state_15852; var statearr_15854_15876 = state_15852__$1; (statearr_15854_15876[(2)] = inst_15848); (statearr_15854_15876[(1)] = (3)); return cljs.core.cst$kw$recur; } else { if((state_val_15853 === (1))){ var state_15852__$1 = state_15852; var statearr_15855_15877 = state_15852__$1; (statearr_15855_15877[(2)] = null); (statearr_15855_15877[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_15853 === (4))){ var inst_15829 = (state_15852[(7)]); var inst_15829__$1 = (state_15852[(2)]); var inst_15830 = (inst_15829__$1 == null); var state_15852__$1 = (function (){var statearr_15856 = state_15852; (statearr_15856[(7)] = inst_15829__$1); return statearr_15856; })(); if(cljs.core.truth_(inst_15830)){ var statearr_15857_15878 = state_15852__$1; (statearr_15857_15878[(1)] = (5)); } else { var statearr_15858_15879 = state_15852__$1; (statearr_15858_15879[(1)] = (6)); } return cljs.core.cst$kw$recur; } else { if((state_val_15853 === (13))){ var state_15852__$1 = state_15852; var statearr_15859_15880 = state_15852__$1; (statearr_15859_15880[(2)] = null); (statearr_15859_15880[(1)] = (14)); return cljs.core.cst$kw$recur; } else { if((state_val_15853 === (6))){ var inst_15829 = (state_15852[(7)]); var inst_15835 = (p.cljs$core$IFn$_invoke$arity$1 ? p.cljs$core$IFn$_invoke$arity$1(inst_15829) : p.call(null,inst_15829)); var state_15852__$1 = state_15852; if(cljs.core.truth_(inst_15835)){ var statearr_15860_15881 = state_15852__$1; (statearr_15860_15881[(1)] = (9)); } else { var statearr_15861_15882 = state_15852__$1; (statearr_15861_15882[(1)] = (10)); } return cljs.core.cst$kw$recur; } else { if((state_val_15853 === (3))){ var inst_15850 = (state_15852[(2)]); var state_15852__$1 = state_15852; return cljs.core.async.impl.ioc_helpers.return_chan(state_15852__$1,inst_15850); } else { if((state_val_15853 === (12))){ var state_15852__$1 = state_15852; var statearr_15862_15883 = state_15852__$1; (statearr_15862_15883[(2)] = null); (statearr_15862_15883[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_15853 === (2))){ var state_15852__$1 = state_15852; return cljs.core.async.impl.ioc_helpers.take_BANG_(state_15852__$1,(4),ch); } else { if((state_val_15853 === (11))){ var inst_15829 = (state_15852[(7)]); var inst_15839 = (state_15852[(2)]); var state_15852__$1 = state_15852; return cljs.core.async.impl.ioc_helpers.put_BANG_(state_15852__$1,(8),inst_15839,inst_15829); } else { if((state_val_15853 === (9))){ var state_15852__$1 = state_15852; var statearr_15863_15884 = state_15852__$1; (statearr_15863_15884[(2)] = tc); (statearr_15863_15884[(1)] = (11)); return cljs.core.cst$kw$recur; } else { if((state_val_15853 === (5))){ var inst_15832 = cljs.core.async.close_BANG_(tc); var inst_15833 = cljs.core.async.close_BANG_(fc); var state_15852__$1 = (function (){var statearr_15864 = state_15852; (statearr_15864[(8)] = inst_15832); return statearr_15864; })(); var statearr_15865_15885 = state_15852__$1; (statearr_15865_15885[(2)] = inst_15833); (statearr_15865_15885[(1)] = (7)); return cljs.core.cst$kw$recur; } else { if((state_val_15853 === (14))){ var inst_15846 = (state_15852[(2)]); var state_15852__$1 = state_15852; var statearr_15866_15886 = state_15852__$1; (statearr_15866_15886[(2)] = inst_15846); (statearr_15866_15886[(1)] = (7)); return cljs.core.cst$kw$recur; } else { if((state_val_15853 === (10))){ var state_15852__$1 = state_15852; var statearr_15867_15887 = state_15852__$1; (statearr_15867_15887[(2)] = fc); (statearr_15867_15887[(1)] = (11)); return cljs.core.cst$kw$recur; } else { if((state_val_15853 === (8))){ var inst_15841 = (state_15852[(2)]); var state_15852__$1 = state_15852; if(cljs.core.truth_(inst_15841)){ var statearr_15868_15888 = state_15852__$1; (statearr_15868_15888[(1)] = (12)); } else { var statearr_15869_15889 = state_15852__$1; (statearr_15869_15889[(1)] = (13)); } return cljs.core.cst$kw$recur; } else { return null; } } } } } } } } } } } } } } });})(c__15437__auto___15875,tc,fc)) ; return ((function (switch__15337__auto__,c__15437__auto___15875,tc,fc){ return (function() { var cljs$core$async$state_machine__15338__auto__ = null; var cljs$core$async$state_machine__15338__auto____0 = (function (){ var statearr_15870 = [null,null,null,null,null,null,null,null,null]; (statearr_15870[(0)] = cljs$core$async$state_machine__15338__auto__); (statearr_15870[(1)] = (1)); return statearr_15870; }); var cljs$core$async$state_machine__15338__auto____1 = (function (state_15852){ while(true){ var ret_value__15339__auto__ = (function (){try{while(true){ var result__15340__auto__ = switch__15337__auto__(state_15852); if(cljs.core.keyword_identical_QMARK_(result__15340__auto__,cljs.core.cst$kw$recur)){ continue; } else { return result__15340__auto__; } break; } }catch (e15871){if((e15871 instanceof Object)){ var ex__15341__auto__ = e15871; var statearr_15872_15890 = state_15852; (statearr_15872_15890[(5)] = ex__15341__auto__); cljs.core.async.impl.ioc_helpers.process_exception(state_15852); return cljs.core.cst$kw$recur; } else { throw e15871; } }})(); if(cljs.core.keyword_identical_QMARK_(ret_value__15339__auto__,cljs.core.cst$kw$recur)){ var G__15891 = state_15852; state_15852 = G__15891; continue; } else { return ret_value__15339__auto__; } break; } }); cljs$core$async$state_machine__15338__auto__ = function(state_15852){ switch(arguments.length){ case 0: return cljs$core$async$state_machine__15338__auto____0.call(this); case 1: return cljs$core$async$state_machine__15338__auto____1.call(this,state_15852); } throw(new Error('Invalid arity: ' + (arguments.length - 1))); }; cljs$core$async$state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$0 = cljs$core$async$state_machine__15338__auto____0; cljs$core$async$state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$1 = cljs$core$async$state_machine__15338__auto____1; return cljs$core$async$state_machine__15338__auto__; })() ;})(switch__15337__auto__,c__15437__auto___15875,tc,fc)) })(); var state__15439__auto__ = (function (){var statearr_15873 = (f__15438__auto__.cljs$core$IFn$_invoke$arity$0 ? f__15438__auto__.cljs$core$IFn$_invoke$arity$0() : f__15438__auto__.call(null)); (statearr_15873[(6)] = c__15437__auto___15875); return statearr_15873; })(); return cljs.core.async.impl.ioc_helpers.run_state_machine_wrapped(state__15439__auto__); });})(c__15437__auto___15875,tc,fc)) ); return new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [tc,fc], null); }); cljs.core.async.split.cljs$lang$maxFixedArity = 4; /** * f should be a function of 2 arguments. Returns a channel containing * the single result of applying f to init and the first item from the * channel, then applying f to that result and the 2nd item, etc. If * the channel closes without yielding items, returns init and f is not * called. ch must close before reduce produces a result. */ cljs.core.async.reduce = (function cljs$core$async$reduce(f,init,ch){ var c__15437__auto__ = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1((1)); cljs.core.async.impl.dispatch.run(((function (c__15437__auto__){ return (function (){ var f__15438__auto__ = (function (){var switch__15337__auto__ = ((function (c__15437__auto__){ return (function (state_15912){ var state_val_15913 = (state_15912[(1)]); if((state_val_15913 === (7))){ var inst_15908 = (state_15912[(2)]); var state_15912__$1 = state_15912; var statearr_15914_15932 = state_15912__$1; (statearr_15914_15932[(2)] = inst_15908); (statearr_15914_15932[(1)] = (3)); return cljs.core.cst$kw$recur; } else { if((state_val_15913 === (1))){ var inst_15892 = init; var state_15912__$1 = (function (){var statearr_15915 = state_15912; (statearr_15915[(7)] = inst_15892); return statearr_15915; })(); var statearr_15916_15933 = state_15912__$1; (statearr_15916_15933[(2)] = null); (statearr_15916_15933[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_15913 === (4))){ var inst_15895 = (state_15912[(8)]); var inst_15895__$1 = (state_15912[(2)]); var inst_15896 = (inst_15895__$1 == null); var state_15912__$1 = (function (){var statearr_15917 = state_15912; (statearr_15917[(8)] = inst_15895__$1); return statearr_15917; })(); if(cljs.core.truth_(inst_15896)){ var statearr_15918_15934 = state_15912__$1; (statearr_15918_15934[(1)] = (5)); } else { var statearr_15919_15935 = state_15912__$1; (statearr_15919_15935[(1)] = (6)); } return cljs.core.cst$kw$recur; } else { if((state_val_15913 === (6))){ var inst_15892 = (state_15912[(7)]); var inst_15895 = (state_15912[(8)]); var inst_15899 = (state_15912[(9)]); var inst_15899__$1 = (f.cljs$core$IFn$_invoke$arity$2 ? f.cljs$core$IFn$_invoke$arity$2(inst_15892,inst_15895) : f.call(null,inst_15892,inst_15895)); var inst_15900 = cljs.core.reduced_QMARK_(inst_15899__$1); var state_15912__$1 = (function (){var statearr_15920 = state_15912; (statearr_15920[(9)] = inst_15899__$1); return statearr_15920; })(); if(inst_15900){ var statearr_15921_15936 = state_15912__$1; (statearr_15921_15936[(1)] = (8)); } else { var statearr_15922_15937 = state_15912__$1; (statearr_15922_15937[(1)] = (9)); } return cljs.core.cst$kw$recur; } else { if((state_val_15913 === (3))){ var inst_15910 = (state_15912[(2)]); var state_15912__$1 = state_15912; return cljs.core.async.impl.ioc_helpers.return_chan(state_15912__$1,inst_15910); } else { if((state_val_15913 === (2))){ var state_15912__$1 = state_15912; return cljs.core.async.impl.ioc_helpers.take_BANG_(state_15912__$1,(4),ch); } else { if((state_val_15913 === (9))){ var inst_15899 = (state_15912[(9)]); var inst_15892 = inst_15899; var state_15912__$1 = (function (){var statearr_15923 = state_15912; (statearr_15923[(7)] = inst_15892); return statearr_15923; })(); var statearr_15924_15938 = state_15912__$1; (statearr_15924_15938[(2)] = null); (statearr_15924_15938[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_15913 === (5))){ var inst_15892 = (state_15912[(7)]); var state_15912__$1 = state_15912; var statearr_15925_15939 = state_15912__$1; (statearr_15925_15939[(2)] = inst_15892); (statearr_15925_15939[(1)] = (7)); return cljs.core.cst$kw$recur; } else { if((state_val_15913 === (10))){ var inst_15906 = (state_15912[(2)]); var state_15912__$1 = state_15912; var statearr_15926_15940 = state_15912__$1; (statearr_15926_15940[(2)] = inst_15906); (statearr_15926_15940[(1)] = (7)); return cljs.core.cst$kw$recur; } else { if((state_val_15913 === (8))){ var inst_15899 = (state_15912[(9)]); var inst_15902 = cljs.core.deref(inst_15899); var state_15912__$1 = state_15912; var statearr_15927_15941 = state_15912__$1; (statearr_15927_15941[(2)] = inst_15902); (statearr_15927_15941[(1)] = (10)); return cljs.core.cst$kw$recur; } else { return null; } } } } } } } } } } });})(c__15437__auto__)) ; return ((function (switch__15337__auto__,c__15437__auto__){ return (function() { var cljs$core$async$reduce_$_state_machine__15338__auto__ = null; var cljs$core$async$reduce_$_state_machine__15338__auto____0 = (function (){ var statearr_15928 = [null,null,null,null,null,null,null,null,null,null]; (statearr_15928[(0)] = cljs$core$async$reduce_$_state_machine__15338__auto__); (statearr_15928[(1)] = (1)); return statearr_15928; }); var cljs$core$async$reduce_$_state_machine__15338__auto____1 = (function (state_15912){ while(true){ var ret_value__15339__auto__ = (function (){try{while(true){ var result__15340__auto__ = switch__15337__auto__(state_15912); if(cljs.core.keyword_identical_QMARK_(result__15340__auto__,cljs.core.cst$kw$recur)){ continue; } else { return result__15340__auto__; } break; } }catch (e15929){if((e15929 instanceof Object)){ var ex__15341__auto__ = e15929; var statearr_15930_15942 = state_15912; (statearr_15930_15942[(5)] = ex__15341__auto__); cljs.core.async.impl.ioc_helpers.process_exception(state_15912); return cljs.core.cst$kw$recur; } else { throw e15929; } }})(); if(cljs.core.keyword_identical_QMARK_(ret_value__15339__auto__,cljs.core.cst$kw$recur)){ var G__15943 = state_15912; state_15912 = G__15943; continue; } else { return ret_value__15339__auto__; } break; } }); cljs$core$async$reduce_$_state_machine__15338__auto__ = function(state_15912){ switch(arguments.length){ case 0: return cljs$core$async$reduce_$_state_machine__15338__auto____0.call(this); case 1: return cljs$core$async$reduce_$_state_machine__15338__auto____1.call(this,state_15912); } throw(new Error('Invalid arity: ' + (arguments.length - 1))); }; cljs$core$async$reduce_$_state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$0 = cljs$core$async$reduce_$_state_machine__15338__auto____0; cljs$core$async$reduce_$_state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$1 = cljs$core$async$reduce_$_state_machine__15338__auto____1; return cljs$core$async$reduce_$_state_machine__15338__auto__; })() ;})(switch__15337__auto__,c__15437__auto__)) })(); var state__15439__auto__ = (function (){var statearr_15931 = (f__15438__auto__.cljs$core$IFn$_invoke$arity$0 ? f__15438__auto__.cljs$core$IFn$_invoke$arity$0() : f__15438__auto__.call(null)); (statearr_15931[(6)] = c__15437__auto__); return statearr_15931; })(); return cljs.core.async.impl.ioc_helpers.run_state_machine_wrapped(state__15439__auto__); });})(c__15437__auto__)) ); return c__15437__auto__; }); /** * async/reduces a channel with a transformation (xform f). * Returns a channel containing the result. ch must close before * transduce produces a result. */ cljs.core.async.transduce = (function cljs$core$async$transduce(xform,f,init,ch){ var f__$1 = (xform.cljs$core$IFn$_invoke$arity$1 ? xform.cljs$core$IFn$_invoke$arity$1(f) : xform.call(null,f)); var c__15437__auto__ = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1((1)); cljs.core.async.impl.dispatch.run(((function (c__15437__auto__,f__$1){ return (function (){ var f__15438__auto__ = (function (){var switch__15337__auto__ = ((function (c__15437__auto__,f__$1){ return (function (state_15949){ var state_val_15950 = (state_15949[(1)]); if((state_val_15950 === (1))){ var inst_15944 = cljs.core.async.reduce(f__$1,init,ch); var state_15949__$1 = state_15949; return cljs.core.async.impl.ioc_helpers.take_BANG_(state_15949__$1,(2),inst_15944); } else { if((state_val_15950 === (2))){ var inst_15946 = (state_15949[(2)]); var inst_15947 = (f__$1.cljs$core$IFn$_invoke$arity$1 ? f__$1.cljs$core$IFn$_invoke$arity$1(inst_15946) : f__$1.call(null,inst_15946)); var state_15949__$1 = state_15949; return cljs.core.async.impl.ioc_helpers.return_chan(state_15949__$1,inst_15947); } else { return null; } } });})(c__15437__auto__,f__$1)) ; return ((function (switch__15337__auto__,c__15437__auto__,f__$1){ return (function() { var cljs$core$async$transduce_$_state_machine__15338__auto__ = null; var cljs$core$async$transduce_$_state_machine__15338__auto____0 = (function (){ var statearr_15951 = [null,null,null,null,null,null,null]; (statearr_15951[(0)] = cljs$core$async$transduce_$_state_machine__15338__auto__); (statearr_15951[(1)] = (1)); return statearr_15951; }); var cljs$core$async$transduce_$_state_machine__15338__auto____1 = (function (state_15949){ while(true){ var ret_value__15339__auto__ = (function (){try{while(true){ var result__15340__auto__ = switch__15337__auto__(state_15949); if(cljs.core.keyword_identical_QMARK_(result__15340__auto__,cljs.core.cst$kw$recur)){ continue; } else { return result__15340__auto__; } break; } }catch (e15952){if((e15952 instanceof Object)){ var ex__15341__auto__ = e15952; var statearr_15953_15955 = state_15949; (statearr_15953_15955[(5)] = ex__15341__auto__); cljs.core.async.impl.ioc_helpers.process_exception(state_15949); return cljs.core.cst$kw$recur; } else { throw e15952; } }})(); if(cljs.core.keyword_identical_QMARK_(ret_value__15339__auto__,cljs.core.cst$kw$recur)){ var G__15956 = state_15949; state_15949 = G__15956; continue; } else { return ret_value__15339__auto__; } break; } }); cljs$core$async$transduce_$_state_machine__15338__auto__ = function(state_15949){ switch(arguments.length){ case 0: return cljs$core$async$transduce_$_state_machine__15338__auto____0.call(this); case 1: return cljs$core$async$transduce_$_state_machine__15338__auto____1.call(this,state_15949); } throw(new Error('Invalid arity: ' + (arguments.length - 1))); }; cljs$core$async$transduce_$_state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$0 = cljs$core$async$transduce_$_state_machine__15338__auto____0; cljs$core$async$transduce_$_state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$1 = cljs$core$async$transduce_$_state_machine__15338__auto____1; return cljs$core$async$transduce_$_state_machine__15338__auto__; })() ;})(switch__15337__auto__,c__15437__auto__,f__$1)) })(); var state__15439__auto__ = (function (){var statearr_15954 = (f__15438__auto__.cljs$core$IFn$_invoke$arity$0 ? f__15438__auto__.cljs$core$IFn$_invoke$arity$0() : f__15438__auto__.call(null)); (statearr_15954[(6)] = c__15437__auto__); return statearr_15954; })(); return cljs.core.async.impl.ioc_helpers.run_state_machine_wrapped(state__15439__auto__); });})(c__15437__auto__,f__$1)) ); return c__15437__auto__; }); /** * Puts the contents of coll into the supplied channel. * * By default the channel will be closed after the items are copied, * but can be determined by the close? parameter. * * Returns a channel which will close after the items are copied. */ cljs.core.async.onto_chan = (function cljs$core$async$onto_chan(var_args){ var G__15958 = arguments.length; switch (G__15958) { case 2: return cljs.core.async.onto_chan.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; case 3: return cljs.core.async.onto_chan.cljs$core$IFn$_invoke$arity$3((arguments[(0)]),(arguments[(1)]),(arguments[(2)])); break; default: throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join(''))); } }); cljs.core.async.onto_chan.cljs$core$IFn$_invoke$arity$2 = (function (ch,coll){ return cljs.core.async.onto_chan.cljs$core$IFn$_invoke$arity$3(ch,coll,true); }); cljs.core.async.onto_chan.cljs$core$IFn$_invoke$arity$3 = (function (ch,coll,close_QMARK_){ var c__15437__auto__ = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1((1)); cljs.core.async.impl.dispatch.run(((function (c__15437__auto__){ return (function (){ var f__15438__auto__ = (function (){var switch__15337__auto__ = ((function (c__15437__auto__){ return (function (state_15983){ var state_val_15984 = (state_15983[(1)]); if((state_val_15984 === (7))){ var inst_15965 = (state_15983[(2)]); var state_15983__$1 = state_15983; var statearr_15985_16006 = state_15983__$1; (statearr_15985_16006[(2)] = inst_15965); (statearr_15985_16006[(1)] = (6)); return cljs.core.cst$kw$recur; } else { if((state_val_15984 === (1))){ var inst_15959 = cljs.core.seq(coll); var inst_15960 = inst_15959; var state_15983__$1 = (function (){var statearr_15986 = state_15983; (statearr_15986[(7)] = inst_15960); return statearr_15986; })(); var statearr_15987_16007 = state_15983__$1; (statearr_15987_16007[(2)] = null); (statearr_15987_16007[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_15984 === (4))){ var inst_15960 = (state_15983[(7)]); var inst_15963 = cljs.core.first(inst_15960); var state_15983__$1 = state_15983; return cljs.core.async.impl.ioc_helpers.put_BANG_(state_15983__$1,(7),ch,inst_15963); } else { if((state_val_15984 === (13))){ var inst_15977 = (state_15983[(2)]); var state_15983__$1 = state_15983; var statearr_15988_16008 = state_15983__$1; (statearr_15988_16008[(2)] = inst_15977); (statearr_15988_16008[(1)] = (10)); return cljs.core.cst$kw$recur; } else { if((state_val_15984 === (6))){ var inst_15968 = (state_15983[(2)]); var state_15983__$1 = state_15983; if(cljs.core.truth_(inst_15968)){ var statearr_15989_16009 = state_15983__$1; (statearr_15989_16009[(1)] = (8)); } else { var statearr_15990_16010 = state_15983__$1; (statearr_15990_16010[(1)] = (9)); } return cljs.core.cst$kw$recur; } else { if((state_val_15984 === (3))){ var inst_15981 = (state_15983[(2)]); var state_15983__$1 = state_15983; return cljs.core.async.impl.ioc_helpers.return_chan(state_15983__$1,inst_15981); } else { if((state_val_15984 === (12))){ var state_15983__$1 = state_15983; var statearr_15991_16011 = state_15983__$1; (statearr_15991_16011[(2)] = null); (statearr_15991_16011[(1)] = (13)); return cljs.core.cst$kw$recur; } else { if((state_val_15984 === (2))){ var inst_15960 = (state_15983[(7)]); var state_15983__$1 = state_15983; if(cljs.core.truth_(inst_15960)){ var statearr_15992_16012 = state_15983__$1; (statearr_15992_16012[(1)] = (4)); } else { var statearr_15993_16013 = state_15983__$1; (statearr_15993_16013[(1)] = (5)); } return cljs.core.cst$kw$recur; } else { if((state_val_15984 === (11))){ var inst_15974 = cljs.core.async.close_BANG_(ch); var state_15983__$1 = state_15983; var statearr_15994_16014 = state_15983__$1; (statearr_15994_16014[(2)] = inst_15974); (statearr_15994_16014[(1)] = (13)); return cljs.core.cst$kw$recur; } else { if((state_val_15984 === (9))){ var state_15983__$1 = state_15983; if(cljs.core.truth_(close_QMARK_)){ var statearr_15995_16015 = state_15983__$1; (statearr_15995_16015[(1)] = (11)); } else { var statearr_15996_16016 = state_15983__$1; (statearr_15996_16016[(1)] = (12)); } return cljs.core.cst$kw$recur; } else { if((state_val_15984 === (5))){ var inst_15960 = (state_15983[(7)]); var state_15983__$1 = state_15983; var statearr_15997_16017 = state_15983__$1; (statearr_15997_16017[(2)] = inst_15960); (statearr_15997_16017[(1)] = (6)); return cljs.core.cst$kw$recur; } else { if((state_val_15984 === (10))){ var inst_15979 = (state_15983[(2)]); var state_15983__$1 = state_15983; var statearr_15998_16018 = state_15983__$1; (statearr_15998_16018[(2)] = inst_15979); (statearr_15998_16018[(1)] = (3)); return cljs.core.cst$kw$recur; } else { if((state_val_15984 === (8))){ var inst_15960 = (state_15983[(7)]); var inst_15970 = cljs.core.next(inst_15960); var inst_15960__$1 = inst_15970; var state_15983__$1 = (function (){var statearr_15999 = state_15983; (statearr_15999[(7)] = inst_15960__$1); return statearr_15999; })(); var statearr_16000_16019 = state_15983__$1; (statearr_16000_16019[(2)] = null); (statearr_16000_16019[(1)] = (2)); return cljs.core.cst$kw$recur; } else { return null; } } } } } } } } } } } } } });})(c__15437__auto__)) ; return ((function (switch__15337__auto__,c__15437__auto__){ return (function() { var cljs$core$async$state_machine__15338__auto__ = null; var cljs$core$async$state_machine__15338__auto____0 = (function (){ var statearr_16001 = [null,null,null,null,null,null,null,null]; (statearr_16001[(0)] = cljs$core$async$state_machine__15338__auto__); (statearr_16001[(1)] = (1)); return statearr_16001; }); var cljs$core$async$state_machine__15338__auto____1 = (function (state_15983){ while(true){ var ret_value__15339__auto__ = (function (){try{while(true){ var result__15340__auto__ = switch__15337__auto__(state_15983); if(cljs.core.keyword_identical_QMARK_(result__15340__auto__,cljs.core.cst$kw$recur)){ continue; } else { return result__15340__auto__; } break; } }catch (e16002){if((e16002 instanceof Object)){ var ex__15341__auto__ = e16002; var statearr_16003_16020 = state_15983; (statearr_16003_16020[(5)] = ex__15341__auto__); cljs.core.async.impl.ioc_helpers.process_exception(state_15983); return cljs.core.cst$kw$recur; } else { throw e16002; } }})(); if(cljs.core.keyword_identical_QMARK_(ret_value__15339__auto__,cljs.core.cst$kw$recur)){ var G__16021 = state_15983; state_15983 = G__16021; continue; } else { return ret_value__15339__auto__; } break; } }); cljs$core$async$state_machine__15338__auto__ = function(state_15983){ switch(arguments.length){ case 0: return cljs$core$async$state_machine__15338__auto____0.call(this); case 1: return cljs$core$async$state_machine__15338__auto____1.call(this,state_15983); } throw(new Error('Invalid arity: ' + (arguments.length - 1))); }; cljs$core$async$state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$0 = cljs$core$async$state_machine__15338__auto____0; cljs$core$async$state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$1 = cljs$core$async$state_machine__15338__auto____1; return cljs$core$async$state_machine__15338__auto__; })() ;})(switch__15337__auto__,c__15437__auto__)) })(); var state__15439__auto__ = (function (){var statearr_16004 = (f__15438__auto__.cljs$core$IFn$_invoke$arity$0 ? f__15438__auto__.cljs$core$IFn$_invoke$arity$0() : f__15438__auto__.call(null)); (statearr_16004[(6)] = c__15437__auto__); return statearr_16004; })(); return cljs.core.async.impl.ioc_helpers.run_state_machine_wrapped(state__15439__auto__); });})(c__15437__auto__)) ); return c__15437__auto__; }); cljs.core.async.onto_chan.cljs$lang$maxFixedArity = 3; /** * Creates and returns a channel which contains the contents of coll, * closing when exhausted. */ cljs.core.async.to_chan = (function cljs$core$async$to_chan(coll){ var ch = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1(cljs.core.bounded_count((100),coll)); cljs.core.async.onto_chan.cljs$core$IFn$_invoke$arity$2(ch,coll); return ch; }); /** * @interface */ cljs.core.async.Mux = function(){}; cljs.core.async.muxch_STAR_ = (function cljs$core$async$muxch_STAR_(_){ if((!((_ == null))) && (!((_.cljs$core$async$Mux$muxch_STAR_$arity$1 == null)))){ return _.cljs$core$async$Mux$muxch_STAR_$arity$1(_); } else { var x__8351__auto__ = (((_ == null))?null:_); var m__8352__auto__ = (cljs.core.async.muxch_STAR_[goog.typeOf(x__8351__auto__)]); if(!((m__8352__auto__ == null))){ return (m__8352__auto__.cljs$core$IFn$_invoke$arity$1 ? m__8352__auto__.cljs$core$IFn$_invoke$arity$1(_) : m__8352__auto__.call(null,_)); } else { var m__8352__auto____$1 = (cljs.core.async.muxch_STAR_["_"]); if(!((m__8352__auto____$1 == null))){ return (m__8352__auto____$1.cljs$core$IFn$_invoke$arity$1 ? m__8352__auto____$1.cljs$core$IFn$_invoke$arity$1(_) : m__8352__auto____$1.call(null,_)); } else { throw cljs.core.missing_protocol("Mux.muxch*",_); } } } }); /** * @interface */ cljs.core.async.Mult = function(){}; cljs.core.async.tap_STAR_ = (function cljs$core$async$tap_STAR_(m,ch,close_QMARK_){ if((!((m == null))) && (!((m.cljs$core$async$Mult$tap_STAR_$arity$3 == null)))){ return m.cljs$core$async$Mult$tap_STAR_$arity$3(m,ch,close_QMARK_); } else { var x__8351__auto__ = (((m == null))?null:m); var m__8352__auto__ = (cljs.core.async.tap_STAR_[goog.typeOf(x__8351__auto__)]); if(!((m__8352__auto__ == null))){ return (m__8352__auto__.cljs$core$IFn$_invoke$arity$3 ? m__8352__auto__.cljs$core$IFn$_invoke$arity$3(m,ch,close_QMARK_) : m__8352__auto__.call(null,m,ch,close_QMARK_)); } else { var m__8352__auto____$1 = (cljs.core.async.tap_STAR_["_"]); if(!((m__8352__auto____$1 == null))){ return (m__8352__auto____$1.cljs$core$IFn$_invoke$arity$3 ? m__8352__auto____$1.cljs$core$IFn$_invoke$arity$3(m,ch,close_QMARK_) : m__8352__auto____$1.call(null,m,ch,close_QMARK_)); } else { throw cljs.core.missing_protocol("Mult.tap*",m); } } } }); cljs.core.async.untap_STAR_ = (function cljs$core$async$untap_STAR_(m,ch){ if((!((m == null))) && (!((m.cljs$core$async$Mult$untap_STAR_$arity$2 == null)))){ return m.cljs$core$async$Mult$untap_STAR_$arity$2(m,ch); } else { var x__8351__auto__ = (((m == null))?null:m); var m__8352__auto__ = (cljs.core.async.untap_STAR_[goog.typeOf(x__8351__auto__)]); if(!((m__8352__auto__ == null))){ return (m__8352__auto__.cljs$core$IFn$_invoke$arity$2 ? m__8352__auto__.cljs$core$IFn$_invoke$arity$2(m,ch) : m__8352__auto__.call(null,m,ch)); } else { var m__8352__auto____$1 = (cljs.core.async.untap_STAR_["_"]); if(!((m__8352__auto____$1 == null))){ return (m__8352__auto____$1.cljs$core$IFn$_invoke$arity$2 ? m__8352__auto____$1.cljs$core$IFn$_invoke$arity$2(m,ch) : m__8352__auto____$1.call(null,m,ch)); } else { throw cljs.core.missing_protocol("Mult.untap*",m); } } } }); cljs.core.async.untap_all_STAR_ = (function cljs$core$async$untap_all_STAR_(m){ if((!((m == null))) && (!((m.cljs$core$async$Mult$untap_all_STAR_$arity$1 == null)))){ return m.cljs$core$async$Mult$untap_all_STAR_$arity$1(m); } else { var x__8351__auto__ = (((m == null))?null:m); var m__8352__auto__ = (cljs.core.async.untap_all_STAR_[goog.typeOf(x__8351__auto__)]); if(!((m__8352__auto__ == null))){ return (m__8352__auto__.cljs$core$IFn$_invoke$arity$1 ? m__8352__auto__.cljs$core$IFn$_invoke$arity$1(m) : m__8352__auto__.call(null,m)); } else { var m__8352__auto____$1 = (cljs.core.async.untap_all_STAR_["_"]); if(!((m__8352__auto____$1 == null))){ return (m__8352__auto____$1.cljs$core$IFn$_invoke$arity$1 ? m__8352__auto____$1.cljs$core$IFn$_invoke$arity$1(m) : m__8352__auto____$1.call(null,m)); } else { throw cljs.core.missing_protocol("Mult.untap-all*",m); } } } }); /** * Creates and returns a mult(iple) of the supplied channel. Channels * containing copies of the channel can be created with 'tap', and * detached with 'untap'. * * Each item is distributed to all taps in parallel and synchronously, * i.e. each tap must accept before the next item is distributed. Use * buffering/windowing to prevent slow taps from holding up the mult. * * Items received when there are no taps get dropped. * * If a tap puts to a closed channel, it will be removed from the mult. */ cljs.core.async.mult = (function cljs$core$async$mult(ch){ var cs = cljs.core.atom.cljs$core$IFn$_invoke$arity$1(cljs.core.PersistentArrayMap.EMPTY); var m = (function (){ if(typeof cljs.core.async.t_cljs$core$async16022 !== 'undefined'){ } else { /** * @constructor * @implements {cljs.core.async.Mult} * @implements {cljs.core.IMeta} * @implements {cljs.core.async.Mux} * @implements {cljs.core.IWithMeta} */ cljs.core.async.t_cljs$core$async16022 = (function (ch,cs,meta16023){ this.ch = ch; this.cs = cs; this.meta16023 = meta16023; this.cljs$lang$protocol_mask$partition0$ = 393216; this.cljs$lang$protocol_mask$partition1$ = 0; }); cljs.core.async.t_cljs$core$async16022.prototype.cljs$core$IWithMeta$_with_meta$arity$2 = ((function (cs){ return (function (_16024,meta16023__$1){ var self__ = this; var _16024__$1 = this; return (new cljs.core.async.t_cljs$core$async16022(self__.ch,self__.cs,meta16023__$1)); });})(cs)) ; cljs.core.async.t_cljs$core$async16022.prototype.cljs$core$IMeta$_meta$arity$1 = ((function (cs){ return (function (_16024){ var self__ = this; var _16024__$1 = this; return self__.meta16023; });})(cs)) ; cljs.core.async.t_cljs$core$async16022.prototype.cljs$core$async$Mux$ = cljs.core.PROTOCOL_SENTINEL; cljs.core.async.t_cljs$core$async16022.prototype.cljs$core$async$Mux$muxch_STAR_$arity$1 = ((function (cs){ return (function (_){ var self__ = this; var ___$1 = this; return self__.ch; });})(cs)) ; cljs.core.async.t_cljs$core$async16022.prototype.cljs$core$async$Mult$ = cljs.core.PROTOCOL_SENTINEL; cljs.core.async.t_cljs$core$async16022.prototype.cljs$core$async$Mult$tap_STAR_$arity$3 = ((function (cs){ return (function (_,ch__$1,close_QMARK_){ var self__ = this; var ___$1 = this; cljs.core.swap_BANG_.cljs$core$IFn$_invoke$arity$4(self__.cs,cljs.core.assoc,ch__$1,close_QMARK_); return null; });})(cs)) ; cljs.core.async.t_cljs$core$async16022.prototype.cljs$core$async$Mult$untap_STAR_$arity$2 = ((function (cs){ return (function (_,ch__$1){ var self__ = this; var ___$1 = this; cljs.core.swap_BANG_.cljs$core$IFn$_invoke$arity$3(self__.cs,cljs.core.dissoc,ch__$1); return null; });})(cs)) ; cljs.core.async.t_cljs$core$async16022.prototype.cljs$core$async$Mult$untap_all_STAR_$arity$1 = ((function (cs){ return (function (_){ var self__ = this; var ___$1 = this; cljs.core.reset_BANG_(self__.cs,cljs.core.PersistentArrayMap.EMPTY); return null; });})(cs)) ; cljs.core.async.t_cljs$core$async16022.getBasis = ((function (cs){ return (function (){ return new cljs.core.PersistentVector(null, 3, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.cst$sym$ch,cljs.core.cst$sym$cs,cljs.core.cst$sym$meta16023], null); });})(cs)) ; cljs.core.async.t_cljs$core$async16022.cljs$lang$type = true; cljs.core.async.t_cljs$core$async16022.cljs$lang$ctorStr = "cljs.core.async/t_cljs$core$async16022"; cljs.core.async.t_cljs$core$async16022.cljs$lang$ctorPrWriter = ((function (cs){ return (function (this__8293__auto__,writer__8294__auto__,opt__8295__auto__){ return cljs.core._write(writer__8294__auto__,"cljs.core.async/t_cljs$core$async16022"); });})(cs)) ; cljs.core.async.__GT_t_cljs$core$async16022 = ((function (cs){ return (function cljs$core$async$mult_$___GT_t_cljs$core$async16022(ch__$1,cs__$1,meta16023){ return (new cljs.core.async.t_cljs$core$async16022(ch__$1,cs__$1,meta16023)); });})(cs)) ; } return (new cljs.core.async.t_cljs$core$async16022(ch,cs,cljs.core.PersistentArrayMap.EMPTY)); })() ; var dchan = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1((1)); var dctr = cljs.core.atom.cljs$core$IFn$_invoke$arity$1(null); var done = ((function (cs,m,dchan,dctr){ return (function (_){ if((cljs.core.swap_BANG_.cljs$core$IFn$_invoke$arity$2(dctr,cljs.core.dec) === (0))){ return cljs.core.async.put_BANG_.cljs$core$IFn$_invoke$arity$2(dchan,true); } else { return null; } });})(cs,m,dchan,dctr)) ; var c__15437__auto___16244 = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1((1)); cljs.core.async.impl.dispatch.run(((function (c__15437__auto___16244,cs,m,dchan,dctr,done){ return (function (){ var f__15438__auto__ = (function (){var switch__15337__auto__ = ((function (c__15437__auto___16244,cs,m,dchan,dctr,done){ return (function (state_16159){ var state_val_16160 = (state_16159[(1)]); if((state_val_16160 === (7))){ var inst_16155 = (state_16159[(2)]); var state_16159__$1 = state_16159; var statearr_16161_16245 = state_16159__$1; (statearr_16161_16245[(2)] = inst_16155); (statearr_16161_16245[(1)] = (3)); return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (20))){ var inst_16058 = (state_16159[(7)]); var inst_16070 = cljs.core.first(inst_16058); var inst_16071 = cljs.core.nth.cljs$core$IFn$_invoke$arity$3(inst_16070,(0),null); var inst_16072 = cljs.core.nth.cljs$core$IFn$_invoke$arity$3(inst_16070,(1),null); var state_16159__$1 = (function (){var statearr_16162 = state_16159; (statearr_16162[(8)] = inst_16071); return statearr_16162; })(); if(cljs.core.truth_(inst_16072)){ var statearr_16163_16246 = state_16159__$1; (statearr_16163_16246[(1)] = (22)); } else { var statearr_16164_16247 = state_16159__$1; (statearr_16164_16247[(1)] = (23)); } return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (27))){ var inst_16102 = (state_16159[(9)]); var inst_16027 = (state_16159[(10)]); var inst_16100 = (state_16159[(11)]); var inst_16107 = (state_16159[(12)]); var inst_16107__$1 = cljs.core._nth.cljs$core$IFn$_invoke$arity$2(inst_16100,inst_16102); var inst_16108 = cljs.core.async.put_BANG_.cljs$core$IFn$_invoke$arity$3(inst_16107__$1,inst_16027,done); var state_16159__$1 = (function (){var statearr_16165 = state_16159; (statearr_16165[(12)] = inst_16107__$1); return statearr_16165; })(); if(cljs.core.truth_(inst_16108)){ var statearr_16166_16248 = state_16159__$1; (statearr_16166_16248[(1)] = (30)); } else { var statearr_16167_16249 = state_16159__$1; (statearr_16167_16249[(1)] = (31)); } return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (1))){ var state_16159__$1 = state_16159; var statearr_16168_16250 = state_16159__$1; (statearr_16168_16250[(2)] = null); (statearr_16168_16250[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (24))){ var inst_16058 = (state_16159[(7)]); var inst_16077 = (state_16159[(2)]); var inst_16078 = cljs.core.next(inst_16058); var inst_16036 = inst_16078; var inst_16037 = null; var inst_16038 = (0); var inst_16039 = (0); var state_16159__$1 = (function (){var statearr_16169 = state_16159; (statearr_16169[(13)] = inst_16077); (statearr_16169[(14)] = inst_16039); (statearr_16169[(15)] = inst_16038); (statearr_16169[(16)] = inst_16036); (statearr_16169[(17)] = inst_16037); return statearr_16169; })(); var statearr_16170_16251 = state_16159__$1; (statearr_16170_16251[(2)] = null); (statearr_16170_16251[(1)] = (8)); return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (39))){ var state_16159__$1 = state_16159; var statearr_16174_16252 = state_16159__$1; (statearr_16174_16252[(2)] = null); (statearr_16174_16252[(1)] = (41)); return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (4))){ var inst_16027 = (state_16159[(10)]); var inst_16027__$1 = (state_16159[(2)]); var inst_16028 = (inst_16027__$1 == null); var state_16159__$1 = (function (){var statearr_16175 = state_16159; (statearr_16175[(10)] = inst_16027__$1); return statearr_16175; })(); if(cljs.core.truth_(inst_16028)){ var statearr_16176_16253 = state_16159__$1; (statearr_16176_16253[(1)] = (5)); } else { var statearr_16177_16254 = state_16159__$1; (statearr_16177_16254[(1)] = (6)); } return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (15))){ var inst_16039 = (state_16159[(14)]); var inst_16038 = (state_16159[(15)]); var inst_16036 = (state_16159[(16)]); var inst_16037 = (state_16159[(17)]); var inst_16054 = (state_16159[(2)]); var inst_16055 = (inst_16039 + (1)); var tmp16171 = inst_16038; var tmp16172 = inst_16036; var tmp16173 = inst_16037; var inst_16036__$1 = tmp16172; var inst_16037__$1 = tmp16173; var inst_16038__$1 = tmp16171; var inst_16039__$1 = inst_16055; var state_16159__$1 = (function (){var statearr_16178 = state_16159; (statearr_16178[(14)] = inst_16039__$1); (statearr_16178[(15)] = inst_16038__$1); (statearr_16178[(16)] = inst_16036__$1); (statearr_16178[(18)] = inst_16054); (statearr_16178[(17)] = inst_16037__$1); return statearr_16178; })(); var statearr_16179_16255 = state_16159__$1; (statearr_16179_16255[(2)] = null); (statearr_16179_16255[(1)] = (8)); return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (21))){ var inst_16081 = (state_16159[(2)]); var state_16159__$1 = state_16159; var statearr_16183_16256 = state_16159__$1; (statearr_16183_16256[(2)] = inst_16081); (statearr_16183_16256[(1)] = (18)); return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (31))){ var inst_16107 = (state_16159[(12)]); var inst_16111 = done(null); var inst_16112 = m.cljs$core$async$Mult$untap_STAR_$arity$2(null,inst_16107); var state_16159__$1 = (function (){var statearr_16184 = state_16159; (statearr_16184[(19)] = inst_16111); return statearr_16184; })(); var statearr_16185_16257 = state_16159__$1; (statearr_16185_16257[(2)] = inst_16112); (statearr_16185_16257[(1)] = (32)); return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (32))){ var inst_16102 = (state_16159[(9)]); var inst_16099 = (state_16159[(20)]); var inst_16101 = (state_16159[(21)]); var inst_16100 = (state_16159[(11)]); var inst_16114 = (state_16159[(2)]); var inst_16115 = (inst_16102 + (1)); var tmp16180 = inst_16099; var tmp16181 = inst_16101; var tmp16182 = inst_16100; var inst_16099__$1 = tmp16180; var inst_16100__$1 = tmp16182; var inst_16101__$1 = tmp16181; var inst_16102__$1 = inst_16115; var state_16159__$1 = (function (){var statearr_16186 = state_16159; (statearr_16186[(9)] = inst_16102__$1); (statearr_16186[(20)] = inst_16099__$1); (statearr_16186[(21)] = inst_16101__$1); (statearr_16186[(11)] = inst_16100__$1); (statearr_16186[(22)] = inst_16114); return statearr_16186; })(); var statearr_16187_16258 = state_16159__$1; (statearr_16187_16258[(2)] = null); (statearr_16187_16258[(1)] = (25)); return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (40))){ var inst_16127 = (state_16159[(23)]); var inst_16131 = done(null); var inst_16132 = m.cljs$core$async$Mult$untap_STAR_$arity$2(null,inst_16127); var state_16159__$1 = (function (){var statearr_16188 = state_16159; (statearr_16188[(24)] = inst_16131); return statearr_16188; })(); var statearr_16189_16259 = state_16159__$1; (statearr_16189_16259[(2)] = inst_16132); (statearr_16189_16259[(1)] = (41)); return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (33))){ var inst_16118 = (state_16159[(25)]); var inst_16120 = cljs.core.chunked_seq_QMARK_(inst_16118); var state_16159__$1 = state_16159; if(inst_16120){ var statearr_16190_16260 = state_16159__$1; (statearr_16190_16260[(1)] = (36)); } else { var statearr_16191_16261 = state_16159__$1; (statearr_16191_16261[(1)] = (37)); } return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (13))){ var inst_16048 = (state_16159[(26)]); var inst_16051 = cljs.core.async.close_BANG_(inst_16048); var state_16159__$1 = state_16159; var statearr_16192_16262 = state_16159__$1; (statearr_16192_16262[(2)] = inst_16051); (statearr_16192_16262[(1)] = (15)); return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (22))){ var inst_16071 = (state_16159[(8)]); var inst_16074 = cljs.core.async.close_BANG_(inst_16071); var state_16159__$1 = state_16159; var statearr_16193_16263 = state_16159__$1; (statearr_16193_16263[(2)] = inst_16074); (statearr_16193_16263[(1)] = (24)); return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (36))){ var inst_16118 = (state_16159[(25)]); var inst_16122 = cljs.core.chunk_first(inst_16118); var inst_16123 = cljs.core.chunk_rest(inst_16118); var inst_16124 = cljs.core.count(inst_16122); var inst_16099 = inst_16123; var inst_16100 = inst_16122; var inst_16101 = inst_16124; var inst_16102 = (0); var state_16159__$1 = (function (){var statearr_16194 = state_16159; (statearr_16194[(9)] = inst_16102); (statearr_16194[(20)] = inst_16099); (statearr_16194[(21)] = inst_16101); (statearr_16194[(11)] = inst_16100); return statearr_16194; })(); var statearr_16195_16264 = state_16159__$1; (statearr_16195_16264[(2)] = null); (statearr_16195_16264[(1)] = (25)); return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (41))){ var inst_16118 = (state_16159[(25)]); var inst_16134 = (state_16159[(2)]); var inst_16135 = cljs.core.next(inst_16118); var inst_16099 = inst_16135; var inst_16100 = null; var inst_16101 = (0); var inst_16102 = (0); var state_16159__$1 = (function (){var statearr_16196 = state_16159; (statearr_16196[(27)] = inst_16134); (statearr_16196[(9)] = inst_16102); (statearr_16196[(20)] = inst_16099); (statearr_16196[(21)] = inst_16101); (statearr_16196[(11)] = inst_16100); return statearr_16196; })(); var statearr_16197_16265 = state_16159__$1; (statearr_16197_16265[(2)] = null); (statearr_16197_16265[(1)] = (25)); return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (43))){ var state_16159__$1 = state_16159; var statearr_16198_16266 = state_16159__$1; (statearr_16198_16266[(2)] = null); (statearr_16198_16266[(1)] = (44)); return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (29))){ var inst_16143 = (state_16159[(2)]); var state_16159__$1 = state_16159; var statearr_16199_16267 = state_16159__$1; (statearr_16199_16267[(2)] = inst_16143); (statearr_16199_16267[(1)] = (26)); return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (44))){ var inst_16152 = (state_16159[(2)]); var state_16159__$1 = (function (){var statearr_16200 = state_16159; (statearr_16200[(28)] = inst_16152); return statearr_16200; })(); var statearr_16201_16268 = state_16159__$1; (statearr_16201_16268[(2)] = null); (statearr_16201_16268[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (6))){ var inst_16091 = (state_16159[(29)]); var inst_16090 = cljs.core.deref(cs); var inst_16091__$1 = cljs.core.keys(inst_16090); var inst_16092 = cljs.core.count(inst_16091__$1); var inst_16093 = cljs.core.reset_BANG_(dctr,inst_16092); var inst_16098 = cljs.core.seq(inst_16091__$1); var inst_16099 = inst_16098; var inst_16100 = null; var inst_16101 = (0); var inst_16102 = (0); var state_16159__$1 = (function (){var statearr_16202 = state_16159; (statearr_16202[(30)] = inst_16093); (statearr_16202[(9)] = inst_16102); (statearr_16202[(29)] = inst_16091__$1); (statearr_16202[(20)] = inst_16099); (statearr_16202[(21)] = inst_16101); (statearr_16202[(11)] = inst_16100); return statearr_16202; })(); var statearr_16203_16269 = state_16159__$1; (statearr_16203_16269[(2)] = null); (statearr_16203_16269[(1)] = (25)); return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (28))){ var inst_16118 = (state_16159[(25)]); var inst_16099 = (state_16159[(20)]); var inst_16118__$1 = cljs.core.seq(inst_16099); var state_16159__$1 = (function (){var statearr_16204 = state_16159; (statearr_16204[(25)] = inst_16118__$1); return statearr_16204; })(); if(inst_16118__$1){ var statearr_16205_16270 = state_16159__$1; (statearr_16205_16270[(1)] = (33)); } else { var statearr_16206_16271 = state_16159__$1; (statearr_16206_16271[(1)] = (34)); } return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (25))){ var inst_16102 = (state_16159[(9)]); var inst_16101 = (state_16159[(21)]); var inst_16104 = (inst_16102 < inst_16101); var inst_16105 = inst_16104; var state_16159__$1 = state_16159; if(cljs.core.truth_(inst_16105)){ var statearr_16207_16272 = state_16159__$1; (statearr_16207_16272[(1)] = (27)); } else { var statearr_16208_16273 = state_16159__$1; (statearr_16208_16273[(1)] = (28)); } return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (34))){ var state_16159__$1 = state_16159; var statearr_16209_16274 = state_16159__$1; (statearr_16209_16274[(2)] = null); (statearr_16209_16274[(1)] = (35)); return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (17))){ var state_16159__$1 = state_16159; var statearr_16210_16275 = state_16159__$1; (statearr_16210_16275[(2)] = null); (statearr_16210_16275[(1)] = (18)); return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (3))){ var inst_16157 = (state_16159[(2)]); var state_16159__$1 = state_16159; return cljs.core.async.impl.ioc_helpers.return_chan(state_16159__$1,inst_16157); } else { if((state_val_16160 === (12))){ var inst_16086 = (state_16159[(2)]); var state_16159__$1 = state_16159; var statearr_16211_16276 = state_16159__$1; (statearr_16211_16276[(2)] = inst_16086); (statearr_16211_16276[(1)] = (9)); return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (2))){ var state_16159__$1 = state_16159; return cljs.core.async.impl.ioc_helpers.take_BANG_(state_16159__$1,(4),ch); } else { if((state_val_16160 === (23))){ var state_16159__$1 = state_16159; var statearr_16212_16277 = state_16159__$1; (statearr_16212_16277[(2)] = null); (statearr_16212_16277[(1)] = (24)); return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (35))){ var inst_16141 = (state_16159[(2)]); var state_16159__$1 = state_16159; var statearr_16213_16278 = state_16159__$1; (statearr_16213_16278[(2)] = inst_16141); (statearr_16213_16278[(1)] = (29)); return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (19))){ var inst_16058 = (state_16159[(7)]); var inst_16062 = cljs.core.chunk_first(inst_16058); var inst_16063 = cljs.core.chunk_rest(inst_16058); var inst_16064 = cljs.core.count(inst_16062); var inst_16036 = inst_16063; var inst_16037 = inst_16062; var inst_16038 = inst_16064; var inst_16039 = (0); var state_16159__$1 = (function (){var statearr_16214 = state_16159; (statearr_16214[(14)] = inst_16039); (statearr_16214[(15)] = inst_16038); (statearr_16214[(16)] = inst_16036); (statearr_16214[(17)] = inst_16037); return statearr_16214; })(); var statearr_16215_16279 = state_16159__$1; (statearr_16215_16279[(2)] = null); (statearr_16215_16279[(1)] = (8)); return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (11))){ var inst_16058 = (state_16159[(7)]); var inst_16036 = (state_16159[(16)]); var inst_16058__$1 = cljs.core.seq(inst_16036); var state_16159__$1 = (function (){var statearr_16216 = state_16159; (statearr_16216[(7)] = inst_16058__$1); return statearr_16216; })(); if(inst_16058__$1){ var statearr_16217_16280 = state_16159__$1; (statearr_16217_16280[(1)] = (16)); } else { var statearr_16218_16281 = state_16159__$1; (statearr_16218_16281[(1)] = (17)); } return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (9))){ var inst_16088 = (state_16159[(2)]); var state_16159__$1 = state_16159; var statearr_16219_16282 = state_16159__$1; (statearr_16219_16282[(2)] = inst_16088); (statearr_16219_16282[(1)] = (7)); return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (5))){ var inst_16034 = cljs.core.deref(cs); var inst_16035 = cljs.core.seq(inst_16034); var inst_16036 = inst_16035; var inst_16037 = null; var inst_16038 = (0); var inst_16039 = (0); var state_16159__$1 = (function (){var statearr_16220 = state_16159; (statearr_16220[(14)] = inst_16039); (statearr_16220[(15)] = inst_16038); (statearr_16220[(16)] = inst_16036); (statearr_16220[(17)] = inst_16037); return statearr_16220; })(); var statearr_16221_16283 = state_16159__$1; (statearr_16221_16283[(2)] = null); (statearr_16221_16283[(1)] = (8)); return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (14))){ var state_16159__$1 = state_16159; var statearr_16222_16284 = state_16159__$1; (statearr_16222_16284[(2)] = null); (statearr_16222_16284[(1)] = (15)); return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (45))){ var inst_16149 = (state_16159[(2)]); var state_16159__$1 = state_16159; var statearr_16223_16285 = state_16159__$1; (statearr_16223_16285[(2)] = inst_16149); (statearr_16223_16285[(1)] = (44)); return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (26))){ var inst_16091 = (state_16159[(29)]); var inst_16145 = (state_16159[(2)]); var inst_16146 = cljs.core.seq(inst_16091); var state_16159__$1 = (function (){var statearr_16224 = state_16159; (statearr_16224[(31)] = inst_16145); return statearr_16224; })(); if(inst_16146){ var statearr_16225_16286 = state_16159__$1; (statearr_16225_16286[(1)] = (42)); } else { var statearr_16226_16287 = state_16159__$1; (statearr_16226_16287[(1)] = (43)); } return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (16))){ var inst_16058 = (state_16159[(7)]); var inst_16060 = cljs.core.chunked_seq_QMARK_(inst_16058); var state_16159__$1 = state_16159; if(inst_16060){ var statearr_16227_16288 = state_16159__$1; (statearr_16227_16288[(1)] = (19)); } else { var statearr_16228_16289 = state_16159__$1; (statearr_16228_16289[(1)] = (20)); } return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (38))){ var inst_16138 = (state_16159[(2)]); var state_16159__$1 = state_16159; var statearr_16229_16290 = state_16159__$1; (statearr_16229_16290[(2)] = inst_16138); (statearr_16229_16290[(1)] = (35)); return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (30))){ var state_16159__$1 = state_16159; var statearr_16230_16291 = state_16159__$1; (statearr_16230_16291[(2)] = null); (statearr_16230_16291[(1)] = (32)); return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (10))){ var inst_16039 = (state_16159[(14)]); var inst_16037 = (state_16159[(17)]); var inst_16047 = cljs.core._nth.cljs$core$IFn$_invoke$arity$2(inst_16037,inst_16039); var inst_16048 = cljs.core.nth.cljs$core$IFn$_invoke$arity$3(inst_16047,(0),null); var inst_16049 = cljs.core.nth.cljs$core$IFn$_invoke$arity$3(inst_16047,(1),null); var state_16159__$1 = (function (){var statearr_16231 = state_16159; (statearr_16231[(26)] = inst_16048); return statearr_16231; })(); if(cljs.core.truth_(inst_16049)){ var statearr_16232_16292 = state_16159__$1; (statearr_16232_16292[(1)] = (13)); } else { var statearr_16233_16293 = state_16159__$1; (statearr_16233_16293[(1)] = (14)); } return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (18))){ var inst_16084 = (state_16159[(2)]); var state_16159__$1 = state_16159; var statearr_16234_16294 = state_16159__$1; (statearr_16234_16294[(2)] = inst_16084); (statearr_16234_16294[(1)] = (12)); return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (42))){ var state_16159__$1 = state_16159; return cljs.core.async.impl.ioc_helpers.take_BANG_(state_16159__$1,(45),dchan); } else { if((state_val_16160 === (37))){ var inst_16118 = (state_16159[(25)]); var inst_16027 = (state_16159[(10)]); var inst_16127 = (state_16159[(23)]); var inst_16127__$1 = cljs.core.first(inst_16118); var inst_16128 = cljs.core.async.put_BANG_.cljs$core$IFn$_invoke$arity$3(inst_16127__$1,inst_16027,done); var state_16159__$1 = (function (){var statearr_16235 = state_16159; (statearr_16235[(23)] = inst_16127__$1); return statearr_16235; })(); if(cljs.core.truth_(inst_16128)){ var statearr_16236_16295 = state_16159__$1; (statearr_16236_16295[(1)] = (39)); } else { var statearr_16237_16296 = state_16159__$1; (statearr_16237_16296[(1)] = (40)); } return cljs.core.cst$kw$recur; } else { if((state_val_16160 === (8))){ var inst_16039 = (state_16159[(14)]); var inst_16038 = (state_16159[(15)]); var inst_16041 = (inst_16039 < inst_16038); var inst_16042 = inst_16041; var state_16159__$1 = state_16159; if(cljs.core.truth_(inst_16042)){ var statearr_16238_16297 = state_16159__$1; (statearr_16238_16297[(1)] = (10)); } else { var statearr_16239_16298 = state_16159__$1; (statearr_16239_16298[(1)] = (11)); } return cljs.core.cst$kw$recur; } else { return null; } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } });})(c__15437__auto___16244,cs,m,dchan,dctr,done)) ; return ((function (switch__15337__auto__,c__15437__auto___16244,cs,m,dchan,dctr,done){ return (function() { var cljs$core$async$mult_$_state_machine__15338__auto__ = null; var cljs$core$async$mult_$_state_machine__15338__auto____0 = (function (){ var statearr_16240 = [null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null]; (statearr_16240[(0)] = cljs$core$async$mult_$_state_machine__15338__auto__); (statearr_16240[(1)] = (1)); return statearr_16240; }); var cljs$core$async$mult_$_state_machine__15338__auto____1 = (function (state_16159){ while(true){ var ret_value__15339__auto__ = (function (){try{while(true){ var result__15340__auto__ = switch__15337__auto__(state_16159); if(cljs.core.keyword_identical_QMARK_(result__15340__auto__,cljs.core.cst$kw$recur)){ continue; } else { return result__15340__auto__; } break; } }catch (e16241){if((e16241 instanceof Object)){ var ex__15341__auto__ = e16241; var statearr_16242_16299 = state_16159; (statearr_16242_16299[(5)] = ex__15341__auto__); cljs.core.async.impl.ioc_helpers.process_exception(state_16159); return cljs.core.cst$kw$recur; } else { throw e16241; } }})(); if(cljs.core.keyword_identical_QMARK_(ret_value__15339__auto__,cljs.core.cst$kw$recur)){ var G__16300 = state_16159; state_16159 = G__16300; continue; } else { return ret_value__15339__auto__; } break; } }); cljs$core$async$mult_$_state_machine__15338__auto__ = function(state_16159){ switch(arguments.length){ case 0: return cljs$core$async$mult_$_state_machine__15338__auto____0.call(this); case 1: return cljs$core$async$mult_$_state_machine__15338__auto____1.call(this,state_16159); } throw(new Error('Invalid arity: ' + (arguments.length - 1))); }; cljs$core$async$mult_$_state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$0 = cljs$core$async$mult_$_state_machine__15338__auto____0; cljs$core$async$mult_$_state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$1 = cljs$core$async$mult_$_state_machine__15338__auto____1; return cljs$core$async$mult_$_state_machine__15338__auto__; })() ;})(switch__15337__auto__,c__15437__auto___16244,cs,m,dchan,dctr,done)) })(); var state__15439__auto__ = (function (){var statearr_16243 = (f__15438__auto__.cljs$core$IFn$_invoke$arity$0 ? f__15438__auto__.cljs$core$IFn$_invoke$arity$0() : f__15438__auto__.call(null)); (statearr_16243[(6)] = c__15437__auto___16244); return statearr_16243; })(); return cljs.core.async.impl.ioc_helpers.run_state_machine_wrapped(state__15439__auto__); });})(c__15437__auto___16244,cs,m,dchan,dctr,done)) ); return m; }); /** * Copies the mult source onto the supplied channel. * * By default the channel will be closed when the source closes, * but can be determined by the close? parameter. */ cljs.core.async.tap = (function cljs$core$async$tap(var_args){ var G__16302 = arguments.length; switch (G__16302) { case 2: return cljs.core.async.tap.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; case 3: return cljs.core.async.tap.cljs$core$IFn$_invoke$arity$3((arguments[(0)]),(arguments[(1)]),(arguments[(2)])); break; default: throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join(''))); } }); cljs.core.async.tap.cljs$core$IFn$_invoke$arity$2 = (function (mult,ch){ return cljs.core.async.tap.cljs$core$IFn$_invoke$arity$3(mult,ch,true); }); cljs.core.async.tap.cljs$core$IFn$_invoke$arity$3 = (function (mult,ch,close_QMARK_){ cljs.core.async.tap_STAR_(mult,ch,close_QMARK_); return ch; }); cljs.core.async.tap.cljs$lang$maxFixedArity = 3; /** * Disconnects a target channel from a mult */ cljs.core.async.untap = (function cljs$core$async$untap(mult,ch){ return cljs.core.async.untap_STAR_(mult,ch); }); /** * Disconnects all target channels from a mult */ cljs.core.async.untap_all = (function cljs$core$async$untap_all(mult){ return cljs.core.async.untap_all_STAR_(mult); }); /** * @interface */ cljs.core.async.Mix = function(){}; cljs.core.async.admix_STAR_ = (function cljs$core$async$admix_STAR_(m,ch){ if((!((m == null))) && (!((m.cljs$core$async$Mix$admix_STAR_$arity$2 == null)))){ return m.cljs$core$async$Mix$admix_STAR_$arity$2(m,ch); } else { var x__8351__auto__ = (((m == null))?null:m); var m__8352__auto__ = (cljs.core.async.admix_STAR_[goog.typeOf(x__8351__auto__)]); if(!((m__8352__auto__ == null))){ return (m__8352__auto__.cljs$core$IFn$_invoke$arity$2 ? m__8352__auto__.cljs$core$IFn$_invoke$arity$2(m,ch) : m__8352__auto__.call(null,m,ch)); } else { var m__8352__auto____$1 = (cljs.core.async.admix_STAR_["_"]); if(!((m__8352__auto____$1 == null))){ return (m__8352__auto____$1.cljs$core$IFn$_invoke$arity$2 ? m__8352__auto____$1.cljs$core$IFn$_invoke$arity$2(m,ch) : m__8352__auto____$1.call(null,m,ch)); } else { throw cljs.core.missing_protocol("Mix.admix*",m); } } } }); cljs.core.async.unmix_STAR_ = (function cljs$core$async$unmix_STAR_(m,ch){ if((!((m == null))) && (!((m.cljs$core$async$Mix$unmix_STAR_$arity$2 == null)))){ return m.cljs$core$async$Mix$unmix_STAR_$arity$2(m,ch); } else { var x__8351__auto__ = (((m == null))?null:m); var m__8352__auto__ = (cljs.core.async.unmix_STAR_[goog.typeOf(x__8351__auto__)]); if(!((m__8352__auto__ == null))){ return (m__8352__auto__.cljs$core$IFn$_invoke$arity$2 ? m__8352__auto__.cljs$core$IFn$_invoke$arity$2(m,ch) : m__8352__auto__.call(null,m,ch)); } else { var m__8352__auto____$1 = (cljs.core.async.unmix_STAR_["_"]); if(!((m__8352__auto____$1 == null))){ return (m__8352__auto____$1.cljs$core$IFn$_invoke$arity$2 ? m__8352__auto____$1.cljs$core$IFn$_invoke$arity$2(m,ch) : m__8352__auto____$1.call(null,m,ch)); } else { throw cljs.core.missing_protocol("Mix.unmix*",m); } } } }); cljs.core.async.unmix_all_STAR_ = (function cljs$core$async$unmix_all_STAR_(m){ if((!((m == null))) && (!((m.cljs$core$async$Mix$unmix_all_STAR_$arity$1 == null)))){ return m.cljs$core$async$Mix$unmix_all_STAR_$arity$1(m); } else { var x__8351__auto__ = (((m == null))?null:m); var m__8352__auto__ = (cljs.core.async.unmix_all_STAR_[goog.typeOf(x__8351__auto__)]); if(!((m__8352__auto__ == null))){ return (m__8352__auto__.cljs$core$IFn$_invoke$arity$1 ? m__8352__auto__.cljs$core$IFn$_invoke$arity$1(m) : m__8352__auto__.call(null,m)); } else { var m__8352__auto____$1 = (cljs.core.async.unmix_all_STAR_["_"]); if(!((m__8352__auto____$1 == null))){ return (m__8352__auto____$1.cljs$core$IFn$_invoke$arity$1 ? m__8352__auto____$1.cljs$core$IFn$_invoke$arity$1(m) : m__8352__auto____$1.call(null,m)); } else { throw cljs.core.missing_protocol("Mix.unmix-all*",m); } } } }); cljs.core.async.toggle_STAR_ = (function cljs$core$async$toggle_STAR_(m,state_map){ if((!((m == null))) && (!((m.cljs$core$async$Mix$toggle_STAR_$arity$2 == null)))){ return m.cljs$core$async$Mix$toggle_STAR_$arity$2(m,state_map); } else { var x__8351__auto__ = (((m == null))?null:m); var m__8352__auto__ = (cljs.core.async.toggle_STAR_[goog.typeOf(x__8351__auto__)]); if(!((m__8352__auto__ == null))){ return (m__8352__auto__.cljs$core$IFn$_invoke$arity$2 ? m__8352__auto__.cljs$core$IFn$_invoke$arity$2(m,state_map) : m__8352__auto__.call(null,m,state_map)); } else { var m__8352__auto____$1 = (cljs.core.async.toggle_STAR_["_"]); if(!((m__8352__auto____$1 == null))){ return (m__8352__auto____$1.cljs$core$IFn$_invoke$arity$2 ? m__8352__auto____$1.cljs$core$IFn$_invoke$arity$2(m,state_map) : m__8352__auto____$1.call(null,m,state_map)); } else { throw cljs.core.missing_protocol("Mix.toggle*",m); } } } }); cljs.core.async.solo_mode_STAR_ = (function cljs$core$async$solo_mode_STAR_(m,mode){ if((!((m == null))) && (!((m.cljs$core$async$Mix$solo_mode_STAR_$arity$2 == null)))){ return m.cljs$core$async$Mix$solo_mode_STAR_$arity$2(m,mode); } else { var x__8351__auto__ = (((m == null))?null:m); var m__8352__auto__ = (cljs.core.async.solo_mode_STAR_[goog.typeOf(x__8351__auto__)]); if(!((m__8352__auto__ == null))){ return (m__8352__auto__.cljs$core$IFn$_invoke$arity$2 ? m__8352__auto__.cljs$core$IFn$_invoke$arity$2(m,mode) : m__8352__auto__.call(null,m,mode)); } else { var m__8352__auto____$1 = (cljs.core.async.solo_mode_STAR_["_"]); if(!((m__8352__auto____$1 == null))){ return (m__8352__auto____$1.cljs$core$IFn$_invoke$arity$2 ? m__8352__auto____$1.cljs$core$IFn$_invoke$arity$2(m,mode) : m__8352__auto____$1.call(null,m,mode)); } else { throw cljs.core.missing_protocol("Mix.solo-mode*",m); } } } }); cljs.core.async.ioc_alts_BANG_ = (function cljs$core$async$ioc_alts_BANG_(var_args){ var args__8835__auto__ = []; var len__8828__auto___16314 = arguments.length; var i__8829__auto___16315 = (0); while(true){ if((i__8829__auto___16315 < len__8828__auto___16314)){ args__8835__auto__.push((arguments[i__8829__auto___16315])); var G__16316 = (i__8829__auto___16315 + (1)); i__8829__auto___16315 = G__16316; continue; } else { } break; } var argseq__8836__auto__ = ((((3) < args__8835__auto__.length))?(new cljs.core.IndexedSeq(args__8835__auto__.slice((3)),(0),null)):null); return cljs.core.async.ioc_alts_BANG_.cljs$core$IFn$_invoke$arity$variadic((arguments[(0)]),(arguments[(1)]),(arguments[(2)]),argseq__8836__auto__); }); cljs.core.async.ioc_alts_BANG_.cljs$core$IFn$_invoke$arity$variadic = (function (state,cont_block,ports,p__16308){ var map__16309 = p__16308; var map__16309__$1 = ((((!((map__16309 == null)))?((((map__16309.cljs$lang$protocol_mask$partition0$ & (64))) || ((cljs.core.PROTOCOL_SENTINEL === map__16309.cljs$core$ISeq$)))?true:false):false))?cljs.core.apply.cljs$core$IFn$_invoke$arity$2(cljs.core.hash_map,map__16309):map__16309); var opts = map__16309__$1; var statearr_16311_16317 = state; (statearr_16311_16317[(1)] = cont_block); var temp__4657__auto__ = cljs.core.async.do_alts(((function (map__16309,map__16309__$1,opts){ return (function (val){ var statearr_16312_16318 = state; (statearr_16312_16318[(2)] = val); return cljs.core.async.impl.ioc_helpers.run_state_machine_wrapped(state); });})(map__16309,map__16309__$1,opts)) ,ports,opts); if(cljs.core.truth_(temp__4657__auto__)){ var cb = temp__4657__auto__; var statearr_16313_16319 = state; (statearr_16313_16319[(2)] = cljs.core.deref(cb)); return cljs.core.cst$kw$recur; } else { return null; } }); cljs.core.async.ioc_alts_BANG_.cljs$lang$maxFixedArity = (3); cljs.core.async.ioc_alts_BANG_.cljs$lang$applyTo = (function (seq16304){ var G__16305 = cljs.core.first(seq16304); var seq16304__$1 = cljs.core.next(seq16304); var G__16306 = cljs.core.first(seq16304__$1); var seq16304__$2 = cljs.core.next(seq16304__$1); var G__16307 = cljs.core.first(seq16304__$2); var seq16304__$3 = cljs.core.next(seq16304__$2); return cljs.core.async.ioc_alts_BANG_.cljs$core$IFn$_invoke$arity$variadic(G__16305,G__16306,G__16307,seq16304__$3); }); /** * Creates and returns a mix of one or more input channels which will * be put on the supplied out channel. Input sources can be added to * the mix with 'admix', and removed with 'unmix'. A mix supports * soloing, muting and pausing multiple inputs atomically using * 'toggle', and can solo using either muting or pausing as determined * by 'solo-mode'. * * Each channel can have zero or more boolean modes set via 'toggle': * * :solo - when true, only this (ond other soloed) channel(s) will appear * in the mix output channel. :mute and :pause states of soloed * channels are ignored. If solo-mode is :mute, non-soloed * channels are muted, if :pause, non-soloed channels are * paused. * * :mute - muted channels will have their contents consumed but not included in the mix * :pause - paused channels will not have their contents consumed (and thus also not included in the mix) */ cljs.core.async.mix = (function cljs$core$async$mix(out){ var cs = cljs.core.atom.cljs$core$IFn$_invoke$arity$1(cljs.core.PersistentArrayMap.EMPTY); var solo_modes = new cljs.core.PersistentHashSet(null, new cljs.core.PersistentArrayMap(null, 2, [cljs.core.cst$kw$pause,null,cljs.core.cst$kw$mute,null], null), null); var attrs = cljs.core.conj.cljs$core$IFn$_invoke$arity$2(solo_modes,cljs.core.cst$kw$solo); var solo_mode = cljs.core.atom.cljs$core$IFn$_invoke$arity$1(cljs.core.cst$kw$mute); var change = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$0(); var changed = ((function (cs,solo_modes,attrs,solo_mode,change){ return (function (){ return cljs.core.async.put_BANG_.cljs$core$IFn$_invoke$arity$2(change,true); });})(cs,solo_modes,attrs,solo_mode,change)) ; var pick = ((function (cs,solo_modes,attrs,solo_mode,change,changed){ return (function (attr,chs){ return cljs.core.reduce_kv(((function (cs,solo_modes,attrs,solo_mode,change,changed){ return (function (ret,c,v){ if(cljs.core.truth_((attr.cljs$core$IFn$_invoke$arity$1 ? attr.cljs$core$IFn$_invoke$arity$1(v) : attr.call(null,v)))){ return cljs.core.conj.cljs$core$IFn$_invoke$arity$2(ret,c); } else { return ret; } });})(cs,solo_modes,attrs,solo_mode,change,changed)) ,cljs.core.PersistentHashSet.EMPTY,chs); });})(cs,solo_modes,attrs,solo_mode,change,changed)) ; var calc_state = ((function (cs,solo_modes,attrs,solo_mode,change,changed,pick){ return (function (){ var chs = cljs.core.deref(cs); var mode = cljs.core.deref(solo_mode); var solos = pick(cljs.core.cst$kw$solo,chs); var pauses = pick(cljs.core.cst$kw$pause,chs); return new cljs.core.PersistentArrayMap(null, 3, [cljs.core.cst$kw$solos,solos,cljs.core.cst$kw$mutes,pick(cljs.core.cst$kw$mute,chs),cljs.core.cst$kw$reads,cljs.core.conj.cljs$core$IFn$_invoke$arity$2((((cljs.core._EQ_.cljs$core$IFn$_invoke$arity$2(mode,cljs.core.cst$kw$pause)) && (!(cljs.core.empty_QMARK_(solos))))?cljs.core.vec(solos):cljs.core.vec(cljs.core.remove.cljs$core$IFn$_invoke$arity$2(pauses,cljs.core.keys(chs)))),change)], null); });})(cs,solo_modes,attrs,solo_mode,change,changed,pick)) ; var m = (function (){ if(typeof cljs.core.async.t_cljs$core$async16320 !== 'undefined'){ } else { /** * @constructor * @implements {cljs.core.IMeta} * @implements {cljs.core.async.Mix} * @implements {cljs.core.async.Mux} * @implements {cljs.core.IWithMeta} */ cljs.core.async.t_cljs$core$async16320 = (function (out,cs,solo_modes,attrs,solo_mode,change,changed,pick,calc_state,meta16321){ this.out = out; this.cs = cs; this.solo_modes = solo_modes; this.attrs = attrs; this.solo_mode = solo_mode; this.change = change; this.changed = changed; this.pick = pick; this.calc_state = calc_state; this.meta16321 = meta16321; this.cljs$lang$protocol_mask$partition0$ = 393216; this.cljs$lang$protocol_mask$partition1$ = 0; }); cljs.core.async.t_cljs$core$async16320.prototype.cljs$core$IWithMeta$_with_meta$arity$2 = ((function (cs,solo_modes,attrs,solo_mode,change,changed,pick,calc_state){ return (function (_16322,meta16321__$1){ var self__ = this; var _16322__$1 = this; return (new cljs.core.async.t_cljs$core$async16320(self__.out,self__.cs,self__.solo_modes,self__.attrs,self__.solo_mode,self__.change,self__.changed,self__.pick,self__.calc_state,meta16321__$1)); });})(cs,solo_modes,attrs,solo_mode,change,changed,pick,calc_state)) ; cljs.core.async.t_cljs$core$async16320.prototype.cljs$core$IMeta$_meta$arity$1 = ((function (cs,solo_modes,attrs,solo_mode,change,changed,pick,calc_state){ return (function (_16322){ var self__ = this; var _16322__$1 = this; return self__.meta16321; });})(cs,solo_modes,attrs,solo_mode,change,changed,pick,calc_state)) ; cljs.core.async.t_cljs$core$async16320.prototype.cljs$core$async$Mux$ = cljs.core.PROTOCOL_SENTINEL; cljs.core.async.t_cljs$core$async16320.prototype.cljs$core$async$Mux$muxch_STAR_$arity$1 = ((function (cs,solo_modes,attrs,solo_mode,change,changed,pick,calc_state){ return (function (_){ var self__ = this; var ___$1 = this; return self__.out; });})(cs,solo_modes,attrs,solo_mode,change,changed,pick,calc_state)) ; cljs.core.async.t_cljs$core$async16320.prototype.cljs$core$async$Mix$ = cljs.core.PROTOCOL_SENTINEL; cljs.core.async.t_cljs$core$async16320.prototype.cljs$core$async$Mix$admix_STAR_$arity$2 = ((function (cs,solo_modes,attrs,solo_mode,change,changed,pick,calc_state){ return (function (_,ch){ var self__ = this; var ___$1 = this; cljs.core.swap_BANG_.cljs$core$IFn$_invoke$arity$4(self__.cs,cljs.core.assoc,ch,cljs.core.PersistentArrayMap.EMPTY); return (self__.changed.cljs$core$IFn$_invoke$arity$0 ? self__.changed.cljs$core$IFn$_invoke$arity$0() : self__.changed.call(null)); });})(cs,solo_modes,attrs,solo_mode,change,changed,pick,calc_state)) ; cljs.core.async.t_cljs$core$async16320.prototype.cljs$core$async$Mix$unmix_STAR_$arity$2 = ((function (cs,solo_modes,attrs,solo_mode,change,changed,pick,calc_state){ return (function (_,ch){ var self__ = this; var ___$1 = this; cljs.core.swap_BANG_.cljs$core$IFn$_invoke$arity$3(self__.cs,cljs.core.dissoc,ch); return (self__.changed.cljs$core$IFn$_invoke$arity$0 ? self__.changed.cljs$core$IFn$_invoke$arity$0() : self__.changed.call(null)); });})(cs,solo_modes,attrs,solo_mode,change,changed,pick,calc_state)) ; cljs.core.async.t_cljs$core$async16320.prototype.cljs$core$async$Mix$unmix_all_STAR_$arity$1 = ((function (cs,solo_modes,attrs,solo_mode,change,changed,pick,calc_state){ return (function (_){ var self__ = this; var ___$1 = this; cljs.core.reset_BANG_(self__.cs,cljs.core.PersistentArrayMap.EMPTY); return (self__.changed.cljs$core$IFn$_invoke$arity$0 ? self__.changed.cljs$core$IFn$_invoke$arity$0() : self__.changed.call(null)); });})(cs,solo_modes,attrs,solo_mode,change,changed,pick,calc_state)) ; cljs.core.async.t_cljs$core$async16320.prototype.cljs$core$async$Mix$toggle_STAR_$arity$2 = ((function (cs,solo_modes,attrs,solo_mode,change,changed,pick,calc_state){ return (function (_,state_map){ var self__ = this; var ___$1 = this; cljs.core.swap_BANG_.cljs$core$IFn$_invoke$arity$3(self__.cs,cljs.core.partial.cljs$core$IFn$_invoke$arity$2(cljs.core.merge_with,cljs.core.merge),state_map); return (self__.changed.cljs$core$IFn$_invoke$arity$0 ? self__.changed.cljs$core$IFn$_invoke$arity$0() : self__.changed.call(null)); });})(cs,solo_modes,attrs,solo_mode,change,changed,pick,calc_state)) ; cljs.core.async.t_cljs$core$async16320.prototype.cljs$core$async$Mix$solo_mode_STAR_$arity$2 = ((function (cs,solo_modes,attrs,solo_mode,change,changed,pick,calc_state){ return (function (_,mode){ var self__ = this; var ___$1 = this; cljs.core.reset_BANG_(self__.solo_mode,mode); return (self__.changed.cljs$core$IFn$_invoke$arity$0 ? self__.changed.cljs$core$IFn$_invoke$arity$0() : self__.changed.call(null)); });})(cs,solo_modes,attrs,solo_mode,change,changed,pick,calc_state)) ; cljs.core.async.t_cljs$core$async16320.getBasis = ((function (cs,solo_modes,attrs,solo_mode,change,changed,pick,calc_state){ return (function (){ return new cljs.core.PersistentVector(null, 10, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.cst$sym$out,cljs.core.cst$sym$cs,cljs.core.cst$sym$solo_DASH_modes,cljs.core.cst$sym$attrs,cljs.core.cst$sym$solo_DASH_mode,cljs.core.cst$sym$change,cljs.core.cst$sym$changed,cljs.core.cst$sym$pick,cljs.core.cst$sym$calc_DASH_state,cljs.core.cst$sym$meta16321], null); });})(cs,solo_modes,attrs,solo_mode,change,changed,pick,calc_state)) ; cljs.core.async.t_cljs$core$async16320.cljs$lang$type = true; cljs.core.async.t_cljs$core$async16320.cljs$lang$ctorStr = "cljs.core.async/t_cljs$core$async16320"; cljs.core.async.t_cljs$core$async16320.cljs$lang$ctorPrWriter = ((function (cs,solo_modes,attrs,solo_mode,change,changed,pick,calc_state){ return (function (this__8293__auto__,writer__8294__auto__,opt__8295__auto__){ return cljs.core._write(writer__8294__auto__,"cljs.core.async/t_cljs$core$async16320"); });})(cs,solo_modes,attrs,solo_mode,change,changed,pick,calc_state)) ; cljs.core.async.__GT_t_cljs$core$async16320 = ((function (cs,solo_modes,attrs,solo_mode,change,changed,pick,calc_state){ return (function cljs$core$async$mix_$___GT_t_cljs$core$async16320(out__$1,cs__$1,solo_modes__$1,attrs__$1,solo_mode__$1,change__$1,changed__$1,pick__$1,calc_state__$1,meta16321){ return (new cljs.core.async.t_cljs$core$async16320(out__$1,cs__$1,solo_modes__$1,attrs__$1,solo_mode__$1,change__$1,changed__$1,pick__$1,calc_state__$1,meta16321)); });})(cs,solo_modes,attrs,solo_mode,change,changed,pick,calc_state)) ; } return (new cljs.core.async.t_cljs$core$async16320(out,cs,solo_modes,attrs,solo_mode,change,changed,pick,calc_state,cljs.core.PersistentArrayMap.EMPTY)); })() ; var c__15437__auto___16484 = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1((1)); cljs.core.async.impl.dispatch.run(((function (c__15437__auto___16484,cs,solo_modes,attrs,solo_mode,change,changed,pick,calc_state,m){ return (function (){ var f__15438__auto__ = (function (){var switch__15337__auto__ = ((function (c__15437__auto___16484,cs,solo_modes,attrs,solo_mode,change,changed,pick,calc_state,m){ return (function (state_16424){ var state_val_16425 = (state_16424[(1)]); if((state_val_16425 === (7))){ var inst_16339 = (state_16424[(2)]); var state_16424__$1 = state_16424; var statearr_16426_16485 = state_16424__$1; (statearr_16426_16485[(2)] = inst_16339); (statearr_16426_16485[(1)] = (4)); return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (20))){ var inst_16351 = (state_16424[(7)]); var state_16424__$1 = state_16424; var statearr_16427_16486 = state_16424__$1; (statearr_16427_16486[(2)] = inst_16351); (statearr_16427_16486[(1)] = (21)); return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (27))){ var state_16424__$1 = state_16424; var statearr_16428_16487 = state_16424__$1; (statearr_16428_16487[(2)] = null); (statearr_16428_16487[(1)] = (28)); return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (1))){ var inst_16326 = (state_16424[(8)]); var inst_16326__$1 = calc_state(); var inst_16328 = (inst_16326__$1 == null); var inst_16329 = cljs.core.not(inst_16328); var state_16424__$1 = (function (){var statearr_16429 = state_16424; (statearr_16429[(8)] = inst_16326__$1); return statearr_16429; })(); if(inst_16329){ var statearr_16430_16488 = state_16424__$1; (statearr_16430_16488[(1)] = (2)); } else { var statearr_16431_16489 = state_16424__$1; (statearr_16431_16489[(1)] = (3)); } return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (24))){ var inst_16375 = (state_16424[(9)]); var inst_16384 = (state_16424[(10)]); var inst_16398 = (state_16424[(11)]); var inst_16398__$1 = (inst_16375.cljs$core$IFn$_invoke$arity$1 ? inst_16375.cljs$core$IFn$_invoke$arity$1(inst_16384) : inst_16375.call(null,inst_16384)); var state_16424__$1 = (function (){var statearr_16432 = state_16424; (statearr_16432[(11)] = inst_16398__$1); return statearr_16432; })(); if(cljs.core.truth_(inst_16398__$1)){ var statearr_16433_16490 = state_16424__$1; (statearr_16433_16490[(1)] = (29)); } else { var statearr_16434_16491 = state_16424__$1; (statearr_16434_16491[(1)] = (30)); } return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (4))){ var inst_16342 = (state_16424[(2)]); var state_16424__$1 = state_16424; if(cljs.core.truth_(inst_16342)){ var statearr_16435_16492 = state_16424__$1; (statearr_16435_16492[(1)] = (8)); } else { var statearr_16436_16493 = state_16424__$1; (statearr_16436_16493[(1)] = (9)); } return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (15))){ var inst_16369 = (state_16424[(2)]); var state_16424__$1 = state_16424; if(cljs.core.truth_(inst_16369)){ var statearr_16437_16494 = state_16424__$1; (statearr_16437_16494[(1)] = (19)); } else { var statearr_16438_16495 = state_16424__$1; (statearr_16438_16495[(1)] = (20)); } return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (21))){ var inst_16374 = (state_16424[(12)]); var inst_16374__$1 = (state_16424[(2)]); var inst_16375 = cljs.core.get.cljs$core$IFn$_invoke$arity$2(inst_16374__$1,cljs.core.cst$kw$solos); var inst_16376 = cljs.core.get.cljs$core$IFn$_invoke$arity$2(inst_16374__$1,cljs.core.cst$kw$mutes); var inst_16377 = cljs.core.get.cljs$core$IFn$_invoke$arity$2(inst_16374__$1,cljs.core.cst$kw$reads); var state_16424__$1 = (function (){var statearr_16439 = state_16424; (statearr_16439[(13)] = inst_16376); (statearr_16439[(9)] = inst_16375); (statearr_16439[(12)] = inst_16374__$1); return statearr_16439; })(); return cljs.core.async.ioc_alts_BANG_(state_16424__$1,(22),inst_16377); } else { if((state_val_16425 === (31))){ var inst_16406 = (state_16424[(2)]); var state_16424__$1 = state_16424; if(cljs.core.truth_(inst_16406)){ var statearr_16440_16496 = state_16424__$1; (statearr_16440_16496[(1)] = (32)); } else { var statearr_16441_16497 = state_16424__$1; (statearr_16441_16497[(1)] = (33)); } return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (32))){ var inst_16383 = (state_16424[(14)]); var state_16424__$1 = state_16424; return cljs.core.async.impl.ioc_helpers.put_BANG_(state_16424__$1,(35),out,inst_16383); } else { if((state_val_16425 === (33))){ var inst_16374 = (state_16424[(12)]); var inst_16351 = inst_16374; var state_16424__$1 = (function (){var statearr_16442 = state_16424; (statearr_16442[(7)] = inst_16351); return statearr_16442; })(); var statearr_16443_16498 = state_16424__$1; (statearr_16443_16498[(2)] = null); (statearr_16443_16498[(1)] = (11)); return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (13))){ var inst_16351 = (state_16424[(7)]); var inst_16358 = inst_16351.cljs$lang$protocol_mask$partition0$; var inst_16359 = (inst_16358 & (64)); var inst_16360 = inst_16351.cljs$core$ISeq$; var inst_16361 = (cljs.core.PROTOCOL_SENTINEL === inst_16360); var inst_16362 = (inst_16359) || (inst_16361); var state_16424__$1 = state_16424; if(cljs.core.truth_(inst_16362)){ var statearr_16444_16499 = state_16424__$1; (statearr_16444_16499[(1)] = (16)); } else { var statearr_16445_16500 = state_16424__$1; (statearr_16445_16500[(1)] = (17)); } return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (22))){ var inst_16383 = (state_16424[(14)]); var inst_16384 = (state_16424[(10)]); var inst_16382 = (state_16424[(2)]); var inst_16383__$1 = cljs.core.nth.cljs$core$IFn$_invoke$arity$3(inst_16382,(0),null); var inst_16384__$1 = cljs.core.nth.cljs$core$IFn$_invoke$arity$3(inst_16382,(1),null); var inst_16385 = (inst_16383__$1 == null); var inst_16386 = cljs.core._EQ_.cljs$core$IFn$_invoke$arity$2(inst_16384__$1,change); var inst_16387 = (inst_16385) || (inst_16386); var state_16424__$1 = (function (){var statearr_16446 = state_16424; (statearr_16446[(14)] = inst_16383__$1); (statearr_16446[(10)] = inst_16384__$1); return statearr_16446; })(); if(cljs.core.truth_(inst_16387)){ var statearr_16447_16501 = state_16424__$1; (statearr_16447_16501[(1)] = (23)); } else { var statearr_16448_16502 = state_16424__$1; (statearr_16448_16502[(1)] = (24)); } return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (36))){ var inst_16374 = (state_16424[(12)]); var inst_16351 = inst_16374; var state_16424__$1 = (function (){var statearr_16449 = state_16424; (statearr_16449[(7)] = inst_16351); return statearr_16449; })(); var statearr_16450_16503 = state_16424__$1; (statearr_16450_16503[(2)] = null); (statearr_16450_16503[(1)] = (11)); return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (29))){ var inst_16398 = (state_16424[(11)]); var state_16424__$1 = state_16424; var statearr_16451_16504 = state_16424__$1; (statearr_16451_16504[(2)] = inst_16398); (statearr_16451_16504[(1)] = (31)); return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (6))){ var state_16424__$1 = state_16424; var statearr_16452_16505 = state_16424__$1; (statearr_16452_16505[(2)] = false); (statearr_16452_16505[(1)] = (7)); return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (28))){ var inst_16394 = (state_16424[(2)]); var inst_16395 = calc_state(); var inst_16351 = inst_16395; var state_16424__$1 = (function (){var statearr_16453 = state_16424; (statearr_16453[(15)] = inst_16394); (statearr_16453[(7)] = inst_16351); return statearr_16453; })(); var statearr_16454_16506 = state_16424__$1; (statearr_16454_16506[(2)] = null); (statearr_16454_16506[(1)] = (11)); return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (25))){ var inst_16420 = (state_16424[(2)]); var state_16424__$1 = state_16424; var statearr_16455_16507 = state_16424__$1; (statearr_16455_16507[(2)] = inst_16420); (statearr_16455_16507[(1)] = (12)); return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (34))){ var inst_16418 = (state_16424[(2)]); var state_16424__$1 = state_16424; var statearr_16456_16508 = state_16424__$1; (statearr_16456_16508[(2)] = inst_16418); (statearr_16456_16508[(1)] = (25)); return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (17))){ var state_16424__$1 = state_16424; var statearr_16457_16509 = state_16424__$1; (statearr_16457_16509[(2)] = false); (statearr_16457_16509[(1)] = (18)); return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (3))){ var state_16424__$1 = state_16424; var statearr_16458_16510 = state_16424__$1; (statearr_16458_16510[(2)] = false); (statearr_16458_16510[(1)] = (4)); return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (12))){ var inst_16422 = (state_16424[(2)]); var state_16424__$1 = state_16424; return cljs.core.async.impl.ioc_helpers.return_chan(state_16424__$1,inst_16422); } else { if((state_val_16425 === (2))){ var inst_16326 = (state_16424[(8)]); var inst_16331 = inst_16326.cljs$lang$protocol_mask$partition0$; var inst_16332 = (inst_16331 & (64)); var inst_16333 = inst_16326.cljs$core$ISeq$; var inst_16334 = (cljs.core.PROTOCOL_SENTINEL === inst_16333); var inst_16335 = (inst_16332) || (inst_16334); var state_16424__$1 = state_16424; if(cljs.core.truth_(inst_16335)){ var statearr_16459_16511 = state_16424__$1; (statearr_16459_16511[(1)] = (5)); } else { var statearr_16460_16512 = state_16424__$1; (statearr_16460_16512[(1)] = (6)); } return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (23))){ var inst_16383 = (state_16424[(14)]); var inst_16389 = (inst_16383 == null); var state_16424__$1 = state_16424; if(cljs.core.truth_(inst_16389)){ var statearr_16461_16513 = state_16424__$1; (statearr_16461_16513[(1)] = (26)); } else { var statearr_16462_16514 = state_16424__$1; (statearr_16462_16514[(1)] = (27)); } return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (35))){ var inst_16409 = (state_16424[(2)]); var state_16424__$1 = state_16424; if(cljs.core.truth_(inst_16409)){ var statearr_16463_16515 = state_16424__$1; (statearr_16463_16515[(1)] = (36)); } else { var statearr_16464_16516 = state_16424__$1; (statearr_16464_16516[(1)] = (37)); } return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (19))){ var inst_16351 = (state_16424[(7)]); var inst_16371 = cljs.core.apply.cljs$core$IFn$_invoke$arity$2(cljs.core.hash_map,inst_16351); var state_16424__$1 = state_16424; var statearr_16465_16517 = state_16424__$1; (statearr_16465_16517[(2)] = inst_16371); (statearr_16465_16517[(1)] = (21)); return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (11))){ var inst_16351 = (state_16424[(7)]); var inst_16355 = (inst_16351 == null); var inst_16356 = cljs.core.not(inst_16355); var state_16424__$1 = state_16424; if(inst_16356){ var statearr_16466_16518 = state_16424__$1; (statearr_16466_16518[(1)] = (13)); } else { var statearr_16467_16519 = state_16424__$1; (statearr_16467_16519[(1)] = (14)); } return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (9))){ var inst_16326 = (state_16424[(8)]); var state_16424__$1 = state_16424; var statearr_16468_16520 = state_16424__$1; (statearr_16468_16520[(2)] = inst_16326); (statearr_16468_16520[(1)] = (10)); return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (5))){ var state_16424__$1 = state_16424; var statearr_16469_16521 = state_16424__$1; (statearr_16469_16521[(2)] = true); (statearr_16469_16521[(1)] = (7)); return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (14))){ var state_16424__$1 = state_16424; var statearr_16470_16522 = state_16424__$1; (statearr_16470_16522[(2)] = false); (statearr_16470_16522[(1)] = (15)); return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (26))){ var inst_16384 = (state_16424[(10)]); var inst_16391 = cljs.core.swap_BANG_.cljs$core$IFn$_invoke$arity$3(cs,cljs.core.dissoc,inst_16384); var state_16424__$1 = state_16424; var statearr_16471_16523 = state_16424__$1; (statearr_16471_16523[(2)] = inst_16391); (statearr_16471_16523[(1)] = (28)); return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (16))){ var state_16424__$1 = state_16424; var statearr_16472_16524 = state_16424__$1; (statearr_16472_16524[(2)] = true); (statearr_16472_16524[(1)] = (18)); return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (38))){ var inst_16414 = (state_16424[(2)]); var state_16424__$1 = state_16424; var statearr_16473_16525 = state_16424__$1; (statearr_16473_16525[(2)] = inst_16414); (statearr_16473_16525[(1)] = (34)); return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (30))){ var inst_16376 = (state_16424[(13)]); var inst_16375 = (state_16424[(9)]); var inst_16384 = (state_16424[(10)]); var inst_16401 = cljs.core.empty_QMARK_(inst_16375); var inst_16402 = (inst_16376.cljs$core$IFn$_invoke$arity$1 ? inst_16376.cljs$core$IFn$_invoke$arity$1(inst_16384) : inst_16376.call(null,inst_16384)); var inst_16403 = cljs.core.not(inst_16402); var inst_16404 = (inst_16401) && (inst_16403); var state_16424__$1 = state_16424; var statearr_16474_16526 = state_16424__$1; (statearr_16474_16526[(2)] = inst_16404); (statearr_16474_16526[(1)] = (31)); return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (10))){ var inst_16326 = (state_16424[(8)]); var inst_16347 = (state_16424[(2)]); var inst_16348 = cljs.core.get.cljs$core$IFn$_invoke$arity$2(inst_16347,cljs.core.cst$kw$solos); var inst_16349 = cljs.core.get.cljs$core$IFn$_invoke$arity$2(inst_16347,cljs.core.cst$kw$mutes); var inst_16350 = cljs.core.get.cljs$core$IFn$_invoke$arity$2(inst_16347,cljs.core.cst$kw$reads); var inst_16351 = inst_16326; var state_16424__$1 = (function (){var statearr_16475 = state_16424; (statearr_16475[(16)] = inst_16349); (statearr_16475[(17)] = inst_16348); (statearr_16475[(18)] = inst_16350); (statearr_16475[(7)] = inst_16351); return statearr_16475; })(); var statearr_16476_16527 = state_16424__$1; (statearr_16476_16527[(2)] = null); (statearr_16476_16527[(1)] = (11)); return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (18))){ var inst_16366 = (state_16424[(2)]); var state_16424__$1 = state_16424; var statearr_16477_16528 = state_16424__$1; (statearr_16477_16528[(2)] = inst_16366); (statearr_16477_16528[(1)] = (15)); return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (37))){ var state_16424__$1 = state_16424; var statearr_16478_16529 = state_16424__$1; (statearr_16478_16529[(2)] = null); (statearr_16478_16529[(1)] = (38)); return cljs.core.cst$kw$recur; } else { if((state_val_16425 === (8))){ var inst_16326 = (state_16424[(8)]); var inst_16344 = cljs.core.apply.cljs$core$IFn$_invoke$arity$2(cljs.core.hash_map,inst_16326); var state_16424__$1 = state_16424; var statearr_16479_16530 = state_16424__$1; (statearr_16479_16530[(2)] = inst_16344); (statearr_16479_16530[(1)] = (10)); return cljs.core.cst$kw$recur; } else { return null; } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } });})(c__15437__auto___16484,cs,solo_modes,attrs,solo_mode,change,changed,pick,calc_state,m)) ; return ((function (switch__15337__auto__,c__15437__auto___16484,cs,solo_modes,attrs,solo_mode,change,changed,pick,calc_state,m){ return (function() { var cljs$core$async$mix_$_state_machine__15338__auto__ = null; var cljs$core$async$mix_$_state_machine__15338__auto____0 = (function (){ var statearr_16480 = [null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null]; (statearr_16480[(0)] = cljs$core$async$mix_$_state_machine__15338__auto__); (statearr_16480[(1)] = (1)); return statearr_16480; }); var cljs$core$async$mix_$_state_machine__15338__auto____1 = (function (state_16424){ while(true){ var ret_value__15339__auto__ = (function (){try{while(true){ var result__15340__auto__ = switch__15337__auto__(state_16424); if(cljs.core.keyword_identical_QMARK_(result__15340__auto__,cljs.core.cst$kw$recur)){ continue; } else { return result__15340__auto__; } break; } }catch (e16481){if((e16481 instanceof Object)){ var ex__15341__auto__ = e16481; var statearr_16482_16531 = state_16424; (statearr_16482_16531[(5)] = ex__15341__auto__); cljs.core.async.impl.ioc_helpers.process_exception(state_16424); return cljs.core.cst$kw$recur; } else { throw e16481; } }})(); if(cljs.core.keyword_identical_QMARK_(ret_value__15339__auto__,cljs.core.cst$kw$recur)){ var G__16532 = state_16424; state_16424 = G__16532; continue; } else { return ret_value__15339__auto__; } break; } }); cljs$core$async$mix_$_state_machine__15338__auto__ = function(state_16424){ switch(arguments.length){ case 0: return cljs$core$async$mix_$_state_machine__15338__auto____0.call(this); case 1: return cljs$core$async$mix_$_state_machine__15338__auto____1.call(this,state_16424); } throw(new Error('Invalid arity: ' + (arguments.length - 1))); }; cljs$core$async$mix_$_state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$0 = cljs$core$async$mix_$_state_machine__15338__auto____0; cljs$core$async$mix_$_state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$1 = cljs$core$async$mix_$_state_machine__15338__auto____1; return cljs$core$async$mix_$_state_machine__15338__auto__; })() ;})(switch__15337__auto__,c__15437__auto___16484,cs,solo_modes,attrs,solo_mode,change,changed,pick,calc_state,m)) })(); var state__15439__auto__ = (function (){var statearr_16483 = (f__15438__auto__.cljs$core$IFn$_invoke$arity$0 ? f__15438__auto__.cljs$core$IFn$_invoke$arity$0() : f__15438__auto__.call(null)); (statearr_16483[(6)] = c__15437__auto___16484); return statearr_16483; })(); return cljs.core.async.impl.ioc_helpers.run_state_machine_wrapped(state__15439__auto__); });})(c__15437__auto___16484,cs,solo_modes,attrs,solo_mode,change,changed,pick,calc_state,m)) ); return m; }); /** * Adds ch as an input to the mix */ cljs.core.async.admix = (function cljs$core$async$admix(mix,ch){ return cljs.core.async.admix_STAR_(mix,ch); }); /** * Removes ch as an input to the mix */ cljs.core.async.unmix = (function cljs$core$async$unmix(mix,ch){ return cljs.core.async.unmix_STAR_(mix,ch); }); /** * removes all inputs from the mix */ cljs.core.async.unmix_all = (function cljs$core$async$unmix_all(mix){ return cljs.core.async.unmix_all_STAR_(mix); }); /** * Atomically sets the state(s) of one or more channels in a mix. The * state map is a map of channels -> channel-state-map. A * channel-state-map is a map of attrs -> boolean, where attr is one or * more of :mute, :pause or :solo. Any states supplied are merged with * the current state. * * Note that channels can be added to a mix via toggle, which can be * used to add channels in a particular (e.g. paused) state. */ cljs.core.async.toggle = (function cljs$core$async$toggle(mix,state_map){ return cljs.core.async.toggle_STAR_(mix,state_map); }); /** * Sets the solo mode of the mix. mode must be one of :mute or :pause */ cljs.core.async.solo_mode = (function cljs$core$async$solo_mode(mix,mode){ return cljs.core.async.solo_mode_STAR_(mix,mode); }); /** * @interface */ cljs.core.async.Pub = function(){}; cljs.core.async.sub_STAR_ = (function cljs$core$async$sub_STAR_(p,v,ch,close_QMARK_){ if((!((p == null))) && (!((p.cljs$core$async$Pub$sub_STAR_$arity$4 == null)))){ return p.cljs$core$async$Pub$sub_STAR_$arity$4(p,v,ch,close_QMARK_); } else { var x__8351__auto__ = (((p == null))?null:p); var m__8352__auto__ = (cljs.core.async.sub_STAR_[goog.typeOf(x__8351__auto__)]); if(!((m__8352__auto__ == null))){ return (m__8352__auto__.cljs$core$IFn$_invoke$arity$4 ? m__8352__auto__.cljs$core$IFn$_invoke$arity$4(p,v,ch,close_QMARK_) : m__8352__auto__.call(null,p,v,ch,close_QMARK_)); } else { var m__8352__auto____$1 = (cljs.core.async.sub_STAR_["_"]); if(!((m__8352__auto____$1 == null))){ return (m__8352__auto____$1.cljs$core$IFn$_invoke$arity$4 ? m__8352__auto____$1.cljs$core$IFn$_invoke$arity$4(p,v,ch,close_QMARK_) : m__8352__auto____$1.call(null,p,v,ch,close_QMARK_)); } else { throw cljs.core.missing_protocol("Pub.sub*",p); } } } }); cljs.core.async.unsub_STAR_ = (function cljs$core$async$unsub_STAR_(p,v,ch){ if((!((p == null))) && (!((p.cljs$core$async$Pub$unsub_STAR_$arity$3 == null)))){ return p.cljs$core$async$Pub$unsub_STAR_$arity$3(p,v,ch); } else { var x__8351__auto__ = (((p == null))?null:p); var m__8352__auto__ = (cljs.core.async.unsub_STAR_[goog.typeOf(x__8351__auto__)]); if(!((m__8352__auto__ == null))){ return (m__8352__auto__.cljs$core$IFn$_invoke$arity$3 ? m__8352__auto__.cljs$core$IFn$_invoke$arity$3(p,v,ch) : m__8352__auto__.call(null,p,v,ch)); } else { var m__8352__auto____$1 = (cljs.core.async.unsub_STAR_["_"]); if(!((m__8352__auto____$1 == null))){ return (m__8352__auto____$1.cljs$core$IFn$_invoke$arity$3 ? m__8352__auto____$1.cljs$core$IFn$_invoke$arity$3(p,v,ch) : m__8352__auto____$1.call(null,p,v,ch)); } else { throw cljs.core.missing_protocol("Pub.unsub*",p); } } } }); cljs.core.async.unsub_all_STAR_ = (function cljs$core$async$unsub_all_STAR_(var_args){ var G__16534 = arguments.length; switch (G__16534) { case 1: return cljs.core.async.unsub_all_STAR_.cljs$core$IFn$_invoke$arity$1((arguments[(0)])); break; case 2: return cljs.core.async.unsub_all_STAR_.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; default: throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join(''))); } }); cljs.core.async.unsub_all_STAR_.cljs$core$IFn$_invoke$arity$1 = (function (p){ if((!((p == null))) && (!((p.cljs$core$async$Pub$unsub_all_STAR_$arity$1 == null)))){ return p.cljs$core$async$Pub$unsub_all_STAR_$arity$1(p); } else { var x__8351__auto__ = (((p == null))?null:p); var m__8352__auto__ = (cljs.core.async.unsub_all_STAR_[goog.typeOf(x__8351__auto__)]); if(!((m__8352__auto__ == null))){ return (m__8352__auto__.cljs$core$IFn$_invoke$arity$1 ? m__8352__auto__.cljs$core$IFn$_invoke$arity$1(p) : m__8352__auto__.call(null,p)); } else { var m__8352__auto____$1 = (cljs.core.async.unsub_all_STAR_["_"]); if(!((m__8352__auto____$1 == null))){ return (m__8352__auto____$1.cljs$core$IFn$_invoke$arity$1 ? m__8352__auto____$1.cljs$core$IFn$_invoke$arity$1(p) : m__8352__auto____$1.call(null,p)); } else { throw cljs.core.missing_protocol("Pub.unsub-all*",p); } } } }); cljs.core.async.unsub_all_STAR_.cljs$core$IFn$_invoke$arity$2 = (function (p,v){ if((!((p == null))) && (!((p.cljs$core$async$Pub$unsub_all_STAR_$arity$2 == null)))){ return p.cljs$core$async$Pub$unsub_all_STAR_$arity$2(p,v); } else { var x__8351__auto__ = (((p == null))?null:p); var m__8352__auto__ = (cljs.core.async.unsub_all_STAR_[goog.typeOf(x__8351__auto__)]); if(!((m__8352__auto__ == null))){ return (m__8352__auto__.cljs$core$IFn$_invoke$arity$2 ? m__8352__auto__.cljs$core$IFn$_invoke$arity$2(p,v) : m__8352__auto__.call(null,p,v)); } else { var m__8352__auto____$1 = (cljs.core.async.unsub_all_STAR_["_"]); if(!((m__8352__auto____$1 == null))){ return (m__8352__auto____$1.cljs$core$IFn$_invoke$arity$2 ? m__8352__auto____$1.cljs$core$IFn$_invoke$arity$2(p,v) : m__8352__auto____$1.call(null,p,v)); } else { throw cljs.core.missing_protocol("Pub.unsub-all*",p); } } } }); cljs.core.async.unsub_all_STAR_.cljs$lang$maxFixedArity = 2; /** * Creates and returns a pub(lication) of the supplied channel, * partitioned into topics by the topic-fn. topic-fn will be applied to * each value on the channel and the result will determine the 'topic' * on which that value will be put. Channels can be subscribed to * receive copies of topics using 'sub', and unsubscribed using * 'unsub'. Each topic will be handled by an internal mult on a * dedicated channel. By default these internal channels are * unbuffered, but a buf-fn can be supplied which, given a topic, * creates a buffer with desired properties. * * Each item is distributed to all subs in parallel and synchronously, * i.e. each sub must accept before the next item is distributed. Use * buffering/windowing to prevent slow subs from holding up the pub. * * Items received when there are no matching subs get dropped. * * Note that if buf-fns are used then each topic is handled * asynchronously, i.e. if a channel is subscribed to more than one * topic it should not expect them to be interleaved identically with * the source. */ cljs.core.async.pub = (function cljs$core$async$pub(var_args){ var G__16538 = arguments.length; switch (G__16538) { case 2: return cljs.core.async.pub.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; case 3: return cljs.core.async.pub.cljs$core$IFn$_invoke$arity$3((arguments[(0)]),(arguments[(1)]),(arguments[(2)])); break; default: throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join(''))); } }); cljs.core.async.pub.cljs$core$IFn$_invoke$arity$2 = (function (ch,topic_fn){ return cljs.core.async.pub.cljs$core$IFn$_invoke$arity$3(ch,topic_fn,cljs.core.constantly(null)); }); cljs.core.async.pub.cljs$core$IFn$_invoke$arity$3 = (function (ch,topic_fn,buf_fn){ var mults = cljs.core.atom.cljs$core$IFn$_invoke$arity$1(cljs.core.PersistentArrayMap.EMPTY); var ensure_mult = ((function (mults){ return (function (topic){ var or__7668__auto__ = cljs.core.get.cljs$core$IFn$_invoke$arity$2(cljs.core.deref(mults),topic); if(cljs.core.truth_(or__7668__auto__)){ return or__7668__auto__; } else { return cljs.core.get.cljs$core$IFn$_invoke$arity$2(cljs.core.swap_BANG_.cljs$core$IFn$_invoke$arity$2(mults,((function (or__7668__auto__,mults){ return (function (p1__16536_SHARP_){ if(cljs.core.truth_((p1__16536_SHARP_.cljs$core$IFn$_invoke$arity$1 ? p1__16536_SHARP_.cljs$core$IFn$_invoke$arity$1(topic) : p1__16536_SHARP_.call(null,topic)))){ return p1__16536_SHARP_; } else { return cljs.core.assoc.cljs$core$IFn$_invoke$arity$3(p1__16536_SHARP_,topic,cljs.core.async.mult(cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1((buf_fn.cljs$core$IFn$_invoke$arity$1 ? buf_fn.cljs$core$IFn$_invoke$arity$1(topic) : buf_fn.call(null,topic))))); } });})(or__7668__auto__,mults)) ),topic); } });})(mults)) ; var p = (function (){ if(typeof cljs.core.async.t_cljs$core$async16539 !== 'undefined'){ } else { /** * @constructor * @implements {cljs.core.async.Pub} * @implements {cljs.core.IMeta} * @implements {cljs.core.async.Mux} * @implements {cljs.core.IWithMeta} */ cljs.core.async.t_cljs$core$async16539 = (function (ch,topic_fn,buf_fn,mults,ensure_mult,meta16540){ this.ch = ch; this.topic_fn = topic_fn; this.buf_fn = buf_fn; this.mults = mults; this.ensure_mult = ensure_mult; this.meta16540 = meta16540; this.cljs$lang$protocol_mask$partition0$ = 393216; this.cljs$lang$protocol_mask$partition1$ = 0; }); cljs.core.async.t_cljs$core$async16539.prototype.cljs$core$IWithMeta$_with_meta$arity$2 = ((function (mults,ensure_mult){ return (function (_16541,meta16540__$1){ var self__ = this; var _16541__$1 = this; return (new cljs.core.async.t_cljs$core$async16539(self__.ch,self__.topic_fn,self__.buf_fn,self__.mults,self__.ensure_mult,meta16540__$1)); });})(mults,ensure_mult)) ; cljs.core.async.t_cljs$core$async16539.prototype.cljs$core$IMeta$_meta$arity$1 = ((function (mults,ensure_mult){ return (function (_16541){ var self__ = this; var _16541__$1 = this; return self__.meta16540; });})(mults,ensure_mult)) ; cljs.core.async.t_cljs$core$async16539.prototype.cljs$core$async$Mux$ = cljs.core.PROTOCOL_SENTINEL; cljs.core.async.t_cljs$core$async16539.prototype.cljs$core$async$Mux$muxch_STAR_$arity$1 = ((function (mults,ensure_mult){ return (function (_){ var self__ = this; var ___$1 = this; return self__.ch; });})(mults,ensure_mult)) ; cljs.core.async.t_cljs$core$async16539.prototype.cljs$core$async$Pub$ = cljs.core.PROTOCOL_SENTINEL; cljs.core.async.t_cljs$core$async16539.prototype.cljs$core$async$Pub$sub_STAR_$arity$4 = ((function (mults,ensure_mult){ return (function (p,topic,ch__$1,close_QMARK_){ var self__ = this; var p__$1 = this; var m = (self__.ensure_mult.cljs$core$IFn$_invoke$arity$1 ? self__.ensure_mult.cljs$core$IFn$_invoke$arity$1(topic) : self__.ensure_mult.call(null,topic)); return cljs.core.async.tap.cljs$core$IFn$_invoke$arity$3(m,ch__$1,close_QMARK_); });})(mults,ensure_mult)) ; cljs.core.async.t_cljs$core$async16539.prototype.cljs$core$async$Pub$unsub_STAR_$arity$3 = ((function (mults,ensure_mult){ return (function (p,topic,ch__$1){ var self__ = this; var p__$1 = this; var temp__4657__auto__ = cljs.core.get.cljs$core$IFn$_invoke$arity$2(cljs.core.deref(self__.mults),topic); if(cljs.core.truth_(temp__4657__auto__)){ var m = temp__4657__auto__; return cljs.core.async.untap(m,ch__$1); } else { return null; } });})(mults,ensure_mult)) ; cljs.core.async.t_cljs$core$async16539.prototype.cljs$core$async$Pub$unsub_all_STAR_$arity$1 = ((function (mults,ensure_mult){ return (function (_){ var self__ = this; var ___$1 = this; return cljs.core.reset_BANG_(self__.mults,cljs.core.PersistentArrayMap.EMPTY); });})(mults,ensure_mult)) ; cljs.core.async.t_cljs$core$async16539.prototype.cljs$core$async$Pub$unsub_all_STAR_$arity$2 = ((function (mults,ensure_mult){ return (function (_,topic){ var self__ = this; var ___$1 = this; return cljs.core.swap_BANG_.cljs$core$IFn$_invoke$arity$3(self__.mults,cljs.core.dissoc,topic); });})(mults,ensure_mult)) ; cljs.core.async.t_cljs$core$async16539.getBasis = ((function (mults,ensure_mult){ return (function (){ return new cljs.core.PersistentVector(null, 6, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.cst$sym$ch,cljs.core.cst$sym$topic_DASH_fn,cljs.core.cst$sym$buf_DASH_fn,cljs.core.cst$sym$mults,cljs.core.cst$sym$ensure_DASH_mult,cljs.core.cst$sym$meta16540], null); });})(mults,ensure_mult)) ; cljs.core.async.t_cljs$core$async16539.cljs$lang$type = true; cljs.core.async.t_cljs$core$async16539.cljs$lang$ctorStr = "cljs.core.async/t_cljs$core$async16539"; cljs.core.async.t_cljs$core$async16539.cljs$lang$ctorPrWriter = ((function (mults,ensure_mult){ return (function (this__8293__auto__,writer__8294__auto__,opt__8295__auto__){ return cljs.core._write(writer__8294__auto__,"cljs.core.async/t_cljs$core$async16539"); });})(mults,ensure_mult)) ; cljs.core.async.__GT_t_cljs$core$async16539 = ((function (mults,ensure_mult){ return (function cljs$core$async$__GT_t_cljs$core$async16539(ch__$1,topic_fn__$1,buf_fn__$1,mults__$1,ensure_mult__$1,meta16540){ return (new cljs.core.async.t_cljs$core$async16539(ch__$1,topic_fn__$1,buf_fn__$1,mults__$1,ensure_mult__$1,meta16540)); });})(mults,ensure_mult)) ; } return (new cljs.core.async.t_cljs$core$async16539(ch,topic_fn,buf_fn,mults,ensure_mult,cljs.core.PersistentArrayMap.EMPTY)); })() ; var c__15437__auto___16659 = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1((1)); cljs.core.async.impl.dispatch.run(((function (c__15437__auto___16659,mults,ensure_mult,p){ return (function (){ var f__15438__auto__ = (function (){var switch__15337__auto__ = ((function (c__15437__auto___16659,mults,ensure_mult,p){ return (function (state_16613){ var state_val_16614 = (state_16613[(1)]); if((state_val_16614 === (7))){ var inst_16609 = (state_16613[(2)]); var state_16613__$1 = state_16613; var statearr_16615_16660 = state_16613__$1; (statearr_16615_16660[(2)] = inst_16609); (statearr_16615_16660[(1)] = (3)); return cljs.core.cst$kw$recur; } else { if((state_val_16614 === (20))){ var state_16613__$1 = state_16613; var statearr_16616_16661 = state_16613__$1; (statearr_16616_16661[(2)] = null); (statearr_16616_16661[(1)] = (21)); return cljs.core.cst$kw$recur; } else { if((state_val_16614 === (1))){ var state_16613__$1 = state_16613; var statearr_16617_16662 = state_16613__$1; (statearr_16617_16662[(2)] = null); (statearr_16617_16662[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_16614 === (24))){ var inst_16592 = (state_16613[(7)]); var inst_16601 = cljs.core.swap_BANG_.cljs$core$IFn$_invoke$arity$3(mults,cljs.core.dissoc,inst_16592); var state_16613__$1 = state_16613; var statearr_16618_16663 = state_16613__$1; (statearr_16618_16663[(2)] = inst_16601); (statearr_16618_16663[(1)] = (25)); return cljs.core.cst$kw$recur; } else { if((state_val_16614 === (4))){ var inst_16544 = (state_16613[(8)]); var inst_16544__$1 = (state_16613[(2)]); var inst_16545 = (inst_16544__$1 == null); var state_16613__$1 = (function (){var statearr_16619 = state_16613; (statearr_16619[(8)] = inst_16544__$1); return statearr_16619; })(); if(cljs.core.truth_(inst_16545)){ var statearr_16620_16664 = state_16613__$1; (statearr_16620_16664[(1)] = (5)); } else { var statearr_16621_16665 = state_16613__$1; (statearr_16621_16665[(1)] = (6)); } return cljs.core.cst$kw$recur; } else { if((state_val_16614 === (15))){ var inst_16586 = (state_16613[(2)]); var state_16613__$1 = state_16613; var statearr_16622_16666 = state_16613__$1; (statearr_16622_16666[(2)] = inst_16586); (statearr_16622_16666[(1)] = (12)); return cljs.core.cst$kw$recur; } else { if((state_val_16614 === (21))){ var inst_16606 = (state_16613[(2)]); var state_16613__$1 = (function (){var statearr_16623 = state_16613; (statearr_16623[(9)] = inst_16606); return statearr_16623; })(); var statearr_16624_16667 = state_16613__$1; (statearr_16624_16667[(2)] = null); (statearr_16624_16667[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_16614 === (13))){ var inst_16568 = (state_16613[(10)]); var inst_16570 = cljs.core.chunked_seq_QMARK_(inst_16568); var state_16613__$1 = state_16613; if(inst_16570){ var statearr_16625_16668 = state_16613__$1; (statearr_16625_16668[(1)] = (16)); } else { var statearr_16626_16669 = state_16613__$1; (statearr_16626_16669[(1)] = (17)); } return cljs.core.cst$kw$recur; } else { if((state_val_16614 === (22))){ var inst_16598 = (state_16613[(2)]); var state_16613__$1 = state_16613; if(cljs.core.truth_(inst_16598)){ var statearr_16627_16670 = state_16613__$1; (statearr_16627_16670[(1)] = (23)); } else { var statearr_16628_16671 = state_16613__$1; (statearr_16628_16671[(1)] = (24)); } return cljs.core.cst$kw$recur; } else { if((state_val_16614 === (6))){ var inst_16544 = (state_16613[(8)]); var inst_16592 = (state_16613[(7)]); var inst_16594 = (state_16613[(11)]); var inst_16592__$1 = (topic_fn.cljs$core$IFn$_invoke$arity$1 ? topic_fn.cljs$core$IFn$_invoke$arity$1(inst_16544) : topic_fn.call(null,inst_16544)); var inst_16593 = cljs.core.deref(mults); var inst_16594__$1 = cljs.core.get.cljs$core$IFn$_invoke$arity$2(inst_16593,inst_16592__$1); var state_16613__$1 = (function (){var statearr_16629 = state_16613; (statearr_16629[(7)] = inst_16592__$1); (statearr_16629[(11)] = inst_16594__$1); return statearr_16629; })(); if(cljs.core.truth_(inst_16594__$1)){ var statearr_16630_16672 = state_16613__$1; (statearr_16630_16672[(1)] = (19)); } else { var statearr_16631_16673 = state_16613__$1; (statearr_16631_16673[(1)] = (20)); } return cljs.core.cst$kw$recur; } else { if((state_val_16614 === (25))){ var inst_16603 = (state_16613[(2)]); var state_16613__$1 = state_16613; var statearr_16632_16674 = state_16613__$1; (statearr_16632_16674[(2)] = inst_16603); (statearr_16632_16674[(1)] = (21)); return cljs.core.cst$kw$recur; } else { if((state_val_16614 === (17))){ var inst_16568 = (state_16613[(10)]); var inst_16577 = cljs.core.first(inst_16568); var inst_16578 = cljs.core.async.muxch_STAR_(inst_16577); var inst_16579 = cljs.core.async.close_BANG_(inst_16578); var inst_16580 = cljs.core.next(inst_16568); var inst_16554 = inst_16580; var inst_16555 = null; var inst_16556 = (0); var inst_16557 = (0); var state_16613__$1 = (function (){var statearr_16633 = state_16613; (statearr_16633[(12)] = inst_16579); (statearr_16633[(13)] = inst_16557); (statearr_16633[(14)] = inst_16555); (statearr_16633[(15)] = inst_16556); (statearr_16633[(16)] = inst_16554); return statearr_16633; })(); var statearr_16634_16675 = state_16613__$1; (statearr_16634_16675[(2)] = null); (statearr_16634_16675[(1)] = (8)); return cljs.core.cst$kw$recur; } else { if((state_val_16614 === (3))){ var inst_16611 = (state_16613[(2)]); var state_16613__$1 = state_16613; return cljs.core.async.impl.ioc_helpers.return_chan(state_16613__$1,inst_16611); } else { if((state_val_16614 === (12))){ var inst_16588 = (state_16613[(2)]); var state_16613__$1 = state_16613; var statearr_16635_16676 = state_16613__$1; (statearr_16635_16676[(2)] = inst_16588); (statearr_16635_16676[(1)] = (9)); return cljs.core.cst$kw$recur; } else { if((state_val_16614 === (2))){ var state_16613__$1 = state_16613; return cljs.core.async.impl.ioc_helpers.take_BANG_(state_16613__$1,(4),ch); } else { if((state_val_16614 === (23))){ var state_16613__$1 = state_16613; var statearr_16636_16677 = state_16613__$1; (statearr_16636_16677[(2)] = null); (statearr_16636_16677[(1)] = (25)); return cljs.core.cst$kw$recur; } else { if((state_val_16614 === (19))){ var inst_16544 = (state_16613[(8)]); var inst_16594 = (state_16613[(11)]); var inst_16596 = cljs.core.async.muxch_STAR_(inst_16594); var state_16613__$1 = state_16613; return cljs.core.async.impl.ioc_helpers.put_BANG_(state_16613__$1,(22),inst_16596,inst_16544); } else { if((state_val_16614 === (11))){ var inst_16568 = (state_16613[(10)]); var inst_16554 = (state_16613[(16)]); var inst_16568__$1 = cljs.core.seq(inst_16554); var state_16613__$1 = (function (){var statearr_16637 = state_16613; (statearr_16637[(10)] = inst_16568__$1); return statearr_16637; })(); if(inst_16568__$1){ var statearr_16638_16678 = state_16613__$1; (statearr_16638_16678[(1)] = (13)); } else { var statearr_16639_16679 = state_16613__$1; (statearr_16639_16679[(1)] = (14)); } return cljs.core.cst$kw$recur; } else { if((state_val_16614 === (9))){ var inst_16590 = (state_16613[(2)]); var state_16613__$1 = state_16613; var statearr_16640_16680 = state_16613__$1; (statearr_16640_16680[(2)] = inst_16590); (statearr_16640_16680[(1)] = (7)); return cljs.core.cst$kw$recur; } else { if((state_val_16614 === (5))){ var inst_16551 = cljs.core.deref(mults); var inst_16552 = cljs.core.vals(inst_16551); var inst_16553 = cljs.core.seq(inst_16552); var inst_16554 = inst_16553; var inst_16555 = null; var inst_16556 = (0); var inst_16557 = (0); var state_16613__$1 = (function (){var statearr_16641 = state_16613; (statearr_16641[(13)] = inst_16557); (statearr_16641[(14)] = inst_16555); (statearr_16641[(15)] = inst_16556); (statearr_16641[(16)] = inst_16554); return statearr_16641; })(); var statearr_16642_16681 = state_16613__$1; (statearr_16642_16681[(2)] = null); (statearr_16642_16681[(1)] = (8)); return cljs.core.cst$kw$recur; } else { if((state_val_16614 === (14))){ var state_16613__$1 = state_16613; var statearr_16646_16682 = state_16613__$1; (statearr_16646_16682[(2)] = null); (statearr_16646_16682[(1)] = (15)); return cljs.core.cst$kw$recur; } else { if((state_val_16614 === (16))){ var inst_16568 = (state_16613[(10)]); var inst_16572 = cljs.core.chunk_first(inst_16568); var inst_16573 = cljs.core.chunk_rest(inst_16568); var inst_16574 = cljs.core.count(inst_16572); var inst_16554 = inst_16573; var inst_16555 = inst_16572; var inst_16556 = inst_16574; var inst_16557 = (0); var state_16613__$1 = (function (){var statearr_16647 = state_16613; (statearr_16647[(13)] = inst_16557); (statearr_16647[(14)] = inst_16555); (statearr_16647[(15)] = inst_16556); (statearr_16647[(16)] = inst_16554); return statearr_16647; })(); var statearr_16648_16683 = state_16613__$1; (statearr_16648_16683[(2)] = null); (statearr_16648_16683[(1)] = (8)); return cljs.core.cst$kw$recur; } else { if((state_val_16614 === (10))){ var inst_16557 = (state_16613[(13)]); var inst_16555 = (state_16613[(14)]); var inst_16556 = (state_16613[(15)]); var inst_16554 = (state_16613[(16)]); var inst_16562 = cljs.core._nth.cljs$core$IFn$_invoke$arity$2(inst_16555,inst_16557); var inst_16563 = cljs.core.async.muxch_STAR_(inst_16562); var inst_16564 = cljs.core.async.close_BANG_(inst_16563); var inst_16565 = (inst_16557 + (1)); var tmp16643 = inst_16555; var tmp16644 = inst_16556; var tmp16645 = inst_16554; var inst_16554__$1 = tmp16645; var inst_16555__$1 = tmp16643; var inst_16556__$1 = tmp16644; var inst_16557__$1 = inst_16565; var state_16613__$1 = (function (){var statearr_16649 = state_16613; (statearr_16649[(17)] = inst_16564); (statearr_16649[(13)] = inst_16557__$1); (statearr_16649[(14)] = inst_16555__$1); (statearr_16649[(15)] = inst_16556__$1); (statearr_16649[(16)] = inst_16554__$1); return statearr_16649; })(); var statearr_16650_16684 = state_16613__$1; (statearr_16650_16684[(2)] = null); (statearr_16650_16684[(1)] = (8)); return cljs.core.cst$kw$recur; } else { if((state_val_16614 === (18))){ var inst_16583 = (state_16613[(2)]); var state_16613__$1 = state_16613; var statearr_16651_16685 = state_16613__$1; (statearr_16651_16685[(2)] = inst_16583); (statearr_16651_16685[(1)] = (15)); return cljs.core.cst$kw$recur; } else { if((state_val_16614 === (8))){ var inst_16557 = (state_16613[(13)]); var inst_16556 = (state_16613[(15)]); var inst_16559 = (inst_16557 < inst_16556); var inst_16560 = inst_16559; var state_16613__$1 = state_16613; if(cljs.core.truth_(inst_16560)){ var statearr_16652_16686 = state_16613__$1; (statearr_16652_16686[(1)] = (10)); } else { var statearr_16653_16687 = state_16613__$1; (statearr_16653_16687[(1)] = (11)); } return cljs.core.cst$kw$recur; } else { return null; } } } } } } } } } } } } } } } } } } } } } } } } } });})(c__15437__auto___16659,mults,ensure_mult,p)) ; return ((function (switch__15337__auto__,c__15437__auto___16659,mults,ensure_mult,p){ return (function() { var cljs$core$async$state_machine__15338__auto__ = null; var cljs$core$async$state_machine__15338__auto____0 = (function (){ var statearr_16654 = [null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null]; (statearr_16654[(0)] = cljs$core$async$state_machine__15338__auto__); (statearr_16654[(1)] = (1)); return statearr_16654; }); var cljs$core$async$state_machine__15338__auto____1 = (function (state_16613){ while(true){ var ret_value__15339__auto__ = (function (){try{while(true){ var result__15340__auto__ = switch__15337__auto__(state_16613); if(cljs.core.keyword_identical_QMARK_(result__15340__auto__,cljs.core.cst$kw$recur)){ continue; } else { return result__15340__auto__; } break; } }catch (e16655){if((e16655 instanceof Object)){ var ex__15341__auto__ = e16655; var statearr_16656_16688 = state_16613; (statearr_16656_16688[(5)] = ex__15341__auto__); cljs.core.async.impl.ioc_helpers.process_exception(state_16613); return cljs.core.cst$kw$recur; } else { throw e16655; } }})(); if(cljs.core.keyword_identical_QMARK_(ret_value__15339__auto__,cljs.core.cst$kw$recur)){ var G__16689 = state_16613; state_16613 = G__16689; continue; } else { return ret_value__15339__auto__; } break; } }); cljs$core$async$state_machine__15338__auto__ = function(state_16613){ switch(arguments.length){ case 0: return cljs$core$async$state_machine__15338__auto____0.call(this); case 1: return cljs$core$async$state_machine__15338__auto____1.call(this,state_16613); } throw(new Error('Invalid arity: ' + (arguments.length - 1))); }; cljs$core$async$state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$0 = cljs$core$async$state_machine__15338__auto____0; cljs$core$async$state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$1 = cljs$core$async$state_machine__15338__auto____1; return cljs$core$async$state_machine__15338__auto__; })() ;})(switch__15337__auto__,c__15437__auto___16659,mults,ensure_mult,p)) })(); var state__15439__auto__ = (function (){var statearr_16657 = (f__15438__auto__.cljs$core$IFn$_invoke$arity$0 ? f__15438__auto__.cljs$core$IFn$_invoke$arity$0() : f__15438__auto__.call(null)); (statearr_16657[(6)] = c__15437__auto___16659); return statearr_16657; })(); return cljs.core.async.impl.ioc_helpers.run_state_machine_wrapped(state__15439__auto__); });})(c__15437__auto___16659,mults,ensure_mult,p)) ); return p; }); cljs.core.async.pub.cljs$lang$maxFixedArity = 3; /** * Subscribes a channel to a topic of a pub. * * By default the channel will be closed when the source closes, * but can be determined by the close? parameter. */ cljs.core.async.sub = (function cljs$core$async$sub(var_args){ var G__16691 = arguments.length; switch (G__16691) { case 3: return cljs.core.async.sub.cljs$core$IFn$_invoke$arity$3((arguments[(0)]),(arguments[(1)]),(arguments[(2)])); break; case 4: return cljs.core.async.sub.cljs$core$IFn$_invoke$arity$4((arguments[(0)]),(arguments[(1)]),(arguments[(2)]),(arguments[(3)])); break; default: throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join(''))); } }); cljs.core.async.sub.cljs$core$IFn$_invoke$arity$3 = (function (p,topic,ch){ return cljs.core.async.sub.cljs$core$IFn$_invoke$arity$4(p,topic,ch,true); }); cljs.core.async.sub.cljs$core$IFn$_invoke$arity$4 = (function (p,topic,ch,close_QMARK_){ return cljs.core.async.sub_STAR_(p,topic,ch,close_QMARK_); }); cljs.core.async.sub.cljs$lang$maxFixedArity = 4; /** * Unsubscribes a channel from a topic of a pub */ cljs.core.async.unsub = (function cljs$core$async$unsub(p,topic,ch){ return cljs.core.async.unsub_STAR_(p,topic,ch); }); /** * Unsubscribes all channels from a pub, or a topic of a pub */ cljs.core.async.unsub_all = (function cljs$core$async$unsub_all(var_args){ var G__16694 = arguments.length; switch (G__16694) { case 1: return cljs.core.async.unsub_all.cljs$core$IFn$_invoke$arity$1((arguments[(0)])); break; case 2: return cljs.core.async.unsub_all.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; default: throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join(''))); } }); cljs.core.async.unsub_all.cljs$core$IFn$_invoke$arity$1 = (function (p){ return cljs.core.async.unsub_all_STAR_.cljs$core$IFn$_invoke$arity$1(p); }); cljs.core.async.unsub_all.cljs$core$IFn$_invoke$arity$2 = (function (p,topic){ return cljs.core.async.unsub_all_STAR_.cljs$core$IFn$_invoke$arity$2(p,topic); }); cljs.core.async.unsub_all.cljs$lang$maxFixedArity = 2; /** * Takes a function and a collection of source channels, and returns a * channel which contains the values produced by applying f to the set * of first items taken from each source channel, followed by applying * f to the set of second items from each channel, until any one of the * channels is closed, at which point the output channel will be * closed. The returned channel will be unbuffered by default, or a * buf-or-n can be supplied */ cljs.core.async.map = (function cljs$core$async$map(var_args){ var G__16697 = arguments.length; switch (G__16697) { case 2: return cljs.core.async.map.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; case 3: return cljs.core.async.map.cljs$core$IFn$_invoke$arity$3((arguments[(0)]),(arguments[(1)]),(arguments[(2)])); break; default: throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join(''))); } }); cljs.core.async.map.cljs$core$IFn$_invoke$arity$2 = (function (f,chs){ return cljs.core.async.map.cljs$core$IFn$_invoke$arity$3(f,chs,null); }); cljs.core.async.map.cljs$core$IFn$_invoke$arity$3 = (function (f,chs,buf_or_n){ var chs__$1 = cljs.core.vec(chs); var out = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1(buf_or_n); var cnt = cljs.core.count(chs__$1); var rets = cljs.core.object_array.cljs$core$IFn$_invoke$arity$1(cnt); var dchan = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1((1)); var dctr = cljs.core.atom.cljs$core$IFn$_invoke$arity$1(null); var done = cljs.core.mapv.cljs$core$IFn$_invoke$arity$2(((function (chs__$1,out,cnt,rets,dchan,dctr){ return (function (i){ return ((function (chs__$1,out,cnt,rets,dchan,dctr){ return (function (ret){ (rets[i] = ret); if((cljs.core.swap_BANG_.cljs$core$IFn$_invoke$arity$2(dctr,cljs.core.dec) === (0))){ return cljs.core.async.put_BANG_.cljs$core$IFn$_invoke$arity$2(dchan,rets.slice((0))); } else { return null; } }); ;})(chs__$1,out,cnt,rets,dchan,dctr)) });})(chs__$1,out,cnt,rets,dchan,dctr)) ,cljs.core.range.cljs$core$IFn$_invoke$arity$1(cnt)); var c__15437__auto___16764 = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1((1)); cljs.core.async.impl.dispatch.run(((function (c__15437__auto___16764,chs__$1,out,cnt,rets,dchan,dctr,done){ return (function (){ var f__15438__auto__ = (function (){var switch__15337__auto__ = ((function (c__15437__auto___16764,chs__$1,out,cnt,rets,dchan,dctr,done){ return (function (state_16736){ var state_val_16737 = (state_16736[(1)]); if((state_val_16737 === (7))){ var state_16736__$1 = state_16736; var statearr_16738_16765 = state_16736__$1; (statearr_16738_16765[(2)] = null); (statearr_16738_16765[(1)] = (8)); return cljs.core.cst$kw$recur; } else { if((state_val_16737 === (1))){ var state_16736__$1 = state_16736; var statearr_16739_16766 = state_16736__$1; (statearr_16739_16766[(2)] = null); (statearr_16739_16766[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_16737 === (4))){ var inst_16700 = (state_16736[(7)]); var inst_16702 = (inst_16700 < cnt); var state_16736__$1 = state_16736; if(cljs.core.truth_(inst_16702)){ var statearr_16740_16767 = state_16736__$1; (statearr_16740_16767[(1)] = (6)); } else { var statearr_16741_16768 = state_16736__$1; (statearr_16741_16768[(1)] = (7)); } return cljs.core.cst$kw$recur; } else { if((state_val_16737 === (15))){ var inst_16732 = (state_16736[(2)]); var state_16736__$1 = state_16736; var statearr_16742_16769 = state_16736__$1; (statearr_16742_16769[(2)] = inst_16732); (statearr_16742_16769[(1)] = (3)); return cljs.core.cst$kw$recur; } else { if((state_val_16737 === (13))){ var inst_16725 = cljs.core.async.close_BANG_(out); var state_16736__$1 = state_16736; var statearr_16743_16770 = state_16736__$1; (statearr_16743_16770[(2)] = inst_16725); (statearr_16743_16770[(1)] = (15)); return cljs.core.cst$kw$recur; } else { if((state_val_16737 === (6))){ var state_16736__$1 = state_16736; var statearr_16744_16771 = state_16736__$1; (statearr_16744_16771[(2)] = null); (statearr_16744_16771[(1)] = (11)); return cljs.core.cst$kw$recur; } else { if((state_val_16737 === (3))){ var inst_16734 = (state_16736[(2)]); var state_16736__$1 = state_16736; return cljs.core.async.impl.ioc_helpers.return_chan(state_16736__$1,inst_16734); } else { if((state_val_16737 === (12))){ var inst_16722 = (state_16736[(8)]); var inst_16722__$1 = (state_16736[(2)]); var inst_16723 = cljs.core.some(cljs.core.nil_QMARK_,inst_16722__$1); var state_16736__$1 = (function (){var statearr_16745 = state_16736; (statearr_16745[(8)] = inst_16722__$1); return statearr_16745; })(); if(cljs.core.truth_(inst_16723)){ var statearr_16746_16772 = state_16736__$1; (statearr_16746_16772[(1)] = (13)); } else { var statearr_16747_16773 = state_16736__$1; (statearr_16747_16773[(1)] = (14)); } return cljs.core.cst$kw$recur; } else { if((state_val_16737 === (2))){ var inst_16699 = cljs.core.reset_BANG_(dctr,cnt); var inst_16700 = (0); var state_16736__$1 = (function (){var statearr_16748 = state_16736; (statearr_16748[(7)] = inst_16700); (statearr_16748[(9)] = inst_16699); return statearr_16748; })(); var statearr_16749_16774 = state_16736__$1; (statearr_16749_16774[(2)] = null); (statearr_16749_16774[(1)] = (4)); return cljs.core.cst$kw$recur; } else { if((state_val_16737 === (11))){ var inst_16700 = (state_16736[(7)]); var _ = cljs.core.async.impl.ioc_helpers.add_exception_frame(state_16736,(10),Object,null,(9)); var inst_16709 = (chs__$1.cljs$core$IFn$_invoke$arity$1 ? chs__$1.cljs$core$IFn$_invoke$arity$1(inst_16700) : chs__$1.call(null,inst_16700)); var inst_16710 = (done.cljs$core$IFn$_invoke$arity$1 ? done.cljs$core$IFn$_invoke$arity$1(inst_16700) : done.call(null,inst_16700)); var inst_16711 = cljs.core.async.take_BANG_.cljs$core$IFn$_invoke$arity$2(inst_16709,inst_16710); var state_16736__$1 = state_16736; var statearr_16750_16775 = state_16736__$1; (statearr_16750_16775[(2)] = inst_16711); cljs.core.async.impl.ioc_helpers.process_exception(state_16736__$1); return cljs.core.cst$kw$recur; } else { if((state_val_16737 === (9))){ var inst_16700 = (state_16736[(7)]); var inst_16713 = (state_16736[(2)]); var inst_16714 = (inst_16700 + (1)); var inst_16700__$1 = inst_16714; var state_16736__$1 = (function (){var statearr_16751 = state_16736; (statearr_16751[(7)] = inst_16700__$1); (statearr_16751[(10)] = inst_16713); return statearr_16751; })(); var statearr_16752_16776 = state_16736__$1; (statearr_16752_16776[(2)] = null); (statearr_16752_16776[(1)] = (4)); return cljs.core.cst$kw$recur; } else { if((state_val_16737 === (5))){ var inst_16720 = (state_16736[(2)]); var state_16736__$1 = (function (){var statearr_16753 = state_16736; (statearr_16753[(11)] = inst_16720); return statearr_16753; })(); return cljs.core.async.impl.ioc_helpers.take_BANG_(state_16736__$1,(12),dchan); } else { if((state_val_16737 === (14))){ var inst_16722 = (state_16736[(8)]); var inst_16727 = cljs.core.apply.cljs$core$IFn$_invoke$arity$2(f,inst_16722); var state_16736__$1 = state_16736; return cljs.core.async.impl.ioc_helpers.put_BANG_(state_16736__$1,(16),out,inst_16727); } else { if((state_val_16737 === (16))){ var inst_16729 = (state_16736[(2)]); var state_16736__$1 = (function (){var statearr_16754 = state_16736; (statearr_16754[(12)] = inst_16729); return statearr_16754; })(); var statearr_16755_16777 = state_16736__$1; (statearr_16755_16777[(2)] = null); (statearr_16755_16777[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_16737 === (10))){ var inst_16704 = (state_16736[(2)]); var inst_16705 = cljs.core.swap_BANG_.cljs$core$IFn$_invoke$arity$2(dctr,cljs.core.dec); var state_16736__$1 = (function (){var statearr_16756 = state_16736; (statearr_16756[(13)] = inst_16704); return statearr_16756; })(); var statearr_16757_16778 = state_16736__$1; (statearr_16757_16778[(2)] = inst_16705); cljs.core.async.impl.ioc_helpers.process_exception(state_16736__$1); return cljs.core.cst$kw$recur; } else { if((state_val_16737 === (8))){ var inst_16718 = (state_16736[(2)]); var state_16736__$1 = state_16736; var statearr_16758_16779 = state_16736__$1; (statearr_16758_16779[(2)] = inst_16718); (statearr_16758_16779[(1)] = (5)); return cljs.core.cst$kw$recur; } else { return null; } } } } } } } } } } } } } } } } });})(c__15437__auto___16764,chs__$1,out,cnt,rets,dchan,dctr,done)) ; return ((function (switch__15337__auto__,c__15437__auto___16764,chs__$1,out,cnt,rets,dchan,dctr,done){ return (function() { var cljs$core$async$state_machine__15338__auto__ = null; var cljs$core$async$state_machine__15338__auto____0 = (function (){ var statearr_16759 = [null,null,null,null,null,null,null,null,null,null,null,null,null,null]; (statearr_16759[(0)] = cljs$core$async$state_machine__15338__auto__); (statearr_16759[(1)] = (1)); return statearr_16759; }); var cljs$core$async$state_machine__15338__auto____1 = (function (state_16736){ while(true){ var ret_value__15339__auto__ = (function (){try{while(true){ var result__15340__auto__ = switch__15337__auto__(state_16736); if(cljs.core.keyword_identical_QMARK_(result__15340__auto__,cljs.core.cst$kw$recur)){ continue; } else { return result__15340__auto__; } break; } }catch (e16760){if((e16760 instanceof Object)){ var ex__15341__auto__ = e16760; var statearr_16761_16780 = state_16736; (statearr_16761_16780[(5)] = ex__15341__auto__); cljs.core.async.impl.ioc_helpers.process_exception(state_16736); return cljs.core.cst$kw$recur; } else { throw e16760; } }})(); if(cljs.core.keyword_identical_QMARK_(ret_value__15339__auto__,cljs.core.cst$kw$recur)){ var G__16781 = state_16736; state_16736 = G__16781; continue; } else { return ret_value__15339__auto__; } break; } }); cljs$core$async$state_machine__15338__auto__ = function(state_16736){ switch(arguments.length){ case 0: return cljs$core$async$state_machine__15338__auto____0.call(this); case 1: return cljs$core$async$state_machine__15338__auto____1.call(this,state_16736); } throw(new Error('Invalid arity: ' + (arguments.length - 1))); }; cljs$core$async$state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$0 = cljs$core$async$state_machine__15338__auto____0; cljs$core$async$state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$1 = cljs$core$async$state_machine__15338__auto____1; return cljs$core$async$state_machine__15338__auto__; })() ;})(switch__15337__auto__,c__15437__auto___16764,chs__$1,out,cnt,rets,dchan,dctr,done)) })(); var state__15439__auto__ = (function (){var statearr_16762 = (f__15438__auto__.cljs$core$IFn$_invoke$arity$0 ? f__15438__auto__.cljs$core$IFn$_invoke$arity$0() : f__15438__auto__.call(null)); (statearr_16762[(6)] = c__15437__auto___16764); return statearr_16762; })(); return cljs.core.async.impl.ioc_helpers.run_state_machine_wrapped(state__15439__auto__); });})(c__15437__auto___16764,chs__$1,out,cnt,rets,dchan,dctr,done)) ); return out; }); cljs.core.async.map.cljs$lang$maxFixedArity = 3; /** * Takes a collection of source channels and returns a channel which * contains all values taken from them. The returned channel will be * unbuffered by default, or a buf-or-n can be supplied. The channel * will close after all the source channels have closed. */ cljs.core.async.merge = (function cljs$core$async$merge(var_args){ var G__16784 = arguments.length; switch (G__16784) { case 1: return cljs.core.async.merge.cljs$core$IFn$_invoke$arity$1((arguments[(0)])); break; case 2: return cljs.core.async.merge.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; default: throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join(''))); } }); cljs.core.async.merge.cljs$core$IFn$_invoke$arity$1 = (function (chs){ return cljs.core.async.merge.cljs$core$IFn$_invoke$arity$2(chs,null); }); cljs.core.async.merge.cljs$core$IFn$_invoke$arity$2 = (function (chs,buf_or_n){ var out = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1(buf_or_n); var c__15437__auto___16838 = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1((1)); cljs.core.async.impl.dispatch.run(((function (c__15437__auto___16838,out){ return (function (){ var f__15438__auto__ = (function (){var switch__15337__auto__ = ((function (c__15437__auto___16838,out){ return (function (state_16816){ var state_val_16817 = (state_16816[(1)]); if((state_val_16817 === (7))){ var inst_16795 = (state_16816[(7)]); var inst_16796 = (state_16816[(8)]); var inst_16795__$1 = (state_16816[(2)]); var inst_16796__$1 = cljs.core.nth.cljs$core$IFn$_invoke$arity$3(inst_16795__$1,(0),null); var inst_16797 = cljs.core.nth.cljs$core$IFn$_invoke$arity$3(inst_16795__$1,(1),null); var inst_16798 = (inst_16796__$1 == null); var state_16816__$1 = (function (){var statearr_16818 = state_16816; (statearr_16818[(7)] = inst_16795__$1); (statearr_16818[(8)] = inst_16796__$1); (statearr_16818[(9)] = inst_16797); return statearr_16818; })(); if(cljs.core.truth_(inst_16798)){ var statearr_16819_16839 = state_16816__$1; (statearr_16819_16839[(1)] = (8)); } else { var statearr_16820_16840 = state_16816__$1; (statearr_16820_16840[(1)] = (9)); } return cljs.core.cst$kw$recur; } else { if((state_val_16817 === (1))){ var inst_16785 = cljs.core.vec(chs); var inst_16786 = inst_16785; var state_16816__$1 = (function (){var statearr_16821 = state_16816; (statearr_16821[(10)] = inst_16786); return statearr_16821; })(); var statearr_16822_16841 = state_16816__$1; (statearr_16822_16841[(2)] = null); (statearr_16822_16841[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_16817 === (4))){ var inst_16786 = (state_16816[(10)]); var state_16816__$1 = state_16816; return cljs.core.async.ioc_alts_BANG_(state_16816__$1,(7),inst_16786); } else { if((state_val_16817 === (6))){ var inst_16812 = (state_16816[(2)]); var state_16816__$1 = state_16816; var statearr_16823_16842 = state_16816__$1; (statearr_16823_16842[(2)] = inst_16812); (statearr_16823_16842[(1)] = (3)); return cljs.core.cst$kw$recur; } else { if((state_val_16817 === (3))){ var inst_16814 = (state_16816[(2)]); var state_16816__$1 = state_16816; return cljs.core.async.impl.ioc_helpers.return_chan(state_16816__$1,inst_16814); } else { if((state_val_16817 === (2))){ var inst_16786 = (state_16816[(10)]); var inst_16788 = cljs.core.count(inst_16786); var inst_16789 = (inst_16788 > (0)); var state_16816__$1 = state_16816; if(cljs.core.truth_(inst_16789)){ var statearr_16825_16843 = state_16816__$1; (statearr_16825_16843[(1)] = (4)); } else { var statearr_16826_16844 = state_16816__$1; (statearr_16826_16844[(1)] = (5)); } return cljs.core.cst$kw$recur; } else { if((state_val_16817 === (11))){ var inst_16786 = (state_16816[(10)]); var inst_16805 = (state_16816[(2)]); var tmp16824 = inst_16786; var inst_16786__$1 = tmp16824; var state_16816__$1 = (function (){var statearr_16827 = state_16816; (statearr_16827[(11)] = inst_16805); (statearr_16827[(10)] = inst_16786__$1); return statearr_16827; })(); var statearr_16828_16845 = state_16816__$1; (statearr_16828_16845[(2)] = null); (statearr_16828_16845[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_16817 === (9))){ var inst_16796 = (state_16816[(8)]); var state_16816__$1 = state_16816; return cljs.core.async.impl.ioc_helpers.put_BANG_(state_16816__$1,(11),out,inst_16796); } else { if((state_val_16817 === (5))){ var inst_16810 = cljs.core.async.close_BANG_(out); var state_16816__$1 = state_16816; var statearr_16829_16846 = state_16816__$1; (statearr_16829_16846[(2)] = inst_16810); (statearr_16829_16846[(1)] = (6)); return cljs.core.cst$kw$recur; } else { if((state_val_16817 === (10))){ var inst_16808 = (state_16816[(2)]); var state_16816__$1 = state_16816; var statearr_16830_16847 = state_16816__$1; (statearr_16830_16847[(2)] = inst_16808); (statearr_16830_16847[(1)] = (6)); return cljs.core.cst$kw$recur; } else { if((state_val_16817 === (8))){ var inst_16795 = (state_16816[(7)]); var inst_16796 = (state_16816[(8)]); var inst_16786 = (state_16816[(10)]); var inst_16797 = (state_16816[(9)]); var inst_16800 = (function (){var cs = inst_16786; var vec__16791 = inst_16795; var v = inst_16796; var c = inst_16797; return ((function (cs,vec__16791,v,c,inst_16795,inst_16796,inst_16786,inst_16797,state_val_16817,c__15437__auto___16838,out){ return (function (p1__16782_SHARP_){ return cljs.core.not_EQ_.cljs$core$IFn$_invoke$arity$2(c,p1__16782_SHARP_); }); ;})(cs,vec__16791,v,c,inst_16795,inst_16796,inst_16786,inst_16797,state_val_16817,c__15437__auto___16838,out)) })(); var inst_16801 = cljs.core.filterv(inst_16800,inst_16786); var inst_16786__$1 = inst_16801; var state_16816__$1 = (function (){var statearr_16831 = state_16816; (statearr_16831[(10)] = inst_16786__$1); return statearr_16831; })(); var statearr_16832_16848 = state_16816__$1; (statearr_16832_16848[(2)] = null); (statearr_16832_16848[(1)] = (2)); return cljs.core.cst$kw$recur; } else { return null; } } } } } } } } } } } });})(c__15437__auto___16838,out)) ; return ((function (switch__15337__auto__,c__15437__auto___16838,out){ return (function() { var cljs$core$async$state_machine__15338__auto__ = null; var cljs$core$async$state_machine__15338__auto____0 = (function (){ var statearr_16833 = [null,null,null,null,null,null,null,null,null,null,null,null]; (statearr_16833[(0)] = cljs$core$async$state_machine__15338__auto__); (statearr_16833[(1)] = (1)); return statearr_16833; }); var cljs$core$async$state_machine__15338__auto____1 = (function (state_16816){ while(true){ var ret_value__15339__auto__ = (function (){try{while(true){ var result__15340__auto__ = switch__15337__auto__(state_16816); if(cljs.core.keyword_identical_QMARK_(result__15340__auto__,cljs.core.cst$kw$recur)){ continue; } else { return result__15340__auto__; } break; } }catch (e16834){if((e16834 instanceof Object)){ var ex__15341__auto__ = e16834; var statearr_16835_16849 = state_16816; (statearr_16835_16849[(5)] = ex__15341__auto__); cljs.core.async.impl.ioc_helpers.process_exception(state_16816); return cljs.core.cst$kw$recur; } else { throw e16834; } }})(); if(cljs.core.keyword_identical_QMARK_(ret_value__15339__auto__,cljs.core.cst$kw$recur)){ var G__16850 = state_16816; state_16816 = G__16850; continue; } else { return ret_value__15339__auto__; } break; } }); cljs$core$async$state_machine__15338__auto__ = function(state_16816){ switch(arguments.length){ case 0: return cljs$core$async$state_machine__15338__auto____0.call(this); case 1: return cljs$core$async$state_machine__15338__auto____1.call(this,state_16816); } throw(new Error('Invalid arity: ' + (arguments.length - 1))); }; cljs$core$async$state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$0 = cljs$core$async$state_machine__15338__auto____0; cljs$core$async$state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$1 = cljs$core$async$state_machine__15338__auto____1; return cljs$core$async$state_machine__15338__auto__; })() ;})(switch__15337__auto__,c__15437__auto___16838,out)) })(); var state__15439__auto__ = (function (){var statearr_16836 = (f__15438__auto__.cljs$core$IFn$_invoke$arity$0 ? f__15438__auto__.cljs$core$IFn$_invoke$arity$0() : f__15438__auto__.call(null)); (statearr_16836[(6)] = c__15437__auto___16838); return statearr_16836; })(); return cljs.core.async.impl.ioc_helpers.run_state_machine_wrapped(state__15439__auto__); });})(c__15437__auto___16838,out)) ); return out; }); cljs.core.async.merge.cljs$lang$maxFixedArity = 2; /** * Returns a channel containing the single (collection) result of the * items taken from the channel conjoined to the supplied * collection. ch must close before into produces a result. */ cljs.core.async.into = (function cljs$core$async$into(coll,ch){ return cljs.core.async.reduce(cljs.core.conj,coll,ch); }); /** * Returns a channel that will return, at most, n items from ch. After n items * have been returned, or ch has been closed, the return chanel will close. * * The output channel is unbuffered by default, unless buf-or-n is given. */ cljs.core.async.take = (function cljs$core$async$take(var_args){ var G__16852 = arguments.length; switch (G__16852) { case 2: return cljs.core.async.take.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; case 3: return cljs.core.async.take.cljs$core$IFn$_invoke$arity$3((arguments[(0)]),(arguments[(1)]),(arguments[(2)])); break; default: throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join(''))); } }); cljs.core.async.take.cljs$core$IFn$_invoke$arity$2 = (function (n,ch){ return cljs.core.async.take.cljs$core$IFn$_invoke$arity$3(n,ch,null); }); cljs.core.async.take.cljs$core$IFn$_invoke$arity$3 = (function (n,ch,buf_or_n){ var out = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1(buf_or_n); var c__15437__auto___16897 = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1((1)); cljs.core.async.impl.dispatch.run(((function (c__15437__auto___16897,out){ return (function (){ var f__15438__auto__ = (function (){var switch__15337__auto__ = ((function (c__15437__auto___16897,out){ return (function (state_16876){ var state_val_16877 = (state_16876[(1)]); if((state_val_16877 === (7))){ var inst_16858 = (state_16876[(7)]); var inst_16858__$1 = (state_16876[(2)]); var inst_16859 = (inst_16858__$1 == null); var inst_16860 = cljs.core.not(inst_16859); var state_16876__$1 = (function (){var statearr_16878 = state_16876; (statearr_16878[(7)] = inst_16858__$1); return statearr_16878; })(); if(inst_16860){ var statearr_16879_16898 = state_16876__$1; (statearr_16879_16898[(1)] = (8)); } else { var statearr_16880_16899 = state_16876__$1; (statearr_16880_16899[(1)] = (9)); } return cljs.core.cst$kw$recur; } else { if((state_val_16877 === (1))){ var inst_16853 = (0); var state_16876__$1 = (function (){var statearr_16881 = state_16876; (statearr_16881[(8)] = inst_16853); return statearr_16881; })(); var statearr_16882_16900 = state_16876__$1; (statearr_16882_16900[(2)] = null); (statearr_16882_16900[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_16877 === (4))){ var state_16876__$1 = state_16876; return cljs.core.async.impl.ioc_helpers.take_BANG_(state_16876__$1,(7),ch); } else { if((state_val_16877 === (6))){ var inst_16871 = (state_16876[(2)]); var state_16876__$1 = state_16876; var statearr_16883_16901 = state_16876__$1; (statearr_16883_16901[(2)] = inst_16871); (statearr_16883_16901[(1)] = (3)); return cljs.core.cst$kw$recur; } else { if((state_val_16877 === (3))){ var inst_16873 = (state_16876[(2)]); var inst_16874 = cljs.core.async.close_BANG_(out); var state_16876__$1 = (function (){var statearr_16884 = state_16876; (statearr_16884[(9)] = inst_16873); return statearr_16884; })(); return cljs.core.async.impl.ioc_helpers.return_chan(state_16876__$1,inst_16874); } else { if((state_val_16877 === (2))){ var inst_16853 = (state_16876[(8)]); var inst_16855 = (inst_16853 < n); var state_16876__$1 = state_16876; if(cljs.core.truth_(inst_16855)){ var statearr_16885_16902 = state_16876__$1; (statearr_16885_16902[(1)] = (4)); } else { var statearr_16886_16903 = state_16876__$1; (statearr_16886_16903[(1)] = (5)); } return cljs.core.cst$kw$recur; } else { if((state_val_16877 === (11))){ var inst_16853 = (state_16876[(8)]); var inst_16863 = (state_16876[(2)]); var inst_16864 = (inst_16853 + (1)); var inst_16853__$1 = inst_16864; var state_16876__$1 = (function (){var statearr_16887 = state_16876; (statearr_16887[(10)] = inst_16863); (statearr_16887[(8)] = inst_16853__$1); return statearr_16887; })(); var statearr_16888_16904 = state_16876__$1; (statearr_16888_16904[(2)] = null); (statearr_16888_16904[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_16877 === (9))){ var state_16876__$1 = state_16876; var statearr_16889_16905 = state_16876__$1; (statearr_16889_16905[(2)] = null); (statearr_16889_16905[(1)] = (10)); return cljs.core.cst$kw$recur; } else { if((state_val_16877 === (5))){ var state_16876__$1 = state_16876; var statearr_16890_16906 = state_16876__$1; (statearr_16890_16906[(2)] = null); (statearr_16890_16906[(1)] = (6)); return cljs.core.cst$kw$recur; } else { if((state_val_16877 === (10))){ var inst_16868 = (state_16876[(2)]); var state_16876__$1 = state_16876; var statearr_16891_16907 = state_16876__$1; (statearr_16891_16907[(2)] = inst_16868); (statearr_16891_16907[(1)] = (6)); return cljs.core.cst$kw$recur; } else { if((state_val_16877 === (8))){ var inst_16858 = (state_16876[(7)]); var state_16876__$1 = state_16876; return cljs.core.async.impl.ioc_helpers.put_BANG_(state_16876__$1,(11),out,inst_16858); } else { return null; } } } } } } } } } } } });})(c__15437__auto___16897,out)) ; return ((function (switch__15337__auto__,c__15437__auto___16897,out){ return (function() { var cljs$core$async$state_machine__15338__auto__ = null; var cljs$core$async$state_machine__15338__auto____0 = (function (){ var statearr_16892 = [null,null,null,null,null,null,null,null,null,null,null]; (statearr_16892[(0)] = cljs$core$async$state_machine__15338__auto__); (statearr_16892[(1)] = (1)); return statearr_16892; }); var cljs$core$async$state_machine__15338__auto____1 = (function (state_16876){ while(true){ var ret_value__15339__auto__ = (function (){try{while(true){ var result__15340__auto__ = switch__15337__auto__(state_16876); if(cljs.core.keyword_identical_QMARK_(result__15340__auto__,cljs.core.cst$kw$recur)){ continue; } else { return result__15340__auto__; } break; } }catch (e16893){if((e16893 instanceof Object)){ var ex__15341__auto__ = e16893; var statearr_16894_16908 = state_16876; (statearr_16894_16908[(5)] = ex__15341__auto__); cljs.core.async.impl.ioc_helpers.process_exception(state_16876); return cljs.core.cst$kw$recur; } else { throw e16893; } }})(); if(cljs.core.keyword_identical_QMARK_(ret_value__15339__auto__,cljs.core.cst$kw$recur)){ var G__16909 = state_16876; state_16876 = G__16909; continue; } else { return ret_value__15339__auto__; } break; } }); cljs$core$async$state_machine__15338__auto__ = function(state_16876){ switch(arguments.length){ case 0: return cljs$core$async$state_machine__15338__auto____0.call(this); case 1: return cljs$core$async$state_machine__15338__auto____1.call(this,state_16876); } throw(new Error('Invalid arity: ' + (arguments.length - 1))); }; cljs$core$async$state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$0 = cljs$core$async$state_machine__15338__auto____0; cljs$core$async$state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$1 = cljs$core$async$state_machine__15338__auto____1; return cljs$core$async$state_machine__15338__auto__; })() ;})(switch__15337__auto__,c__15437__auto___16897,out)) })(); var state__15439__auto__ = (function (){var statearr_16895 = (f__15438__auto__.cljs$core$IFn$_invoke$arity$0 ? f__15438__auto__.cljs$core$IFn$_invoke$arity$0() : f__15438__auto__.call(null)); (statearr_16895[(6)] = c__15437__auto___16897); return statearr_16895; })(); return cljs.core.async.impl.ioc_helpers.run_state_machine_wrapped(state__15439__auto__); });})(c__15437__auto___16897,out)) ); return out; }); cljs.core.async.take.cljs$lang$maxFixedArity = 3; /** * Deprecated - this function will be removed. Use transducer instead */ cljs.core.async.map_LT_ = (function cljs$core$async$map_LT_(f,ch){ if(typeof cljs.core.async.t_cljs$core$async16911 !== 'undefined'){ } else { /** * @constructor * @implements {cljs.core.async.impl.protocols.Channel} * @implements {cljs.core.async.impl.protocols.WritePort} * @implements {cljs.core.async.impl.protocols.ReadPort} * @implements {cljs.core.IMeta} * @implements {cljs.core.IWithMeta} */ cljs.core.async.t_cljs$core$async16911 = (function (f,ch,meta16912){ this.f = f; this.ch = ch; this.meta16912 = meta16912; this.cljs$lang$protocol_mask$partition0$ = 393216; this.cljs$lang$protocol_mask$partition1$ = 0; }); cljs.core.async.t_cljs$core$async16911.prototype.cljs$core$IWithMeta$_with_meta$arity$2 = (function (_16913,meta16912__$1){ var self__ = this; var _16913__$1 = this; return (new cljs.core.async.t_cljs$core$async16911(self__.f,self__.ch,meta16912__$1)); }); cljs.core.async.t_cljs$core$async16911.prototype.cljs$core$IMeta$_meta$arity$1 = (function (_16913){ var self__ = this; var _16913__$1 = this; return self__.meta16912; }); cljs.core.async.t_cljs$core$async16911.prototype.cljs$core$async$impl$protocols$Channel$ = cljs.core.PROTOCOL_SENTINEL; cljs.core.async.t_cljs$core$async16911.prototype.cljs$core$async$impl$protocols$Channel$close_BANG_$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return cljs.core.async.impl.protocols.close_BANG_(self__.ch); }); cljs.core.async.t_cljs$core$async16911.prototype.cljs$core$async$impl$protocols$Channel$closed_QMARK_$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return cljs.core.async.impl.protocols.closed_QMARK_(self__.ch); }); cljs.core.async.t_cljs$core$async16911.prototype.cljs$core$async$impl$protocols$ReadPort$ = cljs.core.PROTOCOL_SENTINEL; cljs.core.async.t_cljs$core$async16911.prototype.cljs$core$async$impl$protocols$ReadPort$take_BANG_$arity$2 = (function (_,fn1){ var self__ = this; var ___$1 = this; var ret = cljs.core.async.impl.protocols.take_BANG_(self__.ch,(function (){ if(typeof cljs.core.async.t_cljs$core$async16914 !== 'undefined'){ } else { /** * @constructor * @implements {cljs.core.async.impl.protocols.Handler} * @implements {cljs.core.IMeta} * @implements {cljs.core.IWithMeta} */ cljs.core.async.t_cljs$core$async16914 = (function (f,ch,meta16912,_,fn1,meta16915){ this.f = f; this.ch = ch; this.meta16912 = meta16912; this._ = _; this.fn1 = fn1; this.meta16915 = meta16915; this.cljs$lang$protocol_mask$partition0$ = 393216; this.cljs$lang$protocol_mask$partition1$ = 0; }); cljs.core.async.t_cljs$core$async16914.prototype.cljs$core$IWithMeta$_with_meta$arity$2 = ((function (___$1){ return (function (_16916,meta16915__$1){ var self__ = this; var _16916__$1 = this; return (new cljs.core.async.t_cljs$core$async16914(self__.f,self__.ch,self__.meta16912,self__._,self__.fn1,meta16915__$1)); });})(___$1)) ; cljs.core.async.t_cljs$core$async16914.prototype.cljs$core$IMeta$_meta$arity$1 = ((function (___$1){ return (function (_16916){ var self__ = this; var _16916__$1 = this; return self__.meta16915; });})(___$1)) ; cljs.core.async.t_cljs$core$async16914.prototype.cljs$core$async$impl$protocols$Handler$ = cljs.core.PROTOCOL_SENTINEL; cljs.core.async.t_cljs$core$async16914.prototype.cljs$core$async$impl$protocols$Handler$active_QMARK_$arity$1 = ((function (___$1){ return (function (___$1){ var self__ = this; var ___$2 = this; return cljs.core.async.impl.protocols.active_QMARK_(self__.fn1); });})(___$1)) ; cljs.core.async.t_cljs$core$async16914.prototype.cljs$core$async$impl$protocols$Handler$blockable_QMARK_$arity$1 = ((function (___$1){ return (function (___$1){ var self__ = this; var ___$2 = this; return true; });})(___$1)) ; cljs.core.async.t_cljs$core$async16914.prototype.cljs$core$async$impl$protocols$Handler$commit$arity$1 = ((function (___$1){ return (function (___$1){ var self__ = this; var ___$2 = this; var f1 = cljs.core.async.impl.protocols.commit(self__.fn1); return ((function (f1,___$2,___$1){ return (function (p1__16910_SHARP_){ var G__16917 = (((p1__16910_SHARP_ == null))?null:(self__.f.cljs$core$IFn$_invoke$arity$1 ? self__.f.cljs$core$IFn$_invoke$arity$1(p1__16910_SHARP_) : self__.f.call(null,p1__16910_SHARP_))); return (f1.cljs$core$IFn$_invoke$arity$1 ? f1.cljs$core$IFn$_invoke$arity$1(G__16917) : f1.call(null,G__16917)); }); ;})(f1,___$2,___$1)) });})(___$1)) ; cljs.core.async.t_cljs$core$async16914.getBasis = ((function (___$1){ return (function (){ return new cljs.core.PersistentVector(null, 6, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.cst$sym$f,cljs.core.cst$sym$ch,cljs.core.cst$sym$meta16912,cljs.core.with_meta(cljs.core.cst$sym$_,new cljs.core.PersistentArrayMap(null, 1, [cljs.core.cst$kw$tag,cljs.core.cst$sym$cljs$core$async_SLASH_t_cljs$core$async16911], null)),cljs.core.cst$sym$fn1,cljs.core.cst$sym$meta16915], null); });})(___$1)) ; cljs.core.async.t_cljs$core$async16914.cljs$lang$type = true; cljs.core.async.t_cljs$core$async16914.cljs$lang$ctorStr = "cljs.core.async/t_cljs$core$async16914"; cljs.core.async.t_cljs$core$async16914.cljs$lang$ctorPrWriter = ((function (___$1){ return (function (this__8293__auto__,writer__8294__auto__,opt__8295__auto__){ return cljs.core._write(writer__8294__auto__,"cljs.core.async/t_cljs$core$async16914"); });})(___$1)) ; cljs.core.async.__GT_t_cljs$core$async16914 = ((function (___$1){ return (function cljs$core$async$map_LT__$___GT_t_cljs$core$async16914(f__$1,ch__$1,meta16912__$1,___$2,fn1__$1,meta16915){ return (new cljs.core.async.t_cljs$core$async16914(f__$1,ch__$1,meta16912__$1,___$2,fn1__$1,meta16915)); });})(___$1)) ; } return (new cljs.core.async.t_cljs$core$async16914(self__.f,self__.ch,self__.meta16912,___$1,fn1,cljs.core.PersistentArrayMap.EMPTY)); })() ); if(cljs.core.truth_((function (){var and__7656__auto__ = ret; if(cljs.core.truth_(and__7656__auto__)){ return !((cljs.core.deref(ret) == null)); } else { return and__7656__auto__; } })())){ return cljs.core.async.impl.channels.box((function (){var G__16918 = cljs.core.deref(ret); return (self__.f.cljs$core$IFn$_invoke$arity$1 ? self__.f.cljs$core$IFn$_invoke$arity$1(G__16918) : self__.f.call(null,G__16918)); })()); } else { return ret; } }); cljs.core.async.t_cljs$core$async16911.prototype.cljs$core$async$impl$protocols$WritePort$ = cljs.core.PROTOCOL_SENTINEL; cljs.core.async.t_cljs$core$async16911.prototype.cljs$core$async$impl$protocols$WritePort$put_BANG_$arity$3 = (function (_,val,fn1){ var self__ = this; var ___$1 = this; return cljs.core.async.impl.protocols.put_BANG_(self__.ch,val,fn1); }); cljs.core.async.t_cljs$core$async16911.getBasis = (function (){ return new cljs.core.PersistentVector(null, 3, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.cst$sym$f,cljs.core.cst$sym$ch,cljs.core.cst$sym$meta16912], null); }); cljs.core.async.t_cljs$core$async16911.cljs$lang$type = true; cljs.core.async.t_cljs$core$async16911.cljs$lang$ctorStr = "cljs.core.async/t_cljs$core$async16911"; cljs.core.async.t_cljs$core$async16911.cljs$lang$ctorPrWriter = (function (this__8293__auto__,writer__8294__auto__,opt__8295__auto__){ return cljs.core._write(writer__8294__auto__,"cljs.core.async/t_cljs$core$async16911"); }); cljs.core.async.__GT_t_cljs$core$async16911 = (function cljs$core$async$map_LT__$___GT_t_cljs$core$async16911(f__$1,ch__$1,meta16912){ return (new cljs.core.async.t_cljs$core$async16911(f__$1,ch__$1,meta16912)); }); } return (new cljs.core.async.t_cljs$core$async16911(f,ch,cljs.core.PersistentArrayMap.EMPTY)); }); /** * Deprecated - this function will be removed. Use transducer instead */ cljs.core.async.map_GT_ = (function cljs$core$async$map_GT_(f,ch){ if(typeof cljs.core.async.t_cljs$core$async16919 !== 'undefined'){ } else { /** * @constructor * @implements {cljs.core.async.impl.protocols.Channel} * @implements {cljs.core.async.impl.protocols.WritePort} * @implements {cljs.core.async.impl.protocols.ReadPort} * @implements {cljs.core.IMeta} * @implements {cljs.core.IWithMeta} */ cljs.core.async.t_cljs$core$async16919 = (function (f,ch,meta16920){ this.f = f; this.ch = ch; this.meta16920 = meta16920; this.cljs$lang$protocol_mask$partition0$ = 393216; this.cljs$lang$protocol_mask$partition1$ = 0; }); cljs.core.async.t_cljs$core$async16919.prototype.cljs$core$IWithMeta$_with_meta$arity$2 = (function (_16921,meta16920__$1){ var self__ = this; var _16921__$1 = this; return (new cljs.core.async.t_cljs$core$async16919(self__.f,self__.ch,meta16920__$1)); }); cljs.core.async.t_cljs$core$async16919.prototype.cljs$core$IMeta$_meta$arity$1 = (function (_16921){ var self__ = this; var _16921__$1 = this; return self__.meta16920; }); cljs.core.async.t_cljs$core$async16919.prototype.cljs$core$async$impl$protocols$Channel$ = cljs.core.PROTOCOL_SENTINEL; cljs.core.async.t_cljs$core$async16919.prototype.cljs$core$async$impl$protocols$Channel$close_BANG_$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return cljs.core.async.impl.protocols.close_BANG_(self__.ch); }); cljs.core.async.t_cljs$core$async16919.prototype.cljs$core$async$impl$protocols$ReadPort$ = cljs.core.PROTOCOL_SENTINEL; cljs.core.async.t_cljs$core$async16919.prototype.cljs$core$async$impl$protocols$ReadPort$take_BANG_$arity$2 = (function (_,fn1){ var self__ = this; var ___$1 = this; return cljs.core.async.impl.protocols.take_BANG_(self__.ch,fn1); }); cljs.core.async.t_cljs$core$async16919.prototype.cljs$core$async$impl$protocols$WritePort$ = cljs.core.PROTOCOL_SENTINEL; cljs.core.async.t_cljs$core$async16919.prototype.cljs$core$async$impl$protocols$WritePort$put_BANG_$arity$3 = (function (_,val,fn1){ var self__ = this; var ___$1 = this; return cljs.core.async.impl.protocols.put_BANG_(self__.ch,(self__.f.cljs$core$IFn$_invoke$arity$1 ? self__.f.cljs$core$IFn$_invoke$arity$1(val) : self__.f.call(null,val)),fn1); }); cljs.core.async.t_cljs$core$async16919.getBasis = (function (){ return new cljs.core.PersistentVector(null, 3, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.cst$sym$f,cljs.core.cst$sym$ch,cljs.core.cst$sym$meta16920], null); }); cljs.core.async.t_cljs$core$async16919.cljs$lang$type = true; cljs.core.async.t_cljs$core$async16919.cljs$lang$ctorStr = "cljs.core.async/t_cljs$core$async16919"; cljs.core.async.t_cljs$core$async16919.cljs$lang$ctorPrWriter = (function (this__8293__auto__,writer__8294__auto__,opt__8295__auto__){ return cljs.core._write(writer__8294__auto__,"cljs.core.async/t_cljs$core$async16919"); }); cljs.core.async.__GT_t_cljs$core$async16919 = (function cljs$core$async$map_GT__$___GT_t_cljs$core$async16919(f__$1,ch__$1,meta16920){ return (new cljs.core.async.t_cljs$core$async16919(f__$1,ch__$1,meta16920)); }); } return (new cljs.core.async.t_cljs$core$async16919(f,ch,cljs.core.PersistentArrayMap.EMPTY)); }); /** * Deprecated - this function will be removed. Use transducer instead */ cljs.core.async.filter_GT_ = (function cljs$core$async$filter_GT_(p,ch){ if(typeof cljs.core.async.t_cljs$core$async16922 !== 'undefined'){ } else { /** * @constructor * @implements {cljs.core.async.impl.protocols.Channel} * @implements {cljs.core.async.impl.protocols.WritePort} * @implements {cljs.core.async.impl.protocols.ReadPort} * @implements {cljs.core.IMeta} * @implements {cljs.core.IWithMeta} */ cljs.core.async.t_cljs$core$async16922 = (function (p,ch,meta16923){ this.p = p; this.ch = ch; this.meta16923 = meta16923; this.cljs$lang$protocol_mask$partition0$ = 393216; this.cljs$lang$protocol_mask$partition1$ = 0; }); cljs.core.async.t_cljs$core$async16922.prototype.cljs$core$IWithMeta$_with_meta$arity$2 = (function (_16924,meta16923__$1){ var self__ = this; var _16924__$1 = this; return (new cljs.core.async.t_cljs$core$async16922(self__.p,self__.ch,meta16923__$1)); }); cljs.core.async.t_cljs$core$async16922.prototype.cljs$core$IMeta$_meta$arity$1 = (function (_16924){ var self__ = this; var _16924__$1 = this; return self__.meta16923; }); cljs.core.async.t_cljs$core$async16922.prototype.cljs$core$async$impl$protocols$Channel$ = cljs.core.PROTOCOL_SENTINEL; cljs.core.async.t_cljs$core$async16922.prototype.cljs$core$async$impl$protocols$Channel$close_BANG_$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return cljs.core.async.impl.protocols.close_BANG_(self__.ch); }); cljs.core.async.t_cljs$core$async16922.prototype.cljs$core$async$impl$protocols$Channel$closed_QMARK_$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return cljs.core.async.impl.protocols.closed_QMARK_(self__.ch); }); cljs.core.async.t_cljs$core$async16922.prototype.cljs$core$async$impl$protocols$ReadPort$ = cljs.core.PROTOCOL_SENTINEL; cljs.core.async.t_cljs$core$async16922.prototype.cljs$core$async$impl$protocols$ReadPort$take_BANG_$arity$2 = (function (_,fn1){ var self__ = this; var ___$1 = this; return cljs.core.async.impl.protocols.take_BANG_(self__.ch,fn1); }); cljs.core.async.t_cljs$core$async16922.prototype.cljs$core$async$impl$protocols$WritePort$ = cljs.core.PROTOCOL_SENTINEL; cljs.core.async.t_cljs$core$async16922.prototype.cljs$core$async$impl$protocols$WritePort$put_BANG_$arity$3 = (function (_,val,fn1){ var self__ = this; var ___$1 = this; if(cljs.core.truth_((self__.p.cljs$core$IFn$_invoke$arity$1 ? self__.p.cljs$core$IFn$_invoke$arity$1(val) : self__.p.call(null,val)))){ return cljs.core.async.impl.protocols.put_BANG_(self__.ch,val,fn1); } else { return cljs.core.async.impl.channels.box(cljs.core.not(cljs.core.async.impl.protocols.closed_QMARK_(self__.ch))); } }); cljs.core.async.t_cljs$core$async16922.getBasis = (function (){ return new cljs.core.PersistentVector(null, 3, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.cst$sym$p,cljs.core.cst$sym$ch,cljs.core.cst$sym$meta16923], null); }); cljs.core.async.t_cljs$core$async16922.cljs$lang$type = true; cljs.core.async.t_cljs$core$async16922.cljs$lang$ctorStr = "cljs.core.async/t_cljs$core$async16922"; cljs.core.async.t_cljs$core$async16922.cljs$lang$ctorPrWriter = (function (this__8293__auto__,writer__8294__auto__,opt__8295__auto__){ return cljs.core._write(writer__8294__auto__,"cljs.core.async/t_cljs$core$async16922"); }); cljs.core.async.__GT_t_cljs$core$async16922 = (function cljs$core$async$filter_GT__$___GT_t_cljs$core$async16922(p__$1,ch__$1,meta16923){ return (new cljs.core.async.t_cljs$core$async16922(p__$1,ch__$1,meta16923)); }); } return (new cljs.core.async.t_cljs$core$async16922(p,ch,cljs.core.PersistentArrayMap.EMPTY)); }); /** * Deprecated - this function will be removed. Use transducer instead */ cljs.core.async.remove_GT_ = (function cljs$core$async$remove_GT_(p,ch){ return cljs.core.async.filter_GT_(cljs.core.complement(p),ch); }); /** * Deprecated - this function will be removed. Use transducer instead */ cljs.core.async.filter_LT_ = (function cljs$core$async$filter_LT_(var_args){ var G__16926 = arguments.length; switch (G__16926) { case 2: return cljs.core.async.filter_LT_.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; case 3: return cljs.core.async.filter_LT_.cljs$core$IFn$_invoke$arity$3((arguments[(0)]),(arguments[(1)]),(arguments[(2)])); break; default: throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join(''))); } }); cljs.core.async.filter_LT_.cljs$core$IFn$_invoke$arity$2 = (function (p,ch){ return cljs.core.async.filter_LT_.cljs$core$IFn$_invoke$arity$3(p,ch,null); }); cljs.core.async.filter_LT_.cljs$core$IFn$_invoke$arity$3 = (function (p,ch,buf_or_n){ var out = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1(buf_or_n); var c__15437__auto___16966 = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1((1)); cljs.core.async.impl.dispatch.run(((function (c__15437__auto___16966,out){ return (function (){ var f__15438__auto__ = (function (){var switch__15337__auto__ = ((function (c__15437__auto___16966,out){ return (function (state_16947){ var state_val_16948 = (state_16947[(1)]); if((state_val_16948 === (7))){ var inst_16943 = (state_16947[(2)]); var state_16947__$1 = state_16947; var statearr_16949_16967 = state_16947__$1; (statearr_16949_16967[(2)] = inst_16943); (statearr_16949_16967[(1)] = (3)); return cljs.core.cst$kw$recur; } else { if((state_val_16948 === (1))){ var state_16947__$1 = state_16947; var statearr_16950_16968 = state_16947__$1; (statearr_16950_16968[(2)] = null); (statearr_16950_16968[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_16948 === (4))){ var inst_16929 = (state_16947[(7)]); var inst_16929__$1 = (state_16947[(2)]); var inst_16930 = (inst_16929__$1 == null); var state_16947__$1 = (function (){var statearr_16951 = state_16947; (statearr_16951[(7)] = inst_16929__$1); return statearr_16951; })(); if(cljs.core.truth_(inst_16930)){ var statearr_16952_16969 = state_16947__$1; (statearr_16952_16969[(1)] = (5)); } else { var statearr_16953_16970 = state_16947__$1; (statearr_16953_16970[(1)] = (6)); } return cljs.core.cst$kw$recur; } else { if((state_val_16948 === (6))){ var inst_16929 = (state_16947[(7)]); var inst_16934 = (p.cljs$core$IFn$_invoke$arity$1 ? p.cljs$core$IFn$_invoke$arity$1(inst_16929) : p.call(null,inst_16929)); var state_16947__$1 = state_16947; if(cljs.core.truth_(inst_16934)){ var statearr_16954_16971 = state_16947__$1; (statearr_16954_16971[(1)] = (8)); } else { var statearr_16955_16972 = state_16947__$1; (statearr_16955_16972[(1)] = (9)); } return cljs.core.cst$kw$recur; } else { if((state_val_16948 === (3))){ var inst_16945 = (state_16947[(2)]); var state_16947__$1 = state_16947; return cljs.core.async.impl.ioc_helpers.return_chan(state_16947__$1,inst_16945); } else { if((state_val_16948 === (2))){ var state_16947__$1 = state_16947; return cljs.core.async.impl.ioc_helpers.take_BANG_(state_16947__$1,(4),ch); } else { if((state_val_16948 === (11))){ var inst_16937 = (state_16947[(2)]); var state_16947__$1 = state_16947; var statearr_16956_16973 = state_16947__$1; (statearr_16956_16973[(2)] = inst_16937); (statearr_16956_16973[(1)] = (10)); return cljs.core.cst$kw$recur; } else { if((state_val_16948 === (9))){ var state_16947__$1 = state_16947; var statearr_16957_16974 = state_16947__$1; (statearr_16957_16974[(2)] = null); (statearr_16957_16974[(1)] = (10)); return cljs.core.cst$kw$recur; } else { if((state_val_16948 === (5))){ var inst_16932 = cljs.core.async.close_BANG_(out); var state_16947__$1 = state_16947; var statearr_16958_16975 = state_16947__$1; (statearr_16958_16975[(2)] = inst_16932); (statearr_16958_16975[(1)] = (7)); return cljs.core.cst$kw$recur; } else { if((state_val_16948 === (10))){ var inst_16940 = (state_16947[(2)]); var state_16947__$1 = (function (){var statearr_16959 = state_16947; (statearr_16959[(8)] = inst_16940); return statearr_16959; })(); var statearr_16960_16976 = state_16947__$1; (statearr_16960_16976[(2)] = null); (statearr_16960_16976[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_16948 === (8))){ var inst_16929 = (state_16947[(7)]); var state_16947__$1 = state_16947; return cljs.core.async.impl.ioc_helpers.put_BANG_(state_16947__$1,(11),out,inst_16929); } else { return null; } } } } } } } } } } } });})(c__15437__auto___16966,out)) ; return ((function (switch__15337__auto__,c__15437__auto___16966,out){ return (function() { var cljs$core$async$state_machine__15338__auto__ = null; var cljs$core$async$state_machine__15338__auto____0 = (function (){ var statearr_16961 = [null,null,null,null,null,null,null,null,null]; (statearr_16961[(0)] = cljs$core$async$state_machine__15338__auto__); (statearr_16961[(1)] = (1)); return statearr_16961; }); var cljs$core$async$state_machine__15338__auto____1 = (function (state_16947){ while(true){ var ret_value__15339__auto__ = (function (){try{while(true){ var result__15340__auto__ = switch__15337__auto__(state_16947); if(cljs.core.keyword_identical_QMARK_(result__15340__auto__,cljs.core.cst$kw$recur)){ continue; } else { return result__15340__auto__; } break; } }catch (e16962){if((e16962 instanceof Object)){ var ex__15341__auto__ = e16962; var statearr_16963_16977 = state_16947; (statearr_16963_16977[(5)] = ex__15341__auto__); cljs.core.async.impl.ioc_helpers.process_exception(state_16947); return cljs.core.cst$kw$recur; } else { throw e16962; } }})(); if(cljs.core.keyword_identical_QMARK_(ret_value__15339__auto__,cljs.core.cst$kw$recur)){ var G__16978 = state_16947; state_16947 = G__16978; continue; } else { return ret_value__15339__auto__; } break; } }); cljs$core$async$state_machine__15338__auto__ = function(state_16947){ switch(arguments.length){ case 0: return cljs$core$async$state_machine__15338__auto____0.call(this); case 1: return cljs$core$async$state_machine__15338__auto____1.call(this,state_16947); } throw(new Error('Invalid arity: ' + (arguments.length - 1))); }; cljs$core$async$state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$0 = cljs$core$async$state_machine__15338__auto____0; cljs$core$async$state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$1 = cljs$core$async$state_machine__15338__auto____1; return cljs$core$async$state_machine__15338__auto__; })() ;})(switch__15337__auto__,c__15437__auto___16966,out)) })(); var state__15439__auto__ = (function (){var statearr_16964 = (f__15438__auto__.cljs$core$IFn$_invoke$arity$0 ? f__15438__auto__.cljs$core$IFn$_invoke$arity$0() : f__15438__auto__.call(null)); (statearr_16964[(6)] = c__15437__auto___16966); return statearr_16964; })(); return cljs.core.async.impl.ioc_helpers.run_state_machine_wrapped(state__15439__auto__); });})(c__15437__auto___16966,out)) ); return out; }); cljs.core.async.filter_LT_.cljs$lang$maxFixedArity = 3; /** * Deprecated - this function will be removed. Use transducer instead */ cljs.core.async.remove_LT_ = (function cljs$core$async$remove_LT_(var_args){ var G__16980 = arguments.length; switch (G__16980) { case 2: return cljs.core.async.remove_LT_.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; case 3: return cljs.core.async.remove_LT_.cljs$core$IFn$_invoke$arity$3((arguments[(0)]),(arguments[(1)]),(arguments[(2)])); break; default: throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join(''))); } }); cljs.core.async.remove_LT_.cljs$core$IFn$_invoke$arity$2 = (function (p,ch){ return cljs.core.async.remove_LT_.cljs$core$IFn$_invoke$arity$3(p,ch,null); }); cljs.core.async.remove_LT_.cljs$core$IFn$_invoke$arity$3 = (function (p,ch,buf_or_n){ return cljs.core.async.filter_LT_.cljs$core$IFn$_invoke$arity$3(cljs.core.complement(p),ch,buf_or_n); }); cljs.core.async.remove_LT_.cljs$lang$maxFixedArity = 3; cljs.core.async.mapcat_STAR_ = (function cljs$core$async$mapcat_STAR_(f,in$,out){ var c__15437__auto__ = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1((1)); cljs.core.async.impl.dispatch.run(((function (c__15437__auto__){ return (function (){ var f__15438__auto__ = (function (){var switch__15337__auto__ = ((function (c__15437__auto__){ return (function (state_17043){ var state_val_17044 = (state_17043[(1)]); if((state_val_17044 === (7))){ var inst_17039 = (state_17043[(2)]); var state_17043__$1 = state_17043; var statearr_17045_17083 = state_17043__$1; (statearr_17045_17083[(2)] = inst_17039); (statearr_17045_17083[(1)] = (3)); return cljs.core.cst$kw$recur; } else { if((state_val_17044 === (20))){ var inst_17009 = (state_17043[(7)]); var inst_17020 = (state_17043[(2)]); var inst_17021 = cljs.core.next(inst_17009); var inst_16995 = inst_17021; var inst_16996 = null; var inst_16997 = (0); var inst_16998 = (0); var state_17043__$1 = (function (){var statearr_17046 = state_17043; (statearr_17046[(8)] = inst_16998); (statearr_17046[(9)] = inst_16996); (statearr_17046[(10)] = inst_16997); (statearr_17046[(11)] = inst_17020); (statearr_17046[(12)] = inst_16995); return statearr_17046; })(); var statearr_17047_17084 = state_17043__$1; (statearr_17047_17084[(2)] = null); (statearr_17047_17084[(1)] = (8)); return cljs.core.cst$kw$recur; } else { if((state_val_17044 === (1))){ var state_17043__$1 = state_17043; var statearr_17048_17085 = state_17043__$1; (statearr_17048_17085[(2)] = null); (statearr_17048_17085[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_17044 === (4))){ var inst_16984 = (state_17043[(13)]); var inst_16984__$1 = (state_17043[(2)]); var inst_16985 = (inst_16984__$1 == null); var state_17043__$1 = (function (){var statearr_17049 = state_17043; (statearr_17049[(13)] = inst_16984__$1); return statearr_17049; })(); if(cljs.core.truth_(inst_16985)){ var statearr_17050_17086 = state_17043__$1; (statearr_17050_17086[(1)] = (5)); } else { var statearr_17051_17087 = state_17043__$1; (statearr_17051_17087[(1)] = (6)); } return cljs.core.cst$kw$recur; } else { if((state_val_17044 === (15))){ var state_17043__$1 = state_17043; var statearr_17055_17088 = state_17043__$1; (statearr_17055_17088[(2)] = null); (statearr_17055_17088[(1)] = (16)); return cljs.core.cst$kw$recur; } else { if((state_val_17044 === (21))){ var state_17043__$1 = state_17043; var statearr_17056_17089 = state_17043__$1; (statearr_17056_17089[(2)] = null); (statearr_17056_17089[(1)] = (23)); return cljs.core.cst$kw$recur; } else { if((state_val_17044 === (13))){ var inst_16998 = (state_17043[(8)]); var inst_16996 = (state_17043[(9)]); var inst_16997 = (state_17043[(10)]); var inst_16995 = (state_17043[(12)]); var inst_17005 = (state_17043[(2)]); var inst_17006 = (inst_16998 + (1)); var tmp17052 = inst_16996; var tmp17053 = inst_16997; var tmp17054 = inst_16995; var inst_16995__$1 = tmp17054; var inst_16996__$1 = tmp17052; var inst_16997__$1 = tmp17053; var inst_16998__$1 = inst_17006; var state_17043__$1 = (function (){var statearr_17057 = state_17043; (statearr_17057[(8)] = inst_16998__$1); (statearr_17057[(9)] = inst_16996__$1); (statearr_17057[(10)] = inst_16997__$1); (statearr_17057[(14)] = inst_17005); (statearr_17057[(12)] = inst_16995__$1); return statearr_17057; })(); var statearr_17058_17090 = state_17043__$1; (statearr_17058_17090[(2)] = null); (statearr_17058_17090[(1)] = (8)); return cljs.core.cst$kw$recur; } else { if((state_val_17044 === (22))){ var state_17043__$1 = state_17043; var statearr_17059_17091 = state_17043__$1; (statearr_17059_17091[(2)] = null); (statearr_17059_17091[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_17044 === (6))){ var inst_16984 = (state_17043[(13)]); var inst_16993 = (f.cljs$core$IFn$_invoke$arity$1 ? f.cljs$core$IFn$_invoke$arity$1(inst_16984) : f.call(null,inst_16984)); var inst_16994 = cljs.core.seq(inst_16993); var inst_16995 = inst_16994; var inst_16996 = null; var inst_16997 = (0); var inst_16998 = (0); var state_17043__$1 = (function (){var statearr_17060 = state_17043; (statearr_17060[(8)] = inst_16998); (statearr_17060[(9)] = inst_16996); (statearr_17060[(10)] = inst_16997); (statearr_17060[(12)] = inst_16995); return statearr_17060; })(); var statearr_17061_17092 = state_17043__$1; (statearr_17061_17092[(2)] = null); (statearr_17061_17092[(1)] = (8)); return cljs.core.cst$kw$recur; } else { if((state_val_17044 === (17))){ var inst_17009 = (state_17043[(7)]); var inst_17013 = cljs.core.chunk_first(inst_17009); var inst_17014 = cljs.core.chunk_rest(inst_17009); var inst_17015 = cljs.core.count(inst_17013); var inst_16995 = inst_17014; var inst_16996 = inst_17013; var inst_16997 = inst_17015; var inst_16998 = (0); var state_17043__$1 = (function (){var statearr_17062 = state_17043; (statearr_17062[(8)] = inst_16998); (statearr_17062[(9)] = inst_16996); (statearr_17062[(10)] = inst_16997); (statearr_17062[(12)] = inst_16995); return statearr_17062; })(); var statearr_17063_17093 = state_17043__$1; (statearr_17063_17093[(2)] = null); (statearr_17063_17093[(1)] = (8)); return cljs.core.cst$kw$recur; } else { if((state_val_17044 === (3))){ var inst_17041 = (state_17043[(2)]); var state_17043__$1 = state_17043; return cljs.core.async.impl.ioc_helpers.return_chan(state_17043__$1,inst_17041); } else { if((state_val_17044 === (12))){ var inst_17029 = (state_17043[(2)]); var state_17043__$1 = state_17043; var statearr_17064_17094 = state_17043__$1; (statearr_17064_17094[(2)] = inst_17029); (statearr_17064_17094[(1)] = (9)); return cljs.core.cst$kw$recur; } else { if((state_val_17044 === (2))){ var state_17043__$1 = state_17043; return cljs.core.async.impl.ioc_helpers.take_BANG_(state_17043__$1,(4),in$); } else { if((state_val_17044 === (23))){ var inst_17037 = (state_17043[(2)]); var state_17043__$1 = state_17043; var statearr_17065_17095 = state_17043__$1; (statearr_17065_17095[(2)] = inst_17037); (statearr_17065_17095[(1)] = (7)); return cljs.core.cst$kw$recur; } else { if((state_val_17044 === (19))){ var inst_17024 = (state_17043[(2)]); var state_17043__$1 = state_17043; var statearr_17066_17096 = state_17043__$1; (statearr_17066_17096[(2)] = inst_17024); (statearr_17066_17096[(1)] = (16)); return cljs.core.cst$kw$recur; } else { if((state_val_17044 === (11))){ var inst_17009 = (state_17043[(7)]); var inst_16995 = (state_17043[(12)]); var inst_17009__$1 = cljs.core.seq(inst_16995); var state_17043__$1 = (function (){var statearr_17067 = state_17043; (statearr_17067[(7)] = inst_17009__$1); return statearr_17067; })(); if(inst_17009__$1){ var statearr_17068_17097 = state_17043__$1; (statearr_17068_17097[(1)] = (14)); } else { var statearr_17069_17098 = state_17043__$1; (statearr_17069_17098[(1)] = (15)); } return cljs.core.cst$kw$recur; } else { if((state_val_17044 === (9))){ var inst_17031 = (state_17043[(2)]); var inst_17032 = cljs.core.async.impl.protocols.closed_QMARK_(out); var state_17043__$1 = (function (){var statearr_17070 = state_17043; (statearr_17070[(15)] = inst_17031); return statearr_17070; })(); if(cljs.core.truth_(inst_17032)){ var statearr_17071_17099 = state_17043__$1; (statearr_17071_17099[(1)] = (21)); } else { var statearr_17072_17100 = state_17043__$1; (statearr_17072_17100[(1)] = (22)); } return cljs.core.cst$kw$recur; } else { if((state_val_17044 === (5))){ var inst_16987 = cljs.core.async.close_BANG_(out); var state_17043__$1 = state_17043; var statearr_17073_17101 = state_17043__$1; (statearr_17073_17101[(2)] = inst_16987); (statearr_17073_17101[(1)] = (7)); return cljs.core.cst$kw$recur; } else { if((state_val_17044 === (14))){ var inst_17009 = (state_17043[(7)]); var inst_17011 = cljs.core.chunked_seq_QMARK_(inst_17009); var state_17043__$1 = state_17043; if(inst_17011){ var statearr_17074_17102 = state_17043__$1; (statearr_17074_17102[(1)] = (17)); } else { var statearr_17075_17103 = state_17043__$1; (statearr_17075_17103[(1)] = (18)); } return cljs.core.cst$kw$recur; } else { if((state_val_17044 === (16))){ var inst_17027 = (state_17043[(2)]); var state_17043__$1 = state_17043; var statearr_17076_17104 = state_17043__$1; (statearr_17076_17104[(2)] = inst_17027); (statearr_17076_17104[(1)] = (12)); return cljs.core.cst$kw$recur; } else { if((state_val_17044 === (10))){ var inst_16998 = (state_17043[(8)]); var inst_16996 = (state_17043[(9)]); var inst_17003 = cljs.core._nth.cljs$core$IFn$_invoke$arity$2(inst_16996,inst_16998); var state_17043__$1 = state_17043; return cljs.core.async.impl.ioc_helpers.put_BANG_(state_17043__$1,(13),out,inst_17003); } else { if((state_val_17044 === (18))){ var inst_17009 = (state_17043[(7)]); var inst_17018 = cljs.core.first(inst_17009); var state_17043__$1 = state_17043; return cljs.core.async.impl.ioc_helpers.put_BANG_(state_17043__$1,(20),out,inst_17018); } else { if((state_val_17044 === (8))){ var inst_16998 = (state_17043[(8)]); var inst_16997 = (state_17043[(10)]); var inst_17000 = (inst_16998 < inst_16997); var inst_17001 = inst_17000; var state_17043__$1 = state_17043; if(cljs.core.truth_(inst_17001)){ var statearr_17077_17105 = state_17043__$1; (statearr_17077_17105[(1)] = (10)); } else { var statearr_17078_17106 = state_17043__$1; (statearr_17078_17106[(1)] = (11)); } return cljs.core.cst$kw$recur; } else { return null; } } } } } } } } } } } } } } } } } } } } } } } });})(c__15437__auto__)) ; return ((function (switch__15337__auto__,c__15437__auto__){ return (function() { var cljs$core$async$mapcat_STAR__$_state_machine__15338__auto__ = null; var cljs$core$async$mapcat_STAR__$_state_machine__15338__auto____0 = (function (){ var statearr_17079 = [null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null]; (statearr_17079[(0)] = cljs$core$async$mapcat_STAR__$_state_machine__15338__auto__); (statearr_17079[(1)] = (1)); return statearr_17079; }); var cljs$core$async$mapcat_STAR__$_state_machine__15338__auto____1 = (function (state_17043){ while(true){ var ret_value__15339__auto__ = (function (){try{while(true){ var result__15340__auto__ = switch__15337__auto__(state_17043); if(cljs.core.keyword_identical_QMARK_(result__15340__auto__,cljs.core.cst$kw$recur)){ continue; } else { return result__15340__auto__; } break; } }catch (e17080){if((e17080 instanceof Object)){ var ex__15341__auto__ = e17080; var statearr_17081_17107 = state_17043; (statearr_17081_17107[(5)] = ex__15341__auto__); cljs.core.async.impl.ioc_helpers.process_exception(state_17043); return cljs.core.cst$kw$recur; } else { throw e17080; } }})(); if(cljs.core.keyword_identical_QMARK_(ret_value__15339__auto__,cljs.core.cst$kw$recur)){ var G__17108 = state_17043; state_17043 = G__17108; continue; } else { return ret_value__15339__auto__; } break; } }); cljs$core$async$mapcat_STAR__$_state_machine__15338__auto__ = function(state_17043){ switch(arguments.length){ case 0: return cljs$core$async$mapcat_STAR__$_state_machine__15338__auto____0.call(this); case 1: return cljs$core$async$mapcat_STAR__$_state_machine__15338__auto____1.call(this,state_17043); } throw(new Error('Invalid arity: ' + (arguments.length - 1))); }; cljs$core$async$mapcat_STAR__$_state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$0 = cljs$core$async$mapcat_STAR__$_state_machine__15338__auto____0; cljs$core$async$mapcat_STAR__$_state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$1 = cljs$core$async$mapcat_STAR__$_state_machine__15338__auto____1; return cljs$core$async$mapcat_STAR__$_state_machine__15338__auto__; })() ;})(switch__15337__auto__,c__15437__auto__)) })(); var state__15439__auto__ = (function (){var statearr_17082 = (f__15438__auto__.cljs$core$IFn$_invoke$arity$0 ? f__15438__auto__.cljs$core$IFn$_invoke$arity$0() : f__15438__auto__.call(null)); (statearr_17082[(6)] = c__15437__auto__); return statearr_17082; })(); return cljs.core.async.impl.ioc_helpers.run_state_machine_wrapped(state__15439__auto__); });})(c__15437__auto__)) ); return c__15437__auto__; }); /** * Deprecated - this function will be removed. Use transducer instead */ cljs.core.async.mapcat_LT_ = (function cljs$core$async$mapcat_LT_(var_args){ var G__17110 = arguments.length; switch (G__17110) { case 2: return cljs.core.async.mapcat_LT_.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; case 3: return cljs.core.async.mapcat_LT_.cljs$core$IFn$_invoke$arity$3((arguments[(0)]),(arguments[(1)]),(arguments[(2)])); break; default: throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join(''))); } }); cljs.core.async.mapcat_LT_.cljs$core$IFn$_invoke$arity$2 = (function (f,in$){ return cljs.core.async.mapcat_LT_.cljs$core$IFn$_invoke$arity$3(f,in$,null); }); cljs.core.async.mapcat_LT_.cljs$core$IFn$_invoke$arity$3 = (function (f,in$,buf_or_n){ var out = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1(buf_or_n); cljs.core.async.mapcat_STAR_(f,in$,out); return out; }); cljs.core.async.mapcat_LT_.cljs$lang$maxFixedArity = 3; /** * Deprecated - this function will be removed. Use transducer instead */ cljs.core.async.mapcat_GT_ = (function cljs$core$async$mapcat_GT_(var_args){ var G__17113 = arguments.length; switch (G__17113) { case 2: return cljs.core.async.mapcat_GT_.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; case 3: return cljs.core.async.mapcat_GT_.cljs$core$IFn$_invoke$arity$3((arguments[(0)]),(arguments[(1)]),(arguments[(2)])); break; default: throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join(''))); } }); cljs.core.async.mapcat_GT_.cljs$core$IFn$_invoke$arity$2 = (function (f,out){ return cljs.core.async.mapcat_GT_.cljs$core$IFn$_invoke$arity$3(f,out,null); }); cljs.core.async.mapcat_GT_.cljs$core$IFn$_invoke$arity$3 = (function (f,out,buf_or_n){ var in$ = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1(buf_or_n); cljs.core.async.mapcat_STAR_(f,in$,out); return in$; }); cljs.core.async.mapcat_GT_.cljs$lang$maxFixedArity = 3; /** * Deprecated - this function will be removed. Use transducer instead */ cljs.core.async.unique = (function cljs$core$async$unique(var_args){ var G__17116 = arguments.length; switch (G__17116) { case 1: return cljs.core.async.unique.cljs$core$IFn$_invoke$arity$1((arguments[(0)])); break; case 2: return cljs.core.async.unique.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; default: throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join(''))); } }); cljs.core.async.unique.cljs$core$IFn$_invoke$arity$1 = (function (ch){ return cljs.core.async.unique.cljs$core$IFn$_invoke$arity$2(ch,null); }); cljs.core.async.unique.cljs$core$IFn$_invoke$arity$2 = (function (ch,buf_or_n){ var out = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1(buf_or_n); var c__15437__auto___17163 = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1((1)); cljs.core.async.impl.dispatch.run(((function (c__15437__auto___17163,out){ return (function (){ var f__15438__auto__ = (function (){var switch__15337__auto__ = ((function (c__15437__auto___17163,out){ return (function (state_17140){ var state_val_17141 = (state_17140[(1)]); if((state_val_17141 === (7))){ var inst_17135 = (state_17140[(2)]); var state_17140__$1 = state_17140; var statearr_17142_17164 = state_17140__$1; (statearr_17142_17164[(2)] = inst_17135); (statearr_17142_17164[(1)] = (3)); return cljs.core.cst$kw$recur; } else { if((state_val_17141 === (1))){ var inst_17117 = null; var state_17140__$1 = (function (){var statearr_17143 = state_17140; (statearr_17143[(7)] = inst_17117); return statearr_17143; })(); var statearr_17144_17165 = state_17140__$1; (statearr_17144_17165[(2)] = null); (statearr_17144_17165[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_17141 === (4))){ var inst_17120 = (state_17140[(8)]); var inst_17120__$1 = (state_17140[(2)]); var inst_17121 = (inst_17120__$1 == null); var inst_17122 = cljs.core.not(inst_17121); var state_17140__$1 = (function (){var statearr_17145 = state_17140; (statearr_17145[(8)] = inst_17120__$1); return statearr_17145; })(); if(inst_17122){ var statearr_17146_17166 = state_17140__$1; (statearr_17146_17166[(1)] = (5)); } else { var statearr_17147_17167 = state_17140__$1; (statearr_17147_17167[(1)] = (6)); } return cljs.core.cst$kw$recur; } else { if((state_val_17141 === (6))){ var state_17140__$1 = state_17140; var statearr_17148_17168 = state_17140__$1; (statearr_17148_17168[(2)] = null); (statearr_17148_17168[(1)] = (7)); return cljs.core.cst$kw$recur; } else { if((state_val_17141 === (3))){ var inst_17137 = (state_17140[(2)]); var inst_17138 = cljs.core.async.close_BANG_(out); var state_17140__$1 = (function (){var statearr_17149 = state_17140; (statearr_17149[(9)] = inst_17137); return statearr_17149; })(); return cljs.core.async.impl.ioc_helpers.return_chan(state_17140__$1,inst_17138); } else { if((state_val_17141 === (2))){ var state_17140__$1 = state_17140; return cljs.core.async.impl.ioc_helpers.take_BANG_(state_17140__$1,(4),ch); } else { if((state_val_17141 === (11))){ var inst_17120 = (state_17140[(8)]); var inst_17129 = (state_17140[(2)]); var inst_17117 = inst_17120; var state_17140__$1 = (function (){var statearr_17150 = state_17140; (statearr_17150[(7)] = inst_17117); (statearr_17150[(10)] = inst_17129); return statearr_17150; })(); var statearr_17151_17169 = state_17140__$1; (statearr_17151_17169[(2)] = null); (statearr_17151_17169[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_17141 === (9))){ var inst_17120 = (state_17140[(8)]); var state_17140__$1 = state_17140; return cljs.core.async.impl.ioc_helpers.put_BANG_(state_17140__$1,(11),out,inst_17120); } else { if((state_val_17141 === (5))){ var inst_17120 = (state_17140[(8)]); var inst_17117 = (state_17140[(7)]); var inst_17124 = cljs.core._EQ_.cljs$core$IFn$_invoke$arity$2(inst_17120,inst_17117); var state_17140__$1 = state_17140; if(inst_17124){ var statearr_17153_17170 = state_17140__$1; (statearr_17153_17170[(1)] = (8)); } else { var statearr_17154_17171 = state_17140__$1; (statearr_17154_17171[(1)] = (9)); } return cljs.core.cst$kw$recur; } else { if((state_val_17141 === (10))){ var inst_17132 = (state_17140[(2)]); var state_17140__$1 = state_17140; var statearr_17155_17172 = state_17140__$1; (statearr_17155_17172[(2)] = inst_17132); (statearr_17155_17172[(1)] = (7)); return cljs.core.cst$kw$recur; } else { if((state_val_17141 === (8))){ var inst_17117 = (state_17140[(7)]); var tmp17152 = inst_17117; var inst_17117__$1 = tmp17152; var state_17140__$1 = (function (){var statearr_17156 = state_17140; (statearr_17156[(7)] = inst_17117__$1); return statearr_17156; })(); var statearr_17157_17173 = state_17140__$1; (statearr_17157_17173[(2)] = null); (statearr_17157_17173[(1)] = (2)); return cljs.core.cst$kw$recur; } else { return null; } } } } } } } } } } } });})(c__15437__auto___17163,out)) ; return ((function (switch__15337__auto__,c__15437__auto___17163,out){ return (function() { var cljs$core$async$state_machine__15338__auto__ = null; var cljs$core$async$state_machine__15338__auto____0 = (function (){ var statearr_17158 = [null,null,null,null,null,null,null,null,null,null,null]; (statearr_17158[(0)] = cljs$core$async$state_machine__15338__auto__); (statearr_17158[(1)] = (1)); return statearr_17158; }); var cljs$core$async$state_machine__15338__auto____1 = (function (state_17140){ while(true){ var ret_value__15339__auto__ = (function (){try{while(true){ var result__15340__auto__ = switch__15337__auto__(state_17140); if(cljs.core.keyword_identical_QMARK_(result__15340__auto__,cljs.core.cst$kw$recur)){ continue; } else { return result__15340__auto__; } break; } }catch (e17159){if((e17159 instanceof Object)){ var ex__15341__auto__ = e17159; var statearr_17160_17174 = state_17140; (statearr_17160_17174[(5)] = ex__15341__auto__); cljs.core.async.impl.ioc_helpers.process_exception(state_17140); return cljs.core.cst$kw$recur; } else { throw e17159; } }})(); if(cljs.core.keyword_identical_QMARK_(ret_value__15339__auto__,cljs.core.cst$kw$recur)){ var G__17175 = state_17140; state_17140 = G__17175; continue; } else { return ret_value__15339__auto__; } break; } }); cljs$core$async$state_machine__15338__auto__ = function(state_17140){ switch(arguments.length){ case 0: return cljs$core$async$state_machine__15338__auto____0.call(this); case 1: return cljs$core$async$state_machine__15338__auto____1.call(this,state_17140); } throw(new Error('Invalid arity: ' + (arguments.length - 1))); }; cljs$core$async$state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$0 = cljs$core$async$state_machine__15338__auto____0; cljs$core$async$state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$1 = cljs$core$async$state_machine__15338__auto____1; return cljs$core$async$state_machine__15338__auto__; })() ;})(switch__15337__auto__,c__15437__auto___17163,out)) })(); var state__15439__auto__ = (function (){var statearr_17161 = (f__15438__auto__.cljs$core$IFn$_invoke$arity$0 ? f__15438__auto__.cljs$core$IFn$_invoke$arity$0() : f__15438__auto__.call(null)); (statearr_17161[(6)] = c__15437__auto___17163); return statearr_17161; })(); return cljs.core.async.impl.ioc_helpers.run_state_machine_wrapped(state__15439__auto__); });})(c__15437__auto___17163,out)) ); return out; }); cljs.core.async.unique.cljs$lang$maxFixedArity = 2; /** * Deprecated - this function will be removed. Use transducer instead */ cljs.core.async.partition = (function cljs$core$async$partition(var_args){ var G__17177 = arguments.length; switch (G__17177) { case 2: return cljs.core.async.partition.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; case 3: return cljs.core.async.partition.cljs$core$IFn$_invoke$arity$3((arguments[(0)]),(arguments[(1)]),(arguments[(2)])); break; default: throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join(''))); } }); cljs.core.async.partition.cljs$core$IFn$_invoke$arity$2 = (function (n,ch){ return cljs.core.async.partition.cljs$core$IFn$_invoke$arity$3(n,ch,null); }); cljs.core.async.partition.cljs$core$IFn$_invoke$arity$3 = (function (n,ch,buf_or_n){ var out = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1(buf_or_n); var c__15437__auto___17243 = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1((1)); cljs.core.async.impl.dispatch.run(((function (c__15437__auto___17243,out){ return (function (){ var f__15438__auto__ = (function (){var switch__15337__auto__ = ((function (c__15437__auto___17243,out){ return (function (state_17215){ var state_val_17216 = (state_17215[(1)]); if((state_val_17216 === (7))){ var inst_17211 = (state_17215[(2)]); var state_17215__$1 = state_17215; var statearr_17217_17244 = state_17215__$1; (statearr_17217_17244[(2)] = inst_17211); (statearr_17217_17244[(1)] = (3)); return cljs.core.cst$kw$recur; } else { if((state_val_17216 === (1))){ var inst_17178 = (new Array(n)); var inst_17179 = inst_17178; var inst_17180 = (0); var state_17215__$1 = (function (){var statearr_17218 = state_17215; (statearr_17218[(7)] = inst_17180); (statearr_17218[(8)] = inst_17179); return statearr_17218; })(); var statearr_17219_17245 = state_17215__$1; (statearr_17219_17245[(2)] = null); (statearr_17219_17245[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_17216 === (4))){ var inst_17183 = (state_17215[(9)]); var inst_17183__$1 = (state_17215[(2)]); var inst_17184 = (inst_17183__$1 == null); var inst_17185 = cljs.core.not(inst_17184); var state_17215__$1 = (function (){var statearr_17220 = state_17215; (statearr_17220[(9)] = inst_17183__$1); return statearr_17220; })(); if(inst_17185){ var statearr_17221_17246 = state_17215__$1; (statearr_17221_17246[(1)] = (5)); } else { var statearr_17222_17247 = state_17215__$1; (statearr_17222_17247[(1)] = (6)); } return cljs.core.cst$kw$recur; } else { if((state_val_17216 === (15))){ var inst_17205 = (state_17215[(2)]); var state_17215__$1 = state_17215; var statearr_17223_17248 = state_17215__$1; (statearr_17223_17248[(2)] = inst_17205); (statearr_17223_17248[(1)] = (14)); return cljs.core.cst$kw$recur; } else { if((state_val_17216 === (13))){ var state_17215__$1 = state_17215; var statearr_17224_17249 = state_17215__$1; (statearr_17224_17249[(2)] = null); (statearr_17224_17249[(1)] = (14)); return cljs.core.cst$kw$recur; } else { if((state_val_17216 === (6))){ var inst_17180 = (state_17215[(7)]); var inst_17201 = (inst_17180 > (0)); var state_17215__$1 = state_17215; if(cljs.core.truth_(inst_17201)){ var statearr_17225_17250 = state_17215__$1; (statearr_17225_17250[(1)] = (12)); } else { var statearr_17226_17251 = state_17215__$1; (statearr_17226_17251[(1)] = (13)); } return cljs.core.cst$kw$recur; } else { if((state_val_17216 === (3))){ var inst_17213 = (state_17215[(2)]); var state_17215__$1 = state_17215; return cljs.core.async.impl.ioc_helpers.return_chan(state_17215__$1,inst_17213); } else { if((state_val_17216 === (12))){ var inst_17179 = (state_17215[(8)]); var inst_17203 = cljs.core.vec(inst_17179); var state_17215__$1 = state_17215; return cljs.core.async.impl.ioc_helpers.put_BANG_(state_17215__$1,(15),out,inst_17203); } else { if((state_val_17216 === (2))){ var state_17215__$1 = state_17215; return cljs.core.async.impl.ioc_helpers.take_BANG_(state_17215__$1,(4),ch); } else { if((state_val_17216 === (11))){ var inst_17195 = (state_17215[(2)]); var inst_17196 = (new Array(n)); var inst_17179 = inst_17196; var inst_17180 = (0); var state_17215__$1 = (function (){var statearr_17227 = state_17215; (statearr_17227[(10)] = inst_17195); (statearr_17227[(7)] = inst_17180); (statearr_17227[(8)] = inst_17179); return statearr_17227; })(); var statearr_17228_17252 = state_17215__$1; (statearr_17228_17252[(2)] = null); (statearr_17228_17252[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_17216 === (9))){ var inst_17179 = (state_17215[(8)]); var inst_17193 = cljs.core.vec(inst_17179); var state_17215__$1 = state_17215; return cljs.core.async.impl.ioc_helpers.put_BANG_(state_17215__$1,(11),out,inst_17193); } else { if((state_val_17216 === (5))){ var inst_17183 = (state_17215[(9)]); var inst_17180 = (state_17215[(7)]); var inst_17188 = (state_17215[(11)]); var inst_17179 = (state_17215[(8)]); var inst_17187 = (inst_17179[inst_17180] = inst_17183); var inst_17188__$1 = (inst_17180 + (1)); var inst_17189 = (inst_17188__$1 < n); var state_17215__$1 = (function (){var statearr_17229 = state_17215; (statearr_17229[(12)] = inst_17187); (statearr_17229[(11)] = inst_17188__$1); return statearr_17229; })(); if(cljs.core.truth_(inst_17189)){ var statearr_17230_17253 = state_17215__$1; (statearr_17230_17253[(1)] = (8)); } else { var statearr_17231_17254 = state_17215__$1; (statearr_17231_17254[(1)] = (9)); } return cljs.core.cst$kw$recur; } else { if((state_val_17216 === (14))){ var inst_17208 = (state_17215[(2)]); var inst_17209 = cljs.core.async.close_BANG_(out); var state_17215__$1 = (function (){var statearr_17233 = state_17215; (statearr_17233[(13)] = inst_17208); return statearr_17233; })(); var statearr_17234_17255 = state_17215__$1; (statearr_17234_17255[(2)] = inst_17209); (statearr_17234_17255[(1)] = (7)); return cljs.core.cst$kw$recur; } else { if((state_val_17216 === (10))){ var inst_17199 = (state_17215[(2)]); var state_17215__$1 = state_17215; var statearr_17235_17256 = state_17215__$1; (statearr_17235_17256[(2)] = inst_17199); (statearr_17235_17256[(1)] = (7)); return cljs.core.cst$kw$recur; } else { if((state_val_17216 === (8))){ var inst_17188 = (state_17215[(11)]); var inst_17179 = (state_17215[(8)]); var tmp17232 = inst_17179; var inst_17179__$1 = tmp17232; var inst_17180 = inst_17188; var state_17215__$1 = (function (){var statearr_17236 = state_17215; (statearr_17236[(7)] = inst_17180); (statearr_17236[(8)] = inst_17179__$1); return statearr_17236; })(); var statearr_17237_17257 = state_17215__$1; (statearr_17237_17257[(2)] = null); (statearr_17237_17257[(1)] = (2)); return cljs.core.cst$kw$recur; } else { return null; } } } } } } } } } } } } } } } });})(c__15437__auto___17243,out)) ; return ((function (switch__15337__auto__,c__15437__auto___17243,out){ return (function() { var cljs$core$async$state_machine__15338__auto__ = null; var cljs$core$async$state_machine__15338__auto____0 = (function (){ var statearr_17238 = [null,null,null,null,null,null,null,null,null,null,null,null,null,null]; (statearr_17238[(0)] = cljs$core$async$state_machine__15338__auto__); (statearr_17238[(1)] = (1)); return statearr_17238; }); var cljs$core$async$state_machine__15338__auto____1 = (function (state_17215){ while(true){ var ret_value__15339__auto__ = (function (){try{while(true){ var result__15340__auto__ = switch__15337__auto__(state_17215); if(cljs.core.keyword_identical_QMARK_(result__15340__auto__,cljs.core.cst$kw$recur)){ continue; } else { return result__15340__auto__; } break; } }catch (e17239){if((e17239 instanceof Object)){ var ex__15341__auto__ = e17239; var statearr_17240_17258 = state_17215; (statearr_17240_17258[(5)] = ex__15341__auto__); cljs.core.async.impl.ioc_helpers.process_exception(state_17215); return cljs.core.cst$kw$recur; } else { throw e17239; } }})(); if(cljs.core.keyword_identical_QMARK_(ret_value__15339__auto__,cljs.core.cst$kw$recur)){ var G__17259 = state_17215; state_17215 = G__17259; continue; } else { return ret_value__15339__auto__; } break; } }); cljs$core$async$state_machine__15338__auto__ = function(state_17215){ switch(arguments.length){ case 0: return cljs$core$async$state_machine__15338__auto____0.call(this); case 1: return cljs$core$async$state_machine__15338__auto____1.call(this,state_17215); } throw(new Error('Invalid arity: ' + (arguments.length - 1))); }; cljs$core$async$state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$0 = cljs$core$async$state_machine__15338__auto____0; cljs$core$async$state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$1 = cljs$core$async$state_machine__15338__auto____1; return cljs$core$async$state_machine__15338__auto__; })() ;})(switch__15337__auto__,c__15437__auto___17243,out)) })(); var state__15439__auto__ = (function (){var statearr_17241 = (f__15438__auto__.cljs$core$IFn$_invoke$arity$0 ? f__15438__auto__.cljs$core$IFn$_invoke$arity$0() : f__15438__auto__.call(null)); (statearr_17241[(6)] = c__15437__auto___17243); return statearr_17241; })(); return cljs.core.async.impl.ioc_helpers.run_state_machine_wrapped(state__15439__auto__); });})(c__15437__auto___17243,out)) ); return out; }); cljs.core.async.partition.cljs$lang$maxFixedArity = 3; /** * Deprecated - this function will be removed. Use transducer instead */ cljs.core.async.partition_by = (function cljs$core$async$partition_by(var_args){ var G__17261 = arguments.length; switch (G__17261) { case 2: return cljs.core.async.partition_by.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; case 3: return cljs.core.async.partition_by.cljs$core$IFn$_invoke$arity$3((arguments[(0)]),(arguments[(1)]),(arguments[(2)])); break; default: throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join(''))); } }); cljs.core.async.partition_by.cljs$core$IFn$_invoke$arity$2 = (function (f,ch){ return cljs.core.async.partition_by.cljs$core$IFn$_invoke$arity$3(f,ch,null); }); cljs.core.async.partition_by.cljs$core$IFn$_invoke$arity$3 = (function (f,ch,buf_or_n){ var out = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1(buf_or_n); var c__15437__auto___17331 = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1((1)); cljs.core.async.impl.dispatch.run(((function (c__15437__auto___17331,out){ return (function (){ var f__15438__auto__ = (function (){var switch__15337__auto__ = ((function (c__15437__auto___17331,out){ return (function (state_17303){ var state_val_17304 = (state_17303[(1)]); if((state_val_17304 === (7))){ var inst_17299 = (state_17303[(2)]); var state_17303__$1 = state_17303; var statearr_17305_17332 = state_17303__$1; (statearr_17305_17332[(2)] = inst_17299); (statearr_17305_17332[(1)] = (3)); return cljs.core.cst$kw$recur; } else { if((state_val_17304 === (1))){ var inst_17262 = []; var inst_17263 = inst_17262; var inst_17264 = cljs.core.cst$kw$cljs$core$async_SLASH_nothing; var state_17303__$1 = (function (){var statearr_17306 = state_17303; (statearr_17306[(7)] = inst_17263); (statearr_17306[(8)] = inst_17264); return statearr_17306; })(); var statearr_17307_17333 = state_17303__$1; (statearr_17307_17333[(2)] = null); (statearr_17307_17333[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_17304 === (4))){ var inst_17267 = (state_17303[(9)]); var inst_17267__$1 = (state_17303[(2)]); var inst_17268 = (inst_17267__$1 == null); var inst_17269 = cljs.core.not(inst_17268); var state_17303__$1 = (function (){var statearr_17308 = state_17303; (statearr_17308[(9)] = inst_17267__$1); return statearr_17308; })(); if(inst_17269){ var statearr_17309_17334 = state_17303__$1; (statearr_17309_17334[(1)] = (5)); } else { var statearr_17310_17335 = state_17303__$1; (statearr_17310_17335[(1)] = (6)); } return cljs.core.cst$kw$recur; } else { if((state_val_17304 === (15))){ var inst_17293 = (state_17303[(2)]); var state_17303__$1 = state_17303; var statearr_17311_17336 = state_17303__$1; (statearr_17311_17336[(2)] = inst_17293); (statearr_17311_17336[(1)] = (14)); return cljs.core.cst$kw$recur; } else { if((state_val_17304 === (13))){ var state_17303__$1 = state_17303; var statearr_17312_17337 = state_17303__$1; (statearr_17312_17337[(2)] = null); (statearr_17312_17337[(1)] = (14)); return cljs.core.cst$kw$recur; } else { if((state_val_17304 === (6))){ var inst_17263 = (state_17303[(7)]); var inst_17288 = inst_17263.length; var inst_17289 = (inst_17288 > (0)); var state_17303__$1 = state_17303; if(cljs.core.truth_(inst_17289)){ var statearr_17313_17338 = state_17303__$1; (statearr_17313_17338[(1)] = (12)); } else { var statearr_17314_17339 = state_17303__$1; (statearr_17314_17339[(1)] = (13)); } return cljs.core.cst$kw$recur; } else { if((state_val_17304 === (3))){ var inst_17301 = (state_17303[(2)]); var state_17303__$1 = state_17303; return cljs.core.async.impl.ioc_helpers.return_chan(state_17303__$1,inst_17301); } else { if((state_val_17304 === (12))){ var inst_17263 = (state_17303[(7)]); var inst_17291 = cljs.core.vec(inst_17263); var state_17303__$1 = state_17303; return cljs.core.async.impl.ioc_helpers.put_BANG_(state_17303__$1,(15),out,inst_17291); } else { if((state_val_17304 === (2))){ var state_17303__$1 = state_17303; return cljs.core.async.impl.ioc_helpers.take_BANG_(state_17303__$1,(4),ch); } else { if((state_val_17304 === (11))){ var inst_17271 = (state_17303[(10)]); var inst_17267 = (state_17303[(9)]); var inst_17281 = (state_17303[(2)]); var inst_17282 = []; var inst_17283 = inst_17282.push(inst_17267); var inst_17263 = inst_17282; var inst_17264 = inst_17271; var state_17303__$1 = (function (){var statearr_17315 = state_17303; (statearr_17315[(7)] = inst_17263); (statearr_17315[(8)] = inst_17264); (statearr_17315[(11)] = inst_17281); (statearr_17315[(12)] = inst_17283); return statearr_17315; })(); var statearr_17316_17340 = state_17303__$1; (statearr_17316_17340[(2)] = null); (statearr_17316_17340[(1)] = (2)); return cljs.core.cst$kw$recur; } else { if((state_val_17304 === (9))){ var inst_17263 = (state_17303[(7)]); var inst_17279 = cljs.core.vec(inst_17263); var state_17303__$1 = state_17303; return cljs.core.async.impl.ioc_helpers.put_BANG_(state_17303__$1,(11),out,inst_17279); } else { if((state_val_17304 === (5))){ var inst_17271 = (state_17303[(10)]); var inst_17264 = (state_17303[(8)]); var inst_17267 = (state_17303[(9)]); var inst_17271__$1 = (f.cljs$core$IFn$_invoke$arity$1 ? f.cljs$core$IFn$_invoke$arity$1(inst_17267) : f.call(null,inst_17267)); var inst_17272 = cljs.core._EQ_.cljs$core$IFn$_invoke$arity$2(inst_17271__$1,inst_17264); var inst_17273 = cljs.core.keyword_identical_QMARK_(inst_17264,cljs.core.cst$kw$cljs$core$async_SLASH_nothing); var inst_17274 = (inst_17272) || (inst_17273); var state_17303__$1 = (function (){var statearr_17317 = state_17303; (statearr_17317[(10)] = inst_17271__$1); return statearr_17317; })(); if(cljs.core.truth_(inst_17274)){ var statearr_17318_17341 = state_17303__$1; (statearr_17318_17341[(1)] = (8)); } else { var statearr_17319_17342 = state_17303__$1; (statearr_17319_17342[(1)] = (9)); } return cljs.core.cst$kw$recur; } else { if((state_val_17304 === (14))){ var inst_17296 = (state_17303[(2)]); var inst_17297 = cljs.core.async.close_BANG_(out); var state_17303__$1 = (function (){var statearr_17321 = state_17303; (statearr_17321[(13)] = inst_17296); return statearr_17321; })(); var statearr_17322_17343 = state_17303__$1; (statearr_17322_17343[(2)] = inst_17297); (statearr_17322_17343[(1)] = (7)); return cljs.core.cst$kw$recur; } else { if((state_val_17304 === (10))){ var inst_17286 = (state_17303[(2)]); var state_17303__$1 = state_17303; var statearr_17323_17344 = state_17303__$1; (statearr_17323_17344[(2)] = inst_17286); (statearr_17323_17344[(1)] = (7)); return cljs.core.cst$kw$recur; } else { if((state_val_17304 === (8))){ var inst_17271 = (state_17303[(10)]); var inst_17263 = (state_17303[(7)]); var inst_17267 = (state_17303[(9)]); var inst_17276 = inst_17263.push(inst_17267); var tmp17320 = inst_17263; var inst_17263__$1 = tmp17320; var inst_17264 = inst_17271; var state_17303__$1 = (function (){var statearr_17324 = state_17303; (statearr_17324[(14)] = inst_17276); (statearr_17324[(7)] = inst_17263__$1); (statearr_17324[(8)] = inst_17264); return statearr_17324; })(); var statearr_17325_17345 = state_17303__$1; (statearr_17325_17345[(2)] = null); (statearr_17325_17345[(1)] = (2)); return cljs.core.cst$kw$recur; } else { return null; } } } } } } } } } } } } } } } });})(c__15437__auto___17331,out)) ; return ((function (switch__15337__auto__,c__15437__auto___17331,out){ return (function() { var cljs$core$async$state_machine__15338__auto__ = null; var cljs$core$async$state_machine__15338__auto____0 = (function (){ var statearr_17326 = [null,null,null,null,null,null,null,null,null,null,null,null,null,null,null]; (statearr_17326[(0)] = cljs$core$async$state_machine__15338__auto__); (statearr_17326[(1)] = (1)); return statearr_17326; }); var cljs$core$async$state_machine__15338__auto____1 = (function (state_17303){ while(true){ var ret_value__15339__auto__ = (function (){try{while(true){ var result__15340__auto__ = switch__15337__auto__(state_17303); if(cljs.core.keyword_identical_QMARK_(result__15340__auto__,cljs.core.cst$kw$recur)){ continue; } else { return result__15340__auto__; } break; } }catch (e17327){if((e17327 instanceof Object)){ var ex__15341__auto__ = e17327; var statearr_17328_17346 = state_17303; (statearr_17328_17346[(5)] = ex__15341__auto__); cljs.core.async.impl.ioc_helpers.process_exception(state_17303); return cljs.core.cst$kw$recur; } else { throw e17327; } }})(); if(cljs.core.keyword_identical_QMARK_(ret_value__15339__auto__,cljs.core.cst$kw$recur)){ var G__17347 = state_17303; state_17303 = G__17347; continue; } else { return ret_value__15339__auto__; } break; } }); cljs$core$async$state_machine__15338__auto__ = function(state_17303){ switch(arguments.length){ case 0: return cljs$core$async$state_machine__15338__auto____0.call(this); case 1: return cljs$core$async$state_machine__15338__auto____1.call(this,state_17303); } throw(new Error('Invalid arity: ' + (arguments.length - 1))); }; cljs$core$async$state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$0 = cljs$core$async$state_machine__15338__auto____0; cljs$core$async$state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$1 = cljs$core$async$state_machine__15338__auto____1; return cljs$core$async$state_machine__15338__auto__; })() ;})(switch__15337__auto__,c__15437__auto___17331,out)) })(); var state__15439__auto__ = (function (){var statearr_17329 = (f__15438__auto__.cljs$core$IFn$_invoke$arity$0 ? f__15438__auto__.cljs$core$IFn$_invoke$arity$0() : f__15438__auto__.call(null)); (statearr_17329[(6)] = c__15437__auto___17331); return statearr_17329; })(); return cljs.core.async.impl.ioc_helpers.run_state_machine_wrapped(state__15439__auto__); });})(c__15437__auto___17331,out)) ); return out; }); cljs.core.async.partition_by.cljs$lang$maxFixedArity = 3; <file_sep>// Compiled by ClojureScript 1.9.946 {:static-fns true, :optimize-constants true, :elide-asserts true} goog.provide('reagent.dom'); goog.require('cljs.core'); goog.require('cljs.core.constants'); goog.require('reagent.impl.util'); goog.require('reagent.impl.template'); goog.require('reagent.impl.batching'); goog.require('reagent.ratom'); goog.require('reagent.debug'); goog.require('reagent.interop'); if(typeof reagent.dom.imported !== 'undefined'){ } else { reagent.dom.imported = null; } reagent.dom.module = (function reagent$dom$module(){ if(!((reagent.dom.imported == null))){ return reagent.dom.imported; } else { if(typeof ReactDOM !== 'undefined'){ return reagent.dom.imported = ReactDOM; } else { if(typeof require !== 'undefined'){ var or__7668__auto__ = reagent.dom.imported = require("react-dom"); if(cljs.core.truth_(or__7668__auto__)){ return or__7668__auto__; } else { throw (new Error("require('react-dom') failed")); } } else { throw (new Error("js/ReactDOM is missing")); } } } }); if(typeof reagent.dom.roots !== 'undefined'){ } else { reagent.dom.roots = cljs.core.atom.cljs$core$IFn$_invoke$arity$1(cljs.core.PersistentArrayMap.EMPTY); } reagent.dom.unmount_comp = (function reagent$dom$unmount_comp(container){ cljs.core.swap_BANG_.cljs$core$IFn$_invoke$arity$3(reagent.dom.roots,cljs.core.dissoc,container); return (reagent.dom.module()["unmountComponentAtNode"])(container); }); reagent.dom.render_comp = (function reagent$dom$render_comp(comp,container,callback){ var _STAR_always_update_STAR_17772 = reagent.impl.util._STAR_always_update_STAR_; reagent.impl.util._STAR_always_update_STAR_ = true; try{return (reagent.dom.module()["render"])((comp.cljs$core$IFn$_invoke$arity$0 ? comp.cljs$core$IFn$_invoke$arity$0() : comp.call(null)),container,((function (_STAR_always_update_STAR_17772){ return (function (){ var _STAR_always_update_STAR_17773 = reagent.impl.util._STAR_always_update_STAR_; reagent.impl.util._STAR_always_update_STAR_ = false; try{cljs.core.swap_BANG_.cljs$core$IFn$_invoke$arity$4(reagent.dom.roots,cljs.core.assoc,container,new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [comp,container], null)); reagent.impl.batching.flush_after_render(); if(!((callback == null))){ return (callback.cljs$core$IFn$_invoke$arity$0 ? callback.cljs$core$IFn$_invoke$arity$0() : callback.call(null)); } else { return null; } }finally {reagent.impl.util._STAR_always_update_STAR_ = _STAR_always_update_STAR_17773; }});})(_STAR_always_update_STAR_17772)) ); }finally {reagent.impl.util._STAR_always_update_STAR_ = _STAR_always_update_STAR_17772; }}); reagent.dom.re_render_component = (function reagent$dom$re_render_component(comp,container){ return reagent.dom.render_comp(comp,container,null); }); /** * Render a Reagent component into the DOM. The first argument may be * either a vector (using Reagent's Hiccup syntax), or a React element. The second argument should be a DOM node. * * Optionally takes a callback that is called when the component is in place. * * Returns the mounted component instance. */ reagent.dom.render = (function reagent$dom$render(var_args){ var G__17775 = arguments.length; switch (G__17775) { case 2: return reagent.dom.render.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; case 3: return reagent.dom.render.cljs$core$IFn$_invoke$arity$3((arguments[(0)]),(arguments[(1)]),(arguments[(2)])); break; default: throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join(''))); } }); reagent.dom.render.cljs$core$IFn$_invoke$arity$2 = (function (comp,container){ return reagent.dom.render.cljs$core$IFn$_invoke$arity$3(comp,container,null); }); reagent.dom.render.cljs$core$IFn$_invoke$arity$3 = (function (comp,container,callback){ reagent.ratom.flush_BANG_(); var f = (function (){ return reagent.impl.template.as_element(((cljs.core.fn_QMARK_(comp))?(comp.cljs$core$IFn$_invoke$arity$0 ? comp.cljs$core$IFn$_invoke$arity$0() : comp.call(null)):comp)); }); return reagent.dom.render_comp(f,container,callback); }); reagent.dom.render.cljs$lang$maxFixedArity = 3; reagent.dom.unmount_component_at_node = (function reagent$dom$unmount_component_at_node(container){ return reagent.dom.unmount_comp(container); }); /** * Returns the root DOM node of a mounted component. */ reagent.dom.dom_node = (function reagent$dom$dom_node(this$){ return (reagent.dom.module()["findDOMNode"])(this$); }); reagent.impl.template.find_dom_node = reagent.dom.dom_node; /** * Force re-rendering of all mounted Reagent components. This is * probably only useful in a development environment, when you want to * update components in response to some dynamic changes to code. * * Note that force-update-all may not update root components. This * happens if a component 'foo' is mounted with `(render [foo])` (since * functions are passed by value, and not by reference, in * ClojureScript). To get around this you'll have to introduce a layer * of indirection, for example by using `(render [#'foo])` instead. */ reagent.dom.force_update_all = (function reagent$dom$force_update_all(){ reagent.ratom.flush_BANG_(); var seq__17777_17781 = cljs.core.seq(cljs.core.vals(cljs.core.deref(reagent.dom.roots))); var chunk__17778_17782 = null; var count__17779_17783 = (0); var i__17780_17784 = (0); while(true){ if((i__17780_17784 < count__17779_17783)){ var v_17785 = chunk__17778_17782.cljs$core$IIndexed$_nth$arity$2(null,i__17780_17784); cljs.core.apply.cljs$core$IFn$_invoke$arity$2(reagent.dom.re_render_component,v_17785); var G__17786 = seq__17777_17781; var G__17787 = chunk__17778_17782; var G__17788 = count__17779_17783; var G__17789 = (i__17780_17784 + (1)); seq__17777_17781 = G__17786; chunk__17778_17782 = G__17787; count__17779_17783 = G__17788; i__17780_17784 = G__17789; continue; } else { var temp__4657__auto___17790 = cljs.core.seq(seq__17777_17781); if(temp__4657__auto___17790){ var seq__17777_17791__$1 = temp__4657__auto___17790; if(cljs.core.chunked_seq_QMARK_(seq__17777_17791__$1)){ var c__8507__auto___17792 = cljs.core.chunk_first(seq__17777_17791__$1); var G__17793 = cljs.core.chunk_rest(seq__17777_17791__$1); var G__17794 = c__8507__auto___17792; var G__17795 = cljs.core.count(c__8507__auto___17792); var G__17796 = (0); seq__17777_17781 = G__17793; chunk__17778_17782 = G__17794; count__17779_17783 = G__17795; i__17780_17784 = G__17796; continue; } else { var v_17797 = cljs.core.first(seq__17777_17791__$1); cljs.core.apply.cljs$core$IFn$_invoke$arity$2(reagent.dom.re_render_component,v_17797); var G__17798 = cljs.core.next(seq__17777_17791__$1); var G__17799 = null; var G__17800 = (0); var G__17801 = (0); seq__17777_17781 = G__17798; chunk__17778_17782 = G__17799; count__17779_17783 = G__17800; i__17780_17784 = G__17801; continue; } } else { } } break; } return "Updated"; }); <file_sep>// Compiled by ClojureScript 1.9.946 {:static-fns true, :optimize-constants true, :elide-asserts true} goog.provide('cljs_http.core'); goog.require('cljs.core'); goog.require('cljs.core.constants'); goog.require('goog.net.EventType'); goog.require('goog.net.ErrorCode'); goog.require('goog.net.XhrIo'); goog.require('goog.net.Jsonp'); goog.require('cljs_http.util'); goog.require('cljs.core.async'); goog.require('clojure.string'); cljs_http.core.pending_requests = cljs.core.atom.cljs$core$IFn$_invoke$arity$1(cljs.core.PersistentArrayMap.EMPTY); /** * Attempt to close the given channel and abort the pending HTTP request * with which it is associated. */ cljs_http.core.abort_BANG_ = (function cljs_http$core$abort_BANG_(channel){ var temp__4657__auto__ = (function (){var fexpr__17369 = cljs.core.deref(cljs_http.core.pending_requests); return (fexpr__17369.cljs$core$IFn$_invoke$arity$1 ? fexpr__17369.cljs$core$IFn$_invoke$arity$1(channel) : fexpr__17369.call(null,channel)); })(); if(cljs.core.truth_(temp__4657__auto__)){ var req = temp__4657__auto__; cljs.core.swap_BANG_.cljs$core$IFn$_invoke$arity$3(cljs_http.core.pending_requests,cljs.core.dissoc,channel); cljs.core.async.close_BANG_(channel); if(cljs.core.truth_(req.hasOwnProperty("abort"))){ return req.abort(); } else { return cljs.core.cst$kw$jsonp.cljs$core$IFn$_invoke$arity$1(req).cancel(cljs.core.cst$kw$request.cljs$core$IFn$_invoke$arity$1(req)); } } else { return null; } }); cljs_http.core.aborted_QMARK_ = (function cljs_http$core$aborted_QMARK_(xhr){ return cljs.core._EQ_.cljs$core$IFn$_invoke$arity$2(xhr.getLastErrorCode(),goog.net.ErrorCode.ABORT); }); /** * Takes an XhrIo object and applies the default-headers to it. */ cljs_http.core.apply_default_headers_BANG_ = (function cljs_http$core$apply_default_headers_BANG_(xhr,headers){ var formatted_h = cljs.core.zipmap(cljs.core.map.cljs$core$IFn$_invoke$arity$2(cljs_http.util.camelize,cljs.core.keys(headers)),cljs.core.vals(headers)); return cljs.core.dorun.cljs$core$IFn$_invoke$arity$1(cljs.core.map.cljs$core$IFn$_invoke$arity$2(((function (formatted_h){ return (function (p__17370){ var vec__17371 = p__17370; var k = cljs.core.nth.cljs$core$IFn$_invoke$arity$3(vec__17371,(0),null); var v = cljs.core.nth.cljs$core$IFn$_invoke$arity$3(vec__17371,(1),null); return xhr.headers.set(k,v); });})(formatted_h)) ,formatted_h)); }); /** * Takes an XhrIo object and sets response-type if not nil. */ cljs_http.core.apply_response_type_BANG_ = (function cljs_http$core$apply_response_type_BANG_(xhr,response_type){ return xhr.setResponseType((function (){var G__17374 = response_type; if(cljs.core._EQ_.cljs$core$IFn$_invoke$arity$2(cljs.core.cst$kw$array_DASH_buffer,G__17374)){ return goog.net.XhrIo.ResponseType.ARRAY_BUFFER; } else { if(cljs.core._EQ_.cljs$core$IFn$_invoke$arity$2(cljs.core.cst$kw$blob,G__17374)){ return goog.net.XhrIo.ResponseType.BLOB; } else { if(cljs.core._EQ_.cljs$core$IFn$_invoke$arity$2(cljs.core.cst$kw$document,G__17374)){ return goog.net.XhrIo.ResponseType.DOCUMENT; } else { if(cljs.core._EQ_.cljs$core$IFn$_invoke$arity$2(cljs.core.cst$kw$text,G__17374)){ return goog.net.XhrIo.ResponseType.TEXT; } else { if(cljs.core._EQ_.cljs$core$IFn$_invoke$arity$2(cljs.core.cst$kw$default,G__17374)){ return goog.net.XhrIo.ResponseType.DEFAULT; } else { if(cljs.core._EQ_.cljs$core$IFn$_invoke$arity$2(null,G__17374)){ return goog.net.XhrIo.ResponseType.DEFAULT; } else { throw (new Error(["No matching clause: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(G__17374)].join(''))); } } } } } } })()); }); /** * Builds an XhrIo object from the request parameters. */ cljs_http.core.build_xhr = (function cljs_http$core$build_xhr(p__17375){ var map__17376 = p__17375; var map__17376__$1 = ((((!((map__17376 == null)))?((((map__17376.cljs$lang$protocol_mask$partition0$ & (64))) || ((cljs.core.PROTOCOL_SENTINEL === map__17376.cljs$core$ISeq$)))?true:false):false))?cljs.core.apply.cljs$core$IFn$_invoke$arity$2(cljs.core.hash_map,map__17376):map__17376); var request = map__17376__$1; var with_credentials_QMARK_ = cljs.core.get.cljs$core$IFn$_invoke$arity$2(map__17376__$1,cljs.core.cst$kw$with_DASH_credentials_QMARK_); var default_headers = cljs.core.get.cljs$core$IFn$_invoke$arity$2(map__17376__$1,cljs.core.cst$kw$default_DASH_headers); var response_type = cljs.core.get.cljs$core$IFn$_invoke$arity$2(map__17376__$1,cljs.core.cst$kw$response_DASH_type); var timeout = (function (){var or__7668__auto__ = cljs.core.cst$kw$timeout.cljs$core$IFn$_invoke$arity$1(request); if(cljs.core.truth_(or__7668__auto__)){ return or__7668__auto__; } else { return (0); } })(); var send_credentials = (((with_credentials_QMARK_ == null))?true:with_credentials_QMARK_); var G__17378 = (new goog.net.XhrIo()); cljs_http.core.apply_default_headers_BANG_(G__17378,default_headers); cljs_http.core.apply_response_type_BANG_(G__17378,response_type); G__17378.setTimeoutInterval(timeout); G__17378.setWithCredentials(send_credentials); return G__17378; }); cljs_http.core.error_kw = cljs.core.PersistentHashMap.fromArrays([(0),(7),(1),(4),(6),(3),(2),(9),(5),(8)],[cljs.core.cst$kw$no_DASH_error,cljs.core.cst$kw$abort,cljs.core.cst$kw$access_DASH_denied,cljs.core.cst$kw$custom_DASH_error,cljs.core.cst$kw$http_DASH_error,cljs.core.cst$kw$ff_DASH_silent_DASH_error,cljs.core.cst$kw$file_DASH_not_DASH_found,cljs.core.cst$kw$offline,cljs.core.cst$kw$exception,cljs.core.cst$kw$timeout]); /** * Execute the HTTP request corresponding to the given Ring request * map and return a core.async channel. */ cljs_http.core.xhr = (function cljs_http$core$xhr(p__17379){ var map__17380 = p__17379; var map__17380__$1 = ((((!((map__17380 == null)))?((((map__17380.cljs$lang$protocol_mask$partition0$ & (64))) || ((cljs.core.PROTOCOL_SENTINEL === map__17380.cljs$core$ISeq$)))?true:false):false))?cljs.core.apply.cljs$core$IFn$_invoke$arity$2(cljs.core.hash_map,map__17380):map__17380); var request = map__17380__$1; var request_method = cljs.core.get.cljs$core$IFn$_invoke$arity$2(map__17380__$1,cljs.core.cst$kw$request_DASH_method); var headers = cljs.core.get.cljs$core$IFn$_invoke$arity$2(map__17380__$1,cljs.core.cst$kw$headers); var body = cljs.core.get.cljs$core$IFn$_invoke$arity$2(map__17380__$1,cljs.core.cst$kw$body); var with_credentials_QMARK_ = cljs.core.get.cljs$core$IFn$_invoke$arity$2(map__17380__$1,cljs.core.cst$kw$with_DASH_credentials_QMARK_); var cancel = cljs.core.get.cljs$core$IFn$_invoke$arity$2(map__17380__$1,cljs.core.cst$kw$cancel); var progress = cljs.core.get.cljs$core$IFn$_invoke$arity$2(map__17380__$1,cljs.core.cst$kw$progress); var channel = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$0(); var request_url = cljs_http.util.build_url(request); var method = cljs.core.name((function (){var or__7668__auto__ = request_method; if(cljs.core.truth_(or__7668__auto__)){ return or__7668__auto__; } else { return cljs.core.cst$kw$get; } })()); var headers__$1 = cljs_http.util.build_headers(headers); var xhr = cljs_http.core.build_xhr(request); cljs.core.swap_BANG_.cljs$core$IFn$_invoke$arity$4(cljs_http.core.pending_requests,cljs.core.assoc,channel,xhr); xhr.listen(goog.net.EventType.COMPLETE,((function (channel,request_url,method,headers__$1,xhr,map__17380,map__17380__$1,request,request_method,headers,body,with_credentials_QMARK_,cancel,progress){ return (function (evt){ var target = evt.target; var response = new cljs.core.PersistentArrayMap(null, 7, [cljs.core.cst$kw$status,target.getStatus(),cljs.core.cst$kw$success,target.isSuccess(),cljs.core.cst$kw$body,target.getResponse(),cljs.core.cst$kw$headers,cljs_http.util.parse_headers(target.getAllResponseHeaders()),cljs.core.cst$kw$trace_DASH_redirects,new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [request_url,target.getLastUri()], null),cljs.core.cst$kw$error_DASH_code,(function (){var G__17382 = target.getLastErrorCode(); return (cljs_http.core.error_kw.cljs$core$IFn$_invoke$arity$1 ? cljs_http.core.error_kw.cljs$core$IFn$_invoke$arity$1(G__17382) : cljs_http.core.error_kw.call(null,G__17382)); })(),cljs.core.cst$kw$error_DASH_text,target.getLastError()], null); if(cljs.core.not(cljs_http.core.aborted_QMARK_(xhr))){ cljs.core.async.put_BANG_.cljs$core$IFn$_invoke$arity$2(channel,response); } else { } cljs.core.swap_BANG_.cljs$core$IFn$_invoke$arity$3(cljs_http.core.pending_requests,cljs.core.dissoc,channel); if(cljs.core.truth_(cancel)){ cljs.core.async.close_BANG_(cancel); } else { } return cljs.core.async.close_BANG_(channel); });})(channel,request_url,method,headers__$1,xhr,map__17380,map__17380__$1,request,request_method,headers,body,with_credentials_QMARK_,cancel,progress)) ); if(cljs.core.truth_(progress)){ var listener_17405 = ((function (channel,request_url,method,headers__$1,xhr,map__17380,map__17380__$1,request,request_method,headers,body,with_credentials_QMARK_,cancel,progress){ return (function (direction,evt){ return cljs.core.async.put_BANG_.cljs$core$IFn$_invoke$arity$2(progress,cljs.core.merge.cljs$core$IFn$_invoke$arity$variadic(cljs.core.prim_seq.cljs$core$IFn$_invoke$arity$2([new cljs.core.PersistentArrayMap(null, 2, [cljs.core.cst$kw$direction,direction,cljs.core.cst$kw$loaded,evt.loaded], null),(cljs.core.truth_(evt.lengthComputable)?new cljs.core.PersistentArrayMap(null, 1, [cljs.core.cst$kw$total,evt.total], null):null)], 0))); });})(channel,request_url,method,headers__$1,xhr,map__17380,map__17380__$1,request,request_method,headers,body,with_credentials_QMARK_,cancel,progress)) ; var G__17383_17406 = xhr; G__17383_17406.setProgressEventsEnabled(true); G__17383_17406.listen(goog.net.EventType.UPLOAD_PROGRESS,cljs.core.partial.cljs$core$IFn$_invoke$arity$2(listener_17405,cljs.core.cst$kw$upload)); G__17383_17406.listen(goog.net.EventType.DOWNLOAD_PROGRESS,cljs.core.partial.cljs$core$IFn$_invoke$arity$2(listener_17405,cljs.core.cst$kw$download)); } else { } xhr.send(request_url,method,body,headers__$1); if(cljs.core.truth_(cancel)){ var c__15437__auto___17407 = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1((1)); cljs.core.async.impl.dispatch.run(((function (c__15437__auto___17407,channel,request_url,method,headers__$1,xhr,map__17380,map__17380__$1,request,request_method,headers,body,with_credentials_QMARK_,cancel,progress){ return (function (){ var f__15438__auto__ = (function (){var switch__15337__auto__ = ((function (c__15437__auto___17407,channel,request_url,method,headers__$1,xhr,map__17380,map__17380__$1,request,request_method,headers,body,with_credentials_QMARK_,cancel,progress){ return (function (state_17394){ var state_val_17395 = (state_17394[(1)]); if((state_val_17395 === (1))){ var state_17394__$1 = state_17394; return cljs.core.async.impl.ioc_helpers.take_BANG_(state_17394__$1,(2),cancel); } else { if((state_val_17395 === (2))){ var inst_17385 = (state_17394[(2)]); var inst_17386 = xhr.isComplete(); var inst_17387 = cljs.core.not(inst_17386); var state_17394__$1 = (function (){var statearr_17396 = state_17394; (statearr_17396[(7)] = inst_17385); return statearr_17396; })(); if(inst_17387){ var statearr_17397_17408 = state_17394__$1; (statearr_17397_17408[(1)] = (3)); } else { var statearr_17398_17409 = state_17394__$1; (statearr_17398_17409[(1)] = (4)); } return cljs.core.cst$kw$recur; } else { if((state_val_17395 === (3))){ var inst_17389 = xhr.abort(); var state_17394__$1 = state_17394; var statearr_17399_17410 = state_17394__$1; (statearr_17399_17410[(2)] = inst_17389); (statearr_17399_17410[(1)] = (5)); return cljs.core.cst$kw$recur; } else { if((state_val_17395 === (4))){ var state_17394__$1 = state_17394; var statearr_17400_17411 = state_17394__$1; (statearr_17400_17411[(2)] = null); (statearr_17400_17411[(1)] = (5)); return cljs.core.cst$kw$recur; } else { if((state_val_17395 === (5))){ var inst_17392 = (state_17394[(2)]); var state_17394__$1 = state_17394; return cljs.core.async.impl.ioc_helpers.return_chan(state_17394__$1,inst_17392); } else { return null; } } } } } });})(c__15437__auto___17407,channel,request_url,method,headers__$1,xhr,map__17380,map__17380__$1,request,request_method,headers,body,with_credentials_QMARK_,cancel,progress)) ; return ((function (switch__15337__auto__,c__15437__auto___17407,channel,request_url,method,headers__$1,xhr,map__17380,map__17380__$1,request,request_method,headers,body,with_credentials_QMARK_,cancel,progress){ return (function() { var cljs_http$core$xhr_$_state_machine__15338__auto__ = null; var cljs_http$core$xhr_$_state_machine__15338__auto____0 = (function (){ var statearr_17401 = [null,null,null,null,null,null,null,null]; (statearr_17401[(0)] = cljs_http$core$xhr_$_state_machine__15338__auto__); (statearr_17401[(1)] = (1)); return statearr_17401; }); var cljs_http$core$xhr_$_state_machine__15338__auto____1 = (function (state_17394){ while(true){ var ret_value__15339__auto__ = (function (){try{while(true){ var result__15340__auto__ = switch__15337__auto__(state_17394); if(cljs.core.keyword_identical_QMARK_(result__15340__auto__,cljs.core.cst$kw$recur)){ continue; } else { return result__15340__auto__; } break; } }catch (e17402){if((e17402 instanceof Object)){ var ex__15341__auto__ = e17402; var statearr_17403_17412 = state_17394; (statearr_17403_17412[(5)] = ex__15341__auto__); cljs.core.async.impl.ioc_helpers.process_exception(state_17394); return cljs.core.cst$kw$recur; } else { throw e17402; } }})(); if(cljs.core.keyword_identical_QMARK_(ret_value__15339__auto__,cljs.core.cst$kw$recur)){ var G__17413 = state_17394; state_17394 = G__17413; continue; } else { return ret_value__15339__auto__; } break; } }); cljs_http$core$xhr_$_state_machine__15338__auto__ = function(state_17394){ switch(arguments.length){ case 0: return cljs_http$core$xhr_$_state_machine__15338__auto____0.call(this); case 1: return cljs_http$core$xhr_$_state_machine__15338__auto____1.call(this,state_17394); } throw(new Error('Invalid arity: ' + (arguments.length - 1))); }; cljs_http$core$xhr_$_state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$0 = cljs_http$core$xhr_$_state_machine__15338__auto____0; cljs_http$core$xhr_$_state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$1 = cljs_http$core$xhr_$_state_machine__15338__auto____1; return cljs_http$core$xhr_$_state_machine__15338__auto__; })() ;})(switch__15337__auto__,c__15437__auto___17407,channel,request_url,method,headers__$1,xhr,map__17380,map__17380__$1,request,request_method,headers,body,with_credentials_QMARK_,cancel,progress)) })(); var state__15439__auto__ = (function (){var statearr_17404 = (f__15438__auto__.cljs$core$IFn$_invoke$arity$0 ? f__15438__auto__.cljs$core$IFn$_invoke$arity$0() : f__15438__auto__.call(null)); (statearr_17404[(6)] = c__15437__auto___17407); return statearr_17404; })(); return cljs.core.async.impl.ioc_helpers.run_state_machine_wrapped(state__15439__auto__); });})(c__15437__auto___17407,channel,request_url,method,headers__$1,xhr,map__17380,map__17380__$1,request,request_method,headers,body,with_credentials_QMARK_,cancel,progress)) ); } else { } return channel; }); /** * Execute the JSONP request corresponding to the given Ring request * map and return a core.async channel. */ cljs_http.core.jsonp = (function cljs_http$core$jsonp(p__17414){ var map__17415 = p__17414; var map__17415__$1 = ((((!((map__17415 == null)))?((((map__17415.cljs$lang$protocol_mask$partition0$ & (64))) || ((cljs.core.PROTOCOL_SENTINEL === map__17415.cljs$core$ISeq$)))?true:false):false))?cljs.core.apply.cljs$core$IFn$_invoke$arity$2(cljs.core.hash_map,map__17415):map__17415); var request = map__17415__$1; var timeout = cljs.core.get.cljs$core$IFn$_invoke$arity$2(map__17415__$1,cljs.core.cst$kw$timeout); var callback_name = cljs.core.get.cljs$core$IFn$_invoke$arity$2(map__17415__$1,cljs.core.cst$kw$callback_DASH_name); var cancel = cljs.core.get.cljs$core$IFn$_invoke$arity$2(map__17415__$1,cljs.core.cst$kw$cancel); var keywordize_keys_QMARK_ = cljs.core.get.cljs$core$IFn$_invoke$arity$3(map__17415__$1,cljs.core.cst$kw$keywordize_DASH_keys_QMARK_,true); var channel = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$0(); var jsonp = (new goog.net.Jsonp(cljs_http.util.build_url(request),callback_name)); jsonp.setRequestTimeout(timeout); var req_17428 = jsonp.send(null,((function (channel,jsonp,map__17415,map__17415__$1,request,timeout,callback_name,cancel,keywordize_keys_QMARK_){ return (function cljs_http$core$jsonp_$_success_callback(data){ var response = new cljs.core.PersistentArrayMap(null, 3, [cljs.core.cst$kw$status,(200),cljs.core.cst$kw$success,true,cljs.core.cst$kw$body,cljs.core.js__GT_clj.cljs$core$IFn$_invoke$arity$variadic(data,cljs.core.prim_seq.cljs$core$IFn$_invoke$arity$2([cljs.core.cst$kw$keywordize_DASH_keys,keywordize_keys_QMARK_], 0))], null); cljs.core.async.put_BANG_.cljs$core$IFn$_invoke$arity$2(channel,response); cljs.core.swap_BANG_.cljs$core$IFn$_invoke$arity$3(cljs_http.core.pending_requests,cljs.core.dissoc,channel); if(cljs.core.truth_(cancel)){ cljs.core.async.close_BANG_(cancel); } else { } return cljs.core.async.close_BANG_(channel); });})(channel,jsonp,map__17415,map__17415__$1,request,timeout,callback_name,cancel,keywordize_keys_QMARK_)) ,((function (channel,jsonp,map__17415,map__17415__$1,request,timeout,callback_name,cancel,keywordize_keys_QMARK_){ return (function cljs_http$core$jsonp_$_error_callback(){ cljs.core.swap_BANG_.cljs$core$IFn$_invoke$arity$3(cljs_http.core.pending_requests,cljs.core.dissoc,channel); if(cljs.core.truth_(cancel)){ cljs.core.async.close_BANG_(cancel); } else { } return cljs.core.async.close_BANG_(channel); });})(channel,jsonp,map__17415,map__17415__$1,request,timeout,callback_name,cancel,keywordize_keys_QMARK_)) ); cljs.core.swap_BANG_.cljs$core$IFn$_invoke$arity$4(cljs_http.core.pending_requests,cljs.core.assoc,channel,new cljs.core.PersistentArrayMap(null, 2, [cljs.core.cst$kw$jsonp,jsonp,cljs.core.cst$kw$request,req_17428], null)); if(cljs.core.truth_(cancel)){ var c__15437__auto___17429 = cljs.core.async.chan.cljs$core$IFn$_invoke$arity$1((1)); cljs.core.async.impl.dispatch.run(((function (c__15437__auto___17429,req_17428,channel,jsonp,map__17415,map__17415__$1,request,timeout,callback_name,cancel,keywordize_keys_QMARK_){ return (function (){ var f__15438__auto__ = (function (){var switch__15337__auto__ = ((function (c__15437__auto___17429,req_17428,channel,jsonp,map__17415,map__17415__$1,request,timeout,callback_name,cancel,keywordize_keys_QMARK_){ return (function (state_17421){ var state_val_17422 = (state_17421[(1)]); if((state_val_17422 === (1))){ var state_17421__$1 = state_17421; return cljs.core.async.impl.ioc_helpers.take_BANG_(state_17421__$1,(2),cancel); } else { if((state_val_17422 === (2))){ var inst_17418 = (state_17421[(2)]); var inst_17419 = jsonp.cancel(req_17428); var state_17421__$1 = (function (){var statearr_17423 = state_17421; (statearr_17423[(7)] = inst_17418); return statearr_17423; })(); return cljs.core.async.impl.ioc_helpers.return_chan(state_17421__$1,inst_17419); } else { return null; } } });})(c__15437__auto___17429,req_17428,channel,jsonp,map__17415,map__17415__$1,request,timeout,callback_name,cancel,keywordize_keys_QMARK_)) ; return ((function (switch__15337__auto__,c__15437__auto___17429,req_17428,channel,jsonp,map__17415,map__17415__$1,request,timeout,callback_name,cancel,keywordize_keys_QMARK_){ return (function() { var cljs_http$core$jsonp_$_state_machine__15338__auto__ = null; var cljs_http$core$jsonp_$_state_machine__15338__auto____0 = (function (){ var statearr_17424 = [null,null,null,null,null,null,null,null]; (statearr_17424[(0)] = cljs_http$core$jsonp_$_state_machine__15338__auto__); (statearr_17424[(1)] = (1)); return statearr_17424; }); var cljs_http$core$jsonp_$_state_machine__15338__auto____1 = (function (state_17421){ while(true){ var ret_value__15339__auto__ = (function (){try{while(true){ var result__15340__auto__ = switch__15337__auto__(state_17421); if(cljs.core.keyword_identical_QMARK_(result__15340__auto__,cljs.core.cst$kw$recur)){ continue; } else { return result__15340__auto__; } break; } }catch (e17425){if((e17425 instanceof Object)){ var ex__15341__auto__ = e17425; var statearr_17426_17430 = state_17421; (statearr_17426_17430[(5)] = ex__15341__auto__); cljs.core.async.impl.ioc_helpers.process_exception(state_17421); return cljs.core.cst$kw$recur; } else { throw e17425; } }})(); if(cljs.core.keyword_identical_QMARK_(ret_value__15339__auto__,cljs.core.cst$kw$recur)){ var G__17431 = state_17421; state_17421 = G__17431; continue; } else { return ret_value__15339__auto__; } break; } }); cljs_http$core$jsonp_$_state_machine__15338__auto__ = function(state_17421){ switch(arguments.length){ case 0: return cljs_http$core$jsonp_$_state_machine__15338__auto____0.call(this); case 1: return cljs_http$core$jsonp_$_state_machine__15338__auto____1.call(this,state_17421); } throw(new Error('Invalid arity: ' + (arguments.length - 1))); }; cljs_http$core$jsonp_$_state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$0 = cljs_http$core$jsonp_$_state_machine__15338__auto____0; cljs_http$core$jsonp_$_state_machine__15338__auto__.cljs$core$IFn$_invoke$arity$1 = cljs_http$core$jsonp_$_state_machine__15338__auto____1; return cljs_http$core$jsonp_$_state_machine__15338__auto__; })() ;})(switch__15337__auto__,c__15437__auto___17429,req_17428,channel,jsonp,map__17415,map__17415__$1,request,timeout,callback_name,cancel,keywordize_keys_QMARK_)) })(); var state__15439__auto__ = (function (){var statearr_17427 = (f__15438__auto__.cljs$core$IFn$_invoke$arity$0 ? f__15438__auto__.cljs$core$IFn$_invoke$arity$0() : f__15438__auto__.call(null)); (statearr_17427[(6)] = c__15437__auto___17429); return statearr_17427; })(); return cljs.core.async.impl.ioc_helpers.run_state_machine_wrapped(state__15439__auto__); });})(c__15437__auto___17429,req_17428,channel,jsonp,map__17415,map__17415__$1,request,timeout,callback_name,cancel,keywordize_keys_QMARK_)) ); } else { } return channel; }); /** * Execute the HTTP request corresponding to the given Ring request * map and return a core.async channel. */ cljs_http.core.request = (function cljs_http$core$request(p__17432){ var map__17433 = p__17432; var map__17433__$1 = ((((!((map__17433 == null)))?((((map__17433.cljs$lang$protocol_mask$partition0$ & (64))) || ((cljs.core.PROTOCOL_SENTINEL === map__17433.cljs$core$ISeq$)))?true:false):false))?cljs.core.apply.cljs$core$IFn$_invoke$arity$2(cljs.core.hash_map,map__17433):map__17433); var request = map__17433__$1; var request_method = cljs.core.get.cljs$core$IFn$_invoke$arity$2(map__17433__$1,cljs.core.cst$kw$request_DASH_method); if(cljs.core._EQ_.cljs$core$IFn$_invoke$arity$2(request_method,cljs.core.cst$kw$jsonp)){ return cljs_http.core.jsonp(request); } else { return cljs_http.core.xhr(request); } }); <file_sep>all: minbuild publish minbuild: lein clean lein cljsbuild once min git commit -am "public update" publish: git subtree push --prefix resources/public/ origin gh-pages <file_sep>// Compiled by ClojureScript 1.9.946 {:static-fns true, :optimize-constants true, :elide-asserts true} goog.provide('cljs.core.async.impl.dispatch'); goog.require('cljs.core'); goog.require('cljs.core.constants'); goog.require('cljs.core.async.impl.buffers'); goog.require('goog.async.nextTick'); cljs.core.async.impl.dispatch.tasks = cljs.core.async.impl.buffers.ring_buffer((32)); cljs.core.async.impl.dispatch.running_QMARK_ = false; cljs.core.async.impl.dispatch.queued_QMARK_ = false; cljs.core.async.impl.dispatch.TASK_BATCH_SIZE = (1024); cljs.core.async.impl.dispatch.process_messages = (function cljs$core$async$impl$dispatch$process_messages(){ cljs.core.async.impl.dispatch.running_QMARK_ = true; cljs.core.async.impl.dispatch.queued_QMARK_ = false; var count_13872 = (0); while(true){ var m_13873 = cljs.core.async.impl.dispatch.tasks.pop(); if((m_13873 == null)){ } else { (m_13873.cljs$core$IFn$_invoke$arity$0 ? m_13873.cljs$core$IFn$_invoke$arity$0() : m_13873.call(null)); if((count_13872 < cljs.core.async.impl.dispatch.TASK_BATCH_SIZE)){ var G__13874 = (count_13872 + (1)); count_13872 = G__13874; continue; } else { } } break; } cljs.core.async.impl.dispatch.running_QMARK_ = false; if((cljs.core.async.impl.dispatch.tasks.length > (0))){ return (cljs.core.async.impl.dispatch.queue_dispatcher.cljs$core$IFn$_invoke$arity$0 ? cljs.core.async.impl.dispatch.queue_dispatcher.cljs$core$IFn$_invoke$arity$0() : cljs.core.async.impl.dispatch.queue_dispatcher.call(null)); } else { return null; } }); cljs.core.async.impl.dispatch.queue_dispatcher = (function cljs$core$async$impl$dispatch$queue_dispatcher(){ if((cljs.core.async.impl.dispatch.queued_QMARK_) && (cljs.core.async.impl.dispatch.running_QMARK_)){ return null; } else { cljs.core.async.impl.dispatch.queued_QMARK_ = true; return goog.async.nextTick(cljs.core.async.impl.dispatch.process_messages); } }); cljs.core.async.impl.dispatch.run = (function cljs$core$async$impl$dispatch$run(f){ cljs.core.async.impl.dispatch.tasks.unbounded_unshift(f); return cljs.core.async.impl.dispatch.queue_dispatcher(); }); cljs.core.async.impl.dispatch.queue_delay = (function cljs$core$async$impl$dispatch$queue_delay(f,delay){ return setTimeout(f,delay); });
9ab0437c57ed3e44b956f05ac17e5dd167adaf27
[ "JavaScript", "Makefile" ]
9
JavaScript
kieranbrowne/rgbtopig
f33c7f96dcbaef7bab45ca4c3ce685f2811b14c7
241d2c0f7db42ee765240d776a5eb07e9ea5e362
refs/heads/master
<file_sep># hdcp_planning ## 1. Introduction We propose an online Hex-Decomposed Coverage Planning (HDCP) algorithm that - guarantees resolution-completeness coverage in unknown, cluttered environments, - includes a variant HDCP-E to trade-off between exploration speed and coverage area, - provides closed-form solutions for planning smooth paths that robots can follow at constant speed. This public repository, organized as a ROS package, offers a complete implementation of the above algorithm. It also provides basic building blocks, such as common operations in hex map and trajectory generation using Dubins paths, which we believe are helpful for future research and development. **Authors:** <NAME>, <NAME>, and <NAME> from [ARCS Lab](https://sites.google.com/view/arcs-lab/) at [UC Riverside](https://www.ucr.edu/). **Videos:** Our presentation at IROS 2020 can be seen [here](https://youtu.be/-Kw2I0kJ-EM). A short 2-min supplementary video can be seen [here](https://youtu.be/T3ZazIgfVw8). **Related Publications:** <NAME>, <NAME>, and <NAME>, "**Online Exploration and Coverage Planning in Unknown Obstacle-Cluttered Environments**", in *IEEE Robotics and Automation Letters*, vol. 5, no. 4, pp. 5969-5976, Oct. 2020 ([paper](https://ieeexplore.ieee.org/abstract/document/9144373), [preprint](https://arxiv.org/abs/2006.16460)) ```latex @article{kan2020online, title={Online Exploration and Coverage Planning in Unknown Obstacle-Cluttered Environments}, author={<NAME> <NAME>}, journal={IEEE Robotics and Automation Letters}, volume={5}, number={4}, pages={5969--5976}, year={2020}, publisher={IEEE} } ``` ## 2. Installation ### 2.1 Prerequisites - Ubuntu 16.04 + ROS Kinetic (or Ubuntu 18.04 + ROS Melodic) - It is possible to run in Ubuntu 18.04, if we [build turtlebot2 from source](https://github.com/UCR-Robotics/Turtlebot2-On-Melodic) or switch to other robots equipped with the same sensors. See the last section for more information. - [turtlebot2n_description](https://github.com/UCR-Robotics/turtlebot2n) - We use a customized turtlebot2 robot, equipped with RPLidar and Astra Pro camera, in both Gazebo simulation and experiments. This is a URDF description package that we developed to be compatible with the hardware. It depends on `turtlebot` meta-package (and `rplidar_ros` package if running hardware). - [obstacle_detector](https://github.com/UCR-Robotics/obstacle_detector) - This is a ROS package that can extract line segments or circular obstacles from 2D laser range data. We forked from the [original package](https://github.com/tysik/obstacle_detector) to maintain consistency. (We thank the author for providing this package.) - [Armadillo library](http://arma.sourceforge.net/) is required by this obstacle detector. We will introduce how to install it in the following section. ### 2.2 Steps We provide a step-by-step installation guideline, including all dependencies. - Please follow ROS Wiki to [install ROS](http://wiki.ros.org/kinetic/Installation/Ubuntu) and [create a ROS workspace](http://wiki.ros.org/catkin/Tutorials/create_a_workspace). In the following, we assume the ROS workspace is at `~/catkin_ws`. - Install `turtlebot` dependencies. Not all of them are required in simulation, but this is a complete list for hardware. (If running in Ubuntu 18, please skip this step and follow the instruction in [this repository](https://github.com/UCR-Robotics/Turtlebot2-On-Melodic) instead to install `turtlebot` dependencies.) ``` sudo apt-get update sudo apt-get upgrade sudo apt-get install ros-kinetic-turtlebot ros-kinetic-turtlebot-apps ros-kinetic-turtlebot-interactions ros-kinetic-turtlebot-simulator sudo apt-get install ros-kinetic-kobuki-ftdi ros-kinetic-ar-track-alvar-msgs ``` - Install Armadillo C++ linear algebra library for obstacle detector. You may use other folders other than `Downloads` as you like. (We provide a backup source in case the original one is expired.) ``` cd ~/Downloads wget http://sourceforge.net/projects/arma/files/armadillo-9.700.2.tar.xz #wget https://github.com/UCR-Robotics/hdcp_planning/raw/armadillo/armadillo-9.700.2.tar.xz tar -xvf armadillo-9.700.2.tar.xz cd armadillo-9.700.2 mkdir build && cd build cmake .. make sudo make install ``` - Git clone and compile ROS packages. ``` cd ~/catkin_ws/src git clone https://github.com/UCR-Robotics/obstacle_detector git clone https://github.com/UCR-Robotics/turtlebot2n git clone https://github.com/UCR-Robotics/hdcp_planning cd ~/catkin_ws catkin_make ``` Note: please double check if `hdcp.py` has executable permission to be run by roslaunch, though this should be already tracked by git. ## 3. Running HDCP ### 3.1 Basic Steps Open three terminals and launch Gazebo simulator, obstacle detector and hdcp planner respectively. ``` roslaunch hdcp_planning gazebo.launch roslaunch hdcp_planning obstacle_detector.launch roslaunch hdcp_planning hdcp_planning.launch ``` Note: sequence does matter. Please wait for the previous one to be completed before launching the new one. ### 3.2 Optional Parameters We offer the following roslaunch parameters to users: - `gazebo.launch` - `x`: robot initial x coordinate (-10 to 10, default 0) - `y`: robot initial y coordinate (-10 to 10, default 0) - `world`: simulation world file (empty, cross, row, random) - `hdcp_planning.launch` - `x`: robot initial x coordinate (-10 to 10, default 0) - `y`: robot initial y coordinate (-10 to 10, default 0) - `hex_radius`: radius or side length of each hexagon (default 1.0m) - `turning_radius`: robot turning radius when following circular trajectory in each hexagon (default 0.5m) - `data_folder`: folder to save hex map and trajectory data (hdcp, hdcp_e or others) - `exploration_mode`: run HDCP-E for fast exploration (true or false) - `debugging_mode`: show more details in visualization (true or false) - `obstacle_threshold`: to remove outlier (avoid false positive) in obstacle detection (recommended 50-200, default 100); use larger threshold for HDCP due to longer staying time in each hex, and smaller threshold for HDCP-E More parameters not exposed to users are optimized internally (e.g., valid sensing range, control point offset, tracking controller param, etc.) ### 3.3 Sample Usage #### run in an uniform environment ``` roslaunch hdcp_planning gazebo.launch world:=cross roslaunch hdcp_planning obstacle_detector.launch roslaunch hdcp_planning hdcp_planning.launch ``` #### spawn the robot at corner ``` roslaunch hdcp_planning gazebo.launch x:=-9 y:=-9 roslaunch hdcp_planning obstacle_detector.launch roslaunch hdcp_planning hdcp_planning.launch x:=-9 y:=-9 ``` #### run HDCP-E (enable exploration mode) ``` roslaunch hdcp_planning gazebo.launch roslaunch hdcp_planning obstacle_detector.launch roslaunch hdcp_planning hdcp_planning.launch exploration_mode:=true data_folder:=hdcp_e ``` ### 3.4 Visualization Only We also provide a python file that can be used offline to visualize previously saved data. ``` roscd hdcp_planning/scripts python plot.py ``` By default, this will show an example set of data in `data/hdcp_e` folder that was captured by running HDCP-E algorithm from initial point [-9, -9] in random environment, with debugging option enabled. ## 4. Code Structure ### 4.1 Pipeline - perception layer - read in point cloud data and register on hexmap - hex and path planning - determine next hex to move according to hexmap - find inner/outer tangent points (start and end points) - trajectory generation - calculate straight-line or circular trajectory - generate waypoints according to sampling period (discretization resolution) - tracking controller - track waypoints according to current robot status - feedback linearization is used for handling non-holonomic kinematics ### 4.2 Files - `scripts` folder - `hdcp.py` has the high-level implementation of the proposed HDCP algorithm, according to Algorithm 1 in our paper. - `turtlebot.py` handles low-level perception, control and planning, while `hexmap.py` provides hex-decomposed map related operations. - `hexcell.py` and `vector2d.py` offer basic data structure used in the development. - `plot.py` shows an example of visualizing previously saved data. - All variables and functions are named explicitly to facilitate understanding. - `models`folder - We use a standard `pine_tree` model provided by Gazebo, and a customized `bare_tree` model provided in `models` folder. In the launch file, we provide `GAZEBO_MODEL_PATH` environment variable pointing to this folder, such that it can be found and loaded in Gazebo simulator. When you launch Gazebo simulation for the first time, it may take some time for Gazebo to download `pine_tree` model from its model library. ## 5. Future Work We acknowledge that some designs are not optimal for now. Future work can include - adding a subclass of HexCell class to include status information (free, occupied, visited, etc.), - using probabilistic update for observed obstacles, - more efficient A* online replanning, - reducing dependencies on turtlebot and supporting other robots. Currently, `turtlebot` meta-package has not been released under ROS Melodic (not able to install by `sudo apt install ros-melodic-turtlebot`), due to deprecated dependencies. It is possible to build from source or switch to other robots with the same configuration. Please follow the instruction in [this repository](https://github.com/UCR-Robotics/Turtlebot2-On-Melodic) to install `turtlebot` in Ubuntu 18. **Our framework is compatible with any other robot (e.g., [ROSbot 2.0](https://store.husarion.com/products/rosbot)) that can provide 2D lidar point cloud and respond to `cmd_vel` (geometry_msgs/Twist) commands.** Though named after turtlebot, the `turtlebot.py` file by itself does not rely on any component in the turtlebot package. Only topic names in subscriber/publisher need to be changed. You are very welcome to contact us or open a new issue in this repository if you have any questions/comments! <file_sep>from math import sqrt, atan2 class Vector2D: def __init__(self, x=0, y=0): self.point = [float(x), float(y)] def __hash__(self): return hash(tuple(self.point)) def __str__(self): return str(self.point) def __repr__(self): return str(self.point) def __eq__(self, other): return self.point == other.point def __abs__(self): return sqrt( (self.x)**2 + (self.y)**2 ) # L-2 norm def __add__(self, other): return Vector2D(self.x + other.x, self.y + other.y) def __sub__(self, other): return Vector2D(self.x - other.x, self.y - other.y) def __mul__(self, scalar): return Vector2D(self.x * scalar, self.y * scalar) def __getitem__(self, idx): return self.point[idx] def __setitem__(self, idx, value): self.point[idx] = value @property def x(self): return self.point[0] @property def y(self): return self.point[1] @property def angle(self): return atan2(self.y, self.x) <file_sep>from math import pi, sqrt, atan2, cos, sin import numpy as np import matplotlib.pyplot as plt import rospy import tf from geometry_msgs.msg import Twist, Pose2D from nav_msgs.msg import Odometry from obstacle_detector.msg import Obstacles, CircleObstacle, SegmentObstacle from vector2d import Vector2D class TurtleBot: def __init__(self, hexmap, turning_radius): self.hexmap = hexmap self.turning_radius = turning_radius # motion planning parameters self.sample_period = 0.1 self.rate = rospy.Rate(1/self.sample_period) self.linear_vel = 1.0 self.angular_vel = self.linear_vel / self.turning_radius self.remaining_time = 0 # within [0, sample_period] self.smooth_start_update_interval = 0.03 # second self.turning_clockwise = False self.turning_clockwise_buffer = False # send velocity commands self.handpoint_offset = 0.2 # meter self.controller_tune_K = 0.3 self.vel = Twist() self.vel_pub = rospy.Publisher('cmd_vel_mux/input/navi', Twist, queue_size=10) # odometry feedback self.logging_counter = 0 self.trajectory = list() self.trajectory_hp = list() self.trajectory_cmd = list() self.pose = Pose2D() self.pose_hp = Pose2D() self.odom_sub = rospy.Subscriber("odom", Odometry, self.odom_callback) # perception # TODO: probabilistic update self.obstacle_list_candidate = dict() self.obstacle_threshold = rospy.get_param("/hdcp_planner/obstacle_threshold", 100) self.valid_sensing_range = self.hexmap.radius * 6 self.obstacle_sub = rospy.Subscriber("raw_obstacles", Obstacles, self.obstacle_callback) def straight_line_trajectory_planning(self, start_point, end_point): direction_vector = end_point - start_point angle = direction_vector.angle total_distance = abs(direction_vector) local_time = self.remaining_time # remaining time is within [0, self.smaple_period] while not rospy.is_shutdown(): current_distance = self.linear_vel * local_time x_ref = start_point[0] + current_distance * cos(angle) y_ref = start_point[1] + current_distance * sin(angle) vx_ref = self.linear_vel * cos(angle) vy_ref = self.linear_vel * sin(angle) self.tracking_controller(x_ref, y_ref, vx_ref, vy_ref) local_time += self.sample_period remaining_distance = total_distance - self.linear_vel * local_time if remaining_distance < 0: self.remaining_time = - remaining_distance/self.linear_vel break if self.remaining_time > self.sample_period or self.remaining_time < 0: rospy.logwarn("line: remaining_time = " + str(self.remaining_time)) rospy.loginfo("local_time = " + str(local_time)) rospy.loginfo("start_point = " + str(start_point) + "; end_point = " + str(end_point)) rospy.loginfo("total_distance = " + str(total_distance) + "; remaining_distance" + str(remaining_distance)) def circle_trajectory_planning(self, start_point, end_point, center): start_angle = atan2(start_point[1]-center[1], start_point[0]-center[0]) angle_difference = self.get_angle_difference(start_point, end_point, center) local_time = self.remaining_time # remaining time is within [0, self.smaple_period] while not rospy.is_shutdown(): if self.turning_clockwise: current_angle = start_angle - self.angular_vel * local_time # from x to x_dot: take derivative wrt local_time x_ref = center[0] + self.turning_radius * cos(current_angle) # x = cx + r*cos(a-vt) y_ref = center[1] + self.turning_radius * sin(current_angle) # y = cy + r*sin(a-vt) vx_ref = self.linear_vel * sin(current_angle) # x_dot = rv*sin(a-vt) # lin_vel = r*ang_vel vy_ref = - self.linear_vel * cos(current_angle) # y_dot = -rv*cos(a-vt) else: current_angle = start_angle + self.angular_vel * local_time # from x to x_dot: take derivative wrt local_time x_ref = center[0] + self.turning_radius * cos(current_angle) # x = cx + r*cos(a+vt) y_ref = center[1] + self.turning_radius * sin(current_angle) # y = cy + r*sin(a+vt) vx_ref = - self.linear_vel * sin(current_angle) # x_dot = -rv*sin(a+vt) # lin_vel = r*ang_vel vy_ref = self.linear_vel * cos(current_angle) # y_dot = rv*cos(a+vt) self.tracking_controller(x_ref, y_ref, vx_ref, vy_ref) local_time += self.sample_period remaining_angle = angle_difference - self.angular_vel * local_time if remaining_angle < 0: self.remaining_time = - remaining_angle/self.angular_vel break if self.remaining_time > self.sample_period or self.remaining_time < 0: rospy.logwarn("circle: remaining_time = " + str(self.remaining_time)) rospy.loginfo("local_time = " + str(local_time) + "; center = " + str(center)) rospy.loginfo("start_point = " + str(start_point) + "; end_point = " + str(end_point)) rospy.loginfo("angle_difference = " + str(angle_difference) + "; remaining_angle" + str(remaining_angle)) def initial_circle_trajectory_planning(self): angle_difference = 2*pi factor = 0 current_angle = 0 while not rospy.is_shutdown(): factor = factor + self.smooth_start_update_interval linear_vel = self.linear_vel * min(factor, 1) angular_vel = self.angular_vel * min(factor, 1) current_angle = current_angle + angular_vel * self.sample_period x_ref = self.turning_radius * cos(current_angle) y_ref = self.turning_radius * sin(current_angle) vx_ref = - linear_vel * sin(current_angle) vy_ref = linear_vel * cos(current_angle) self.tracking_controller(x_ref, y_ref, vx_ref, vy_ref) remaining_angle = angle_difference - current_angle if remaining_angle < 0: self.remaining_time = - remaining_angle/self.angular_vel break def get_angle_difference(self, start_point, end_point, center): # compute CCW angle difference between two points on circumference start_angle = atan2(start_point[1]-center[1], start_point[0]-center[0]) end_angle = atan2(end_point[1]-center[1], end_point[0]-center[0]) angle_difference = end_angle - start_angle if angle_difference <= 0: # make sure value is within (0, 2pi] angle_difference += 2*pi # switch to CW angle difference if needed if self.turning_clockwise and angle_difference != 2*pi: # 2*pi means we will turn full circle angle_difference = 2*pi - angle_difference return angle_difference def find_tangent_points(self, current_hex, next_hex, init_point): current_hex_center = self.hexmap.cube_to_cat(current_hex) outer_start, outer_end = self.outer_tangent_points(current_hex, next_hex) inner_start, inner_end = self.inner_tangent_points(current_hex, next_hex) outer_diff = self.get_angle_difference(init_point, outer_start, current_hex_center) inner_diff = self.get_angle_difference(init_point, inner_start, current_hex_center) if inner_diff < outer_diff: self.turning_clockwise_buffer = not self.turning_clockwise return inner_start, inner_end else: self.turning_clockwise_buffer = self.turning_clockwise return outer_start, outer_end def inner_tangent_points(self, current_hex, target_hex): current_center = self.hexmap.cube_to_cat(current_hex) target_center = self.hexmap.cube_to_cat(target_hex) ai = current_center[0] bi = current_center[1] aj = target_center[0] bj = target_center[1] w = (aj-ai)**2 + (bj-bi)**2 rt = self.turning_radius rt2 = rt**2 if self.turning_clockwise: xi = ai + (2*rt2*(aj-ai) - rt*(bj-bi)*sqrt(w-4*rt2))/w # minus sign for CW yi = bi + (2*rt2*(bj-bi) - rt*(ai-aj)*sqrt(w-4*rt2))/w xj = aj + (2*rt2*(ai-aj) - rt*(bi-bj)*sqrt(w-4*rt2))/w yj = bj + (2*rt2*(bi-bj) - rt*(aj-ai)*sqrt(w-4*rt2))/w else: xi = ai + (2*rt2*(aj-ai) + rt*(bj-bi)*sqrt(w-4*rt2))/w # plus sign for CCW yi = bi + (2*rt2*(bj-bi) + rt*(ai-aj)*sqrt(w-4*rt2))/w xj = aj + (2*rt2*(ai-aj) + rt*(bi-bj)*sqrt(w-4*rt2))/w yj = bj + (2*rt2*(bi-bj) + rt*(aj-ai)*sqrt(w-4*rt2))/w return Vector2D(xi, yi), Vector2D(xj, yj) # start_point, end_point def outer_tangent_points(self, current_hex, target_hex): current_center = self.hexmap.cube_to_cat(current_hex) target_center = self.hexmap.cube_to_cat(target_hex) ai = current_center[0] bi = current_center[1] aj = target_center[0] bj = target_center[1] w = (aj-ai)**2 + (bj-bi)**2 rt = self.turning_radius if self.turning_clockwise: xi = ai + rt*(bi-bj)/sqrt(w) # plus sign for CW yi = bi + rt*(aj-ai)/sqrt(w) xj = aj + rt*(bi-bj)/sqrt(w) yj = bj + rt*(aj-ai)/sqrt(w) else: xi = ai - rt*(bi-bj)/sqrt(w) # minus sign for CCW yi = bi - rt*(aj-ai)/sqrt(w) xj = aj - rt*(bi-bj)/sqrt(w) yj = bj - rt*(aj-ai)/sqrt(w) return Vector2D(xi, yi), Vector2D(xj, yj) # start_point, end_point def tracking_controller(self, x_ref, y_ref, vx_ref, vy_ref): ''' tracking controller design vx = xh_d_dot - K * (xh - xh_d) => xh --> xh_d vy = yh_d_dot - K * (yh - yh_d) => yh --> yh_d ''' self.trajectory_cmd.append([x_ref, y_ref]) K = self.controller_tune_K # controller parameter ux = vx_ref - K * (self.pose_hp.x - x_ref) uy = vy_ref - K * (self.pose_hp.y - y_ref) vel_hp = [ux, uy] self.pub_vel_hp(vel_hp) def pub_vel_hp(self, vel_hp): ''' matrix transform [ v ] 1 [ L*cos0 L*sin0 ] [ x ] [ ] = --- * [ ] * [ ] [ w ] L [ -sin0 cos0 ] [ y ] ''' x = vel_hp[0] y = vel_hp[1] theta = self.pose_hp.theta v = x*cos(theta) + y*sin(theta) w = (x*(-sin(theta)) + y*cos(theta))/self.handpoint_offset rospy.logdebug("vel: theta=" + str(theta) + "; x=" + str(x) +\ "; y=" + str(y) + "; v=" + str(v) + "; w=" + str(w)) self.vel.linear.x = v self.vel.angular.z = w self.vel_pub.publish(self.vel) self.rate.sleep() def odom_callback(self, msg): # get (x, y, theta) specification from odometry topic quarternion = [msg.pose.pose.orientation.x,msg.pose.pose.orientation.y,\ msg.pose.pose.orientation.z, msg.pose.pose.orientation.w] (_, _, yaw) = tf.transformations.euler_from_quaternion(quarternion) self.pose.theta = yaw self.pose.x = msg.pose.pose.position.x self.pose.y = msg.pose.pose.position.y self.pose_hp.theta = yaw self.pose_hp.x = self.pose.x + self.handpoint_offset * cos(yaw) self.pose_hp.y = self.pose.y + self.handpoint_offset * sin(yaw) # reduce the number of saved messages to 1/10 self.logging_counter += 1 if self.logging_counter == 10: self.logging_counter = 0 self.trajectory.append([self.pose.x, self.pose.y, self.pose.theta]) self.trajectory_hp.append([self.pose_hp.x, self.pose_hp.y, self.pose_hp.theta]) rospy.logdebug("odom: x=" + str(self.pose.x) +\ "; y=" + str(self.pose.y) + "; theta=" + str(yaw)) rospy.logdebug("odom_hp: x_hp=" + str(self.pose_hp.x) +\ "; y_hp=" + str(self.pose_hp.y) + "; theta=" + str(yaw)) def valid_sensing(self, point): return abs(point - Vector2D(self.pose.x, self.pose.y)) < self.valid_sensing_range def obstacle_callback(self, msg): # sampling points on the obstacles points = list() for circle in msg.circles: center = Vector2D(circle.center.x, circle.center.y) points.append(center) r = circle.true_radius if r > 0: for theta in np.arange(0, 2*pi, 0.3): radius = Vector2D(r*cos(theta), r*sin(theta)) points.append(center + radius) for segment in msg.segments: line = Vector2D(segment.last_point.x - segment.first_point.x, \ segment.last_point.y - segment.first_point.y) interval = 0 while abs(line) - interval > 0: cx = segment.first_point.x + interval * cos(line.angle) cy = segment.first_point.y + interval * sin(line.angle) points.append(Vector2D(cx, cy)) interval += 0.2 for p in points: if self.valid_sensing(p): p_hex = self.hexmap.cat_to_cube(p) if p_hex not in self.obstacle_list_candidate: self.obstacle_list_candidate[p_hex] = 1 else: self.obstacle_list_candidate[p_hex] += 1 for candidate, times in self.obstacle_list_candidate.items(): #TODO: probabilistic update if times > self.obstacle_threshold and not self.hexmap.is_explored(candidate): self.hexmap.add_obstacle(candidate) def save_and_plot_trajectory(self, directory, debugging_mode=False): if not isinstance(directory, str): raise TypeError("please specify the directory using string type") trajectory = np.array(self.trajectory) trajectory_hp = np.array(self.trajectory_hp) trajectory_cmd = np.array(self.trajectory_cmd) np.savetxt(directory + "/trajectory.csv", trajectory, fmt='%f', delimiter=',') np.savetxt(directory + "/trajectory_hp.csv", trajectory_hp, fmt='%f', delimiter=',') np.savetxt(directory + "/trajectory_cmd.csv", trajectory_cmd, fmt='%f', delimiter=',') if debugging_mode: plt.plot(trajectory[:, 0], trajectory[:, 1]) plt.plot(trajectory_hp[:, 0], trajectory_hp[:, 1]) plt.plot(trajectory_cmd[:, 0], trajectory_cmd[:, 1]) else: plt.plot(trajectory[:, 0], trajectory[:, 1]) @staticmethod def load_and_plot_trajectory(directory, debugging_mode=False): if not isinstance(directory, str): raise TypeError("please specify the directory using string type") if debugging_mode: trajectory = np.loadtxt(directory + "/trajectory.csv", delimiter=',') trajectory_hp = np.loadtxt(directory + "/trajectory_hp.csv", delimiter=',') trajectory_cmd = np.loadtxt(directory + "/trajectory_cmd.csv", delimiter=',') plt.plot(trajectory[:, 0], trajectory[:, 1]) plt.plot(trajectory_hp[:, 0], trajectory_hp[:, 1]) plt.plot(trajectory_cmd[:, 0], trajectory_cmd[:, 1]) else: trajectory = np.loadtxt(directory + "/trajectory.csv", delimiter=',') plt.plot(trajectory[:, 0], trajectory[:, 1]) <file_sep>#!/usr/bin/env python from math import pi, sqrt, atan2, cos, sin import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as mpatches import rospy from vector2d import Vector2D from hexcell import HexCell from hexmap import HexMap from turtlebot import TurtleBot ''' ## HDCP Algorithm ## - this file features the high-level implementation of the proposed HDCP algorithm, according to Algorithm 1 in our paper. - "turtlebot.py" handles low-level perception, control and planning, while "hexmap.py" provides hex-decomposed map related operations. - variables and functions are named explicitly to facilitate understanding. ## Pipeline ## - perception layer - read in point cloud data and register on hexmap - hex and path planning - determine next hex to move according to hexmap - find inner/outer tangent points (start and end points) - trajectory generation - calculate straight-line or circular trajectory - generate waypoints according to sampling period (discretization resolution) - tracking controller - track waypoints according to current robot status - feedback linearization is used for handling non-holonomic kinematics ''' class HexDecompositionCoveragePlanning: def __init__(self): # read in ros params rospy.init_node('hdcp_planner') hex_radius = rospy.get_param("/hdcp_planner/hex_radius", 1.0) robot_turning_radius = rospy.get_param("/hdcp_planner/robot_turning_radius", 0.5) init_x = rospy.get_param("/hdcp_planner/x", 0) init_y = rospy.get_param("/hdcp_planner/y", 0) data_path = rospy.get_param("/hdcp_planner/data_path") exploration_mode = rospy.get_param("/hdcp_planner/exploration_mode", False) debugging_mode = rospy.get_param("/hdcp_planner/debugging_mode", False) # motion planning parameters self.R_hex = float(hex_radius) # hex radius equals to the side length self.R_traj = float(robot_turning_radius) # radius of circular trajectory that robot follows self.exploration_mode = exploration_mode # whether to run the variant HDCP-E algorithm # initialize hex map and robot interface self.hexmap = HexMap(self.R_hex) self.robot = TurtleBot(self.hexmap, self.R_traj) # TODO # let's go try: self.run() except rospy.ROSInterruptException as error: print(error) finally: self.visualization(data_path, [init_x, init_y], debugging_mode) def run(self): init_point = Vector2D(self.R_traj, 0) current_hex = HexCell(0, 0, 0) # in cube coordinate current_hex_center = Vector2D(0.0, 0.0) # in cartesian coordiante self.robot.initial_circle_trajectory_planning() self.hexmap.add_visited(current_hex) while not rospy.is_shutdown(): if not self.hexmap.is_visited(current_hex): # observing mode if not self.exploration_mode: self.robot.circle_trajectory_planning(init_point, init_point, current_hex_center) # full circle self.hexmap.add_visited(current_hex) self.hexmap.update_obstacles() next_hex = self.next_hex(current_hex) if self.hexmap.coverage_completed is True: # could go back to the origin, but just stop here for now self.robot.pub_vel_hp([0, 0]) break start_point, end_point = self.robot.find_tangent_points(current_hex, next_hex, init_point) # inner and outer if abs(init_point - start_point)>0.01: # transitioning mode self.robot.circle_trajectory_planning(init_point, start_point, current_hex_center) self.robot.turning_clockwise = self.robot.turning_clockwise_buffer self.robot.straight_line_trajectory_planning(start_point, end_point) # transitioning mode current_hex = next_hex current_hex_center = self.hexmap.cube_to_cat(next_hex) init_point = end_point def next_hex(self, current_hex): # find an unexplored hex that has the maximum number of explored neighbors candidate = self.hexmap.get_hex_from_neighbor(current_hex) # eq(1) in paper # if not empty if candidate: return candidate # all neighbors have been explored else: target_hex = self.hexmap.get_hex_from_history(current_hex) # eq(2) in paper list_of_hex = self.hexmap.get_path_from_A_star(current_hex, target_hex) return list_of_hex[0] # the closest one def visualization(self, directory, center, debugging_mode): # plot trajectory once finished _, ax = plt.subplots(1) ax.set_aspect('equal') # map boundary X_min = -10 - center[0] X_max = 10 - center[0] Y_min = -10 - center[1] Y_max = 10 - center[1] # save and plot hex map self.hexmap.save_map(directory) self.hexmap.plot_map(ax, debugging_mode=debugging_mode) # save and plot trajectory self.robot.save_and_plot_trajectory(directory, debugging_mode) plt.xlim(X_min - 1, X_max + 1) plt.ylim(Y_min - 1, Y_max + 1) plt.show() if __name__ == '__main__': whatever = HexDecompositionCoveragePlanning() <file_sep> class HexCell: def __init__(self, x=0, y=0, z=0): if x + y + z !=0: raise TypeError("Hex cell must meet x+y+z=0 requirement") self.cube = (int(x), int(y), int(z)) def __hash__(self): return hash(self.cube) def __str__(self): return str(self.cube) def __repr__(self): return str(self.cube) def __eq__(self, other): return self.x == other.x and self.y == other.y and self.z == other.z def __abs__(self): return max(abs(self.x), abs(self.y), abs(self.z)) # cube distance def __add__(self, other): return HexCell(self.x+other.x, self.y+other.y, self.z+other.z) def __sub__(self, other): return HexCell(self.x-other.x, self.y-other.y, self.z-other.z) def __mul__(self, scalar): # [i*scalar for i in self.cube] return HexCell(self.x*scalar, self.y*scalar, self.z*scalar) def __getitem__(self, idx): return self.cube[idx] @property def x(self): return self.cube[0] @property def y(self): return self.cube[1] @property def z(self): return self.cube[2] ''' TODO: add more features in subclass class ColorHexCell(HexCell): property: - self.status or self.color light green: visited dark green: visited twice or more light yellow: visitable (free space) light red: unvisitable/obstacle light grey: unknown - may use dictionary/hashing to improve indexing speed function: - self.boundary() returns boundary hex cube coordiantes - self.update_cells() updates cell status ''' <file_sep>#!/usr/bin/env python import matplotlib.pyplot as plt from hexmap import HexMap from turtlebot import TurtleBot def visualization(directory, center, debugging_mode): # plot trajectory once finished _, ax = plt.subplots(1) ax.set_aspect('equal') # map boundary X_min = -10 - center[0] X_max = 10 - center[0] Y_min = -10 - center[1] Y_max = 10 - center[1] # load and plot hex map hexmap = HexMap(radius=1.0) hexmap.plot_map(ax, directory, debugging_mode) # load and plot trajectory TurtleBot.load_and_plot_trajectory(directory, debugging_mode) plt.xlim(X_min - 1, X_max + 1) plt.ylim(Y_min - 1, Y_max + 1) plt.show() if __name__ == '__main__': directory = "../data/hdcp_e" robot_init_coordinate = [-9, -9] debugging_mode = True visualization(directory, robot_init_coordinate, debugging_mode) <file_sep>from math import pi, sqrt, atan2, cos, sin import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as mpatches from vector2d import Vector2D from hexcell import HexCell class HexMap: def __init__(self, radius=1.0): self.coverage_completed = False self.radius = radius self.visited_list = list() self.obstacle_list = list() self.neighbor_ordering = [HexCell(0,-1, 1), HexCell(1, -1, 0), HexCell(1, 0, -1), # S, SE, NE HexCell(0, 1,-1), HexCell(-1, 1, 0), HexCell(-1, 0, 1)] # N, NW, SW def is_visited(self, hexcell): return hexcell in self.visited_list def is_obstacle(self, hexcell): return hexcell in self.obstacle_list def is_explored(self, hexcell): return hexcell in self.visited_list or hexcell in self.obstacle_list def neighbors(self, hexcell): # hexcell addition is defined in the HexCell class return [hexcell + i for i in self.neighbor_ordering] def visited_neighbors(self, hexcell): return [i for i in self.neighbors(hexcell) if i in self.visited_list] def obstacle_neighbors(self, hexcell): return [i for i in self.neighbors(hexcell) if i in self.obstacle_list] def explored_neighbors(self, hexcell): return [i for i in self.neighbors(hexcell) if i in self.visited_list or i in self.obstacle_list] def unexplored_neighbors(self, hexcell): return [i for i in self.neighbors(hexcell) if i not in self.visited_list and i not in self.obstacle_list] def number_of_explored_neighbors(self, hexcell): # TODO: each hex should have its own property return len(self.explored_neighbors(hexcell)) # (visitable or not) defined in HexCell class def add_visited(self, hexcell): self.visited_list.append(hexcell) def add_obstacle(self, hexcell): self.obstacle_list.append(hexcell) def update_obstacles(self): self.obstacle_list = [i for i in self.obstacle_list if i not in self.visited_list] def hex_distance(self, hex1, hex2): return abs(hex1-hex2) def range_hex(self, current_hex, h=1): # h is the searching range; h=1 is the same as self.neighbors hex_list = list() for a in range(-h, h+1): for b in range(max(-h, -a-h), min(h, -a+h)+1): candidate = HexCell(current_hex[0]+a, current_hex[1]+b, current_hex[2]-a-b) if self.hex_distance(candidate, current_hex) == h: hex_list.append(candidate) return hex_list def cat_to_cube(self, cat): # convert from cartesian coordinate to cube coodinate x = 2 * cat.x / (3*self.radius) y = (-cat.x + sqrt(3)*cat.y) / (3*self.radius) z = (-cat.x - sqrt(3)*cat.y) / (3*self.radius) cube = [round(x), round(y), round(z)] diff = [abs(cube[0]-x), abs(cube[1]-y), abs(cube[2]-z)] if diff[0] > diff[1] and diff[0] > diff[2]: cube[0] = - cube[1] - cube[2] elif diff[1] > diff[2]: cube[1] = - cube[0] - cube[2] else: cube[2] = - cube[0] - cube[1] return HexCell(cube[0], cube[1], cube[2]) def cube_to_cat(self, cube): # convert from cube coordinate to cartesian coodinate # project cube y and z onto cat y, where cube coordiante has a constraint x + y + z = 0 return Vector2D(cube.x * 1.5 * self.radius, (cube.y-cube.z) * sqrt(3)/2 * self.radius) def get_hex_from_neighbor(self, hexcell): # find an unexplored hex that has the maximum number of explored neighbors candidate = self.unexplored_neighbors(hexcell) number = [self.number_of_explored_neighbors(i) for i in candidate] if number: # not empty return candidate[number.index(max(number))] else: return [] def get_hex_from_history(self, hexcell): # find the first available hex whose neighbors have not been fully explored for idx, candidate in reversed(list(enumerate(self.visited_list))): num = self.number_of_explored_neighbors(candidate) if num < 6: return candidate # idx and candidate keep the last value after for loop if idx == 0 and num == 6: # meaning all neighbors of the origin have been explored self.coverage_completed = True return candidate # should be (0,0,0) else: raise ValueError("get_hex is not working properly") def get_path_from_A_star(self, start, goal): open_list = [] open_list.append((0, start)) parent = {} # parent is not closed_list parent[start] = None # we skipped closed_list in this implementation past_cost = {} past_cost[start] = 0 if goal in self.obstacle_list: raise ValueError("the goal is not reachable in A*") # expand open list while open_list: open_list.sort() current = open_list.pop(0)[1] if current == goal: break for candidate in self.neighbors(current): if candidate in self.obstacle_list: continue new_cost = past_cost[current] + 1 # constant cost = 1 if candidate not in past_cost or new_cost < past_cost[candidate]: past_cost[candidate] = new_cost heuristic = self.hex_distance(candidate, goal) open_list.append((new_cost + heuristic, candidate)) parent[candidate] = current # construct the path backward path = [] while current != start: path.append(current) current = parent[current] path.reverse() print("A* path: " + str(start) + " " + str(path)) return path def save_map(self, directory): if not isinstance(directory, str): raise TypeError("please specify the directory using string type") obstacle = np.array([list(i.cube) for i in self.obstacle_list]) np.savetxt(directory + "/obstacle.csv", obstacle, fmt='%f', delimiter=',') visited = np.array([list(i.cube) for i in self.visited_list]) np.savetxt(directory + '/visited.csv', visited, fmt='%f', delimiter=',') def plot_map(self, ax, directory=None, debugging_mode=False): if directory: if not isinstance(directory, str): raise TypeError("please specify the directory using string type") obstacle_list = np.loadtxt(directory + "/obstacle.csv", delimiter=',') visited_list = np.loadtxt(directory + "/visited.csv", delimiter=',') else: obstacle_list = self.obstacle_list visited_list = self.visited_list for obstacle in obstacle_list: obstacle = HexCell(obstacle[0], obstacle[1], obstacle[2]) self.plot_hexagon(ax, self.cube_to_cat(obstacle), 'red', ' ') for (idx, visited) in enumerate(visited_list, 1): visited = HexCell(visited[0], visited[1], visited[2]) if debugging_mode: self.plot_hexagon(ax, self.cube_to_cat(visited), 'green', str(idx)) else: self.plot_hexagon(ax, self.cube_to_cat(visited), 'white', ' ') def plot_hexagon(self, ax, center, color, label): # color in lower case words xy = tuple(center) hexagon = mpatches.RegularPolygon(xy, numVertices=6, radius=self.radius, orientation=np.radians(30), facecolor=color, alpha=0.2, edgecolor='k') ax.add_patch(hexagon) ax.text(center[0], center[1], label, ha='center', va='center', size=10)
440f78515c49a8ec5fad80a1973b614503c0405b
[ "Markdown", "Python" ]
7
Markdown
afaroo01/hdcp_planning
6664d59a478aced5e5e8109fde2cc6e589dd0ec3
b668bad2138ba8c623d9f6094fd834a66a127bbf
refs/heads/master
<file_sep>// // DebugView.swift // import UIKit class DebugView: UIView { private let imageView = UIImageView() func setImage(_ image: UIImage) { imageView.image = image } override init(frame: CGRect) { super.init(frame: frame) imageView.contentMode = .scaleAspectFit imageView.translatesAutoresizingMaskIntoConstraints = false addSubview(imageView) let constraints = [ imageView.topAnchor.constraint(equalTo: topAnchor), imageView.leadingAnchor.constraint(equalTo: leadingAnchor), imageView.trailingAnchor.constraint(equalTo: trailingAnchor), imageView.bottomAnchor.constraint(equalTo: bottomAnchor) ] NSLayoutConstraint.activate(constraints) backgroundColor = .red } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
339e9b8060d87173ca1faa2600b10efb0c493675
[ "Swift" ]
1
Swift
ObservantLabs/examples
0c95cc2201245728d32a44ccd33cd5daad17ae25
909bf026c5507826fcc89e63eb766471b00010cb
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, FormGroupDirective, Validators } from '@angular/forms' import { Router } from '@angular/router'; import { CommonService } from 'src/app/services/common.service'; import { Login } from 'src/app/types/loginDto'; import { AuthService } from '../auth.service'; @Component({ selector: 'app-logIn', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { loginForm: FormGroup = new FormGroup({ 'username': new FormControl(null, [Validators.required]), 'password': new FormControl(null, [Validators.required]) }) constructor(private router: Router, private auth: AuthService, private _commonService: CommonService) { } ngOnInit() { } async onSubmit(formData: FormGroup) { try { const loginPayload = formData.value as Login; const response: any = await this.auth.loginUser(loginPayload); localStorage.setItem("token", response.token); this.router.navigate(["home"]); } catch (error) { this._commonService.openSnackBar(error.error.message); } } checkValidation(input: string) { const validation = this.loginForm.get(input)?.invalid && (this.loginForm.get(input)?.dirty || this.loginForm.get(input)?.touched) return validation; } OnRegistrationClick() { this.router.navigate(['sign-up']) } } <file_sep>import { HttpClient, HttpClientModule, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { environment } from 'src/environments/environment'; @Injectable({ providedIn: 'root' }) export class HttpService { constructor(private httpClient: HttpClient) {} get(url: string, headers: HttpHeaders = new HttpHeaders()): Promise<any> { return this.httpClient.get(environment.baseUrl + url, { headers: headers }).toPromise(); } post(url: string, payload: any, headers: HttpHeaders = new HttpHeaders()): Promise<any> { headers.set('content-type', 'application/json'); return this.httpClient.post(environment.baseUrl + url, payload, { headers: headers }).toPromise(); } put(url: string, payload: any, headers: HttpHeaders): Promise<any> { return this.httpClient.put(environment.baseUrl + url, payload, { headers: headers }).toPromise(); } } <file_sep>version: '3' services: web: # Path to dockerfile. # '.' represents the current directory in which # docker-compose.yml is present. build: context: . dockerfile: ./images/Dockerfile # Mapping of container port to host ports: - "5200:5200" - "4200:4200" # Mount volume volumes: - .:/var/www/app<file_sep>FROM node:12-alpine WORKDIR /var/www/app EXPOSE 4200 COPY package.json package-lock.json ./ RUN npm ci COPY . . CMD ["npm", "run", "start"]<file_sep>import { Injectable } from '@angular/core'; import { MatSnackBar } from '@angular/material/snack-bar'; @Injectable({ providedIn: 'root' }) export class CommonService { constructor(private _matSnackBar: MatSnackBar) { } openSnackBar(message: string, action: string = "OK", duration: number = 3000): void { this._matSnackBar.open(message, action, { duration }); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { FormControl, FormGroup, FormGroupDirective, Validators } from '@angular/forms'; import { CommonService } from 'src/app/services/common.service'; import { AuthService } from '../auth.service'; @Component({ selector: 'app-signup', templateUrl: './signup.component.html', styleUrls: ['./signup.component.css'] }) export class SignupComponent implements OnInit { constructor(private auth: AuthService, private _commonService: CommonService) { } emailregex: RegExp = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ registerForm: FormGroup = new FormGroup( { 'username': new FormControl(null, [Validators.required]), 'email': new FormControl(null, [Validators.required, Validators.pattern(this.emailregex)]), 'firstname': new FormControl(null, [Validators.required]), 'lastname': new FormControl(null, [Validators.required]), 'phoneNo': new FormControl(null, [Validators.required]), 'password': new FormControl(null, [Validators.required, this.checkPassword]), 'role': new FormControl(null, [Validators.required]), } ); fieldRequired: string = "This field is required" roles: Array<{ name: String, label: String, }> = [ { label: "Admin", name: "ROLE_ADMIN", }, { label: "Student", name: "ROLE_STUDENT", } ]; ngOnInit() { } emaiErrors() { return this.registerForm.get('email')?.hasError('required') ? 'This field is required' : this.registerForm.get('email')?.hasError('pattern') ? 'Not a valid emailaddress' : '' } checkPassword(control: FormControl) { let enteredPassword = control.value let passwordCheck = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{6,})/; return (!passwordCheck.test(enteredPassword) && enteredPassword) ? { 'requirements': true } : null; } getErrorPassword() { return this.registerForm.get('password')?.hasError('required') ? 'This field is required (The password must be at least six characters, one uppercase letter and one number)' : this.registerForm.get('password')?.hasError('requirements') ? 'Password needs to be at least six characters, one uppercase letter and one number' : ''; } checkValidation(input: string) { const validation = this.registerForm.get(input)?.invalid && (this.registerForm.get(input)?.dirty || this.registerForm.get(input)?.touched) return validation; } async onSubmit(formData: FormGroup, formDirective: FormGroupDirective) { try { await this.auth.registerUser(formData.value) } catch (error) { this._commonService.openSnackBar(error.error.message); } } } <file_sep>import { Injectable } from '@angular/core'; import { HttpService } from 'src/app/services/http.service'; @Injectable() export class HomeService { constructor(private _http: HttpService) { } getStudents() { return this._http.get("/api/students"); } } <file_sep>import { Injectable } from '@angular/core'; import { HttpService } from 'src/app/services/http.service'; import { Login } from 'src/app/types/loginDto'; import { Signup } from 'src/app/types/signup'; @Injectable() export class AuthService { constructor(private httpService: HttpService) { } registerUser(payload: Signup): Promise<any> { return this.httpService.post('/signup', payload) } loginUser(payload: Login): Promise<any> { return this.httpService.post("/authenticate", payload); } }
04bdd9ac4f529916d7e77545edc289b0b7d4694c
[ "TypeScript", "YAML", "Dockerfile" ]
8
TypeScript
neeraj00890/Job-Alert-UI
8440655798e05ee8ef5b2133a2292fb374d44e38
310cf61e3f212640efdaeea9d2e1f380caefc37c
refs/heads/master
<file_sep>$.fn.easyTimer=function(){ $(this).html("UNDER DEVELOPMENT"); }
281da5b5271c2b047fb1f6503a3c1b8666c8b3f1
[ "JavaScript" ]
1
JavaScript
kukko/easyTimer
51801e1b97fada96f9791f83fe3b4830203aabb4
90c99eda94046bfe6d41e6d066e354d9a7fd0b03
refs/heads/main
<file_sep><?php namespace App\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Annotation\Route; use App\Entity\Upload; use App\Form\UploadType; use Symfony\Flex\Response; class HomeController extends AbstractController { /** * @Route("/home", name="home") */ public function HomeController(Request $request) { $upload =new Upload(); $form = $this->createForm(UploadType::class, $upload); //traitement du formulaire $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()){ $files = $upload->getNames(); //récupération du fichier $fileName0 = $files[0]->getClientOriginalName(); // définition d'un nouveau nom de fichier $fileName1 = $files[1]->getClientOriginalName(); $files[0]->move($this->getParameter('upload_directory'), $fileName0); //recupération du paramètre $files[1]->move($this->getParameter('upload_directory'), $fileName1); $upload->setNames(($fileName0)); $upload->setNames(($fileName1)); return $this->redirectToRoute('home');//redirection sur le home } return $this->render('home/index.html.twig', [ 'form' => $form->createView(), ]); } /** * @Route("/home/new") */ public function new(MessageGenerator $messageGenerator): Response{ $message = $messageGenerator->getMessage(); $this->addFlash('success', $message); } } <file_sep>-- phpMyAdmin SQL Dump -- version 5.1.1 -- https://www.phpmyadmin.net/ -- -- Hôte : 127.0.0.1 -- Généré le : dim. 31 oct. 2021 à 21:06 -- Version du serveur : 10.4.20-MariaDB -- Version de PHP : 8.0.9 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de données : `vetux_line` -- -- -------------------------------------------------------- -- -- Structure de la table `utilisateur` -- CREATE TABLE `utilisateur` ( `id` int(11) NOT NULL, `username` varchar(180) COLLATE utf8mb4_unicode_ci NOT NULL, `roles` longtext COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '(DC2Type:json)', `password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Déchargement des données de la table `utilisateur` -- INSERT INTO `utilisateur` (`id`, `username`, `roles`, `password`) VALUES (1, 'eva', '[\"ROLE_ADMIN\"]', <PASSWORD>'), (2, 'Laura', '[\"ROLE_USER\"]', '$2y$13$IqCr0xDwlRLiCJG2rgiAz.OEc27MsOSk17aId8p7uEG.okT.7CuOW'); -- -- Index pour les tables déchargées -- -- -- Index pour la table `utilisateur` -- ALTER TABLE `utilisateur` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `UNIQ_1D1C63B3F85E0677` (`username`); -- -- AUTO_INCREMENT pour les tables déchargées -- -- -- AUTO_INCREMENT pour la table `utilisateur` -- ALTER TABLE `utilisateur` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep><?php namespace App\Controller; use PHPUnit\Exception; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; class FusionController extends AbstractController { /** * @Route("/fusion", name="fusion") */ public function index() { //ouverture du dossier à partir d'un chemin de fichier en lecture seul grace au mode "r" $csv = fopen('../public/uploads/small-french-client.csv', 'r'); $csv1 = fopen('../public/uploads/small-german-client.csv', 'r'); //création et ouverture du fichier grace au mode "x" $fusion=fopen('../public/fusion/french-german-client.csv','x' ); $liste=array(); // si le fichier a été ouvert, il analyse la ligne qu'il lit et // recherche les champs CSV, qu'il va retourner dans un tableau "$liste" // les contenant. if($csv) { $ligne = fgetcsv($csv, 1000, ","); if ($csv1) { $ligne1 = fgetcsv($csv1, 1000, ","); $ligne1 = fgetcsv($csv1, 1000, ","); //fusion séquentielle while ($ligne) { $liste[] = $ligne; $ligne = fgetcsv($csv, 1000, ","); } while ($ligne1) { $liste[] = $ligne1; $ligne1 = fgetcsv($csv1, 1000, ","); } fclose($csv); //fermeture de fichier qui est représenter par le pointeur fclose($csv1); } else{ echo"Ouverture impossible"; } } else{ echo"Ouverture impossible"; } foreach ($liste as $fields){ fputcsv($fusion, $fields); } fclose($fusion); dump($liste); exit; /* $colonne= ["Gender","Title","NameSet","GivenName","EmailAddress","Birthday","TelephoneNumber","CCType","CCNumber","CVV2","CCExpires","Vehicle","UPS", "StreetAdress","FeetInches","Kilograms"]; */ } } <file_sep># Guess What Prise en main de la POO avec PHP Niveau : Deuxième année de BTS SIO SLAM Prérequis : bases de la programmation, PHP 7 ou supérieur installé sur votre machine de dev. ## Objectif Ce projet a pour but de développer une application métier pour l'entreprise VETUX-LINE. Cette application doit lui permettre de fusionner 2 fichiers csv en un fichier unique. ## Première partie: ### Création de la Base de donnée J'ai créé la base de données avec phpMyAdmin pour le projet. Pour cela j'ai réduit la taille des deux fichiers csv comme demandé. J'obtient donc deux tables que je vais utiliser .Si javais utiliser les fichiers complets (2000 et 3000 lignes), il suffira d’augmenter la taille maximale de fichiers sur la DDB. Mais pour rendre les tests plus simples et compréhensifs, j'utilise les petits fichiers. ### Upload de fichier: Premièrement, pour pouvoir faire le upload de fichier, j'ai créé un formulaire qui va contenir un input de fichiers pour uploader des fichiers csv par exemple. Se formulaire permet de selectionner deux fichiers en même temps. * j'ai créé un entité "upload" dans lequel y a le champ "name" ```php class Upload { /* nom du fichier */ private $names; public function getNames() { return $this->names; } public function setNames($names) { $this->names= $names; return $this; } public function addNames($name) { $this->names[] = $name; return $this; } ``` * Ensuite j'ai fait une classe de formulaire qui contient toutes les instructions nécessaires pour créer le formulaire de tâche qui sera associé à l'entité upload ```php public function buildForm(FormBuilderInterface $builder, array $options): void { $builder ->add('names', FileType::class, [ 'multiple' => true, 'label'=> 'Selectionner deux fichiers csv', 'attr' => [ 'multiple' => 'multiple' ] ]) ->add('submit',SubmitType::class) ; } public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'data_class' => Upload::class, ]); } ``` * Ensuite j'ai fait un classe controller qui permet de le restituer ```php /** * @Route("/home", name="home") */ public function HomeController(Request $request) { $upload =new Upload(); $form = $this->createForm(UploadType::class, $upload); //traitement du formulaire $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()){ $files = $upload->getNames(); //récupération du fichier $fileName0 = $files[0]->getClientOriginalName(); // définition d'un nouveau nom de fichier $fileName1 = $files[1]->getClientOriginalName(); $files[0]->move($this->getParameter('upload_directory'), $fileName0); //recupération du paramètre $files[1]->move($this->getParameter('upload_directory'), $fileName1); $upload->setNames(($fileName0)); $upload->setNames(($fileName1)); return $this->redirectToRoute('home');//redirection sur le home } return $this->render('home/index.html.twig', [ 'form' => $form->createView(), ]); } ``` * Dans le répertoire service.yaml, j'ai défini un paramètre qui contient le nom du répertoire ou les fichiers doivent être affiché. ```php parameters: upload_directory: '%kernel.project_dir%/public/uploads' ``` ###Fusion des fichiers uploader D'abord, pour pouvoir fusionné les fichiers j'ai indiqué le chemin dans lequel le dossier se trouve à partir d'un chemin de fichier en lecture seul grace au mode "r", puis je crée et ouvre en même temps le fichier fusionné en indiquant le chemin ou il va se trouver grace au mode "x" Si le fichier a été ouvert, il analyse la ligne qu'il lit et recherche les champs CSV, qu'il va retourner dans un tableau "$liste" les contenant. Et enfin on format les ligne en csv et l'écrit dans un fichier. ```php /** * @Route("/fusion", name="fusion") */ public function index() { //ouverture du dossier à partir d'un chemin de fichier en lecture seul grace au mode "r" $csv = fopen('../public/uploads/small-french-client.csv', 'r'); $csv1 = fopen('../public/uploads/small-german-client.csv', 'r'); NHJTRFDX $fusion=fopen('../public/fusion/french-german-client.csv','x' ); $liste=array(); // si le fichier a été ouvert, il analyse la ligne qu'il lit et // recherche les champs CSV, qu'il va retourner dans un tableau "$liste" // les contenant. if($csv) { $ligne = fgetcsv($csv, 1000, ","); if ($csv1) { $ligne1 = fgetcsv($csv1, 1000, ","); $ligne1 = fgetcsv($csv1, 1000, ","); //fusion séquentielle while ($ligne) { $liste[] = $ligne; $ligne = fgetcsv($csv, 1000, ","); } while ($ligne1) { $liste[] = $ligne1; $ligne1 = fgetcsv($csv1, 1000, ","); } fclose($csv); //fermeture de fichier qui est représenter par le pointeur fclose($csv1); } else{ echo"Ouverture impossible"; } } else{ echo"Ouverture impossible"; } foreach ($liste as $fields){ fputcsv($fusion, $fields); } fclose($fusion); dump($liste); exit; ``` ### Droit accés Dans la classe Utilisateur, les rôles sont un tableau stocké dans la base de données et chaque utilisateur à un role. ```php public function getRoles(): array { $roles = $this->roles; //on va chercher le role de l'utilsateur // guarantee every user at least has ROLE_USER $roles[] = 'ROLE_USER'; //n'importe quel utilisateur connecter aura se role return array_unique($roles); } ``` <file_sep><?php namespace App\Entity; use App\Repository\UploadRepository; use Doctrine\ORM\Mapping as ORM; class Upload { /* nom du fichier */ private $names; public function getNames() { return $this->names; } public function setNames($names) { $this->names= $names; return $this; } public function addNames($name) { $this->names[] = $name; return $this; } }
9985c76dea5a7eeb7763ef3cc51919d3bb173f3c
[ "Markdown", "SQL", "PHP" ]
5
PHP
awa-dev/Vetux-Line
7ad50c75db014efcaa04cd4d7fcd761bdeb01c72
08efcb0ecc6c98b9a9cc35a46e1d05d29db92b7d
refs/heads/master
<repo_name>RandoriDev/querybuilder<file_sep>/site_builder.py import argparse import copy import json import os import re import shutil import subprocess import sys assert sys.version_info >= (3, 0), "This script requires the use of Python 3" # Api Endpoints that aren't real endpoints so do skip them when encountered do_not_includes = ['querybuilder_rule_group_schema', 'querybuilder_rule_group_schema_2', 'querybuilder_rule_group_schema_3', 'querybuilder_rule_group_schema_4', 'querybuilder_rule_schema', 'saved_views_model_custom_in', 'saved_views_patch_in'] # API endpoints that result in a "special" picklist that maps Names to Values # using the "Selectize" feature of jquery querybuilder global_specials = { 'confidence': [ 'integer', { "name": "Min", "val": 0 }, { "name": "Low", "val": 25 }, { "name": "Medium", "val":60 }, { "name": "High", "val": 75 }, { "name": "Extreme", "val": 90 }, { "name": "Max", "val": 100 } ], 'name_type': [ 'integer', { "name": "Domain Name", "val": 0 }, { "name": "Hostname", "val": 1 } ], 'priority_score': [ 'double', { "name": "Low", "val": 0 }, { "name": "Medium", "val": 20 }, { "name": "High", "val": 29.98 } ], 'target_confidence': [ 'integer', { "name": "Min", "val": 0 }, { "name": "Low", "val": 25 }, { "name": "Medium", "val":60 }, { "name": "High", "val": 75 }, { "name": "Extreme", "val": 90 }, { "name": "Max", "val": 100 } ], 'target_temptation': [ 'integer', { "name": "Low", "val": 0}, { "name": "Medium", "val": 15}, { "name": "High", "val": 30}, { "name": "Critical", "val": 40} ] } # Default rules for the "all_detections_for_target" API endpoint. # Is intended to illustrate a "complex/compound" query example_complex_rule='''var rules_REPLACEME = { condition: 'AND', rules: [{ id: 'table.confidence', operator: 'greater_or_equal', value: 60 }, { condition: 'OR', rules: [{ id: 'table.hostname', operator: 'not_ends_with', value: 'foo.com' }, { id: 'table.target_temptation', operator: 'greater_or_equal', value: 15 }] }] }; ''' # Default query for most API endpoints default_rule='''var rules_REPLACEME = { condition: "AND", rules: [ { id: "table.confidence", operator: "greater_or_equal", value: 60 } ] }; ''' # Default query for API endpoints that do not have a "confidence" attribute ep_wo_confidence_rule='''var rules_REPLACEME = { condition: "AND", rules: [ { id: "table.id", operator: "equal", value: "<uuid_here>" } ] }; ''' def copytree(src, dst, symlinks=False, ignore=None): if not os.path.exists(dst): os.makedirs(dst) for item in os.listdir(src): s = os.path.join(src, item) d = os.path.join(dst, item) if os.path.isdir(s): copytree(s, d, symlinks, ignore) else: if not os.path.exists(d) or \ os.stat(s).st_mtime - os.stat(d).st_mtime > 1: shutil.copy2(s, d) def craft_selectize_string(field_name, picklist_data_type): ss = ''' { id: 'table.xxxfield_namexxx', label: 'xxxfield_namexxx', type: 'xxxdata_typexxx', plugin: 'selectize', plugin_config: { valueField: 'val', labelField: 'name', searchField: 'name', sortField: 'val', create: true, maxItems: 1, plugins: ['remove_button'], onInitialize: function() { var that = this; xxxfield_namexxx_json.forEach(function(item) { that.addOption(item); }); } }, valueSetter: function(rule, value) { rule.$el.find('.rule-value-container input')[0].selectize.setValue(value); } }'''.replace('xxxfield_namexxx', field_name).replace('xxxdata_typexxx', picklist_data_type) return ss def process_api_file(): sect_str = '' js_sources_string = '' with open(api_file, 'r') as af: datastore = json.load(af) schemas = datastore['components']['schemas'] for dash_endpoint in sorted(schemas.keys()): try: filters = [] if not schemas[dash_endpoint]['required']: continue endpoint = dash_endpoint.replace('-', '_') if endpoint in do_not_includes: continue sort_list = [] specials = copy.deepcopy(global_specials) endpoint_has_confidence = False for k,v in sorted(schemas[dash_endpoint]['properties'].items()): # skip deleted because it is not cust facing # skip all_ports because it is an array and jquery Querybuilder does not support array types if k in ['deleted', 'all_ports']: continue if k == 'confidence': endpoint_has_confidence = True # good for it! sort_list.append(f'<nobr>{k}, -{k}</nobr>') try: enum_values = v['enum'] ev_list = [v['type']] for ev in enum_values: ev_list.append({"name": ev, "val": ev}) specials[k] = ev_list except KeyError: pass if k in specials.keys(): filters.append(k) continue filter_dict = {} filter_dict['id'] = f'table.{k}' filter_dict['label'] = k if v['type'] == 'number': filter_dict['type'] = 'double' else: filter_dict['type'] = v['type'] if k in ['first_seen', 'last_seen' ]: filter_dict['type'] = 'date' filter_dict['validation'] = {'format': 'MM/DD/YYYY'} filter_dict['plugin'] = 'datepicker' filter_dict['plugin_config'] = { 'format': 'mm/dd/yyyy', 'todayBtn': 'linked', 'todayHighlight': True, 'autoclose': True } filters.append(filter_dict) filt_string = json.dumps(filters, indent=2).replace('"','\'') picklist_str = '\n' for special, sv in specials.items(): picklist_data_type = sv.pop(0) picklist_str += f'var {special}_json = {json.dumps(sv, indent=2)};\n\n' new_str = craft_selectize_string(special, picklist_data_type) spec_str = f" '{special}'" tmpstr = re.sub(spec_str, new_str, filt_string) filt_string = copy.deepcopy(tmpstr) if endpoint == 'all_detections_for_target': def_rules_str = example_complex_rule elif endpoint_has_confidence: def_rules_str = default_rule else: def_rules_str = ep_wo_confidence_rule with open('templates/template-javascript.js', 'r') as j: js_source_code = j.read().rstrip('\n') js_str = ''.join([picklist_str, def_rules_str, js_source_code, filt_string, '\n});']) js_str = js_str.replace('REPLACEME', endpoint) output_filename = f'{output_dir}/js/randori/{endpoint}.js' with open(output_filename, 'w+') as o: o.write(js_str) sort_str = ', '.join(sort_list) sort_str = f'{sort_str}\n\n<section>' with open('templates/template-index-section.html', 'r') as f: sect_str = sect_str + f.read().replace('REPLACEME', endpoint) sect_str = sect_str + sort_str js_sources_string = js_sources_string + \ '<script src="js/randori/{}.js"></script>\n'.format(endpoint) except KeyError: pass return (sect_str, js_sources_string) def build_website(): with open('templates/template-index-start.html', 'r') as e: html_str_1 = e.read() with open('templates/template-index-middle.html', 'r') as e: html_str_2 = e.read() with open('templates/template-index-end.html', 'r') as e: html_str_3 = e.read() section_str, js_str = process_api_file() full_page = ''.join([html_str_1, section_str, html_str_2, js_str, html_str_3]) index_outfile = f'{output_dir}/index.html' with open(index_outfile, 'w+') as o: o.write(full_page) print ('Done') if __name__ == '__main__': parser = argparse.ArgumentParser(description = '') required = parser.add_argument_group('required arguments') required.add_argument('-i', '--input', required=True, help='File containing the Randori API Spec.') required.add_argument('-o', '--output', required=True, help='Directory in which to write the generated files.') parser.add_argument('-s', '--setup', default=False, action='store_true', help='If the setup arg/flag is provided, copy the\ contents of the "framework" directory to the\ output directory.') args = parser.parse_args() api_file = args.input output_dir = args.output if not os.path.isdir(output_dir): print ('{} does not exist. Please create the directory and \ run the script again.'.format(output_dir)) sys.exit(1) if not (os.access(output_dir, os.W_OK) and os.access(output_dir, os.X_OK)): print ('{} is not writeable by the current user. \ Please change the permissions on the directory \ and run the script again.'.format(output_dir)) sys.exit(1) if args.setup: os.chdir('framework') copytree('.', output_dir) os.chdir('..') if os.path.isfile('/etc/selinux/config'): with open('/etc/selinux/config', 'r') as sel: if 'SELINUX=enforcing' in sel.read(): try: subprocess.run(['restorecon', '-r', output_dir], check=True) except FileNotFoundError: pass build_website()
46b9f077a5462b8a7b5ef0dd3e81f5b8ddf338df
[ "Python" ]
1
Python
RandoriDev/querybuilder
50d5aa46a4d80bbcd079bcf6fdfec7890a5c9c69
5a9b3f2dfc5fe869f2b95d08a1e5b522f47cdc80
refs/heads/master
<file_sep>'use strict'; const { error404 } = require('./controllers/errors'); const { getPlaces } = require('./controllers/places'); module.exports = app => { app.get('/', getPlaces); app.all('*', error404); }; <file_sep>'use strict'; const path = require('path'); const express = require('express'); const dotenv = require('dotenv'); const hbs = require('hbs'); const cors = require('cors'); const routes = require('./routes'); const app = express(); // Определяем директорию для хранения шаблонов. // Для работы с директориями всегда используем модуль «path» // и преобразуем относительные пути в абсолютные const viewsDir = path.join(__dirname, 'views'); // Определяем директорию для хранения отдельных частей шаблонов const partialsDir = path.join(viewsDir, 'partials'); const publicDir = path.join(__dirname, 'public'); const defaultValues = dotenv.config({ path: path.join(__dirname, '.env') }).parsed; // Подключаем шаблонизатор app.set('view engine', 'hbs'); // Подключаем директорию с шаблонами app.set('views', viewsDir); app.use(cors()); // Отдаём статичные файлы из соответствующей директории app.use(express.static(publicDir)); app.use((err, req, res, next) => { console.error(err.stack); next(); }); // Собираем общие данные для всех страниц приложения app.use((req, res, next) => { // Хранение в res.locals – рекомендованный способ // Не перезаписываем, а дополняем объект res.locals.meta = { charset: 'utf-8', description: 'Задача «Павел слишком занят»' }; res.locals.title = 'Задача «Павел слишком занят»'; next(); }); // Подключаем маршруты routes(app); // Фиксируем фатальную ошибку и отправляем ответ с кодом 500 app.use((err, req, res) => { console.error(err.stack); res.sendStatus(500); }); hbs.registerPartials(partialsDir, () => { app.listen(defaultValues.PORT, () => { console.info(`Open http://localhost:${defaultValues.PORT}/api/places`); }); }); <file_sep> const searchBtn = document.getElementById('search'); const allPlaces = 'https://webdev-task-2-bfflqxwpwl.now.sh/api/places/'; const deleteAllPlaces = 'https://webdev-task-2-bfflqxwpwl.now.sh/api/places/deleting/'; const deleteBtn = document.getElementById('delete'); const createBtn = document.getElementById('create'); const allPlacesBtn = document.getElementById('all'); const visitedPlacesBtn = document.getElementById('visited'); const plannedPlaceBtn = document.getElementById('planned'); let placesList = document.getElementById('places'); document.addEventListener('DOMContentLoaded', showAllPlaces); function showAllPlaces() { fetch(allPlaces) .then(response => response.json()) .then(data => data.places.forEach((element, index, array) => createNewPlace(element, index, array.length))) .catch(e => console.error(e)); } function createNewPlace(place, index, arrayLength) { let newElement = document.createElement('div'); let newPlace = document.createElement('input'); let isVisited = document.createElement('input'); let saveChanges = document.createElement('input'); let deleteChanges = document.createElement('input'); let btnUp = document.createElement('input'); let btnDown = document.createElement('input'); let deletePlace = document.createElement('input'); let editDescription = document.createElement('input'); let editDiv = document.createElement('div'); let editNameDiv = document.createElement('div'); saveChanges.type = 'button'; saveChanges.id = 'saveChanges'; deleteChanges.type = 'button'; deleteChanges.id = 'deleteChanges'; deletePlace.type = 'button'; deletePlace.id = 'deletePlaceBtn'; deletePlace.className = 'deletePlaceBtn'; editDescription.type = 'button'; editDescription.id = 'editDescriptionBtn'; editDescription.className = 'editDescriptionBtn'; isVisited.type = 'checkbox'; isVisited.id = 'tick'; isVisited.checked = place.visited; // поле с 2 кнопками - изменение описания места и отмена изменений editNameDiv.style.display = 'none'; editNameDiv.id = 'editNameField'; editNameDiv.className = 'editNameField'; editNameDiv.appendChild(saveChanges); editNameDiv.appendChild(deleteChanges); editDiv.style.display = 'none'; // поле с 2 кнопками - удалить место и отмена изменения editDiv.id = 'editField'; editDiv.className = 'editField'; editDiv.appendChild(deletePlace); editDiv.appendChild(editDescription); btnUp.type = 'button'; btnUp.id = 'btnUp'; btnDown.type = 'button'; btnDown.id = 'btnDown'; newPlace.readOnly = true; newPlace.type = 'text'; newPlace.id = 'nameField'; newPlace.value = place.description; newElement.className = 'place'; newElement.value = place.description; newElement.dataset.index = index; newElement.appendChild(newPlace); newElement.appendChild(isVisited); newElement.appendChild(btnUp); newElement.appendChild(btnDown); newElement.appendChild(editDiv); newElement.appendChild(editNameDiv); placesList.appendChild(newElement); moveUp(btnUp, arrayLength); moveDown(btnDown, arrayLength); changeVisitedState(isVisited); } function changeVisitedState(checkbox) { let parent = checkbox.parentNode; checkbox.addEventListener('click', function () { fetch(allPlaces + 'modification/visiting/' + parent.value + '/' + checkbox.checked, { method: 'PUT' }) .then(() => { deleteAll(); showAllPlaces(); }) .catch (e => console.error(e)); }); } function deleteAll() { while (placesList.firstChild) { placesList.removeChild(placesList.firstChild); } } function moveUp(arrow, arrayLength) { let parent = arrow.parentNode; arrow.addEventListener('click', function () { fetch(allPlaces + 'modification/index/' + parent.value + '/' + (parent.dataset.index - 1 + arrayLength) % arrayLength, { method: 'PUT' }) .then(() => { deleteAll(); showAllPlaces(); }) .catch (e => console.error(e)); }); } function moveDown(arrow, arrayLength) { let parent = arrow.parentNode; arrow.addEventListener('click', function () { fetch(allPlaces + 'modification/index/' + parent.value + '/' + (parent.dataset.index + 1 + arrayLength) % arrayLength, { method: 'PUT' }) .then(() => { deleteAll(); showAllPlaces(); }) .catch (e => console.error(e)); }); } placesList.addEventListener('mouseenter', function () { let fields = document.getElementsByClassName('editField'); for (let i = 0; i < fields.length; i++) { fields[i].style.width = '100px'; fields[i].style.height = '22px'; fields[i].style.display = 'inline-block'; fields[i].style.verticalAlign = 'top'; fields[i].style.border = '1px solid #ff0080'; } deleteOnePlace(); editPlace(); }); function editPlace() { let editFields = document.getElementsByClassName('editDescriptionBtn'); for (let i = 0; i < editFields.length; i++) { editFields[i].addEventListener('click', function () { let editNameFields = document.getElementsByClassName('editNameField'); for (let j = 0; j < editFields.length; j++) { editNameFields[j].style.display = 'block'; let oldDescription = getOldDescription(); unfreeze(); saveChangesInDescription(oldDescription); deleteChangesInDescription(oldDescription); } }); } } function getOldDescription() { return document.getElementById('nameField').value; } function unfreeze() { document.getElementById('nameField').readOnly = false; } function closeField() { document.getElementById('editNameField').style.display = 'none'; } function deleteChangesInDescription(oldDescription) { document.getElementById('deleteChanges').addEventListener('click', function () { document.getElementById('nameField').value = oldDescription; }); } function saveChangesInDescription(oldDescription) { document.getElementById('saveChanges').addEventListener('click', function () { let newDescription = document.getElementById('nameField').value; document.getElementById('saveChanges').style.disabled = true; fetch(allPlaces + 'modification/description/' + oldDescription + '/' + newDescription, { method: 'PUT' }) .then(() => { closeField(); deleteAll(); showAllPlaces(); }) .catch (e => console.error(e)); }); } function deleteOnePlace() { document.getElementById('deletePlaceBtn').addEventListener('click', function () { fetch(deleteAllPlaces + this.parentNode.parentNode.value, { method: 'DELETE' }) .then(() => { deleteAll(); showAllPlaces(); }) .catch (e => console.error(e)); }); } plannedPlaceBtn.addEventListener('click', function () { fetch(allPlaces) .then(response => response.json()) .then(data => { deleteAll(); data.places.forEach((element, index, array) => { if (!element.visited) { createNewPlace(element, index, array.length); } }); }) .catch (e => console.error(e)); }); visitedPlacesBtn.addEventListener('click', function () { fetch(allPlaces) .then(response => response.json()) .then(data => { deleteAll(); data.places.forEach((element, index, array) => { if (element.visited) { createNewPlace(element, index, array.length); } }); }) .catch(e => console.error(e)); }); allPlacesBtn.addEventListener('click', function () { deleteAll(); showAllPlaces(); }); searchBtn.addEventListener('click', function () { const placeName = document.getElementById('search-input').value; fetch(allPlaces + placeName) .then(response => response.json()) .then(data => { deleteAll(); createNewPlace(data); }) .catch(e => console.error(e)); }); deleteBtn.addEventListener('click', function () { fetch(deleteAllPlaces, { method: 'DELETE' }) .then(deleteAll()); }); createBtn.addEventListener('click', function () { const newPlace = document.getElementById('create-input').value; fetch(allPlaces + newPlace, { method: 'POST' }) .then(response => response.json()) .then(data => { createNewPlace(data[data.length - 1], data.length - 1, data.length); }) .catch(e => console.error(e)); }); <file_sep>'use strict'; let places = []; class Place { constructor({ description }) { this.description = description; this.visited = false; this.created = new Date(); } save() { places.push(this); } static find(description) { return places.find(place => place.description === description); } static clearAll() { places.length = 0; } static removePlace(description) { places.splice(places[description], 1); } static mark(description, tick) { Place.find(description).visited = tick; } static edit(oldDescription, NewDescription) { Place.find(oldDescription).description = NewDescription; } static findAll() { return places; } static changeIndex(description, to) { let elemByDescription = Place.find(description); let elemByIndex = places[to]; let from = places.indexOf(elemByDescription); places.splice(to, 1, elemByDescription); places.splice(from, 1, elemByIndex); } static dateSortAsc() { return places.sort(function (a, b) { return a.created - b.created; }); } static dateSortDesc() { return places.sort(function (a, b) { return b.created - a.created; }); } static abcSort() { return places.sort(); } static paginate() { let pages = []; for (let i = 0; i < places.length; i += 3) { let page = places.slice(i, i + 3); pages.push(page); } return pages; } } module.exports = Place;
f4e0c8a8f32353a416c2128b7dabb461911905ee
[ "JavaScript" ]
4
JavaScript
chrighter/webdev-task-3
37bb395cf7baa273258a2aafc6b000e160b91a25
c8f5353d8ab67779921eea2f8b8b58ba514dc53a
refs/heads/master
<repo_name>zhurongguang/hbRPC-tracker<file_sep>/hbRPC-tracker/hbRPC-tracker-web/src/main/java/com/botech/hbrpc/tracker/action/JsVersionFilter.java package com.botech.hbrpc.tracker.action; import java.io.IOException; import java.util.Date; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class JsVersionFilter implements Filter { private Date date; @Override public void init(FilterConfig filterConfig) throws ServletException { date = new Date(); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //针对上线更改js之后的版本,用于处理缓存,每次tomcat启动刷新一下版本 //调试阶段注释掉 // ((HttpServletRequest)request).getSession().getServletContext().setAttribute("staticVersion", date); chain.doFilter(request, response); } @Override public void destroy() { //To change body of implemented methods use File | Settings | File Templates. } } <file_sep>/hbRPC-tracker/hbRPC-tracker-client/src/main/java/com/botech/hbrpc/tracker/wrapper/TraceRunnable.java package com.botech.hbrpc.tracker.wrapper; import com.botech.hbrpc.tracker.Span; import com.botech.hbrpc.tracker.agent.Tracer; public class TraceRunnable implements Runnable { private final Span parent; private final Runnable runnable; private Tracer tracer = Tracer.getTracer(); public TraceRunnable(Runnable r) { this.parent = tracer.getParentSpan(); this.runnable = r; } public TraceRunnable(Runnable r, Span p) { this.runnable = r; this.parent = p; } @Override public void run() { if (parent != null) { tracer.setParentSpan(parent); } runnable.run(); } } <file_sep>/hbRPC-tracker/hbRPC-tracker-collector/src/main/resources/mysql.properties jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://192.168.3.244:3306/hb_rpc_tracker?useUnicode=true&characterEncoding=utf-8 jdbc.username=root jdbc.password=<PASSWORD><file_sep>/hbRPC-tracker/hbRPC-tracker-manager-db/src/main/java/com/botech/hbrpc/tracker/mysql/persistent/service/ServiceService.java package com.botech.hbrpc.tracker.mysql.persistent.service; import java.util.List; import com.botech.hbrpc.tracker.mysql.persistent.entity.ServicePara; public interface ServiceService { String getServiceId(String serviceName, String appName); List<ServicePara> get(Integer appId); } <file_sep>/hbRPC-tracker/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.botech</groupId> <artifactId>hbRPC-tracker</artifactId> <version>1.0.0</version> <packaging>pom</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <springframework-version>4.1.9.RELEASE</springframework-version> <servlet.version>3.1.0</servlet.version> <jsp-api.version>2.2</jsp-api.version> <jstl-api.version>1.2</jstl-api.version> <hbRPC.version>2.0.4</hbRPC.version> <metamorphosis.version>1.4.3</metamorphosis.version> <disruptor.version>2.10.3</disruptor.version> <glowworm.version>1.0-SNAPSHOT</glowworm.version> <mybatis.version>3.4.2</mybatis.version> <mybatis-spring>1.3.1</mybatis-spring> <mysql-connector-java.version>6.0.5</mysql-connector-java.version> <google-collections.version>1.0</google-collections.version> <commons-configuration.version>1.9</commons-configuration.version> <commons-lang3.version>3.5</commons-lang3.version> <druid.version>1.0.28</druid.version> <jackson.version>1.9.10</jackson.version> <log4j.version>1.2.17</log4j.version> <slf4j.version>1.7.22</slf4j.version> <fastjson.version>1.2.24</fastjson.version> <validation-api.version>1.1.0.Final</validation-api.version> <zookeeper.version>3.4.8</zookeeper.version> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${springframework-version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${servlet.version}</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>${jsp-api.version}</version> </dependency> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>jstl-api</artifactId> <version>${jstl-api.version}</version> </dependency> <dependency> <groupId>org.glassfish.web</groupId> <artifactId>jstl-impl</artifactId> <version>${jstl-api.version}</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-lgpl</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-lgpl</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.botech</groupId> <artifactId>hbRPC</artifactId> <version>${hbRPC.version}</version> </dependency> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>${zookeeper.version}</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> <exclusions> <exclusion> <artifactId>jmxri</artifactId> <groupId>com.sun.jmx</groupId> </exclusion> <exclusion> <artifactId>jmxtools</artifactId> <groupId>com.sun.jdmk</groupId> </exclusion> <exclusion> <artifactId>jms</artifactId> <groupId>javax.jms</groupId> </exclusion> <exclusion> <artifactId>mail</artifactId> <groupId>javax.mail</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${slf4j.version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>com.googlecode.disruptor</groupId> <artifactId>disruptor</artifactId> <version>${disruptor.version}</version> </dependency> <dependency> <groupId>com.jd.dd</groupId> <artifactId>glowworm</artifactId> <version>${glowworm.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis-spring}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql-connector-java.version}</version> </dependency> <dependency> <groupId>com.google.collections</groupId> <artifactId>google-collections</artifactId> <version>${google-collections.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>${commons-lang3.version}</version> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>${validation-api.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${fastjson.version}</version> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${springframework-version}</version> </dependency> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> </dependency> </dependencies> <build> <pluginManagement> <plugins> <!-- compiler插件, 设定JDK版本 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> <!-- test插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <!--<skip>true</skip> --> <failIfNoTests>false</failIfNoTests> <includes> <include>**/*Test.java</include> </includes> </configuration> </plugin> <!-- resource插件, 设定编码 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <configuration> <encoding>${project.build.sourceEncoding}</encoding> </configuration> </plugin> <!-- clean插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-clean-plugin</artifactId> </plugin> <!-- install插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-install-plugin</artifactId> </plugin> <!-- deploy插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-deploy-plugin</artifactId> </plugin> <!-- war插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <configuration> <warName>${project.artifactId}</warName> </configuration> </plugin> <!-- jar插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <configuration> <archive> <manifest> <addDefaultImplementationEntries>true</addDefaultImplementationEntries> <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries> </manifest> </archive> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> </plugin> <!-- dependency插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> </plugin> <!--release 插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-release-plugin</artifactId> <version>2.1</version> </plugin> </plugins> </pluginManagement> </build> <modules> <module>hbRPC-tracker-interface</module> <module>hbRPC-tracker-client</module> <module>hbRPC-tracker-store</module> <module>hbRPC-tracker-collector</module> <module>hbRPC-tracker-collector-service</module> <module>hbRPC-tracker-manager</module> <module>hbRPC-tracker-manager-db</module> <module>hbRPC-tracker-web</module> </modules> <distributionManagement> <repository> <id>thirdparty</id> <name>3rd party</name> <url>http://172.16.1.251:8081/nexus/content/repositories/thirdparty</url> </repository> </distributionManagement> </project><file_sep>/hbRPC-tracker/hbRPC-tracker-manager-db/src/main/java/com/botech/hbrpc/tracker/mysql/persistent/service/AppService.java package com.botech.hbrpc.tracker.mysql.persistent.service; import java.util.List; import com.botech.hbrpc.tracker.mysql.persistent.entity.AppPara; public interface AppService { Integer getAppId(String appName); List<AppPara> getAll(); } <file_sep>/hbRPC-tracker/hbRPC-tracker-client/src/main/java/com/botech/hbrpc/tracker/agent/support/GenerateTraceId.java package com.botech.hbrpc.tracker.agent.support; import java.util.concurrent.atomic.AtomicLong; public class GenerateTraceId { private Long seed; private Long MAX_STEP = 0xffffffL; private AtomicLong plusId = new AtomicLong(0L); public GenerateTraceId(Long seed) { this.seed = seed; } public Long getTraceId() { return (seed << 40) | getPlusId(); } private long getPlusId() { if (plusId.get() >= MAX_STEP) { plusId.set(0L); } return plusId.incrementAndGet(); } } <file_sep>/hbRPC-tracker/hbRPC-tracker-store/hbRPC-tracker-mysql/src/main/java/com/botech/hbrpc/tracker/mysql/service/impl/Utils.java package com.botech.hbrpc.tracker.mysql.service.impl; import java.util.List; import org.apache.commons.lang3.StringUtils; import com.botech.hbrpc.tracker.Annotation; import com.botech.hbrpc.tracker.Span; public class Utils { public static boolean isTopAnntation(Span span) { List<Annotation> alist = span.getAnnotations(); boolean isfirst = false; for (Annotation a : alist) { if (StringUtils.endsWithIgnoreCase("cs", a.getValue())) { isfirst = true; } } return isfirst; } public static Annotation getCsAnnotation(List<Annotation> alist) { for (Annotation a : alist) { if (StringUtils.endsWithIgnoreCase("cs", a.getValue())) { return a; } } return null; } public static Annotation getCrAnnotation(List<Annotation> alist) { for (Annotation a : alist) { if (StringUtils.endsWithIgnoreCase("cr", a.getValue())) { return a; } } return null; } public static boolean isRoot(Span span) { return span.getParentId() == null; } } <file_sep>/hbRPC-tracker/hbRPC-tracker-store/hbRPC-tracker-mysql/src/main/java/com/botech/hbrpc/tracker/mysql/persistent/dao/TraceMapper.java package com.botech.hbrpc.tracker.mysql.persistent.dao; import java.util.List; import com.botech.hbrpc.tracker.mysql.persistent.entity.Trace; public interface TraceMapper { List<Trace> findTraces(String serviceId, Long startTime, int num); List<Trace> findTracesByDuration(String serviceId, Long startTime, int durationMin, int durationMax, int num); List<Trace> findTracesEx(String serviceId, Long startTime, int num); public void addTrace(Trace t); void deleteAllTraces();// 只用于测试 } <file_sep>/hbRPC-tracker/hbRPC-tracker-manager-db/src/main/java/com/botech/hbrpc/tracker/mysql/persistent/dao/impl/ServiceIdGenMapperImpl.java package com.botech.hbrpc.tracker.mysql.persistent.dao.impl; import org.mybatis.spring.SqlSessionTemplate; import com.botech.hbrpc.tracker.mysql.persistent.dao.ServiceIdGenMapper; import com.botech.hbrpc.tracker.mysql.persistent.entity.ServiceIdGen; public class ServiceIdGenMapperImpl implements ServiceIdGenMapper { @Override public void updateServiceIdGen(ServiceIdGen serviceIdGen) { sqlSession.update("updateServiceIdGen", serviceIdGen); } @Override public ServiceIdGen getServiceIdGen() { return (ServiceIdGen) sqlSession.selectOne("getServiceIdGen"); } private SqlSessionTemplate sqlSession; public void setSqlSession(SqlSessionTemplate sqlSession) { this.sqlSession = sqlSession; } } <file_sep>/hbRPC-tracker/hbRPC-tracker-manager-db/src/main/java/com/botech/hbrpc/tracker/mysql/persistent/entity/ServiceIdGen.java package com.botech.hbrpc.tracker.mysql.persistent.entity; public class ServiceIdGen { private Integer maxId; private Integer head; private Integer maxHead; private Integer idScope; public Integer getMaxId() { return maxId; } public void setMaxId(Integer maxId) { this.maxId = maxId; } public Integer getHead() { return head; } public void setHead(Integer head) { this.head = head; } public Integer getMaxHead() { return maxHead; } public Integer getIdScope() { return idScope; } } <file_sep>/hbRPC-tracker/hbRPC-tracker-store/hbRPC-tracker-mysql/src/main/java/com/botech/hbrpc/tracker/mysql/persistent/dao/impl/TraceMapperImpl.java package com.botech.hbrpc.tracker.mysql.persistent.dao.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import org.mybatis.spring.SqlSessionTemplate; import com.botech.hbrpc.tracker.mysql.persistent.dao.TraceMapper; import com.botech.hbrpc.tracker.mysql.persistent.entity.Trace; public class TraceMapperImpl implements TraceMapper{ @Override public List<Trace> findTraces(String serviceId, Long startTime, int num){ Map<String, Object> map = new HashMap<String, Object>(); map.put("startTime", startTime); map.put("num", num); map.put("serviceId", serviceId); return sqlSession.selectList("findTraces", map); } @Override public List<Trace> findTracesByDuration(String serviceId, Long startTime, int durationMin, int durationMax, int num){ Map<String, Object> map = new HashMap<String, Object>(); map.put("serviceId", serviceId); map.put("startTime", startTime); map.put("num", num); map.put("durationMin", durationMin); map.put("durationMax", durationMax); return sqlSession.selectList("findTracesByDuration", map); } @Override public List<Trace> findTracesEx(String serviceId, Long startTime, int num) { Map<String, Object> map = new HashMap<String, Object>(); map.put("startTime", startTime); map.put("num", num); map.put("serviceId", serviceId); return sqlSession.selectList("findTracesEx", map); } public void addTrace(Trace t) { sqlSession.insert("addTrace",t); } @Override public void deleteAllTraces(){ sqlSession.delete("deleteAllTraces"); } private SqlSessionTemplate sqlSession; public void setSqlSession(SqlSessionTemplate sqlSession) { this.sqlSession = sqlSession; } } <file_sep>/hbRPC-tracker/hbRPC-tracker-store/hbRPC-tracker-mysql/src/main/java/com/botech/hbrpc/tracker/mysql/persistent/entity/Trace.java package com.botech.hbrpc.tracker.mysql.persistent.entity; public class Trace { private Long id; private Long time; private Long traceId; private Integer duration; private String service; //查询用 private String annValue; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getTime() { return time; } public void setTime(Long time) { this.time = time; } public Long getTraceId() { return traceId; } public void setTraceId(Long traceId) { this.traceId = traceId; } public Integer getDuration() { return duration; } public void setDuration(Integer duration) { this.duration = duration; } public String getService() { return service; } public void setService(String service) { this.service = service; } public String getAnnValue() { return annValue; } public void setAnnValue(String annValue) { this.annValue = annValue; } } <file_sep>/hbRPC-tracker/hbRPC-tracker-client/src/main/java/com/botech/hbrpc/tracker/agent/RegisterService.java package com.botech.hbrpc.tracker.agent; import java.util.List; /** * 注册服务接口 */ public interface RegisterService { public boolean registerService(String name,List<String> services); /*更新注册信息*/ boolean registerService(String appName, String serviceName); } <file_sep>/README.md # hbRPC-tracker hbRPC服务追踪,用于追中hbRPC服务的调用流程、调用时间等,辅助分析服务的调用情况,基于之前京东Hydra修改,目前只支持MySql以及内存队列, 后期可能加入MongoDB、HBase以及MQ。 <file_sep>/hbRPC-tracker/hbRPC-tracker-collector-service/target/classes/conf.properties metaq.zk.address=192.168.200.110:2181 metaq.topic=hydra metaq.consumer.maxDelayFetchTimeInMills=100<file_sep>/hbRPC-tracker/hbRPC-tracker-collector/src/main/resources/collector-common.properties collector.taskCount=5 collector.queueSize=2048<file_sep>/hbRPC-tracker/hbRPC-tracker-collector/target/classes/hbrpc-collector.properties hbrpc.application.name=hbRPC-tracker-collector hbrpc.application.owner=zhurg hbrpc.registry.protocol=zookeeper hbrpc.registry.address=192.168.3.189:2181,192.168.3.243:2181,192.168.3.244:2181 hbrpc.protocol.name=hbrpc hbrpc.protocol.port=20889<file_sep>/hbRPC-tracker/hbRPC-tracker-client/target/classes/META-INF/maven/com.botech/hbRPC-tracker-client/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.botech</groupId> <artifactId>hbRPC-tracker</artifactId> <version>1.0.0</version> </parent> <artifactId>hbRPC-tracker-client</artifactId> <dependencies> <dependency> <groupId>com.botech</groupId> <artifactId>hbRPC-tracker-interface</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> <dependency> <groupId>com.botech</groupId> <artifactId>hbRPC</artifactId> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> </dependency> </dependencies> <build> <plugins> <!-- compiler插件, 设定JDK版本 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> </plugin> <!-- jar插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> </plugin> </plugins> </build> </project><file_sep>/hbRPC-tracker/hbRPC-tracker-web/target/m2e-wtp/web-resources/META-INF/maven/com.botech/hbRPC-tracker-web/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.botech</groupId> <artifactId>hbRPC-tracker</artifactId> <version>1.0.0</version> </parent> <artifactId>hbRPC-tracker-web</artifactId> <packaging>war</packaging> <dependencies> <dependency> <groupId>com.botech</groupId> <artifactId>hbRPC-tracker-mysql</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>com.botech</groupId> <artifactId>hbRPC-tracker-manager-db</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> </dependency> <!-- servlet--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> </dependency> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>jstl-api</artifactId> </dependency> <dependency> <groupId>org.glassfish.web</groupId> <artifactId>jstl-impl</artifactId> </dependency> <!-- json --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-lgpl</artifactId> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-lgpl</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.8.5</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.5</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.8.5</version> </dependency> </dependencies> </project>
ab261265cb7ce3942fc62848a1cde55e33ba65ac
[ "Markdown", "Java", "Maven POM", "INI" ]
20
Java
zhurongguang/hbRPC-tracker
33b1eeec826e440feba9bce6b3303b1f29aa36d7
81435b3e5734a753235e38a9713982af0d1e44c9
refs/heads/master
<file_sep>import styles from './FooterLink.less'; import React from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import { AUTHENTICATED, UNAUTHENTICATED, AUTH_PENDING } from '../../private/authStatusTypes'; import urlForAuthStatus from '../../private/urlForAuthStatus'; import Badge from '../../Badge/Badge'; export default function FooterLink({ secondary, partner, analytics, className, linkRenderer, href, newBadge, authRequired, promo, authenticationStatus, ...props }) { return ( <li className={classnames(className, { [styles.secondary]: secondary })}> {linkRenderer({ 'data-analytics': analytics, className: classnames({ [styles.link]: true, [styles.promo]: promo }), href: authRequired ? urlForAuthStatus(authenticationStatus, href) : href, ...props })} {newBadge && ( <span> &nbsp;&nbsp; <Badge children="New" strong tone="info" /> </span> )} {partner ? ( <span className={styles.partnerCountry}>{` — ${partner}`}</span> ) : null} </li> ); } FooterLink.propTypes = { secondary: PropTypes.bool, analytics: PropTypes.string, href: PropTypes.string, newBadge: PropTypes.bool, className: PropTypes.string, partner: PropTypes.string, promo: PropTypes.bool, children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node ]), linkRenderer: PropTypes.func.isRequired, authRequired: PropTypes.bool, authenticationStatus: PropTypes.oneOf([ AUTHENTICATED, UNAUTHENTICATED, AUTH_PENDING ]) }; FooterLink.defaultProps = { secondary: false, authenticationStatus: AUTH_PENDING }; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import Header from './Header'; const DummyLinkRenderer = ({ href, ...props }) => <a {...props} />; DummyLinkRenderer.propTypes = { href: PropTypes.string }; export const blockSymbols = { 'Header/Australia/Unauthenticated': ( <Header linkRenderer={DummyLinkRenderer} authenticationStatus="unauthenticated" /> ), 'Header/Australia/Authenticated': ( <Header linkRenderer={DummyLinkRenderer} authenticationStatus="authenticated" userName="Name" /> ), 'Header/New Zealand/Unauthenticated': ( <Header locale="NZ" linkRenderer={DummyLinkRenderer} authenticationStatus="unauthenticated" /> ), 'Header/New Zealand/Authenticated': ( <Header locale="NZ" linkRenderer={DummyLinkRenderer} authenticationStatus="authenticated" userName="Name" /> ) }; <file_sep>// This selector prefix is automatically prepended to all selectors // to ensure styles don't leak out into the global scope. module.exports = '.__SSG__'; <file_sep>const auOrgSchema = { socialLinks: [ 'https://www.instagram.com/seekau/', 'https://twitter.com/seekjobs', 'https://plus.google.com/+seekau', 'https://au.linkedin.com/company/seek' ], telephone: '+61-1300-658-700', url: 'https://www.seek.com.au' }; const nzOrgSchema = { socialLinks: [ 'https://www.instagram.com/seeknz/', 'https://twitter.com/seekjobsnz', 'https://plus.google.com/+seeknz', 'https://nz.linkedin.com/company/seek' ], telephone: '+64-0508-733-569', url: 'https://www.seek.co.nz/' }; const commonSocialLinks = [ 'https://www.facebook.com/SEEK/', 'https://en.wikipedia.org/wiki/Seek_Limited', 'https://www.youtube.com/user/SEEKJobs' ]; const generateStructureDataSchema = (locale = 'AU') => { const { telephone, socialLinks, url } = locale === 'NZ' ? nzOrgSchema : auOrgSchema; return { '@context': 'http://schema.org', '@type': 'Organization', url, legalName: '<NAME>', logo: 'https://www.seek.com.au/content/images/logos/seek-logo-positive.svg', sameAs: [...commonSocialLinks, ...socialLinks], contactPoint: [ { '@type': 'ContactPoint', telephone, contactType: 'customer service', contactOption: 'TollFree' } ] }; }; export default generateStructureDataSchema; <file_sep>import styles from './FooterNav.less'; import React from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; export default function FooterNav({ secondary, label, children, className }) { return ( <nav aria-label={label} className={classnames(className || styles.category, { [styles.secondary]: secondary })} > <h4 className={styles.heading}>{label}</h4> <ul>{children}</ul> </nav> ); } FooterNav.propTypes = { secondary: PropTypes.bool, label: PropTypes.string, className: PropTypes.string, children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node ]) }; FooterNav.defaultProps = { secondary: false }; <file_sep>export default locale => /^nz$/i.test(locale) ? 'https://talent.seek.co.nz/' : 'https://talent.seek.com.au/'; <file_sep>// Alias 'seek-style-guide' so 'seek-style-guide-webpack' works correctly const path = require('path'); require('module-alias').addAlias( 'seek-style-guide', path.join(__dirname, '../..') ); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const StaticSiteGeneratorPlugin = require('static-site-generator-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const autoprefixer = require('autoprefixer'); const autoprefixerConfig = require('../../config/autoprefixer.config'); const { decorateClientConfig, decorateServerConfig } = require('seek-style-guide-webpack'); const babelConfig = require('../../config/babel.config.js')({ reactHotLoader: false }); const cssSelectorPrefix = require('./cssSelectorPrefix'); // Must be absolute paths const appPaths = [__dirname]; const resolveConfig = { modules: ['node_modules', 'components'] }; const getCommonRules = () => [ { test: /\.js$/, include: appPaths, use: { loader: 'babel-loader', options: babelConfig } }, { test: /\.svg$/, include: appPaths, use: [ { loader: 'raw-loader' }, { loader: 'svgo-loader' } ] } ]; const getStyleLoaders = (options = {}) => { return [ { loader: `css-loader${options.server ? '/locals' : ''}`, options: { modules: true, localIdentName: '[name]__[local]___[hash:base64:5]' } }, ...(options.server ? [] : [ { loader: 'postcss-loader', options: { plugins: [autoprefixer(autoprefixerConfig)] } } ]), { loader: 'less-loader' }, ...(options.server ? [] : [ { loader: 'string-replace-loader', options: { search: '__standalone_css_selector_prefix__', replace: cssSelectorPrefix } } ]) ]; }; const clientConfig = { mode: process.env.NODE_ENV === 'production' ? 'production' : 'development', entry: path.resolve(__dirname, 'src/client.js'), output: { path: path.resolve(__dirname, '../../dist/header-footer'), filename: 'client.js', library: 'SeekHeaderFooter', libraryTarget: 'umd' }, module: { rules: [ ...getCommonRules(), { test: /\.less$/, include: appPaths, use: [MiniCssExtractPlugin.loader].concat( getStyleLoaders({ server: false }) ) } ] }, resolve: resolveConfig, plugins: [new MiniCssExtractPlugin({ filename: 'styles.css' })].concat( process.env.NODE_ENV !== 'production' ? [new HtmlWebpackPlugin()] : [] ), stats: { children: false } }; const renderConfig = { mode: process.env.NODE_ENV === 'production' ? 'production' : 'development', entry: path.resolve(__dirname, 'src/render.js'), output: { path: path.resolve(__dirname, '../../dist/header-footer'), filename: 'render.js', libraryTarget: 'umd' }, module: { rules: [ ...getCommonRules(), { test: /\.less$/, include: appPaths, use: getStyleLoaders({ server: true }) } ] }, resolve: resolveConfig, plugins: [ new StaticSiteGeneratorPlugin({ globals: { window: {} } }) ] }; module.exports = [ decorateClientConfig(clientConfig, { cssOutputLoader: MiniCssExtractPlugin.loader, cssSelectorPrefix }), decorateServerConfig(renderConfig) ]; <file_sep>import makeStandalone from './makeStandalone'; import Header from 'seek-style-guide/react/Header/Header'; import Footer from 'seek-style-guide/react/Footer/Footer'; export const renderHeader = makeStandalone(Header); export const renderFooter = makeStandalone(Footer); // Allow standalone header consumers to create React elements import React from 'react'; export const createElement = React.createElement; <file_sep>// @flow import styles from './UserAccountMenu.less'; import React, { Fragment } from 'react'; import classnames from 'classnames'; import ArticleIcon from '../../ArticleIcon/ArticleIcon'; import SearchIcon from '../../SearchIcon/SearchIcon'; import ProfileIcon from '../../ProfileIcon/ProfileIcon'; import HeartIcon from '../../HeartIcon/HeartIcon'; import StarIcon from '../../StarIcon/StarIcon'; import ThumbsUpIcon from '../../ThumbsUpIcon/ThumbsUpIcon'; import TickCircleIcon from '../../TickCircleIcon/TickCircleIcon'; import Hidden from '../../Hidden/Hidden'; import Loader from '../../Loader/Loader'; import Badge from '../../Badge/Badge'; import employerLinkForLocale from '../employerLinkForLocale'; import { AUTHENTICATED, UNAUTHENTICATED, AUTH_PENDING } from '../../private/authStatusTypes'; import appendReturnUrl from '../../private/appendReturnUrl'; import urlForAuthStatus from '../../private/urlForAuthStatus'; const JOB_SEARCH = 'Job Search'; const PROFILE = 'Profile'; const SAVED_SEARCHES = 'Saved Searches'; const SAVED_AND_APPLIED = 'Saved & Applied Jobs'; const APPLIED_JOBS = 'Applied Jobs'; const RECOMMENDED_JOBS = 'Recommended Jobs'; const SETTINGS = 'Settings'; const CAREER_ADVICE = 'Career Advice'; const COMPANY_REVIEWS = 'Company Reviews'; type TabsType = | typeof JOB_SEARCH | typeof PROFILE | typeof SAVED_SEARCHES | typeof SAVED_AND_APPLIED | typeof APPLIED_JOBS | typeof RECOMMENDED_JOBS | typeof SETTINGS | typeof CAREER_ADVICE | typeof COMPANY_REVIEWS; type Props = { locale?: 'AU' | 'NZ', authenticationStatus?: AUTHENTICATED | UNAUTHENTICATED | AUTH_PENDING, linkRenderer: Function, returnUrl?: string, activeTab?: TabsType, newBadgeTab?: TabsType }; const clearLocalStorage = () => { if (window && window.localStorage) { localStorage.clear(); } }; const BadgeComponent = () => ( <Hidden desktop key="new" className={styles.newBadge}> <Badge strong tone="info"> New </Badge> </Hidden> ); export default ({ locale, authenticationStatus, linkRenderer, returnUrl, activeTab, newBadgeTab }: Props) => ( <ul className={styles.root}> <Hidden desktop component="li" className={classnames(activeTab === JOB_SEARCH && styles.activeTab)} > {linkRenderer({ 'data-analytics': 'header:jobs', className: styles.item, href: '/', children: [ newBadgeTab === JOB_SEARCH && <BadgeComponent />, <span key="label">{JOB_SEARCH}</span>, <SearchIcon key="icon" className={classnames(styles.icon, styles.jobSearch)} svgClassName={styles.iconSvg} /> ] })} </Hidden> <li className={classnames(activeTab === PROFILE && styles.activeTab)}> {linkRenderer({ 'data-analytics': 'header:profile', className: styles.item, href: '/profile/', children: [ newBadgeTab === PROFILE && <BadgeComponent />, <span key="label">{PROFILE}</span>, <ProfileIcon key="icon" className={classnames(styles.icon, styles.profile)} svgClassName={styles.iconSvg} /> ] })} </li> <li className={classnames(activeTab === SAVED_SEARCHES && styles.activeTab)} > {linkRenderer({ 'data-analytics': 'header:saved+searches', className: styles.item, href: '/my-activity/saved-searches', children: [ <span key="label">{SAVED_SEARCHES}</span>, <HeartIcon key="icon" className={classnames(styles.icon, styles.saveSearches)} svgClassName={styles.iconSvg} /> ] })} </li> <li className={classnames( activeTab === SAVED_AND_APPLIED && styles.activeTab )} > {linkRenderer({ 'data-analytics': 'header:saved+jobs', className: styles.item, href: urlForAuthStatus(authenticationStatus, '/my-activity/saved-jobs'), children: [ newBadgeTab === SAVED_AND_APPLIED && <BadgeComponent />, <span key="label"> Saved <Hidden desktop>& Applied </Hidden>Jobs </span>, <StarIcon key="icon" className={classnames(styles.icon, styles.saveJobs)} svgClassName={styles.iconSvg} /> ] })} </li> <Hidden mobile component="li" className={classnames(activeTab === APPLIED_JOBS && styles.activeTab)} > {linkRenderer({ 'data-analytics': 'header:applied+jobs', className: styles.item, href: urlForAuthStatus( authenticationStatus, '/my-activity/applied-jobs' ), children: [ newBadgeTab === APPLIED_JOBS && <BadgeComponent />, <span key="label">{APPLIED_JOBS}</span>, <TickCircleIcon key="icon" className={classnames(styles.icon, styles.appliedJobs)} svgClassName={styles.iconSvg} /> ] })} </Hidden> <li className={classnames(activeTab === RECOMMENDED_JOBS && styles.activeTab)} > {linkRenderer({ 'data-analytics': 'header:recommended+jobs', className: styles.item, href: urlForAuthStatus(authenticationStatus, '/recommended'), children: [ newBadgeTab === RECOMMENDED_JOBS && <BadgeComponent />, <span key="label">{RECOMMENDED_JOBS}</span>, <ThumbsUpIcon key="icon" className={classnames(styles.icon, styles.recommendedJobs)} svgClassName={styles.iconSvg} /> ] })} </li> <Hidden mobile component="hr" className={styles.menuSeparator} /> {locale === 'NZ' ? null : ( <Hidden desktop component="li" className={classnames(activeTab === CAREER_ADVICE && styles.activeTab)} > {linkRenderer({ 'data-analytics': 'header:advice', className: styles.item, href: '/career-advice/', children: [ newBadgeTab === CAREER_ADVICE && <BadgeComponent />, CAREER_ADVICE, <ArticleIcon key="icon" className={styles.icon} svgClassName={styles.caSvg} /> ] })} </Hidden> )} <Hidden mobile component="li" className={classnames(activeTab === SETTINGS && styles.activeTab)} > {linkRenderer({ 'data-analytics': 'header:settings', className: styles.item, href: '/settings/', children: SETTINGS })} </Hidden> {(() => { switch (authenticationStatus) { case UNAUTHENTICATED: return ( <Hidden desktop component="li" className={styles.firstItemInGroup}> <span className={styles.item}> {linkRenderer({ 'data-analytics': 'header:sign-in', href: appendReturnUrl('/sign-in', returnUrl), className: styles.itemLink, title: 'Sign in', children: 'Sign in' })} <span className={styles.secondaryItemText}>&nbsp;or&nbsp;</span> {linkRenderer({ 'data-analytics': 'header:register', href: appendReturnUrl('/sign-up', returnUrl), className: styles.itemLink, title: 'Register', children: 'Register' })} <div className={styles.iconSpacer} /> </span> </Hidden> ); case AUTHENTICATED: return ( <Fragment> <Hidden desktop component="li" className={classnames( activeTab === SETTINGS && styles.activeTab, styles.firstItemInGroup )} > {linkRenderer({ 'data-analytics': 'header:settings', className: styles.item, href: '/settings/', children: [ SETTINGS, <div key="iconSpacer" className={styles.iconSpacer} /> ] })} </Hidden> <Hidden desktop component="li"> {linkRenderer({ 'data-analytics': 'header:sign-out', className: styles.item, onClick: clearLocalStorage, href: returnUrl ? appendReturnUrl('/login/LogoutWithReturnUrl', returnUrl) : '/Login/Logout', children: [ 'Sign Out', <div key="iconSpacer" className={styles.iconSpacer} /> ] })} </Hidden> </Fragment> ); default: return ( <span className={classnames(styles.item, styles.pendingAuth)}> <Loader inline xsmall /> <Hidden desktop key="iconSpacer" className={styles.iconSpacer} /> </span> ); } })()} {locale === 'NZ' ? null : ( <Hidden desktop component="li" className={classnames( activeTab === COMPANY_REVIEWS && styles.activeTab, styles.firstItemInGroup )} > {linkRenderer({ 'data-analytics': 'header:companies', className: styles.item, href: '/companies/', children: [ newBadgeTab === COMPANY_REVIEWS && <BadgeComponent />, COMPANY_REVIEWS, <div key="iconSpacer" className={styles.iconSpacer} /> ] })} </Hidden> )} <Hidden desktop component="li" className={classnames(locale === 'NZ' && styles.firstItemInGroup)} > {linkRenderer({ 'data-analytics': 'header:employer+site', className: styles.item, href: employerLinkForLocale(locale), children: [ 'Employer Site', <div key="iconSpacer" className={styles.iconSpacer} /> ] })} </Hidden> <Hidden desktop component="li"> {linkRenderer({ 'data-analytics': 'header:courses', className: styles.item, href: 'https://www.seek.com.au/learning/', children: [ 'Courses', <div key="iconSpacer" className={styles.iconSpacer} /> ] })} </Hidden> {authenticationStatus === AUTHENTICATED ? ( <Hidden mobile component="li"> {linkRenderer({ 'data-analytics': 'header:sign-out', className: styles.item, onClick: clearLocalStorage, href: returnUrl ? appendReturnUrl('/login/LogoutWithReturnUrl', returnUrl) : '/Login/Logout', children: 'Sign Out' })} </Hidden> ) : null} </ul> ); <file_sep>import React from 'react'; import { render } from 'react-dom'; import StandaloneProvider from './StandaloneProvider/StandaloneProvider'; export default (Component, defaultProps = {}) => (el, props) => { if (typeof Component.displayName !== 'string') { throw new Error('Component must have a display name'); } let updateProps; const registerPropsUpdater = propsUpdater => { updateProps = propsUpdater; }; const renderTarget = el || document.getElementById(`__SSG_${Component.displayName}__`); const initialProps = props || window[`__SSG_${Component.displayName}_props__`] || {}; render( <StandaloneProvider component={Component} initialProps={{ ...defaultProps, ...initialProps }} registerPropsUpdater={registerPropsUpdater} />, renderTarget ); return { updateProps }; }; <file_sep>import React from 'react'; import { renderToString } from 'react-dom/server'; import dedent from 'dedent'; import serialize from 'serialize-javascript'; import { minify } from 'html-minifier'; import StandaloneProvider from './StandaloneProvider/StandaloneProvider'; import Header from 'seek-style-guide/react/Header/Header'; import Footer from 'seek-style-guide/react/Footer/Footer'; const renderHtml = (Component, initialProps, options = { preview: false }) => { const componentHtml = renderToString( <StandaloneProvider component={Component} initialProps={initialProps} registerPropsUpdater={() => {}} /> ); const html = ` ${ !options.preview ? '' : ` <!DOCTYPE html> <head> <style type="text/css">html,body{padding:0;margin:0;}</style> <link rel="stylesheet" type="text/css" href="styles.css" /> </head> <body> ` } <div id="__SSG_${Component.displayName}__">${componentHtml}</div> <script type="text/javascript">window.__SSG_${ Component.displayName }_props__ = ${serialize(initialProps)}</script> ${ !options.preview ? '' : dedent` <script type="text/javascript" src="client.js"></script> <script type="text/javascript"> // Create the instance window.seek${Component.displayName}Instance = SeekHeaderFooter.render${ Component.displayName }(); // Simulate authenticating the user seek${ Component.displayName }Instance.updateProps({ authenticationStatus: 'authenticated', userName: 'Olivia' }); // Let developers know what's up console.log("The standalone ${Component.displayName.toLowerCase()} instance is available as 'window.seek${ Component.displayName }Instance'"); </script> </body> ` } `; return minify(html, { collapseWhitespace: true }); }; const renderFileForLocale = (Component, props, locale) => { if (typeof Component.displayName !== 'string') { throw new Error('Component must have a display name'); } const tabSuffix = !props.activeTab ? '' : `__${props.activeTab .toLowerCase() .replace(/ /g, '_') .replace('$', '') .replace('&', 'and')}`; const fileName = `${Component.displayName.toLowerCase()}__${locale.toLowerCase()}${tabSuffix}`; const localeProps = locale !== 'AU' ? { locale } : {}; const renderProps = { ...props, ...localeProps }; return { [`/${fileName}.html`]: renderHtml(Component, renderProps), [`/${fileName}__preview.html`]: renderHtml(Component, renderProps, { preview: true }) }; }; const renderFiles = (Component, props = {}) => { return { ...renderFileForLocale(Component, props, 'AU'), ...renderFileForLocale(Component, props, 'NZ') }; }; export default () => ({ ...renderFiles(Header), ...renderFiles(Header, { activeTab: 'Career Advice' }), ...renderFiles(Header, { activeTab: 'Advice & Tips' }), // Render old Advice & Tips files to maintain backwards compatibility ...renderFiles(Footer) }); <file_sep>import React, { Component } from 'react'; import PropTypes from 'prop-types'; import styles from './StandaloneProvider.less'; import cssSelectorPrefix from '../../cssSelectorPrefix'; export default class StandaloneProvider extends Component { static propTypes = { component: PropTypes.func.isRequired, registerPropsUpdater: PropTypes.func.isRequired, initialProps: PropTypes.object }; constructor(props) { super(props); this.props.registerPropsUpdater(this.updateProps.bind(this)); this.state = { componentProps: this.props.initialProps }; } updateProps(componentProps) { this.setState({ componentProps: { ...this.state.componentProps, ...componentProps } }); } render() { const { component: StandaloneComponent } = this.props; const { componentProps } = this.state; return ( <div className={cssSelectorPrefix.replace('.', '')}> <div className={styles.root}> <StandaloneComponent {...componentProps} /> </div> </div> ); } } <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import generateStructureDataSchema from './generate-structured-data-schema'; /* eslint-disable react/no-danger */ const StructuredDataSchema = ({ locale }) => ( <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(generateStructureDataSchema(locale)) }} /> ); /* eslint-enable react/no-danger */ StructuredDataSchema.propTypes = { locale: PropTypes.oneOf(['AU', 'NZ']) }; StructuredDataSchema.defaultProps = { locale: 'AU' }; export default StructuredDataSchema; <file_sep>import styles from './Header.less'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import PartnerSites from '../PartnerSites/PartnerSites'; import Logo from '../Logo/Logo'; import Navigation from './Navigation/Navigation'; import Hidden from '../Hidden/Hidden'; import ScreenReaderOnly from '../ScreenReaderOnly/ScreenReaderOnly'; import SignInRegister from './SignInRegister/SignInRegister'; import UserAccount from './UserAccount/UserAccount'; import employerLinkForLocale from './employerLinkForLocale'; import StructuredDataSchema from './StructuredDataSchema/StructuredDataSchema'; import { AUTHENTICATED, UNAUTHENTICATED, AUTH_PENDING } from '../private/authStatusTypes'; const handleLegacyTabName = tabName => tabName === 'Advice & Tips' ? 'Career Advice' : tabName; const defaultLinkRenderer = props => <a {...props} />; const tabNames = [ 'Job Search', 'Profile', 'Saved & Applied Jobs', 'Recommended Jobs', 'Company Reviews', 'Career Advice', 'Advice & Tips' // Backwards compatible name for 'Career Advice' ]; const allowedBadgeTabs = [...tabNames, null]; export default function Header({ logoComponent: LogoComponent, newBadgeTab: newBadgeTabProp, activeTab: activeTabProp, locale, authenticationStatus, userName, userEmail, linkRenderer, divider, returnUrl, onMenuToggle = () => {} }) { const activeTab = handleLegacyTabName(activeTabProp); const newBadgeTab = handleLegacyTabName(newBadgeTabProp); const isAuthenticated = authenticationStatus === AUTHENTICATED && (userName || userEmail); const isUnauthenticated = authenticationStatus === UNAUTHENTICATED; const userClasses = classnames({ [styles.user]: true, [styles.user_isAuthenticated]: isAuthenticated, [styles.user_isUnauthenticated]: isUnauthenticated, [styles.user_isReady]: isUnauthenticated || isAuthenticated }); const displayName = userName || userEmail.split('@')[0]; return ( <header className={styles.root} role="banner"> <StructuredDataSchema locale={locale} /> <div className={styles.content}> <div className={styles.banner}> <div data-automation="logo" className={styles.logo}> <LogoComponent locale={locale} svgClassName={styles.logoSvg} /> {linkRenderer({ 'data-analytics': 'header:jobs', className: styles.logoLink, href: '/', children: <ScreenReaderOnly>SEEK</ScreenReaderOnly> })} </div> <Hidden screen className={styles.logoNote}> Australia’s #1 job site </Hidden> <Hidden print className={styles.userWrapper}> <div className={userClasses}> <div className={styles.userAccountWrapper}> <UserAccount locale={locale} authenticationStatus={authenticationStatus} userName={displayName} linkRenderer={linkRenderer} returnUrl={returnUrl} activeTab={activeTab} newBadgeTab={newBadgeTab} onMenuToggle={onMenuToggle} /> </div> <div className={styles.signInRegisterWrapper}> <SignInRegister linkRenderer={linkRenderer} returnUrl={returnUrl} /> </div> <span className={styles.divider} /> </div> <div className={styles.employerSite}> {linkRenderer({ 'data-analytics': 'header:employer+site', className: styles.employerLink, href: employerLinkForLocale(locale), children: 'Employer site' })} </div> </Hidden> </div> <Hidden print className={styles.navigation}> <Navigation locale={locale} linkRenderer={linkRenderer} activeTab={activeTab} newBadgeTab={newBadgeTab} divider={divider} /> </Hidden> <div className={styles.topBanner}> <PartnerSites locale={locale} linkRenderer={linkRenderer} activeSite="Jobs" /> </div> </div> </header> ); } Header.propTypes = { locale: PropTypes.oneOf(['AU', 'NZ']), logoComponent: PropTypes.oneOfType([ PropTypes.instanceOf(Component), PropTypes.func ]), authenticationStatus: PropTypes.oneOf([ AUTHENTICATED, UNAUTHENTICATED, AUTH_PENDING ]), userName: PropTypes.string, userEmail: PropTypes.string, linkRenderer: PropTypes.func, activeTab: PropTypes.oneOf(tabNames), newBadgeTab: PropTypes.oneOf(allowedBadgeTabs), divider: PropTypes.bool, returnUrl: PropTypes.string, onMenuToggle: PropTypes.func }; Header.defaultProps = { locale: 'AU', logoComponent: Logo, linkRenderer: defaultLinkRenderer, authenticationStatus: AUTH_PENDING, activeTab: null, newBadgeTab: null, divider: true, userEmail: '' }; <file_sep>import React, { Component } from 'react'; import PropTypes from 'prop-types'; import ChevronIcon from '../../ChevronIcon/ChevronIcon'; import Hidden from '../../Hidden/Hidden'; import ScreenReaderOnly from '../../ScreenReaderOnly/ScreenReaderOnly'; import UserAccountMenu from '../UserAccountMenu/UserAccountMenu'; import { AUTHENTICATED, UNAUTHENTICATED, AUTH_PENDING } from '../../private/authStatusTypes'; import styles from './UserAccount.less'; const calculateMobileMenuLabel = (authenticationStatus, userName) => { if (authenticationStatus === AUTH_PENDING) { return ''; } if (authenticationStatus === AUTHENTICATED) { return userName; } return 'Menu'; }; export default class UserAccount extends Component { static propTypes = { locale: PropTypes.oneOf(['AU', 'NZ']), authenticationStatus: PropTypes.oneOf([ AUTHENTICATED, UNAUTHENTICATED, AUTH_PENDING ]), userName: PropTypes.string, linkRenderer: PropTypes.func.isRequired, returnUrl: PropTypes.string, activeTab: PropTypes.string, newBadgeTab: PropTypes.string, onMenuToggle: PropTypes.func }; static defaultProps = { onMenuToggle: () => {} }; constructor(props) { super(props); this.state = { menuOpen: false }; } handleMenuToggle = () => { this.setState(state => { this.props.onMenuToggle({ open: !state.menuOpen }); return { menuOpen: !state.menuOpen }; }); }; handleMenuClick = () => { this.setState({ menuOpen: false }); }; render() { const { locale, authenticationStatus, userName, linkRenderer, returnUrl, activeTab, newBadgeTab } = this.props; const mobileMenuLabel = calculateMobileMenuLabel( authenticationStatus, userName ); const desktopMenuLabel = userName; return ( <nav aria-label="my account" role="navigation" data-automation="user-account" className={styles.root} > <input id="user-account-menu-toggle" autoComplete="off" className={styles.toggle} type="checkbox" checked={this.state.menuOpen} onChange={this.handleMenuToggle} /> <div className={styles.menuBackdrop}> <label data-automation="user-account-menu-backdrop" htmlFor="user-account-menu-toggle" className={styles.menuBackdropLabel} > <ScreenReaderOnly>Show user menu</ScreenReaderOnly> </label> </div> <label data-automation="user-account-menu-toggle" className={styles.toggleLabel} htmlFor="user-account-menu-toggle" > <ScreenReaderOnly>Show user menu</ScreenReaderOnly> <span data-hj-masked={true}> <Hidden desktop className={styles.menuLabel}> {mobileMenuLabel} </Hidden> <Hidden mobile className={styles.menuLabel} data-automation="user-account-name" > {desktopMenuLabel} </Hidden> </span> <ChevronIcon direction="down" className={styles.chevron} svgClassName={styles.chevronSvg} /> </label> <div onClick={this.handleMenuClick} className={styles.toggleContainer}> <UserAccountMenu locale={locale} authenticationStatus={authenticationStatus} linkRenderer={linkRenderer} returnUrl={returnUrl} activeTab={activeTab} newBadgeTab={newBadgeTab} /> </div> </nav> ); } } <file_sep>import { Footer } from 'seek-style-guide/react'; import * as sketch from './Footer.sketch'; import { makeDummyLinkRendererForPath } from '../Header/Header.demo'; const ROUTE = '/footer'; export default { route: '/footer', title: 'Footer', category: 'Layout', component: Footer, sketch, initialProps: { authenticationStatus: 'authenticated', linkRenderer: makeDummyLinkRendererForPath(ROUTE) }, options: [ { label: 'Locale', type: 'radio', states: [ { label: 'AU', transformProps: props => props }, { label: 'NZ', transformProps: props => ({ ...props, locale: 'NZ' }) } ] }, { label: 'Authentication', type: 'radio', states: [ { label: 'Authenticated', transformProps: props => props }, { label: 'Unauthenticated', transformProps: props => ({ ...props, authenticationStatus: 'unauthenticated' }) }, { label: 'Pending', transformProps: props => ({ ...props, authenticationStatus: 'pending' }) } ] }, { type: 'checklist', label: 'States', states: [ { label: 'Promo', transformProps: props => ({ ...props, promo: true }) } ] } ] };
605989d8faee20e00d5c8c8d4ec8ff3ba1ff6607
[ "JavaScript" ]
16
JavaScript
chronotc/seek-style-guide
e225ca3d99f55f08833593132af9ec609288b19a
d8af1abe7a74f7aa5f9519442f462d15197b5e98
refs/heads/master
<file_sep>import java.util.Scanner; public class PakuriProgram { public static void main(String[] args) { // variable dump int pakudexCapacity = -1; int menuInput; // scanner Scanner scanny = new Scanner(System.in); // display welcome message System.out.print("Welcome to Pakudex: Tracker Extraordinaire!\n"); // prompt for capacity while (true) { System.out.print("Enter max capacity of the Pakudex: "); if (scanny.hasNextInt()) { pakudexCapacity = scanny.nextInt(); } else { pakudexCapacity = -1; scanny.next(); } if (pakudexCapacity > 0) { break; } else { System.out.println("Please enter a valid size."); } } System.out.println("The Pakudex can hold " + pakudexCapacity + " species of Pakuri.\n"); // IMPORTANT Pakudex pakudex = new Pakudex(pakudexCapacity); while(true) { System.out.print("Pakudex Main Menu\n" + "-----------------\n" + "1. List Pakuri\n" + "2. Show Pakuri\n" + "3. Add Pakuri\n" + "4. Evolve Pakuri\n" + "5. Sort Pakuri\n" + "6. Exit\n\n" + "What would you like to do? "); try { menuInput = scanny.nextInt(); } catch (Exception e) { menuInput = -1; scanny.next(); } switch (menuInput) { default: System.out.println("Unrecognized menu selection!\n"); break; case 1: // List Pakuri String[] currentCollection = pakudex.getSpeciesArray(); if (currentCollection == null) { System.out.println("No Pakuri in Pakudex yet!\n"); } else { System.out.println("Pakuri In Pakudex:"); for (int i = 0; i < currentCollection.length; i++) { System.out.println((i + 1) + ". " + currentCollection[i]); } System.out.println(""); } break; case 2: // Show Pakuri System.out.print("Enter the name of the species to display: "); String pakuriName = scanny.next(); int[] currentStats = pakudex.getStats(pakuriName); if (currentStats == null) { System.out.println("Error: No such Pakuri!\n"); break; } System.out.println("\nSpecies: " + pakuriName + "\n" + "Attack: " + currentStats[0] + "\n" + "Defense: " + currentStats[1] + "\n" + "Speed: " + currentStats[2] + "\n"); break; case 3: // Add Pakuri if (pakudex.getCapacity() == pakudex.getSize()) { System.out.println("Error: Pakudex is full!\n"); break; } System.out.print("Enter the name of the species to add: "); String addedPakuri = scanny.next(); if (pakudex.addPakuri(addedPakuri)) { System.out.println("Pakuri species " + addedPakuri + " successfully added!\n"); } else { System.out.println("Error: Pakudex already contains this species!\n"); } break; case 4: // Evolve Pakuri System.out.print("Enter the name of the species to evolve: "); String speciesToEvolve = scanny.next(); if (pakudex.evolveSpecies(speciesToEvolve)) { System.out.println(speciesToEvolve + " has evolved!\n"); } else { System.out.println("Error: No such Pakuri!\n"); } break; case 5: // Sort Pakuri pakudex.sortPakuri(); System.out.println("Pakuri have been sorted!\n"); break; case 6: System.out.print("Thanks for using Pakudex! Bye!"); return; } } } }
d892ac6d234649ad01e321aac70c43e000ee8ac5
[ "Java" ]
1
Java
vertease/Off-Brand_Pokedex
a68d359a8e26aba269fd5fe0a73c14c5424d36c6
b7071ea379b0a5e306b8d8814cfd612cece17d5d
refs/heads/master
<repo_name>MDShields7/fetch-the-news<file_sep>/src/components/Guest_Party_Nav/GP_Nav.js import React, { Component } from 'react'; import {connect} from 'react-redux'; import socketIOClient from 'socket.io-client'; const socket = socketIOClient("http://192.168.1.5:4000/"); class GP_Nav extends Component { constructor(props){ super(props); this.state ={ user: props.user, room: props.room, userList: [], } socket.emit('join user', { user: this.state.user.toLowerCase(), room: this.state.room.toLowerCase() }) socket.on('user joined', (userJoin) => { socket.join(userJoin.room) console.log(`${this.state.user} joined a game in room ${this.state.room}`); }) socket.on('joined', (joined) => { console.log('GP_Nav.js, before setState', this.state.userList) console.log('GP_Nav.js, joined.userList', this.state.userList) this.setState({ room: joined.room, userList: joined.userList}) console.log(`The user list is ${this.state.userList} in room, ${this.state.room}`) }) } socketTestBtn = () => { console.log('socket test button clicked!'); socket.emit('test', {message: 'This is a test'}) } render() { console.log('GP_Nav, this.state', this.state) return ( <div> <h1>GP_Nav</h1> <h2>Guest Party Navigation</h2> <button onClick={this.socketTestBtn}>Test Socket</button> </div> ) } } function mapStateToProps( state ){ const {room, user} = state; return { room, user, }; } export default connect (mapStateToProps)(GP_Nav); <file_sep>/src/App.js import React, { Component } from 'react'; import {connect} from 'react-redux'; import './App.css'; // import socketIOClient from 'socket.io-client'; import HLogin from './components/Host_Nav/H_Login'; import HNav from './components/Host_Nav/H_Nav'; import HPNav from './components/Host_Party_Nav/HP_Nav'; import GPLogin from './components/Guest_Party_Nav/GP_Login'; import GPNav from './components/Guest_Party_Nav/GP_Nav'; // const socket = socketIOClient(); class App extends Component { constructor(props){ super(props); this.state ={ room: '', user: '', userList: [], host: '', } } componentDidMount(){ } componentDidUpdate(prevProps) { if (this.props !== prevProps) { this.setState({ room: this.props.room, user: this.props.user, host: this.props.host, }) } } stateBtn = () => { console.log(this.state); } render() { console.log('App.js, this.state', this.state) const {room, host, user, userList} = this.state; //HOST VIEW FLOW const hostView = () => { if(!host){ return <HLogin/> } else if ( host && !room ) { return <HNav/> } else if (host && room) { return <HPNav/> } }; // GUEST (user) VIEW FLOW const guestView = (() => { if (!room) { return <GPLogin/> } else if ( room && user ) { return <GPNav/> } }); return ( <div className="App"> <h1>App</h1> {/* <div>`Host is ${this.props.host}`</div> */} <div>`Room is ${this.props.room}`</div> <button onClick={this.stateBtn}>Check App.js State</button> <div className='Laptop'>{hostView()}</div> <div className='Phone'>{guestView()}</div> </div> ); } } function mapStateToProps( state ){ const {room, host, user} = state; return { room, host, user }; } export default connect (mapStateToProps)(App); <file_sep>/src/components/Host_Party_Nav/HP_Nav.js import React, { Component } from 'react'; import {connect} from 'react-redux'; import socketIOClient from 'socket.io-client'; const socket = socketIOClient("http://192.168.1.5:4000/"); class HP_Nav extends Component { constructor(props){ super(props); this.state ={ host: props.host, room: props.room, userList: [], } socket.emit('join host', { host: this.state.host.toLowerCase(), room: this.state.room.toLowerCase() }) socket.on('host joined', (hostJoin) => { socket.join(hostJoin.room) console.log(`${this.state.host} started a game in room ${this.state.room}`); }) socket.on('joined', (joined) => { console.log('HP_Nav.js, before setState') this.setState({ room: joined.room, userList: joined.userList}) console.log(`The user list is ${this.state.userList} in room, ${this.state.room}`) }) } socketTestBtn = () => { console.log('socket test button clicked!'); socket.emit('test', {message: 'This is a test'}) } render() { // console.log('HPNav, this.props', this.props) console.log('HP_Nav, this.state', this.state) return ( <div> <h1>Host Party Nav</h1> <h2>Players go to .... to log in</h2> <button onClick={this.socketTestBtn}>Test Socket</button> </div> ) } } function mapStateToProps( state ){ const {room, host} = state; return { room, host }; } export default connect (mapStateToProps)(HP_Nav); <file_sep>/src/ducks/reducer.js const initialState = { host: '', // Host - only assigned from laptop view room: '', // Typed by host rndLimit: 3, // Round, set by host in lobby rndCurrent: null, // Round, set during game user: '', // User { id:#, avName:'', avPhoto:'url' } userList: [], // List of playing users userScoreList: [], // Scores - only party mode newsAllList: [], // Lists available to play newsPlayingList: [], // List played in party mode avatarList: [], // Hard-coded items } const UPDATE_HOST = 'UPDATE_HOST'; const UPDATE_ROOM = 'UPDATE_ROOM'; const UPDATE_RND_LIMIT = 'UPDATE_RND_LIMIT'; const UPDATE_RND_CURRENT = 'UPDATE_RND_CURRENT'; const UPDATE_USER = 'UPDATE_USER'; const UPDATE_USER_LIST = 'UPDATE_USER_LIST'; const UPDATE_USER_SCORE_LIST = 'UPDATE_USER_SCORE_LIST'; const UPDATE_NEWS_ALL_LIST = 'NEWS_ALL_LIST'; const UPDATE_NEWS_PLAYING_LIST = 'NEWS_PLAYING_LIST'; function reducer( state = initialState, action){ switch(action.type){ case UPDATE_HOST: return Object.assign({},state, {host: action.payload}) case UPDATE_ROOM: return Object.assign({},state, {room: action.payload}) case UPDATE_RND_LIMIT: return Object.assign({},state, {rndLimit: action.payload}) case UPDATE_RND_CURRENT: return Object.assign({},state, {rndCurrent: action.payload}) case UPDATE_USER: return Object.assign({}, state, {user: action.payload}) case UPDATE_USER_LIST: return Object.assign({}, state, {userList: action.payload}) case UPDATE_USER_SCORE_LIST: return Object.assign({}, state, {userScoreList: action.payload}) case UPDATE_NEWS_ALL_LIST: return Object.assign({}, state, {newsAllList: action.payload}) case UPDATE_NEWS_PLAYING_LIST: return Object.assign({}, state, {newsPlayingList: action.payload}) default: return state; } } export function updateHost ( host ){ return { type: UPDATE_HOST, payload: host } } export function updateRoom ( room ){ return { type: UPDATE_ROOM, payload: room } } export function updateRndLimit ( rndLimit ){ return { type: UPDATE_RND_LIMIT, payload: rndLimit } } export function updateLoanType ( rndCurrent ){ return { type: UPDATE_RND_CURRENT, payload: rndCurrent } } export function updateUser ( user ){ return { type: UPDATE_USER, payload: user } } export function updateUserList ( userList ){ return { type: UPDATE_USER_LIST, payload: userList } } export function updateUserScoreList ( userScoreList ){ return { type: UPDATE_USER_SCORE_LIST, payload: userScoreList } } export function updateNewsAllList ( newsAllList ){ return { type: UPDATE_NEWS_ALL_LIST, payload: newsAllList } } export function updateNewsPlayingList ( newsPlayingList ){ return { type: UPDATE_NEWS_PLAYING_LIST, payload: newsPlayingList } } export default reducer;<file_sep>/server/index.js const express = require('express'); const app = express(); const server = require('http').createServer(app) const bodyParser = require('body-parser'); const io = require('socket.io')(server) var host = ''; var room = 'hi'; var userList = []; let counter = 0; //[{ host:true, avatar_image:'Fluffy_url', avatar_name:'Fluffy', totalScore:150, roundScore:50 }, {}, {} ] // function createUser (joinUserObj){ // return // } function User (host, room, user, avatar_image, avatar_color, roundScore, currentScore) { this.host = host; this.user = user; this.avatar_name = avatar_name; this.avatar_image = avatar_image; this.roundScore = roundScore; this.currentScore = currentScore; } io.sockets.on('connection', (socket) =>{ console.log(socket) // console.log('the room is "', room, '"') // console.log(`user connected, ${socket['id']}`); // socket.on('test', message => { // console.log(`${message.message}`); // }) socket.on('join host', (join) => { console.log('host', join.host, 'enters room', join.room); if (join.host) { host = join.host; room = join.room } }); socket.on('join user', (join) => { socket.join.id = counter; socket.join.user = join.user; console.log('user', join.user, 'enters room', join.room, 'id', socket.join.id); if (join.user) { let newUser = { id: counter, host: null, user: join.user, // avatar_name: join.avatar_name, avatar_image: join.avatar_image, avatar_color: join.avatar_color, roundScore: 0, currentScore: 0, }; counter++; !userList[0] ? newUser.host=true :newUser.host=false userList.push(newUser); } socket.join(join.room); io.in(join.room).emit("joined", {room: room, userList: userList}) // console.log('put in room') // socket.emit('joined', (joined) => { // this.state.userList = join.userList; // console.log(`In room, ${this.state.room}, the user list is ${this.state.userList}`) // }) }); socket.on('disconnect', () => { for (i = userList.length-1; i>=0; i--){ // console.log(userList,userList[i]) if (userList[i]['id'] === socket.join.id){ // console.log('before list length', userList.length, userList) userList.splice(i, 1) } } // console.log('after splice list length', userList.length, userList) // console.log(`user disconnected, ${socket['id']}`) console.log('user', socket.join.user, ', id', socket.join.id, 'disconnected', '.', userList.length, 'users still in room') if(userList[0] ){room = ''} }) }) const PORT = 4000; server.listen(PORT, ()=> console.log(`Server listening on port PORT`));<file_sep>/src/components/Guest_Party_Nav/GP_Lobby/GP_Lobby.js import React, { Component } from 'react'; import './GP_Lobby.css'; // import selectAvatar from '../GP_Login'; // import styled from 'styled-components'; export default class GP_Lobby extends Component { constructor(props){ super(props); // this.chooseDog = this.chooseDog.bind(this); } // chooseDog = (e) => { // console.log(e.target.name) // this.props.selectAvatar(e.target.name) // } render() { const avatarList = [ {name: "fluffy", photo: 'https://cdn.pixabay.com/photo/2014/03/14/20/13/dog-287420_1280.jpg', color: 'orange'}, {name: "wilco", photo: 'https://cdn.pixabay.com/photo/2016/05/09/10/42/weimaraner-1381186_1280.jpg', color: 'dodgerBlue'}, {name: "lincoln", photo: 'https://cdn.pixabay.com/photo/2014/04/05/11/40/dog-316598_1280.jpg', color: 'slateBlue'}, {name: "bear", photo: 'https://cdn.pixabay.com/photo/2016/03/09/15/21/dog-1246610_1280.jpg', color: 'yellow'}, {name: "schnapps", photo: 'https://cdn.pixabay.com/photo/2018/05/07/10/48/husky-3380548_1280.jpg', color: 'forestGreen'}, {name: "flower", photo: 'https://cdn.pixabay.com/photo/2018/03/31/06/31/dog-3277416_1280.jpg', color: 'tomato'}, {name: "fiji", photo: 'https://cdn.pixabay.com/photo/2014/05/03/01/04/puppy-336707_1280.jpg', color: 'royalBlue'}, {name: "nibbles", photo: 'https://cdn.pixabay.com/photo/2015/11/17/13/13/dogue-de-bordeaux-1047521_1280.jpg', color: 'deepPink'}, ] const dogs = avatarList.map( (elem) =>{ let styles = { borderColor: elem.color, } let id = elem.id; let name = elem.name; let photo = elem.photo; let color = elem.color; let group = [name, photo, color] return ( <div className='dogsCard'> <img src={photo} alt="" key={id} border='15px' style={styles} name={group} onClick={() =>this.props.selectAvatar(group)}/> {/* <div>{name}</div> */} {/* <button bsSize='large' >{elem.name}</button> */} </div> ) }) console.log('GP_Lobby,dogs', dogs) return ( <div className='mapDogs'> {/* <div>GP_Lobby</div> */} {dogs} </div> ) } } <file_sep>/src/components/Host_Nav/H_Login.js import React, { Component } from 'react'; import {connect} from 'react-redux'; import {updateRoom, updateHost} from '../../ducks/reducer'; class H_Login extends Component { constructor(props){ super(props); this.state ={ room: '', host: '' } } handleChange = (e) => { const name = e.target.name const value = e.target.value this.setState({[name]: value}) } handleSubmit = () => { // console.log(this.props.updateHost, typeof this.props.updateHost) this.props.updateHost(this.state.host); this.props.updateRoom(this.state.room); } render() { const {host, room} = this.state; return ( <div> <h1>Host Login</h1> <h2>Room Name:</h2> <input type="text" name={'room'} value={room} onChange={this.handleChange}/> <h2>Host username:</h2> <input type="text" name={'host'} value={host} onChange={this.handleChange}/> <button onClick={this.handleSubmit}>Submit</button> </div> ) } } function mapStateToProps( state ){ const {room, host} = state; return { room, host }; } export default connect (mapStateToProps, {updateRoom, updateHost})(H_Login);
26fc6567f6d73b2d973f61274d580f60d2c879c0
[ "JavaScript" ]
7
JavaScript
MDShields7/fetch-the-news
1266ff0ce2a4f15eec0aeaa62f292f1fa49f346b
74635292bd5d303f54d758fcda7e87e06321c9e6
refs/heads/master
<file_sep>package com.sw.view; import java.util.ArrayList; import javax.swing.JButton; import javax.swing.JTable; import javax.swing.JTextField; /** * * @author Me */ public class PrendasInterfaz extends javax.swing.JFrame { public PrendasInterfaz() { initWindow(); initMyComponents(); initComponents(); } private void initWindow() { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { System.out.println(ex.getMessage()); } //</editor-fold> } private void initMyComponents() { eliminar = new ArrayList<>(); } /** * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this method is always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { scrollPrendas = new javax.swing.JScrollPane(); prendas = new javax.swing.JTable(); addPrenda = new javax.swing.JButton(); totalKgLabel = new javax.swing.JLabel(); precioTotalLabel = new javax.swing.JLabel(); piezasLabel = new javax.swing.JLabel(); totalKg = new javax.swing.JTextField(); totalPrecio = new javax.swing.JTextField(); totalPiezas = new javax.swing.JTextField(); logo = new javax.swing.JLabel(); editarPrenda = new javax.swing.JButton(); fondo = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Añadir prendas"); setMaximumSize(new java.awt.Dimension(579, 690)); setMinimumSize(new java.awt.Dimension(579, 690)); setName("prendasInterfaz"); // NOI18N setPreferredSize(new java.awt.Dimension(579, 690)); setResizable(false); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); scrollPrendas.setMaximumSize(new java.awt.Dimension(575, 555)); scrollPrendas.setMinimumSize(new java.awt.Dimension(575, 555)); scrollPrendas.setPreferredSize(new java.awt.Dimension(575, 555)); prendas.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, }, new String [] { null, null, null, null } ) { Class[] types = new Class [] { java.lang.Object.class, Object.class, java.lang.Integer.class, Object.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); scrollPrendas.setViewportView(prendas); getContentPane().add(scrollPrendas, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 110, -1, -1)); addPrenda.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/src/images/add.png"))); // NOI18N addPrenda.setToolTipText("Añadir nueva prenda"); addPrenda.setActionCommand("addPrenda"); addPrenda.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 3, true)); addPrenda.setMaximumSize(new java.awt.Dimension(100, 80)); addPrenda.setMinimumSize(new java.awt.Dimension(100, 80)); getContentPane().add(addPrenda, new org.netbeans.lib.awtextra.AbsoluteConstraints(470, 10, 100, 40)); totalKgLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); totalKgLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/src/images/kilos.png"))); // NOI18N totalKgLabel.setText(" Total kg :"); totalKgLabel.setMaximumSize(new java.awt.Dimension(105, 25)); totalKgLabel.setMinimumSize(new java.awt.Dimension(105, 25)); totalKgLabel.setPreferredSize(new java.awt.Dimension(105, 25)); getContentPane().add(totalKgLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, -1)); precioTotalLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); precioTotalLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/src/images/precio.png"))); // NOI18N precioTotalLabel.setText(" Precio total :"); precioTotalLabel.setMaximumSize(new java.awt.Dimension(105, 25)); precioTotalLabel.setMinimumSize(new java.awt.Dimension(105, 25)); precioTotalLabel.setPreferredSize(new java.awt.Dimension(105, 25)); getContentPane().add(precioTotalLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 40, -1, -1)); piezasLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); piezasLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/src/images/tshirt.png"))); // NOI18N piezasLabel.setText(" Piezas :"); piezasLabel.setMaximumSize(new java.awt.Dimension(105, 25)); piezasLabel.setMinimumSize(new java.awt.Dimension(105, 25)); piezasLabel.setPreferredSize(new java.awt.Dimension(105, 25)); getContentPane().add(piezasLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 70, -1, -1)); getContentPane().add(totalKg, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 10, 100, -1)); totalPrecio.setEnabled(false); getContentPane().add(totalPrecio, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 40, 100, -1)); totalPiezas.setEnabled(false); getContentPane().add(totalPiezas, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 70, 100, -1)); logo.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); logo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/src/images/logo.jpg"))); // NOI18N getContentPane().add(logo, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 0, 230, -1)); editarPrenda.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/src/images/edit.png"))); // NOI18N editarPrenda.setToolTipText("Editar prenda"); editarPrenda.setActionCommand("modificar"); editarPrenda.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 3, true)); editarPrenda.setMaximumSize(new java.awt.Dimension(100, 40)); editarPrenda.setMinimumSize(new java.awt.Dimension(100, 40)); editarPrenda.setPreferredSize(new java.awt.Dimension(100, 40)); getContentPane().add(editarPrenda, new org.netbeans.lib.awtextra.AbsoluteConstraints(470, 60, 100, 40)); fondo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/src/images/fondo.jpg"))); // NOI18N fondo.setMaximumSize(new java.awt.Dimension(600, 700)); fondo.setMinimumSize(new java.awt.Dimension(600, 700)); fondo.setPreferredSize(new java.awt.Dimension(600, 700)); getContentPane().add(fondo, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 580, 690)); pack(); }// </editor-fold>//GEN-END:initComponents public ArrayList<JButton> getEliminar() { return eliminar; } public JButton getAddPrenda() { return addPrenda; } public JButton getEditarPrenda() { return editarPrenda; } public JTable getPrendasTable() { return prendas; } public JTextField getTotalKg() { return totalKg; } public JTextField getTotalPiezas() { return totalPiezas; } public JTextField getTotalPrecio() { return totalPrecio; } private ArrayList<JButton> eliminar; // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton addPrenda; private javax.swing.JButton editarPrenda; private javax.swing.JLabel fondo; private javax.swing.JLabel logo; private javax.swing.JLabel piezasLabel; private javax.swing.JLabel precioTotalLabel; private javax.swing.JTable prendas; private javax.swing.JScrollPane scrollPrendas; private javax.swing.JTextField totalKg; private javax.swing.JLabel totalKgLabel; private javax.swing.JTextField totalPiezas; private javax.swing.JTextField totalPrecio; // End of variables declaration//GEN-END:variables } <file_sep>package com.sw.controller; import com.sw.model.Ticket; import com.sw.view.TicketInterfaz; /** * * @author Me */ public class VerTicketController { private TicketInterfaz ticketInterfaz; private Ticket ticket; public VerTicketController(TicketInterfaz ticketInterfaz, Ticket ticket) { this.ticketInterfaz = ticketInterfaz; this.ticket = ticket; } public void mostrarTicket() { ticketInterfaz.getVerTicket().setText(new TicketGenerator(ticket).generarTicket()); } } <file_sep>package com.sw.view; import javax.swing.JButton; import javax.swing.JTextField; /** * * @author Me */ public class AnadirTipoPrendaInterfaz extends javax.swing.JFrame { /** * Creates new form AnadirTipoPrenda */ public AnadirTipoPrendaInterfaz() { initWindow(); initComponents(); } private void initWindow() { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { System.out.println(ex.getMessage()); } //</editor-fold> } /** * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this method is always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { title = new javax.swing.JLabel(); tipoPrendaLabel = new javax.swing.JLabel(); entradaTipoPrenda = new javax.swing.JTextField(); anadirTipoPrenda = new javax.swing.JButton(); fondo = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Añadir tipo de prenda"); setResizable(false); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); title.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N title.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); title.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/src/images/addPrendasTitle.png"))); // NOI18N title.setText("Añadir un tipo de prenda"); getContentPane().add(title, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 20, 340, 50)); tipoPrendaLabel.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N tipoPrendaLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); tipoPrendaLabel.setText("Tipo de prenda:"); tipoPrendaLabel.setMaximumSize(new java.awt.Dimension(120, 30)); tipoPrendaLabel.setMinimumSize(new java.awt.Dimension(120, 30)); tipoPrendaLabel.setPreferredSize(new java.awt.Dimension(120, 30)); getContentPane().add(tipoPrendaLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 140, 180, -1)); entradaTipoPrenda.setMaximumSize(new java.awt.Dimension(120, 30)); entradaTipoPrenda.setMinimumSize(new java.awt.Dimension(120, 30)); entradaTipoPrenda.setPreferredSize(new java.awt.Dimension(120, 30)); getContentPane().add(entradaTipoPrenda, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 140, 160, -1)); anadirTipoPrenda.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/src/images/add.png"))); // NOI18N anadirTipoPrenda.setActionCommand("add"); anadirTipoPrenda.setMaximumSize(new java.awt.Dimension(80, 40)); anadirTipoPrenda.setMinimumSize(new java.awt.Dimension(80, 40)); anadirTipoPrenda.setPreferredSize(new java.awt.Dimension(80, 40)); getContentPane().add(anadirTipoPrenda, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 230, -1, -1)); fondo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/src/images/fondo.jpg"))); // NOI18N getContentPane().add(fondo, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 400, 300)); pack(); }// </editor-fold>//GEN-END:initComponents public JButton getAnadirTipoPrenda() { return anadirTipoPrenda; } public JTextField getEntradaTipoPrenda() { return entradaTipoPrenda; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton anadirTipoPrenda; private javax.swing.JTextField entradaTipoPrenda; private javax.swing.JLabel fondo; private javax.swing.JLabel tipoPrendaLabel; private javax.swing.JLabel title; // End of variables declaration//GEN-END:variables } <file_sep>package com.sw.utilities; import javax.swing.JLabel; /** * * @author Me */ public class TableTimer extends Timer { private static final long serialVersionUID = -7987864950655752437L; private JLabel label; private int id; private volatile boolean alive; public TableTimer(JLabel label, Time time, int id) { super(time); this.label = label; this.id = id; } @Override public void run() { alive = true; while (imAlive()) try { Thread.sleep(1000); if (!imAlive()) break; time.updateTime(); label.setText(time.toString()); } catch (InterruptedException ex) { System.out.println(ex.getMessage()); } } public JLabel getLabel() { return label; } public void setLabel(JLabel label) { this.label = label; } public int getId() { return id; } public void setId(int id) { this.id = id; } public boolean imAlive() { return alive; } public void setAlive(boolean alive) { this.alive = alive; } } <file_sep>package com.sw.persistence; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Formatter; /** * * @author Me */ public class DAO { public static final String RUTA_CLIENTESREGISTRADOS = "res/com/sw/data/ClientesRegistrados.txt"; public static final String RUTA_TIPOSPRENDAS = "res/com/sw/data/TiposPrendas.txt"; public static final String RUTA_HISTORIALES = "res/com/sw/data/Historiales.txt"; public static final String RUTA_TABLETIMERS = "res/com/sw/data/TableTimers.txt"; public static final String RUTA_SERVICIOSENCOLA = "res/com/sw/data/ServiciosEnCola.txt"; public static final String RUTA_SERVICIOSENPROCESO = "res/com/sw/data/ServiciosEnProceso.txt"; public static final String RUTA_SERVICIOSTERMINADOS = "res/com/sw/data/ServiciosTerminados.txt"; private File file; public DAO(String ruta) { file = new File(ruta); if (!file.exists()) try { file.createNewFile(); try (Formatter out = new Formatter(new FileWriter(file, false))) { out.format("%s", "0"); } } catch (IOException ex) { System.out.println(ex.getMessage()); } } public ArrayList<?> getObjects() { try { try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(file))) { return (ArrayList<?>) in.readObject(); } } catch (IOException | ClassNotFoundException ex) { System.out.println(ex.getMessage()); } return new ArrayList<>(); } public void saveObjects(ArrayList<?> objects) { try { try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file))) { out.writeObject(objects); } } catch (IOException ex) { System.out.println(ex.getMessage()); } } } <file_sep>package com.sw.controller; import com.sw.model.Cliente; import com.sw.others.TextFieldListener; import com.sw.view.NuevoCliente; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.AbstractButton; import javax.swing.JButton; import javax.swing.JOptionPane; /** * @author Me * @since 1.0 * */ public class NuevoClienteController implements ActionListener { private Cliente clienteModificando; private NuevoCliente nuevoCliente; private ClientesRegistradosController clientesRegistradosController; private NuevoServicioController nuevoServicioController; private TextFieldListener[] textFieldListeners; private boolean modificandoCliente; public NuevoClienteController(NuevoCliente nuevoCliente, ClientesRegistradosController clientesRegistradosController) { this.nuevoCliente = nuevoCliente; this.clientesRegistradosController = clientesRegistradosController; initAllMyComponents(); } public NuevoClienteController(NuevoCliente nuevoCliente, NuevoServicioController nuevoServicioController) { this.nuevoCliente = nuevoCliente; this.nuevoServicioController = nuevoServicioController; initAllMyComponents(); } public void establecerDatosDefecto(Cliente clienteModificando) { setModificandoCliente(true); // Estamos modificando a un cliente. this.clienteModificando = clienteModificando; // Rellenamos los campo con los datos del cliente que estamos modificando. nuevoCliente.getNombre().setText(clienteModificando.getNombre()); nuevoCliente.getCorreo().setText(clienteModificando.getCorreo()); nuevoCliente.getTelefono().setText(clienteModificando.getTelefono()); nuevoCliente.getDireccion().setText(clienteModificando.getDireccion()); } /** * Iniciamos los componentes para esta interfaz. */ private void initAllMyComponents() { textFieldListeners = new TextFieldListener[4]; textFieldListeners[0] = new TextFieldListener("^[a-zA-ZÁ-Úá-ú ]{5,}+$", nuevoCliente.getNombreValidoLabel(), nuevoCliente.getNombre()); textFieldListeners[1] = new TextFieldListener("([a-zA-zá-ú0-9_]{4,}.?)+@([a-zA-Z]{3,}.?)+.([a-zA-Z]+){2,}", nuevoCliente.getCorreoValidoLabel(), nuevoCliente.getCorreo()); textFieldListeners[2] = new TextFieldListener("^[0-9]{5,10}+$", nuevoCliente.getTelefonoValidoLabel(), nuevoCliente.getTelefono()); textFieldListeners[3] = new TextFieldListener("^[a-zA-Zá-ú0-9@ ._-]+$", nuevoCliente.getDireccionValidaLabel(), nuevoCliente.getDireccion()); nuevoCliente.getNombre().getDocument().addDocumentListener(textFieldListeners[0]); nuevoCliente.getCorreo().getDocument().addDocumentListener(textFieldListeners[1]); nuevoCliente.getTelefono().getDocument().addDocumentListener(textFieldListeners[2]); nuevoCliente.getDireccion().getDocument().addDocumentListener(textFieldListeners[3]); nuevoCliente.getNombre().addFocusListener(textFieldListeners[0]); nuevoCliente.getCorreo().addFocusListener(textFieldListeners[1]); nuevoCliente.getTelefono().addFocusListener(textFieldListeners[2]); nuevoCliente.getDireccion().addFocusListener(textFieldListeners[3]); nuevoCliente.getOk().addActionListener(this); } /** * Gestiona los eventos que ocurren cuando se presiona un botón. * * @param e El objeto de tipo ActionEvent que se crea cuando se presiona un botón en esta interfaz. */ @Override public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof JButton) ((AbstractButton) e.getSource()).setMultiClickThreshhold(1000); Cliente cliente; if (!textFieldListeners[0].isValido()) { JOptionPane.showMessageDialog(nuevoCliente, "Al menos el nombre del cliente debe ser válido", "Nombre no válido", JOptionPane.ERROR_MESSAGE); return; } else if (!todosCamposValidos()) switch (JOptionPane.showConfirmDialog(nuevoCliente, "Los campo inválidos no se tomarán en cuenta. ¿Continuar?", "Datos inválidos", JOptionPane.YES_NO_OPTION)) { case 0: // Si se presiona Sí cliente = obtenerDatosCliente(); break; default: return; } else cliente = obtenerDatosCliente(); nuevoCliente.dispose(); if (clientesRegistradosController != null) { if (!isModificandoCliente()) clientesRegistradosController.addClienteRegistrado(cliente); else clientesRegistradosController.modificarClienteRegistrado(clienteModificando, cliente); clientesRegistradosController.getClientesRegistradosInterfaz().setVisible(true); } else { nuevoServicioController.addCliente(cliente); nuevoServicioController.getNuevoServicio().setVisible(true); } } /** * Obtenemos los datos de la interfaz y creamos al cliente nuevo. * * @return El cliente con los datos de la interfaz. */ private Cliente obtenerDatosCliente() { return new Cliente(nuevoCliente.getNombre().getText(), textFieldListeners[1].isValido() ? nuevoCliente.getCorreo().getText() : "", textFieldListeners[2].isValido() ? nuevoCliente.getTelefono().getText() : "", textFieldListeners[3].isValido() ? nuevoCliente.getDireccion().getText() : ""); } /** * Todos los campos son válidos. * * @return @return <code> verdadero </code> si todos los campos son correctos, <code>falso</code> en caso contrario. */ private boolean todosCamposValidos() { for (TextFieldListener listener : textFieldListeners) if (!listener.isValido()) return false; return true; } private boolean isModificandoCliente() { return modificandoCliente; } private void setModificandoCliente(boolean modificandoCliente) { this.modificandoCliente = modificandoCliente; } } <file_sep>package com.sw.controller; import com.sw.model.Servicio; import com.sw.persistence.DAO; import com.sw.renderer.ListRenderer; import com.sw.renderer.ListRenderer.ListItem; import com.sw.utilities.Utilities; import java.awt.Font; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.util.ArrayList; import javax.swing.DefaultListModel; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; /** * * Controlador para la barra de búsqueda de clientes. * * @author Me * @since 1.0 */ public class BuscadorController implements FocusListener, DocumentListener { private JScrollPane scrollPane; private VistaPrincipalController vistaPrincipalController; private DefaultListModel<ListItem> modeloLista; private JList<ListItem> lista; public BuscadorController(JScrollPane scrollPane, VistaPrincipalController vistaPrincipalController, JList<ListItem> lista) { this.scrollPane = scrollPane; this.vistaPrincipalController = vistaPrincipalController; this.lista = lista; modeloLista = new DefaultListModel<>(); lista.setModel(modeloLista); lista.setFont(new Font("Tahoma", Font.PLAIN, 12)); lista.setCellRenderer(new ListRenderer()); } /** * Cuando el foco se gana en el buscador, ocultamos la tabla que muestra la búsqueda de los clientes. * * @param e El objeto FocusEvent que se crea cuando se gana el foco. */ @Override public void focusGained(FocusEvent e) { scrollPane.setVisible(false); vistaPrincipalController.getVistaPrincipal().getBuscar().selectAll(); } /** * Cuando el foco se píerde en el buscador, ocultamos la tabla que muestra la búsqueda de los clientes. * * @param e El objeto FocusEvent que se crea cuando se pierde el foco. */ @Override public void focusLost(FocusEvent e) { scrollPane.setVisible(false); } /** * Cada vez que se escriba algo en el buscador, actualizamos las búsquedas. * * @param e El objeto DocumentEvent que se crea cuando se escribe algo en el buscador. */ @Override public void insertUpdate(DocumentEvent e) { updateLista(vistaPrincipalController.getVistaPrincipal().getBuscar().getText()); } /** * Cada vez que se borre algo en el buscador, actualizamos las búsquedas. * * @param e El objeto DocumentEvent que se crea cuando se borra algo en el buscador. */ @Override public void removeUpdate(DocumentEvent e) { updateLista(vistaPrincipalController.getVistaPrincipal().getBuscar().getText()); } @Override public void changedUpdate(DocumentEvent e) { } /** * Actualizamos la busqueda. * * @param aBuscar La cadena a buscar para mostrar los resultados de la búsqueda. */ private void updateLista(String aBuscar) { modeloLista.removeAllElements(); if (aBuscar.trim().equals(" ") || aBuscar.trim().equals("")) { scrollPane.setVisible(false); return; } ArrayList<Servicio> serviciosEnCola = vistaPrincipalController.getServicios(DAO.RUTA_SERVICIOSENCOLA); ArrayList<Servicio> serviciosEnProceso = vistaPrincipalController.getServicios(DAO.RUTA_SERVICIOSENPROCESO); ArrayList<Servicio> serviciosTerminado = vistaPrincipalController.getServicios(DAO.RUTA_SERVICIOSTERMINADOS); buscarEnLista(serviciosEnCola, aBuscar, "EN COLA"); buscarEnLista(serviciosEnProceso, aBuscar, "EN PROCESO"); buscarEnLista(serviciosTerminado, aBuscar, "TERMINADO"); scrollPane.setVisible(!modeloLista.isEmpty()); } /** * Si la cadena a buscar concuerda con alguna búsqueda, se añade a la lista. * * @param servicios La lista con los elementos a buscar. * @param aBuscar La cadena a buscar. * @param status El status del servicio. */ private void buscarEnLista(ArrayList<Servicio> servicios, String aBuscar, String status) { int temp = 0; for (int i = 0; i < servicios.size(); i++) if (servicios.get(i).getCliente().getNombre().toLowerCase().startsWith(aBuscar.toLowerCase())) modeloLista.add(temp++, new ListItem(Utilities.getIcon("/com/src/images/clienteCombo.png"), String.format("%-25s N° TICKET : %-4s PRECIO : $%-10s STATUS : %s", servicios.get(i).getCliente().getNombre(), String.valueOf(servicios.get(i).getNumeroTicket()), String.valueOf(servicios.get(i).getPrecioTotal()), status))); } } <file_sep>package com.sw.view; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JTextField; /** * * @author Me */ public class ConfiguracionInterfaz extends javax.swing.JFrame { public ConfiguracionInterfaz() { initWindow(); initComponents(); } private void initWindow() { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { System.out.println(ex.getMessage()); } //</editor-fold> } /** * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this method is always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { tiltleLabel = new javax.swing.JLabel(); precioLabel = new javax.swing.JLabel(); precio = new javax.swing.JTextField(); precioValido = new javax.swing.JLabel(); tiposLabel = new javax.swing.JLabel(); tiposPrendas = new javax.swing.JButton(); colorLabel = new javax.swing.JLabel(); colorChooser = new javax.swing.JButton(); ok = new javax.swing.JButton(); ordenarPor = new javax.swing.JLabel(); order = new javax.swing.JComboBox<>(); fondo = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Configuración"); setMaximumSize(new java.awt.Dimension(500, 370)); setMinimumSize(new java.awt.Dimension(500, 370)); setResizable(false); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); tiltleLabel.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N tiltleLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/src/images/config.png"))); // NOI18N tiltleLabel.setText("Configuración"); getContentPane().add(tiltleLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 10, -1, -1)); precioLabel.setFont(new java.awt.Font("Tahoma", 0, 17)); // NOI18N precioLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); precioLabel.setText("Precio por kg:"); precioLabel.setToolTipText(""); precioLabel.setMaximumSize(new java.awt.Dimension(140, 30)); precioLabel.setMinimumSize(new java.awt.Dimension(140, 30)); precioLabel.setPreferredSize(new java.awt.Dimension(140, 30)); getContentPane().add(precioLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 110, 170, -1)); precio.setMaximumSize(new java.awt.Dimension(140, 30)); precio.setMinimumSize(new java.awt.Dimension(140, 30)); precio.setPreferredSize(new java.awt.Dimension(140, 30)); getContentPane().add(precio, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 110, -1, -1)); precioValido.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); precioValido.setMaximumSize(new java.awt.Dimension(110, 30)); precioValido.setMinimumSize(new java.awt.Dimension(110, 30)); precioValido.setPreferredSize(new java.awt.Dimension(110, 30)); getContentPane().add(precioValido, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 110, -1, -1)); tiposLabel.setFont(new java.awt.Font("Tahoma", 0, 17)); // NOI18N tiposLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); tiposLabel.setText("Tipos de prendas:"); tiposLabel.setMaximumSize(new java.awt.Dimension(140, 30)); tiposLabel.setMinimumSize(new java.awt.Dimension(140, 30)); tiposLabel.setPreferredSize(new java.awt.Dimension(140, 30)); getContentPane().add(tiposLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 190, 170, -1)); tiposPrendas.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/src/images/tshirt.png"))); // NOI18N tiposPrendas.setToolTipText("Añadir tipos de prendas"); tiposPrendas.setActionCommand("tipoPrendas"); tiposPrendas.setMaximumSize(new java.awt.Dimension(90, 40)); tiposPrendas.setMinimumSize(new java.awt.Dimension(90, 40)); tiposPrendas.setPreferredSize(new java.awt.Dimension(90, 40)); getContentPane().add(tiposPrendas, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 190, -1, -1)); colorLabel.setFont(new java.awt.Font("Tahoma", 0, 17)); // NOI18N colorLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); colorLabel.setText("Color de las tablas:"); colorLabel.setMaximumSize(new java.awt.Dimension(140, 30)); colorLabel.setMinimumSize(new java.awt.Dimension(140, 30)); colorLabel.setPreferredSize(new java.awt.Dimension(140, 30)); getContentPane().add(colorLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 240, 170, -1)); colorChooser.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/src/images/color.png"))); // NOI18N colorChooser.setActionCommand("Color"); colorChooser.setMaximumSize(new java.awt.Dimension(90, 40)); colorChooser.setMinimumSize(new java.awt.Dimension(90, 40)); colorChooser.setPreferredSize(new java.awt.Dimension(90, 40)); getContentPane().add(colorChooser, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 240, -1, -1)); ok.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/src/images/ok.png"))); // NOI18N ok.setActionCommand("ok"); ok.setMaximumSize(new java.awt.Dimension(90, 40)); ok.setMinimumSize(new java.awt.Dimension(90, 40)); ok.setPreferredSize(new java.awt.Dimension(90, 40)); getContentPane().add(ok, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 310, -1, -1)); ordenarPor.setFont(new java.awt.Font("Tahoma", 0, 17)); // NOI18N ordenarPor.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); ordenarPor.setText("Ordenar de forma:"); ordenarPor.setMaximumSize(new java.awt.Dimension(140, 30)); ordenarPor.setMinimumSize(new java.awt.Dimension(140, 30)); ordenarPor.setPreferredSize(new java.awt.Dimension(140, 30)); getContentPane().add(ordenarPor, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 150, -1, -1)); order.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Ascendente", "Desendente" })); order.setMaximumSize(new java.awt.Dimension(140, 30)); order.setMinimumSize(new java.awt.Dimension(140, 30)); order.setPreferredSize(new java.awt.Dimension(140, 30)); getContentPane().add(order, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 150, -1, -1)); fondo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/src/images/fondo.jpg"))); // NOI18N getContentPane().add(fondo, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 500, 370)); pack(); }// </editor-fold>//GEN-END:initComponents public JButton getColorChooser() { return colorChooser; } public JButton getOk() { return ok; } public JComboBox<String> getOrder() { return order; } public JTextField getPrecio() { return precio; } public JLabel getPrecioValido() { return precioValido; } public JButton getTiposPrendas() { return tiposPrendas; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton colorChooser; private javax.swing.JLabel colorLabel; private javax.swing.JLabel fondo; private javax.swing.JButton ok; private javax.swing.JLabel ordenarPor; private javax.swing.JComboBox<String> order; private javax.swing.JTextField precio; private javax.swing.JLabel precioLabel; private javax.swing.JLabel precioValido; private javax.swing.JLabel tiltleLabel; private javax.swing.JLabel tiposLabel; private javax.swing.JButton tiposPrendas; // End of variables declaration//GEN-END:variables } <file_sep>package com.sw.controller; import com.sw.model.Prenda; import com.sw.model.Servicio; import com.sw.others.MyWindowListener; import com.sw.utilities.Utilities; import com.sw.view.AnadirPrendaInterfaz; import com.sw.view.PrendasInterfaz; import java.awt.Color; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import javax.swing.AbstractButton; import javax.swing.JButton; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.table.DefaultTableModel; /** * * @author Me */ public class PrendasController extends MouseAdapter implements ActionListener { private PrendasInterfaz prendasInterfaz; private NuevoServicioController nuevoServicioController; private VistaPrincipalController vistaPrincipalController; private Servicio servicio; private ArrayList<Prenda> prendas; public PrendasController(PrendasInterfaz prendasInterfaz, VistaPrincipalController vistaPrincipalController, Servicio servicio) { this.vistaPrincipalController = vistaPrincipalController; this.prendasInterfaz = prendasInterfaz; this.servicio = servicio; prendas = servicio.getPrendas(); initCampos(servicio.getTotalKg(), servicio.getCostoKg()); initAllMyComponents(servicio.getCostoKg()); } public PrendasController(PrendasInterfaz prendasInterfaz, NuevoServicioController nuevoServicioController, ArrayList<Prenda> prendas, double totalKg, double costoKg) { this.prendasInterfaz = prendasInterfaz; this.nuevoServicioController = nuevoServicioController; this.prendas = prendas; initCampos(totalKg, costoKg); initAllMyComponents(costoKg); } public PrendasController(PrendasInterfaz prendasInterfaz, ArrayList<Prenda> prendas, double totalKg, double costoKg) { this.prendasInterfaz = prendasInterfaz; this.prendas = prendas; prendasInterfaz.getAddPrenda().setEnabled(false); prendasInterfaz.getEditarPrenda().setEnabled(false); prendasInterfaz.getTotalKg().setEnabled(false); initCampos(totalKg, costoKg); initAllMyComponents(costoKg); } private void iniciarLista() { if (prendas.isEmpty()) { prendasInterfaz.getEliminar().add(new JButton(Utilities.getIcon("/com/src/images/delete.png"))); return; } prendas.forEach((prenda) -> { prendasInterfaz.getEliminar().add(new JButton(Utilities.getIcon("/com/src/images/delete.png"))); }); } private void initCampos(double totalKg, double costoKg) { prendasInterfaz.getTotalKg().setText(String.valueOf(totalKg)); prendasInterfaz.getTotalPrecio().setText(String.format("$%,.2f", totalKg * costoKg)); } private void initAllMyComponents(double costoKg) { iniciarLista(); renderPrendasInterfazTable(); MyTextFieldListener textFieldListener = new MyTextFieldListener("^[0-9]+(.?[0-9]+)?$", prendasInterfaz.getTotalKg(), prendasInterfaz.getTotalPrecio(), costoKg); prendasInterfaz.getTotalKg().getDocument().addDocumentListener(textFieldListener); prendasInterfaz.getTotalKg().addFocusListener(textFieldListener); if (!prendas.isEmpty()) prendasInterfaz.getTotalPiezas().setText(String.valueOf(getNumTotalPrendas())); prendasInterfaz.getAddPrenda().addActionListener(this); prendasInterfaz.getEditarPrenda().addActionListener(this); } private void renderPrendasInterfazTable() { TableManager tableManager = new TableManager(); tableManager.renderTableModel(prendasInterfaz.getPrendasTable(), this, "Prendas"); Object[][] items = getItems(); prendasInterfaz.getPrendasTable().setModel(new DefaultTableModel(tableManager.loadTableComponents(items, new int[] { 3 }, prendasInterfaz.getEliminar()), new String[] { "Prenda", "Tipo de prenda", "Cantidad", "Eliminar" })); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof JButton) ((AbstractButton) e.getSource()).setMultiClickThreshhold(1000); switch (e.getActionCommand()) { case "addPrenda": EventQueue.invokeLater(() -> { AnadirPrendaInterfaz anadirPrendaInterfaz = new AnadirPrendaInterfaz(); anadirPrendaInterfaz.setVisible(true); anadirPrendaInterfaz.setLocationRelativeTo(prendasInterfaz); anadirPrendaInterfaz.addWindowListener(new MyWindowListener(prendasInterfaz)); prendasInterfaz.setVisible(false); new AnadirPrendaController(anadirPrendaInterfaz, this); }); break; case "modificar": if (!new TableManager().isFirstRowEmpty(prendasInterfaz.getPrendasTable()) && prendasInterfaz.getPrendasTable().getSelectedRow() >= 0) EventQueue.invokeLater(() -> { AnadirPrendaInterfaz anadirPrendaInterfaz = new AnadirPrendaInterfaz(); anadirPrendaInterfaz.setVisible(true); anadirPrendaInterfaz.setLocationRelativeTo(prendasInterfaz); anadirPrendaInterfaz.addWindowListener(new MyWindowListener(prendasInterfaz)); prendasInterfaz.setVisible(false); new AnadirPrendaController(anadirPrendaInterfaz, this).establecerPrendaDefecto(prendas.get(prendasInterfaz.getPrendasTable().getSelectedRow())); }); else mostrarMensaje("Error.", prendasInterfaz.getPrendasTable().getSelectedRow() < 0 ? "No ha seleccionado ninguna prenda." : "Aún no se ha añadido alguna prenda.", JOptionPane.ERROR_MESSAGE); default: break; } } @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() > 1) return; TableManager tableManager = new TableManager(); JTable table = prendasInterfaz.getPrendasTable(); if (tableManager.encimaBoton(table, e.getX(), e.getY(), 3)) { if (!prendasInterfaz.getAddPrenda().isEnabled()) { mostrarMensaje("Error.", "No se pueden borrar prendas cuando el ticket ya ha sido generado.", JOptionPane.ERROR_MESSAGE); return; } if (prendas.size() == 1) { mostrarMensaje("Error.", "Al menos una prenda debe ser añadida por servicio", JOptionPane.ERROR_MESSAGE); return; } if (!tableManager.isFirstRowEmpty(table)) eliminarPrenda(tableManager.getClickedRow(table, e.getY())); else mostrarMensaje("Error.", "Aún no se ha añadido alguna prenda.", JOptionPane.ERROR_MESSAGE); } } private Object[][] getItems() { if (prendas.isEmpty()) return new Object[1][4]; Object[][] items = new Object[prendas.size()][4]; for (int i = 0; i < items.length; i++) { items[i][0] = prendas.get(i).getDescripcion(); items[i][1] = prendas.get(i).getTipo(); items[i][2] = String.valueOf(prendas.get(i).getCantidad()); } return items; } public void anadirPrenda(Prenda prenda) { prendas.add(prenda); new TableManager().addRow(prendasInterfaz.getPrendasTable(), new Object[] { prenda.getDescripcion(), prenda.getTipo(), String.valueOf(prenda.getCantidad()) }); establecerPrendas(); } public void modificarPrenda(Prenda prendaAModificar, Prenda prendaNuevosDatos) { prendaAModificar.setDescripcion(prendaNuevosDatos.getDescripcion()); prendaAModificar.setTipo(prendaNuevosDatos.getTipo()); prendaAModificar.setCantidad(prendaNuevosDatos.getCantidad()); new TableManager().setTableItems(prendasInterfaz.getPrendasTable(), getItems()); establecerPrendas(); } private void eliminarPrenda(int index) { new TableManager().removeRow(prendasInterfaz.getPrendasTable(), index); getPrendas().remove(index); establecerPrendas(); } private void establecerPrendas() { if (nuevoServicioController != null) nuevoServicioController.setPrendas(getPrendas()); else { servicio.setPrendas(getPrendas()); vistaPrincipalController.saveAllServices(); } prendasInterfaz.getTotalPiezas().setText(String.valueOf(getNumTotalPrendas())); } public ArrayList<Prenda> getPrendas() { return prendas; } public void setPrendas(ArrayList<Prenda> prendas) { this.prendas = prendas; } private int getNumTotalPrendas() { int nTotal = 0; for (int i = 0; i < getPrendas().size(); i++) nTotal += getPrendas().get(i).getCantidad(); if (nuevoServicioController != null) nuevoServicioController.setNTotalPrendas(nTotal); return nTotal; } private void mostrarMensaje(String titulo, String text, int tipo) { JOptionPane.showMessageDialog(prendasInterfaz, text, titulo, tipo); } public PrendasInterfaz getPrendasInterfaz() { return prendasInterfaz; } /** * @author Me */ private class MyTextFieldListener implements DocumentListener, FocusListener { private JTextField totalKg; private JTextField precioTotal; private String regex; private double costoKg; private boolean campoValido; public MyTextFieldListener(String regex, JTextField totalKg, JTextField precioTotal, double costoKg) { this.regex = regex; this.totalKg = totalKg; this.precioTotal = precioTotal; this.costoKg = costoKg; } @Override public void insertUpdate(DocumentEvent e) { updateCampo(); } @Override public void removeUpdate(DocumentEvent e) { updateCampo(); } @Override public void focusGained(FocusEvent e) { totalKg.selectAll(); totalKg.setForeground(Color.black); precioTotal.setText(""); setCampoValido(false); if (nuevoServicioController != null) nuevoServicioController.setTotalKg(0); else servicio.setTotalKg(0); if (vistaPrincipalController != null) { vistaPrincipalController.saveAllServices(); vistaPrincipalController.updateAllTables(); } } @Override public void focusLost(FocusEvent e) { updateCampo(); } private void updateCampo() { if (!totalKg.getText().trim().equals("")) { boolean valido = totalKg.getText().matches(regex); totalKg.setForeground(valido ? Color.green : Color.red); precioTotal.setText(valido ? String.format("$%,.2f", Double.parseDouble(totalKg.getText()) * costoKg) : ""); setCampoValido(valido); if (valido && nuevoServicioController != null) nuevoServicioController.setTotalKg(Double.parseDouble(totalKg.getText())); else if (valido) servicio.setTotalKg(Double.parseDouble(totalKg.getText())); if (vistaPrincipalController != null) { vistaPrincipalController.saveAllServices(); vistaPrincipalController.updateAllTables(); } } else { totalKg.setForeground(Color.black); precioTotal.setText(""); setCampoValido(false); } } @Override public void changedUpdate(DocumentEvent e) { } public boolean isCampoValido() { return campoValido; } private void setCampoValido(boolean campoValido) { this.campoValido = campoValido; } } } <file_sep>package com.sw.utilities; import java.util.ArrayList; import javax.swing.ImageIcon; /** * * @author Me */ public class Utilities { public static ImageIcon getIcon(String ruta) { return new ImageIcon(Utilities.class.getClass().getResource(ruta)); } public static int[] asArray(ArrayList<Integer> lista) { int[] items = new int[lista.size()]; for (int i = 0; i < lista.size(); i++) items[i] = lista.get(i); return items; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.sw.viewMejorada; /** * * @author Nicolás */ public class PrendasInterfaz extends javax.swing.JFrame { /** * Creates new form PrendasInterfaz */ public PrendasInterfaz() { initComponents(); } /** * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this method is always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jPanel2 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jPanel5 = new javax.swing.JPanel(); jPanel4 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jTextField2 = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jTextField3 = new javax.swing.JTextField(); jPanel6 = new javax.swing.JPanel(); jLabel4 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setMaximumSize(new java.awt.Dimension(500, 400)); setMinimumSize(new java.awt.Dimension(500, 400)); setPreferredSize(new java.awt.Dimension(500, 400)); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane1.setViewportView(jTable1); getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER); jPanel2.setBackground(new java.awt.Color(255, 255, 255)); jPanel2.setLayout(new java.awt.BorderLayout()); jPanel3.setBackground(new java.awt.Color(255, 255, 255)); jPanel3.setLayout(new java.awt.GridBagLayout()); jButton1.setText("Añadir prenda"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 3, 5, 3); jPanel3.add(jButton1, gridBagConstraints); jButton2.setText("Modificar prenda"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 3, 5, 3); jPanel3.add(jButton2, gridBagConstraints); jPanel2.add(jPanel3, java.awt.BorderLayout.EAST); jPanel5.setLayout(new javax.swing.BoxLayout(jPanel5, javax.swing.BoxLayout.LINE_AXIS)); jPanel4.setBackground(new java.awt.Color(255, 255, 255)); jPanel4.setMinimumSize(new java.awt.Dimension(120, 78)); jPanel4.setPreferredSize(new java.awt.Dimension(120, 78)); jPanel4.setLayout(new java.awt.GridBagLayout()); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel1.setText("Total de Kg:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(3, 5, 3, 5); jPanel4.add(jLabel1, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.1; gridBagConstraints.insets = new java.awt.Insets(3, 5, 3, 5); jPanel4.add(jTextField1, gridBagConstraints); jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel2.setText("Precio total:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(3, 5, 3, 5); jPanel4.add(jLabel2, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.1; gridBagConstraints.insets = new java.awt.Insets(3, 5, 3, 5); jPanel4.add(jTextField2, gridBagConstraints); jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel3.setText("Piezas:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(3, 5, 3, 5); jPanel4.add(jLabel3, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.1; gridBagConstraints.insets = new java.awt.Insets(3, 5, 3, 5); jPanel4.add(jTextField3, gridBagConstraints); jPanel5.add(jPanel4); jPanel6.setBackground(new java.awt.Color(255, 255, 255)); jPanel6.setLayout(new java.awt.BorderLayout()); jLabel4.setBackground(new java.awt.Color(255, 255, 255)); jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/src/images/logo.jpg"))); // NOI18N jPanel6.add(jLabel4, java.awt.BorderLayout.CENTER); jPanel5.add(jPanel6); jPanel2.add(jPanel5, java.awt.BorderLayout.CENTER); getContentPane().add(jPanel2, java.awt.BorderLayout.NORTH); pack(); }// </editor-fold>//GEN-END:initComponents /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) if ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { System.out.println(ex.getMessage()); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(() -> { PrendasInterfaz vista = new PrendasInterfaz(); vista.setVisible(true); vista.setLocationRelativeTo(null); }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; // End of variables declaration//GEN-END:variables } <file_sep>package com.sw.controller; import com.sw.model.Prenda; import com.sw.others.TextFieldListener; import com.sw.persistence.DAO; import com.sw.renderer.ComboRenderer; import com.sw.utilities.Utilities; import com.sw.view.AnadirPrendaInterfaz; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.AbstractButton; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JOptionPane; /** * * @author Me * @since 1.0 * */ public class AnadirPrendaController implements ActionListener { private AnadirPrendaInterfaz anadirPrendaInterfaz; private PrendasController prendasController; private TextFieldListener[] textFieldListeners; private ArrayList<String> tiposPrendas; private Prenda prendaAModificar; private boolean modificandoPrenda; public AnadirPrendaController(AnadirPrendaInterfaz anadirPrendaInterfaz, PrendasController prendasController) { this.anadirPrendaInterfaz = anadirPrendaInterfaz; this.prendasController = prendasController; initMyComponents(); } /** * Iniciamos los componentes para esta ventana. */ private void initMyComponents() { textFieldListeners = new TextFieldListener[2]; textFieldListeners[0] = new TextFieldListener("^[á-úÁ-Úa-zA-Z0-9 ,_-]+$", anadirPrendaInterfaz.getPrenda()); textFieldListeners[1] = new TextFieldListener("^[1-90*]+$", anadirPrendaInterfaz.getCantidad()); anadirPrendaInterfaz.getPrenda().getDocument().addDocumentListener(textFieldListeners[0]); anadirPrendaInterfaz.getCantidad().getDocument().addDocumentListener(textFieldListeners[1]); anadirPrendaInterfaz.getPrenda().addFocusListener(textFieldListeners[0]); anadirPrendaInterfaz.getCantidad().addFocusListener(textFieldListeners[1]); anadirPrendaInterfaz.getCantidad().setText("1"); anadirPrendaInterfaz.getOk().addActionListener(this); loadComboModel(); } /** * Establece el renderer y los ítems para este JComboBox. */ private void loadComboModel() { anadirPrendaInterfaz.getTiposPrenda().setRenderer(new ComboRenderer()); anadirPrendaInterfaz.getTiposPrenda().setModel(loadComboItems()); } /** * Carga los ítems que muestra este JComoBox. * * @return El DefaultComboBoxModel con los elementos cargados. */ private DefaultComboBoxModel<ComboRenderer.ComboItem> loadComboItems() { DefaultComboBoxModel<ComboRenderer.ComboItem> dm = new DefaultComboBoxModel<>(); tiposPrendas = getTiposPrendas(); for (int i = tiposPrendas.isEmpty() ? -1 : 0; i < tiposPrendas.size(); i++) dm.addElement(new ComboRenderer.ComboItem(Utilities.getIcon("/com/src/images/tshirtCombo.png"), tiposPrendas.isEmpty() ? "No existen tipos de prendas" : tiposPrendas.get(i))); return dm; } /** * Gestiona los eventos que ocurren cuando se presiona un botón. * * @param e El objeto de tipo ActionEvent que se crea cuando se presiona un botón en esta interfaz. */ @Override public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof JButton) ((AbstractButton) e.getSource()).setMultiClickThreshhold(1000); if (!todosLosCampoValidos()) // Si alguno de los campo es inválido, se muestra la siguiente error. JOptionPane.showMessageDialog(anadirPrendaInterfaz, "Alguno de los campos no es válido", "Campo no válido", JOptionPane.ERROR_MESSAGE); else { if (!isModificandoPrenda()) // Si no se está modificando una prenda la añadimos a la tabla, en caso contrario, la modificamos. prendasController.anadirPrenda(getPrenda()); else prendasController.modificarPrenda(prendaAModificar, getPrenda()); prendasController.getPrendasInterfaz().setVisible(true); anadirPrendaInterfaz.dispose(); } } /** * Rellenamos los campos con valores por defecto (cuando se está modificando una prenda). * * @param prenda La prenda con la cual rellenaremos los campos. */ public void establecerPrendaDefecto(Prenda prenda) { setModificandoPrenda(true); prendaAModificar = prenda; anadirPrendaInterfaz.getPrenda().setText(prenda.getDescripcion()); anadirPrendaInterfaz.getCantidad().setText(String.valueOf(prenda.getCantidad())); anadirPrendaInterfaz.getTiposPrenda().setSelectedIndex(getIndexTipoPrenda(prenda)); } /** * Obtenemos la prenda a partir de las datos insertados por el usuario. * * @return La prenda que se obtiene de los datos de los campos. */ private Prenda getPrenda() { return new Prenda(anadirPrendaInterfaz.getPrenda().getText(), tiposPrendas.isEmpty() ? " " : tiposPrendas.get(anadirPrendaInterfaz.getTiposPrenda().getSelectedIndex()), Integer.parseInt(anadirPrendaInterfaz.getCantidad().getText())); } /** * Retornamos el índice del tipo de prenda que estamos modificando. * * @param prenda La prenda a la cual queremos saber su tipo. * * @return El índice del tipo de prenda para la prenda que estamos modificando. */ private int getIndexTipoPrenda(Prenda prenda) { for (int i = 0; i < tiposPrendas.size(); i++) if (tiposPrendas.get(i).equals(prenda.getTipo())) return i; return 0; } /** * Valida si todos los campos insertados por el usuario son válidos. * * @return <code> verdadero </code> si todos los campos son correctos, <code>falso</code> en caso contrario. */ private boolean todosLosCampoValidos() { for (TextFieldListener textFieldListener : textFieldListeners) if (!textFieldListener.isValido()) return false; return true; } private ArrayList<String> getTiposPrendas() { return (ArrayList<String>) new DAO(DAO.RUTA_TIPOSPRENDAS).getObjects(); } private boolean isModificandoPrenda() { return modificandoPrenda; } private void setModificandoPrenda(boolean modificandoPrenda) { this.modificandoPrenda = modificandoPrenda; } } <file_sep>package com.sw.view; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JTextField; /** * * @author Me */ public class NuevoCliente extends javax.swing.JFrame { public NuevoCliente() { initWindow(); initComponents(); } private void initWindow() { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { System.out.println(ex.getMessage()); } //</editor-fold> } /** * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this method is always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { titleLabel = new javax.swing.JLabel(); telefonoLabel = new javax.swing.JLabel(); nombreLabel = new javax.swing.JLabel(); direccionLabel = new javax.swing.JLabel(); nombre = new javax.swing.JTextField(); direccion = new javax.swing.JTextField(); telefono = new javax.swing.JTextField(); ok = new javax.swing.JButton(); correoLabel = new javax.swing.JLabel(); correo = new javax.swing.JTextField(); nombreValidoLabel = new javax.swing.JLabel(); correoValidoLabel = new javax.swing.JLabel(); telefonoValidoLabel = new javax.swing.JLabel(); direccionValidaLabel = new javax.swing.JLabel(); fondo = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Añadir a nuevo cliente"); setMinimumSize(new java.awt.Dimension(550, 400)); setResizable(false); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); titleLabel.setFont(new java.awt.Font("Consolas", 0, 36)); // NOI18N titleLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); titleLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/src/images/anadirClienteTitle.png"))); // NOI18N titleLabel.setText("Añadir cliente "); getContentPane().add(titleLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 10, -1, -1)); telefonoLabel.setFont(new java.awt.Font("Consolas", 0, 18)); // NOI18N telefonoLabel.setText("Teléfono:"); getContentPane().add(telefonoLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(106, 211, -1, 33)); nombreLabel.setFont(new java.awt.Font("Consolas", 0, 18)); // NOI18N nombreLabel.setText("Nombre completo:"); getContentPane().add(nombreLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(36, 132, -1, 33)); direccionLabel.setFont(new java.awt.Font("Consolas", 0, 18)); // NOI18N direccionLabel.setText("Dirección:"); getContentPane().add(direccionLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(96, 251, -1, 33)); nombre.setFont(new java.awt.Font("Consolas", 0, 11)); // NOI18N nombre.setHorizontalAlignment(javax.swing.JTextField.LEFT); nombre.setToolTipText("Nombre del cliente"); nombre.setMaximumSize(new java.awt.Dimension(195, 35)); nombre.setMinimumSize(new java.awt.Dimension(195, 35)); nombre.setPreferredSize(new java.awt.Dimension(195, 35)); getContentPane().add(nombre, new org.netbeans.lib.awtextra.AbsoluteConstraints(214, 133, -1, -1)); direccion.setFont(new java.awt.Font("Consolas", 0, 11)); // NOI18N direccion.setHorizontalAlignment(javax.swing.JTextField.LEFT); direccion.setToolTipText("Dirección del cliente"); direccion.setMaximumSize(new java.awt.Dimension(195, 35)); direccion.setMinimumSize(new java.awt.Dimension(195, 35)); direccion.setPreferredSize(new java.awt.Dimension(195, 35)); getContentPane().add(direccion, new org.netbeans.lib.awtextra.AbsoluteConstraints(214, 252, -1, -1)); telefono.setFont(new java.awt.Font("Consolas", 0, 11)); // NOI18N telefono.setHorizontalAlignment(javax.swing.JTextField.LEFT); telefono.setToolTipText("Teléfono del cliente"); telefono.setMaximumSize(new java.awt.Dimension(195, 35)); telefono.setMinimumSize(new java.awt.Dimension(195, 35)); telefono.setPreferredSize(new java.awt.Dimension(195, 35)); getContentPane().add(telefono, new org.netbeans.lib.awtextra.AbsoluteConstraints(214, 212, -1, -1)); ok.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/src/images/add.png"))); // NOI18N ok.setToolTipText("Añadir cliente"); getContentPane().add(ok, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 330, 127, 40)); correoLabel.setFont(new java.awt.Font("Consolas", 0, 18)); // NOI18N correoLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); correoLabel.setText("Correo:"); getContentPane().add(correoLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(106, 174, 90, 26)); correo.setFont(new java.awt.Font("Consolas", 0, 11)); // NOI18N correo.setHorizontalAlignment(javax.swing.JTextField.LEFT); correo.setToolTipText("Correo del cliente"); correo.setMaximumSize(new java.awt.Dimension(195, 35)); correo.setMinimumSize(new java.awt.Dimension(195, 35)); correo.setPreferredSize(new java.awt.Dimension(195, 35)); getContentPane().add(correo, new org.netbeans.lib.awtextra.AbsoluteConstraints(214, 172, -1, -1)); nombreValidoLabel.setFont(new java.awt.Font("Consolas", 0, 11)); // NOI18N nombreValidoLabel.setText(" "); nombreValidoLabel.setMaximumSize(new java.awt.Dimension(150, 35)); nombreValidoLabel.setMinimumSize(new java.awt.Dimension(150, 35)); nombreValidoLabel.setPreferredSize(new java.awt.Dimension(150, 35)); getContentPane().add(nombreValidoLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(420, 133, -1, -1)); correoValidoLabel.setFont(new java.awt.Font("Consolas", 0, 11)); // NOI18N correoValidoLabel.setText(" "); correoValidoLabel.setMaximumSize(new java.awt.Dimension(150, 35)); correoValidoLabel.setMinimumSize(new java.awt.Dimension(150, 35)); correoValidoLabel.setPreferredSize(new java.awt.Dimension(150, 35)); getContentPane().add(correoValidoLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(418, 173, -1, -1)); telefonoValidoLabel.setFont(new java.awt.Font("Consolas", 0, 11)); // NOI18N telefonoValidoLabel.setText(" "); telefonoValidoLabel.setMaximumSize(new java.awt.Dimension(150, 35)); telefonoValidoLabel.setMinimumSize(new java.awt.Dimension(150, 35)); telefonoValidoLabel.setPreferredSize(new java.awt.Dimension(150, 35)); getContentPane().add(telefonoValidoLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(418, 213, -1, -1)); direccionValidaLabel.setFont(new java.awt.Font("Consolas", 0, 11)); // NOI18N direccionValidaLabel.setText(" "); direccionValidaLabel.setMaximumSize(new java.awt.Dimension(150, 35)); direccionValidaLabel.setMinimumSize(new java.awt.Dimension(150, 35)); direccionValidaLabel.setPreferredSize(new java.awt.Dimension(150, 35)); getContentPane().add(direccionValidaLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(418, 253, -1, -1)); fondo.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); fondo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/src/images/fondo.jpg"))); // NOI18N getContentPane().add(fondo, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 590, 400)); pack(); }// </editor-fold>//GEN-END:initComponents public JButton getOk() { return ok; } public JTextField getCorreo() { return correo; } public JLabel getCorreoValidoLabel() { return correoValidoLabel; } public JTextField getDireccion() { return direccion; } public JLabel getDireccionValidaLabel() { return direccionValidaLabel; } public JTextField getNombre() { return nombre; } public JLabel getNombreValidoLabel() { return nombreValidoLabel; } public JTextField getTelefono() { return telefono; } public JLabel getTelefonoValidoLabel() { return telefonoValidoLabel; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField correo; private javax.swing.JLabel correoLabel; private javax.swing.JLabel correoValidoLabel; private javax.swing.JTextField direccion; private javax.swing.JLabel direccionLabel; private javax.swing.JLabel direccionValidaLabel; private javax.swing.JLabel fondo; private javax.swing.JTextField nombre; private javax.swing.JLabel nombreLabel; private javax.swing.JLabel nombreValidoLabel; private javax.swing.JButton ok; private javax.swing.JTextField telefono; private javax.swing.JLabel telefonoLabel; private javax.swing.JLabel telefonoValidoLabel; private javax.swing.JLabel titleLabel; // End of variables declaration//GEN-END:variables } <file_sep>package com.sw.model; import java.io.Serializable; import java.util.ArrayList; import java.util.Calendar; /** * * @author Me */ public class Ticket implements Serializable { private static final long serialVersionUID = 6162162262623189765L; private String nombreCliente; private ArrayList<Prenda> prendas; private Calendar fecha; private int numeroTicket; private int totalPrendas; private double precioTotal; private double totalKg; public Ticket(int numeroTicket, Calendar fecha, String nombreCliente, ArrayList<Prenda> prendas, int totalPrendas, double precioTotal, double totalKg) { this.numeroTicket = numeroTicket; this.fecha = fecha; this.nombreCliente = nombreCliente; this.prendas = prendas; this.totalPrendas = totalPrendas; this.precioTotal = precioTotal; this.totalKg = totalKg; } public int getNumeroTicket() { return numeroTicket; } public void setNumeroTicket(int numeroTicket) { this.numeroTicket = numeroTicket; } public Calendar getFecha() { return fecha; } public void setFecha(Calendar fecha) { this.fecha = fecha; } public String getNombreCliente() { return nombreCliente; } public void setNombreCliente(String nombreCliente) { this.nombreCliente = nombreCliente; } public ArrayList<Prenda> getPrendas() { return prendas; } public void setPrendas(ArrayList<Prenda> prendas) { this.prendas = prendas; } public int getTotalPrendas() { return totalPrendas; } public void setTotalPrendas(int totalPiezas) { this.totalPrendas = totalPiezas; } public double getPrecioTotal() { return precioTotal; } public void setTotalPrecio(double totalPrecio) { this.precioTotal = totalPrecio; } public double getTotalKg() { return totalKg; } public void setTotalKg(double totalKg) { this.totalKg = totalKg; } } <file_sep>package com.sw.renderer; import com.sw.controller.TableManager; import com.sw.others.MouseMotionModel; import com.sw.persistence.ConfigDAO; import com.sw.utilities.Utilities; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.SwingConstants; import javax.swing.table.DefaultTableCellRenderer; /** * * @author Me */ public class TableCellRenderer extends DefaultTableCellRenderer implements MouseMotionModel { private static final long serialVersionUID = -2422440758692459668L; private int x; private int y; @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { table.getColumnModel().getColumn(0).setWidth(table.getName().equals("Historial") ? 250 : table.getName().equals("Clientes") ? 280 : table.getName().equals("Tipos prendas") ? 370 : table.getName().equals("En cola") ? 350 : table.getColumnCount() == 8 ? 350 : 280); table.setRowHeight(30); if (value instanceof JButton) switch (table.getName()) { case "Clientes": updateIcon(((JButton) value), table, 5, "/com/src/images/historialSelected.png", "/com/src/images/historial.png"); return (Component) value; case "Prendas": updateIcon(((JButton) value), table, 3, "/com/src/images/deleteSelected.png", "/com/src/images/delete.png"); return (Component) value; case "Historial": switch (column) { case 3: updateIcon(((JButton) value), table, column, "/com/src/images/tshirtSelected.png", "/com/src/images/tshirt.png"); break; case 4: updateIcon(((JButton) value), table, column, "/com/src/images/ticketSelected.png", "/com/src/images/ticket.png"); break; case 5: updateIcon(((JButton) value), table, column, "/com/src/images/deleteSelected.png", "/com/src/images/delete.png"); } return (Component) value; case "En cola": switch (column) { case 2: updateIcon(((JButton) value), table, column, "/com/src/images/tshirtSelected.png", "/com/src/images/tshirt.png"); break; case 5: updateIcon(((JButton) value), table, column, "/com/src/images/downSelected.png", "/com/src/images/down.png"); break; case 6: updateIcon(((JButton) value), table, column, "/com/src/images/deleteSelected.png", "/com/src/images/delete.png"); break; } return (Component) value; case "Terminado": case "En proceso": switch (column) { case 2: updateIcon(((JButton) value), table, column, "/com/src/images/tshirtSelected.png", "/com/src/images/tshirt.png"); break; case 5: updateIcon(((JButton) value), table, column, "/com/src/images/upSelected.png", "/com/src/images/up.png"); break; case 6: if (!table.getName().equals("Terminado")) updateIcon(((JButton) value), table, column, "/com/src/images/downSelected.png", "/com/src/images/down.png"); else updateIcon(((JButton) value), table, column, "/com/src/images/ticketSelected.png", "/com/src/images/ticket.png"); break; case 7: updateIcon(((JButton) value), table, column, "/com/src/images/deleteSelected.png", "/com/src/images/delete.png"); } return (Component) value; case "Tipos prendas": updateIcon(((JButton) value), table, 1, "/com/src/images/deleteSelected.png", "/com/src/images/delete.png"); return (Component) value; default: return (Component) value; } else if (value instanceof JLabel) { ((JLabel) value).setHorizontalAlignment(SwingConstants.LEFT); ((Component) value).setSize(30, ((Component) value).getWidth()); ((Component) value).setPreferredSize(new Dimension(6, ((Component) value).getWidth())); Color color = new ConfigDAO().getColorTablas(); ((JComponent) value).setBorder(BorderFactory.createMatteBorder(0, 0, 1, 1, new Color(255, 255, 255))); ((JComponent) value).setOpaque(true); ((Component) value).setFont(new Font("Consolas", Font.PLAIN, 12)); ((Component) value).setBackground(row % 2 == 0 ? color.brighter() : Color.white); ((Component) value).setForeground(Color.black); if (row == table.getSelectedRow()) ((Component) value).setBackground(color.darker()); return ((Component) value); } JComponent jcomponent = new JLabel((String) value); ((JLabel) jcomponent).setHorizontalAlignment(SwingConstants.LEFT); jcomponent.setFont(new Font("Consolas", Font.PLAIN, 12)); jcomponent.setSize(30, jcomponent.getWidth()); jcomponent.setPreferredSize(new Dimension(6, jcomponent.getWidth())); Color color = new ConfigDAO().getColorTablas(); jcomponent.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 1, new Color(255, 255, 255))); jcomponent.setOpaque(true); jcomponent.setBackground(row % 2 == 0 ? color.brighter() : Color.white); jcomponent.setForeground(Color.black); if (row == table.getSelectedRow()) jcomponent.setBackground(color.darker()); return jcomponent; } private void updateIcon(JButton boton, JTable table, int column, String rutaSelected, String rutaDefault) { boton.setIcon(Utilities.getIcon(new TableManager().encimaBoton(table, boton, getX(), getY(), column) ? rutaSelected : rutaDefault)); } @Override public int getX() { return x; } @Override public void setX(int x) { this.x = x; } @Override public int getY() { return y; } @Override public void setY(int y) { this.y = y; } } <file_sep>package com.sw.others; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; /** * * @author Me * * @param <E> */ public class MouseMotionManager<E extends MouseMotionModel> implements MouseMotionListener { private E item; public MouseMotionManager(E item) { this.item = item; } @Override public void mouseDragged(MouseEvent e) { } @Override public void mouseMoved(MouseEvent e) { item.setY(e.getY()); item.setX(e.getX()); } public E getItem() { return item; } public void setItem(E item) { this.item = item; } } <file_sep>package com.sw.controller; import com.sw.model.Cliente; import com.sw.model.Historial; import com.sw.model.Servicio; import com.sw.persistence.ConfigDAO; import com.sw.utilities.TableTimer; import java.util.ArrayList; import java.util.Comparator; import javax.swing.JLabel; /** * Ordena los elementos de una determinada lista. * * @author Me * @see TableManager * @since 1.0 */ public class DataSorterManager { private final int ORDEN_ASCENDENTE = 0; private final int ORDEN_DESCENDENTE = 1; private int orden; public DataSorterManager() { orden = new ConfigDAO().getOrden(); } public void ordenarPorNombreServicios(ArrayList<Servicio> servicio) { servicio.sort((c1, c2) -> { return orden == ORDEN_ASCENDENTE ? c1.getCliente().getNombre().compareTo(c2.getCliente().getNombre()) : c2.getCliente().getNombre().compareTo(c1.getCliente().getNombre()); }); } public void ordenarPorPrecioTotal(ArrayList<Servicio> servicio) { if (orden == ORDEN_ASCENDENTE) servicio.sort(Comparator.comparing(Servicio::getPrecioTotal)); else servicio.sort(Comparator.comparing(Servicio::getPrecioTotal).reversed()); } public void ordenarPorTotalKg(ArrayList<Servicio> servicio) { if (orden == ORDEN_ASCENDENTE) servicio.sort(Comparator.comparing(Servicio::getTotalKg)); else servicio.sort(Comparator.comparing(Servicio::getTotalKg).reversed()); } public void ordenarPorTotalPiezas(ArrayList<Servicio> servicio) { if (orden == ORDEN_ASCENDENTE) servicio.sort(Comparator.comparing(Servicio::getTotalPrendas)); else servicio.sort(Comparator.comparing(Servicio::getTotalPrendas).reversed()); } public void ordenarPorNumTicket(ArrayList<Servicio> servicio) { if (orden == ORDEN_ASCENDENTE) servicio.sort(Comparator.comparing(Servicio::getNumeroTicket)); else servicio.sort(Comparator.comparing(Servicio::getNumeroTicket).reversed()); } public void ordenarPorNombreClientes(ArrayList<Cliente> clientes) { if (orden == ORDEN_ASCENDENTE) clientes.sort(Comparator.comparing(Cliente::getNombre)); else clientes.sort(Comparator.comparing(Cliente::getNombre).reversed()); } public void ordenarPorNServiciosClientes(ArrayList<Cliente> clientes) { if (orden == ORDEN_ASCENDENTE) clientes.sort(Comparator.comparing(Cliente::getnServicios)); else clientes.sort(Comparator.comparing(Cliente::getnServicios).reversed()); } public void ordenarPorNombreHistorial(ArrayList<Historial> historial) { historial.sort((c1, c2) -> { return orden == ORDEN_ASCENDENTE ? c1.getCliente().getNombre().compareTo(c2.getCliente().getNombre()) : c2.getCliente().getNombre().compareTo(c1.getCliente().getNombre()); }); } public void ordenarPorFechaHistorial(ArrayList<Historial> historial) { if (orden == ORDEN_ASCENDENTE) historial.sort(Comparator.comparing(Historial::getFecha)); else historial.sort(Comparator.comparing(Historial::getFecha).reversed()); } public void ordenarPorPrecioTotalHistorial(ArrayList<Historial> historial) { if (orden == ORDEN_ASCENDENTE) historial.sort(Comparator.comparing(Historial::getPrecioTotal)); else historial.sort(Comparator.comparing(Historial::getPrecioTotal).reversed()); } /** * Ordena los temporizadores de la tabla de proceso. * * @param serviciosEnProceso Los servicios a ordenar. * @param tableTimers Los temporizadores a ordenar. * */ public void ordenarTimers(ArrayList<Servicio> serviciosEnProceso, ArrayList<TableTimer> tableTimers) { for (int i = ORDEN_ASCENDENTE; i < serviciosEnProceso.size() - 1; i++) for (int j = ORDEN_ASCENDENTE; j < tableTimers.size(); j++) if (serviciosEnProceso.get(i).getNumeroTicket() == tableTimers.get(j).getId()) { JLabel tempLabel = tableTimers.get(j).getLabel(); tableTimers.get(j).setLabel(tableTimers.get(i).getLabel()); tableTimers.get(i).setLabel(tempLabel); TableTimer tableTimerTemp = tableTimers.get(j); tableTimers.set(j, tableTimers.get(i)); tableTimers.set(i, tableTimerTemp); } } } <file_sep>package com.sw.controller; import com.sw.others.MyWindowListener; import com.sw.others.TextFieldListener; import com.sw.persistence.ConfigDAO; import com.sw.view.ConfiguracionInterfaz; import com.sw.view.TiposPrendasInterfaz; import java.awt.Color; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.AbstractButton; import javax.swing.JButton; import javax.swing.JColorChooser; import javax.swing.JOptionPane; /** * Controlador de la configuración. * * @author Me * @since 1.0 * */ public class ConfigController implements ActionListener { private ConfiguracionInterfaz configuracionInterfaz; private TextFieldListener textFieldListener; private VistaPrincipalController vistaPrincipalController; public ConfigController(ConfiguracionInterfaz configuracionInterfaz, VistaPrincipalController vistaPrincipalController) { this.configuracionInterfaz = configuracionInterfaz; this.vistaPrincipalController = vistaPrincipalController; initMyComponents(); } /** * Iniciamos los componentes para esta interfaz. */ private void initMyComponents() { textFieldListener = new TextFieldListener("^[0-9]+(.?[0-9]+)?$", configuracionInterfaz.getPrecioValido(), configuracionInterfaz.getPrecio()); configuracionInterfaz.getPrecio().getDocument().addDocumentListener(textFieldListener); configuracionInterfaz.getPrecio().setText(String.valueOf(new ConfigDAO().getCostoKg())); configuracionInterfaz.getOrder().setSelectedIndex(new ConfigDAO().getOrden()); configuracionInterfaz.getColorChooser().addActionListener(this); configuracionInterfaz.getTiposPrendas().addActionListener(this); configuracionInterfaz.getOk().addActionListener(this); } /** * Gestiona los eventos que ocurren cuando se presiona un botón. * * @param e El objeto de tipo ActionEvent que se crea cuando se presiona un botón en esta interfaz. */ @Override public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof JButton) ((AbstractButton) e.getSource()).setMultiClickThreshhold(1000); switch (e.getActionCommand()) { case "Color": // Se muestra la ventana para seleccionar el color. new ConfigDAO().saveColorTablas(JColorChooser.showDialog(configuracionInterfaz, "Selecciona un color.", Color.yellow)); vistaPrincipalController.revalidateAllTables(); break; case "tipoPrendas": // Se muestra la interfaz para los tipos de prendas. EventQueue.invokeLater(() -> { TiposPrendasInterfaz tiposPrendasInterfaz = new TiposPrendasInterfaz(); tiposPrendasInterfaz.setVisible(true); tiposPrendasInterfaz.setLocationRelativeTo(configuracionInterfaz); tiposPrendasInterfaz.addWindowListener(new MyWindowListener(configuracionInterfaz)); configuracionInterfaz.setVisible(false); new TiposPrendasController(tiposPrendasInterfaz); }); break; case "ok": // Guardamos todos los datos. if (textFieldListener.isValido() && Double.parseDouble(configuracionInterfaz.getPrecio().getText()) != 0) { ConfigDAO configDAO = new ConfigDAO(); configDAO.savePrecioKg(Double.parseDouble(configuracionInterfaz.getPrecio().getText())); configDAO.saveOrden(configuracionInterfaz.getOrder().getSelectedIndex()); vistaPrincipalController.updateCostoKg(Double.parseDouble(configuracionInterfaz.getPrecio().getText())); vistaPrincipalController.updateAllTables(); configuracionInterfaz.dispose(); vistaPrincipalController.getVistaPrincipal().setVisible(true); } else mostrarMensaje("Error.", "El precio por kg. que insertó no es válido.", JOptionPane.ERROR_MESSAGE); break; default: break; } } /** * Mostramos un mensaje. * * @param titulo El título. * @param text El texto a mostrar. * @param tipo El tipo de mensaje. * */ private void mostrarMensaje(String titulo, String text, int tipo) { JOptionPane.showMessageDialog(configuracionInterfaz, text, titulo, tipo); } } <file_sep>package com.sw.others; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; /** * * @author Me */ public class MyWindowListener extends WindowAdapter { private JFrame ventana; public MyWindowListener(JFrame ventana) { this.ventana = ventana; } @Override public void windowClosing(WindowEvent e) { ventana.setVisible(true); } } <file_sep>package com.sw.model; import java.io.Serializable; /** * * @author Me */ public class Prenda implements Serializable { private static final long serialVersionUID = -6261626867347158543L; private String descripcion; private String tipo; private int cantidad; public Prenda(String descripcion, String tipo, int cantidad) { this.descripcion = descripcion; this.tipo = tipo; this.cantidad = cantidad; } public Prenda(String tipo, int cantidad) { this(tipo, tipo, cantidad); } public Prenda(int cantidad) { this("", cantidad); } public Prenda() { this("", 0); } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public int getCantidad() { return cantidad; } public void setCantidad(int cantidad) { this.cantidad = cantidad; } public String getTipo() { return tipo; } public void setTipo(String tipo) { this.tipo = tipo; } } <file_sep>package com.sw.persistence; import java.awt.Color; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Formatter; import java.util.Scanner; /** * * @author Me */ public class ConfigDAO { public static final String RUTA_PRECIOKG = "res/com/sw/data/PrecioKg.txt"; public static final String RUTA_COLORTABLAS = "res/com/sw/data/ColorTablas.txt"; public static final String RUTA_ORDEN = "res/com/sw/data/OrdenarPor.txt"; public double getCostoKg() { File file = new File(RUTA_PRECIOKG); if (!file.exists()) try { file.createNewFile(); try (Formatter out = new Formatter(new FileWriter(file, false))) { out.format("%s", "9.5"); } } catch (IOException ex) { System.out.println(ex.getMessage()); } else try (Scanner in = new Scanner(new FileReader(file))) { return in.nextDouble(); } catch (FileNotFoundException ex) { System.out.println(ex.getMessage()); } return 9.5; } public void savePrecioKg(double precio) { File file = new File(RUTA_PRECIOKG); try (Formatter out = new Formatter(new FileWriter(file, false))) { out.format("%s", precio); } catch (IOException ex) { System.out.println(ex.getMessage()); } } public Color getColorTablas() { File file = new File(RUTA_COLORTABLAS); if (!file.exists()) try { file.createNewFile(); try (Formatter out = new Formatter(new FileWriter(file, false))) { out.format("%s;%s;%s", "180", "180", "180"); } } catch (IOException ex) { System.out.println(ex.getMessage()); } else try (Scanner in = new Scanner(new FileReader(file))) { String[] RGB = in.nextLine().split(";"); return new Color(Integer.parseInt(RGB[0]), Integer.parseInt(RGB[1]), Integer.parseInt(RGB[2])); } catch (FileNotFoundException ex) { System.out.println(ex.getMessage()); } return new Color(180, 180, 180); } public void saveColorTablas(Color color) { if (color == null) return; File file = new File(RUTA_COLORTABLAS); try (Formatter out = new Formatter(new FileWriter(file, false))) { out.format("%s;%s;%s", color.getRed(), color.getGreen(), color.getBlue()); } catch (IOException ex) { System.out.println(ex.getMessage()); } } public int getOrden() { File file = new File(RUTA_ORDEN); if (!file.exists()) try { file.createNewFile(); try (Formatter out = new Formatter(new FileWriter(file, false))) { out.format("%s", "0"); } } catch (IOException ex) { System.out.println(ex.getMessage()); } else try (Scanner in = new Scanner(new FileReader(file))) { return in.nextInt(); } catch (FileNotFoundException ex) { System.out.println(ex.getMessage()); } return 0; } public void saveOrden(int orden) { File file = new File(RUTA_ORDEN); try (Formatter out = new Formatter(new FileWriter(file, false))) { out.format("%s", orden); } catch (IOException ex) { System.out.println(ex.getMessage()); } } } <file_sep>package com.sw.view; import java.util.ArrayList; import javax.swing.JButton; import javax.swing.JTable; /** * * @author Me */ public class TiposPrendasInterfaz extends javax.swing.JFrame { public TiposPrendasInterfaz() { initWindow(); initComponents(); initMyComponents(); } private void initWindow() { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { System.out.println(ex.getMessage()); } //</editor-fold> } private void initMyComponents() { eliminar = new ArrayList<>(); } /** * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this method is always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { logo = new javax.swing.JLabel(); editar = new javax.swing.JButton(); anadir = new javax.swing.JButton(); scrollTipoPrendas = new javax.swing.JScrollPane(); tiposPrendas = new javax.swing.JTable(); fondo = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Tipos prendas"); setMaximumSize(new java.awt.Dimension(495, 650)); setMinimumSize(new java.awt.Dimension(495, 650)); setPreferredSize(new java.awt.Dimension(495, 650)); setResizable(false); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); logo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/src/images/logo.jpg"))); // NOI18N getContentPane().add(logo, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, -1)); editar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/src/images/edit.png"))); // NOI18N editar.setToolTipText("Editar prenda"); editar.setActionCommand("editTipoPrenda"); editar.setMaximumSize(new java.awt.Dimension(100, 45)); editar.setMinimumSize(new java.awt.Dimension(100, 45)); editar.setPreferredSize(new java.awt.Dimension(100, 45)); getContentPane().add(editar, new org.netbeans.lib.awtextra.AbsoluteConstraints(380, 60, -1, -1)); anadir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/src/images/add.png"))); // NOI18N anadir.setToolTipText("Añadir nueva prenda"); anadir.setActionCommand("addTipoPrenda"); anadir.setMaximumSize(new java.awt.Dimension(100, 45)); anadir.setMinimumSize(new java.awt.Dimension(100, 45)); anadir.setPreferredSize(new java.awt.Dimension(100, 45)); getContentPane().add(anadir, new org.netbeans.lib.awtextra.AbsoluteConstraints(380, 10, -1, -1)); scrollTipoPrendas.setMaximumSize(new java.awt.Dimension(490, 485)); scrollTipoPrendas.setMinimumSize(new java.awt.Dimension(490, 485)); scrollTipoPrendas.setPreferredSize(new java.awt.Dimension(490, 485)); tiposPrendas.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null}, }, new String [] { "Title 1", "Title 2" } )); scrollTipoPrendas.setViewportView(tiposPrendas); getContentPane().add(scrollTipoPrendas, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 140, -1, -1)); fondo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/src/images/fondo.jpg"))); // NOI18N getContentPane().add(fondo, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 490, 680)); pack(); }// </editor-fold>//GEN-END:initComponents public ArrayList<JButton> getEliminar() { return eliminar; } public JButton getAnadir() { return anadir; } public JButton getEditar() { return editar; } public JTable getTiposPrendasTable() { return tiposPrendas; } private ArrayList<JButton> eliminar; // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton anadir; private javax.swing.JButton editar; private javax.swing.JLabel fondo; private javax.swing.JLabel logo; private javax.swing.JScrollPane scrollTipoPrendas; private javax.swing.JTable tiposPrendas; // End of variables declaration//GEN-END:variables } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.sw.viewMejorada; /** * * @author Nicolás */ public class NuevoServicio extends javax.swing.JFrame { /** * Creates new form Test3 */ public NuevoServicio() { initComponents(); } /** * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this method is always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; jPanel1 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jPanel3 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jSpinner1 = new javax.swing.JSpinner(); jLabel4 = new javax.swing.JLabel(); jSpinner2 = new javax.swing.JSpinner(); jLabel6 = new javax.swing.JLabel(); jSpinner3 = new javax.swing.JSpinner(); jLabel7 = new javax.swing.JLabel(); jPanel5 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jComboBox2 = new javax.swing.JComboBox<>(); jButton4 = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); jButton5 = new javax.swing.JButton(); jPanel4 = new javax.swing.JPanel(); filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 10), new java.awt.Dimension(0, 10), new java.awt.Dimension(32767, 10)); jLabel8 = new javax.swing.JLabel(); filler2 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 10), new java.awt.Dimension(0, 10), new java.awt.Dimension(32767, 10)); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Nuevo servicio"); setMaximumSize(new java.awt.Dimension(350, 250)); setMinimumSize(new java.awt.Dimension(325, 225)); setPreferredSize(new java.awt.Dimension(350, 250)); jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 10, 5)); jButton1.setText("Vale!"); jPanel1.add(jButton1); jButton2.setText("Ver ticket"); jPanel1.add(jButton2); getContentPane().add(jPanel1, java.awt.BorderLayout.PAGE_END); jPanel3.setLayout(new java.awt.BorderLayout()); jPanel2.setLayout(new java.awt.GridBagLayout()); jLabel1.setText("Tiempo estimado:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(jLabel1, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(jSpinner1, gridBagConstraints); jLabel4.setText("Horas"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(jLabel4, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(jSpinner2, gridBagConstraints); jLabel6.setText("Minutos"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 1; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(jLabel6, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(jSpinner3, gridBagConstraints); jLabel7.setText("Segundos"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 1; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(jLabel7, gridBagConstraints); jPanel3.add(jPanel2, java.awt.BorderLayout.SOUTH); jPanel5.setLayout(new java.awt.GridBagLayout()); jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel2.setText("Cliente:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel5.add(jLabel2, gridBagConstraints); jComboBox2.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel5.add(jComboBox2, gridBagConstraints); jButton4.setText("Crear clientes"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel5.add(jButton4, gridBagConstraints); jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel3.setText("Prendas:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel5.add(jLabel3, gridBagConstraints); jButton5.setText("Añadir prendas"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel5.add(jButton5, gridBagConstraints); jPanel3.add(jPanel5, java.awt.BorderLayout.CENTER); jPanel4.setLayout(new javax.swing.BoxLayout(jPanel4, javax.swing.BoxLayout.Y_AXIS)); jPanel4.add(filler1); jLabel8.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel8.setText("Nuevo servicio"); jLabel8.setAlignmentX(0.5F); jPanel4.add(jLabel8); jPanel4.add(filler2); jPanel3.add(jPanel4, java.awt.BorderLayout.NORTH); getContentPane().add(jPanel3, java.awt.BorderLayout.PAGE_START); pack(); }// </editor-fold>//GEN-END:initComponents /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) if ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { System.out.println(ex.getMessage()); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(() -> { NuevoServicio t = new NuevoServicio(); t.setLocationRelativeTo(null); t.setVisible(true); }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.Box.Filler filler1; private javax.swing.Box.Filler filler2; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private javax.swing.JComboBox<String> jComboBox2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JSpinner jSpinner1; private javax.swing.JSpinner jSpinner2; private javax.swing.JSpinner jSpinner3; // End of variables declaration//GEN-END:variables } <file_sep>package com.sw.persistence; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Formatter; import java.util.Scanner; /** * * @author Me */ public class ClienteDAO { public static final String RUTA_CLAVECLIENTES = "res/com/sw/data/ClaveCliente.txt"; private File file; public ClienteDAO() { file = new File(RUTA_CLAVECLIENTES); if (!file.exists()) try { file.createNewFile(); try (Formatter out = new Formatter(new FileWriter(file, false))) { out.format("%s", "0"); } } catch (IOException ex) { System.out.println(ex.getMessage()); } } public int getClaveClientes() { try (Scanner in = new Scanner(new FileReader(file))) { return in.nextInt(); } catch (FileNotFoundException ex) { System.out.println(ex.getMessage()); } return 0; } public void saveClaveClientes(int clave) { try (Formatter out = new Formatter(new FileWriter(file, false))) { out.format("%s", clave); } catch (IOException ex) { System.out.println(ex.getMessage()); } } }
48433e990cb980f1a45d98623c805560453593cb
[ "Java" ]
24
Java
HikingCarrot7/ProyectoPOO
8b9ab92d888bb74c5b5cfbf96f1da9d3e2e27c80
40f26856a2021da40c7be45d43a96df508aca46b
refs/heads/master
<repo_name>marcodings/j2Mantis---Joomla-1.6<file_sep>/Helper.class.php <?php /** * User: Marco * Date: 2/22/13 * Time: 3:59 PM * To change this template use File | Settings | File Templates. */ class J2MantisHelper { static $viewLevels; public static function getJ2M_Status($bug) { $j2m=array(); $additional_information=$bug->additional_information; // $aaa['action']="actiehouder1";$aaa['state']="assigned";$bbb['action']="ac\"tiehouder2";$bbb['other']="anders"; // $additional_information=$additional_information."#J2M#v1.0#".json_encode($aaa)."#J2M#\n"; // $additional_information=$additional_information."asdfadsf asd\n"; // $additional_information=$additional_information."#J2M#v1.0#".json_encode($bbb)."#J2M#"; // #J2M#v1.0# #J2M# $tomatch="/#J2M#v(\d+\.\d+)#(.*?)#J2M#/sm"; preg_match_all($tomatch, $additional_information, $matches); $max_matches=count($matches[0]); for($idx=0; $idx<$max_matches; $idx++) { if ( $matches[1][$idx] == '1.0' ) { $j2m=array_merge($j2m,json_decode($matches[2][$idx],true)); } }; return $j2m; } public static function setJ2M_Status($bug, $j2m) { $additional_information=$bug->additional_information; $bug->additional_information=$additional_information."\n#J2M#v1.0#".json_encode($j2m)."#J2M#"; } public static function FilterJ2M_Status($bug) { $tomatch="/#J2M#v(\d+\.\d+)#(.*?)#J2M#\n?/sm"; $additional_information=$bug->additional_information; return preg_replace($tomatch, "", $additional_information);; } public static function getAuthorisedViewLevelsUsers($viewlevel) { // Only load the view levels once. if (empty(self::$viewLevels)) { // Get a database object. $db = JFactory::getDBO(); // Build the base query. $query = $db->getQuery(true); $query->select('id, rules'); $query->from($query->qn('#__viewlevels')); // Set the query for execution. $db->setQuery((string) $query); // Build the view levels array. foreach ($db->loadAssocList() as $level) { self::$viewLevels[$level['id']] = (array) json_decode($level['rules']); } } $users=array(); foreach (self::$viewLevels[$viewlevel] as $group) { $users= array_merge($users,JAccess::getUsersByGroup($group)); } return $users; } } <file_sep>/j2mantis.php <?php /** * @package Joomla.J2Mantis * @subpackage Components * components/com_J2Mantis/J2Mantis.class.php * @license GNU/GPL */ // No direct access defined( '_JEXEC' ) or die( 'Restricted access' ); // Require the base controller require_once( JPATH_COMPONENT.DS.'JoomlaMantisController.class.php' ); class ErrorHandler extends Exception { protected $severity; public function __construct($message, $code, $severity, $filename, $lineno) { $this->message = $message; $this->code = $code; $this->severity = $severity; $this->file = $filename; $this->line = $lineno; } public function getSeverity() { return $this->severity; } } function exception_error_handler($errno, $errstr, $errfile, $errline ) { throw new ErrorHandler($errstr, 0, $errno, $errfile, $errline); } set_error_handler("exception_error_handler", E_USER_ERROR); // Require specific controller if requested if($controller = JRequest::getWord('controller')) { $path = JPATH_COMPONENT.DS.'controllers'.DS.$controller.'.php'; if (file_exists($path)) { require_once $path; } else { $controller = ''; } } // Create the controller $classname = 'JoomlaMantisController'.$controller; $controller = new $classname( ); // Perform the Request task $controller->execute( JRequest::getVar( 'task' ) ); // Redirect if set by the controller $controller->redirect(); ?><file_sep>/views/addbug/tmpl/default.php <?php // No direct access defined('_JEXEC') or die('Restricted access'); ?> <?php JHTML::_('behavior.formvalidation') ?> <?php JHTML::_('behavior.calendar') ?> <?php JHTML::stylesheet('j2mantis.css', 'components/com_j2mantis/assets/'); ?> <script type="text/javascript"> //<![CDATA[ function myValidate(f) { if (document.formvalidator.isValid(f)) { //f.check.value='<?php echo JUtility::getToken(); ?>';//send token return true; } else { alert('<?php echo JText::_('please check the form');?>'); } return false; } //]]> </script> <div class="item-page<?php echo $this->moduleclass_sfx ?>" id="j2Mantis"> <h2><?php echo $this->caption; ?></h2> <?php if (!empty($_POST['errors'])): ?> <div class="error"><h3><?php echo JText::_('Error');?></h3> <ul> <?php foreach ($_POST['errors'] as $error) { echo "<li>" . $error . "</li>"; }?> </ul> </div> <?php endif; ?> <form method="post" action="?option=com_j2mantis&amp;task=addBug&amp;Itemid=<?php echo JRequest::getInt('Itemid', 0);?>" onsubmit="return myValidate(this);"> <input type="hidden" name="view" value="addbug"/> <input type="hidden" name="check" value="post"/> <?php if (sizeof($this->project) > 1): ?> <label for="project"><?php echo JText::_('Project');?></label> <select name="project" id="project" onchange="changeProject(this)"> <?php foreach ($this->project as $pid => $name) { ?> <option <?php if (!empty($_POST['project']) && $_POST['project'] == $pid) echo 'selected="selected"'; ?> value="<?php echo $pid; ?>"><?php echo $name ?></option> <?php } ?> </select> <br/> <?php else: ?> <?php foreach ($this->project as $pid => $name) { ?> <input type="hidden" name="project" value="<?php echo $pid; ?>"/> <?php } ?> <?php endif; ?> <label for="category"><?php echo JText::_('Category');?></label> <select name="category" id="category"> <?php foreach ($this->cat as $id => $cArray) { ?> <?php foreach ($cArray as $c) { ?> <option <?php if (!empty($_POST['category']) && $_POST['category'] == $c) echo 'selected="selected"'; ?> value="<?php echo $c; ?>" class="project-<?php echo $id; ?>"><?php echo $c ?></option> <?php } ?> <?php } ?> </select> <br/> <label for="summary"><?php echo JText::_('Short Description');?>*</label> <input type="text" name="summary" id="summary" class="required" <?php if (!empty($_POST['summary'])) echo 'value="' . $_POST['summary'] . '"' ?> /> <br/> <label for="name"><?php echo JText::_('Name'); if ( $this->fo_name == 1 ) echo '*';?></label> <input type="text" name="name" id="name" style="width: 200px;"<?php if ( $this->fo_name == 1 ) echo 'class="required"'; if ( ! $this->fo_nameedit ) echo ' readonly'; ?> <?php if (!empty($this->user->name)) { echo 'value="' . $this->user->name . ' [' . $this->user->username . ']"'; } ?> /> <br/> <label for="email"><?php echo JText::_('E-Mail'); if ( $this->fo_email == 1 ) echo '*';?></label> <input type="text" name="email" id="email" style="width: 200px;" class="validate-email <?php if ( $this->fo_email == 1 ) echo 'required'; ?>" <?php if ( ! $this->fo_emailedit ) echo 'readonly'; ?> <?php if (!empty($this->user->email)) { echo 'value="' . $this->user->email . '"'; } ?> /> <br/> <?php if ( isset($this->actionholders) ) { ?> <label>Actionholder:</label> <select name="actionholderId" STYLE="width: 200px"> <option value="-1">- none -</option> <?php foreach($this->actionholders as $actionholder){ ?> <option value="<?php echo $actionholder->id; ?>"><?php echo $actionholder->name; ?></option> <?php } ?> </select> <br/> <?php } ?> <label for="duedate"><?php echo JText::_('Due date');?></label> <?php echo JHTML::_('calendar', $this->due_date, 'due_date', 'dd_id', '%Y-%m-%d', array('class' => 'inputbox', 'size' => '12', 'maxlength' => '10')); ?> <br/> <br/> <label for="priority"><?php echo JText::_('Priority');?></label> <select name="priority" id="priority"> <option value="20" <?php if (!empty($_POST['priority']) && $_POST['priority'] == 20) echo 'selected="selected"'; ?>><?php echo JText::_('low');?></option> <option value="30" <?php if (empty($_POST['priority']) or (!empty($_POST['priority']) && $_POST['priority'] == 30)) echo 'selected="selected"'; ?>><?php echo JText::_('normal');?></option> <option value="40" <?php if (!empty($_POST['priority']) && $_POST['priority'] == 40) echo 'selected="selected"'; ?>><?php echo JText::_('high');?></option> </select> <br/> <label for="description"><?php echo JText::_('Description');?></label> <textarea name="description" id="description" cols="50" rows="8"><?php if (!empty($_POST['description'])) echo $_POST['description'] ?></textarea> <br/> <?php $params = &JComponentHelper::getParams('com_j2mantis'); ?> <input style="float:right; background-color: lightsteelblue;" type="submit" value="<?php echo JText::_('Submit');?>"/> </form> <?php if ((boolean)$params->get('overview')): ?> <br/> <a href="?option=com_j2mantis&amp;Itemid=<?php echo JRequest::getInt('Itemid', 0);?>"><?php echo JText::_('Return to Report Overview');?></a> <?php endif; ?> <br style="clear: both;"/> </div> <script type="text/javascript"> //<![CDATA[ var catogoryLists = new Array(<?php echo sizeof($this->project) ?>); <?php foreach ($this->project as $id => $name): ?> catogoryLists[<?php echo $id ?>] = ["<?php echo implode('","', $this->cat[$id]) ?>"]; <?php endforeach; ?> function addNewOptions(id, projectId) { var cList = catogoryLists[projectId]; for (var i = 0; i < cList.length; i++) { newOption = document.createElement("option"); newOption.value = cList[i]; // assumes option string and value are the same newOption.text = cList[i]; try { newOption.inject($('category')); } catch (ex) { id.add(newOption); } } } function changeProject(el) { var projectId = el.value; $('category').options.length = 0; addNewOptions($('category'), projectId); } changeProject($('project')); //]]> </script> <file_sep>/views/showbug/view.html.php <?php /** * @package Joomla.J2Mantis * @subpackage Components * components/com_J2Mantis/view/view.html.php * @license GNU/GPL */ // no direct access defined( '_JEXEC' ) or die( 'Restricted access' ); jimport( 'joomla.application.component.view'); require_once( JPATH_COMPONENT_SITE.DS.'Helper.class.php'); /** * HTML View class for the J2Mantis Component * * @package J2Mantis */ class J2MantisViewshowbug extends JView { function display($tpl = null) { require_once( JPATH_COMPONENT.DS.'JoomlaMantisParameter.class.php'); $settings = new JoomlaMantisParameter(); require_once( JPATH_COMPONENT.DS.'MantisConnector.class.php'); $Mantis = new MantisConnector($settings); $params = &JComponentHelper::getParams( 'com_j2mantis' ); $bugid = $params->get('bug_id'); if( empty($bugid) ){ $bugid = JRequest::getVar('bugid',0); $bugid = $Mantis->encode(base64_decode(JRequest::getVar('bugid',0))); } //var_dump( $bugid ); $bug = $Mantis->getBug( $bugid ); $this->caption=JText::_("problem description"); $this->bug=$bug; $this->additional_info_readonly=J2MantisHelper::FilterJ2M_Status($bug); if ($bug->due_date ) { $this->due_date = date( "Y-m-d",strtotime($bug->due_date)); } else { $bug->due_date = null; } /* * config_inc.php * $g_due_date_update_threshold = MANAGER; * $g_due_date_view_threshold = DEVELOPER; * */ // global option to support "due date" $support_duedate // only display if $support_duedate set // // Get list of potential action holders jimport('joomla.access.access'); $params = JFactory::getApplication()->getParams('com_j2mantis'); $action_acl = $params->get('access'); $action_user_ids = J2MantisHelper::getAuthorisedViewLevelsUsers($action_acl); jimport('joomla.user.user'); foreach ($action_user_ids as $action_user_id) { $this->actionholders[] = JFactory::getUser($action_user_id); } $j2m=J2MantisHelper::getJ2M_Status($bug); $this->default_autionholderid=$j2m['actionholderid']; $this->user = JFactory::getUser(); $this->defCaption = $settings->getMantisCaption(); $this->fo_name = $settings->getmantisFo_name(); $this->fo_nameedit = $settings->getmantisFo_nameedit(); $this->fo_email = $settings->getmantisFo_email(); $this->fo_emailedit = $settings->getmantisFo_emailedit(); $this->moduleclass_sfx=$params->get('moduleclass_sfx',""); if( $this->user->id==0 ){ // no logged in user, then edit cannot be false if field required if ($this->fo_name == 1 ) $this->fo_nameedit = 1; if ($this->fo_email == 1 ) $this->fo_emailedit = 1; } $this->caption = ($this->defCaption) ? $this->defCaption : JText::_('Problem description'); parent::display($tpl); } } ?> <file_sep>/soa_objects/project_data.php <?php class ProjectData { var $id = 0; var $name = null; } ?><file_sep>/views/j2mantis/tmpl/default.php <?php // No direct access defined('_JEXEC') or die('Restricted access'); ?> <?php JHTML::stylesheet('j2mantis.css', 'components/com_j2mantis/assets/'); JHTML::_('behavior.tooltip'); $timezone_offset = -date("H", strtotime("Y-m-d", time()))+1; $fmt_date_long = "Y/m/d H:i"; $fmt_date_short = "d M"; ?> <div class="item-list<?php echo $this->moduleclass_sfx ?>" xmlns="http://www.w3.org/1999/html"> <h1><?php echo $this->caption; ?></h1> <table id="mt_overview"> <thead> <tr> <th> <?php echo JText::_('Status');?> </th> <th> <?php echo JText::_('Summary');?> </th> <?php if ($this->hasactionholders) { ?> <th> <?php echo JText::_('actionholder');?> </th> <?php } ?> <?php if ($this->hasduedate) { ?> <th> <?php echo JText::_('due date');?> </th> <?php } ?> <th> <?php echo JText::_('last update');?> </th> </tr> </thead> <?php foreach ($this->bugs as $bug) { $uxts_last_updated = strtotime($bug->last_updated . " +" . $timezone_offset . " hours"); $last_updated_long = date($fmt_date_long, $uxts_last_updated); $last_updated_short = date($fmt_date_short, $uxts_last_updated); $uxts_date_submitted = strtotime($bug->date_submitted . " +" . $timezone_offset . " hours"); $date_submitted_long = date($fmt_date_long, $uxts_date_submitted); $duedate_long = " "; $duedate_short = " "; if ($bug->due_date) { $uxts_duedate = strtotime($bug->due_date . " +" . $timezone_offset . " hours"); $duedate_long = date($fmt_date_long, $uxts_duedate); $duedate_short = date($fmt_date_short, $uxts_duedate); } $url = "?option=com_j2mantis&amp;view=showbug&amp;bugid=" . base64_encode($this->mantis->encode((string)$bug->id)) . "&amp;Itemid=" . JRequest::getInt('Itemid', 0); ?> <tr> <td> <?php echo JHTML::tooltip($bug->category . ' (' . $bug->priority->name . ')</br>' . '<b>S:</b> ' . $date_submitted_long . '</br>' . '<b>U:</b> ' . $last_updated_long , $bug->project->name, '', $bug->status->name); ?> </td> <td> <?php echo JHTML::tooltip($bug->description . '</br>' , $bug->project->name, '', $bug->summary, $url); ?> </td> <?php if ($this->hasactionholders) { ?> <td> <?php if ($bug->j2m['actionholderid']>0) { echo JHTML::tooltip(sprintf("%s (%s)", $bug->j2m['actionholder'], $bug->j2m['actionholderid']) , 'action holder', '', $bug->j2m['actionholder']); } else { echo "&nbsp;"; } ?> </td> <?php } ?> <?php if ($this->hasduedate) { ?> <td> <?php echo JHTML::tooltip($duedate_long , 'due date', '', $duedate_short) ?> </td> <?php } ?> <td> <?php echo JHTML::tooltip($last_updated_long , 'last update', '', $last_updated_short) ?> </td> </tr> <?php } ?> </table> </br> <a href="?option=com_j2mantis&amp;view=addbug&amp;Itemid=<?php echo JRequest::getInt('Itemid', 0);?>"><?php echo JText::_('Add new bug report');?></a> </br> </br> <h3>Filter list..</h3> <form method="post" action="?option=com_j2mantis&amp;task=display&amp;Itemid=<?php echo JRequest::getInt('Itemid', 0);?>" enctype="multipart/form-data"> <select name="allowed_state[]" multiple="multiple" STYLE="width: 200px; margin:0;"> <option <?php if ( in_array(10,$this->allowed_states) ) { echo "selected"; } ?> value="10">new</option> <option <?php if ( in_array(50,$this->allowed_states) ) { echo "selected"; } ?> value="50">assigned</option> <option <?php if ( in_array(80,$this->allowed_states) ) { echo "selected"; } ?> value="80">resolved</option> <option <?php if ( in_array(90,$this->allowed_states) ) { echo "selected"; } ?> value="90">closed</option> <option <?php if ( in_array(20,$this->allowed_states) ) { echo "selected"; } ?> value="20">feedback</option> <option <?php if ( in_array(30,$this->allowed_states) ) { echo "selected"; } ?> value="30">acknowledged</option> <option <?php if ( in_array(40,$this->allowed_states) ) { echo "selected"; } ?> value="40">confirmed</option> </select> <select name="allowed_users[]" multiple="multiple" STYLE="width: 200px; margin:0;"> <option <?php if (( in_array(0,$this->allowed_users) ) || (is_null($this->allowed_users)) ) { echo "selected"; } ?> value=0>- no action holder -</option> <?php foreach ($this->actionholders as $actionholder) { ?> <option <?php if (( in_array($actionholder->id,$this->allowed_users) ) || (is_null($this->allowed_users))){ echo "selected"; } ?> value="<?php echo $actionholder->id; ?>"><?php echo $actionholder->name; ?></option> <?php } ?> </select> <input style="background-color: lightsteelblue;" type="submit" value="<?php echo JText::_('submit');?>"> </form> </div> <file_sep>/soa_objects/note.php <?php class Note{ var $id = 0; var $reporter = null; var $text = null; var $view_state = null; var $date_submitted = null; var $last_modified = null; } ?><file_sep>/JoomlaMantisController.class.php <?php /** * @package Joomla.J2Mantis * @subpackage Components * components/com_J2Mantis/JoomlaMantisController.class.php * @license GNU/GPL */ // No direct access defined( '_JEXEC' ) or die( 'Restricted access' ); // import controller jimport('joomla.application.component.controller'); require_once( JPATH_COMPONENT_SITE.DS.'Helper.class.php'); /** * Main Controller for J2Mantis Component */ class JoomlaMantisController extends JController { /** * basic constructor */ function __construct(){ parent::__construct(array('name'=>'J2Mantis')); $this->registerTask('addBug','addBug'); $this->registerTask('addNote','addNote'); } /** * add a Bug from the Request to Mantis using SOA * */ function addBug(){ if($_POST['check']!=JUtility::getToken()) { //First verify if by a javascript error or other possibilities the form has not been submitted without the validation if ($_POST['check']=='post') $errors[] = 'Bitte aktivieren sie Javascript!'; //If then still the check isn't a valid token, do nothing as this might be a spoof attack or other invalid form submission //return false; } $app = JFactory::getApplication('site'); $params = JFactory::getApplication()->getParams('com_j2mantis'); $errors = array(); if($params->get('captcha') && !plgSystemJCCReCaptcha::confirm( $_POST['recaptcha_response_field'] )){ $errors[] = "captcha falsch!"; } $summary = JRequest::getString('summary',''); $category = JRequest::getString('category',''); $description = $app->input->get('description', ' ', 'STR'); if ( $description == "" ) { $description="."; } if ( $app->input->get('email', null, 'STR' ) != "" ) { $additional_information = " (" . $app->input->get('email', null, 'STR' ) . ")"; } else { $additional_information=""; } $additional_information = $app->input->get('name', null, 'STR' ) . $additional_information; $priority = JRequest::getInt('priority', 30); // $projectId = JRequest::getInt('project',0); $projectIds = explode(',',$params->get('project')); $projectId=$projectIds[0]; $due_date = $app->input->get('due_date', null, 'STR' ); if ( $due_date == "" ) { $due_date = null; } $ActionholderId = $app->input->get('actionholderId', null, 'STR' ); if(count($errors) > 0){ $_POST['errors'] = $errors; parent::display(); return; } require_once( JPATH_COMPONENT.DS.'soa_objects'.DS.'bug_data.php'); $newBug = new BugData(); $newBug->summary = $summary; $newBug->due_date = $due_date; $newBug->category = $category; $newBug->description = $description; $newBug->additional_information = $additional_information; if ( ( $ActionholderId > 0 ) || ( is_null($ActionholderId))) { $Actionholder=JFactory::getUser($ActionholderId); $j2m['actionholderid']=$ActionholderId; $j2m['actionholder']=$Actionholder->name; $user =& JFactory::getUser(); $j2m['submitterid']=$user->get( 'id' ); $j2m['submitter']=$user->name; $j2m['dts']=strtotime("now"); J2MantisHelper::setJ2M_Status($newBug, $j2m); }; require_once( JPATH_COMPONENT.DS.'soa_objects'.DS.'project_data.php'); $pr = new ProjectData(); $pr->id = $projectId; $newBug->project = $pr; $newBug->priority = $priority; $newBug->severity = 50; $newBug->status = 10; $newBug->reproducibility = ''; $newBug->resolution = ''; $newBug->projection = 10; $newBug->eta = 10; $newBug->view_state = 10; require_once( JPATH_COMPONENT.DS.'JoomlaMantisParameter.class.php'); $settings = new JoomlaMantisParameter(); if($projectId != 0 ){ $settings->setMantisProjectId( $projectId ); } require_once( JPATH_COMPONENT.DS.'MantisConnector.class.php'); $Mantis = new MantisConnector($settings); //var_dump($settings); if($result = $Mantis->addBug($newBug)){ $result = base64_encode($Mantis->encode((string)$result)); $this->setRedirect('index.php?option=com_j2mantis&view=showbug&bugid='.$result.'&Itemid='.JRequest::getInt('Itemid',0)); }else{ $to = $params->get('email'); $text = $newBug->description . "\n"; $text .= $newBug->category . "\n"; $text .= $newBug->additional_information . "\n"; $text .= $newBug->summary . "\n\n\n"; $text .= "Note: this email was sent by j2Mantis, becouse the webservice on ".$params->get('url')." dosn't work"; if(mail($to, 'j2Mantis request', $text)){ echo "Dein Anliegen wurde per EMail übermittelt"; return; }else{ echo "Es ist ein Fehler aufgetreten"; return; } } } function addFile(){ $bugid = JRequest::getInt('bugid', 0); if($bugid == 0){ echo "kein BugId gegeben"; } require_once( JPATH_COMPONENT.DS.'soa_objects'.DS.'bug_attachment.php'); $att = new BugAttachment(); $att->id = $bugid; $att->name = $_FILES['name']['name']; $att->file_type = $_FILES['name']['type']; jimport( 'joomla.filesystem.file' ); $att->content = JFile::read($_FILES['name']['tmp_name']); require_once( JPATH_COMPONENT.DS.'JoomlaMantisParameter.class.php'); $settings = new JoomlaMantisParameter(); require_once( JPATH_COMPONENT.DS.'MantisConnector.class.php'); $Mantis = new MantisConnector($settings); if($Mantis->addAttachment($att)){ $bugid = base64_encode($Mantis->encode((string)$bugid)); $this->setRedirect('index.php?option=com_j2mantis&view=showbug&bugid='.$bugid.'&Itemid='.JRequest::getInt('Itemid',0)); }else{ echo "Es ist ein Fehler aufgetreten"; } } /** * add a Note to a Bug from the Request to Mantis while using SOA * */ function addNote( $text="", $name="", $bugid=0){ if ($bugid == 0) { $name = JRequest::getString('name'); $bugid = JRequest::getInt('bugid', 0); } if($bugid == 0){ echo "kein BugId gegeben"; } if ( ( $name > "" ) ) { $text .= $name . ":\n"; } $text .= JRequest::getString('text'); require_once( JPATH_COMPONENT.DS.'JoomlaMantisParameter.class.php'); $settings = new JoomlaMantisParameter(); require_once( JPATH_COMPONENT.DS.'MantisConnector.class.php'); $Mantis = new MantisConnector($settings); if($Mantis->addNote($bugid, $text)){ $bugid = base64_encode($Mantis->encode((string)$bugid)); $this->setRedirect('index.php?option=com_j2mantis&view=showbug&bugid='.$bugid.'&Itemid='.JRequest::getInt('Itemid',0)); }else{ echo "Es ist ein Fehler aufgetreten"; } } /** * add a Note to a Bug from the Request to Mantis while using SOA * */ function editBug(){ $app = JFactory::getApplication('site'); require_once( JPATH_COMPONENT.DS.'JoomlaMantisParameter.class.php'); $settings = new JoomlaMantisParameter(); require_once( JPATH_COMPONENT.DS.'MantisConnector.class.php'); $Mantis = new MantisConnector($settings); $bugid = $app->input->get('bugid', null, 'INT' ); if( empty($bugid) || $bugid == 0){ echo "no associated bugid"; } $bug = $Mantis->getBug( $bugid ); $due_date = $app->input->get('due_date', null, 'STR' ); $action_holder = $app->input->get('actionholderId', null, 'INT' ); $bugmodified=false; $j2m=J2MantisHelper::getJ2M_Status($bug); $old_action_holder=$j2m['actionholderid']; if ( ( $action_holder >= 0 ) && ( $action_holder != $old_action_holder )) { $j2m=array(); $j2m['actionholderid']=$action_holder; if ( $action_holder ) { $j2m['actionholder']=JFactory::getUser($action_holder)->name; } $user =& JFactory::getUser(); $j2m['submitterid']=$user->get( 'id' ); $j2m['submitter']=$user->name; $j2m['dts']=strtotime("now"); J2MantisHelper::setJ2M_Status($bug, $j2m); $bugmodified=true; }; $action_status = $app->input->get('actionstatus', null, 'INT' ); if ( $action_status != $bug->status->id ) { $bugmodified=true; $bug->status->id = $action_status; } if( empty($due_date) || is_null($due_date)){ $due_date = ""; } if ( $bug->due_date != $due_date ) { // due_date in format Y-m-d, 'm-d-y H:i T'??, what dateformat is configured to be used ? $bug->due_date = $due_date ; $bugmodified=true; } if ($bugmodified) { if ( $Mantis->setBug($bugid,$bug)) { $EncodedBugId = base64_encode($Mantis->encode((string)$bugid)); $Itemid=JRequest::getInt('Itemid',0); $this->setRedirect('index.php?option=com_j2mantis&view=showbug&bugid='.$EncodedBugId.'&Itemid='.$Itemid); }else{ echo "Oops someething went wrong contacting mantis"; } } } /** * Method to display the view * * @access public */ function display($cachable = false, $urlparams = false) { parent::display($cachable, $urlparams); return $this; } } ?> <file_sep>/admin/j2mantis.php <?php /** * @package Joomla.J2Mantis * @subpackage Components * components/com_J2Mantis/J2Mantis.class.php * @license GNU/GPL */ // No direct access defined( '_JEXEC' ) or die( 'Restricted access' ); class ErrorHandler extends Exception { protected $severity; public function __construct($message, $code, $severity, $filename, $lineno) { $this->message = $message; $this->code = $code; $this->severity = $severity; $this->file = $filename; $this->line = $lineno; } public function getSeverity() { return $this->severity; } } function exception_error_handler($errno, $errstr, $errfile, $errline ) { //var_dump($errfile); //throw new ErrorHandler($errstr, 0, $errno, $errfile, $errline); } set_error_handler("exception_error_handler", E_WARNING); JToolBarHelper::preferences( 'com_j2mantis' ,'300'); JToolBarHelper::title('j2Mantis'); echo "<h2>Your current settings</h2>"; $params = &JComponentHelper::getParams( 'com_j2mantis'); echo "<strong>Mantis wsdl Url:</strong> " . $params->get('url') . "<br/>"; echo "<strong>Mantis User:</strong> " . $params->get('username') . "<br/>"; // JPATH_COMPONENT_SITE require_once( JPATH_COMPONENT_SITE.DS.'JoomlaMantisParameter.class.php'); $settings = new JoomlaMantisParameter(); //check if the url is good $page = simplexml_load_file($settings->getWsdlUrl()); //var_dump($page->attributes()->targetNamespace); if($page && $page->attributes()->targetNamespace == 'http://futureware.biz/mantisconnect'){ require_once( JPATH_COMPONENT_SITE.DS.'MantisConnector.class.php'); echo "Connection: <span style='color: #090; font-weight: bold;'>works</span><br/>"; //Getting projects $Mantis = new MantisConnector($settings); $projects = $Mantis->getAllProjects(true,true); if($projects){ echo "Loggin: <span style='color: #090; font-weight: bold;'>works</span><br/>"; echo "access to the following projects: <br/>"; foreach($projects as $id => $p){ echo "- ". $p . " ( ".$id." )<br/>"; } // // Getting filters // $mc_filters = $Mantis->getFiltersOfProject( 13 ); // $p_serialized_filter = $mc_filters[13][2]->filter_string; // $t_setting_arr = explode( '#', $p_serialized_filter, 2 ); // $t_filter_array = array(); // if( isset( $t_setting_arr[1] ) ) { // $t_filter_array = unserialize( $t_setting_arr[1] ); // } else { // return false; // } }else{ echo "Loggin: <span style='color: #900; font-weight: bold;'>dont work</span><br/>"; } }else{ echo "Connection: <span style='color: #900; font-weight: bold;'>dont work</span><br/>"; } ?> <file_sep>/MantisConnector.class.php <?php /** * Handle the connection with Mantis and make the SOA Calls */ class MantisConnector{ /** * JoomlaMantisParameter.class instance */ private $settings; /** * basic consturctor for the Connector * @param JoomlaMantisParameter * @return void */ function __construct(&$JoomlaMantisParameter){ $this->settings = $JoomlaMantisParameter; } /** * Add attachment to mantis bug report. * @param object Class with attachment data inside. * @return mixed Returns false if attaching failed, number of issue otherwise. */ public function addAttachment( $attachment ){ $client = new soapclient($this->settings->getWsdlUrl()); //webservice might throw exception... try{ $result = $client->mc_issue_attachment_add($this->settings->getMantisUser(),$this->settings->getMantisPassword(), $attachment->id, $attachment->name, $attachment->file_type, $attachment->content); } catch (Exception $e){ Logging::getInstance()->logException($e); return false; } return $result; } protected function setStatusToReOpen($mantisId){ $client = new soapclient($this->setting->getWsdlUrl()); $getBug = $client->mc_issue_get($this->setting->getMantisUser(),$this->setting->getMantisPassword(), $mantisId); if($getBug->status->id <= 20){ return; } $getBug->status->id = 20; try{ $client->mc_issue_update($this->setting->getMantisUser(),$this->setting->getMantisPassword(), $mantisId, $getBug); }catch (Exception $e){ return false; } } /** * get all categories of the project define in the settings * * @return ArrayString */ public function getAllCategoriesOfProject(){ try{ $client = new soapclient($this->settings->getWsdlUrl()); }catch (Exception $e){ return false; } require_once( JPATH_COMPONENT_SITE.DS.'soa_objects'.DS.'bug_data.php'); foreach( $this->settings->getMantisProjectIds() as $id ){ try{ $getArray[$id] = $client->mc_project_get_categories($this->settings->getMantisUser(),$this->settings->getMantisPassword(), $id ); }catch (Exception $e){ $getArray[$id] = array(); } } return $getArray; } /** * @param $id * @return bool */ public function getFiltersOfProject( $id ){ try{ $client = new soapclient($this->settings->getWsdlUrl()); }catch (Exception $e){ return false; } require_once( JPATH_COMPONENT_SITE.DS.'soa_objects'.DS.'filter_data.php'); $getArray[$id] = $client->mc_filter_get($this->settings->getMantisUser(),$this->settings->getMantisPassword(), $id ); return $getArray; } /** * get all definition of projects define in the settings * * @return ArrayObject */ public function getAllProjects($withSubProjects = true, $noCheck = false){ try{ $client = new soapclient($this->settings->getWsdlUrl()); }catch (Exception $e){ return false; } require_once( JPATH_COMPONENT_SITE.DS.'soa_objects'.DS.'bug_data.php'); try{ $getArray = $client->mc_projects_get_user_accessible($this->settings->getMantisUser(),$this->settings->getMantisPassword() ); }catch (Exception $e){ //var_dump($e); $getArray = array(); } //var_dump($getArray); $returnArray = array(); $projectids=$this->settings->getMantisProjectIds(); while( !empty($getArray) ){ $project = array_pop($getArray); if( ( in_array( $project->id, $projectids ) || $noCheck ) && $project->enabled ){ $returnArray[$project->id] = $project->name; } if( $withSubProjects ){ foreach( $project->subprojects as $p ){ $p->name = $project->name . " >> " . $p->name; $p->parrentId = $project->id; // $this->settings->addMantisProjectId($p->id); // why change it? array_push($getArray, $p ); } } } return $returnArray; } /** * give all Bugs from the current Project store in the Settings * * @return array BugData */ public function getAllBugsOfProject(){ $client = new soapclient($this->settings->getWsdlUrl()); require_once( JPATH_COMPONENT_SITE.DS.'soa_objects'.DS.'bug_data.php'); try{ $getBugArray = $client->mc_project_get_issues($this->settings->getMantisUser(),$this->settings->getMantisPassword(), $this->settings->getMantisProjectId()); }catch (Exception $e){ return false; } return $getBugArray; } /** * give all Bugs from the current Project store in the Settings * * @return array BugData */ public function getAllBugsOfAllProjects(){ $client = new soapclient($this->settings->getWsdlUrl()); require_once( JPATH_COMPONENT_SITE.DS.'soa_objects'.DS.'bug_data.php'); $getBugArray = array(); foreach($this->settings->getMantisProjectIds() as $id){ try{ //mc_filter_get_issuesRequest $page_len=50; // range 1 .. for ($page = 1; true; $page++) { $getBugArrayPage = $client->mc_project_get_issues($this->settings->getMantisUser(), $this->settings->getMantisPassword(), $id, $page, $page_len); if (sizeof($getBugArrayPage)) { $getBugArray = array_merge($getBugArray, $getBugArrayPage); if (sizeof($getBugArrayPage)<$page_len) { break; } } else { break; } } }catch (Exception $e){ //return false; //var_dump($e); } } /* TODO due_date is NOT available in SOAP list query as mantis 1.2.14 .., only part of "IssueData", requiring additional call on details for every listed item * or patch mantis (http://www.mantisbt.org/bugs/view.php?id=15522) * mantisbt/api/soap/mc_issue_api.php * at LINE 1355 function mci_issue_data_as_array( $p_issue_data, $p_user_id, $p_lang ) * add before return: $t_issue['due_date'] = SoapObjectsFactory::newDateTimeVar( $p_issue_data->due_date ) ; */ return $getBugArray; } /** * get a Bug by hi Id * * @param int $bugID * @return BugData */ public function getBug($bugID){ require_once( JPATH_COMPONENT.DS.'soa_objects'.DS.'bug_data.php'); if(empty($bugID)){ return new BugData(); } $client = new soapclient($this->settings->getWsdlUrl()); try{ $getBug = $client->mc_issue_get($this->settings->getMantisUser(),$this->settings->getMantisPassword(), $bugID); }catch (Exception $e){ return false; } return $getBug; } /** * set a Bug by hi Id * @param $bugID * @param $bug * @return bool */ public function setBug($bugID,$bug){ require_once( JPATH_COMPONENT.DS.'soa_objects'.DS.'project_data.php'); if(empty($bugID)){ return; } $client = new soapclient($this->settings->getWsdlUrl()); try{ $setBug = $client->mc_issue_update($this->settings->getMantisUser(),$this->settings->getMantisPassword(), $bugID, $bug); }catch (Exception $e){ return false; } return true; } /** * Add bug report to mantis using webservice. * @param object Class with bug report data inside. * @return mixed Returns false if attaching failed, number of issue otherwise. */ public function addBug($bug) { require_once( JPATH_COMPONENT.DS.'soa_objects'.DS.'project_data.php'); $client = new soapclient($this->settings->getWsdlUrl()); //webservice might throw exception... try{ $result = $client->mc_issue_add($this->settings->getMantisUser(),$this->settings->getMantisPassword(), $bug); } catch (Exception $e){ //var_dump($e); return false; } return $result; } /** * add a Note to this Bug * * @param int $bugId * @param string $text * @return multible, false on error */ public function addNote($bugId, $text){ $client = new soapclient($this->settings->getWsdlUrl()); require_once( JPATH_COMPONENT.DS.'soa_objects'.DS.'note.php'); $note = new Note(); $note->text = $text; //webservice might throw exception... try{ $result = $client->mc_issue_note_add($this->settings->getMantisUser(),$this->settings->getMantisPassword(), $bugId, $note); } catch (Exception $e){ //var_dump($e); return false; } return $result; } function encode($text, $key = 'S4Gengu6weopgrk') { $somekey = $this->settings->getKey(); if(!empty($somekey)){ $key = $this->settings->getKey(); } $l_k = strlen($key); $l_t = strlen($text); if($l_k == 0) return $text; // Ohne Key keine Verschlüsselung!!! $encoded = ""; $k = 0; // Position im Key for($i=0; $i<$l_t; $i++) { if($k > $l_k) $k = 0; // Wenn ende des keys, dann wieder von vorne $encoded .= chr(ord($text[$i]) ^ ord($key[$k])); // Verschlüsselung $k++; } return $encoded; } } ?> <file_sep>/views/showbug/tmpl/default.php <?php // No direct access defined('_JEXEC') or die('Restricted access'); ?> <?php JHTML::stylesheet('j2mantis.css', 'components/com_j2mantis/assets/'); $timezone_offset = -date("H", strtotime("Y-m-d", time()))+1; $fmt_date_long = "Y/m/d H:i"; $fmt_date_short = "d M"; ?> <div class="j2m_showbug<?php echo $this->moduleclass_sfx ?>" id="j2Mantis"> <!-- <a href="?option=com_j2mantis" style="float: right">zurück zur Übersicht</a> --> <h2><?php echo JText::_('Action holder & due date');?></h2> <form method="post" action="?option=com_j2mantis&amp;task=editBug&amp;Itemid=<?php echo JRequest::getInt('Itemid', 0);?>" enctype="multipart/form-data"> <input type="hidden" name="bugid" value="<?php echo $this->bug->id ?>"/> <label for="duedate"><?php echo JText::_('Due date');?></label> <?php echo JHTML::_('calendar', $this->due_date, 'due_date', 'dd_id', '%Y-%m-%d', array('class' => 'inputbox', 'size' => '12', 'maxlength' => '10')); ?> <br/> <?php if (isset($this->actionholders)) { ?> <label>Actionholder:</label> <select name="actionholderId" STYLE="width: 200px"> <option <?php if ($this->default_autionholderid == -1) { ?> selected <?php } ?> value="-1">- none - </option> <?php foreach ($this->actionholders as $actionholder) { ?> <option <?php if ($this->default_autionholderid == $actionholder->id) { ?> selected <?php } ?> value="<?php echo $actionholder->id; ?>"><?php echo $actionholder->name; ?></option> <?php } ?> </select> <br/> <?php } ?> <label>Actionstatus:</label> <select name="actionstatus" default="<?php echo $this->bug->status->id ?>" STYLE="width: 200px"> <option <?php $val=10; if ($val==$this->bug->status->id) { echo "selected ";} echo "value=\"".$val ?>">new</option> <option <?php $val=50; if ($val==$this->bug->status->id) { echo "selected ";} echo "value=\"".$val ?>">assigned</option> <option <?php $val=80; if ($val==$this->bug->status->id) { echo "selected ";} echo "value=\"".$val ?>">resolved</option> <option <?php $val=90; if ($val==$this->bug->status->id) { echo "selected ";} echo "value=\"".$val ?>">closed</option> <option <?php $val=20; if ($val==$this->bug->status->id) { echo "selected ";} echo "value=\"".$val ?>">feedback</option> <option <?php $val=30; if ($val==$this->bug->status->id) { echo "selected ";} echo "value=\"".$val ?>">acknowledged</option> <option <?php $val=40; if ($val==$this->bug->status->id) { echo "selected ";} echo "value=\"".$val ?>">confirmed</option> </select> <br/> <input style="float:right; background-color: lightsteelblue;" type="submit" value="<?php echo JText::_('submit');?>"> <br/> </form> <h2><?php echo $this->caption; ?></h2> <table id="mt_overview"> <tr class="head"> <td> <?php echo JText::_('Status');?>: <?php echo $this->bug->status->name ?> </td> <td> <?php echo $this->bug->category . " <i>" . JText::_('in') . "</i> " . $this->bug->project->name;?> </td> <td> <?php $uxts_last_updated = strtotime($this->bug->last_updated . " +" . $timezone_offset . " hours"); $last_updated_long = date($fmt_date_long, $uxts_last_updated); echo $last_updated_long; ?> </td> </tr> <tr> <td colspan="3"> <?php echo $this->bug->summary ?> </td> </tr> <tr> <td colspan="3"> <?php echo nl2br($this->bug->description) ?> </td> </tr> <?php if (!empty($this->additional_info_readonly)) { ?> <tr> <td colspan="3"> <?php echo $this->additional_info_readonly;nl2br($this->additional_info_readonly); ?> </td> </tr> <?php }; ?> <?php if (count($this->bug->attachments) > 0): ?> <tr> <td><?php echo JText::_('File');?>:</td> <td colspan="2"> <?php foreach ($this->bug->attachments as $att): ?> <p><?php echo $att->filename ?> ( <i><?php echo gmdate("d.m.Y H:i", strtotime($att->date_submitted)); ?></i> )</p> <?php endforeach; ?> </td> </tr> <?php endif; ?> </table> <h2><?php echo JText::_('attach File');?></h2> <form method="post" action="?option=com_j2mantis&amp;task=addFile&amp;Itemid=<?php echo JRequest::getInt('Itemid', 0);?>" enctype="multipart/form-data"> <input type="hidden" name="bugid" value="<?php echo $this->bug->id ?>"/> <label for="name">File:</label> <input type="file" name="name" size="30" id="name" maxlength="100000"/><br/> <input style="float:right; background-color: lightsteelblue;" type="submit" value="<?php echo JText::_('submit');?>"> </form> <?php //var_dump($this->bug); ?> <?php if (is_array($this->bug->notes) && sizeof($this->bug->notes) > 0) { ?> <br/> <h2><?php echo JText::_('Notes');?></h2> <table> <?php foreach ($this->bug->notes as $note) { ?> <tr> <td class="author"> <?php echo $note->reporter->real_name; ?> <br/> <span> <?php $uxts_submitted = strtotime($note->date_submitted . " +" . $timezone_offset . " hours"); $last_submitted = date($fmt_date_long, $uxts_submitted); echo $last_submitted; ?> </td> <td> <?php echo nl2br($note->text); //var_dump($note)?> </td> </tr> <?php } ?> </table> <?php } ?> <?php if ($this->bug->status->id < 90) { /* check if closed */ ?> <br/> <h2><?php echo JText::_('add Note');?></h2> <form method="post" action="?option=com_j2mantis&amp;task=addNote&amp;Itemid=<?php echo JRequest::getInt('Itemid', 0);?>"> <input type="hidden" name="bugid" value="<?php echo $this->bug->id ?>"/> <label for="name"><?php echo JText::_('Name'); if ($this->fo_name == 1) echo '*';?></label> <input type="text" name="name" id="name" <?php if ($this->fo_name == 1) echo 'class="required"'; if (!$this->fo_nameedit) echo ' readonly'; ?> <?php if (!empty($this->user->name)) { echo 'value="' . $this->user->name . ' [' . $this->user->username . ']"'; } ?> /> <br/> <label for="text"><?php echo JText::_('Note');?></label> <textarea rows="5" cols="50" name="text" id="text"></textarea> <input style="float:right; background-color: lightsteelblue; clear:both" type="submit" value="<?php echo JText::_('submit');?>"> </form> <?php } ?> <br/> <?php $params = &JComponentHelper::getParams('com_j2mantis'); ?> <?php if ((string)$params->get('overview') != '0'): ?> <a href="?option=com_j2mantis&amp;Itemid=<?php echo JRequest::getInt('Itemid', 0);?>"><?php echo JText::_('Return to Report Overview');?></a> <?php endif; ?> </div> <file_sep>/views/j2mantis/view.html.php <?php /** * @package Joomla.J2Mantis * @subpackage Components * components/com_J2Mantis/view/view.html.php * @license GNU/GPL */ // no direct access defined( '_JEXEC' ) or die( 'Restricted access' ); jimport( 'joomla.application.component.view'); require_once( JPATH_COMPONENT_SITE.DS.'Helper.class.php'); /** * HTML View class for the J2Mantis Component * * @package J2Mantis */ class J2MantisViewj2mantis extends JView { var $sort_on; var $sort_order; function issue_compare($a, $b) { $on=$this->sort_on; if ( in_array( $on, array('priority', 'severity', 'status', 'project', 'handler', 'reporter', 'resolution' ) ) ) { $aa=$a->$on->id; $bb=$b->$on->id; } elseif ( in_array( $on, array( 'last_updated', 'due_date', 'summary', 'date_submitted', 'additional_information', 'description' ) ) ) { // add configuration item to make searching case sensative if ( $this->sort_case ) { $aa=strtolower($a->$on); $bb=strtolower($b->$on); } else { $aa=$a->$on; $bb=$b->$on; } } else { // 'id', 'sticky' $aa=$a->$on; $bb=$b->$on; } if ($aa == $bb) { return 0; } return ($aa < $bb) ? -$this->sort_order : $this->sort_order; } /** * Sort the issue list * * @param $array * @param string $sort_on : field from IssueData to sort on, 'NONE' implies no sorting * @param int $sort_order * @return mixed */ function issue_array_sort($array, $sort_on='last_updated', $sort_order=1, $sort_case=0 ) { $this->sort_on=$sort_on; $this->sort_order=$sort_order; $this->sort_case=$sort_case; if ( (count($array) > 0) && ( $sort_on != 'NONE' ) ) { uasort($array, array($this, 'issue_compare')); } return $array; } function display($tpl = null) { $app = &JFactory::getApplication(); if ($app->isSite()) { // when on 'site' merge menu and 'component' $params = $app->getParams('com_j2mantis'); } else { $params = &JComponentHelper::getParams('com_j2mantis'); } $overview = $params->get('overview'); if(empty($overview)){ echo "no overview allowed"; return; } require_once( JPATH_COMPONENT.DS.'JoomlaMantisParameter.class.php'); $settings = new JoomlaMantisParameter(); require_once( JPATH_COMPONENT.DS.'MantisConnector.class.php'); $Mantis = new MantisConnector($settings); $findIds = $settings->getMantisProjectIds(); if( empty( $findIds ) || (sizeof($findIds)==1 && $findIds[0] == 0) ){ foreach($Mantis->getAllProjects(false, true) as $id => $p){ $settings->addMantisProjectId($id); } } $action_acl = $params->get('access'); $action_user_ids = J2MantisHelper::getAuthorisedViewLevelsUsers($action_acl); jimport('joomla.user.user'); foreach ($action_user_ids as $action_user_id) { $this->actionholders[] = JFactory::getUser($action_user_id); } $bugs = $Mantis->getAllBugsOfAllProjects(); $bugs = $this->issue_array_sort($bugs,$params->get('sort_on'), $params->get('sort_order'), $params->get('sort_case')); $hasactionholders=false; $hasduedate=false; $filter_states = $params->get('filter_states'); $allowed_states = $app->input->get('allowed_state', null, 'ARRAY' ); if ( (! is_null($filter_states)) && (is_null($allowed_states)) ) { $allowed_states=$filter_states; } $allowed_users = $app->input->get('allowed_users', null, 'ARRAY' ); for( $idx=count($bugs)-1; $idx>=0; $idx--) { $bug=$bugs[$idx]; $bug->j2m=J2MantisHelper::getJ2M_Status($bug); $actionholderid=$bug->j2m['actionholderid']; if (is_null($actionholderid)) { $actionholderid=0; } if ((in_array($bug->status->id,$allowed_states) || (is_null($allowed_states))) && ((in_array($actionholderid,$allowed_users)) || (is_null($allowed_users)) )){ $hasactionholders =($hasactionholders)||($bug->j2m[actionholder]); $hasduedate =($hasduedate) ||($bug->due_date); } else { // remove filtered items unset($bugs[$idx]); }; } $this->allowed_states=$allowed_states; $this->allowed_users=$allowed_users; $this->hasactionholders=$hasactionholders; $this->hasduedate=$hasduedate; $this->bugs = $bugs; $this->mantis=$Mantis; $this->moduleclass_sfx=$params->get('moduleclass_sfx',""); $this->user = JFactory::getUser(); $this->defCaption = $settings->getMantisCaption(); $this->fo_name = $settings->getmantisFo_name(); $this->fo_nameedit = $settings->getmantisFo_nameedit(); $this->fo_email = $settings->getmantisFo_email(); $this->fo_emailedit = $settings->getmantisFo_emailedit(); if( $this->user->id==0 ){ // no logged in user, then edit cannot be false if field required if ($this->fo_name == 1 ) $this->fo_nameedit = 1; if ($this->fo_email == 1 ) $this->fo_emailedit = 1; } $this->caption = ($this->defCaption) ? $this->defCaption : JText::_('Report Overview'); parent::display($tpl); } } ?><file_sep>/languages/en-GB.com_j2mantis.ini ADD NEW BUG REPORT=Add new bug report ADD NOTE=add note ATTACH FILE=attach file CATEGORY=Category DESCRIPTION=Description E-MAIL=E-Mail ERROR=Error FILE=File HIGH=high NAME=Name NEW PROBLEM ADDED= New problem added NOTE=Note NOTES=Notes NORMAL=normal LAST UPDATE=last update LOW=low SHORT DESCRIPTION=Short Description Submit=Submit Summary=Summary STATUS=status PRIORITY=Priority PROBLEM DESCRIPTION=problem description PLEASE CHECK THE FORM=please check the form RETURN TO REPORT OVERVIEW=Return to Report Overview REPORT OVERVIEW=Mantis Report Overview! <file_sep>/languages/de-DE.com_j2mantis.ini ADD NEW BUG REPORT=Neues Problem hinzufügen ADD NOTE=Notiz hinzufügen ATTACH FILE=Datei hinzufügen CATEGORY=Kategorie DESCRIPTION=Beschreibung E-MAIL=E-Mail ERROR=Fehler FILE=Datei HIGH=hoch NAME=Name NEW PROBLEM ADDED=neues Problem hinzugefügt NOTE=Notiz NOTES=Notizen NORMAL=normal LAST UPDATE=letztes update LOW=gering SHORT DESCRIPTION=Kurzbeschreibung SUBMIT=Absenden SUMMARY=Zusammenfassung STATUS=Status PRIORITY=Wichtigkeit PROBLEM DESCRIPTION=Problembeschreibung PROJECT=Projekt PLEASE CHECK THE FORM=Bitte überprüfen sie die Eingabe. RETURN TO REPORT OVERVIEW=zurück zum Reportübersicht REPORT OVERVIEW=Mantis Reportübersicht MANTIS OVERVIEW=Mantis Übersicht <file_sep>/JoomlaMantisParameter.class.php <?php /** * @package Joomla.J2Mantis * @subpackage Components * components/com_J2Mantis/JoomlaMantisParameter.class.php * @license GNU/GPL */ // No direct access defined( '_JEXEC' ) or die( 'Restricted access' ); /** * Contains all configuration parameter * * @author <NAME> */ class JoomlaMantisParameter { /** * The project name of bugs * * @var string */ private $mantisProjectName; /** * the project id of bugs * * @var int */ private $mantisProjectId; /** * multiple project ids * * @var int of array */ private $mantisProjectIds; /** * The name of the custome field which contain the name of a customer. * * @var string */ private $mantisCustomerField; /** * The user to login into mantis * * @var string */ private $mantisUser; /** * The passwort to login into mantis. * * @var string */ private $mantisPassword; /** * The caption for form * * @var string */ private $mantisCaption; /** * The URL to the websersice description file * * @var string */ private $wsdlUrl; private $key; /** * basic constructor * * @param string $url the wsdl url * @param string $user Mantis Username * @param string $passwd <PASSWORD> of the Mantis Account * @param string $name The name of the Projekt */ function __construct($name = '', $isAdmin = false) { // configuration params, combining parameters from "component" and "menu" level $app = JFactory::getApplication(); if ($app->isSite()) { // when on 'site' merge menu and 'component' $params = $app->getParams('com_j2mantis'); $this->mantisFo_name = $params->get('fo_name', 0); $this->mantisFo_nameedit = $params->get('fo_nameedit', 1); $this->mantisFo_email = $params->get('fo_email', 0 ); $this->mantisFo_emailedit = $params->get('fo_emailedit', 1); } else { $params = &JComponentHelper::getParams('com_j2mantis'); } $this->wsdlUrl = $params->get('url'); $this->mantisUser = $params->get('username'); $this->mantisPassword = $params->get('password'); $this->mantisProjectIds = preg_split('/,/', $params->get('project')); $this->mantisProjectId = $this->mantisProjectIds[0]; $this->key = $params->get('key'); $this->mantisProjectName = $name; } /** * @see $mantisProjectName * @return string */ public function getMantisProjectName() { return $this->mantisProjectName; } public function getMantisProjectId(){ return $this->mantisProjectId; } public function setMantisProjectId($id){ if( in_array($id, $this->mantisProjectIds ) ){ $this->mantisProjectId = $id; } } public function getMantisProjectIds(){ return $this->mantisProjectIds; } public function addMantisProjectId($id){ if( !in_array( $id, $this->mantisProjectIds ) ) array_push( $this->mantisProjectIds, $id); } /** * @see $mantisCustomerField * @return string */ public function getMantisCustomerField() { return $this->mantisCustomerField; } /** * @see $mantisUser * @return string */ public function getMantisUser() { return $this->mantisUser; } /** * @see $mantisPassword * @return string */ public function getMantisPassword() { return $this->mantisPassword; } /** * @see $mantisCaption * @return string */ public function getMantisCaption() { return $this->mantisCaption; } public function getmantisFo_name() { return $this->mantisFo_name; } public function getmantisFo_nameedit() { return $this->mantisFo_nameedit; } public function getmantisFo_email() { return $this->mantisFo_email; } public function getmantisFo_emailedit() { return $this->mantisFo_emailedit; } /** * @see $wsdlUrl * @return string */ public function getWsdlUrl() { return $this->wsdlUrl; } public function getKey(){ return $this->key; } } ?> <file_sep>/soa_objects/bug_attachment.php <?php class BugAttachment{ var $id=0; var $name = null; var $file_type = null; var $content = null; } ?><file_sep>/soa_objects/bug_data.php <?php class BugData { var $id = null; var $view_state = null; var $last_updated = null; var $project = null; var $category = null; var $priority = null; var $severity = null; var $status = null; var $reporter = null; var $summary = null; var $version = null; var $build = null; var $platform = null; var $os = null; var $os_build = null; var $reproducibility = null; var $date_submitted = null; var $sponsorship_total = null; var $handler = null; var $projection = null; var $eta = null; var $resolution = null; var $fixed_in_version = null; var $description = ""; var $steps_to_reproduce = null; var $additional_information = null; var $attachments = null; var $relationships = null; var $notes = null; var $custom_fields = null; } ?>
71477f6acd6cc47521613422d08a3d1b6672ce2f
[ "PHP", "INI" ]
17
PHP
marcodings/j2Mantis---Joomla-1.6
136a4a24ca69889e5f1912f305f8ee4c6936b150
8566e0a6647473b50f64f218d746179888b8ade3
refs/heads/main
<repo_name>alexjamesmalcolm/secret-santa<file_sep>/src/hooks/usePeopleManager/index.ts import { useCallback, useMemo, useState } from "react"; const usePeopleManager = () => { const [people, setPeople] = useState<Set<string>>(new Set()); const addPerson = useCallback<(name: string) => void>( (name) => { const temp = new Set(people); temp.add(name); setPeople(temp); }, [people] ); const removePerson = useCallback<(name: string) => void>( (name) => { const temp = new Set(people); temp.delete(name); setPeople(temp); }, [people] ); const peopleList = useMemo(() => [...people], [people]); return useMemo(() => ({ addPerson, removePerson, people: peopleList }), [ addPerson, peopleList, removePerson, ]); }; export default usePeopleManager;
67b01eb27e2ab96bf5f1264819b78a9b1423a6fd
[ "TypeScript" ]
1
TypeScript
alexjamesmalcolm/secret-santa
17ea2c91ef8d67bd004a60f427bab3c2544b2536
f6d2b43c16b2887c25cb4cf22ff7330c16df2152
refs/heads/master
<file_sep>package edu.buffalo.cse562; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import net.sf.jsqlparser.expression.BinaryExpression; import net.sf.jsqlparser.expression.BooleanValue; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.LeafValue; import net.sf.jsqlparser.schema.Column; public class SelectionOperator extends Eval implements Operator { Operator inputOperator; Expression whereCondition; Tuple tuple = null; public SelectionOperator(Operator inputOperator, Expression condition) { super(); this.inputOperator = inputOperator; this.whereCondition = condition; } @Override public void open() { //////////////System.out.println("---------SELECT-------\n"); inputOperator.open(); } @Override public Tuple getNextTuple() { try { do { tuple = inputOperator.getNextTuple(); if(whereCondition == null) return tuple; if(tuple == null) break; ////////////////System.out.println(tuple); // ////////////////////////////////////////////////////System.out.println(whereCondition); LeafValue status = super.eval(whereCondition); //////////System.out.println(status.toString()); if (status instanceof BooleanValue) { if (status == BooleanValue.FALSE) { tuple = null; } } } while (tuple == null); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return tuple; } @Override public void close() { inputOperator.close(); } @Override public LeafValue eval(Column col) throws SQLException { return tuple.get(col.getWholeColumnName()); } } <file_sep>package edu.buffalo.cse562; import java.sql.SQLException; import java.util.ArrayList; import java.util.LinkedHashMap; import net.sf.jsqlparser.expression.BooleanValue; import net.sf.jsqlparser.expression.DoubleValue; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.LeafValue; import net.sf.jsqlparser.expression.StringValue; import net.sf.jsqlparser.expression.operators.relational.EqualsTo; import net.sf.jsqlparser.schema.Column; import net.sf.jsqlparser.schema.Table; import net.sf.jsqlparser.statement.select.FromItem; import net.sf.jsqlparser.statement.select.Join; public class JoinOperator extends Eval implements Operator { public Operator inputOperator; public Operator joinInputOperator; public FromItem fromTable; public Join join; // public Expression whereCondition; Tuple fromTuple = null; Tuple joinTuple = null; public JoinOperator(Operator inputOperator, Operator joinInputOperator, FromItem fromTable, Join join) { super(); this.joinInputOperator = joinInputOperator; this.inputOperator = inputOperator; this.fromTable = fromTable; this.join = join; // this.whereCondition = whereCondition; } @Override public void open() { //////////////System.out.println("---------JOIN-------\n"); // TODO Auto-generated method stub inputOperator.open(); joinInputOperator.open(); joinTuple = joinInputOperator.getNextTuple(); } @Override public Tuple getNextTuple() { Tuple joinedTuple = null; if (true) { do { fromTuple = inputOperator.getNextTuple(); if (fromTuple == null) { joinTuple = joinInputOperator.getNextTuple(); inputOperator.close(); inputOperator.open(); } } while (fromTuple == null); do { if (joinTuple == null) break; LinkedHashMap<String, LeafValue> joinedTupleMap = new LinkedHashMap<String, LeafValue>(); joinedTupleMap.putAll(fromTuple.getTupleMap()); joinedTupleMap.putAll(joinTuple.getTupleMap()); joinedTuple = new Tuple(joinedTupleMap); //fromTuple.appendTuple(); } while (joinTuple == null); } return joinedTuple; } @Override public void close() { // TODO Auto-generated method stub inputOperator.close(); joinInputOperator.close(); } @Override public LeafValue eval(Column col) throws SQLException { if (col.getTable().getName().equalsIgnoreCase(((Table)fromTable).getName())) { return fromTuple.get(col.getWholeColumnName()); } else if (col.getTable().getName().equalsIgnoreCase(((Table)join.getRightItem()).getName())) { return joinTuple.get(col.getWholeColumnName()); } return null; } } <file_sep>package edu.buffalo.cse562; public interface Operator{ public void open(); public Tuple getNextTuple() ; public void close(); } <file_sep>package edu.buffalo.cse562; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map.Entry; import net.sf.jsqlparser.expression.DoubleValue; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.Function; import net.sf.jsqlparser.expression.LeafValue; import net.sf.jsqlparser.expression.LeafValue.InvalidLeaf; import net.sf.jsqlparser.expression.operators.relational.ExpressionList; import net.sf.jsqlparser.schema.Column; class AverageValue implements LeafValue{ public Double sum; public Double count; public AverageValue(Double sum, Double count) { super(); this.sum = sum; this.count = count; } @Override public double toDouble() throws InvalidLeaf { // TODO Auto-generated method stub return 0; } @Override public long toLong() throws InvalidLeaf { // TODO Auto-generated method stub return 0; } @Override public String toString() { return "AverageValue [sum=" + sum + ", count=" + count + "]"; } } public class GroupProperties extends Eval{ Tuple tuple = null; HashMap<Function, LeafValue> results = new HashMap<Function, LeafValue>(); public GroupProperties(ArrayList<Function> functions) { for(Function function: functions){ if(function.getName().equalsIgnoreCase("MIN")){ results.put(function, new DoubleValue(Double.MAX_VALUE)); }else if(function.getName().equalsIgnoreCase("AVG")){ results.put(function, new AverageValue(0.0, 0.0)); }else{ results.put(function, new DoubleValue(0)); } } } // public void init(Function function){ // if(function.getName().equalsIgnoreCase("MIN")){ // results.put(function, new DoubleValue(Double.MAX_VALUE)); // // }else{ // results.put(function, null); // } // // } public void consume(Tuple inputTuple){ Double result; tuple = inputTuple; for (Entry<Function, LeafValue> entry : results.entrySet()){ //////////////////////////////////System.out.println(entry.getKey().getName()); if(entry.getKey().getName().equalsIgnoreCase("SUM")){ result= calculateSum(entry.getKey(), tuple); ////////////////////////////////////////////System.out.println("result : "+new DoubleValue(result.toString())); results.put(entry.getKey(), new DoubleValue(result.toString())); }else if(entry.getKey().getName().equalsIgnoreCase("AVG")){ LeafValue avg = calculateAvg(entry.getKey(), tuple); results.put(entry.getKey(), avg); }else if(entry.getKey().getName().equalsIgnoreCase("MIN")){ result= calculateMin(entry.getKey(), tuple); results.put(entry.getKey(), new DoubleValue(result.toString())); }else if(entry.getKey().getName().equalsIgnoreCase("MAX")){ result= calculateMax(entry.getKey(), tuple); results.put(entry.getKey(), new DoubleValue(result.toString())); }else if(entry.getKey().getName().equalsIgnoreCase("COUNT")){ result= calculateCount(entry.getKey(), tuple); results.put(entry.getKey(), new DoubleValue(result.toString())); } } } private Double calculateCount(Function function, Tuple tuple2) { ExpressionList params = function.getParameters(); LeafValue value = null; Double count = new Double(0); try { if(function.isAllColumns()){ if(results.containsKey(function)){ count = results.get(function).toDouble(); count++; } return count; } for(Object expression : params.getExpressions()){ value = super.eval((Expression)expression); } if(results.containsKey(function)){ count = results.get(function).toDouble(); count++; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidLeaf e) { // TODO Auto-generated catch block e.printStackTrace(); } return count; } private Double calculateMax(Function function, Tuple tuple2) { ExpressionList params = function.getParameters(); LeafValue value = null; Double max = new Double(0); // ////////////////////////////////System.out.println("Max"); try { for(Object expression : params.getExpressions()){ value = super.eval((Expression)expression); } if(results.containsKey(function)){ max = results.get(function).toDouble(); if(value.toDouble() > max){ max = value.toDouble(); } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidLeaf e) { // TODO Auto-generated catch block e.printStackTrace(); } return max; } private Double calculateMin(Function function, Tuple tuple2) { ExpressionList params = function.getParameters(); LeafValue value = null; Double min = Double.MAX_VALUE; try { for(Object expression : params.getExpressions()){ value = super.eval((Expression)expression); } if(results.containsKey(function)){ min = results.get(function).toDouble(); if(value.toDouble() < min){ min = value.toDouble(); } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidLeaf e) { // TODO Auto-generated catch block e.printStackTrace(); } return min; } private AverageValue calculateAvg(Function function, Tuple tuple2) { ExpressionList params = function.getParameters(); LeafValue value = null; Double sum = new Double(0); Double count = new Double(0); AverageValue avg = new AverageValue(0.0, 0.0); try { for(Object expression : params.getExpressions()){ value = super.eval((Expression)expression); } if(results.containsKey(function)){ avg =(AverageValue) results.get(function); avg.count++; avg.sum += value.toDouble(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidLeaf e) { // TODO Auto-generated catch block e.printStackTrace(); } return avg; } private Double calculateSum(Function function, Tuple tuple) { ////////////System.out.println(function); ExpressionList params = function.getParameters(); LeafValue value = null; Double sum = new Double(0); try { for(Object expression : params.getExpressions()){ value = super.eval((Expression)expression); ////////////System.out.println(value); } if(results.containsKey(function)){ sum = results.get(function).toDouble(); sum = sum+Double.parseDouble(value.toString()); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidLeaf e) { // TODO Auto-generated catch block e.printStackTrace(); } return sum; } public LeafValue roundUp(Function function){ if(results.containsKey(function)){ ////////////////////////////////////////////System.out.println("contains Key"); if(function.getName().equalsIgnoreCase("AVG")) { LeafValue avg = results.get(function); if(avg instanceof AverageValue){ avg = new DoubleValue((((AverageValue) avg).sum)/((AverageValue) avg).count); return avg; } }else return results.get(function); } return null; } @Override public LeafValue eval(Column col) throws SQLException { if(col!=null){ LeafValue value = tuple.get(col.getWholeColumnName()); ////////////System.out.println(col + value.toString()); return value; } return null; } } <file_sep>package edu.buffalo.cse562; import java.io.File; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import net.sf.jsqlparser.schema.Table; import net.sf.jsqlparser.statement.create.table.ColumnDefinition; import net.sf.jsqlparser.statement.select.SelectItem; import net.sf.jsqlparser.expression.DoubleValue; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.LeafValue; import net.sf.jsqlparser.expression.LeafValue.InvalidLeaf; import net.sf.jsqlparser.expression.StringValue; import net.sf.jsqlparser.statement.select.AllColumns; import net.sf.jsqlparser.statement.select.Distinct; import net.sf.jsqlparser.statement.select.FromItem; import net.sf.jsqlparser.statement.select.Join; import net.sf.jsqlparser.statement.select.Limit; import net.sf.jsqlparser.statement.select.PlainSelect; import net.sf.jsqlparser.statement.select.SelectBody; import net.sf.jsqlparser.statement.select.SelectExpressionItem; import net.sf.jsqlparser.statement.select.SubSelect; import net.sf.jsqlparser.statement.select.Union; public class ParseTree { public class Node{ Operator operator; Node[] children; public Node(Operator operator, Node[] children) { super(); this.operator = operator; this.children = children; } } File dataDir; HashMap<String, List<ColumnDefinition>> schema; public ParseTree( File dataDir, HashMap<String, List<ColumnDefinition>> schema) { super(); this.dataDir = dataDir; this.schema = schema; } public Operator createParseTree(SelectBody selectBody){ PlainSelect select = null; if(selectBody instanceof PlainSelect ){ select = (PlainSelect) selectBody; } Operator scanOp = null; FromItem fromTable = select.getFromItem(); ////////////////////////////System.out.println(fromTable.getClass()); if(fromTable instanceof Table){ //////////////////////System.out.println(fromTable.getAlias()); scanOp = new ScanOperator(fromTable, dataDir, schema); }else if(fromTable instanceof SubSelect){ scanOp = createParseTree((PlainSelect)((SubSelect) fromTable).getSelectBody()); } //////////////////////////////System.out.println("FromTable : " + fromTable); Expression whereCondition = select.getWhere(); //SelectOperator // ////////////////////////////////////////////////System.out.println(whereCondition); Operator joinScanOp = null; JoinOperator joinOp = null; Operator selectOp = null; @SuppressWarnings("unchecked") List<Join> joinTables = select.getJoins(); Operator leftJoinOp = scanOp; if(joinTables != null){ //////////////////////////////////////////////System.out.println("Join Detected : " +joinTables); for (Join joinTable : joinTables){ //////////////////////////////////////////////System.out.println(joinTable.getRightItem()); joinScanOp = new ScanOperator(joinTable.getRightItem(), dataDir, schema); leftJoinOp = new JoinOperator(leftJoinOp, joinScanOp ,fromTable, joinTable); selectOp = new SelectionOperator(leftJoinOp, whereCondition); } }else{ selectOp = new SelectionOperator(scanOp, whereCondition); ////////////////////////////////////////////////////System.out.println("whereCondition : " + whereCondition); } Limit limitItem = select.getLimit(); if(limitItem != null){ System.out.print("LimitItem"); int a = 10/0; } @SuppressWarnings("unchecked") List<SelectItem> projectColumns = select.getSelectItems(); //project for(SelectItem projectColumn : projectColumns){ if(projectColumn instanceof SelectExpressionItem){ ((SelectExpressionItem) projectColumn).getAlias(); } } @SuppressWarnings("unchecked") List<Expression> groupBy = select.getGroupByColumnReferences(); //groupBy GroupByOperator groupByOp = new GroupByOperator(selectOp, groupBy, projectColumns, true); Operator projectOp = new ProjectionOperator(groupByOp, projectColumns); ArrayList orderByItems = (ArrayList) select.getOrderByElements(); OrderByOperator orderByOp = new OrderByOperator(projectOp, orderByItems); Distinct distinct = select.getDistinct(); //Distinct GroupByOperator distinctGroupByOp = new GroupByOperator(orderByOp, groupBy, projectColumns, false); List<Expression> distinctItems = new ArrayList<Expression>(); if(distinct != null){ for(SelectItem projectColumn : projectColumns){ if(projectColumn instanceof SelectExpressionItem) distinctItems.add(((SelectExpressionItem) projectColumn).getExpression()); } distinctGroupByOp = new GroupByOperator(orderByOp, distinctItems, projectColumns, true); } Union unionItem = null; UnionOperator unionOp = new UnionOperator(distinctGroupByOp, null);; if(selectBody instanceof Union){ unionItem = (Union) selectBody; List<SelectBody> selects = unionItem.getPlainSelects(); Operator leftUnionOp = createParseTree(selects.get(0)); Operator rightUnionOp = createParseTree(selects.get(1)); unionOp = new UnionOperator(leftUnionOp, rightUnionOp); } Operator rootOperator = distinctGroupByOp; return rootOperator; } public void executeQuery(SelectBody select){ Operator rootOperator = createParseTree(select); rootOperator.open(); Tuple tuple = null; do{ tuple = rootOperator.getNextTuple(); if(tuple == null) break; printOutput(tuple); }while(tuple!=null); rootOperator.close(); } private void printOutput(Tuple tuple) { if (tuple == null) return; ////////////////////////////////////////////System.out.println(tuple); try { ArrayList<String> printBuffer = new ArrayList<String>(); for (Entry<String, LeafValue> keyValue : tuple.getTupleMap().entrySet()) { LeafValue value = keyValue.getValue(); if (value instanceof StringValue) { printBuffer.add(value.toString().replaceAll("^'", "").replaceAll("'$", "")); } else if (value instanceof DoubleValue) { DecimalFormat format = new DecimalFormat("0.##"); printBuffer.add(format.format(value.toDouble())); } else { printBuffer.add(value.toString()); } printBuffer.add("|"); } if (printBuffer.size() > 1) printBuffer.remove(printBuffer.size() - 1); // to remove the // last pipes for (String cell : printBuffer) { System.out.print(cell); } System.out.print("\n"); } catch (InvalidLeaf e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>package edu.buffalo.cse562; import net.sf.jsqlparser.expression.DateValue; import net.sf.jsqlparser.expression.DoubleValue; import net.sf.jsqlparser.expression.LeafValue; import net.sf.jsqlparser.expression.LeafValue.InvalidLeaf; import net.sf.jsqlparser.expression.LongValue; import net.sf.jsqlparser.expression.StringValue; public class Cloner { public static LeafValue clone(LeafValue value) { try { if(value instanceof StringValue){ return new StringValue(value.toString()); }else if(value instanceof DoubleValue){ return new DoubleValue(value.toDouble()); }else if(value instanceof LongValue){ return new LongValue(value.toLong()); }else if(value instanceof DateValue){ return new DateValue("'"+value.toString()+"'"); } } catch (InvalidLeaf e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } } <file_sep>package edu.buffalo.cse562; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map.Entry; import java.util.Set; import net.sf.jsqlparser.expression.DoubleValue; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.Function; import net.sf.jsqlparser.expression.LeafValue; import net.sf.jsqlparser.expression.operators.relational.ExpressionList; import net.sf.jsqlparser.schema.Column; import net.sf.jsqlparser.schema.Table; import net.sf.jsqlparser.statement.select.Distinct; import net.sf.jsqlparser.statement.select.SelectExpressionItem; import net.sf.jsqlparser.statement.select.SelectItem; public class GroupByOperator extends Eval implements Operator{ Operator inputOperator; List<Expression> groupByItems; Set<Tuple> keySet = new HashSet<Tuple>(); List<SelectItem> projectColumns; Tuple tuple = null; Tuple groupByTuple = new Tuple();; Tuple finalTuple = null; ArrayList<Function> functions = new ArrayList<Function>(); Iterator<Tuple> iterator; HashMap<Tuple, GroupProperties> groups = new HashMap<Tuple, GroupProperties>(); Boolean isDistinct ; public GroupByOperator(Operator inputOperator, List<Expression> groupByItems, List<SelectItem> projectColumns, Boolean isDistinct) { super(); this.inputOperator = inputOperator; this.groupByItems = groupByItems; this.projectColumns = projectColumns; this.isDistinct = isDistinct; } @Override public void open() { //////////////System.out.println("---------GROUPBY-------\n"); inputOperator.open(); } @Override public Tuple getNextTuple() { GroupProperties properties; try { if(keySet.isEmpty()){ for (SelectItem projectItem : projectColumns) { if (projectItem instanceof SelectExpressionItem) { Expression expression = ((SelectExpressionItem) projectItem).getExpression(); if (expression instanceof Function) { Function function = ((Function) expression); functions.add(function); String functionName = function.getName(); ExpressionList parameters = function.getParameters(); // ////////////////////////////////////////////System.out.println("function Name & parameters : " // + functionName +"&"+ parameters); //GroupProperties.init(function); } } } do { tuple = inputOperator.getNextTuple(); // ////////////////////////////////////System.out.println("tuple input to groupBy"+ tuple.columns); if(isDistinct == false){ // when group By op is not used for distinct return tuple; } if (groupByItems == null){ if(!functions.isEmpty()){ // when group by op is used for aggregation groupByItems = new ArrayList<Expression>(); }else{// if no group by items and no aggregation return tuple; } } if (tuple == null) break; ////////////////////////////////////System.out.println("groupByItems : " + groupByItems); LinkedHashMap<String, LeafValue> tupleMap = new LinkedHashMap<String, LeafValue>(); for (Expression groupByItem : groupByItems) { ////////////////////////////////////System.out.println("GroupByItem : "+groupByItem); //////////////////////////System.out.println(groupByItem); LeafValue groupByValue = super.eval(groupByItem); groupByTuple.addValue(groupByItem.toString(), Cloner.clone(groupByValue)); } if (groups.containsKey(groupByTuple)) { properties = groups.get(groupByTuple); properties.consume(tuple); } else { properties = new GroupProperties(functions); properties.consume(tuple); } groups.put(groupByTuple, properties); groupByTuple = new Tuple(); // //////////////////////////////////////////System.out.println("group"); // for(Entry tmp : groups.entrySet()){ // //////////////////////////////////////////System.out.println(tmp.getKey().toString()+tmp.getValue()); // } } while (tuple != null); keySet = groups.keySet(); ////////////////////////////////////System.out.println("groups"+groups); iterator = keySet.iterator(); } if (iterator.hasNext()){ Tuple currentTuple = iterator.next(); finalTuple = new Tuple((LinkedHashMap<String, LeafValue>) currentTuple.getTupleMap().clone()); ////////////////////////////////////System.out.println("FinalTuple" + finalTuple); //////////////////////////////////////////System.out.println(groups); for(Function function : functions){ LeafValue value = groups.get(currentTuple).roundUp(function); finalTuple.addValue(function.toString() ,value); } }else return null; } catch (SQLException e) { e.printStackTrace(); } return finalTuple; } @Override public void close() { inputOperator.close(); } @Override public LeafValue eval(Column col) throws SQLException { return tuple.get(col.getWholeColumnName()); } public LeafValue eval(Function func){ ////////////////////////////////////System.out.println(func.toString()); return tuple.get(func.toString()); } } <file_sep>package edu.buffalo.cse562; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.Function; import net.sf.jsqlparser.expression.LeafValue; import net.sf.jsqlparser.schema.Column; import net.sf.jsqlparser.schema.Table; import net.sf.jsqlparser.statement.select.AllColumns; import net.sf.jsqlparser.statement.select.SelectExpressionItem; import net.sf.jsqlparser.statement.select.SelectItem; public class ProjectionOperator extends Eval implements Operator{ Operator inputOperator; List<SelectItem> projectExpression; Tuple tuple; public ProjectionOperator(Operator inputOperator, List<SelectItem> projectExpression) { super(); this.inputOperator = inputOperator; this.projectExpression = projectExpression; } @Override public void open() { //////////////System.out.println("---------PROJECT-------\n"); inputOperator.open(); } @Override public Tuple getNextTuple() { ArrayList<LeafValue> tupleData = new ArrayList<LeafValue>(); ArrayList<Column> columns = new ArrayList<>(); Tuple outputTuple = null; try { do { tuple = inputOperator.getNextTuple(); ////////////////////////////////////System.out.println("Columns in Project Op : "+tuple.columns); if (tuple == null) break; outputTuple = new Tuple(); for (SelectItem projectItem : projectExpression) { // ////////////////////////////////////////////System.out.println(projectItem.getClass()); if (projectItem instanceof SelectExpressionItem) { ////////////////////////////////////////////////System.out.println(((SelectExpressionItem) projectItem).getExpression()); Expression expression = ((SelectExpressionItem) projectItem).getExpression(); LeafValue value = super.eval(expression); tupleData.add(value); // Column tmp = new Column(); if(((SelectExpressionItem) projectItem).getAlias() != null){ outputTuple.addValue(((SelectExpressionItem) projectItem).getAlias().toString(), value); }else{ outputTuple.addValue(((SelectExpressionItem) projectItem).toString(), value); } // tmp.setTable(new Table("", "")); // columns.add(tmp ); // TODO column aliasing //////////////////System.out.println(outputTuple.columns); }else if(projectItem instanceof AllColumns){ outputTuple = tuple; } } } while (tuple == null); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return outputTuple; } @Override public void close() { inputOperator.close(); } @Override public LeafValue eval(Column col) throws SQLException { return tuple.get(col.getWholeColumnName()); } public LeafValue eval(Function func){ ////////////////////////////////////System.out.println(func.toString()); return tuple.get(func.toString()); } }
f8d4247e9b97c01feecba0cd1ff23c09b6a8b856
[ "Java" ]
8
Java
cgb-jsqlparser/SQLqueryEvaluator
bb7320cadea7a77892f85d02e4c78e9c23f76e36
e4fbb87fdce9ba5b2ab8a3b3a1df2b239d4adf5f
refs/heads/master
<file_sep>//We're in a job interview. Answer the following questions (try to not look at your notes unless you have to). // 1) What is the purpose of the 'this keyword'? //Answer var answer1 ="'This' keyword is used as a shortcut to a reference of the the object's subject in context" // 2) What are the four rules that govern what the 'this keyword' is bound to and describe each? //Answer var answer2 = "The four rules that govern 'this' are; Implicit, explicit, new and default. call a method on a function left of the dot - Implicit explicit - three methods of functions where you use call() apply and bind new - when js uses a brand new object and passes a param into it;" // 3) What is the difference between call and apply? //Answer // 4) What does .bind do? //Answer //Next Problem //Create an object called user which has the following properties. //username --> which is a string //email --> which is a string //getUsername --> which is a function that returns the current object's username property. *Don't use 'user' instead use the 'this' keyword* //Code Here function User(username, email) { this.username = username; this.email = email; this.getUsername = function () { return this.username; }; } var user = new User("BryanKnows", "bryan.email.com"); //Now, invoke the getUsername method and verify you got the username of the object and not anything else. user.getUsername(); // "BryanKnows" //Next Problem // Write the function definitions which will make the following function invocations function properly. /* constructor is not what they wanted but works better. function Car(brand, model, year) { this.brand = brand; this.model = model; this.year = year; this.move = 0; this.moveCar = function(){ return this.move += 10;}; } */ //Function Invocations Here function Car(brand, model, year) { return { brand: brand, model: model, year: year, move: 0, moveCar: function() { return this.move += 10;} }; } var prius = Car('Toyota', 'Prius', 2011); var mustang = Car('Ford', 'Mustang', 2013); prius.moveCar(); //increments prius' move property by 10. Returns the new move property. mustang.moveCar(); //increments prius' move property by 10. Returns the new move property. //Hint, you'll need to write a moveCar function which is added to every object //that is being returned from the Car function. You'll also need to use the //'this' keyword properly in order to make sure you're invoking moveCar on the // write object (prius vs mustang). //Continuation of previous problem var getYear = function(){ return this.year; }; //Above you're given the getYear function. Using your prius and mustang objects // from above, use the proper syntax that will allow for you to call the getYear // function with the prius then the mustang objects being the focal objects. // *Don't add getYear as a property on both objects*. //Code Here var priusYear = getYear.bind(prius); var mustangYear = getYear.bind(mustang); priusYear(); mustangYear(); //New Problem var user = { username: 'iliketurtles', age: 13, email: '<EMAIL>' }; var getUsername = function(){ console.log(this.username); }; setTimeout(getUsername, 5000); //Above you're given an object, a function, and a setTimeout invocation. After // 5 seconds, what will the getUsername function return? //Answer Here var answer3 = "It will log the usernam of the window because it is not bound to a variable, rather it moves up to window.name" //In the example above, what is the 'this keyword' bound to when getUsername runs? //Answer Here var answer4 = "it is calling the 'this keyword' type of 'default'" //Fix the setTimeout invocation so that the user object will be the focal object when getUsername is ran. var user = { username: 'iliketurtles', age: 13, email: '<EMAIL>' }; var getUsername = function(){ console.log(this.username); }; //the answer is below setTimeout(getUsername.call(user), 5000);
3ac9a88b366fb78a0ae8c9d5d84332f3d41da088
[ "JavaScript" ]
1
JavaScript
Bryanschauerte/the-keyword-this
8ede3c4ae2c3b9055cc4a5af5521a20ca9e263ae
d6afe19fc2f4457fc7bccdb17a1487795c9fe2a8
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace MusicPlaylistAnalyzer { public static class MusicPlaylistReport { public static string GenerateText(List<MusicPlaylistInfo> musicPlaylistList) { string report = "Music Playlist Report\n\n"; if (musicPlaylistList.Count() < 1) { report += "No data is available.\n"; return report; } report += "Songs that recieved 200 or more plays: \n"; var records = from musicInfo in musicPlaylistList where musicInfo.Plays > 200 select musicInfo; if (records.Count() > 0) { foreach (var record in records) { report += "Name: " + record.Name + ", Artist: " + record.Artist + ", Album: " + record.Album + ", Genre: " + record.Genre + ", Size: " + record.Size + ", Time: " + record.Time + ", Year: " + record.Year + ", Plays: " + record.Plays + "\n"; } report.TrimEnd('\t'); report += "\n"; } else { report += "not available\n\n"; } report += "Number of Alternative songs: "; var altCount = from musicInfo in musicPlaylistList where musicInfo.Genre == "Alternative" select musicInfo.Name; if (altCount.Count() > 0) { report += altCount.Count() + "\n\n"; report.TrimEnd('\t'); report += "\n"; } else { report += "not available\n\n"; } report += "Number of Hip-Hop/Rap songs: "; var rapCount = from musicInfo in musicPlaylistList where musicInfo.Genre == "Hip-Hop/Rap" select musicInfo.Name; if (rapCount.Count() > 0) { report += rapCount.Count() + "\n\n"; report.TrimEnd('\t'); report += "\n"; } else { report += "not available\n\n"; } report += "Songs from the album Welcome to the Fishbowl: \n"; var fishbowl = from musicInfo in musicPlaylistList where musicInfo.Album == "Welcome to the Fishbowl" select musicInfo; if (fishbowl.Count() > 0) { foreach (var fishbowlInfo in fishbowl) { report += "Name: " + fishbowlInfo.Name + ", Artist: " + fishbowlInfo.Artist + ", Album: " + fishbowlInfo.Album + ", Genre: " + fishbowlInfo.Genre + ", Size: " + fishbowlInfo.Size + ", Time: " + fishbowlInfo.Time + ", Year: " + fishbowlInfo.Year + ", Plays: " + fishbowlInfo.Plays + "\n"; } report.TrimEnd('\t'); report += "\n"; } else { report += "not available\n\n"; } report += "Songs from before 1970: \n"; var oldies = from musicInfo in musicPlaylistList where musicInfo.Year < 1970 select musicInfo; if (oldies.Count() > 0) { foreach (var oldie in oldies) { report += "Name: " + oldie.Name + ", Artist: " + oldie.Artist + ", Album: " + oldie.Album + ", Genre: " + oldie.Genre + ", Size: " + oldie.Size + ", Time: " + oldie.Time + ", Year: " + oldie.Year + ", Plays: " + oldie.Plays + "\n"; } report.TrimEnd('\t'); report += "\n"; } else { report += "not available\n\n"; } report += "Song names longer than 85 characters: \n"; var titles = from musicInfo in musicPlaylistList where musicInfo.Name.Length > 85 select musicInfo; if (titles.Count() > 0) { foreach (var title in titles) { report += title.Name + "\n"; } report.TrimEnd('\t'); report += "\n"; } else { report += "not available\n\n"; } report += "Longest song: \n"; var mostTime = from musicInfo in musicPlaylistList where musicInfo.Time == ((from info in musicPlaylistList select info.Time).Max()) select musicInfo.Name; if (mostTime.Count() > 0) { report += "Name: " + mostTime.First(); } else { report += "not available\n"; } var mostTimeArtist = from musicInfo in musicPlaylistList where musicInfo.Time == ((from info in musicPlaylistList select info.Time).Max()) select musicInfo.Artist; report += ", Artist: " + mostTimeArtist.First(); var mostTimeAlbum = from musicInfo in musicPlaylistList where musicInfo.Time == ((from info in musicPlaylistList select info.Time).Max()) select musicInfo.Album; report += ", Album: " + mostTimeAlbum.First(); var mostTimeGenre = from musicInfo in musicPlaylistList where musicInfo.Time == ((from info in musicPlaylistList select info.Time).Max()) select musicInfo.Genre; report += ", Genre: " + mostTimeGenre.First(); var mostTimeSize = from musicInfo in musicPlaylistList where musicInfo.Time == ((from info in musicPlaylistList select info.Time).Max()) select musicInfo.Size; report += ", Size: " + mostTimeSize.First(); var mostTimeTime = from musicInfo in musicPlaylistList where musicInfo.Time == ((from info in musicPlaylistList select info.Time).Max()) select musicInfo.Time; report += ", Time: " + mostTimeTime.First(); var mostTimeYear = from musicInfo in musicPlaylistList where musicInfo.Time == ((from info in musicPlaylistList select info.Time).Max()) select musicInfo.Year; report += ", Year: " + mostTimeYear.First(); var mostTimePlays = from musicInfo in musicPlaylistList where musicInfo.Time == ((from info in musicPlaylistList select info.Time).Max()) select musicInfo.Plays; report += ", Plays: " + mostTimePlays.First(); return report; } } }
3a7417222c6556951c371076d7ea63de769a92f1
[ "C#" ]
1
C#
brennna/McGrail-Music-Playlist-Analyzer
cde9aa2e1533554f2cf27e28cc8d5d9c065e83ed
7560a63cd3aade82a0a2b20c9b07ec11134fd8b5
refs/heads/master
<repo_name>Hankered/CustomGrowGithub<file_sep>/us/pawgames/CustomGrow/Plant/PlantMain.java package us.pawgames.CustomGrow.Plant; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; public class PlantMain implements Listener { // private final FileConfiguration config = Grow.plugin.getConfig(); public ItemStack tob() { ItemStack is = new ItemStack(Material.BREAD); ItemMeta im = is.getItemMeta(); im.setDisplayName(ChatColor.BLUE + "Bread or something idk"); is.setItemMeta(im); return is; } @EventHandler public void onPlaceEvent(PlayerInteractEvent e) { Block b = e.getClickedBlock(); Player p = e.getPlayer(); if (e.getClickedBlock() == null || e.getAction() == Action.LEFT_CLICK_AIR // || e.getAction() == Action.LEFT_CLICK_BLOCK || e.getAction() == Action.RIGHT_CLICK_AIR || p.getItemInHand() == null) return; } }
230043c7c119507ef6e063c2105c581431f863ee
[ "Java" ]
1
Java
Hankered/CustomGrowGithub
e3fdcb8e9523d4750b2b70f3bbaf000c4bb67927
5080665018ed026a0eeea67ec33d13205c0629db
refs/heads/master
<repo_name>eMKeii/Node0toE<file_sep>/02-fundamentos/let-var.js // var nombre = 'Wolverine'; // if (true) { // nombre = 'Magneto' // } // let nombre = '<NAME>' // let nombre = 'Wolverine 2' // let nombre = 'Wolverine 3' // let nombre = 'Wolverine 4' // let nombre = 'Wolverine 5' // console.log(nombre) let i; for ( let i = 0; i <= 5; i++){ console.log(`i ${i}`); } console.log(i);<file_sep>/02-fundamentos/callback.js // setTimeout( () => { // console.log('Hola mundo'); // }, 3000); let getUsuarioById = (id, callback) => { let usuario = { nombre: 'Marcos', // Cuando la propiedad es igual al valor entonces se puede obiviar el valor = id } if( id === 20){ callback(`El usuario con el id ${ id }, no existe en la base de datos`); }else{ callback(usuario); } } getUsuarioById(20, (err, usuario) => { if( err ){ return console.log(err); } console.log('Usuario de base de datos', usuario) });
597e67464ab91055278d2eff58f8b3ee691aab59
[ "JavaScript" ]
2
JavaScript
eMKeii/Node0toE
af6b7138958678113d449000a66e9ab682b38a59
9bfe99b30f23fbb93973e0332bc758268060b6e0
refs/heads/master
<repo_name>AdrianoAS/ponto-inteligente.api<file_sep>/src/main/resources/db/migration/mysql/v1__init.sql -- phpMyAdmin SQL Dump -- version 4.8.0.1 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: 21-Set-2018 às 22:19 CREATE TABLE `empresa` ( `id` bigint(20) NOT NULL, `cnpj` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `data_atualizacao` datetime NOT NULL, `data_criacao` datetime NOT NULL, `razao_social` varchar(255) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -------------------------------------------------------- -- -- Estrutura da tabela `funcionario` -- CREATE TABLE `funcionario` ( `id` bigint(20) NOT NULL, `cpf` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `data_atualizacao` datetime DEFAULT NULL, `data_criacao` datetime DEFAULT NULL, `email` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `nome` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `perfil` int(11) DEFAULT NULL, `qtde_hora_almoco` float DEFAULT NULL, `qtde_hora_trabalhada` float DEFAULT NULL, `senha` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `valor_hora` double DEFAULT NULL, `empresa_id` bigint(20) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -------------------------------------------------------- -- -- Estrutura da tabela `lancamento` -- CREATE TABLE `lancamento` ( `id` bigint(20) NOT NULL, `data` datetime DEFAULT NULL, `data_atualizacap` datetime DEFAULT NULL, `data_criacao` datetime DEFAULT NULL, `descricao` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `localizacao` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `tipo` int(11) DEFAULT NULL, `funcionario_id` bigint(20) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Indexes for dumped tables -- -- -- Indexes for table `empresa` -- ALTER TABLE `empresa` ADD PRIMARY KEY (`id`); -- -- Indexes for table `funcionario` -- ALTER TABLE `funcionario` ADD PRIMARY KEY (`id`), ADD KEY `FK4cm1kg523jlopyexjbmi6y54j` (`empresa_id`); -- -- Indexes for table `lancamento` -- ALTER TABLE `lancamento` ADD PRIMARY KEY (`id`), ADD KEY `FK46i4k5vl8wah7feutye9kbpi4` (`funcionario_id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `empresa` -- ALTER TABLE `empresa` MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `funcionario` -- ALTER TABLE `funcionario` MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `lancamento` -- ALTER TABLE `lancamento` MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT; COMMIT; <file_sep>/src/main/java/com/adrianoSantos/pontoInteligente/api/services/LancamentoService.java package com.adrianoSantos.pontoInteligente.api.services; import java.util.Optional; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import com.adrianoSantos.pontoInteligente.api.entities.Lancamento; public interface LancamentoService { Page<Lancamento> buscarPorFuncionarioId(Long id, PageRequest page); Lancamento persistir(Lancamento lancamento); void remover(Long id); } <file_sep>/src/test/java/com/adrianoSantos/pontoInteligente/api/test/FuncinarioRepositoryTest.java package com.adrianoSantos.pontoInteligente.api.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import com.adrianoSantos.pontoInteligente.api.entities.Empresa; import com.adrianoSantos.pontoInteligente.api.entities.Funcionario; import com.adrianoSantos.pontoInteligente.api.enums.PerfilEnum; import com.adrianoSantos.pontoInteligente.api.repository.EmpresaRepository; import com.adrianoSantos.pontoInteligente.api.repository.FuncionarioRepository; import com.adrianoSantos.pontoInteligente.api.utils.PasswordUtils; @RunWith(SpringRunner.class) @SpringBootTest @ActiveProfiles("test") public class FuncinarioRepositoryTest { @Autowired private FuncionarioRepository funcionarioRepository; @Autowired private EmpresaRepository empresaRepository; private static final String EMAIL = "<EMAIL>"; private static final String CPF = "24291173474"; SimpleDateFormat fd = new SimpleDateFormat("dd/MM/yyyy HH:mm"); @Before public void setUp() throws Exception{ Empresa empresa = new Empresa(); empresa.setCnpj("51463645000100"); empresa.setDataAtualizacao(new Date(System.currentTimeMillis())); empresa.setDataCriacao(fd.parse("21/09/2018 19:01")); empresa.setRazaoSocial("Empresa de exemplo"); Funcionario fun = new Funcionario(); fun.setNome("<NAME>"); fun.setCpf(CPF); fun.setDataAtualizacao(new Date(System.currentTimeMillis())); fun.setDataCriacao(fd.parse("20/09/2018 20:00")); fun.setEmail(EMAIL); fun.setEmpresa(empresa); fun.setPerfil(PerfilEnum.ROLE_USUARIO); fun.setSenha(PasswordUtils.gerarBcrypt("<PASSWORD>")); fun.setQuatidadeHorasTrabalhada(240.0F); fun.setQuantidadeHorasAlmoco(1.00F); List<Funcionario> func = new ArrayList<>(); func.add(fun); empresa.setFuncionarios(func); empresaRepository.save(empresa); funcionarioRepository.saveAll(func); } @After public final void tearDown() { funcionarioRepository.deleteAll(); } @Test public void testBuscarFuncionarioPorEmailOrCpf() { Funcionario fun = funcionarioRepository.findByCpfOrEmail("24291173474", EMAIL); assertNotNull(fun); } @Test public void testBuscarFuncionarioPorEmail() { Funcionario fun = funcionarioRepository.findByEmail(EMAIL); assertEquals(EMAIL,fun.getEmail()); } @Test public void testBuscarFuncionarioPorCpf() { Funcionario fun = funcionarioRepository.findByCpf("24291173474"); assertEquals(CPF, fun.getCpf()); } } <file_sep>/src/main/java/com/adrianoSantos/pontoInteligente/api/services/impl/FuncionarioServiceImpl.java package com.adrianoSantos.pontoInteligente.api.services.impl; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.adrianoSantos.pontoInteligente.api.entities.Funcionario; import com.adrianoSantos.pontoInteligente.api.repository.FuncionarioRepository; import com.adrianoSantos.pontoInteligente.api.services.FuncionarioService; @Service public class FuncionarioServiceImpl implements FuncionarioService { private static final Logger log =LoggerFactory.getLogger(FuncionarioServiceImpl.class); @Autowired private FuncionarioRepository funcionarioRepository; @Override public Optional<Funcionario> busucarPorCpf(String cpf) { log.info("Buscando Funcionario por cpf", cpf); return Optional.ofNullable(funcionarioRepository.findByCpf(cpf)); } @Override public Optional<Funcionario> buscarPorEmail(String email) { log.info("Buscando Funcionario por email", email); return Optional.ofNullable(funcionarioRepository.findByEmail(email)); } public Optional<Optional<Funcionario>> buscarPorid(Long id) { log.info("Buscando Funcionario por id", id); return Optional.ofNullable(funcionarioRepository.findById(id)); } @Override public Optional<Funcionario> persistir(Funcionario funcionario) { log.info("Buscando Funcionario por funcionario", funcionario); return Optional.ofNullable(funcionarioRepository.save(funcionario)); } } <file_sep>/src/test/java/com/adrianoSantos/pontoInteligente/api/test/LancamentoRepositoryTest.java package com.adrianoSantos.pontoInteligente.api.test; import static org.junit.Assert.assertEquals; import java.security.NoSuchAlgorithmException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import com.adrianoSantos.pontoInteligente.api.entities.Empresa; import com.adrianoSantos.pontoInteligente.api.entities.Funcionario; import com.adrianoSantos.pontoInteligente.api.entities.Lancamento; import com.adrianoSantos.pontoInteligente.api.enums.PerfilEnum; import com.adrianoSantos.pontoInteligente.api.enums.TipoEnum; import com.adrianoSantos.pontoInteligente.api.repository.EmpresaRepository; import com.adrianoSantos.pontoInteligente.api.repository.FuncionarioRepository; import com.adrianoSantos.pontoInteligente.api.repository.LancamentoRepository; import com.adrianoSantos.pontoInteligente.api.utils.PasswordUtils; @RunWith(SpringRunner.class) @SpringBootTest @ActiveProfiles("test") public class LancamentoRepositoryTest { @Autowired private LancamentoRepository lancamentoRepository; @Autowired private FuncionarioRepository funcionarioRepository; @Autowired private EmpresaRepository empresaRepository; private static final String EMAIL = "<EMAIL>"; private static final String CPF = "24291173474"; SimpleDateFormat fd = new SimpleDateFormat("dd/MM/yyyy HH:mm"); private Long funcionarioid; @Before public void setUp() throws Exception { Empresa empresa = empresaRepository.save(obterDadosEmpresa()); Funcionario funcionario = funcionarioRepository.save(obterDadosFuncionatio(empresa)); funcionarioid = funcionario.getId(); lancamentoRepository.save(oberDadosLancamentos(funcionario)); lancamentoRepository.save(oberDadosLancamentos(funcionario)); } @After public final void tearDown() { empresaRepository.deleteAll(); } @Test public void testBuscarLancamentoPorFuncionario() { List<Lancamento> lancamentos = lancamentoRepository.findByfuncionarioId(funcionarioid); assertEquals(2, lancamentos.size()); } @Test public void testBuscarLancamentoPorFuncionarioIdPaginado() { PageRequest page = new PageRequest(0, 10); Page<Lancamento> lancamentos = lancamentoRepository.findByFuncionarioId(funcionarioid, page); assertEquals(2, lancamentos.getTotalElements()); } @SuppressWarnings("unused") private Lancamento oberDadosLancamentos(Funcionario funcionario) { Lancamento lancamento = new Lancamento(); lancamento.setData(new Date(System.currentTimeMillis())); lancamento.setTipo(TipoEnum.INICIO_ALMOCO); lancamento.setFuncionario(funcionario); return lancamento; } @SuppressWarnings("unused") private Funcionario obterDadosFuncionatio(Empresa empresa) throws NoSuchAlgorithmException { Funcionario funcionario = new Funcionario(); funcionario.setCpf("45633314816"); funcionario.setEmail("<EMAIL>"); funcionario.setNome("Adriano"); funcionario.setPerfil(PerfilEnum.ROLE_USUARIO); funcionario.setSenha(PasswordUtils.gerarBcrypt("<PASSWORD>")); funcionario.setEmpresa(empresa); return funcionario; } @SuppressWarnings("unused") private Empresa obterDadosEmpresa() { Empresa empresa = new Empresa(); empresa.setCnpj("51463645000100"); empresa.setDataAtualizacao(new Date(System.currentTimeMillis())); empresa.setRazaoSocial("Empresa de exemplo"); return empresa; } }
cb69229702d9c6268406d693aaeddb70aa8610f3
[ "Java", "SQL" ]
5
SQL
AdrianoAS/ponto-inteligente.api
4339640320ea16cb13404bc2234de906a90fb640
cd0a17865991203e0406b568f036dbbaaa6b4393
refs/heads/master
<file_sep>package org.tibetjungle.web.protocol; import org.tibetjungle.web.BaseTest; public class ProtocolVersionCompatibilityTest extends BaseTest { } <file_sep>package org.tibetjungle.web; public class WebServiceImpl implements WebService { @Override public Object echo( Object request ){ return request; } } <file_sep>package org.tibetjungle.web; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; public class HessianWebServiceImplTest extends BaseTest{ @BeforeClass public static void init() { URL = "http://localhost:8080/web/service"; BaseTest.init(); } @Test public void testEchoString() { String result = (String) client.echo(ECHO_STRING); Assert.assertEquals(ECHO_STRING, result); } @Test public void testEchoObject() { WebService response = (WebService) client.echo(client); Assert.assertNotNull(response); } @Test public void testEchoWorkableObject() { WebService newClient = (WebService) client.echo(client); String result = (String) newClient.echo(ECHO_STRING); Assert.assertEquals(ECHO_STRING, result); } }<file_sep>package org.tibetjungle.web; import com.caucho.hessian.server.HessianServlet; public class HessianWebServiceImpl extends HessianServlet implements WebService { private static final long serialVersionUID = 992218851611632955L; @Override public Object echo( Object request ){ return request; } }
603fa83fc9c3ccc93dcb58b3f047bdd16c461ecc
[ "Java" ]
4
Java
tibetjungle/java-web
004682128697e080557a43f85876d04f66b645e1
1f9b725d03ae0b1a19d18d08e765dbc7cd2e65df
refs/heads/master
<file_sep>DROP DATABASE IF EXISTS employee_trackerDB CREATE DATABASE employee_trackerDB USE employee_trackerDB CREATE TABLE department( id INTEGER NOT NULL, name VARCHAR(30) NOT NULL, PRIMARY KEY(id) ); CREATE TABLE role( id INTEGER AUTO_INCREMENT NOT NULL, title VARCHAR(30) NOT NULL, salary DECIMAL, department_id INTEGER, PRIMARY KEY (id), FOREIGN KEY (department_id) REFERENCES department (id) ); CREATE TABLE employee( id INTEGER AUTO_INCREMENT NOT NULL, first_name VARCHAR(50) NOT NULL, last_name VARCHAR(50) NOT NULL, role_id INTEGER NOT NULL, manager_id INT NULL, PRIMARY KEY(id), FOREIGN KEY (role_id) REFERENCES role (id), FOREIGN KEY (manager_id) REFERENCES employee (id) ); <file_sep>INSERT into department VALUES ("Management"); INSERT into department VALUES ("Coaching"); INSERT into department VALUES ("Players"); INSERT into department VALUES ("Everyone Else"); INSERT into role (title, salary, department_id) VALUES ("General Manager", 250000, 1); INSERT into role (title, salary, department_id) VALUES ("Head coach", 200000, 2); INSERT into role (title, salary, department_id) VALUES ("Assistant coach", 100000, 3); INSERT into role (title, salary, department_id) VALUES ("Trainer", 100000, 3); INSERT into role (title, salary, department_id) VALUES ("Player" 350000, 4); INSERT into role (title, salary, department_id) VALUES ("Waterboy", 75000, 5); --MANAGEMENT INSERT into employee (first_name, last_name, role_id, manager_id) VALUES ("Lisa", "Carrol", 1, 1); INSERT into employee (first_name, last_name, role_id, manager_id) VALUES ("Matt", "Flannery", 2, null ); INSERT into employee (first_name, last_name, role_id, manager_id) VALUES ("Sarah", "Baran", 1, 1); --COACHING INSERT into employee (first_name, last_name, role_id, manager_id) VALUES ("Coach", "K", 5, null ); INSERT into employee (first_name, last_name, role_id, manager_id) VALUES ("Coach", "Jackson", 6, null); --PLAYERS INSERT into employee (first_name, last_name, role_id, manager_id) VALUES ("Serena", "Williams", 7, null); INSERT into employee (first_name, last_name, role_id, manager_id) VALUES ("Venus", "williams", 7, null); --EVERYONE ELSE INSERT into employee (first_name, last_name, role_id, manager_id) VALUES ("Adam", "Sandler", 4, null) <file_sep># HW12_Employee-Tracker MySql
b476a2672a1fac014216cfbf8ba5b67715e5fc39
[ "Markdown", "SQL" ]
3
SQL
lisaannecabrera/HW12_Employee-Tracker
e7cb225810b12d3d985fb92f6843708512f01c7d
e8c2f1f4df844dcf049111cac717fd3a6c61164f
refs/heads/master
<repo_name>gitamineHM/TRUSK<file_sep>/README.md # TRUSK - Install Redis server - Do node tool.js - Enjoy ## Context Dans le but de simplifier la relation avec les Truskers, Trusk souhaite faciliter leur onboarding à travers le chat bot qu'ils utilisent déjà à ce jour pour la saisie des courses. Le but de l'exercice est de permettre la saisie de leurs informations de profil à travers un outil en ligne de commande. Les informations à saisir sont: - Le nom du trusker - Le nom de la société - Le nombre d'employés - Pour chaque employé son nom - Le nombre de camion - Pour chaque camion le volume en m³ du camion - Le type de camion Chaque champs doit saisir une information valide, si l'information est invalide ou vide la question doit être posée à nouveau. À la fin de la saisie des informations, on les affiche et on prompt à nouveau "Les informations sont elles valides?" si non on recommence au début. On stocke les réponses dans redis. Si on coupe le tool au milieu de l'onboarding et qu'on le relance, les réponses précédentes sont affichées et le tool saute automatiquement à la prochaine question. A la fin le redis est vidé. Technos utilisées: - NodeJS - https://www.npmjs.com/package/inquirer - async/await - ES6 Promise https://www.npmjs.com/package/bluebird - https://www.npmjs.com/package/redis - Map, Filter, Reduce <file_sep>/tool.js 'use strict'; var bluebird = require("bluebird"); var async = require('async'); const inquirer = require('inquirer'); var redisclient = require('redis'); var redis = redisclient.createClient() var i = 0, j = 0; redis.on('connect', () => { console.log('\x1Bc'); main() }); redis.on('error', () => { console.log(error) }); function validateName(name) { return name !== ''; } function validateNumber(number) { var reg = /^([1-9]|[1-9][0-9]|[1-9][0-9][0-9])$/; //1-999 return reg.test(number) || "Doit être un nombre positif"; } var questions = [{ message: "Le nom du trusker", type: "input", name: "TruskerName", validate: validateName },{ message: "Le nom de la société", type: "input", name: "EntrepriseName", validate: validateName },{ message: "Le nombre d'employés", type: "input", name: "NumberOfEmployees", validate: validateNumber, next: true, },{ message: "Le nom de l'employé ", type: "input", name: "NameOfEmployee", validate: validateName },{ message: "Le nombre de camion", type: "input", name: "NumberOfTrucks", validate: validateNumber, next: true, },{ message: "Volume en m³ du camion ", type: "input", name: "TruckVolume", validate: validateNumber },{ message: "Type de camion", type: "list", name : 'TruckType', choices: ['A', 'B', 'C'] },{ message: "Les informations sont-elles valides ?", type: "list", name : 'Valid', choices: ['Oui', 'Non'], confirm: true }] //Main routine async function main() { bluebird.mapSeries(questions, async (qs) => { if(j >i) while (j >i) { qs = addNumberToNameAndNumber(qs) await ask(qs).then(async (a)=> { await save(Object.keys(a)[0], a[Object.keys(a)[0]]) }) i++; } else { if(i==j) i=0;j=0; return ask(qs).then(async (a) => { await save(Object.keys(a)[0], a[Object.keys(a)[0]]) if(qs.next) j = parseInt(a[Object.keys(a)[0]]); if (qs.confirm && a.Valid == 'Oui') //informations Valides { redis.flushdb() console.log('FIN') } else if (qs.confirm && a.Valid == 'Non') { console.log('\x1Bc'); redis.flushdb() main() } }) } }) } function addNumberToNameAndNumber(string, number) { if(isNaN(string.name.substr(string.name.length-1, string.name.length))) { string.name += i +1 ; string.message += i +1 ; } else { string.name = string.name.substr(0,string.name.length -1) string.name += i + 1 string.message = string.message.substr(0,string.message.length -1) string.message += i + 1 } return string } //Ask function function ask(qs) { return new Promise((resolve, reject) => { read(qs.name) .then((a) => { console.log(qs.message + ' : ' + a) resolve(a) }) .catch(() => { inquirer.prompt(qs) .then((a) => { if (qs.next) j = parseInt(a[Object.keys(a)[0]]); resolve(a) }) }) }) } //Save redis key function save(key,data) { return new Promise(function (resolve, reject) { redis.set(key,data,function(err,reply) { if (err) reject(err) resolve(reply); }); }); } //Read Redis key function read(key) { return new Promise(function (resolve, reject) { redis.exists(key, function(err, reply) { if (reply === 1) { redis.get(key,function(err,reply) { if (err) reject(err) resolve(reply); }); } else reject(); }); }); }
d20933e4fde2e367832a547a5700a7897f077799
[ "Markdown", "JavaScript" ]
2
Markdown
gitamineHM/TRUSK
0caf8e8737c4391fcb372f5c4252a603cf39f872
8217b7394f8e3a87b03d6680497ec727f3bc65bd
refs/heads/master
<file_sep>import { ModuleWithProviders } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { AddSobaComponent } from './addSoba/addSoba.component'; import { AddHotelComponent } from './addHotel/addHotel.component'; import { LoginComponent } from './login/login.component'; import { RegisterComponent } from './register/register.component'; import { EditRoomComponent } from './editRoom/editRoom.component'; import { OpenRoomComponent } from './openRoom/openRoom.component'; const appRoutes: Routes = [ { path: '', component: AddHotelComponent}, { path: 'addHotel', component: AddHotelComponent}, { path: 'addSoba', component: AddSobaComponent}, { path: 'login', component: LoginComponent}, { path: 'register', component: RegisterComponent}, { path: 'editRoom/:id', component: EditRoomComponent}, { path: 'openRoom/:id', component: OpenRoomComponent } ]; export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes); <file_sep><?php header("Access-Control-Allow-Origin: *"); header('Access-Control-Allow-Methods: POST'); if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { die(); } include("config.php"); global $conn; if(isset($_POST['id']) && isset($_POST['ime']) && isset($_POST['velicina']) && isset($_POST['cena'])){ $id = $_POST['id']; $ime = $_POST['ime']; $velicina = $_POST['velicina']; $cena = $_POST['cena']; $rarray = array(); $stmt = $conn->prepare("UPDATE soba SET ime=?, velicina=?, cena=? WHERE id = ?"); $stmt->bind_param("sssi", $ime, $velicina, $cena, $id); if($stmt->execute()){ $rarray['success'] = "ok"; }else{ $rarray['error'] = "Connection error"; } return json_encode($rarray); } ?><file_sep><?php header("Access-Control-Allow-Origin: *"); header('Access-Control-Allow-Methods: GET, POST, OPTIONS'); header("Access-Control-Allow-Headers: X-XSRF-TOKEN"); include("config.php"); if ( isset($_POST['username']) && isset($_POST['password']) && isset($_POST['name']) && isset($_POST['last']) && isset($_POST['email']) ) { $username = $_POST['username']; $password = md5($_POST['password']); $name = $_POST['name']; $last = $_POST['last']; $email = $_POST['email']; $stmt = $conn->prepare("INSERT INTO korisnik (username, password,name,last,email) VALUES (?,?,?,?,?)"); $stmt->bind_param("sssss", $username,$password,$name,$last,$email); $stmt->execute(); echo "ok"; } ?><file_sep>import { Component, Directive } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; import { Http, Response, Headers } from '@angular/http'; import 'rxjs/Rx'; import {Router, ActivatedRoute, Params} from '@angular/router'; @Component({ moduleId: module.id, selector: 'EditRoomComponent', templateUrl: './editRoom.html', }) export class EditRoomComponent { http: Http; data: any; router: Router; route: ActivatedRoute; postResponse: String; id: number; editRoomComponent = new FormGroup({ ime: new FormControl(), velicina: new FormControl(), cena: new FormControl() }); constructor(http: Http, router: Router, route: ActivatedRoute) { this.http = http; this.router = router; this.route=route; } ngOnInit() { this.route.params.subscribe((params: Params) => { let id = params['id']; this.id=id; let headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); headers.append('token',localStorage.getItem('token')); console.log(headers); this.http.get('http://localhost/baza/getRoom.php?id='+id, {headers: headers}).map(res => res.json()).share() .subscribe(data => { this.data = data.data; this.editRoomComponent.controls['ime'].setValue(this.data.ime); this.editRoomComponent.controls['velicina'].setValue(this.data.velicina); this.editRoomComponent.controls['cena'].setValue(this.data.cena); }, err => { //this._router.navigate(['']); } ); }); } onEditRoom(): void { this.route.params.subscribe((params: Params) => { var data ="id=" + params['id'] + "&ime=" + this.editRoomComponent.value.ime + "&velicina=" + this.editRoomComponent.value.velicina + "&cena=" + this.editRoomComponent.value.cena; var headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); this.http.post('http://localhost/baza/editRoom.php', data, { headers: headers }) .subscribe( data => { console.log(data); if (data["_body"] == " ok") { this.router.navigate(['/']); } }); }); } } <file_sep><?php header("Access-Control-Allow-Origin: *"); header('Access-Control-Allow-Methods: GET, POST, OPTIONS'); header("Access-Control-Allow-Headers: X-XSRF-TOKEN"); include("config.php"); if(isset($_POST['ime']) && isset($_POST['velicina'])&& isset($_POST['cena'])) { $ime = $_POST['ime']; $velicina = $_POST['velicina']; $cena = $_POST['cena']; $stmt = $conn->prepare("INSERT INTO soba (ime, velicina, cena) VALUES (?, ?, ?)"); $stmt->bind_param("sss", $ime, $velicina, $cena); $stmt->execute(); echo "ok"; } ?><file_sep><?php header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: GET'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token , Authorization, Token, token, TOKEN'); include("config.php"); if(isset($_GET['id'])){ $id = $_GET['id']; global $conn; $rarray = array(); $room = array(); $result2 = $conn->query("SELECT * FROM soba WHERE id = ".$id.""); while($row = $result2->fetch_assoc()) { $room['id'] = $row['id']; $room['ime'] = $row['ime']; $room['velicina'] = $row['velicina']; $room['cena'] = $row['cena']; } $rarray['data'] = $room; echo json_encode($rarray); } ?><file_sep><?php include 'config.php'; function getHotel(){ global $conn; $sobaSql = "SELECT * FROM hotel"; if($stmt = $conn->prepare($sobaSql)) { $stmt->execute(); if(!$stmt->execute()) { echo $stmt->error; } else { $parameters = array(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { array_push($parameters,$row); } $stmt->close(); return $parameters; } $stmt->close(); } } $rez = getHotels(); echo json_encode($rez) ?><file_sep><?php header("Access-Control-Allow-Origin: *"); header('Access-Control-Allow-Methods: GET, POST, OPTIONS'); header("Access-Control-Allow-Headers: X-XSRF-TOKEN"); include("config.php"); if(isset($_POST['ime']) && isset($_POST['grad'])&& isset($_POST['drzava'])) { $ime = $_POST['ime']; $grad = $_POST['grad']; $drzava = $_POST['drzava']; $stmt = $conn->prepare("INSERT INTO hotel (ime, grad, drzava) VALUES (?, ?, ?)"); $stmt->bind_param("sss", $ime, $grad, $drzava); $stmt->execute(); echo "ok"; } ?><file_sep>import { Component } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/Rx'; import {Router} from '@angular/router'; @Component({ moduleId: module.id, selector: 'app-root', templateUrl: './template.html', }) export class AppComponent { private data: Object[]; private router: Router; constructor(private http: Http, router: Router) { this.router = router; let headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); headers.append('token', localStorage.getItem('token')); http.get('http://localhost/baza/prikaz.php') .map(res => res.json()).share() .subscribe(data => { console.log(data); this.data = data; }, err => { this.router.navigate(['./']); } ); } public editRoom(id: number) { this.router.navigateByUrl('/editRoom/' + id); } public openRoom(id: number) { this.router.navigateByUrl('/openRoom/' + id); } public deleteRoom(event: Event, id: Number) { let headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); headers.append('token', localStorage.getItem('token')); this.http.get('http://localhost/baza/deleteRoom.php?id='+id) .subscribe( data => { console.log(data); event.srcElement.parentElement.parentElement.remove(); }); } }<file_sep>import { Component, OnInit } from '@angular/core'; import { FormControl, FormGroup } from '@angular/forms'; import { Router, ActivatedRoute, Params } from '@angular/router'; import { Http, Response, Headers } from '@angular/http'; import 'rxjs/Rx'; @Component({ moduleId:module.id, selector: 'room-component', templateUrl: './openRoom.html' }) export class OpenRoomComponent implements OnInit { private _data: any; private http:any; private route:any; private router:any; roomData = new FormGroup({ openRoomComponent: new FormControl(), beds: new FormControl(), area: new FormControl() }); constructor(router: Router, route: ActivatedRoute, http: Http) { this.http = http; this.router = router; this.route = route; console.log(this.route); } ngOnInit() { this.route.params.subscribe((params: Params) => { let id = params['id']; let headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); headers.append('token',localStorage.getItem('token')); console.log(headers); this.http.get('http://localhost/baza/getRoom.php?id='+id, {headers: headers}).map(res => res.json()).share() .subscribe(data => { this._data = data.data; }, err => { //this._router.navigate(['']); } ); }); } }<file_sep><?php header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: GET'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token , Authorization, Token, token, TOKEN'); include("config.php"); if(isset($_GET['id'])){ global $conn; $rarray = array(); $hotel = array(); $result2 = $conn->query("SELECT * FROM hotel WHERE id = ".$id); while($row = $result2->fetch_assoc()) { $hotel['id'] = $row['id']; $hotel['ime'] = $row['ime']; $hotel['grad'] = $row['grad']; $hotel['drzava'] = $row['drzava']; $rarray['data'] = $room; return json_encode($rarray); } ?><file_sep><?php header("Access-Control-Allow-Origin: *"); header('Access-Control-Allow-Methods: GET, POST, OPTIONS'); header("Access-Control-Allow-Headers: X-XSRF-TOKEN"); include("config.php"); if(isset($_POST['username']) && isset($_POST['password'])) { $result = $conn->prepare("SELECT * FROM korisnik WHERE username=? AND password=?"); $result->bind_param("ss",($_POST['username']),md5($_POST['password'])); $result->execute(); $result->store_result(); $num_rows = $result->num_rows; if($num_rows > 0) { echo "ok"; } else{ echo "false"; } } ?><file_sep>import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { HttpModule } from '@angular/http'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { routing } from './app.routes'; import { AddHotelComponent } from './addHotel/addHotel.component'; import { AddSobaComponent } from './addSoba/addSoba.component'; import { LoginComponent } from './login/login.component'; import { RegisterComponent } from './register/register.component'; import { SearchPipe } from './pipe/search'; import { EditRoomComponent } from './editRoom/editRoom.component'; import { OpenRoomComponent } from './openRoom/openRoom.component'; @NgModule({ imports: [ BrowserModule, HttpModule, routing, FormsModule, ReactiveFormsModule ], declarations: [ AppComponent, AddHotelComponent, AddSobaComponent, LoginComponent,RegisterComponent, SearchPipe, OpenRoomComponent,EditRoomComponent], bootstrap: [ AppComponent ] }) export class AppModule { }
6966ac673c0edd8b0b4e2818f08caa1f7e9f96f3
[ "TypeScript", "PHP" ]
13
TypeScript
isidoradjokic2638/it255-dz11
e3caab7d295bc82e3bceafdc0b785922fd316b84
800e8c7bc6b5c4a12321e3a96d93b950a47e9e82
refs/heads/master
<repo_name>jingalls1/weather<file_sep>/src/data.js export const jsonData = { coord: { lon: -123.1, lat: 44.05 }, weather: [ { id: 500, main: "Rain", description: "light rain", icon: "10n" }, { id: 601, main: "Snow", description: "snow", icon: "13n" } ], base: "stations", main: { temp: 275.19, pressure: 1016, humidity: 93, temp_min: 273.71, temp_max: 276.48 }, visibility: 16093, wind: { speed: 1.62, deg: 210.502 }, rain: { "1h": 0.53 }, snow: { "1h": 0.51 }, clouds: { all: 90 }, dt: 1552114426, sys: { type: 1, id: 3727, message: 0.0067, country: "US", sunrise: 1552142105, sunset: 1552183877 }, id: 420029683, name: "Eugene", cod: 200 };
83418f418c43f560667f30700475ffe7c8fe81e8
[ "JavaScript" ]
1
JavaScript
jingalls1/weather
8c7a1c5d8ee440f2f932ce0ee1ee740ba2303353
a2ad10f0a57b070f07593ddda468a39455179357
refs/heads/master
<file_sep>$(function(){ // alert("test"); $('#LeftToRight').on('click', function(){ var content = $('#left').val(); disassemble(content); }); }); var disassemble = function(target){ var column_list = []; var length_list = []; var data_list = []; var temp = []; var split_n = target.split('\n'); column_list = split_n[0].split(/\s+/); var length_origin = split_n[1].split(/\s/); for(i in length_origin) length_list.push(length_origin[i].length); var index = 0; for(i in split_n){ if (i == 0 || i == 1) continue; if (split_n[i] == "") continue; if (split_n[i].match(/^\(/) != null) continue; for(j in length_list){ temp.push($.trim(split_n[i].substr(index, length_list[j]))); index = index + length_list[j] + 1; } data_list.push(temp); index = 0; temp = []; } for(i in data_list){ for(j in column_list){ var content = ""; content = column_list[j] + " : " + data_list[i][j] $("#contents").append(content + '<br/>'); } $("#contents").append('<br/>'); } var a = 1; }
9d8d4f177802e0346b7a1a6ba183bc2ee266ea84
[ "JavaScript" ]
1
JavaScript
suhyun-p/parsing_mssql
f996408f0c34d42b91ec7fa9b6e994fd58e9f12a
a9e8d3cbb49e00c5e955ebd98c562f2bfcc26cdf
refs/heads/master
<repo_name>0x55aa/fast-2d-poisson-disk-sampling<file_sep>/README.md # fast-2d-poisson-disk-sampling [![Build Status](https://travis-ci.org/kchapelier/fast-2d-poisson-disk-sampling.svg)](https://travis-ci.org/kchapelier/fast-2d-poisson-disk-sampling) [![NPM version](https://badge.fury.io/js/fast-2d-poisson-disk-sampling.svg)](http://badge.fury.io/js/fast-2d-poisson-disk-sampling) Fast 2D Poisson Disk Sampling based on a modified Bridson algorithm. ## Installing With [npm](https://www.npmjs.com/) do: ``` npm install fast-2d-poisson-disk-sampling ``` With [yarn](https://yarnpkg.com/) do: ``` yarn add fast-2d-poisson-disk-sampling ``` A compiled version for web browsers is also available on a CDN: ```html <script src="https://cdn.jsdelivr.net/gh/kchapelier/fast-2d-poisson-disk-sampling@1.0.1/build/fast-poisson-disk-sampling.min.js"></script> ``` ## Features - Can be used with a custom RNG function. - Allow the configuration of the max number of tries. - Same general API as [poisson-disk-sampling](https://github.com/kchapelier/poisson-disk-sampling). - Speed, see [benchmark results](https://github.com/kchapelier/fast-2d-poisson-disk-sampling/blob/master/BENCHMARK.md). ## Basic example ```js var p = new FastPoissonDiskSampling({ shape: [500, 200], radius: 6, tries: 20 }); var points = p.fill(); console.log(points); // array of sample points, themselves represented as simple arrays ``` ### Result as an image <img src="https://github.com/kchapelier/fast-2d-poisson-disk-sampling/raw/master/img/example1.png" style="image-rendering:pixelated; width:500px;"></img> ## Public API ### Constructor **new FastPoissonDiskSampling(options[, rng])** - *options :* - *shape :* Size/dimensions of the grid to generate points in, required. - *radius :* Minimum distance between each points, required. - *tries :* Maximum number of tries per point, defaults to 30. - *rng :* A function to use as random number generator, defaults to Math.random. Note: "minDistance" can be used instead of "radius", ensuring API compatibility with [poisson-disk-sampling](https://github.com/kchapelier/poisson-disk-sampling). ```js var pds = new FastPoissonDiskSampling({ shape: [50, 50], radius: 4, tries: 10 }); ``` ### Method **pds.fill()** Fill the grid with random points following the distance constraint. Returns the entirety of the points in the grid as an array of coordinate arrays. The points are sorted in their generation order. ```js var points = pds.fill(); console.log(points[0]); // prints something like [30, 16] ``` **pds.getAllPoints()** Get all the points present in the grid without trying to generate any new points. Returns the entirety of the points in the grid as an array of coordinate arrays. The points are sorted in their generation order. ```js var points = pds.getAllPoints(); console.log(points[0]); // prints something like [30, 16] ``` **pds.addRandomPoint()** Add a completely random point to the grid. There won't be any check on the distance constraint with the other points already present in the grid. Returns the point as a coordinate array. **pds.addPoint(point)** - *point :* Point represented as a coordinate array. Add an arbitrary point to the grid. There won't be any check on the distance constraint with the other points already present in the grid. Returns the point added to the grid. If the given coordinate array does not have a length of 2 or doesn't fit in the grid size, null will be returned. ```js pds.addPoint([20, 30]); ``` **pds.next()** Try to generate a new point in the grid following the distance constraint. Returns a coordinate array when a point is generated, null otherwise. ```js var point; while(point = pds.next()) { console.log(point); // [x, y] } ``` **pds.reset()** Reinitialize the grid as well as the internal state. When doing multiple samplings in the same grid, it is preferable to reuse the same instance of PoissonDiskSampling instead of creating a new one for each sampling. ## History ### [1.0.1](https://github.com/kchapelier/fast-2d-poisson-disk-sampling/tree/1.0.1) (2020-05-24) : - Tweaks to improve the result (higher point density). ### [1.0.0](https://github.com/kchapelier/fast-2d-poisson-disk-sampling/tree/1.0.0) (2020-05-24) : - First release ## Roadmap Write a proper description of the algorithm. ## How to contribute ? For new features and other enhancements, please make sure to contact me beforehand, either on [Twitter](https://twitter.com/kchplr) or through an issue on Github. ## License MIT<file_sep>/benchmark.js "use strict"; function toMs (time) { return (time[0] * 1000 + time[1] / 1000000); } var Poisson = require('./'), time, p, i, s; // warmup s = 0; for (i = 0; i < 10; i++) { p = new Poisson({ shape: [800, 400], radius: 10, tries: 10 }); s+= p.fill().length; } function benchmark (size, radius, tries, testIterations) { var time = process.hrtime(); var s = 0; for (var i = 0; i < testIterations; i++) { p = new Poisson({ shape: [size, size], radius: radius, tries: tries }); p.addPoint([size / 2, size / 2]); s+= p.fill().length; } time = process.hrtime(time); console.log('[' + size + 'x' + size + ' radius ' + radius + ' tries ' + tries + ']: ' + (toMs(time) / testIterations).toFixed(3) + 'ms for ~' + (s/testIterations|0)+' points'); } console.log(); console.log('Fast 2D Poisson Disc Sampling benchmark'); console.log(); benchmark(800, 8, 15, 10); benchmark(800, 8, 30, 10); benchmark(800, 8, 60, 10); console.log(); benchmark(800, 4, 15, 10); benchmark(800, 4, 30, 10); benchmark(800, 4, 60, 10); console.log(); benchmark(800, 2, 15, 10); benchmark(800, 2, 30, 10); benchmark(800, 2, 60, 10); console.log();<file_sep>/BENCHMARK.md # Benchmark In this benchmark, the performance of this javascript implementation is tested against the `poisson-disk-sampling` package. `poisson-disk-sampling` supports arbitrary dimensions but previous benchmarks demonstrated it is just as fast as the fastest 2d-only implementation available on NPM. `poisson-disk-sampling` samples its points at a distance of `r` (minDistance) to `2r` (maxDistance) of the active point (this behavior is overridable but changing it tends to reduce the quality/randomness of the result), while `fast-2d-poisson-disk-sampling` samples its points at a fixed distance of `r`. Two benchmarks will be made for `poisson-disk-sampling`, one with the same `r` as `fast-2d-poisson-disk-sampling` thus generating a much lower point density and one with an adjusted `r` to generate the same point density. ## Fast 2D Poisson Disc Sampling (1.0.0) benchmark ``` [800x800 radius 8 tries 15]: 12.981ms for ~8079 points [800x800 radius 8 tries 30]: 23.658ms for ~8407 points [800x800 radius 8 tries 60]: 35.481ms for ~8624 points [800x800 radius 4 tries 15]: 50.549ms for ~32158 points [800x800 radius 4 tries 30]: 85.435ms for ~33423 points [800x800 radius 4 tries 60]: 143.065ms for ~34302 points [800x800 radius 2 tries 15]: 206.735ms for ~128235 points [800x800 radius 2 tries 30]: 343.746ms for ~133204 points [800x800 radius 2 tries 60]: 590.924ms for ~136693 points ``` ## Poisson Disc Sampling (2.2.1) benchmark, r adjusted, ~same point density ``` [800x800 minDistance 6.96 maxDistance 13.93 tries 15]: 24.062ms for ~8052 points [800x800 minDistance 6.96 maxDistance 13.93 tries 30]: 39.890ms for ~8377 points [800x800 minDistance 6.96 maxDistance 13.93 tries 60]: 73.508ms for ~8715 points [800x800 minDistance 3.48 maxDistance 6.96 tries 15]: 87.390ms for ~32174 points [800x800 minDistance 3.48 maxDistance 6.96 tries 30]: 156.458ms for ~33423 points [800x800 minDistance 3.48 maxDistance 6.96 tries 60]: 292.271ms for ~34634 points [800x800 minDistance 1.74 maxDistance 3.48 tries 15]: 351.898ms for ~128359 points [800x800 minDistance 1.74 maxDistance 3.48 tries 30]: 626.503ms for ~133321 points [800x800 minDistance 1.74 maxDistance 3.48 tries 60]: 1162.315ms for ~138357 points ``` ## Poisson Disc Sampling (2.2.1) benchmark, same r, lower point density ``` [800x800 minDistance 8.00 maxDistance 16.00 tries 15]: 18.508ms for ~6110 points [800x800 minDistance 8.00 maxDistance 16.00 tries 30]: 30.538ms for ~6373 points [800x800 minDistance 8.00 maxDistance 16.00 tries 60]: 55.596ms for ~6608 points [800x800 minDistance 4.00 maxDistance 8.00 tries 15]: 66.215ms for ~24381 points [800x800 minDistance 4.00 maxDistance 8.00 tries 30]: 118.758ms for ~25335 points [800x800 minDistance 4.00 maxDistance 8.00 tries 60]: 221.161ms for ~26298 points [800x800 minDistance 2.00 maxDistance 4.00 tries 15]: 267.078ms for ~97268 points [800x800 minDistance 2.00 maxDistance 4.00 tries 30]: 473.950ms for ~101045 points [800x800 minDistance 2.00 maxDistance 4.00 tries 60]: 880.385ms for ~104867 points ```
d28b6eb8c73a323cfa67f0dddb158b6af98ecb28
[ "Markdown", "JavaScript" ]
3
Markdown
0x55aa/fast-2d-poisson-disk-sampling
9af7ae5c6c3a9abcb507bfbbe302e269bff0b7e8
4d477580a1333c7f1809246769daf916cfcb6097
refs/heads/main
<file_sep>// // calculatorKey.swift // SwiftUI-example // // Created by <NAME> on 2/8/21. // import Foundation enum PressedKey: String { case A1 = "A1" case A2 = "A2" case A3 = "A3" case A4 = "A4" case A5 = "A5" case A6 = "A6" case A7 = "A7" case A8 = "A8" case B1 = "B1" case B2 = "B2" case B3 = "B3" case B4 = "B4" case B5 = "B5" case B6 = "B6" case B7 = "B7" case B8 = "B8" case C1 = "C1" case C2 = "C2" case C3 = "C3" case C4 = "C4" case C5 = "C5" case C6 = "C6" case C7 = "C7" case C8 = "C8" case D1 = "D1" case D2 = "D2" case D3 = "D3" case D4 = "D4" case D5 = "D5" case D6 = "D6" case D7 = "D7" case D8 = "D8" } <file_sep>// // SeqencerApp.swift // Seqencer // // Created by <NAME> on 2/8/21. // import SwiftUI @main struct SeqencerApp: App { var body: some Scene { WindowGroup { ContentView().environmentObject(GlobalState()) } } } <file_sep># SwiftSamplerSequencer A simple audio sampler and sequencer **8 step sqeuencer where each cell is able to trigger an audio sample playback.** #### Todo + ~~Grid of buttons~~ + ~~Buttons change color in time~~ + ~~Button play sound when pressed~~ + ~~Get button to play sound when color is changed~~ + + ~~Create a switch in the globalstate file to represent each independent button~~ + + ~~Hold the playSound logic in those struct cases~~ + Get button to play a different sound per cell + ~~When button held, open sample menu~~ + Record and save new samples + + There might be an issue with calling two samples at the same time... <file_sep>// // GlobalState.swift // SwiftUI-example // // Created by <NAME> on 2/8/21. // import Foundation import AVFoundation import AVKit class GlobalState: ObservableObject { @Published var display = "8" @Published var timeRemaining = 1 @Published var timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect() var fileName: String = "hi" var fileExtension: String = "wav" var operation: PressedKey? = nil func stepCount(){ if timeRemaining < 8 { timeRemaining += 1 display = String(timeRemaining) }else{ timeRemaining = 1 display = String(timeRemaining) } } // func recordSample(){ // // // } func playSound(fileName: String, fileExtension: String) { let url = Bundle.main.url(forResource: fileName, withExtension: fileExtension) guard url != nil else{ return } do { player = try AVAudioPlayer(contentsOf: url!) player?.play() } catch { print("error") } return } func seqPlay(){ // auto trigger samples with corrisponding time if timeRemaining == 8{ // A8.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") // B8.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") // C8.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") // D8.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") }else if timeRemaining == 7{ // A7.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") // B7.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") // C7.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") // D7.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") }else if timeRemaining == 6{ // A6.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") // B6.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") // C6.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") // D6.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") }else if timeRemaining == 5{ // A5.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") // B5.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") // C5.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") // D5.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") }else if timeRemaining == 4{ // A4.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") // B4.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") // C4.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") // D4.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") }else if timeRemaining == 3{ // A3.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") // B3.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") // C3.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") // D3.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") }else if timeRemaining == 2{ // A2.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") // B2.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") // C2.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") // D2.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") }else if timeRemaining == 1{ // A1.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") // B1.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") // C1.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") // D1.wav or mp3 or whatever playSound(fileName: "hi", fileExtension: "wav") }else{ // do nothing } } // Each case should be able to contain a unique sample. func keyPressed(key: PressedKey) { switch key { case .A1: playSound(fileName: "hi", fileExtension: "wav") case .A2: playSound(fileName: "hi", fileExtension: "wav") case .A3: playSound(fileName: "hi", fileExtension: "wav") case .A4: playSound(fileName: "hi", fileExtension: "wav") case .A5: playSound(fileName: "hi", fileExtension: "wav") case .A6: playSound(fileName: "hi", fileExtension: "wav") case .A7: playSound(fileName: "hi", fileExtension: "wav") case .A8: playSound(fileName: "hi", fileExtension: "wav") case .B1: playSound(fileName: "hi", fileExtension: "wav") case .B2: playSound(fileName: "hi", fileExtension: "wav") case .B3: playSound(fileName: "hi", fileExtension: "wav") case .B4: playSound(fileName: "hi", fileExtension: "wav") case .B5: playSound(fileName: "hi", fileExtension: "wav") case .B6: playSound(fileName: "hi", fileExtension: "wav") case .B7: playSound(fileName: "hi", fileExtension: "wav") case .B8: playSound(fileName: "hi", fileExtension: "wav") case .C1: playSound(fileName: "hi", fileExtension: "wav") case .C2: playSound(fileName: "hi", fileExtension: "wav") case .C3: playSound(fileName: "hi", fileExtension: "wav") case .C4: playSound(fileName: "hi", fileExtension: "wav") case .C5: playSound(fileName: "hi", fileExtension: "wav") case .C6: playSound(fileName: "hi", fileExtension: "wav") case .C7: playSound(fileName: "hi", fileExtension: "wav") case .C8: playSound(fileName: "hi", fileExtension: "wav") case .D1: playSound(fileName: "hi", fileExtension: "wav") case .D2: playSound(fileName: "hi", fileExtension: "wav") case .D3: playSound(fileName: "hi", fileExtension: "wav") case .D4: playSound(fileName: "hi", fileExtension: "wav") case .D5: playSound(fileName: "hi", fileExtension: "wav") case .D6: playSound(fileName: "hi", fileExtension: "wav") case .D7: playSound(fileName: "hi", fileExtension: "wav") case .D8: playSound(fileName: "hi", fileExtension: "wav") } } } <file_sep>// // ContentView.swift // SwiftUI-example // // Created by <NAME> on 2/3/21. // import SwiftUI import AVFoundation var player: AVAudioPlayer! struct ContentView: View { @EnvironmentObject var env: GlobalState @State private var showPopUp = false @State var isLongPressing = false var body: some View { ZStack { Color.black .ignoresSafeArea() VStack(spacing: 2){ Text(env.display).onReceive(env.timer){ input in env.stepCount() env.seqPlay() }.foregroundColor(Color.white) HStack{ Button("Stop", action: { env.timer.upstream.connect().cancel() }) Button("Start", action: { env.timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect() }) Button("Retrigger", action: { env.timer.upstream.connect() }) Button("Record",action: { // RecordingAction() }) } HStack{ if env.timeRemaining == 8{ self.makeButton(key: .A8, bgColor: .red) self.makeButton(key: .B8, bgColor: .red) self.makeButton(key: .C8, bgColor: .red) self.makeButton(key: .D8, bgColor: .red) }else{ self.makeButton(key: .A8, bgColor: .green) self.makeButton(key: .B8,bgColor: .green) self.makeButton(key: .C8, bgColor: .green) self.makeButton(key: .D8, bgColor: .green) } } HStack{ if env.timeRemaining == 7{ self.makeButton(key: .A7, bgColor: .red) self.makeButton(key: .B7, bgColor: .red) self.makeButton(key: .C7, bgColor: .red) self.makeButton(key: .D7, bgColor: .red) }else{ self.makeButton(key: .A7, bgColor: .green) self.makeButton(key: .B7,bgColor: .green) self.makeButton(key: .C7, bgColor: .green) self.makeButton(key: .D7, bgColor: .green) } } HStack{ if env.timeRemaining == 6{ self.makeButton(key: .A6, bgColor: .red) self.makeButton(key: .B6, bgColor: .red) self.makeButton(key: .C6, bgColor: .red) self.makeButton(key: .D6, bgColor: .red) }else{ self.makeButton(key: .A6, bgColor: .green) self.makeButton(key: .B6,bgColor: .green) self.makeButton(key: .C6, bgColor: .green) self.makeButton(key: .D6, bgColor: .green) } } HStack{ if env.timeRemaining == 5{ self.makeButton(key: .A5, bgColor: .red) self.makeButton(key: .B5, bgColor: .red) self.makeButton(key: .C5, bgColor: .red) self.makeButton(key: .D5, bgColor: .red) }else{ self.makeButton(key: .A5, bgColor: .green) self.makeButton(key: .B5,bgColor: .green) self.makeButton(key: .C5, bgColor: .green) self.makeButton(key: .D5, bgColor: .green) } } HStack{ if env.timeRemaining == 4{ self.makeButton(key: .A4, bgColor: .red) self.makeButton(key: .B4, bgColor: .red) self.makeButton(key: .C4, bgColor: .red) self.makeButton(key: .D4, bgColor: .red) }else{ self.makeButton(key: .A4, bgColor: .green) self.makeButton(key: .B4,bgColor: .green) self.makeButton(key: .C4, bgColor: .green) self.makeButton(key: .D4, bgColor: .green) } } HStack{ if env.timeRemaining == 3{ self.makeButton(key: .A3, bgColor: .red) self.makeButton(key: .B3, bgColor: .red) self.makeButton(key: .C3, bgColor: .red) self.makeButton(key: .D3, bgColor: .red) }else{ self.makeButton(key: .A3, bgColor: .green) self.makeButton(key: .B3,bgColor: .green) self.makeButton(key: .C3, bgColor: .green) self.makeButton(key: .D3, bgColor: .green) } } HStack{ if env.timeRemaining == 2{ self.makeButton(key: .A2, bgColor: .red) self.makeButton(key: .B2, bgColor: .red) self.makeButton(key: .C2, bgColor: .red) self.makeButton(key: .D2, bgColor: .red) }else{ self.makeButton(key: .A2, bgColor: .green) self.makeButton(key: .B2,bgColor: .green) self.makeButton(key: .C2, bgColor: .green) self.makeButton(key: .D2, bgColor: .green) } } HStack{ if env.timeRemaining == 1{ self.makeButton(key: .A1, bgColor: .red) self.makeButton(key: .B1, bgColor: .red) self.makeButton(key: .C1, bgColor: .red) self.makeButton(key: .D1, bgColor: .red) }else{ self.makeButton(key: .A1, bgColor: .green) self.makeButton(key: .B1,bgColor: .green) self.makeButton(key: .C1, bgColor: .green) self.makeButton(key: .D1, bgColor: .green) } } // Spacer(minLength: 2) } if $showPopUp.wrappedValue { ZStack { Color.white VStack { Text("Sample Menu") Spacer() Button(action: { self.showPopUp = false }, label: { Text("Close") }) }.padding() } .frame(width: 300, height: 200, alignment: .center) .cornerRadius(20).shadow(radius: 20) } } } func makeButton(key: PressedKey = .A1, width: CGFloat = 60, height: CGFloat = 60, bgColor: Color = Color(white: 0.4)) -> some View { return AnyView( Button(action: { print("tap") if(self.isLongPressing){ self.isLongPressing.toggle() } else { //just a regular tap env.keyPressed(key: key) } }, label: { Text(key.rawValue) .frame(width: width, height: height, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/) .background(bgColor) .cornerRadius(35) .font(.system(size: 28)) .foregroundColor(.white) })).simultaneousGesture(LongPressGesture(minimumDuration: 0.2).onEnded { _ in print("long press") self.isLongPressing = true self.showPopUp = true }) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView().environmentObject(GlobalState()) } }
a6e08c11f311405139951ff8c140ede9d7e2ae58
[ "Swift", "Markdown" ]
5
Swift
fatpat314/SwiftSamplerSequencer
8fe7d797be9eebd711aaac7344514b491070c688
df55c39bb3c5c90a5d4630be9ae79910be1fa6db
refs/heads/master
<repo_name>jinx-USTC/Reid_UDA_Noisy_Label<file_sep>/reid/trainers.py from __future__ import print_function, absolute_import import time import torch from torch.autograd import Variable from .evaluation_metrics import accuracy from .loss import OIMLoss, TripletLoss from .utils.meters import AverageMeter class BaseTrainer(object): def __init__(self, model, criterions, print_freq=1): super(BaseTrainer, self).__init__() self.model = model self.criterions = criterions self.print_freq = print_freq def train(self, epoch, data_loader, optimizer): self.model.train() # for name, param in self.model.named_parameters(): # if 'classifier' in name: # param.requires_grad = False batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() precisions = AverageMeter() end = time.time() #inputs_all = [] #targets_all = [] for i, inputs in enumerate(data_loader): data_time.update(time.time() - end) inputs, targets = self._parse_data(inputs) loss, prec1 = self._forward(inputs, targets, epoch) # # for My accumulated loss: # if (i + 1) % 20 == 0: # inputs_all.append(*inputs) # '*' 代表序列解包 # targets_all.append(targets) losses.update(loss.data[0], targets.size(0)) precisions.update(prec1, targets.size(0)) optimizer.zero_grad() loss.backward() #add gradient clip for lstm for param in self.model.parameters(): try: param.grad.data.clamp(-1., 1.) except: continue optimizer.step() batch_time.update(time.time() - end) end = time.time() if (i + 1) % self.print_freq == 0: print('Epoch: [{}][{}/{}]\t' 'Time {:.3f} ({:.3f})\t' 'Data {:.3f} ({:.3f})\t' 'Loss {:.3f} ({:.3f})\t' 'Prec {:.2%} ({:.2%})\t' .format(epoch, i + 1, len(data_loader), batch_time.val, batch_time.avg, data_time.val, data_time.avg, losses.val, losses.avg, precisions.val, precisions.avg)) # # for My accumulated loss # inputs_all = torch.cat(inputs_all, 0) # targets_all = torch.cat(targets_all, 0) # _, _, features_all = self._forward([inputs_all], targets_all, epoch) # loss_accumulated = self.criterions[2](features_all, targets_all) # optimizer.zero_grad() # loss_accumulated.backward() # # add gradient clip for lstm # for param in self.model.parameters(): # try: # param.grad.data.clamp(-1., 1.) # except: # continue # optimizer.step() def _parse_data(self, inputs): raise NotImplementedError def _forward(self, inputs, targets, epoch): raise NotImplementedError class Trainer(BaseTrainer): def _parse_data(self, inputs): imgs, _, pids, _ = inputs inputs = [Variable(imgs)] targets = Variable(pids.cuda()) return inputs, targets def _forward(self, inputs, targets, epoch): outputs = self.model(*inputs) #outputs=[x1,x2,x3] #new added by wc # x1 triplet loss loss_tri, prec_tri = self.criterions[0](outputs[0], targets, epoch) # x2 triplet loss loss_global, prec_global = self.criterions[1](outputs[1], targets, epoch) #new added by xin: loss_accumulated = self.criterions[2](outputs[0], targets) return loss_tri+loss_global+loss_accumulated, prec_global class BaseTrainer_with_learnable_label(object): def __init__(self, model, classifier, criterions, print_freq=1): super(BaseTrainer_with_learnable_label, self).__init__() self.model = model self.criterions = criterions self.print_freq = print_freq self.classifier = classifier def train(self, epoch, data_loader, new_label, optimizer, optimizer_cla): self.model.train() batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() precisions = AverageMeter() import torch.nn as nn softmax = nn.Softmax(dim=1).cuda() end = time.time() for i, inputs in enumerate(data_loader): data_time.update(time.time() - end) inputs, targets, index = self._parse_data(inputs) index = index.numpy() new_label_update = new_label new_label_update = new_label_update[index,:] new_label_update = torch.FloatTensor(new_label_update) new_label_update = new_label_update.cuda(async = True) new_label_update = torch.autograd.Variable(new_label_update,requires_grad = True) # obtain label distributions (y_hat) last_updating_label_var = softmax(new_label_update) loss, prec1 = self._forward(inputs, targets, last_updating_label_var, epoch) losses.update(loss.data[0], targets.size(0)) precisions.update(prec1, targets.size(0)) optimizer.zero_grad() optimizer_cla.zero_grad() loss.backward() #add gradient clip for lstm for param in self.model.parameters(): try: param.grad.data.clamp(-1., 1.) except: continue optimizer.step() optimizer_cla.step() # update pseudo by back-propagation lambda1 = 600 new_label_update.data.sub_(lambda1*new_label_update.grad.data) new_label[index,:] = new_label_update.data.cpu().numpy() batch_time.update(time.time() - end) end = time.time() if (i + 1) % self.print_freq == 0: print('Epoch: [{}][{}/{}]\t' 'Time {:.3f} ({:.3f})\t' 'Data {:.3f} ({:.3f})\t' 'Loss {:.3f} ({:.3f})\t' 'Prec {:.2%} ({:.2%})\t' .format(epoch, i + 1, len(data_loader), batch_time.val, batch_time.avg, data_time.val, data_time.avg, losses.val, losses.avg, precisions.val, precisions.avg)) def _parse_data(self, inputs): raise NotImplementedError def _forward(self, inputs, targets, last_updating_label_var, epoch): raise NotImplementedError class Trainer_with_learnable_label(BaseTrainer_with_learnable_label): def _parse_data(self, inputs): imgs, _, pids, _, index = inputs inputs = [Variable(imgs)] targets = Variable(pids.cuda()) return inputs, targets, index def _forward(self, inputs, targets, last_updating_label_var, epoch): outputs = self.model(*inputs) #outputs=[x1,x2,x3] #new added by wc # x1 triplet loss loss_tri, prec_tri = self.criterions[0](outputs[0], targets, epoch) # x2 triplet loss loss_global, prec_global = self.criterions[1](outputs[1], targets, epoch) #new added by xin: loss_accumulated = self.criterions[2](outputs[0], targets) # Noisy label updating: import torch.nn as nn logsoftmax = nn.LogSoftmax(dim=1).cuda() softmax = nn.Softmax(dim=1).cuda() criterion = nn.CrossEntropyLoss().cuda() output = self.classifier(outputs[0]) loss_cla = torch.mean(softmax(output) * (logsoftmax(output) - torch.log((last_updating_label_var)))) # lo is compatibility loss loss_lo = criterion(last_updating_label_var, targets) # le is entropy loss loss_le = - torch.mean(torch.mul(softmax(output), logsoftmax(output))) return loss_tri + loss_global + loss_accumulated + (loss_cla + 0.4*loss_lo + 0.1*loss_le), prec_global <file_sep>/reid/utils/data/__init__.py from __future__ import absolute_import from .dataset import Dataset from .preprocessor import Preprocessor, Preprocessor_return_index <file_sep>/README.md # Unsupervised Domain Adaptive Re-Identification for reid, with clustering and noisy label techniques. Implementation of the paper [Unsupervised Domain Adaptive Re-Identification: Theory and Practice](https://arxiv.org/abs/1807.11334), and [Probabilistic End-to-end Noise Correction for Learning with Noisy Labels][http://openaccess.thecvf.com/content_CVPR_2019/papers/Yi_Probabilistic_End-To-End_Noise_Correction_for_Learning_With_Noisy_Labels_CVPR_2019_paper.pdf ] The selftraining scheme proposed in the paper is simple yet effective. ![Illustration of the selftraining scheme.](./data/algorithm_illustration.png) ## Acknowledgement Our code is based on [open-reid](https://github.com/Cysu/open-reid). [SSG][https://github.com/OasisYang/SSG], and [PENCIL][https://github.com/yikun2019/PENCIL/blob/master/PENCIL.py] <file_sep>/reid/loss/__init__.py from __future__ import absolute_import from .oim import oim, OIM, OIMLoss from .triplet import TripletLoss, AccumulatedLoss __all__ = [ 'oim', 'OIM', 'OIMLoss', 'TripletLoss', 'AccumulatedLoss', ] <file_sep>/reid/models/backup.py from __future__ import absolute_import from __future__ import division import torch from torch import nn from torch.nn import functional as F import torchvision import torch.utils.model_zoo as model_zoo __all__ = ['resnet50_SNR'] model_urls = { 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth', 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth', 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth', 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth', 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth', } def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) class ChannelGate_sub(nn.Module): """A mini-network that generates channel-wise gates conditioned on input tensor.""" def __init__(self, in_channels, num_gates=None, return_gates=False, gate_activation='sigmoid', reduction=16, layer_norm=False): super(ChannelGate_sub, self).__init__() if num_gates is None: num_gates = in_channels self.return_gates = return_gates self.global_avgpool = nn.AdaptiveAvgPool2d(1) self.fc1 = nn.Conv2d(in_channels, in_channels//reduction, kernel_size=1, bias=True, padding=0) self.norm1 = None if layer_norm: self.norm1 = nn.LayerNorm((in_channels//reduction, 1, 1)) self.relu = nn.ReLU(inplace=True) self.fc2 = nn.Conv2d(in_channels//reduction, num_gates, kernel_size=1, bias=True, padding=0) if gate_activation == 'sigmoid': self.gate_activation = nn.Sigmoid() elif gate_activation == 'relu': self.gate_activation = nn.ReLU(inplace=True) elif gate_activation == 'linear': self.gate_activation = None else: raise RuntimeError("Unknown gate activation: {}".format(gate_activation)) def forward(self, x): input = x x = self.global_avgpool(x) x = self.fc1(x) if self.norm1 is not None: x = self.norm1(x) x = self.relu(x) x = self.fc2(x) if self.gate_activation is not None: x = self.gate_activation(x) if self.return_gates: return x return input * x, input * (1 - x), x class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes) self.bn2 = nn.BatchNorm2d(planes) self.downsample = downsample self.stride = stride def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return out class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(planes * self.expansion) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return out class UpBlock(nn.Module): def __init__(self, inplanes, planes, upsample=False): super(UpBlock, self).__init__() self.conv = nn.Conv2d(inplanes, planes, 1, 1) self.bn = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.will_ups = upsample def forward(self, x): if self.will_ups: x = nn.functional.interpolate(x, scale_factor=2, mode="bilinear", align_corners=True) x = self.conv(x) x = self.bn(x) x = self.relu(x) return x # class GetParams(nn.Linear): # def __init__(self): # super(GetParams, self).__init__() # for p in self.parameters(): # p.requires_grad = False # # def forward(self, x): # print(self.weight) # print(self.bias) class Conv1x1nonLinear(nn.Module): """1x1 convolution + bn (w/o non-linearity).""" def __init__(self, in_channels, out_channels, stride=1): super(Conv1x1nonLinear, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, 1, stride=stride, padding=0, bias=False) self.bn = nn.BatchNorm2d(out_channels) self.relu = nn.ReLU(inplace=True) def forward(self, x): x = self.conv(x) x = self.relu(self.bn(x)) return x def weights_init_kaiming(m): classname = m.__class__.__name__ if classname.find('Linear') != -1: nn.init.kaiming_normal_(m.weight, a=0, mode='fan_out') nn.init.constant_(m.bias, 0.0) elif classname.find('Conv') != -1: nn.init.kaiming_normal_(m.weight, a=0, mode='fan_in') if m.bias is not None: nn.init.constant_(m.bias, 0.0) elif classname.find('BatchNorm') != -1: if m.affine: nn.init.constant_(m.weight, 1.0) nn.init.constant_(m.bias, 0.0) def weights_init_classifier(m): classname = m.__class__.__name__ if classname.find('Linear') != -1: nn.init.normal_(m.weight, std=0.001) if m.bias: nn.init.constant_(m.bias, 0.0) class ResNet_SNR(nn.Module): """ Residual network, SE, 1 - attention Reference: <NAME> al. Deep Residual Learning for Image Recognition. CVPR 2016. """ def __init__(self, block, layers, last_stride=2, fc_dims=None, dropout_p=None, **kwargs): self.inplanes = 64 super(ResNet_SNR, self).__init__() self.feature_dim = 512 * block.expansion global args # backbone network self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(64) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer(block, 64, layers[0]) self.layer2 = self._make_layer(block, 128, layers[1], stride=2) self.layer3 = self._make_layer(block, 256, layers[2], stride=2) self.layer4 = self._make_layer(block, 512, layers[3], stride=last_stride) self.global_avgpool = nn.AdaptiveAvgPool2d(1) # for inner triplet loss: self.global_avgpool_1 = nn.AdaptiveAvgPool2d(1) self.global_avgpool_2 = nn.AdaptiveAvgPool2d(1) self.global_avgpool_3 = nn.AdaptiveAvgPool2d(1) self.global_avgpool_4 = nn.AdaptiveAvgPool2d(1) # IN bridge: self.IN1 = nn.InstanceNorm2d(256, affine=True) self.IN2 = nn.InstanceNorm2d(512, affine=True) self.IN3 = nn.InstanceNorm2d(1024, affine=True) self.IN4 = nn.InstanceNorm2d(2048, affine=True) # 1*1 Conv for style decomposition: self.style_reid_laye1 = ChannelGate_sub(256, num_gates=256, return_gates=False, gate_activation='sigmoid', reduction=16, layer_norm=False) self.style_reid_laye2 = ChannelGate_sub(512, num_gates=512, return_gates=False, gate_activation='sigmoid', reduction=16, layer_norm=False) self.style_reid_laye3 = ChannelGate_sub(1024, num_gates=1024, return_gates=False, gate_activation='sigmoid', reduction=16, layer_norm=False) self.style_reid_laye4 = ChannelGate_sub(2048, num_gates=2048, return_gates=False, gate_activation='sigmoid', reduction=16, layer_norm=False) self._init_params() # BNN Neck: self.BN = nn.BatchNorm1d(512 * block.expansion) self.BN.bias.requires_grad_(False) # no shift #self.classifier = nn.Linear(self.feature_dim, num_classes, bias=False) self.BN.apply(weights_init_kaiming) #self.classifier.apply(weights_init_classifier) self.relu_final = nn.ReLU(inplace=True) def _make_layer(self, block, planes, blocks, stride=1): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(planes * block.expansion), ) layers = [] layers.append(block(self.inplanes, planes, stride, downsample)) self.inplanes = planes * block.expansion for i in range(1, blocks): layers.append(block(self.inplanes, planes)) return nn.Sequential(*layers) def _construct_fc_layer(self, fc_dims, input_dim, dropout_p=None): """ Construct fully connected layer - fc_dims (list or tuple): dimensions of fc layers, if None, no fc layers are constructed - input_dim (int): input dimension - dropout_p (float): dropout probability, if None, dropout is unused """ if fc_dims is None: self.feature_dim = input_dim return None assert isinstance(fc_dims, (list, tuple)), "fc_dims must be either list or tuple, but got {}".format( type(fc_dims)) layers = [] for dim in fc_dims: layers.append(nn.Linear(input_dim, dim)) layers.append(nn.BatchNorm1d(dim)) layers.append(nn.ReLU(inplace=True)) if dropout_p is not None: layers.append(nn.Dropout(p=dropout_p)) input_dim = dim self.feature_dim = fc_dims[-1] return nn.Sequential(*layers) def _init_params(self): for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') if m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) elif isinstance(m, nn.BatchNorm1d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) elif isinstance(m, nn.InstanceNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Linear): nn.init.normal_(m.weight, 0, 0.01) if m.bias is not None: nn.init.constant_(m.bias, 0) def featuremaps(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) x_1 = self.layer1(x) # torch.Size([64, 256, 64, 32]) x_1_ori = x_1 x_IN_1 = self.IN1(x_1) x_style_1 = x_1 - x_IN_1 x_style_1_reid_useful, x_style_1_reid_useless, selective_weight_useful_1 = self.style_reid_laye1(x_style_1) x_1 = x_IN_1 + x_style_1_reid_useful x_1_useless = x_IN_1 + x_style_1_reid_useless x_2 = self.layer2(x_1) # torch.Size([64, 512, 32, 16]) x_2_ori = x_2 x_IN_2 = self.IN2(x_2) x_style_2 = x_2 - x_IN_2 x_style_2_reid_useful, x_style_2_reid_useless, selective_weight_useful_2 = self.style_reid_laye2(x_style_2) x_2 = x_IN_2 + x_style_2_reid_useful x_2_useless = x_IN_2 + x_style_2_reid_useless x_3 = self.layer3(x_2) # torch.Size([64, 1024, 16, 8]) x_3_ori = x_3 x_IN_3 = self.IN3(x_3) x_style_3 = x_3 - x_IN_3 x_style_3_reid_useful, x_style_3_reid_useless, selective_weight_useful_3 = self.style_reid_laye3(x_style_3) x_3 = x_IN_3 + x_style_3_reid_useful x_3_useless = x_IN_3 + x_style_3_reid_useless x_4 = self.layer4(x_3) # torch.Size([64, 2048, 16, 8]) x_4_ori = x_4 x_IN_4 = self.IN4(x_4) x_style_4 = x_4 - x_IN_4 x_style_4_reid_useful, x_style_4_reid_useless, selective_weight_useful_4 = self.style_reid_laye4(x_style_4) x_4 = x_IN_4 + x_style_4_reid_useful x_4_useless = x_IN_4 + x_style_4_reid_useless return x_4, x_3, x_2, x_1, \ x_4_useless, x_3_useless, x_2_useless, x_1_useless, \ x_IN_4, x_IN_3, x_IN_2, x_IN_1, \ x_4_ori, x_3_ori, x_2_ori, x_1_ori, \ x_style_4_reid_useful, x_style_3_reid_useful, x_style_2_reid_useful, x_style_1_reid_useful, \ x_style_4_reid_useless, x_style_3_reid_useless, x_style_2_reid_useless, x_style_1_reid_useless, \ selective_weight_useful_4, selective_weight_useful_3, selective_weight_useful_2, selective_weight_useful_1 def forward(self, x): f_4, f_3, f_2, f_1, \ f_4_reid_useless, f_3_reid_useless, f_2_reid_useless, f_1_reid_useless, \ f_IN_4, f_IN_3, f_IN_2, f_IN_1, \ f_4_ori, f_3_ori, f_2_ori, f_1_ori, \ f_style_4_reid_useful, f_style_3_reid_useful, f_style_2_reid_useful, f_style_1_reid_useful, \ f_style_4_reid_useless, f_style_3_reid_useless, f_style_2_reid_useless, f_style_1_reid_useless, \ selective_weight_useful_4, selective_weight_useful_3, selective_weight_useful_2, selective_weight_useful_1 = self.featuremaps(x) v = self.global_avgpool(f_4) v = v.view(v.size(0), -1) v3 = self.global_avgpool(f_3) v3 = v3.view(v3.size(0), -1) v2 = self.global_avgpool(f_2) v2 = v2.view(v2.size(0), -1) v1 = self.global_avgpool(f_1) v1 = v1.view(v1.size(0), -1) v_bn = self.BN(v) v_relu = self.relu_final(v_bn) return v_bn, v_relu#torch.cat((v_bn, v3, v2, v1), 1), v def init_pretrained_weights(model, model_url): """ Initialize model with pretrained weights. Layers that don't match with pretrained layers in name or size are kept unchanged. """ pretrain_dict = model_zoo.load_url(model_url) model_dict = model.state_dict() pretrain_dict = {k: v for k, v in pretrain_dict.items() if k in model_dict and model_dict[k].size() == v.size()} model_dict.update(pretrain_dict) model.load_state_dict(model_dict) print("Initialized model with pretrained weights from {}".format(model_url)) """ Residual network configurations: -- resnet18: block=BasicBlock, layers=[2, 2, 2, 2] resnet34: block=BasicBlock, layers=[3, 4, 6, 3] resnet50: block=Bottleneck, layers=[3, 4, 6, 3] resnet101: block=Bottleneck, layers=[3, 4, 23, 3] resnet152: block=Bottleneck, layers=[3, 8, 36, 3] """ def resnet50_SNR(**kwargs): model = ResNet_SNR( block=Bottleneck, layers=[3, 4, 6, 3], last_stride=1, fc_dims=[512], dropout_p=None, **kwargs ) return model<file_sep>/selftraining_noisylabel.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: <NAME>, L.Song """ from __future__ import print_function, absolute_import import argparse import time import os.path as osp import os import numpy as np import torch from torch import nn from torch.nn import init from torch.backends import cudnn from torch.utils.data import DataLoader from reid import datasets from reid import models from reid.dist_metric import DistanceMetric from reid.loss import TripletLoss, AccumulatedLoss from reid.trainers import Trainer, Trainer_with_learnable_label from reid.evaluators import Evaluator, extract_features from reid.utils.data import transforms as T from reid.utils.data.preprocessor import Preprocessor, Preprocessor_return_index from reid.utils.data.sampler import RandomIdentitySampler from reid.utils.serialization import load_checkpoint, save_checkpoint from sklearn.cluster import DBSCAN #与K-means方法相比,DBSCAN不需要事先知道要形成的簇类的数量 from reid.rerank import re_ranking def get_data(name, data_dir, height, width, batch_size, workers): root = osp.join(data_dir, name) dataset = datasets.create(name, root, num_val=0.1) normalizer = T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) # use all training and validation images in target dataset train_set = dataset.trainval num_classes = dataset.num_trainval_ids transformer = T.Compose([ T.Resize((height,width)), T.ToTensor(), normalizer, ]) extfeat_loader = DataLoader( Preprocessor(train_set, root=dataset.images_dir, transform=transformer), batch_size=batch_size, num_workers=workers, shuffle=False, pin_memory=True) test_loader = DataLoader( Preprocessor(list(set(dataset.query) | set(dataset.gallery)), root=dataset.images_dir, transform=transformer), batch_size=batch_size, num_workers=workers, shuffle=False, pin_memory=True) return dataset, num_classes, extfeat_loader, test_loader def get_source_data(name, data_dir, height, width, batch_size, workers): root = osp.join(data_dir, name) dataset = datasets.create(name, root, num_val=0.1) normalizer = T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) # use all training images on source dataset train_set = dataset.train num_classes = dataset.num_train_ids transformer = T.Compose([ T.Resize((height,width)), T.ToTensor(), normalizer, ]) extfeat_loader = DataLoader( Preprocessor(train_set, root=dataset.images_dir, transform=transformer), batch_size=batch_size, num_workers=workers, shuffle=False, pin_memory=True) return dataset, extfeat_loader def weights_init_classifier(m): classname = m.__class__.__name__ if classname.find('Linear') != -1: nn.init.normal_(m.weight, std=0.001) if m.bias: nn.init.constant_(m.bias, 0.0) def main(args): np.random.seed(args.seed) torch.manual_seed(args.seed) cudnn.benchmark = True # Create data loaders assert args.num_instances > 1, "num_instances should be greater than 1" assert args.batch_size % args.num_instances == 0, \ 'num_instances should divide batch_size' if args.height is None or args.width is None: args.height, args.width = (144, 56) if args.arch == 'inception' else \ (256, 128) # get source data src_dataset, src_extfeat_loader = \ get_source_data(args.src_dataset, args.data_dir, args.height, args.width, args.batch_size, args.workers) # get target data tgt_dataset, num_classes, tgt_extfeat_loader, test_loader = \ get_data(args.tgt_dataset, args.data_dir, args.height, args.width, args.batch_size, args.workers) # Create model # Hacking here to let the classifier be the number of source ids if args.src_dataset == 'dukemtmc': model = models.create(args.arch, num_classes=632, pretrained=False) elif args.src_dataset == 'market1501': model = models.create(args.arch, num_classes=676, pretrained=False) else: raise RuntimeError('Please specify the number of classes (ids) of the network.') # Load from checkpoint if args.resume: print('Resuming checkpoints from finetuned model on another dataset...\n') checkpoint = load_checkpoint(args.resume) model.load_state_dict(checkpoint['state_dict'], strict=False) else: raise RuntimeWarning('Not using a pre-trained model.') model = nn.DataParallel(model).cuda() # Distance metric # metric = DistanceMetric(algorithm=args.dist_metric) # Evaluator evaluator = Evaluator(model, print_freq=args.print_freq) print("Test with the original model trained on source domain (direct transfer):") rank_score_best = evaluator.evaluate(test_loader, tgt_dataset.query, tgt_dataset.gallery) best_map = rank_score_best.map #market1501[0]-->rank-1 if args.evaluate: return # Criterion criterion = [ TripletLoss(args.margin, args.num_instances).cuda(), TripletLoss(args.margin, args.num_instances).cuda(), AccumulatedLoss(args.margin, args.num_instances).cuda(), nn.CrossEntropyLoss().cuda() ] # Optimizer optimizer = torch.optim.SGD( model.parameters(), lr=args.lr, momentum=0.9, ) # training stage transformer on input images normalizer = T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) train_transformer = T.Compose([ T.Resize((args.height,args.width)), T.RandomHorizontalFlip(), T.ToTensor(), normalizer, T.RandomErasing(probability=0.5, sh=0.2, r1=0.3) ]) # Start training for iter_n in range(args.iteration): if args.lambda_value == 0: source_features = 0 #this value controls the usage of source data else: # get source datas' feature source_features, _ = extract_features(model, src_extfeat_loader, print_freq=args.print_freq) # synchronization feature order with src_dataset.train source_features = torch.cat([source_features[f].unsqueeze(0) for f, _, _ in src_dataset.train], 0) # extract training images' features print('Iteration {}: Extracting Target Dataset Features...'.format(iter_n+1)) target_features, _ = extract_features(model, tgt_extfeat_loader, print_freq=args.print_freq) # synchronization feature order with dataset.train target_features = torch.cat([target_features[f].unsqueeze(0) for f, _, _ in tgt_dataset.trainval], 0) # calculate distance and rerank result print('Calculating feature distances...') target_features = target_features.numpy() rerank_dist = re_ranking(source_features, target_features, lambda_value=args.lambda_value) if iter_n==0: # DBSCAN cluster tri_mat = np.triu(rerank_dist, 1) # tri_mat.dim=2 tri_mat = tri_mat[np.nonzero(tri_mat)] # tri_mat.dim=1 tri_mat = np.sort(tri_mat,axis=None) top_num = np.round(args.rho*tri_mat.size).astype(int) eps = tri_mat[:top_num].mean() print('eps in cluster: {:.3f}'.format(eps)) cluster = DBSCAN(eps=eps,min_samples=4,metric='precomputed', n_jobs=8) # HDBSCAN cluster import hdbscan cluster_hdbscan = hdbscan.HDBSCAN(min_cluster_size=10, min_samples=4, metric='precomputed') # select & cluster images as training set of this epochs print('Clustering and labeling...') if args.use_hdbscan_clustering: print('Use the better chlustering algorithm HDBSCAN for clustering') labels = cluster_hdbscan.fit_predict(rerank_dist) else: print('Use DBSCAN for clustering') labels = cluster.fit_predict(rerank_dist) num_ids = len(set(labels)) - 1 print('Only do once, Iteration {} have {} training ids'.format(iter_n+1, num_ids)) # generate new dataset new_dataset = [] for (fname, _, _), label in zip(tgt_dataset.trainval, labels): if label==-1: continue # dont need to change codes in trainer.py _parsing_input function and sampler function after add 0 new_dataset.append((fname,label,0)) print('Only do once, Iteration {} have {} training images'.format(iter_n+1, len(new_dataset))) train_loader = DataLoader( Preprocessor_return_index(new_dataset, root=tgt_dataset.images_dir, transform=train_transformer), batch_size=args.batch_size, num_workers=4, sampler=RandomIdentitySampler(new_dataset, args.num_instances), pin_memory=True, drop_last=True) # init pseudo/fake labels, y_tilde in cvpr19's paper: new_label = np.zeros([len(new_dataset), num_ids]) # init y_tilde, let softmax(y_tilde) is noisy labels for index, (imgs, _, pids, _, index) in enumerate(train_loader): index = index.numpy() onehot = torch.zeros(pids.size(0), num_ids).scatter_(1, pids.view(-1, 1), 10.0) onehot = onehot.numpy() new_label[index, :] = onehot # Using clustered label to init the new classifier: classifier = nn.Linear(2048, num_ids, bias=False) classifier.apply(weights_init_classifier) classifier = nn.DataParallel(classifier).cuda() optimizer_cla = torch.optim.SGD(classifier.parameters(), lr=args.lr*10, momentum=0.9) # train model with new generated dataset trainer = Trainer_with_learnable_label(model, classifier, criterion, print_freq=args.print_freq) evaluator = Evaluator(model, print_freq=args.print_freq) # Start training for epoch in range(args.epochs): trainer.train(epoch, train_loader, new_label, optimizer, optimizer_cla) # Evaluate rank_score = evaluator.evaluate(test_loader, tgt_dataset.query, tgt_dataset.gallery) #Save the best ckpt: rank1 = rank_score.market1501[0] mAP = rank_score.map is_best_mAP = mAP > best_map best_map = max(mAP, best_map) save_checkpoint({ 'state_dict': model.module.state_dict(), 'epoch': iter_n + 1, 'best_mAP': best_map, # 'num_ids': num_ids, }, is_best_mAP, fpath=osp.join(args.logs_dir, 'checkpoint.pth.tar')) print('\n * Finished epoch {:3d} top1: {:5.1%} mAP: {:5.1%} best_mAP: {:5.1%}{}\n'. format(iter_n + 1, rank1, mAP, best_map, ' *' if is_best_mAP else '')) return (rank_score.map, rank_score.market1501[0]) if __name__ == '__main__': parser = argparse.ArgumentParser(description="Triplet loss classification") # data parser.add_argument('--src_dataset', type=str, default='dukemtmc', choices=datasets.names()) parser.add_argument('--tgt_dataset', type=str, default='market1501', choices=datasets.names()) parser.add_argument('--batch_size', type=int, default=128) parser.add_argument('--workers', type=int, default=4) parser.add_argument('--split', type=int, default=0) parser.add_argument('--height', type=int, help="input height, default: 256 for resnet*, " "144 for inception") parser.add_argument('--width', type=int, help="input width, default: 128 for resnet*, " "56 for inception") parser.add_argument('--combine-trainval', action='store_true', help="train and val sets together for training, " "val set alone for validation") parser.add_argument('--num_instances', type=int, default=4, help="each minibatch consist of " "(batch_size // num_instances) identities, and " "each identity has num_instances instances, " "default: 4") # model parser.add_argument('--arch', type=str, default='resnet50', choices=models.names()) # loss parser.add_argument('--margin', type=float, default=0.5, help="margin of the triplet loss, default: 0.5") parser.add_argument('--lambda_value', type=float, default=0.1, help="balancing parameter, default: 0.1") parser.add_argument('--rho', type=float, default=1.6e-3, help="rho percentage, default: 1.6e-3") # optimizer parser.add_argument('--lr', type=float, default=6e-5, help="learning rate of all parameters") # training configs parser.add_argument('--resume', type=str, metavar='PATH', default = '') parser.add_argument('--evaluate', type=int, default=0, help="evaluation only") parser.add_argument('--seed', type=int, default=1) parser.add_argument('--print_freq', type=int, default=1) parser.add_argument('--iteration', type=int, default=30) parser.add_argument('--epochs', type=int, default=70) # metric learning parser.add_argument('--dist_metric', type=str, default='euclidean', choices=['euclidean', 'kissme']) # misc parser.add_argument('--data_dir', type=str, metavar='PATH', default='') parser.add_argument('--logs_dir', type=str, metavar='PATH', default='') #Myself: parser.add_argument('--use-hdbscan-clustering', action='store_true', help="Use the better algorithm HDBSCAN for clustering") args = parser.parse_args() mean_ap, rank1 = main(args) results_file = np.asarray([mean_ap, rank1]) file_name = time.strftime("%H%M%S", time.localtime()) file_name = osp.join(args.logs_dir, file_name) np.save(file_name, results_file)
d87409a14365b86ee6c1ffa8ba76f36e1b5fadeb
[ "Markdown", "Python" ]
6
Python
jinx-USTC/Reid_UDA_Noisy_Label
e5b654cfaf2e7278948daf28cb5c534604dc9340
9108808e69a183678cb88c617912160f9f205f2c
refs/heads/master
<repo_name>NorthwesternDirector/react-learning<file_sep>/ 01 weboack-base/src/01 jsx的基本使用.js // 假设 main.js 还是入口函数 // console.log('good!!!') import React from 'react' import ReactDOM from 'react-dom' // const myh1 = React.createElement('h1',{id:'myh1'},'这是一个H1') // const mydiv = React.createElement('div',null,'这是一个div',myh1) //在js页面中混合写入类似HTML的语法,叫做JSX语法,符合XML规范的JS const mydiv=<div id="htmlDIV"> 这是一个HTMLdiv <h1>hahaha</h1> </div> ReactDOM.render(mydiv,document.querySelector('#app'))<file_sep>/01 react-base/src/components/CmtList2.jsx import React from 'react' import CmItem from '@/components/CmtItem2' import cssobj from '@/css/cmtList.scss' console.log(cssobj) import bootcss from 'bootstrap/dist/css/bootstrap.css' console.log(bootcss) export default class CmList extends React.Component{ constructor(){ super() this.state = { CommentList:[ {id:1, user:'dt', content:'1dt'}, {id:2, user:'fs', content:'2dt'}, {id:3, user:'mm', content:'3dt'}, {id:4, user:'ss', content:'4dt'}, ] } } render(){ return <div> <h1 className={ cssobj.title}>评论组件</h1> {/* <button className={ [bootcss.btn, bootcss['btn-primary']].join(' ') }>add</button> */} <button className="btn btn-primary">add</button> {this.state.CommentList.map(item => <CmItem {...item} key={item.id}></CmItem> )} </div> } }<file_sep>/01 react-base/src/index.js import React from 'react' import ReactDOM from 'react-dom' import CmList from './components/CmtList2' ReactDOM.render(<div> <CmList></CmList> </div>,document.getElementById("app"))<file_sep>/01 react-base/src/03 class关键字创建react组件.js // import React,{Component} from 'react' import React from 'react' import ReactDOM from 'react-dom' // import Hello from '@/components/Hello' // import '@/02 class继承公共方法' class Movie extends React.Component{ constructor(){ super() this.state= { msg: "Movie-constructor-state" } } render(){ return <div> <h1>哈哈😄</h1><h2>{this.props.name}</h2><h2>{this.state.msg}</h2></div> } } const user = { name: 'dt', age: 18, gender: 'man' } ReactDOM.render(<div> 123 {/* <Hello {...user}></Hello> */} <Movie {...user}></Movie> </div>,document.querySelector('#app'))<file_sep>/README.md ### 每天学习react,快乐多一点点<file_sep>/01 react-base/src/components/CmtItem2.jsx import React from 'react' import styles from '@/components/style' export default function CmItem(props) { return <div> <h1>评论人:{props.user}</h1> 评论内容:{props.content} </div> }<file_sep>/01 react-base/src/01 class继承.js class Person { constructor(name, age) { this.name = name this.age = age } } class American extends Person{ } const a1 = new American("Jack", 88) console.log(a1) class Chinese extends Person{ } const a2 = new Chinese("小米", 77) console.log(a2)<file_sep>/01 react-base/src/components/Hello.jsx import React from 'react' function Hello(props){ console.log(props) return <h1>haha+{props.name}</h1> } export default Hello<file_sep>/01 react-base/src/components/CmtItem.jsx import React from 'react' import styles from '@/components/style' export default function CmItem(props) { return <div style={styles.item}> <h3>评论人:{props.user}</h3> 评论内容:{props.content} </div> }<file_sep>/ 01 weboack-base/webpack.config.js const path = require('path') const HtmlWebPackPlugin = require('html-webpack-plugin') // 导入在内存中自动生成的index页面 // 创建一个插件实例 const htmlPlugin = new HtmlWebPackPlugin({ template: path.join(__dirname, './src/index.html'), filename : 'index.html' }) // 向外暴露一个打包的配置对象 module.exports = { mode : 'development', // 在webpack 4.x 中,默认的打包入口是 src/index.js plugins:[ htmlPlugin ], module: { rules: [ {test : /\.js|jsx$/, use:'babel-loader', exclude: /node_modules/}, ] }, resolve:{ extensions:['.js','.jsx','.json'] } }<file_sep>/01 react-router/components/moive.jsx import React from 'react' export default class Moive extends React.Component{ constructor(props){ super(props) this.state={ routeParams:props.match.params } } render(){ return <div> movie---{this.state.routeParams.type}----{this.state.routeParams.id} </div> } }<file_sep>/01 react-base/src/components/style.js export default { item:{ border:'1px dashed #ccc', margin:'10px', padding:'10px',boxShadow:'0 0 10px #ccc' }, }<file_sep>/ 01 weboack-base/src/04 clas的基本使用.js console.log("ok") class animal{ constructor(name, age){ this.name=name this.age=age } } const a1=new animal('大黄',15) console.log(a1)<file_sep>/01 react-router/src/App.jsx import React from 'react' import {HashRouter, Route, Link} from 'react-router-dom' import Home from '../components/home' import About from '../components/about' import Moive from '../components/moive' import store from './store/index' import {DatePicker, Input, Button} from 'antd' export default class App extends React.Component{ constructor(props){ super(props) this.state={} } render(){ return <HashRouter><div> 这是web APP <hr/> <DatePicker/> <hr/> <Input style={{width:'300px',margin:'0px 10px'}} value={store.getState().inputValue} onChange={this.handleInputChange}></Input><Button type="danger">无情 </Button> <hr/> <Link to="/home">首页</Link>&nbsp;&nbsp; <Link to="/movie/top250/20">电影</Link>&nbsp;&nbsp; <Link to="/about">关于</Link>&nbsp;&nbsp; <hr/> <Route path="/home" component={Home}></Route> <Route path="/movie/:type/:id" component={Moive} exact></Route> <Route path="/about" component={About}></Route> </div> </HashRouter> } handleInputChange(e){ const action = { type: 'change_input_value', value: e.target.value } store.dispatch() } }
5eb2c2d2e5e3ff5b18a9be6201c4f118eeaa2089
[ "JavaScript", "Markdown" ]
14
JavaScript
NorthwesternDirector/react-learning
bd829edb305c6d31f9d8d359f081823618903750
47bdd54509d35fecb6647983821f5519f01136ea
refs/heads/master
<file_sep>const currentUser = require('./currentUser'); const isAuth = require('./isAuth'); module.exports = { currentUser: currentUser, isAuth: isAuth };<file_sep>const token = require('express-jwt'); const config = require('../../config'); /* * We are assuming that the JWT will come in a header with the form * Authorization: Bearer ${JWT} * But it could come in a query parameter with the name that you want like * GET https://domain.com/stats?apiKey=${JWT} */ const getTokenFromHeader = req => { const requestHeader = req.headers.authorization; if(requestHeader && (requestHeader.split(' ')[0] ==='Token' || requestHeader.split(' ')[0] ==='Bearer')){ return requestHeader.split(' ')[1]; } return null; } const isAuth = token({ secret: config.jwtSecret, userProperty: 'token', getToken: getTokenFromHeader }); module.exports = isAuth; <file_sep>'use strict'; const expressLoader = require('./express'); const mongooseLoader = require('./mongoose'); const Logger = require('./logger'); const appLoader = async (expressApp) => { try { const mongoConnection = await mongooseLoader(); Logger.info('DB loaded and connected!'); await expressLoader({ app: expressApp }); Logger.info('Express loaded'); } catch (error) { console.log(error); } } module.exports = appLoader;<file_sep>'use strict'; const router = require('express').Router(); const auth = require('./auth'); const user = require('./routes/user'); const driver = require('./routes/driver'); const appRoute = () => { const app = router(); auth(app); user(app); driver(app); return app; } module.exports = appRoute;<file_sep>'use strict'; const { Router } = require('express'); const { celebrate, Joi } = require('celebrate'); const middlewares = require('../middlewares'); const Container = require("typedi").Container; const route = Router(); route.post('/signup', celebrate({ body: Joi.object({ name: Joi.string().required(), email: Joi.string().required(), password: Joi.string().required() }) }), async (req, res, next) => { const logger = Container.get('logger'); try { const authService = Container.get(AuthService); const { user, token } = await authService.signup(req.body); return res.json({user, taken}).status(201); } catch (error) { logger.error('error %o ', error); return next(error); } } ); route.post('/signin', celebrate({ body: Joi.object({ email: Joi.string().required(), password: Joi.string().required() }) }), async (req, res, next) => { const logger = Container.get('logger'); try { const authService = Container.get(AuthService); const { user, token } = await authService.signup(req.body); return res.json({user, taken}).status(200); } catch (error) { logger.error('error %o ', error); return next(error); } } ); route.post('/logout', middlewares.isAuth, (req, res, next) => { async (req, res, next) => { const logger = Container.get('logger'); try { return res.status(200).end() } catch (error) { logger.error('error %o ', error); return next(error); } } });
7df03ac672add1fc2cd48f9106e8205393bed244
[ "JavaScript" ]
5
JavaScript
raj967452/uber_app
2110b87c8f630b3540782129d9090fa4d723aaf5
75523a4daf9da4953705fa2b57ea119895c1dd91
refs/heads/master
<repo_name>maxkalahur/GuestBook_app<file_sep>/src/AppBundle/Controller/DefaultController.php <?php namespace AppBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use AppBundle\Form\MessageType; class DefaultController extends Controller { /** * @Route("/", name="homepage") */ public function indexAction(Request $request) { $form = $this->createForm(MessageType::class); $form->handleRequest($request); if ($form->isValid()) { $data = $form->getData(); $this->get('app.messages_manager')->saveMessage($data); unset($form); $form = $this->createForm(MessageType::class); } $em = $this->getDoctrine()->getManager(); $messages = $em->getRepository('AppBundle:Message')->findAllDesc(); return $this->render('default/index.html.twig', [ 'form' => $form->createView(), 'messages' => $messages, ]); } } <file_sep>/src/AppBundle/Command/MessagesRemoveCommand.php <?php // src/AppBundle/Command/GreetCommand.php namespace AppBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class MessagesRemoveCommand extends ContainerAwareCommand { protected function configure() { $this ->setName('messages:remove') ->setDescription('Remove old messages') ->addArgument( 'count', InputArgument::REQUIRED, 'How many old massages delete?' ) ; } protected function execute(InputInterface $input, OutputInterface $output) { $count = $input->getArgument('count'); $messagesManager = $this->getContainer()->get('app.messages_manager'); $res = $messagesManager->remove($count); if( $res ) { $text = 'Messages were removed'; } else { $text = 'Error is occurred'; } $output->writeln($text); } }<file_sep>/README.md ollsent-test.app ================ A Symfony project created on June 16, 2016, 11:42 am. <file_sep>/src/AppBundle/Messages/MessagesManager.php <?php namespace AppBundle\Messages; use Doctrine\ORM\EntityManager; use AppBundle\Entity\Message; use AppBundle\Entity\User; class MessagesManager { protected $em; protected $tokenGenerator; public function __construct(EntityManager $em, $tokenGenerator) { $this->em = $em; $this->tokenGenerator = $tokenGenerator; } public function saveMessage($data) { $em = $this->em; $user = $this->getUser($data); $message = new Message(); $message->setText( $data['text'] ); $message->setUser( $user ); $em->persist($message); $em->flush(); return true; } public function getUser($data) { $em = $this->em; $user = $em->getRepository('AppBundle:User')->findOneByEmail($data['email']); if( !$user ) { $user = new User(); $user->setEmail($data['email']); $user->setUsername($data['username']); $password = substr($this->tokenGenerator->generateToken(), 0, 8); $user->setPassword($password); } return $user; } public function remove($count) { $em = $this->em; $repo = $em->getRepository('AppBundle:Message'); return $lastMessages = $repo->deleteLast($count); } }<file_sep>/src/AppBundle/EventListener/RegistrationListener.php <?php namespace AppBundle\EventListener; use Doctrine\ORM\EntityManager; use Doctrine\ORM\EntityManagerInterface; use FOS\UserBundle\FOSUserEvents; use FOS\UserBundle\Event\FormEvent; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use AppBundle\Entity\Message; /** * Listener responsible to change the redirection at the end of the password resetting */ class RegistrationListener implements EventSubscriberInterface { private $em; private $router; public function __construct(EntityManagerInterface $em, UrlGeneratorInterface $router) { $this->em = $em; $this->router = $router; } public static function getSubscribedEvents() { return array( FOSUserEvents::REGISTRATION_SUCCESS => 'onRegistrationSuccess', ); } public function onRegistrationSuccess(FormEvent $event) { $message = new Message(); $message->setText('Приветствуем нового пользователя ' . $event->getForm()->get('username')->getData()); $this->em->persist($message); $this->em->flush(); $url = $this->router->generate('homepage'); $event->setResponse(new RedirectResponse($url)); } }<file_sep>/src/AppBundle/Repository/MessageRepository.php <?php namespace AppBundle\Repository; /** * MessageRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class MessageRepository extends \Doctrine\ORM\EntityRepository { public function findAllDesc() { return $this->findBy(array(), array('id' => 'DESC')); } public function deleteLast($count) { $qb = $this->createQueryBuilder('m'); $query = $qb->select('m') ->orderBy('m.id', 'DESC') ->setMaxResults($count) ->getQuery(); $res = $query->getResult(); $em = $this->getEntityManager(); foreach ($res as $message) { $em->remove($message); } $em->flush(); return $res; } }
24f97531a75ecd44cfe6870f79878a9b3bcd879e
[ "Markdown", "PHP" ]
6
PHP
maxkalahur/GuestBook_app
a1444ef642810cc09827ec5bcb63cc51e4980bef
53085ece749c62a3e5b28692ca59aa8c0fce7a73
refs/heads/main
<repo_name>GoldenBear19355/Assignments<file_sep>/README.md # Assignments Repo for submitting assignments
c8a3750f9c99aeb361163add03894106fad09cdc
[ "Markdown" ]
1
Markdown
GoldenBear19355/Assignments
0f7b24c8fd2b19d8ca54ce429567b8b04fb71fd8
6fcdce15123a02921b154244659cb34c6dce49bf
refs/heads/master
<repo_name>zgw18829280229/toy_app<file_sep>/app/models/class1.rb class Class1 < ActiveRecord::Base has_many :student2s end <file_sep>/app/views/student2s/_student2.json.jbuilder json.extract! student2, :id, :name, :age, :class1_id, :created_at, :updated_at json.url student2_url(student2, format: :json) <file_sep>/app/models/student1.rb class Student1 < ActiveRecord::Base belongs_to :class1 end <file_sep>/app/views/class1s/index.json.jbuilder json.array! @class1s, partial: 'class1s/class1', as: :class1 <file_sep>/app/controllers/class1s_controller.rb class Class1sController < ApplicationController before_action :set_class1, only: [:show, :edit, :update, :destroy] # GET /class1s # GET /class1s.json def index @class1s = Class1.all end # GET /class1s/1 # GET /class1s/1.json def show end # GET /class1s/new def new @class1 = Class1.new end # GET /class1s/1/edit def edit end # POST /class1s # POST /class1s.json def create @class1 = Class1.new(class1_params) respond_to do |format| if @class1.save format.html { redirect_to @class1, notice: 'Class1 was successfully created.' } format.json { render :show, status: :created, location: @class1 } else format.html { render :new } format.json { render json: @class1.errors, status: :unprocessable_entity } end end end # PATCH/PUT /class1s/1 # PATCH/PUT /class1s/1.json def update respond_to do |format| if @class1.update(class1_params) format.html { redirect_to @class1, notice: 'Class1 was successfully updated.' } format.json { render :show, status: :ok, location: @class1 } else format.html { render :edit } format.json { render json: @class1.errors, status: :unprocessable_entity } end end end # DELETE /class1s/1 # DELETE /class1s/1.json def destroy @class1.destroy respond_to do |format| format.html { redirect_to class1s_url, notice: 'Class1 was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_class1 @class1 = Class1.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def class1_params params.require(:class1).permit(:name) end end <file_sep>/app/models/student2.rb class Student2 < ActiveRecord::Base belongs_to :class1 end <file_sep>/app/views/student2s/index.json.jbuilder json.array! @student2s, partial: 'student2s/student2', as: :student2 <file_sep>/app/views/class1s/_class1.json.jbuilder json.extract! class1, :id, :name, :created_at, :updated_at json.url class1_url(class1, format: :json) <file_sep>/app/views/student2s/show.json.jbuilder json.partial! "student2s/student2", student2: @student2 <file_sep>/test/controllers/student2s_controller_test.rb require 'test_helper' class Student2sControllerTest < ActionController::TestCase setup do @student2 = student2s(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:student2s) end test "should get new" do get :new assert_response :success end test "should create student2" do assert_difference('Student2.count') do post :create, student2: { age: @student2.age, class1_id: @student2.class1_id, name: @student2.name } end assert_redirected_to student2_path(assigns(:student2)) end test "should show student2" do get :show, id: @student2 assert_response :success end test "should get edit" do get :edit, id: @student2 assert_response :success end test "should update student2" do patch :update, id: @student2, student2: { age: @student2.age, class1_id: @student2.class1_id, name: @student2.name } assert_redirected_to student2_path(assigns(:student2)) end test "should destroy student2" do assert_difference('Student2.count', -1) do delete :destroy, id: @student2 end assert_redirected_to student2s_path end end <file_sep>/db/migrate/20170807101710_add_age_to_student1.rb class AddAgeToStudent1 < ActiveRecord::Migration def change add_column :student1s, :age, :integer end end <file_sep>/app/views/student1s/_student1.json.jbuilder json.extract! student1, :id, :name, :class1_id, :created_at, :updated_at json.url student1_url(student1, format: :json) <file_sep>/test/controllers/class1s_controller_test.rb require 'test_helper' class Class1sControllerTest < ActionController::TestCase setup do @class1 = class1s(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:class1s) end test "should get new" do get :new assert_response :success end test "should create class1" do assert_difference('Class1.count') do post :create, class1: { name: @class1.name } end assert_redirected_to class1_path(assigns(:class1)) end test "should show class1" do get :show, id: @class1 assert_response :success end test "should get edit" do get :edit, id: @class1 assert_response :success end test "should update class1" do patch :update, id: @class1, class1: { name: @class1.name } assert_redirected_to class1_path(assigns(:class1)) end test "should destroy class1" do assert_difference('Class1.count', -1) do delete :destroy, id: @class1 end assert_redirected_to class1s_path end end <file_sep>/app/controllers/student2s_controller.rb class Student2sController < ApplicationController before_action :set_student2, only: [:show, :edit, :update, :destroy] # GET /student2s # GET /student2s.json def index @student2s = Student2.all end # GET /student2s/1 # GET /student2s/1.json def show end # GET /student2s/new def new @student2 = Student2.new end # GET /student2s/1/edit def edit end # POST /student2s # POST /student2s.json def create @student2 = Student2.new(student2_params) respond_to do |format| if @student2.save format.html { redirect_to @student2, notice: 'Student2 was successfully created.' } format.json { render :show, status: :created, location: @student2 } else format.html { render :new } format.json { render json: @student2.errors, status: :unprocessable_entity } end end end # PATCH/PUT /student2s/1 # PATCH/PUT /student2s/1.json def update respond_to do |format| if @student2.update(student2_params) format.html { redirect_to @student2, notice: 'Student2 was successfully updated.' } format.json { render :show, status: :ok, location: @student2 } else format.html { render :edit } format.json { render json: @student2.errors, status: :unprocessable_entity } end end end # DELETE /student2s/1 # DELETE /student2s/1.json def destroy @student2.destroy respond_to do |format| format.html { redirect_to student2s_url, notice: 'Student2 was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_student2 @student2 = Student2.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def student2_params params.require(:student2).permit(:name, :age, :class1_id) end end
06fc68d1ae597d97a5e49a8ff0b08a92c46aabfa
[ "Ruby" ]
14
Ruby
zgw18829280229/toy_app
2646c2c908608cfda86c1b2df24b64cc0607d3f4
1f2652de94de41500f4465124d909470eee0f3da
refs/heads/master
<file_sep>#!/bin/bash function summary() { read_len=`sed -n '2p' $1 | cut -f 2` read raw clean <<< `sed -n '3p' $1 | awk '{print $5*2,$7*2}'` read C1 C2 <<< `sed -n '10p' $1 | awk '{print $7,$11}'` read G1 G2 <<< `sed -n '11p' $1 | awk '{print $7,$11}'` GC=`echo "scale=2; (${C1:1:5} + ${C2:1:5} + ${G1:1:5} + ${G2:1:5})/2" | bc` ((bases=raw*150)) read Q1 Q2 <<< `sed -n '15p' $1 | awk '{print $15,$19}'` Q20=`echo "scale=2; (${Q1:1:5} + ${Q2:1:5})/2" | bc` read Q1 Q2 <<< `sed -n '16p' $1 | awk '{print $15,$19}'` Q30=`echo "scale=2; (${Q1:1:5} + ${Q2:1:5})/2" | bc` printf "Raw\t%s\t%s\t%s\t%s%%\t%s%%\t%s%%\n" $2 $raw $bases $GC $Q20 $Q30 read C1 C2 <<< `sed -n '10p' $1 | awk '{print $9,$13}'` read G1 G2 <<< `sed -n '11p' $1 | awk '{print $9,$13}'` GC=`echo "scale=2; (${C1:1:5} + ${C2:1:5} + ${G1:1:5} + ${G2:1:5})/2" | bc` ((bases=clean*150)) read Q1 Q2 <<< `sed -n '15p' $1 | awk '{print $17,$21}'` Q20=`echo "scale=2; (${Q1:1:5} + ${Q2:1:5})/2" | bc` read Q1 Q2 <<< `sed -n '16p' $1 | awk '{print $15,$19}'` Q30=`echo "scale=2; (${Q1:1:5} + ${Q2:1:5})/2" | bc` printf "Clean\t%s\t%s\t%s\t%s%%\t%s%%\t%s%%\n" $2 $clean $bases $GC $Q20 $Q30 } if [ $# -ne 2 ]; then echo "USAGE: sh filter_stat_summary.sh Basic_Statistics_of_Sequencing_Quality.txt sampleName" exit 0 fi summary $1 $2 <file_sep>#!/bin/env python # 2014-5-6 Linxzh import argparse parser = argparse.ArgumentParser() parser.add_argument('-i', help = 'input file', type = argparse.FileType('r')) parser.add_argument('-o', help = 'output file', type = argparse.FileType('w')) args = parser.parse_args() # fpkm line cache def fpkm_line(in_file, out_file): for l in in_file: llist = l.split() frag = llist[2] fpkm = llist[13][1:-4] id = llist[11][1:-4].replace('M','G') if frag == 'transcript' and 'Csa' in l: out_file.write(id + '\t' + fpkm + '\n') if __name__ == '__main__': fpkm_line(args.i, args.o) <file_sep># load expression data load('datExpr.RData') if(dim(datExpr)[2]^2 > 2^31){ print('Now, Data is too huge to handle for WGCNA!\n You could trim you data or follow the block-wise- network-construction script in WGCNA.') quit(save='no') } # environment library(WGCNA) options(stringsAsFactors=FALSE) enableWGCNAThreads(6) # softpower softPower = 7 # unsigned type adjacency = adjacency(datExpr, power = softPower) save(file='adjMat.RData', adjacency) TOM = TOMsimilarity(adjacency) dissTOM = 1 - TOM save(file='dissTOM.RData', dissTOM) #load('dissTOM.RData') geneTree = hclust(as.dist(dissTOM), method='average') minModuleSize = 30 dynamicMods = cutreeDynamic(dendro = geneTree, distM = dissTOM, deepSplit = 4, pamRespectsDendro = FALSE, minClusterSize = minModuleSize) dynamicColors = labels2colors(dynamicMods) MEList = moduleEigengenes(datExpr, colors = dynamicColors) MEs = MEList$eigengenes MEDiss = 1 - cor(MEs) METree = hclust(as.dist(MEDiss), method = 'average') # plot genetree cluster #pdf(file = 'GeneTreeCluster.pdf', wi=12, he=9) #plot(METree, main= 'Clustering of module eigengenes', xlab = '', sub = '', cex.lab = 0.6, cex.axis = 0.8) #dev.off() # plot module eigengenes cluster MEDissThres = 0.25 #pdf(file = 'ClusterModuleEigengenes.pdf', wi=12, he=9) #plot(METree, main='Clustering of module eigengenes', xlab = '', sub = '') #abline(h=MEDissThres, col = 'red') #dev.off() # module merge merge = mergeCloseModules(datExpr, dynamicColors, cutHeight = MEDissThres , verbose = 3) mergedColors = merge$colors mergedMEs = merge$newMEs pdf(file = 'BeforeAndAfterMerge.pdf', wi=12, he=9) plotDendroAndColors(geneTree, cbind(dynamicColors, mergedColors), dendroLabels = FALSE, hang = 0.03, addGuide = TRUE, guideHang = 0.05) dev.off() png(file = 'BeforeAndAfterMerge.png', wi=2000, he=1600) plotDendroAndColors(geneTree, cbind(dynamicColors, mergedColors), dendroLabels = FALSE, hang = 0.03, addGuide = TRUE, guideHang = 0.05) dev.off() moduleColors = mergedColors colorOrder = c('grey', standardColors(100)) moduleLabels = match(moduleColors, colorOrder) - 1 MEs = mergedMEs save(file='dynamic_merged_networkdata.RData', MEs, moduleLabels, moduleColors, geneTree, dynamicMods) intramoduleConectivity = intramodularConnectivity(adjacency, moduleColors) intramoduleConectivity = cbind(intramoduleConectivity, moduleColors) write.table(intramoduleConectivity, file='intramoduleConectivity_all.xls', sep='\t', quote=F, col.names=NA) <file_sep>#!/usr/bin/env python import sys def fun(gtf): D = {} with open(gtf) as handle: for l in handle: if l.startswith('#') or l.startswith('\n'): continue tmplist = l.split('\t') qStart = int(tmplist[3]) qEnd = int(tmplist[4]) items = tmplist[8].split(';') # qName = items[1][5:] tName = tmplist[0] strand = tmplist[6] blockSize = qEnd - qStart + 1 if tmplist[2] == 'gene': transcript = '' elif 'mRNA' == tmplist[2]: transcript = items[0][3:] D[transcript] = [strand, transcript, tName, [], [], [], (qStart,qEnd)] elif 'CDS' == tmplist[2] and transcript: D[transcript][3].append(qStart) D[transcript][4].append(qEnd) D[transcript][5].append(blockSize) return D def write_lines(D, psl): out = open(psl, 'w') for t in D: line = '0\t0\t0\t0\t0\t0\t0\t0\t%s\t%s\t%s\t0\t%s\t%s\t0\t%s\t%s\t%s\t%s\t%s\t%s\n' % (D[t][0], D[t][1], D[t][-1][1] + 1 - D[t][-1][0], D[t][-1][1] - D[t][-1][0], D[t][2], D[t][-1][0] -1, D[t][-1][1], len(D[t][5]), ''.join([str(x)+',' for x in D[t][5]]), '0,' * len(D[t][5]), ''.join([str(x-1)+',' for x in D[t][3]])) out.write(line) out.close() if __name__ == '__main__': D = fun(sys.argv[1]) print len(D) write_lines(D, sys.argv[2]) <file_sep>#!/bin/env python # 2014-12-28 Linxzh # Modified: 2015-7-13 # get motif accession html from PLACE import urllib2 import argparse import os parser = argparse.ArgumentParser() parser.add_argument('-p', help='output folder') parser.add_argument('-i', help='input file, accession2genes.txt') args = parser.parse_args() def get_html(accession, outpath): '''download description from PLACE by accession, save it as text.''' if not outpath.endswith('/'): outpath = outpath + '/' user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' userheader = {'User-Agent': user_agent} prefix = 'http://www.dna.affrc.go.jp/sigscan/disp.cgi?' url = ''.join((prefix, accession)) req = urllib2.Request(url, None, userheader) htmltext = urllib2.urlopen(req, timeout=10).read() outhtmlname = ''.join((outpath, accession, '.txt')) outhtml = open(outhtmlname, 'w') outhtml.write(htmltext) outhtml.close() def get_item(filedir, accession, itemName): filename = ''.join((filedir, accession, '.txt')) with open(filename) as handle: handlelist = handle.readlines() targetline = [x for x in handlelist if x.startswith(itemName)] if targetline: item = targetline[0].split(' ')[1] item = item.strip() else: item = 'None' return item if __name__ == '__main__': if not os.path.exists(args.p): os.mkdir(args.p) print "Create folder: %s" % args.p path = args.p infile = args.i with open(infile) as handle: for f in handle: if not f.startswith('S'): continue flist = f.split('\t') accession = flist[0] # 1st col as accession get_html(accession, path) <file_sep>import sys from reportlab.lib.units import cm from Bio.Graphics import BasicChromosome from reportlab.lib import colors def group2features(infile): features = [] with open(infile) as handle: for f in handle: if f.startswith(';'): continue tmplist = f.split() tmp_feature = ( float(tmplist[1]) * 1000, float(tmplist[1]) * 1000, '0', tmplist[1] + ' : ' + tmplist[0], 'black') features.append(tmp_feature) return features if __name__ == "__main__": max_length = float(sys.argv[2]) * 1000 telomere_length = 10000 chr_diagram = BasicChromosome.Organism() chr_diagram.page_size = (15*cm, 30*cm) features = group2features(sys.argv[1]) group = BasicChromosome.Chromosome(sys.argv[3]) group.scale_num = max_length + 2 * telomere_length start = BasicChromosome.TelomereSegment() start.scale = telomere_length group.add(start) body = BasicChromosome.AnnotatedChromosomeSegment(max_length, features) body.scale = max_length group.add(body) end = BasicChromosome.TelomereSegment(inverted=True) end.scale = telomere_length group.add(end) chr_diagram.add(group) chr_diagram.draw(sys.argv[4], "Group for Joinmap") <file_sep>#!/bin/env python # 2014-11-28 Linxzh # according to the gene position in the genome, draw the cluster import argparse import svgwrite from svgwrite import cm,mm parser = argparse.ArgumentParser() parser.add_argument('-i', help='input file') parser.add_argument('-o', help='output file') args = parser.parse_args() chr_len = {'Chr1':29149675, 'Chr2':23174626, 'Chr3':39782674, 'Chr4':23425844, 'Chr5':28023477, 'Chr6':29076228, 'Chr7':19226500} # draw 7 chromosome line def chromesome_line(draw): for i in range(1,8): chrom = 'Chr' + str(i) x1, y1 = 1*cm, (2 + i * 1.5)*cm x2, y2 = (1 + chr_len[chrom] / 1000000.0)*cm, y1 draw.add(draw.line(start=(x1, y1), end=(x2, y2), stroke ='black', stroke_width = 0.25*mm)) return draw # read genes pos into dict def pos_to_dict(infile): Chr1 = Chr2 = Chr3 = Chr4 = Chr5 = Chr6 = Chr7 = [] with open(infile) as f: # draw all genes' start positions def all_gene(draw): # with open('/share/fg3/Linxzh/Tmp/tmp.txt') as f: # with open('/share/fg3/Linxzh/Data/Cucumber_ref/genes_pos.txt') as f: fl = f.readlines() pos = [x.split()[:2] for x in fl] # print pos for p in pos: chrom = int(p[0][-1]) position = int(p[1]) x1, y1 = (1 + position / 1000000.0), (2 + chrom * 1.5 - 0.2) x2, y2 = x1, (2 + chrom * 1.5 + 0.2) draw.add(draw.line(start=(x1*cm, y1*cm), end=(x2*cm, y2*cm), stroke='blue', stroke_width = 0.05 *mm)) # print position / 1000000.0 return draw # draw cluster genes as a single line def clust_line(draw, pos_list): Chr1 = Chr2 = Chr3 = Chr4 = Chr5 = Chr6 = Chr7 = [] for p in pos_list: if __name__ == '__main__': dwg = svgwrite.Drawing(filename='test.svg', size =(45*cm, 15*cm)) chromesome_line(dwg) all_gene(dwg) dwg.save() <file_sep>#!/usr/bin/python import sys if len(sys.argv) != 5: print "USAGE: python filter.py input.loc output.loc missingRate(float) ProSampleNum(int)" sys.exit(0) sample= int(sys.argv[4]) missnum = int(sample * float(sys.argv[3])) + 1 with open(sys.argv[1]) as handle: filelist = handle.readlines() # markerlist = filelist[5:-(sample+1)] markerlist = [x for x in filelist if not x.startswith('#')] out = [x for x in markerlist if x.count('--') < missnum and x.strip()] print len(out) print out[0] D={} for l in out: llist = l.split('\t') k='\t'.join(llist[2:]) v='\t'.join(llist[:2]) D[k] = v print D.items()[0] with open(sys.argv[2], 'w') as handle: for k,v in D.items(): s = '%s\t%s' % (v,k) handle.write(s) <file_sep>#!/usr/bin/python #----------------------------------------------------- # python script.py Basic_Statistics_of_Sequencing_Quality.txt Statistics_of_Filtered_Reads.txt output.txt #----------------------------------------------------- import sys import os if len(sys.argv) != 4: print "python script.py Basic_Statistics_of_Sequencing_Quality.txt Statistics_of_Filtered_Reads.txt output.txt" sys.exit() with open(sys.argv[1]) as handle: basic = handle.readlines() with open(sys.argv[2]) as handle: statics = handle.readlines() clean_reads = int(basic[2].split('\t')[3].split(' ')[0]) N_bases = int(statics[6].split('\t')[1]) /2 low_quality = int(statics[3].split('\t')[1])/2 adapters = int(statics[2].split('\t')[1])/2 result = 'Clean Reads\t%s\nContaining N\t%s\nLow Quality\t%s\nContaining Adaptor\t%s\n' % (clean_reads,N_bases,low_quality,adapters) with open(sys.argv[3],'w') as handle: handle.write(result) #cmd = '/nfs2/pipe/RNA/soft/R-3.1.2/bin/Rscript /nfs/pipe/RNA/RNA-ref/version1/filter/plot_RawReadsClass.R ' + sys.argv[3] cmd = 'Rscript /nfs3/onegene/user/group1/linxingzhong/scripts/bio/QC/plot_RawReadsClass.R ' + sys.argv[3] os.system(cmd) #print clean_reads,N_bases,low_quality,adapters <file_sep>library(pheatmap) args = commandArgs(T) agene = read.table(args[1], header=T) #bgene = read.table(args[2], header=T) #intergene = intersect(agene[,1], bgene[,1]) allexp = read.table(args[2], header=T, row.names = 1) prefix = args[3] inter_gene_exp = allexp[rownames(allexp)%in%agene[,1],] pdf(paste(prefix,'.pdf',sep='')) # 在进行聚类的时候,一般选择的基因数目不能太多,最好别超过250个 # 有时基因数目太多,需要设置下右边基因ID字体的大小(参数 fontsize_row) pheatmap(log10(data.matrix(inter_gene_exp)+1), fontsize_row = 8) dev.off() png(filename=paste(prefix, '.png', sep='')) pheatmap(log10(data.matrix(inter_gene_exp)+1), fontsize_row = 8) dev.off() write.table(file=paste(prefix, '_exp.xls', sep=''), inter_gene_exp, sep='\t', quote=F) <file_sep>#!/usr/bin/python import sys if len(sys.argv) != 3: print "USAGE: python degenerate.py inputfile outputfile" sys.exit(0) DegenerateBase_Dict = {'A':'AA', 'T':'TT', 'C':'CC', 'G':'GG', 'R':"AG", 'Y':'CT', 'M':'AC', 'K':'GT', 'S':'GC', 'W':'AT', 'H':'ATC', 'B':'GTC', 'V':'GAC', 'D':'GAT', '-':'--'} infile = open(sys.argv[1]) out = [] for f in infile: if f.startswith('#'): out.append(f) continue flist = f.strip().split('\t') bases = map(lambda x : DegenerateBase_Dict[x], flist[1:]) newline = flist[0] + '\t' + '\t'.join(bases) + '\n' out.append(newline) infile.close() with open(sys.argv[2], 'w') as handle: handle.writelines(out) <file_sep>#!/usr/bin/python import sys import numpy as np base_dict = {'A':'A', "T":'T', 'C':'C', 'G':'G', 'R':'AG', 'Y':'CT', 'M':'AC', 'K':'GT', 'S':'GC', 'W':'AT', 'H':'ATC', 'B':'GTC', 'V':'GAC', 'D':'GAT', 'N':'ATCG'} def settest(): baseA = base_dict['A'] baseB = base_dict['R'] if set(list(baseA)).intersection(set(list(baseB))): pass def difftest(): baseA = base_dict['A'] baseB = base_dict['R'] if difflib.SequenceMatcher(None, baseA, baseB).ratio(): pass def parseGT(infile): matrix = [] with open(infile) as handle: for f in handle: tmplist = f.split() matrix.append(tmplist[3:]) return matrix def simi(inlist, acol, bcol): M = 0; m = 0 # if f.startswith('#'): # continue for snp_list in inlist: baseA = base_dict[snp_list[acol]] baseB = base_dict[snp_list[bcol]] if set(list(baseA)).intersection(set(list(baseB))): m += 1 M += 1 # print baseA,baseB, M,m return float(m)/M def simiMatrix(gt_matrix, sample_num): similarity_m = np.zeros(sample_num * sample_num).reshape(sample_num, sample_num) for i in range(sample_num): for j in range(i+1, sample_num): similarity_m[i][j] = simi(gt_matrix, i, j) return similarity_m if __name__ == '__main__': gt_matrix = parseGT(sys.argv[1]) simi_matrix = simiMatrix(gt_matrix, int(sys.argv[2])) print simi_matrix <file_sep>#!/usr/bin/python # create by linxzh, 2015-10-27 # according input marker locus, get stacks depth at this locus. import os import sys import gzip import operator if len(sys.argv) != 4: print 'USAGE: python depth_filter.py indir marker_locus output.txt' sys.exit(0) # files' suffix with 'gz' def filter_files(indir): files = os.listdir(indir) files = [x for x in files if x.endswith('gz')] return files # def stacks_depth(marker_locus, infile): D = dict(zip(marker_locus, ["--"] * len(marker_locus))) handle = gzip.open(infile) for f in handle: flist = f.split() locus = flist[2] if locus in marker_locus: depth = int(flist[-2]) if D[locus] == "-": D[locus] = depth else: D[locus] = D[locus] + depth sorted_items = sorted(D.items(), key=operator.itemgetter(0)) depth_list = [x[1] for x in sorted_items] return depth_list if __name__ == '__main__': gzfiles = filter_files(sys.argv[1]) with open(sys.argv[2]) as handle: marker_locus = handle.readlines() marker_locus = [x.strip() for x in marker_locus] sample_list = ['locus'] tmp_depth = [] for gzfile in gzfiles: print 'parsing %s' % gzfile sample = gzfile.split('_')[0] sample_list.append(sample) infile = sys.argv[1] + '/' + gzfile depth_list = stacks_depth(marker_locus, infile) tmp_depth.append(depth_list) sorted_locus = sorted(marker_locus, key=lambda x:int(x)) out_list = [] for i in range(len(marker_locus)): tmp = [str(x[i]) for x in tmp_depth] out_list.append(sorted_locus[i] + '\t' + '\t'.join(tmp) + '\n') with open(sys.argv[3], 'w') as handle: handle.write('\t'.join(sample_list)+'\n') handle.writelines(out_list) <file_sep>#!/bin/bash if [ $# -ne 2 ]; then echo "USAGE: sh check_summary.sh checkfile1 checkfile2" exit 0 fi #echo -e "Sample\tLength\tReads\tBases\tGC(%)\tQ20(%)\tQ30(%)" read readsNum bases length <<< `sed -n '1p' $1 | awk -F '[ ,: ]' '{print $11,$14,$20}'` read gc1 q201 q301<<< `sed -n '$p' $1 | cut -f 2,3,4` read gc2 q202 q302<<< `sed -n '$p' $2 | cut -f 2,3,4` GC=`echo "scale=2;($gc1 + $gc2)/2" | bc` Q20=`echo "scale=2; ($q201 + $q202)/2" | bc` Q30=`echo "scale=2; ($q301 + $q302)/2" | bc` Bases=`echo "$bases * 2" | bc` Reads=`echo "$readsNum * 2" | bc` echo -e "${1%_*}\t$length\t$Reads\t$Bases\t$GC\t$Q20\t$Q30" <file_sep> import sys from Bio import SeqIO def hdrs(fasta, organism): fa = SeqIO.parse(fasta, 'fasta') tmp = [] for f in fa: chrom = f.id chrom_length = len(f) chrom_length_noN = chrom_length - f.seq.count('N') - f.seq.count('n') tmpline = '>%s /len=%s /nonNlen=%s /org=%s\n' % (chrom, chrom_length, chrom_length_noN, organism) tmp.append(tmpline) return tmp if __name__ == "__main__": chrinfo = hdrs(sys.argv[1], sys.argv[2]) with open(sys.argv[3], 'w') as handle: handle.writelines(chrinfo) <file_sep># Writing for Tang # Linxzh 2016-06-21 # Find out genes belong to a Gene Ontology ID. args = commandArgs(T) if (length(args) != 3) { print('USAGE: Rscript GO.R GO_Mapping GO_ID Ontology') print('Ontology: BP for Biological Process') print('CC for Cellular Component') print('MF for Molecular Function') quit(save='no') } tryCatch({ library(topGO) }, error = function(e) { print("You need to install topGO package from bioconductor.") print("You can find help from https://bioconductor.org/packages/release/bioc/html/topGO.html.") quit(save='no') }) library(topGO) geneID2GO = readMappings(file=args[1]) geneNames = names(geneID2GO) tmpgene = geneNames[1:100] geneList = factor(as.integer(geneNames %in% tmpgene)) names(geneList) = geneNames GOdata = new('topGOdata', ontology=args[3], allGenes=geneList, annot=annFUN.gene2GO, gene2GO = geneID2GO) ann.genes = genesInTerm(GOdata, args[2]) write.table(ann.genes, file=paste(args[3], '_',args[2],'.txt', sep=''), sep='\t', quote=F) <file_sep>#! /bin/env python #Date: 2013-11-3 #Author: Linxzh # reverse the sequence from Bio.Seq import reverse_complement import argparse parser = argparse.ArgumentParser() parser.add_argument("-i", help='input file',type=argparse.FileType('r')) parser.add_argument("-o", help='output file',type=argparse.FileType('w')) args = parser.parse_args() n = 0 for l in args.i: if n == 0: n = 1 tmp_id = l elif n ==1: n = 0 if '-' in tmp_id: seq = reverse_complement(l[:-1]) + '\n' else: seq = l args.o.write(tmp_id,seq) args.i.close() args.o.close() <file_sep>import re import sys def summary(infile): with open(infile) as handle: infos = handle.readlines() if len(infos) != 17: raise Exception("Bowtie seems currupt.", infile) total_reads = re.search('^(\d+) ', infos[0]).group(1) uniq = re.search('\s*(\d+).*?([\d\.]+)%.*', infos[3]) total_map = re.search('^([\d\.]+)%*', infos[14]).group(1) #print total_map return total_reads, uniq.group(1), uniq.group(2), total_map if __name__ == "__main__": total_reads, uniq_reads, uniq_map, total_map = summary(sys.argv[1]) sample = re.search('.*_([\d\-\w]*).sh.e.*', sys.argv[1]).group(1) single = float(total_map) - float(uniq_map) print "%s\t%s\t%s%%\t%s%%(%s)\t%s%%(%s)" % \ (sample, format(int(total_reads),','), total_map, uniq_map, format(int(uniq_reads),','), single, format(int(int(total_reads)*single/100),',')) <file_sep># bio-analysis-kit Scripts for bio-data analysis and svg fig drawing. <file_sep>#!/usr/bin/python # get proteion-proteion interaction according genes # expressing differently(significantly) import os import re import gzip import sys def read_pp(infile): if infile.endswith('gz'): handle = gzip.open(infile, 'rb') else: handle = open(infile) pplist = handle.readlines() pplist = [re.sub('\.\d', '', x).split() for x in pplist] # outlist = ['\t'.join(f.split()[:2])+'\n' for f in pplist] return pplist def read_dge(infile): with open(infile) as handle: flist = handle.readlines() return [x.split()[0] for x in flist[1:]] # gene name to string id def name_stringid(stringname): with open(stringname) as handle: handlist = handle.readlines() tmp = [(x.split('\t')[1],x.split('\t')[6].strip()) for x in handlist] f = lambda x:x[::-1] return dict(tmp),dict(map(f, tmp)) def pick_out(pplist, genes, stringids, dgelist): out = [] for gene in dgelist: if gene in genes: out += [x for x in pplist if stringids[genes.index(gene)] in x] return out def add_name(link, dge, id2name): pps = link.split() if pps[0] in id2name: p1name = id2name[pps[0]] else: p1name = pps[0] if pps[1] in id2name: p2name = id2name[pps[1]] else: p2name = pps[1] if p1name in dge: p1dge = dge[p1name] else: p1dge = 'None' if p2name in dge: p2dge = dge[p2name] else: p2dge = 'None' newline = '%s\t%s\t%s\t%s\t%s' % (p1name, p2name, p1dge, p2dge,link) return newline def read_updown(infile): D = {} with open(infile) as handle: for f in handle: flist = f.split('\t') D[flist[0]] = flist[5] return D if __name__ == "__main__": if len(sys.argv) != 4: print "python %s stringdb_links sig_deg outprefix" % sys.argv[0] sys.exit(0) pplinks = read_pp(sys.argv[1]) print len(pplinks) # id2name, name2id = name_stringid('9606__proteins.tsv') updown = read_updown(sys.argv[2]) print len(updown) dge = updown.keys() outsif = [] outdiff = [] for links in pplinks: if links[0] in dge and links[1] in dge: linksline = '\t'.join(sorted(links[:2])) + '\t' + links[2] + '\n' if linksline not in outsif: outsif.append(linksline) outdiff += [gene + '\t'+ updown[gene]+'\n' for gene in links[:2] if gene in updown] outsif = list(set(outsif)) prefix = sys.argv[3] with open(prefix + '.sif','w') as handle: handle.writelines(outsif) with open(prefix + '.data','w') as handle: handle.writelines(outdiff) <file_sep>#!/usr/bin/env python #Created: 2013-11-4 #Modified: 2014-7-16 #Author: Linxzh #retrive promoter sequence before ATG start codon import time import argparse from Bio.Seq import reverse_complement from Bio import SeqIO #specify the arguments parser = argparse.ArgumentParser(description='Find the promoter sequence', prog='Promoter Finder', usage='PROG [options]') parser.add_argument('-l',help='sequence length, default is 2000bp', type=int, default=2000) parser.add_argument('-i',help='input a gene id list', type=argparse.FileType('r')) parser.add_argument('-g', help='gff3 file', type=argparse.FileType('r')) parser.add_argument('-f', help="genome sequence file",type=str) parser.add_argument('-c', type=int, default=1, help='specify the col number of input gene list,default is 1') parser.add_argument('-o', help='output file name(fasta format by default', type=argparse.FileType('w')) parser.add_argument('-r', help='''reverse_complement of the sequence if the strand is '-',default is false, valid parameter is T or F''', default='F', choices=['T','F']) parser.add_argument('-b', help='Remove first line.', default='F', choices=['T','F']) #parser.add_argument('-feature', help='GFF file feature needs to get', type=str) args=parser.parse_args() start = time.clock() #start a clock # transfer the fasta file in a dict def fa_to_dict(fa_file): fa_dict = SeqIO.to_dict(SeqIO.parse(fa_file,'fasta')) print 'Chromesome read complete!' return fa_dict #select gene id by col number def select_gene(inputfile,gene_col, header): #file input and gene col nm gene_list = [] for x in inputfile: if x == '\n': continue x = x.split()[args.c -1] gene_list.append(x) print '%s genes input.' % (len(gene_list)) if header == 'F': return gene_list elif header == 'T': return gene_list[1:] # creat a dict,gene id as key, position as value # input gff3 file def pos(gff3): '''get CDS''' D = {} for x in gff3: if x.startswith('#'): continue elif 'CDS' in x: xlist = x.split() start = int(xlist[3]) end = int(xlist[4]) strand = xlist[6] gene_id = xlist[8].split('=')[1].split(';')[0] chr_id = xlist[0] if gene_id in D: D[gene_id][0].append(start) D[gene_id][0].append(end) else: D[gene_id] = [[start,end],strand,chr_id] print 'GFF3 file parse complete!' return D # find 2000 bp before the ATG def promoter(chr_dict, pos_dict, reverse, output, gene_list, length): n = 0 outputList = [] for gene in gene_list: positions = sorted(pos_dict[gene][0]) gene_strand = pos_dict[gene][1] chrome = chr_dict[pos_dict[gene][2]] print positions if gene_strand == '+': gene_start = positions[0] pro_start = gene_start-length if pro_start < 0: # gene start pos less than length gene_seq = chrome[:gene_start].seq else: gene_seq = chrome[gene_start-length:gene_start].seq elif gene_strand == '-': gene_start = positions[-1] print gene_start # sequence of + strand gene_seq = chrome[gene_start :gene_start + length].seq print gene_start, gene_start + length if reverse == 'T': gene_strand += ' reverse_complement' else: gene_seq = gene_seq.reverse_complement() n+=1 wl = '>%s|%s\n%s\n' % (gene,gene_strand,str(gene_seq)) outputList.append(wl) output.writelines(outputList) print "%s genes found!" % n output.close() if __name__ == '__main__': chr_dict = fa_to_dict(args.f) pos_dict = pos(args.g) gene_list = select_gene(args.i, args.c, args.b) promoter(chr_dict, pos_dict, args.r, args.o, gene_list, args.l) t = time.clock() - start #time comsumed print 'Time: ' ,t #print time consumed <file_sep>args<-commandArgs(T) library(ggplot2) library(grid) library(tools) colours=c("#29B5F0", "#EB5A28" ,"#36D750","#ffffb3") d=read.table(args[1],sep="\t",stringsAsFactors=F) file=strsplit(args[1],"/")[[1]][length(strsplit(args[1],"/")[[1]])] sample=strsplit(file,"\\.")[[1]][1] values=d$V2 d$V1=factor(d$V1,levels=d$V1,order=TRUE) percent_str <- paste(round(values/sum(values) * 100,4), "%", sep="") values <- data.frame(Percentage = round(values/sum(values) * 100,4), Part = d$V1,percent=percent_str ) lab_legend=paste(paste((paste(d$V1,d$V2,sep=" (")),values$percent,sep=","),")",sep="") out=paste(file_path_sans_ext(args[1]),".readsClass.png",sep="") ggtitle1=paste(paste("Partition of Raw Reads(",sample,sep=""),")",sep="") png(out,width=600,height=600) ggplot(values, aes(x="",y=Percentage,fill=Part)) + geom_bar(stat="identity",width=3,color="#555555") +coord_polar("y")+xlab('')+ylab('')+labs(fill="")+scale_fill_manual(values=colours,labels=lab_legend)+theme(axis.ticks=element_blank(),axis.text=element_blank(),panel.grid=element_blank())+ggtitle(ggtitle1)+theme(legend.text = element_text(size = 12, family = "Arial"), plot.title=element_text(size=18, family = "Arial",face="bold"), plot.margin=unit(c(0.1,1.2,0.1,0.4),"cm"))+guides(fill=guide_legend(keywidth=1,keyheight=1.2)) dev.off() <file_sep>#!/bin/env python import sys import xlwt import xlrd def row_writer(idx,rowline,ws, style, infile): '''idx = row index rowline = value list ws = worksheet object''' for i,v in enumerate(rowline): try: ws.write(idx,i,v, style) except ValueError: print "The max column number of xls format is 256!\nPlease check your file or use xlsx instead." print "%s" % infile sys.exit(0) return ws def transfer(infile, style): sheetname ='sheet1' workbook = xlwt.Workbook(encoding='ascii') worksheet = workbook.add_sheet(sheetname) with open(infile) as handle: for idx, rowline in enumerate(handle): rowline = rowline[:-1].split('\t') if len(rowline) > 256: print "Maximun colmun num reached!\nPlease check your file or use xlsx instead." sys.exit(0) worksheet = row_writer(idx, rowline, worksheet, style, infile) return workbook if __name__ == '__main__': if len(sys.argv) != 3: print "USAGE: python excel.py infile outfile" sys.exit(0) filename = sys.argv[1] outfile = sys.argv[2] fontname='Times New Roman' font = xlwt.Font() font.name = fontname style = xlwt.XFStyle() style.font= font workbook = transfer(filename, style) workbook.save(outfile) <file_sep>#!/bin/env python # 2014-3-25 created by Linxzh import svgwrite from svgwrite import cm, mm lengthD = {'Chr1':29149675,'Chr2':23174626,'Chr3':39782674,'Chr4':23425844,'Chr5':28023477,\ 'Chr6':29076228,'Chr7':19226500} infile = open('eurasian_vs_xsbn.txt').readlines() posD = {'Chr1':[],'Chr2':[],'Chr3':[],'Chr4':[],'Chr5':[],'Chr6':[],'Chr7':[]} for i in infile: if '#' in i: continue il = i.split() if il[0] in posD: posD[il[0]].append(il[1:]) dwg = svgwrite.Drawing(filename = 'lintao2.svg', size = (18*cm, 8*cm)) # draw vline def draw_tick(x, y, base, draw, l=0.12): col = {'T':'red', 'A':'black', 'C':'blue', 'G':'green','W':'brown','S':'brown','K':'brown',\ 'M':'brown','Y':'brown','R':'brown','11':'pink','12':'lightpurple'} draw.add(draw.line(start = (x*cm, (y-l/2)*cm), end = (x*cm, (y+l/2)*cm), stroke = col[base],\ stroke_width = 0.1*mm)) return draw for i in range(1,8): x1 = 1; y1 = 1 + (i-1) chrome = 'Chr' + str(i) scale = 2350000.0 # scale number length = lengthD[chrome] pos_set = posD[chrome] chr_len = length /scale # dwg.add(dwg.line(start = (x1*cm, y1*cm), end = ((x1+chr_len)*cm, y1*cm), stroke = 'lightgrey',\ # stroke_width = 5*mm)) dwg.add(dwg.rect(insert = (x1*cm, y1*cm), size = (chr_len*cm, 0.5*cm), fill = 'none', stroke = 'black', stroke_width = 0.5)) for j in pos_set: offset = int(j[0]) / scale span = int(j[2]) / scale dwg.add(dwg.rect(insert = ((x1+offset)*cm, y1*cm), size = (span*cm, 0.5*cm), fill = 'red', stroke = 'red', stroke_width = 0.5)) dwg.save() <file_sep>for i in $(ls $1/${2}*/*gz) do filename=$(basename $i) dirname=$(basename ${i%/*}) #echo $filename $dirname ln -s $i $3/${dirname}_${filename} done <file_sep>#!/bin/env python import os import urllib2 import re import argparse import time parser = argparse.ArgumentParser() parser.add_argument('-p', help='input folder') parser.add_argument('-o1', help='output file, accession to many genes') parser.add_argument('-o2', help='output file, gene to many accessions') args=parser.parse_args() def get_description(accession): user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' userheader = {'User-Agent':user_agent} prefix = 'http://www.dna.affrc.go.jp/sigscan/disp.cgi?' url = ''.join((prefix,accession)) req = urllib2.Request(url, None, userheader) htmltext = urllib2.urlopen(req, timeout=5).read() textlist = htmltext.split('\n') textlist = [x.split(' ')[1] for x in textlist if x.startswith('DE')] return ' '.join(textlist) def motif_anno(path, output1, output2): files = os.listdir(path) files = [f for f in files if f.endswith('html')] motif_acD = {} gene_acsD = {} cwd = os.getcwd() acs = [] for f in files: filename = '/'.join((path,f)) with open(filename) as handle: fl = handle.readlines() header = 85 * '_' + '\n' tail = 43 * '-' + '\n' gene = re.split(";|\|", fl[9])[1] start = fl.index(header) end = fl.index(tail) motif_text = fl[start+1:end -3] for motifline in motif_text: lists = motifline.split() motif = lists[4] name = lists[0] accession = re.search(r'S\d+', lists[-1]).group() acs.append(accession) if motif not in motif_acD: description = get_description(accession) wl = [accession, name, motif, description] motif_acD[motif] = wl # print wl, gene motif_acD[motif].append(gene) gene_acsD[gene] = acs acs = [] os.chdir(cwd) with open(output1,'w') as handle: header = '%s\t%s\t%s\t%s\t%s\n' % ('accession', 'name', 'pattern', 'description', 'genes') handle.write(header) for l in motif_acD.values(): line = '%s\t%s\n' % ('\t'.join(l[:4]), ','.join(set(l[4:]))) handle.writelines(line) with open(output2, 'w') as handle: header = '%s\t%s\n' % ('Gene', 'Accessions') handle.write(header) lines = ['%s\t%s\n' % (x, ','.join(set(y))) for x, y in gene_acsD.items()] handle.writelines(lines) if __name__ == "__main__": motif_anno(args.p, args.o1, args.o2) <file_sep>#!/usr/bin/python # create by linxzh at 2014-8-19 import argparse import re import sys parser = argparse.ArgumentParser('pymerge') parser.add_argument('-A', type=argparse.FileType('r')) parser.add_argument('-B', type=argparse.FileType('r')) parser.add_argument('-Aby', type=int, default=1, help='key col of -A file, default is 1') parser.add_argument('-Bby', type=int, default=1, help='key col of -B file, default is 1') parser.add_argument('-Acol', type=str, help ='to be merged cols') parser.add_argument('-Bcol', type=str, help ='to be merged cols') parser.add_argument('-s', type=str, choices=['all','a','b','ab'], default='all', help ="all = union, a = by -A items,\ b = by -B items, ab = a intersect with b, default is \ all(union). None exits field is filled with '--'") parser.add_argument('-Out', type=argparse.FileType('w')) parser.add_argument('-Sep', type=str, default='\t', help='field delimiter, default is TAB') parser.add_argument('-H', type=int, default=1, help='line num of head line, default is 1') parser.add_argument('-F', type=argparse.FileType('r'), help='file contains a filelist to be merged') args=parser.parse_args() def get_col(flist, cols): colslist = re.split(',|-', cols) if '' in colslist: out = flist[int(colslist[0])-1:] elif '-' in cols: out = flist[int(colslist[0])-1:int(colslist[1])] else: out = [flist[int(x)-1] for x in colslist] return out # read data to dict def read_data(infile, bycol, cols, sep, h): '''bycol is the arg specified by -Aby / -Bby cols specified by -Acol / -Bcol return a dict: {bycol : [target cols] ... }''' if isinstance(infile, str): infile = open(infile) D = {} c = 1 for f in infile: flist = f.strip().split(sep) k = flist[bycol-1] v = get_col(flist, cols) if c == h: hk = 'header' D[hk] = v else: D[k] = v c += 1 return D # def merge_dict(D1, D2, s): '''D1 as primary''' D = {} D1len = len(D1[D1.keys()[0]]) D2len = len(D2[D2.keys()[0]]) if s == 'all': kset = set(D1.keys()) | set(D2.keys()) elif s == 'a': kset = D1.keys() elif s == 'b': kset = D2.keys() elif s == 'ab': kset = set(D1.keys()) & set(D2.keys()) for k in kset: if k in D1 and k in D2 and k != 'header': v = D1[k] + D2[k] elif k in D1 and k not in D2: empty = ['--']*D2len v = D1[k] + empty elif k not in D1 and k in D2: empty = ['--'] * D1len v = empty + D2[k] D[k] = v D['header'] = D1['header'] + D2['header'] return D # def reduce_merge_dict(F, bycol, cols, sep, h, s): filelist = F.readlines() filelist = [x.strip() for x in filelist] tmp = map(lambda x : read_data(x, bycol, cols, sep, h), filelist) D = reduce(lambda x, y : merge_dict(x, y, s), tmp) return D if __name__ == '__main__': if args.F: D = reduce_merge_dict(args.F, args.Aby, args.Acol, args.Sep, args.H, args.s) else: D1 = read_data(args.A, args.Aby, args.Acol, args.Sep, args.H) D2 = read_data(args.B, args.Bby, args.Bcol, args.Sep, args.H) D = merge_dict(D1,D2, args.s) outline = [] header = 'Name\t%s\n' % ('\t'.join(D['header'])) outline.append(header) del D['header'] for k in D: line = '%s\t%s\n' % (k, '\t'.join(D[k])) outline.append(line) args.Out.writelines(outline) <file_sep>#!/bin/bash # created by linxzh, 2015-10-24 # script for sample raw data renaming, converting quality,filtering #----------------------------------------------------------------------- # $1 == index2sample.txt # $2 == index of index # $3 == raw data path # $4 == working dir # $5 == reads length # $6 == data size # sh quality.sh index2sample.txt <index num> <rawdata path> <working dir> <read length> <data size in Gb> #------------------------------------------------------------------------ #echo $1,$2,$3,$4 if [ $# -lt 4 ]; then echo "sh quality.sh index2sample.txt <index num> <rawdata path> <working dir> <readlength> <datasize(G)>" echo "index2sample.list : index1<tab>sample1" echo "index is seperated by '_-'" exit 0 fi mkdir $4/01.ph64 mkdir $4/02.filter declare -A index2sample declare -A old2new # read index and sample file while read a b do # read a b <<< `echo $line | awk '{print $1"\t"$2}'` index2sample[$a]=$b done < $1 # for quality converting for i in $(ls $3/*.gz) do old=$(basename $i) tmpindex=`echo $old | awk -F '_|-' '{print $"'$2'"}'` # echo $tmpindex,tmpindex if [ -n "$tmpindex" ] && [ -n "${index2sample[$tmpindex]}" ]; then #suffix=R${old##*_R[12]} if [[ "$old" =~ "_R1" ]];then suffix=R1.fastq.gz #echo $suffix elif [[ "$old" =~ "_R2" ]];then suffix=R2.fastq.gz fi #echo $suffix,$old new=${index2sample[$tmpindex]}_${suffix} old2new[$old]=$new ln -s $i $4/$new echo -e "$old\t$new" >> old2new.txt ph64sh=${new%%.*}.sh if [[ $ph64sh =~ ^[0-9] ]];then ph64sh=X_${ph64sh} fi echo -e "/nfs/onegene/user/1gene/charles/bin/phred33to64 ../$new $new" > $4/01.ph64/$ph64sh # fqpath for configure file if [[ "$new" =~ _R1\.fastq.gz ]];then echo "KeyName=${new%%_R1*}" >> $4/01.ph64/fqpath.txt echo "length=You need change here" >> $4/01.ph64/fqpath.txt echo "insert=200" >> $4/01.ph64/fqpath.txt echo "q1=$4/01.ph64/$new" >> $4/01.ph64/fqpath.txt echo "q2=$4/01.ph64/${new/_R1./_R2.}" >> $4/01.ph64/fqpath.txt echo >> $4/01.ph64/fqpath.txt fi fi done # for filtering G=$6 if [ $G = 0 ]; then G='' fi mkdir $4/03.cut for j in ${index2sample[*]} do mkdir $4/02.filter/$j filtersh=$j.sh if [[ ${filtersh} =~ ^[0-9] ]];then filtersh=X_${filtersh} fi echo -e "/nfs/pipe/RNA/RNA-ref/version1/filter/SOAPnuke1.3.0 filter -1 $4/01.ph64/${j}_R1.fastq.gz -2 $4/01.ph64/${j}_R2.fastq.gz -r AGATCGGAAGAGCGTCGTGTAGGGAAAGAGTGTA -f GATCGGAAGAGCACACGTCTGAACTCCAGTCAC -l 20 -q 0.3 -n 0.02 -i -c 0 -o $4/02.filter/$j -C ${j}_R1.fq.gz -D ${j}_R2.fq.gz" > $4/02.filter/${filtersh} echo -e "perl /nfs/pipe/RNA/RNA-ref/version1/filter/PlotfilterResult_GC-PE_Forsoapnuke.pl $j/Base_distributions_by_read_position_1.txt $j/Base_distributions_by_read_position_2.txt -k $j -o $j" >> $4/02.filter/${filtersh} # cut sh filename == fitler sh name echo -e "perl /nfs/pipe/RNA/RNA-ref/version1/cutFq2.pl $4/02.filter/${j}/${j}_R1.fq.gz $4/02.filter/${j}/${j}_R2.fq.gz $5 ${j} $6" > $4/03.cut/${filtersh} # fqpath for configure file in cut echo "KeyName=$j" >> $4/03.cut/fqpath.txt echo "length=$5,$5" >> $4/03.cut/fqpath.txt echo "insert=200" >> $4/03.cut/fqpath.txt echo "q1=$4/03.cut/${j}_R1.fq.gz" >> $4/03.cut/fqpath.txt echo "q2=$4/03.cut/${j}_R2.fq.gz" >> $4/03.cut/fqpath.txt echo >> $4/03.cut/fqpath.txt done <file_sep>library(topGO) library(multtest) geneID2GO = readMappings(file='/share/fg3/Linxzh/Tmp/GO/2014-10-6_cucumber_gene2go.map') geneNames = names(geneID2GO) args = commandArgs(TRUE) infile = args[1] outfile = paste(sep='', strsplit(infile, '.', fixed=T)[[1]][1], '_topGO.txt') outgene = paste(sep='', strsplit(infile, '.', fixed=T)[[1]][1], '_topGOgenes.txt') ingene = read.table(infile, header=F) Ingene = as.character(ingene[,1]) geneList = factor(as.integer(geneNames %in% Ingene)) names(geneList) = geneNames GOdata = new('topGOdata', ontology='BP', allGenes=geneList, annot=annFUN.gene2GO, gene2GO = geneID2GO) resultFis = runTest(GOdata, algorithm='classic', statistic='fisher') sigNum = sum(resultFis@score <0.05) Res = GenTable(GOdata,classic=resultFis,orderBy='classic',ranksOf = 'classic', numChar=1000, topNodes=sigNum + 1) # FDR Running raw_p = as.numeric(Res$classic) res = mt.rawp2adjp(raw_p,"BH") adjp = res$adjp[order(res$index), ] ResOut = cbind(Res,data.frame(adjp)) write.table(ResOut, file=outfile, quote=F,row.names=F, sep='\t') # write out gene in every goterm goID = Res$GO.ID for (go in goID) { write.table(go, file=outgene, quote=F,row.names=F, sep='\t', append=T, col.names=F) genesInAll = genesInTerm(GOdata, go)[[1]] genesInSample = intersect(genesInAll, Ingene) write.table(t(data.frame(genesInAll)), file=outgene, quote=F,row.names=F, sep='\t', append=T, col.names=F) write.table(t(data.frame(genesInSample)), file=outgene, quote=F,row.names=F, sep='\t', append=T, col.names=F) } <file_sep>#!/bin/env python # 2014-12-11 Linxzh import argparse import time import re import sys parse = argparse.ArgumentParser() parse.add_argument('-i', help='input') parse.add_argument('-o', help='output') args = parse.parse_args() # read feature pos from gff file def pos_D(posfile): '''read gff file into a dict D = {chrom1:{gene1:{feature1:(start,end) ... }, gene2:{feature1:(start,end)...}, ...}, chrom2:{gene:{feature:(start,end), ... }, ...}, ...}''' D = {} f = open(posfile) for x in f: if 'mRNA' in x or 'CDS' in x or x =='\n': continue # flitter mrna and cds xl = x.split() chrom = xl[0] start = int(xl[3]) end = int(xl[4]) values = re.split('\t|\.|=|,|;', xl[8]) gene = values[1].replace('M','G') # geneID formate if chrom not in D: D[chrom] = {} if gene not in D[chrom]: D[chrom][gene] = {} if 'gene' in x: # add gene and upstream 3k freatures D[chrom][gene]['gene'] = (start, end) D[chrom][gene]['Up3k'] = (start-3000, start -1) continue feature = values[3] D[chrom][gene][feature] = (start, end) return D # detect the features in the peak pos def det_fea(peak_pos, geneD): '''peak_pos = [int(start), int(end)] geneD ={'gene':(intS,intE), 'exon1':(intS,intE)...}''' out = {} for gene,feaD in geneD.items(): for fea,pos in feaD.items(): if pos[0] < peak_pos[0] < pos[1] or pos[0] < peak_pos[1] < pos[1]: if gene not in out: out[gene] = [] out[gene].append(fea) return out # read the peak file def locate(infile, outfile): '''according the peak's position, find the features in the peak's range''' D = pos_D('/share/fg3/Linxzh/Data/Cucumber_ref/Cucumber_20101104.gff3') f = open(infile) o = open(outfile,'w') tmp = [] for x in f: if x.startswith('#') or x.startswith('"') or not x.strip(): continue elif 'fold_enrichment' in x: wl = x.replace('#NAME?','-10*LOG10(pvalue)') wl = '#%s\t%s\t%s\n' % (wl.strip(), 'gene','features') tmp.append(wl) continue xl = x.split() st = int(xl[1]) ed = int(xl[2]) chrom = xl[0] try: geneD = D[chrom] res = det_fea([st, ed], geneD) if res: # print res for gene in res: wl = '%s\t%s\t%s\n' % (x.strip(), gene, '+'.join(res[gene])) else: wl = '%s\t%s\t%s\n' % (x.strip(), 'None', 'None') except KeyError: wl = '%s\t%s\t%s\n' % (x.strip(), 'None', 'None') tmp.append(wl) o.writelines(tmp) if __name__ == '__main__': a = time.time() tmp = locate(args.i, args.o) b = time.time() print b-a <file_sep>#!/bin/python # 2014-11-3 Linxzh import argparse parser = argparse.ArgumentParser() parser.add_argument('-i', help='input file') parser.add_argument('-p', help='ipr enrich output') parser.add_argument('-o', help='output file') args=parser.parse_args() def to_set(infile): with open(infile,'r') as f: fl = f.readlines() fl = [x.strip() for x in fl] fl_set = set(fl) return fl_set def sel_ipr(infile): ipr_list = [] with open(infile) as f: for fl in f: if 'IPR-id' in fl: continue fls = fl.split('\t') ipr = fls[0] if float(fls[6]) <= 0.05: ipr_list.append(ipr) return ipr_list def ipr_dict(infile): D = {} with open(infile) as f: for fl in f: fl_list = fl.split('\t') gene = fl_list[0][:-2].replace('P','G') tmp = fl_list[1].split() iprs = [x for x in tmp if 'IPR' in x] for ipr in iprs: if ipr not in D: D[ipr] = [gene] else: D[ipr].append(gene) return D def final_step(ipr_list, D, sample_set, outfile): out = open(outfile,'w') for ipr in ipr_list: ipr_genes_set = set(D[ipr]) g_set_ipr = '\t'.join(D[ipr]) s_set_ipr = '\t'.join(ipr_genes_set & sample_set) out.write(ipr + '\n') out.write(g_set_ipr + '\n') out.write(s_set_ipr + '\n') out.close() if __name__ == '__main__': M_set = to_set(args.i) M_sel_ipr = sel_ipr(args.p) D = ipr_dict('/share/fg3/Linxzh/Data/Annotation/domestic.ipr.txt') final_step(M_sel_ipr, D, M_set, args.o) <file_sep>library(DESeq) countsTable <- read.delim("readsCount.txt",header=TRUE,stringsAsFactors=TRUE, row.names="GeneID") #countsTable <-countsTable[rowSums(countsTable) >=16, ] conds <- factor(c("CK1","CK2","CK3","Con1","Con2","Con3")) cds <- newCountDataSet( countsTable, conds ) cdsAB <- cds[,c("CK","Con")] cdsAB <- estimateSizeFactors( cdsAB ) cdsAB <- estimateDispersions(cdsAB,method="blind",sharingMode ="fit-only",fitType="local") resAB <- nbinomTest(cdsAB,"CK","Con") write.table(resAB,"out.DESeq.Result.xls",sep = "\t",row.names = F,quote=F) <file_sep>#!/bin/env Rscript args = commandArgs(T) if (length(args) != 4){ print('USAGE: Rscript merge.R pattern merge_colname input_dir output_file') quit() } files = list.files(args[3],pattern = paste(args[1],'$',sep='')) a <- files[1] atable <- read.table(a, header=T, check.names=F, sep='\t') samplea = strsplit(basename(a), '.', fixed=T)[[1]][1] colnames(atable) = c(args[2], samplea) for (i in files[-1]){ print (i) sampleb = strsplit(basename(i), '.', fixed=T)[[1]][1] btable <- read.table(i, header=T, check.names=F, sep='\t') colnames(btable) = c(args[2], sampleb) print(colnames(btable)) #names(btable) <- c('gene_id', fpkm) atable <- merge(atable, btable, by = args[2], all =TRUE) } row.names(atable) = atable[,1] atable = atable[,-1] print(colnames(atable)) write.table(atable, sep='\t', file=args[4], col.names=NA,quote=FALSE, na='NA') command = sprintf("sed -i '1s/^\t/%s\t/g' %s", args[2], args[4]) system(command) <file_sep>#! /bin/env python #Date: 2013-10-31, last edit: 2014-7-9 #Author: Linxzh version = 0.1.3 #add the annotation import argparse import re parser = argparse.ArgumentParser() parser.add_argument("-i", help = 'input a non annotation file',\ type= argparse.FileType('r')) parser.add_argument("-a", \ help = "input an annotation file, default value is 1234.txt, support multi annotation file, -a anno1 -a anno2") parser.add_argument('-o', help = 'the output file', \ type = argparse.FileType('w')) parser.add_argument('-m',default = 1,\ help='gene id col number of non annotation file, default is 1',\ type=int) parser.add_argument('-n',default = 1,\ help='gene id col number of annotation file, default is 1',\ type=int) parser.add_argument('-s', default = '| ', type = str, help='seperate symbol') args=parser.parse_args() # creat a annotation dict def an_2_dict(anno): '''convert the annotation list into a dict, gene id as key, anno as value''' anno_dict = {} annof = open(anno) for x in annof: if '#' in x: anno_dict['header'] = x xl = x.split('\t') gene_id = xl[args.n -1] if '.' in gene_id: gene_id = xl[args.n -1].split('.')[0] gene_id = re.sub('[PM]', 'G', gene_id) anno_dict[gene_id] = x.strip() if 'header' not in anno_dict: print 'You need a header line!' return anno_dict # gene_id corresponding to the annotation def add_anno(infile, anno_dict, sep, m): '''for every item of the input list, add the annotation at the end of the line''' def match_gene(add, gene, anno_dict, tmpD, sep): if gene in anno_dict: add = add + sep + anno_dict[gene] else: add = add + sep + 'None\n' tmpD[gene] = add return tmpD tmpD = {} if isinstance(infile,file): # infile is a file for x in infile: add = '' if x=='\n': continue elif '#' in x: # add header add = x.replace('\n', '\t') + anno_dict['header'] tmpD['header'] = add continue gene = x.split()[m-1] gene = re.sub('[MP]', 'G', gene) gene = gene.split('.')[0] tmp = match_gene(add,gene, anno_dict, tmpD, sep) elif isinstance(infile, dict): # infile is a dict print 'dict' for k,v in infile.items(): tmpD = match_gene(v,k, anno_dict, tmpD, sep) return tmpD def write_dict(tmpD, outfile): wl = ['%s\t%s\n' % (k,v.strip()) for k,v in tmpD.items()] outfile.writelines(wl) if __name__ == '__main__': print type(args.a) print args.a if isinstance(args.a, str): anno1 = an_2_dict(args.a) all_D = add_anno(args.i, anno1, args.s, args.m) else: anno1 = an_2_dict(args.a[0]) all_D = add_anno(args.i, anno1, args.s, args.m) for i in args.a[1:]: annoi = an_2_dict(i) all_D = add_anno(all_D, annoi, args.s, args.m) write_dict(all_D, args.o) <file_sep>import sys import time if len(sys.argv) != 4: print "USAGE: python script.py stringdb_links.txt SigDiff.txt out_prefix" sys.exit(0) score = 750 start = time.time() links = [] with open(sys.argv[1]) as handle: tmplist = handle.readlines() links = [tuple(sorted(x.split()[:2])) for x in tmplist if int(x.split()[2])>score] links = list(set(links)) print time.time() - start start = time.time() diffgenes = [] with open(sys.argv[2]) as handle: for f in handle: if f.startswith('GeneID'): continue gene = f.split()[0] diffgenes.append(gene) print time.time() - start start = time.time() D = {} for gene in diffgenes: tmpgene = [x for x in links if gene in x] D[gene] = tmpgene print time.time() - start start = time.time() all_links_diff = set(reduce(lambda x,y:x+y, D.values())) all_links_diff = ['\t'.join(x)+'\n' for x in all_links_diff] print time.time() - start topGenes = sorted(D.keys(), key=lambda x: len(D[x]), reverse=True) outlinks = [] outlinks += D[topGenes[0]][:100] outlinks += D[topGenes[1]][:50] outlinks += D[topGenes[2]][:50] outlinks += D[topGenes[3]][:50] allout = sys.argv[3] + '_all.txt' topout = sys.argv[3] + '_top250.txt' with open(topout, 'w') as handle: handle.writelines(['\t'.join(x) + '\n' for x in outlinks]) with open(allout, 'w') as handle: handle.writelines(all_links_diff) <file_sep>#!/bin/env python # 2014-12-15 Linxzh # script for my own article # motif enrichment analysis for genes in one module import argparse from fisher import pvalue parse = argparse.ArgumentParser() parse.add_argument('-i', type=argparse.FileType('w'), help='input file') args = parse.parse_args() # summary the motif number def motif_count(motif_list): '''motif count in the input list''' D = {} uni_list = set(motif_list) for motif in uni_list: c = motif_list.count(motif) D[motif]=c return D # fisher exact test def fisher_test(countList): '''countList = [A,B,C,D] ________________|_ALL_|_Module |___ Genes_have_motif|_B___|_D______|___ ___not_have_____|_A-B_|_C-D____|___ ________________|_A___|_C______|___ ''' a = countList[1] b = countList[3] c = countList[0] - a d = countList[2] - b p = pvalue(a,b,c,d) return p.right_tail # read mapping file def read_mapping(infile, dot=False): '''gene to motif mapping file to dict: gene1 motifA,motifB,... gene2 motifA,motifB,motifC,... ... dict like : {gene1:[motifA,motifB...], gene2:[motifA,motifB,motifC...],...''' with open(infile) as f: fl = f.readlines() D = {} for i in fl: ilist = i.split() k = ilist[0] v = ilist[1] v = v.split(',') if dot: v = [x.split('.')[0] for x in v] D[k] = v return D # read module data def read_module(tissus_module): '''{tissue:modules}''' # tissue_module = '/share/fg3/Linxzh/Workspace/subject/dome/FpkmMax5/unmerged/moduleDist/module_tissue_p65.txt' tissue_moduleD = {} with open(tissus_module) as f: for i in f: if i.startswith('#'): continue ilist = i.split() if ilist[1] not in tissue_moduleD: tissue_moduleD[ilist[1]] = [] tissue_moduleD[ilist[1]].append(ilist[3]) return tissue_moduleD # motif in modules, return a motif list def motif_in_module(module, module_geneD, D): genes = module_geneD[module] motif_list = reduce(lambda x,y: x+y, [D[g] for g in genes]) return motif_list # write out the result def writeouttissue(tissue, out): outfile = ''.join((tissue,'_motifEnrichment.txt')) with open(outfile, 'w') as f: f.writelines(out) # enrichment analysis def motif_enrich(D, module, module_geneD, all_motif_countD, all): out = [] out.append(m+'\n') sample_motif_countD = motif_count(motif_in_module(module, module_geneD, D)) sample = len(module_geneD[m]) for motif in sample_motif_countD: countList = [all,all_motif_countD[motif],sample,sample_motif_countD[motif]] p = fisher_test(countList) outline = '--%s\t%s\t%s\n' % (motif, ','.join([str(j) for j in countList]), p) out.append(outline) return out def tissue_motif_enrich(D, tissue_moduleD, module_geneD): all_motif_countD = motif_count(reduce(lambda x,y:x+y,D.values())) all = len(D) # gene num in total for t,modules in tissue_moduleD.items(): # every tissue out = [] for m in modules: # every module in tissue module_out = motif_enrich(D, m, module_geneD, all_motif_countD, all) out += module_out writeouttissue(t, out) if __name__ == '__main__': D = read_mapping('motifsInGene.txt') tissue_moduleD = read_module('/share/fg3/Linxzh/Workspace/subject/dome/FpkmMax5/unmerged/moduleDist/module_tissue_p65.txt') module_geneD = read_mapping('/share/fg3/Linxzh/Workspace/subject/dome/FpkmMax5/unmerged/moduleDist/genesInModule.txt', True) tissue_motif_enrich(D, tissue_moduleD, module_geneD) <file_sep>#!/bin/env python # 2014-4-18 created by Linxzh # to combine additional fqfile with specific fqfile import os import argparse # arguments parser = argparse.ArgumentParser(description='Merge the fqfiles of the same sample produced by different lane', prog = 'Fqfile Merger') parser.add_argument('-dira', type = str) parser.add_argument('-dirb', type = str) parser.add_argument('-diro', type = str, help = 'output dir') args = parser.parse_args() <file_sep>library(ggplot2) library(grid) args = commandArgs(T) infile = args[1] d <- read.table(infile, sep = "\t",stringsAsFactor=F,header=T) draw = function(indexA, indexB, d) { colA = colnames(d)[indexA] colB = colnames(d)[indexB] title = sprintf("Gene Expression between %s and %s", colA,colB) pdffile = sprintf("%s_vs_%s.cor.pdf", colA,colB) pngfile = sprintf("%s_vs_%s.cor.png", colA,colB) B <- cor(d[,colA], d[,colB], method = c("spearman"), use="pairwise.complete.obs") C <- cor(d[,colA], d[,colB], method = c("pearson"), use="pairwise.complete.obs") print('cor') linefit <-lm(d[,colA] ~ d[,colB]) B=round(B,4) C=round(C,4) linefit$coefficients[[2]]=sprintf("%.4f",linefit$coefficients[[2]]) print('darwing') #pdf(pdffile) p = ggplot(data = d, mapping = aes(x = log10(get(colA)), y = log10(get(colB)))) p1 = p + geom_point(colour="#B1639F",size=1) p2 = p1 + xlab(sprintf("log10(%s)",colA))+ylab(sprintf("log10(%s)",colB)) + ggtitle(title) p3 = p2+ theme(axis.text=element_text(size=10),axis.title = element_text(size =13), plot.title=element_text(size=16),legend.title=element_text(size=14,face="plain"),legend.title.align=0,legend.key=element_blank(),legend.text=element_blank(),legend.position=c(0.18,0.92),legend.key.size=unit(0,"cm")) p4 = p3 + geom_text(data=NULL, x=-1, y=3.5,label=paste(paste(" slope k = ",linefit$coefficients[[2]],"\n"),paste("spearman r = ",B,"\n"),paste("pearson r = ",C)),size=3) # p5 = p4 + stat_abline(colour="#A2A3A4",linetype="dashed",lw=0.6) ggsave(p4, file=pdffile) ggsave(p4, file=pngfile) } pick = function(idx, m, d) { choices = combn(idx, m) for (i in seq(1, ncol(choices))) { draw(choices[1,i], choices[2,i], d) } } # for 0 5 9 #for (i in c(0,5,9)) { # pattern = paste('^[Cc].*', i, sep='') # controls = grep(pattern, colnames(d)) # print(controls) # pick(controls, 2, d) #} # for 5 9 for (i in c(5,9)) { pattern = paste('^ABA.*', i, sep='') treats = grep(pattern, colnames(d)) pick(treats, 2, d) pattern = paste('^NDGA.*', i, sep='') treats = grep(pattern, colnames(d)) pick(treats, 2, d) pattern = paste('^control.*', i, sep='') treats = grep(pattern, colnames(d)) pick(treats, 2, d) } <file_sep>#!/nfs2/pipe/RNA/soft/R-3.1.2/bin/Rscript # Created by Linxingzhong at 2015-7-24 # get items in the intersection of venn plot library('VennDiagram') args = commandArgs(TRUE) options(stringsAsFactors=F) #----------------------------------------------------- # USAGE # Rscript VennItemGroup.r <outdir> 1/2 <file1> <file2> <file3> ... # 1 : for venn drawing # 2 : for genes groups #---------------------------------------------------- # read input file as a list File2List = function(args) { tmpList = list() for (arg in args) { name = strsplit(basename(arg), '.', fixed=T)[[1]][1] geneList = read.table(arg, header=T, sep='\t', fill=TRUE, quote="", stringsAsFactors=F)[,1] tmpList[[name]] = geneList } return(tmpList) } # redefined function of set analyis, add the sample names to the result Intersection = function(...) { out = Reduce(intersect, list(...)) return(out) } Union = function(...) { out = Reduce(union, list(...)) return(out) } # get intersection and write them to file InterItems = function(datalist) { if (class(datalist) != "list") stop("Please make sure the input data is in list! ") m = length(datalist) # sample number Names = names(datalist) # sample names outlist = list() if (m == 1) { outlist = datalist } else if (m == 2) { cross = Intersection(datalist[[1]], datalist[[2]]) outlist[[paste(Names, collapse="-")]] = cross a12 = setdiff(datalist[[1]], cross) outlist[[paste(Names, collapse="-")]] = a12 a21 = setdiff(datalist[[2]], cross) outlist[[paste(rev(Names), collapse="-")]] = a21 } else if (m == 3) { n12 = intersect(datalist[[1]], datalist[[2]]) n13 = intersect(datalist[[1]], datalist[[3]]) n23 = intersect(datalist[[2]], datalist[[3]]) n123 = Intersection(n13, n12, n23) a1 = setdiff(datalist[[1]], union(n12,n13)) a2 = setdiff(n12, n123) a3 = setdiff(datalist[[2]], union(n12, n23)) a4 = setdiff(n13, n123) a5 = n123 a6 = setdiff(n23, n123) a7 = setdiff(datalist[[3]], union(n13, n23)) outlist[['a1']] = a1 outlist[['a2']] = a2 outlist[['a3']] = a3 outlist[['a4']] = a4 outlist[['a5']] = a5 outlist[['a6']] = a6 outlist[['a7']] = a7 } else if (m == 4) { n12 = intersect(datalist[[1]], datalist[[2]]) n13 = intersect(datalist[[1]], datalist[[3]]) n14 = intersect(datalist[[1]], datalist[[4]]) n23 = intersect(datalist[[2]], datalist[[3]]) n24 = intersect(datalist[[2]], datalist[[4]]) n34 = intersect(datalist[[3]], datalist[[4]]) n123 = intersect(n12, datalist[[3]]) n124 = intersect(n12, datalist[[4]]) n134 = intersect(n13, datalist[[4]]) n234 = intersect(n23, datalist[[4]]) n1234 = intersect(n123, datalist[[4]]) a6 = n1234 a12 = setdiff(n123, a6) a11 = setdiff(n124, a6) a5 = setdiff(n134, a6) a7 = setdiff(n234, a6) a15 = setdiff(n12, Union(a6, a11, a12)) a4 = setdiff(n13, Union(a6, a5, a12)) a10 = setdiff(n14, Union(a6, a5, a11)) a13 = setdiff(n23, Union(a6, a7, a12)) a8 = setdiff(n24, Union(a6, a7, a11)) a2 = setdiff(n34, Union(a6, a5, a7)) a9 = setdiff(datalist[[1]], Union(a4, a5, a6, a10, a11, a12, a15)) a14 = setdiff(datalist[[2]], Union(a6, a7, a8, a11, a12, a13, a15)) a1 = setdiff(datalist[[3]], Union(a2, a4, a5, a6, a7, a12, a13)) a3 = setdiff(datalist[[4]], Union(a2, a5, a6, a7, a8, a10, a11)) outlist[['a1']] = a1 outlist[['a2']] = a2 outlist[['a3']] = a3 outlist[['a4']] = a4 outlist[['a5']] = a5 outlist[['a6']] = a6 outlist[['a7']] = a7 outlist[['a8']] = a8 outlist[['a9']] = a9 outlist[['a10']] = a10 outlist[['a11']] = a11 outlist[['a12']] = a12 outlist[['a13']] = a13 outlist[['a14']] = a14 outlist[['a15']] = a15 } else if (m == 5) { n12 = intersect(datalist[[1]], datalist[[2]]) n13 = intersect(datalist[[1]], datalist[[3]]) n14 = intersect(datalist[[1]], datalist[[4]]) n15 = intersect(datalist[[1]], datalist[[5]]) n23 = intersect(datalist[[2]], datalist[[3]]) n24 = intersect(datalist[[2]], datalist[[4]]) n25 = intersect(datalist[[2]], datalist[[5]]) n34 = intersect(datalist[[3]], datalist[[4]]) n35 = intersect(datalist[[3]], datalist[[5]]) n45 = intersect(datalist[[4]], datalist[[5]]) n123 = intersect(n12, datalist[[3]]) n124 = intersect(n12, datalist[[4]]) n125 = intersect(n12, datalist[[5]]) n134 = intersect(n13, datalist[[4]]) n135 = intersect(n13, datalist[[5]]) n145 = intersect(n14, datalist[[5]]) n234 = intersect(n23, datalist[[4]]) n235 = intersect(n23, datalist[[5]]) n245 = intersect(n24, datalist[[5]]) n345 = intersect(n34, datalist[[5]]) n1234 = intersect(n123, datalist[[4]]) n1235 = intersect(n123, datalist[[5]]) n1245 = intersect(n124, datalist[[5]]) n1345 = intersect(n134, datalist[[5]]) n2345 = intersect(n234, datalist[[5]]) n12345 = intersect(n1234, datalist[[5]]) a31 = n12345 a30 = setdiff(n1234, a31) a29 = setdiff(n1235, a31) a28 = setdiff(n1245, a31) a27 = setdiff(n1345, a31) a26 = setdiff(n2345, a31) a25 = setdiff(n245, Union(a26, a28, a31)) a24 = setdiff(n234, Union(a26, a30, a31)) a23 = setdiff(n134, Union(a27, a30, a31)) a22 = setdiff(n123, Union(a29, a30, a31)) a21 = setdiff(n235, Union(a26, a29, a31)) a20 = setdiff(n125, Union(a28, a29, a31)) a19 = setdiff(n124, Union(a28, a30, a31)) a18 = setdiff(n145, Union(a27, a28, a31)) a17 = setdiff(n135, Union(a27, a29, a31)) a16 = setdiff(n345, Union(a26, a27, a31)) a15 = setdiff(n45, Union(a18, a25, a16, a28, a27, a26, a31)) a14 = setdiff(n24, Union(a19, a24, a25, a30, a28, a26, a31)) a13 = setdiff(n34, Union(a16, a23, a24, a26, a27, a30, a31)) a12 = setdiff(n13, Union(a17, a22, a23, a27, a29, a30, a31)) a11 = setdiff(n23, Union(a21, a22, a24, a26, a29, a30, a31)) a10 = setdiff(n25, Union(a20, a21, a25, a26, a28, a29, a31)) a9 = setdiff(n12, Union(a19, a20, a22, a28, a29, a30, a31)) a8 = setdiff(n14, Union(a18, a19, a23, a27, a28, a30, a31)) a7 = setdiff(n15, Union(a17, a18, a20, a27, a28, a29, a31)) a6 = setdiff(n35, Union(a16, a17, a21, a26, a27, a29, a31)) a5 = setdiff(datalist[[5]], Union(a6, a7, a15, a16, a17, a18, a25, a26, a27, a28, a31, a20, a29, a21, a10)) a4 = setdiff(datalist[[4]], Union(a13, a14, a15, a16, a23, a24, a25, a26, a27, a28, a31, a18, a19, a8, a30)) a3 = setdiff(datalist[[3]], Union(a21, a11, a12, a13, a29, a22, a23, a24, a30, a31, a26, a27, a16, a6, a17)) a2 = setdiff(datalist[[2]], Union(a9, a10, a19, a20, a21, a11, a28, a29, a31, a22, a30, a26, a25, a24, a14)) a1 = setdiff(datalist[[1]], Union(a7, a8, a18, a17, a19, a9, a27, a28, a31, a20, a30, a29, a22, a23, a12)) outlist[['a1']] = a1 outlist[['a2']] = a2 outlist[['a3']] = a3 outlist[['a4']] = a4 outlist[['a5']] = a5 outlist[['a6']] = a6 outlist[['a7']] = a7 outlist[['a8']] = a8 outlist[['a9']] = a9 outlist[['a10']] = a10 outlist[['a11']] = a11 outlist[['a12']] = a12 outlist[['a13']] = a13 outlist[['a14']] = a14 outlist[['a15']] = a15 outlist[['a16']] = a16 outlist[['a17']] = a17 outlist[['a18']] = a18 outlist[['a19']] = a19 outlist[['a20']] = a20 outlist[['a21']] = a21 outlist[['a22']] = a22 outlist[['a23']] = a23 outlist[['a24']] = a24 outlist[['a25']] = a25 outlist[['a26']] = a26 outlist[['a27']] = a27 outlist[['a28']] = a28 outlist[['a29']] = a29 outlist[['a30']] = a30 outlist[['a31']] = a31 } return(outlist) } # find out specific and common genes among many DGE output files Uniq_Comm = function(datalist) { outlist = list() com_genes = Reduce(intersect, datalist) outlist[['Common_genes']] = com_genes for (i in 1:length(datalist)) { tmpunion = Reduce(union, datalist[-i]) tmpinter = intersect(tmpunion, datalist[[i]]) spegenes = setdiff(datalist[[i]], tmpinter) tmpname = paste(names(datalist)[i],'_Specific', sep='') outlist[[tmpname]] = spegenes } return(outlist) } # write inter items to file WriteInter = function(outlist, outdir) { for (i in 1:length(outlist)) { outfile = paste(outdir, '/', names(outlist[i]), '_', length(outlist[[i]]), '.txt', sep = '') tmpdataframe = as.data.frame(outlist[[i]]) names(tmpdataframe) = 'Gene' write.table(tmpdataframe, file= outfile, row.names=FALSE, sep='\t', quote=F) # print(outfile) } } # draw plot DrawVenn = function(datalist, outdir) { venn.plot=venn.diagram(datalist,filename=NULL,col = "#222222",lty = 1, lwd = 1,fill = rainbow(length(datalist)),alpha = 0.40,cex = 1, fontfamily = "serif",fontface = "bold",cat.col = "black", cat.cex =1.3,cat.fontfamily = "serif",cat.default.pos = "outer", margin=0.12,cat.dist=rep(0.06,length(datalist)), col='transparent') picname = paste(outdir, '/', paste(names(datalist), collapse='--'), '_venn.png', sep='') png(picname, 540, 540) grid.draw(venn.plot) dev.off() } # check outdir otherwise create dir.create(args[1], showWarnings = FALSE) filenames = args[-c(1,2)] tmpList = File2List(filenames) if (args[2] == '1') { DrawVenn(tmpList, args[1]) outlist = InterItems(tmpList) WriteInter(outlist, args[1]) } else if (args[2] == '2') { outlist = Uniq_Comm(tmpList) WriteInter(outlist, args[1]) } <file_sep>#!/usr/bin/python import sys import svgwrite from svgwrite import cm,mm # Parse the blast output file by query id. Each query id is one setction. def query_section(infile): with open(infile) as handle: filelist = handle.readlines() section_dict = {} for fline in filelist: if fline.startswith('#') or not fline.strip(): continue tmplist = fline.split() query_id = tmplist[0] subject_id = tmplist[1] query_region = map(int,tmplist[6:8]) subject_region = map(int, tmplist[8:10]) if query_id not in section_dict: section_dict[query_id] = {subject_id:[(query_region, subject_region)]} else: if subject_id not in section_dict[query_id]: section_dict[query_id][subject_id] = [(query_region, subject_region)] else: section_dict[query_id][subject_id].append((query_region, subject_region)) print "Blast result was parsed." return section_dict # One subject one plot. def plot_subject(dwg, query_dict, subject_id, y): cbPalette = ["#999999", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7"] # add query id dwg.add(dwg.text(subject_id, insert=(0.2*cm, (y+0.5)*cm), style='font-size:12px; font-family:Arial')) query_max = max(reduce(lambda x,y : x+y, [pos[0] for pos in query_dict[subject_id]])) query_min = min(reduce(lambda x,y : x+y, [pos[0] for pos in query_dict[subject_id]])) subject_max = max(reduce(lambda x,y : x+y, [pos[1] for pos in query_dict[subject_id]])) subject_min = min(reduce(lambda x,y : x+y, [pos[1] for pos in query_dict[subject_id]])) if (subject_max - subject_min) > (query_max - query_min): scale = 16.0 / (subject_max - subject_min) else: scale = 16.0 / (query_max - query_min) print scale query_start = 2 + 8 - (query_max-query_min)/2 * scale query_end = 2 + 8 + (query_max-query_min)/2 * scale subject_start = 2 + 8 - (subject_max-subject_min)/2 * scale subject_end = 2 + 8 + (subject_max-subject_min)/2 * scale # Query line and subject line. print query_start,query_end,subject_start,subject_end dwg.add(dwg.line(start=(query_start * cm, (y+1)*cm), end=(query_end * cm, (y+1)*cm), stroke='black', stroke_width=1)) dwg.add(dwg.line(start=(subject_start * cm, (y+5)*cm), end=(subject_end * cm, (y+5)*cm), stroke='black', stroke_width=1)) for idx, match in enumerate(query_dict[subject_id]): qmatch = match[0] smatch = match[1] line1start = (qmatch[0] - query_min) * scale + query_start line1end = (smatch[0] - subject_min) * scale + subject_start line2start = (qmatch[1] - query_min) * scale + query_start line2end = (smatch[1] - subject_min) * scale + subject_start dwg.add(dwg.line(start=(line1start * cm, (y+1) *cm), end=(line1end * cm, (y+5) *cm), stroke=cbPalette[idx%8], stroke_width=0.5)) dwg.add(dwg.line(start=(line2start * cm, (y+1) *cm), end=(line2end * cm, (y+5) *cm), stroke=cbPalette[idx%8], stroke_width=0.5)) dwg.add(dwg.rect(insert=(line1start*cm, (y+1-(idx%2+1) *0.1)*cm), size=((line2start-line1start)*cm, 0.5*mm), fill=cbPalette[idx%8], stroke='white', stroke_width=0.5)) dwg.add(dwg.rect(insert=(min(line1end, line2end)*cm, (y+5+(idx%2+1)*0.1)*cm), size=((line2start-line1start)*cm, 0.5*mm), fill=cbPalette[idx%8], stroke='white', stroke_width=0.5)) return dwg # Main plot function def ploter(section_dict): if not section_dict: print "There is no result!" return None for query_id in section_dict: high = len(section_dict[query_id]) * 6 dwg = svgwrite.Drawing(filename=("%s.svg" % query_id), size=(18*cm, high *cm)) for y, subject_id in enumerate(section_dict[query_id].keys()): dwg = plot_subject(dwg, section_dict[query_id], subject_id, y*6) dwg.save() print 'OK!' if __name__ == '__main__': section_dict = query_section(sys.argv[1]) ploter(section_dict) <file_sep>#!/bin/python # 2014-11-4 Linxzh # retrive gene seq for genome seq by gene id import argparse from Bio import SeqIO parser = argparse.ArgumentParser(description='Retrive gene sequence by gene id', prog='SeqGeter', usage='PROG [options]') parser.add_argument('-i', help='file contains gene ids') parser.add_argument('-o', help='output file in fasta format', type=argparse.FileType('w')) parser.add_argument('-c', help='column of gene id, default is 1', type=int, default=1) parser.add_argument('-g', help="format gene id as 'Csa1G000111', default is FALSE'", default='F', choices=['T', 'F']) args = parser.parse_args() def pos_dict(infile): D={} with open(infile) as f: for fl in f: if 'gene' in fl: fl_list = fl.split() chrom = fl_list[0] geneid = fl_list[8].split(';')[0][3:] start = int(fl_list[3]) - 1 end = int(fl_list[4]) D[geneid] = [chrom, start, end] return D def read_id(infile, c=1, g='F'): gene_list = [] with open(infile) as f: for fl in f: if '#' in fl: continue elif 'Csa' not in fl: continue elif fl == '\n': continue fl_list = fl.split() gene = fl_list[c-1] if g == 'T': gene = gene.split('.')[0] gene = gene.replace('P','G') gene = gene.replace('M','G') gene_list.append(gene) return gene_list def get_seq(gene_list, outfile): D = pos_dict('/share/fg3/Linxzh/Data/Cucumber_ref/Cucumber_20101104.gff3') fa_dict = SeqIO.to_dict(SeqIO.parse('/share/fg3/Linxzh/Data/Cucumber_ref/whole_genome/origin/domestic_Chr_20101102.fa','fasta')) for gene in gene_list: seq = str(fa_dict[D[gene][0]][D[gene][1]:D[gene][2]].seq) wl = '>%s\n%s\n' % (gene, seq) outfile.write(wl) outfile.close() if __name__ == '__main__': gene_list = read_id(args.i, c = args.c, g = args.g) get_seq(gene_list, args.o) <file_sep>#!/bin/env python # linxzh 2015-12-10 import sys # home: 1/1, 0/0, hete: 0/1 type_dict = {"1/1":1, "0/0":0, "0/1":-1} def CalRate(inlist): miss = inlist.count(0) home = inlist.count(1) hete = inlist.count(-1) all = float(len(inlist)) return "%s\t%s\t%.2f%%\t%s\t%.2f%%\t%s\t%.2f%%\n" % (home + hete, home, home/all*100, hete, hete/all*100, miss, miss/all*100) def PopSNP(infile, sampleNum): snp_dict = dict((k,[]) for k in range(1,sampleNum + 1)) for i in open(infile): if i.startswith('#'): continue tmplist = i.strip().split('\t')[9:] tmptype = [type_dict[x.split(':')[0]] for x in tmplist] for m,n in enumerate(tmptype): snp_dict[m+1].append(n) return snp_dict if __name__ == "__main__": if len(sys.argv) != 4: print 'python script.py in.vcf sampleNum outputfile' sys.exit(0) snp_dict = PopSNP(sys.argv[1],int(sys.argv[2])) out = ['Sample\tAll\tHome\tHome-rate\tHete\tHete-rate\tMiss\tMiss-rate\n'] for k in snp_dict: ratio = CalRate(snp_dict[k]) out.append('%s\t%s' % (k, ratio)) with open(sys.argv[3], 'w') as handle: handle.writelines(out) <file_sep>#!/bin/env python # linxzh 2015012-2 # import os import sys from Bio import SeqIO if len(sys.argv) != 4: print "USAGE: python split.py origin.fa outdir sequenceNum" sys.exit(0) if not os.path.exists(sys.argv[2]): os.mkdir(sys.argv[2]) fa_dict = SeqIO.to_dict(SeqIO.parse(sys.argv[1], 'fasta')) step = int(sys.argv[3]) print step unigenes = fa_dict.keys() print len(unigenes) n = 0 for i in range(0,len(unigenes), step): genes = unigenes[i:i+step] recs = [fa_dict[j] for j in genes] outfasta = '%s/unigenes_%s.fa' % (sys.argv[2], i) SeqIO.write(recs, outfasta,'fasta') n += 1 print n <file_sep>args = commandArgs(T) infile = args[1] title = sprintf("Gene Expression between %s and %s", args[2],args[3]) pdffile = sprintf("%s_vs_%s.cor.pdf", args[2],args[3]) pngfile = sprintf("%s_vs_%s.cor.png", args[2],args[3]) d <- read.table(infile, sep = "\t",stringsAsFactor=F,header=T) library(ggplot2) library(grid) print('loaded packages') colA = paste(args[2], '_FPKM', sep='') colB = paste(args[3], '_FPKM', sep='') print('col rename') print(names(d)) B <- cor(d[,colA], d[,colB], method = c("spearman")) C <- cor(d[,colA], d[,colB], method = c("pearson")) print('cor') linefit <-lm(d[,colA] ~ d[,colB]) B=round(B,4) C=round(C,4) linefit$coefficients[[2]]=sprintf("%.4f",linefit$coefficients[[2]]) print('darwing') #pdf(pdffile) p = ggplot(data = d, mapping = aes(x = log10(get(colA)), y = log10(get(colB)))) p1 = p + geom_point(colour="#B1639F",size=1) p2 = p1 + xlab(sprintf("log10($s)",colA))+ylab(sprintf("log10(%s)",colB)) + ggtitle(title) p3 = p2+ theme(axis.text=element_text(size=10),axis.title = element_text(size =13), plot.title=element_text(size=16),legend.title=element_text(size=14,face="plain"),legend.title.align=0,legend.key=element_blank(),legend.text=element_blank(),legend.position=c(0.18,0.92),legend.key.size=unit(0,"cm")) p4 = p3 + geom_text(data=NULL, x=-1, y=3.5,label=paste(paste(" slope k = ",linefit$coefficients[[2]],"\n"),paste("spearman r = ",B,"\n"),paste("pearson r = ",C)),size=3) p5 = p4 + stat_abline(colour="#A2A3A4",linetype="dashed",lw=0.6) ggsave(p5, file=pdffile) ggsave(p5, file=pngfile) #dev.off() #png(pngfile,600,600) #p = ggplot(data = d, mapping = aes(x = log10(get(colA)), y = log10(get(colB)))) #p1 = p + geom_point(colour="#B1639F",size=1) #p2 = p1 + xlab(sprintf("log10(%s)", colA)) + ylab(sprintf("log10(%s)", colB)) + ggtitle(title) #p3 = p2 + + theme(axis.text=element_text(size=10),axis.title = element_text(size =13), plot.title=element_text(size=16),legend.title=element_text(size=14,face="plain"),legend.title.align=0,legend.key=element_blank(),legend.text=element_blank(),legend.position=c(0.18,0.92),legend.key.size=unit(0,"cm")) #p4 = p3 + geom_text(data=NUll, x=-1, y=3.5,label=paste(paste(" slope k = ",linefit$coefficients[[2]],"\n"),paste("spearman r = ",B,"\n"),paste("pearson r = ",C)), size =3) #p5 = p4 + stat_abline(colour="#A2A3A4",linetype="dashed",lw=0.6) #dev.off() <file_sep>#!/usr/local/bin/python # 2014-12-2 Linxzh import argparse parser = argparse.ArgumentParser() parser.add_argument('-i', help='input file') parser.add_argument('-o', help='output file') parser.add_argument('-p', help='Positional file') parser.add_argument('-d', help='distance * kb', type=int, default=10000) parser.add_argument('-f', help='fliter the uncluster genes', type=str, default='True', choices=['True','False']) args = parser.parse_args() # read gene-id from module, args.i -- input file def read_gene(infile): '''input file format: moduleName1 Gene1 Gene2... moduleName2 GeneA GeneB...''' D = {} with open(infile) as f: fl = f.readlines() for i in range(0,len(fl),2): genes = [x for x in fl[i+1].split()] D[fl[i]] = genes return D # read gene--pos dictionary def read_pos(infile): posD = {} chrom_genes = {} with open(infile) as f: for line in f: lineList = line.split() posD[lineList[3]] = int(lineList[1]) if lineList[0] not in chrom_genes: chrom_genes[lineList[0]] = [lineList[3]] else: chrom_genes[lineList[0]].append(lineList[3]) return posD, chrom_genes # remove unclustered gene from the result line def remove_uncluster(outstring): outlist = outstring.split(' | ') outlist = [x for x in outlist if '-' in x] outstr = ' | '.join(outlist) return outstr # positional cluster def cluster(D, posD, chrom_genes, outfile, dist=10000, f='True'): '''D: input gene, {moduleName: gene1 gene2 ...} posD: {geneID: start pos}''' # cluster the gene with '-', sep by ' | ' def find_cluster(chrom_genes, posD, inputgenes): outList = [] for k in chrom_genes.keys(): geneList = chrom_genes[k] geneList = list(set(geneList).intersection(set(inputgenes))) geneList = sorted(geneList, key=lambda g:posD[g]) if not geneList: continue for i in range(len(geneList)-1): d = posD[geneList[i+1]] - posD[geneList[i]] if d <= dist : geneList[i] += '<->' else: geneList[i] += ' | ' newline = ''.join(geneList) if '-' in newline: # only need cluster genes if f == 'True': newline = remove_uncluster(newline) newline = k + '\t' + newline + '\n' outList.append(newline) return outList wl = [] for (m,l) in D.items(): outList = find_cluster(chrom_genes, posD, l) if outList: # fliter empty out list wl.append(m) # add module number wl += outList with open(outfile,'w') as f: print len(wl) f.writelines(wl) if __name__ == '__main__': D = read_gene(args.i) for sca in D: print sca, len(D[sca]) posD, chrom_genes = read_pos(args.p) cluster(D, posD, chrom_genes, args.o, args.d, args.f) <file_sep>#!/bin/bash # 2014-10-10 Linxzh AllNum=24274 SampleNum=`cat $1 | wc -l` # sample gene number item=`echo $1 | cut -d . -f 1` # generate the sample gene to ipr mapping file(*.map), $2 while read line do grep ${line/G/P}.1 /share/fg3/Linxzh/Tmp/ipr/gene2ipr.map >> ${item}.map done < $1 echo $item.map "Done" # all ipr ids mapping to sample genes(ipr to gene)(uni_ipr), $4 awk '{for (i=2;i<=NF;i++) {print $i}}' $item.map > tmp sort tmp | uniq > ${item}_uni_ipr.txt rm tmp echo ${item}_uni_ipr.txt "Done" # count the frequency of occurrence of each ipr id, $3 while read line do IprNum=`grep $line /share/fg3/Linxzh/Data/Annotation/domestic.ipr.txt | wc -l` IprSamNum=`grep $line $item.map | wc -l` printf $line"\t"${AllNum}"\t"${IprNum}"\t"${SampleNum}"\t"${IprSamNum}"\n" >> tmp3 grep $line /share/fg3/Linxzh/Data/Annotation/domestic_ipr_seperate_id.txt >> tmp2 done < ${item}_uni_ipr.txt paste tmp3 tmp2 > ${item}_num.txt rm tmp3 tmp2 echo ${item}_num.txt "Done" <file_sep>#!/usr/bin/python import sys from Bio import Entrez # get gene id list with open(sys.argv[1]) as handle: idlist = handle.readlines() idlist = [x.strip() for x in idlist] Entrez.email = '<EMAIL>' fas = [] for i in idlist: handle = Entrez.esearch(db='nucleotide', term=i) rec = Entrez.read(handle) fetchid = rec['IdList'] print i, rec['Count'] if len(fetchid) == 1: fetchid = [fetchid] for rid in fetchid: handle = Entrez.efetch(db='nucleotide', id=rid, rettype='fasta') fa = handle.read() fas.append(fa) with open(sys.argv[2], 'w') as handle: handle.writelines(fas) <file_sep>#!/bin/env python # 2014-3-18 created by Linxzh # SNP mutation detection from Bio import SeqIO from Bio.Alphabet import IUPAC from Bio.Seq import MutableSeq # handle the record id def get_accession(record): parts = record.id.split() return parts[0] # converse the gff file into a dict def Gff_dict(infile): D = {} for x in infile: if 'Scaffold' in x: continue elif 'gene' in x: xlist = x.split() gid = xlist[8].split('=')[1][:-1] key = xlist[0] + '-' + gid value = [int(xlist[3]),int(xlist[4]),xlist[6], gid] D[key] = value return D # find the sym def Mutant(chrom,start, end, strand, base, pos,fa_dict,snp): '''we need to read the corresponding gene location by SNP position in the GFF file''' if strand == '+': step = (pos - start)/3 p = (pos - start)% 3 code = fa_dict[chrom][start-1+3*step:start-1+3*(1+step)] asnp_code = bsnp_code = code.seq.tostring() asnp_code = asnp_code[1:p] + base + asnp_code[1+p:] ap = asnp_code.toseq().translate().to bsnp_code[p] = snp bp = asnp_code.toseq().translate().tostring() elif strand == '-': step = (end -pos)/3 code = fa_dict[chrom][end-3*(1+step):end-3*step] p = (end-pos)%3 asnp_code = bsnp_code = code.seq.tomutable() bsnp_code[2-p]=snp asnp_code[2-p]=base ap = asnp_code.reverse_complement().toseq().translate().tostring() bp = bsnp_code.reverse_complement().toseq().translate().tostring() print asnp_code,bsnp_code,base,snp,p if ap == bp: sym = 'yes' else: sym = 'no' wl = '%s%s%s\t%s%s%s\t%s\n' % (asnp_code,chr(26),bsnp_code,ap,chr(26),bp,sym) return wl def SNP_in_GID(gffdict, infile, outfile): cucu_fa = SeqIO.to_dict(SeqIO.parse(\ '/share/fg3/Linxzh/Data/Cucumber_ref/domestic_Chr_20101102.fa',\ 'fasta'),key_function=get_accession) for x in infile: if '#' in x: wl = '%s\t%s\t%s\t%s\t%s\t%s\n' % (x[:-1],'start','end','pos',\ 'strand','gid') outfile.write(wl) continue xlist = x.split() pos = int(xlist[1]) chrom = xlist[0] base = xlist[2] snp = xlist[3] for k in gffdict: if xlist[0] in k: start = gffdict[k][0] end = gffdict[k][1] strand = gffdict[k][2] if pos >= start and pos <= end: mut_line = Mutant(chrom,start,end,strand,base,pos,cucu_fa,snp) wl = '%s\t%s\t%s\t%s\t%s\t%s\t%s' % (x[:-1],start,end,\ pos,strand,gffdict[k][3],mut_line) outfile.write(wl) if __name__ == '__main__': gfffile = open('/share/fg3/Linxzh/Data/Cucumber_ref/Cucumber_20101104.gff3') snpfile = open('rare_snp.txt') outfile = open('tmp_file.txt','w') gffdict = Gff_dict(gfffile) SNP_in_GID(gffdict, snpfile, outfile) outfile.close() snpfile.close() <file_sep>#!/usr/bin/python import sys with open(sys.argv[1]) as handle: lines = handle.readlines() outlines = ['\t'.join(x.split('\t')[:3])+'\n' for x in lines[:3]] outlines.append(lines[3]) # total mapped reads def combine(line): l = line.strip().split('\t') reads = (int(l[1]) + int(l[4]) + int(l[7])) pers = (float(l[2][:-1]) + float(l[5][:-1]) + float(l[8][:-1])) return (reads, pers) line5 = 'Total Mapped Reads\t%s\t%s%%\n' % combine(lines[4]) outlines.append(line5) outlines.append('\n') line7 = 'perfect match\t%s\t%s%%\n' % combine(lines[6]) outlines.append(line7) line8 = '<=5bp mismatch\t%s\t%s%%\n' % combine(lines[7]) outlines.append(line8) outlines.append('\n') line10 = 'unique match\t%s\t%s%%\n' % combine(lines[9]) line11 = 'multi-position match\t%s\t%s%%\n' % combine(lines[10]) outlines.append(line10) outlines.append(line11) outlines.append('\n') line13 = 'Total Unmapped Reads\t%s\t%s%%\n' % combine(lines[12]) outlines.append(line13) with open(sys.argv[2], 'w') as handle: handle.writelines(outlines) <file_sep># coding: utf-8 # 每个循环只提交一个序列,每个序列产生一个HTML文件,再从HTML结果中 # 整理得到结果 import urllib2 import re import os import argparse from poster.encode import multipart_encode from poster.streaminghttp import register_openers parser = argparse.ArgumentParser() parser.add_argument('-fa', help='promoter seq file', type=argparse.FileType='r') parser.add_argument('-outdir', help='output dir', type=str, default='htmlresult') args = parser.parse_args() def upload_analysis(fa, outdir): os.path.exists(outdir) and pass or os.mkdir(outdir) register_openers() f = openfa.readlines() # sepline = '____________________________________________________________________________' url = 'https://sogo.dna.affrc.go.jp/cgi-bin/sogo.cgi?sid=&lang=en&pj=640&action=page&page=newplace' for i in range(0, len(f), 2): query_id = f[i] result_html = '%s/%s.html' % (outdir, query_id) data = {'query_seq':'\n'.join(f[i:i+2]), 'action':'newplace', 'sid':'', 'pj':'640',"style":'html'} datagen, header = multipart_encode(data) request = urllib2.Request(url, datagen, header) htmltext = urllib2.urlopen(request).read() # write analysis result in html with open(result_html) as handle: handle.write(htmltext) # htmllines = htmltext.split('\n') # targetlines = htmllines[htmllines.index(sepline)+1:-6] if __name__ == '__main__': upload_analysis(args.fa, args.outdir) <file_sep>#!/usr/bin/python # created by linxzh 2015 10-22 # filter output result of genotype of stacks workflow import sys def similarity(s, l1, l2, simi=0.99): thresh_num = int((len(l1) -s) * (1-simi) + 1) n = 0 for a1,b1 in zip(l1,l2): if a1 != b1: n += 1 if n >= thresh_num: return False break return True if __name__ == '__main__': if len(sys.argv) != 4: print "USAGE: python script.py inputfile outfile similarity(float)" sys.exit(0) with open(sys.argv[1]) as handle: filelist = handle.readlines() start_col = 2 tmplist = [filelist[0].strip().split('\t')] out = [] n = len(filelist) for i in range(n): flag = 1 for j in range(i+1,n): if similarity(start_col, filelist[i], filelist[j], float(sys.argv[3])): flag = 0 break if flag: out.append(filelist[i]) # print len(out) with open(sys.argv[2], 'w') as handle: handle.writelines(out) <file_sep>#! /usr/bin/python #! linxingxhong 201606028 # Retrive prptein sequences from StringDB by specie id. import sys try: from Bio import SeqIO except ImportError: print "Please run the command below:" print "source /nfs3/onegene/user/group1/linxingzhong/workspace/bio2.7.10/bin/activate" print "Or you can install biopython by yourself." sys.exit(0) def faGet(infile, num): prefix = num + '.' fa = SeqIO.parse(infile,'fasta') out = [f for f in fa if f.id.startswith(prefix)] return out if __name__=='__main__': spe_id = sys.argv[1] stringdb = sys.argv[2] specieFa = sys.argv[3] rec = faGet(stringdb, spe_id) SeqIO.write(rec, specieFa, 'fasta') <file_sep>import sys from Bio import Entrez Entrez.email = '<EMAIL>' handle = Entrez.esearch(db='nucest', term='Oryza sativa indica', usehistory='y') search_result = Entrez.read(handle) count = search_result['Count'] batch_size = 500 webenv = search_result["WebEnv"] query_key = search_result["QueryKey"] out_handle = open('test.fa','w') for start in range(0, count, batch_size): end = min(start+batch_size, count) print "Going to download record %i to %i" % (start+1, end) fetch_handle = Entrez.efetch(db="nucest", rettype="fasta", retmode="text", retstart=start, retmax=batch_size, webenv=webenv, query_key=query_key) data = fetch_handle.read() fetch_handle.close() out_handle.write(data) out_handle.close() <file_sep>#!/usr/bin/python # 2015-9-18, created by Linxzh import sys import svgwrite from svgwrite import cm, mm from math import log #global W = 18; H=15; SAMPLE_STEP=2 def marker_trans(marker): ''' ['TTG','CCA','CCG','CTG'] => ['TCCC','TCCT','GAGG'] ''' f = lambda x, y: [ ''.join(i) for i in zip(x, y) ] marker_t = reduce(f, marker) return marker_t def read_data(infile): ''' transcform input data into a dict: {blockid:{pos1:markers1,pos2:markers2, ..., 'frequency':(f1,f2,...)}, ...} ''' D = {} marker = []; freq = [] i = 0 with open(infile) as handle: for f in handle: if f.startswith('BLOCK'): if marker: marker_t = marker_trans(marker) D[i] = dict(zip(pos, marker_t)) D[i]['frequency'] = freq marker = []; freq = [] pos = [int(x) for x in f.split()[3:]] i += 1 elif f.startswith('Multiallelic'): continue else: flist = f.split() marker.append(flist[0]) freq.append(float(flist[1][1:-1])) marker_t = marker_trans(marker) D[i] = dict(zip(pos, marker_t)) D[i]['frequency'] = freq return D # read gene positions information def read_gene(geneinfo): '''return dict {chrom:{gene1:[start, end], ...}, ...}''' gene_dict = {} with open(geneinfo) as handle: for f in handle: flist = f.split() if flist[0] not in gene_dict: gene_dict[flist[0]] = {flist[1]:[int(flist[2]), int(flist[3])]} else: gene_dict[flist[0]][flist[1]] = [int(flist[2]), int(flist[3])] return gene_dict # draw block def draw_block(dwg, D, Allpos, distlog, ministep, y, barsize = 0.5): y1 = y y2 = y + 0.5 step_list = [1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1] # draw rect region from 2 ~ 16 dwg.add(dwg.line(start=(2*cm, y1*cm), end=(16*cm,y1*cm), stroke='black', stroke_width=0.25)) dwg.add(dwg.line(start=(2*cm, y2*cm), end=(16*cm,y2*cm), stroke='black', stroke_width=0.25)) # dwg.add(dwg.rect(insert=(2 * cm, y1 * cm), size=(14 * cm, 0.5 * cm), # fill='none', stroke='black', stroke_width=0.5)) # draw y-xaxis from 0 ~ 1 indicate grequence dwg.add(dwg.line(start=(1.975*cm, y1*cm), end=(1.975*cm,(y1-1)*cm), stroke='black', stroke_width=0.5)) # ticks for y-axis, 0.25,0.5,0.75 dwg.add(dwg.text('Frequency', insert=(0.9*cm, (y1-1.1)*cm),style="font-size:6px; font-family:Arial")) for t in (0,0.25,0.5,0.75,1): dwg.add(dwg.line(start=(1.95*cm, (y1-t)*cm), end=(1.975*cm,(y1-t)*cm), stroke='black', stroke_width=0.5)) dwg.add(dwg.text(str(t), insert=(1.75*cm, (y1-t)*cm),style="font-size:3px; font-family:Arial")) # draw blocks and marker from here # blocks = D.keys() for block in D.keys(): # block id is int pos_and_freq_dict = D[block] pos = pos_and_freq_dict.keys() pos.remove('frequency') frequency = D[block]['frequency'] maxidx = Allpos.index(max(pos)) minidx = Allpos.index(min(pos)) if minidx == 0: blockposX = [2, 2 + ((maxidx + sum(distlog[:maxidx - 1]))) * ministep] else: blockposX = [2 + (maxidx + sum(distlog[:maxidx - 1])) * ministep, 2+ (minidx + sum(distlog[:minidx - 1])) * ministep] step_index = block % 17 dwg.add(dwg.line(start=(blockposX[0]*cm, (step_list[step_index]* 0.05 + y1)*cm), end=(blockposX[1]*cm, (step_list[step_index]* 0.05 + y1)*cm), stroke="grey", stroke_width=0.5)) for p in pos: if p in Allpos: idx = Allpos.index(p) if idx == 0: x1 = 2 else: x1 = 2 + (idx + sum(distlog[:idx - 1])) * ministep common_marker = max(set(list(pos_and_freq_dict[p])), key=list(pos_and_freq_dict[p]).count) for i, c in enumerate(pos_and_freq_dict[p]): if c == common_marker: c='#0a67a3' else: c = '#ff8e00' dwg.add(dwg.line(start=(x1 * cm, (y1 - frequency[i]-0.025) * cm), end=(x1 * cm, (y1 - frequency[i]+0.025) * cm), stroke=c, stroke_width=barsize)) # dwg.add(dwg.circle(center=(x1 * cm, (y1 - frequency[i]) * cm), r=0.025*cm, fill=c)) return dwg # def filter_pos(D, r): keys = D.keys() for k in keys: Max = max(D[k]) Min = min(D[k]) if Max < r[0] or Min > r[1]: del D[k] return D def subdict_keys(D): keys = [] for i in D: keys += D[i].keys() return keys # read sample info from file def read_sample(sampleinfo): out = {} with open(sampleinfo) as handle: filelist = handle.readlines() positions = filelist[0].split(':') region = [positions[0], int(positions[1]), int(positions[2])] for l in filelist[1:]: names = l.split() if len(names) >1: out[names[0]] = filter_pos(read_data(names[1]), region[1:]) else: out[names[0]] = {} return out, region # draw gene region def draw_gene(chrome, Allpos, distlog, gene_dict, sample_data, dwg, ministep): samples = sorted(sample_data.keys()) samples_step = [samples.index(x) for x in samples if sample_data[x]] genes = gene_dict[chrome] def get_xaxis(pos, Allpos, ministep): if pos <= min(Allpos): pos = 2 elif pos >= max(Allpos): pos = 16 else: newpos = sorted(set(Allpos+ [pos])) pos = (2 + (newpos.index(pos)-1 + sum(distlog[:(newpos.index(pos) - 2)])) + log(pos-newpos[newpos.index(pos)-1],10)) * ministep return pos for g in genes: x_axis = [get_xaxis(genes[g][0], Allpos, ministep), get_xaxis(genes[g][1], Allpos, ministep)] print g, x_axis tmpcolor = {0:'red',1:'blue'} for i in samples_step: dwg.add(dwg.line(start=(x_axis[0]*cm, (2.5+2*i)*cm), end=(x_axis[1]*cm, (2.5+2*i)*cm), stroke=tmpcolor[genes.keys().index(g)%2], stroke_width=1)) dwg.add(dwg.text(g, insert=((sum(x_axis)/2)*cm, (2.7+2*i)*cm), style="font-size:8px; font-family:Arial; font-style:italic")) return dwg if __name__ == '__main__': sample_data, region = read_sample(sys.argv[1]) dwg = svgwrite.Drawing(filename=sys.argv[3], size=(18 * cm, 15 * cm)) if len(sample_data) > 1: Allpos = sorted(reduce(lambda x,y : set(x) | set(subdict_keys(y)), sample_data.values()[1:], subdict_keys(sample_data.values()[0]))) else: Allpos = sorted(set(subdict_keys(sample_data.values()[0]))) # print Allpos Allpos.remove('frequency') # remove frequency item for calc print "Number of markers:%s, min:%s, max:%s\n" % (len(Allpos), min(Allpos), max(Allpos)) dwg.add(dwg.text('%s:%s-%s, distance between blocks is converted in log10' % (region[0], min(Allpos), max(Allpos)), insert=(0.1*cm, 13.5*cm), style="font-size:8px; font-family:Arial")) distlog = map(lambda x: log(Allpos[x + 1] - Allpos[x], 10), range(len(Allpos) - 1)) ministep = round(14.0 / (int(sum(distlog)) + len(Allpos)), 6) if len(Allpos) > 10000: barsize = 0.5 elif len(Allpos) > 5000: barsize = 1 else: barsize = 2 for i,j in enumerate(sorted(sample_data.keys())): print '%s, BLOCKS: %s' % (j, len(sample_data[j])) # add empty chromosome if sample_data[j]: dwg = draw_block(dwg, sample_data[j], Allpos, distlog, ministep, 2+i*2, barsize) else: dwg.add(dwg.rect(insert=(2 * cm, (2+i*2) * cm), size=(14 * cm, 0.5 * cm), fill='none', stroke='black', stroke_width=0.5)) dwg.add(dwg.text(j, insert=(0.5*cm, (2.25+i*2)*cm), style="font-size:8px")) # add gene positions here gene_dict = read_gene(sys.argv[2]) dwg = draw_gene(region[0], Allpos, distlog, gene_dict, sample_data, dwg, ministep) dwg.save() <file_sep>library(WGCNA) options(stringsAsFactors=F) args = commandArgs(T) if (length(args) != 3) { print("USAGE: Rscript wgcna3.r datExpr.RData dynamic_merged_networkdata.RData dissTOM.RData") quit(save='no') } #load("datExpr.RData") #load("dynamic_merged_networkdata.RData") #load('dissTOM.RData') load(args[1]) load(args[2]) load(args[3]) TOM = 1 - dissTOM dir.create('moduleGenes', showWarnings = FALSE) colors = names(table(moduleColors)) data = t(datExpr) genes = colnames(datExpr) # Module Membership(Kme) and Module Membership p-value dir.create('moduleMembership', showWarnings = FALSE) geneModuleMembership = as.data.frame(cor(datExpr, MEs, use="p")) MMpvalue = as.data.frame(corPvalueStudent(as.matrix(geneModuleMembership), dim(datExpr)[1])) write.table(geneModuleMembership, file='moduleMembership/All_ModuleMembership.xls',quote=F, sep='\t', col.names=NA) write.table(MMpvalue, file='moduleMembership/All_ModuleMembershipPvalue.xls',quote=F, sep='\t', col.names=NA) # output data for (c in colors) { if (c == 'grey'){ next } selected = moduleColors == c tmpdata = data[selected,] outfilename = paste('moduleGenes/', c,'.xls', sep='') write.table(file=outfilename, tmpdata, quote=F, sep='\t',col.names=NA) modGenes = genes[selected] modTOM = TOM[selected,selected] dimnames(modTOM) = list(modGenes, modGenes) exportNetworkToCytoscape(modTOM, edgeFile = paste("moduleGenes/cyt-edge_", c, ".txt", sep=""), nodeFile = paste("moduleGenes/cyt-nodes-", c, ".txt", sep=""), weighted = TRUE, threshold = 0.02, nodeNames = modGenes, altNodeNames = modGenes, nodeAttr = moduleColors[selected]) tmpMM = paste('moduleMembership/', c,'_MM.xls', sep='') tmpMMp = paste('moduleMembership/', c,'_MMp.xls', sep='') write.table(geneModuleMembership[selected,], file=tmpMM, quote=F, sep='\t', col.names=NA) write.table(MMpvalue[selected,], file=tmpMMp, quote=F, sep='\t', col.names=NA) } <file_sep>#!/usr/bin/env python # <EMAIL> 2016-8-17 # Create network graph for ppi result. import sys import networkx as nx import matplotlib.pyplot as plt def readPPI(ppi): ''' Read protein to protein interaction file, then convert to a list: [[ppa, ppb], [ppa,ppc], ...] ''' with open(ppi) as handle: links = handle.readlines()[1:] # exclude header line links = [x.split() for x in links] return links def getNodes(links): ''' Get unique nodes from links, remove duplicates. ''' return list(set(reduce(lambda a,b : a+b, links))) def readFC(nodeattr): with open(nodeattr) as handle: attributes = handle.readlines() attributes = [x.strip().split('\t') for x in attributes if (not x.startswith('#')) and (not x.startswith('GeneID'))] return dict([(x[0],x[1]) for x in attributes]) if __name__ == "__main__": links = readPPI(sys.argv[1]) nodes = getNodes(links) G = nx.Graph() G.add_nodes_from(nodes) G.add_edges_from(links) plt.figure(figsize=(10,10)) plt.axis('off') pos = nx.fruchterman_reingold_layout(G) nx.draw_networkx_nodes(G, pos) nx.draw_networkx_edges(G, pos, alpha=0.4) nx.draw_networkx_labels(G, pos, font_size=10, font_family='sans-serif') plt.savefig(sys.argv[2]) <file_sep>#!/usr/bin/python import sys from Bio import Entrez # get gene id list with open(sys.argv[1]) as handle: idlist = handle.readlines() idlist = [x.strip().split('\t') for x in idlist] Entrez.email = '<EMAIL>' out = open(sys.argv[2],'a') for i in idlist: # term = "(%s[Protein Name]) AND %s[Organism]" % (i[0], i[1]) term = "((%s[Gene Name]) OR %s[Properties]) AND %s[Organism]" % ((i[0], i[0], i[1])) handle = Entrez.esearch(db='protein', term=term, usehistory='y') rec = Entrez.read(handle) webenv = rec["WebEnv"] query_key = rec["QueryKey"] if len(rec['IdList']) == 0: print "%s\t%s missing." % (i[0], i[1]) continue handle = Entrez.efetch(db='protein', rettype='fasta', retmode='text', retstart=0, retmax=int(rec['Count']), webenv=webenv, query_key=query_key) fa = handle.read() print "%s\t%s, %s sequences downloaded." % (i[0], rec['Count'], i[1]) out.write(fa) out.close() <file_sep>#!/usr/bin/env python import math import sys from scipy.stats import chisquare if len(sys.argv) != 6: print "USAGE: python script.py input.loc summary.txt output.txt ProSampleNum chi_pvalue" sys.exit(0) def chi_test(alist, tlist, pvalue): chi_values = {'0.05':[3.84,5.99], '0.01': [6.63,9.21], '0.005':[7.88,10.6], '0.1':[2.71,4.61], '0.25':[1.32,2.77]} if len(alist) == 2: f = lambda i : pow((abs(float(alist[i])-tlist[i])-0.5),2) / tlist[i] chi = f(0) + f(1) if chi >= chi_values[pvalue][0]: s = 'sig' else: s = 'No sig' return chi, 1, s else: f = lambda i : pow((float(alist[i])-tlist[i]),2) / tlist[i] chi = sum([f(j) for j in range(len(alist))]) if chi >= chi_values[pvalue][1]: s = 'sig' else: s = 'No sig' return chi, 2, s def sci_chi(alist, tlist, pvalue): pvalue = float(pvalue) chi_result = chisquare(alist, f_exp=tlist) if chi_result[1] < pvalue: s='sig' else: s='No sig' return chi_result[0], chi_result[1], s def segregation(seg, sampleNum): seg = seg.split('x') sega = seg[0][1:] segb = seg[1][:-1] seglist = [''.join(sorted(i + j)) for i in sega for j in segb] segfeq = [float(seglist.count(i))/len(seglist) * sampleNum for i in set(seglist)] return set(seglist), segfeq if __name__ == '__main__': sample_num = int(sys.argv[4]) with open(sys.argv[1]) as handle: fl = handle.readlines() out = [] filtered = [] for f in fl: flist = f.strip().split() marker = flist[0] seg = flist[1] # filter pure parent if len(set(seg)) > 4: seglist, segfeq = segregation(seg, sample_num-flist[2:].count('--')) # sort genotype letters prolist = [''.join(sorted(x)) for x in flist[2:]] afeq = [prolist.count(i) for i in seglist] chi, df, sig = sci_chi(afeq, segfeq, sys.argv[5]) if sig == 'No sig': f = '\t'.join((marker,seg,'\t'.join(prolist),'\n')) filtered.append(f) out.append('%s\t%5g\t%s\t%s\t%s\t%s\n' % (marker, chi, df, str(afeq), str(segfeq), sig)) with open(sys.argv[2], 'w') as handle: handle.writelines(out) with open(sys.argv[3], 'w') as handle: handle.writelines(filtered) <file_sep>#!/bin/env python # 2014-12-14 Linxzh import argparse import re import sys parse = argparse.ArgumentParser() parse.add_argument('-i', type=argparse.FileType('r'), help='input file') #parse.add_argument('-o', type=argparse.FileType('w'), help='output file') args = parse.parse_args() def motif_genes(infile): fl = infile.readlines() head = 85 * '_' + '\n' tail = 43 * '-' + '\n' try: start = fl.index(head) end = fl.index(tail) except ValueError: print infile sys.exit() pattern = re.compile(r'Csa([0-9]|UN)M[0-9]+') startLine = fl.index(head) + 1 endLine = fl.index(tail) - 3 for x in fl[:startLine]: out = pattern.search(x) if out: gene = out.group() motifList = [] for i in fl[startLine:endLine]: il = i.split() motif = il[4] motifList.append(motif) motifList = list(set(motifList)) wl = '%s\t%s\n' % (gene,','.join(motifList)) return wl if __name__ == '__main__': outList = motif_genes(args.i) print outList <file_sep>#!/usr/bin/env python # <EMAIL>, created at 2016-2-17 import sys INTER_DIS = 1000 # set default snp inter-distance as 1kb def file2dict(filein): with open(filein) as handle: d = dict([(f.split('\t')[0], f) for f in handle]) return d def chr_dict(d): """ Input dictionary generated by file2dict to make a new dict: chromosome as key name, positions as value list. """ new_dict = {} for k in d: chromosome, pos = tuple(k.split('_')) if chromosome in new_dict: new_dict[chromosome].append(int(pos)) else: new_dict[chromosome] = [int(pos)] return new_dict def inter_distance(new_dict, intd=INTER_DIS): filtered_dict = {} for chromosome in new_dict: pos_list = new_dict[chromosome][:] pos_list.sort() if len(pos_list) == 1: # one snp in chromosome filtered_dict[chromosome] = pos_list else: tmplist = [pos_list[0]] pos_list.reverse() pos_list.pop() while pos_list: b_pos = pos_list.pop() a_pos = tmplist[-1] if abs(a_pos - b_pos) > intd: tmplist.append(b_pos) filtered_dict[chromosome] = tmplist return filtered_dict def num_control(filtered_dict, thresh): upstep = INTER_DIS / 2 downstep = 500 step = INTER_DIS / 2 inter_dis = INTER_DIS marker_counter = lambda x : sum(len(x[y]) for y in x) # def filter_circle(filtered_dict, upstep, downstep, inter_dis): # tmp_dict = inter_distance(filtered_dict, inter_dis) # marker_count = marker_counter(tmp_dict) # print upstep, downstep, inter_dis, marker_count # if abs(marker_count - thresh) <= 100: # return filtered_dict # elif marker_count - thresh > 100: # inter_dis = inter_dis + upstep # upstep = upstep + upstep # return filter_circle(filtered_dict, upstep, downstep, inter_dis) # elif marker_count - thresh < -100: # inter_dis = inter_dis - downstep # return filter_circle(filtered_dict, upstep, downstep, inter_dis) def filter_circle(filtered_dict, step, inter_dis): tmp_dict = inter_distance(filtered_dict, inter_dis) marker_count = marker_counter(tmp_dict) print upstep, inter_dis, marker_count if abs(marker_count - thresh) <= 100: return tmp_dict, inter_dis elif marker_count - thresh > 100: inter_dis = inter_dis + step step = step + INTER_DIS return filter_circle(filtered_dict, step, inter_dis) elif marker_count - thresh < -100: inter_dis = inter_dis - INTER_DIS/2 return filter_circle(filtered_dict, step, inter_dis) return filter_circle(filtered_dict, step, inter_dis) def get_value(d, final_dict): final_list = ['_'.join((y, str(x))) for y in final_dict for x in final_dict[y]] return [d[x] for x in final_list] if __name__ == "__main__": if len(sys.argv) != 3: print "USAGE: python script.py <input file> <marker number>" sys.exit(0) filein = sys.argv[1] d = file2dict(filein) new_dict = chr_dict(d) final_dict, inter_dis = num_control(new_dict, int(sys.argv[2])) # print sum(len(final_dict[y]) for y in final_dict) # print len(final_dict) final_list = get_value(d, final_dict) # print len(final_list) prefix = sys.argv[1].split('.')[0] outfile = "%s_D%s.txt" % (prefix, inter_dis) with open(outfile, 'w') as handle: handle.writelines(final_list) <file_sep>#!/bin/bash source /nfs3/onegene/user/group1/linxingzhong/workspace/bio2.7.10/bin/activate read -p "Please input chromosome number(int): " chrNum echo $chrNum for i in $(seq 1 ${chrNum}) do i=`printf "%02d" ${i}` printf "chr%s starts...\n" $i echo -e "chr${i}\tchr${i}\t1\t1000000000" >> region.txt echo -e "chr${i}:1:1000000000" >> chr${i}_sample.txt for j in $(ls *chr${i}.filter.block) do echo -e "${j%%.*}\t${j}" >> chr${i}_sample.txt done printf "chr%s drawing...\n" $i python /nfs3/onegene/user/group1/linxingzhong/scripts/bio/HapMap/draw.py chr${i}_sample.txt region.txt chr${i}.svg printf "chr%s done.\n" $i done deactivate <file_sep>library(WGCNA) options(stringsAsFactors = FALSE) enableWGCNAThreads() args = commandArgs(trailingOnly=TRUE) #***********************************step1 cluster Sample************************************* prefix = strsplit(args[1], '.', fixed=TRUE)[[1]][1] d=read.table(args[1],sep="\t",header=T,check.names=F, row.names=1) #d=d[1:10000,] datExpr = t(d) gsg = goodSamplesGenes(datExpr, verbose = 3) if (!gsg$allOK) { if (sum(!gsg$goodGenes)>0) printFlush(paste("Removing genes:", paste(names(datExpr)[!gsg$goodGenes], collapse = ", "))) if (sum(!gsg$goodSamples)>0) printFlush(paste("Removing samples:", paste(rownames(datExpr)[!gsg$goodSamples], collapse = ", "))) datExpr = datExpr[gsg$goodSamples, gsg$goodGenes] } #write.table(names(datExpr)[!gsg$goodGenes], file="removeGene.xls", row.names=FALSE, col.names=FALSE, quote=FALSE) #write.table(names(datExpr)[!gsg$goodSamples], file="removeSample.xls", row.names=FALSE, col.names=FALSE, quote=FALSE) sampleTree = hclust(dist(datExpr), method = "average") pdf(file = paste(prefix,"sampleClustering.pdf", sep='_'), width = 12, height = 9) par(cex = 0.6) par(mar = c(0,4,2,0)) plot(sampleTree, main = "Sample clustering", sub="", xlab="", cex.lab = 1.5, cex.axis = 1.5, cex.main = 2) dev.off() #***********************************step2 Choosing the soft threshold beta via scale free topology************************************* powers = c(c(1:10), seq(from = 12, to=20, by=2)) #sft = pickSoftThreshold(datExpr, powerVector = powers, verbose = 5) sft=pickSoftThreshold(datExpr,dataIsExpr = TRUE,powerVector = powers,corFnc = cor,corOptions = list(use = 'p'),networkType = "unsigned") pdf(file=paste(prefix,'pickSoftThreshold.pdf', sep='_'), wi=12, he=9) par(mfrow = c(1,2)) cex1 = 0.9 # Plot the results: par(mfrow = c(1, 2)) # SFT index as a function of different powers plot(sft$fitIndices[,1], -sign(sft$fitIndices[, 3])*sft$fitIndices[, 2], xlab = "Soft Threshold (power)", ylab = "Scale Free Topology Model Fit, signed R^2", type = "n", main = paste("Scale independence")) text(sft$fitIndices[, 1], -sign(sft$fitIndices[, 3]) * sft$fitIndices[, 2], labels = powers, col = "red") # this line corresponds to using an R^2 cut-off of h abline(h = 0.9, col = "red") # Mean connectivity as a function of different powers plot(sft$fitIndices[, 1], sft$fitIndices[, 5], type = "n", xlab = "Soft Threshold (power)", ylab = "Mean Connectivity", main = paste("Mean connectivity")) text(sft$fitIndices[, 1], sft$fitIndices[, 5], labels = powers, col = "red") dev.off() save(datExpr, file='datExpr.RData') <file_sep>#!/usr/bin/python # linxzh, create at 2015-9-16 # get feature sequence from genome according gff/gtf annotation file import argparse from Bio import SeqIO parser = argparse.ArgumentParser() parser.add_argument('-f', help='genome fasta file', type=str) parser.add_argument('-g', help='gff/gtf file', type=argparse.FileType('r')) parser.add_argument('-t', help='feature type, default is gene', default='gene', type=str) parser.add_argument('-o', help='output file in fasta', type=str) args = parser.parse_args() # read feature position from gff/gtf file def read_feature_pos(gff, feature): pos_dict = {} for f in gff: if f.startswith('#') or f.startswith('\n'): continue elif feature in f: fl = f.split() feature_id = fl[8].split(';')[1].split('=')[1] pos_dict[feature_id] = [fl[0], int(fl[3]), int(fl[4])] return pos_dict # retrieve feature sequence from genome def retrieve_seq(genome, pos_dict, outfasta): genome_dict = SeqIO.to_dict(SeqIO.parse(genome, 'fasta')) records = [] # f = lambda x : genome_dict[pos_dict[x][0]][pos_dict[x][1]-1:pos_dict[x][2]] for g in pos_dict: s = genome_dict[pos_dict[g][0]][pos_dict[g][1]-1:pos_dict[g][2]] s.id = g s.name = '' s.description = '' records.append(s) SeqIO.write(records, outfasta, 'fasta') if __name__ == '__main__': pos_dict = read_feature_pos(args.g, args.t) retrieve_seq(args.f, pos_dict, args.o) <file_sep>library(multtest) args = commandArgs(TRUE) infile = args[1] outfile = paste(sep='', strsplit(infile, '_', fixed=T)[[1]][1], "_IPRout.txt") D = read.delim(infile, sep='\t') n = seq(1:nrow(D)) fisher = rep('NA',nrow(D)) FDR = rep('NA',nrow(D)) for (i in n) { a = D[i,2] - D[i,3] b = D[i,3] c = D[i,4] - D[i,5] d =D[i,5] m = matrix(c(a,b,c,d),nrow=2) p = fisher.test(m)$p.value fisher[i] = p } res = mt.rawp2adjp(as.numeric(fisher),"BH") adjp = res$adjp[order(res$index), ] M = cbind(data.frame(adjp), D, all=T) colnames(M) = c('raw-p_value','FDR', 'IPR-id','Gene_num','Genes_in_ipr_num','Sample_gene_num','Sample_Genes_in_ipr_num','IPR_term') write.table(M,file=outfile, row.names=F,quote=F,sep='\t') <file_sep>#!/bin/bash #2013-12-2 Linxzh version:0.01 #work flow for call snps #you must build an index first #bwa index -a bwtsw reference.fa #short name ref=/share/fg1/Linxzh/Data/Mutant/Ref/domestic_Chr_20101102.fa #specify the working dicrectory by $3 cd $3 #$1 = 1.fq.gz, $2 = 2.fq.gz, SA coordinates bwa aln -t 3 $ref $1 > leftRead.sai bwa aln -t 3 $ref $2 > rightRead.sai #sam bwa sampe -f pair-end.sam $ref leftRead.sai rightRead.sai $1 $2 #sam to bam samtools view -bS pair-end.sam > pair-end.bam #sort samtools sort pair-end.bam pair-end.sorted #index samtools faidx $ref #rm duplication samtools rmdup -S pair-end.sorted.bam pair-end.sorted.rmdup.bam #index the bam samtools index pair-end.sorted.rmdup.bam #call snps samtools mpileup -u -f $ref pair-end.sorted.rmdup.bam | bcftools view -cg - > pair-end.raw.cg
89ef6e12398c7e41bfcd96aedf0192fc6820aed8
[ "Markdown", "Python", "R", "Shell" ]
65
Shell
Jun-NIBS/bio-analysis-kit
b92bb4f09f42ff74e3d955e5fdbebb107379f548
fa17d45c848e0445f0451e3ad3cbdcbf16dec4f3
refs/heads/master
<repo_name>daxxog/mustache-builder<file_sep>/README.md mustache-builder ================ mustache powered JavaScript building! Install ---------------- ```bash npm install https://github.com/daxxog/mustache-builder/tarball/master ``` stache --help ---------------- ``` mustache-builder v0.1.7 ==================================== _ Usage: stache {input-filename} _ stache {input-filename} --output {output-filename} == Output to {output-filename} instead of STDOUT _ stache -o == Same as stache --output _ stache -o --auto == Auto magic file name _ stache --tag == Scan for the tag directory for imports _ stache --test == Run the unit test _ stache --help == Display this page _ stache {input-filename} --nominify == Do not minify the output ``` TODO 0.1.8 ---------- Injections (maybe) code generators Parallel compile<file_sep>/lib/mustache-builder.js /* mustache-builder * mustache powered JavaScript building! * (c) 2012 David (daXXog) Volm ><> + + + <>< * Released under Apache License, Version 2.0: * http://www.apache.org/licenses/LICENSE-2.0.html */ var fs = require('fs'), //import filesystem path = require('path'), //import path tools mustache = require('mustache'), //import mustache UglifyJS = require('uglify-js2'); //import UglifyJS2 //fs.exists support for older node versions if(typeof fs.exists != 'function') { fs.exists = path.exists; } if(typeof fs.existsSync != 'function') { fs.existsSync = path.existsSync; } //the stache object, holds all our stachieness var stache = {}; //current tag directory depth stache.tagdepth = 0; stache.setvals = function() { //(re)set the default values (except tag depth) //script version stache.version = "0.1.7" ; //help file stache.help = "mustache-builder v" + stache.version +"\n"+ "====================================" +"\n_\n"+ "Usage: " +"\n"+ " stache {input-filename}" +"\n_\n"+ " stache {input-filename} --output {output-filename}" +"\n"+ " == Output to {output-filename} instead of STDOUT" +"\n_\n"+ " stache -o" +"\n"+ " == Same as stache --output" +"\n_\n"+ " stache -o --auto" +"\n"+ " == Auto magic file name" +"\n_\n"+ " stache --tag" +"\n"+ " == Scan for the tag directory for imports" +"\n_\n"+ " stache --test" +"\n"+ " == Run the unit test" +"\n_\n"+ " stache --help" +"\n"+ " == Display this page" +"\n_\n"+ " stache {input-filename} --nominify" +"\n"+ " == Do not minify the output" ; stache.didhelp = false; //flag that says we showed the help file //file that contains stache arguments stache.argvfn = './sta.che'; //flag that says we found the argument file and are using it stache.foundargvfile = false; //The JavaScript source code stache.src = ''; //the JavaScript source filename stache.js = false; //auto magic file name stache.autofn = ""; //use auto magic file name flag stache.useauto = false; //directory containing JavaScript files to be imported as tags stache.tagdir = './tags'; //tag imports in one string stache.tagstr = ''; //use tag imports falg stache.usetags = false; //mustache view rules {{flags}} stache.view = {}; //command line arg flags stache.test = false; stache.minify = true; //strings that hold compiled and minified versions of the JavaScript source stache.compiled = ''; stache.minified = ''; stache.fout = false; //the file name for output stache.out = ""; //the output stache._ = {}; //temp global space }; stache.setvals(); stache.save = function() { //function for storing (most of) the stache object as a string return JSON.stringify({ 'stache.didhelp' : stache.didhelp, 'stache.argvfn' : stache.argvfn, 'stache.foundargvfile' : stache.foundargvfile, 'stache.src' : stache.src, 'stache.js' : stache.js, 'stache.autofn' : stache.autofn, 'stache.useauto' : stache.useauto, 'stache.tagdir' : stache.tagdir, 'stache.tagstr' : stache.tagstr, 'stache.usetags' : stache.usetags, 'stache.view' : stache.view, 'stache.test' : stache.test, 'stache.minify' : stache.minify, 'stache.compiled' : stache.compiled, 'stache.minified' : stache.minified, 'stache.fout' : stache.fout, 'stache.out' : stache.out, 'stache._' : stache._ }); }; stache.load = function(str) { //function for restoring (most of) the stache object from a string var _stache = JSON.parse(str); stache.didhelp = _stache['stache.didhelp']; stache.argvfn = _stache['stache.argvfn']; stache.foundargvfile = _stache['stache.foundargvfile']; stache.src = _stache['stache.src']; stache.js = _stache['stache.js']; stache.autofn = _stache['stache.autofn']; stache.useauto = _stache['stache.useauto']; stache.tagdir = _stache['stache.tagdir']; stache.tagstr = _stache['stache.tagstr']; stache.usetags = _stache['stache.usetags']; stache.view = _stache['stache.view']; stache.test = _stache['stache.test']; stache.minify = _stache['stache.minify']; stache.compiled = _stache['stache.compiled']; stache.minified = _stache['stache.minified']; stache.fout = _stache['stache.fout']; stache.out = _stache['stache.out']; stache._ = _stache['stache._']; }; stache.runsafe = function(runme) { //run it global safe (NOT parallel safe) var _stache = stache.save(); //save what we were doing runme(); //run the code stache.load(_stache); //go back to what we were doing }; stache.log = function(str) { //stylized logging function console.log('stache: ' + str); }; stache.error = function(error) { //stylized logging function console.log('stache [ERROR]: ' + error); }; stache.argvloop = function(val, i, argv) { //argument loop if(!(i === 0 || i == 1)) { //if not the first or second argument and val is not undefined switch(val) { //try and find command line options case '--help': console.log(stache.help); //show the help file stache.didhelp = true; //flag that we showed the help file break; case '--test': stache.js = __dirname + '/test.js'; //set the input file to 'test.js' stache.test = true; //flag that we are testing break; case '--nominify': stache.minify = false; //flag that we don't want to minify output break; case '--output': //same as -o stache.fout = i + 1; //set fout to one step in the future break; case '-o': //same as --output stache.fout = i + 1; //set fout to one step in the future break; case '--tag': //use imported tags if(fs.existsSync(stache.tagdir)) { //check if the tag directory exists if(fs.existsSync(path.join(stache.tagdir, stache.argvfn))) { //check if the stache argument file exists in the tag directory stache.runsafe(function() { //run it global safe (NOT parallel safe) delete stache._; //reset values process.chdir(stache.tagdir); //change to the tag directory stache.tagdepth += 1; //add depth stache.log('running sub-process: '+stache.tagdepth); //say what depth we are on stache.setvals(); //reset to default values stache.argvloop('', 0, ['']); //run the sub process stache.tagdepth -= 1; //remove depth process.chdir('..'); //go back up the tag tree }); } fs.readdirSync(stache.tagdir).forEach(function(filename, i, array) { //scan the tags directory var tagDirFileName = path.join(stache.tagdir, filename); //join the tag directory and the current file if(!fs.lstatSync(tagDirFileName).isDirectory()) { //check if the file is not a directory var tag = filename.replace('.js', ''); //find the name of the tag stache.tagstr += '\n{{#' + tag + '}}\n' + fs.readFileSync(tagDirFileName, 'utf-8') + '\n{{/' + tag + '}}\n'; //append the tag to the tag string } }); stache.usetags = true; //flag that we are using imported tags } else { stache.log('WARN: using --tag but directory "'+stache.tagdir+'" does not exists!'); } break; default: //no command line options found, continue with other checks if(i === stache.fout) { //check if we need to set fout if(val == '--auto') { stache.useauto = true; //using auto magic file name } else { stache.fout = val; //set fout } } else if((function (filename) { //inline function to find file extension if(typeof filename != 'undefined') { var i = filename.lastIndexOf('.'); return (i < 0) ? '' : filename.substr(i+1); } else { return false; } }(val))=='js') { //if file extension == 'js' stache.js = val; //set the source name } else { stache.view[val] = true; //if all else fails, we must be passing a flag stache.autofn += '-' + val; //append flag to auto magic file name } break; } } if(i==argv.length-1) { //if we are at the end of the loop if(stache.js !== false) { //if the source name is set if(stache.useauto) { //if we are using auto magic file names stache.fout = stache.js.replace('.js', stache.autofn + (stache.minify ? '.min' : '') + '.js'); //make the magic happen } stache.src = fs.existsSync(stache.js) ? fs.readFileSync(stache.js, 'utf-8') : ''; //read the stache.js source code, blank if it does not exist if(stache.usetags) { //if we are importing tagsg stache.src = stache.tagstr + stache.src; //combine the tags + stache.js source code } stache.compiled = mustache.render(stache.src, stache.view); //compile using mustache if(stache.minify === true) { //if we want it minified stache.minified = UglifyJS.minify(stache.compiled, {fromString: true}).code; //minify using UglifyJS2 stache.out = stache.minified; //output the minified version } if(stache.test) { //if we are testing eval(stache.minified); //evaluate the test } else if(stache.minify !== true) { //if we are not using the minified version stache.out = stache.compiled; //output the compiled version } if(stache.fout === false) { //if we are not sending output to a file if(stache.test === true) { //if we are testing stache.log(stache.out); //make it look pretty } else { console.log(stache.out); //send it to STDOUT } } else { fs.writeFileSync(stache.fout, stache.out, 'utf-8'); //write the output to a file stache.log(stache.fout + ' built'); //file output success! } } else if(!stache.didhelp) { //if no input files and did not show help if(fs.existsSync(stache.argvfn) && !stache.foundargvfile) { //if stache.argvfn exists and we haven't found the argument file fs.readFileSync(stache.argvfn, 'utf-8').split("\n").forEach(function(val, i, array) { //split the argument file into lines stache.runsafe(function() { //run it global safe (NOT parallel safe) stache._['process.argv'] = [process.argv[0], process.argv[1]]; //copy process.argv to temp global space val.split(" ").forEach(function(val, i, array) { //split each line by spaces stache._['process.argv'].push(val); //push arguments onto temp process.argv stack }); stache.foundargvfile = true; //prevent infinite loop when stache.argvfn is blank stache._['process.argv'].forEach(stache.argvloop); //run the argument loop on the temp process.argv delete stache._['process.argv']; //we are all done with the temp process.argv }); }); } else { stache.log('no input files specified, try --help'); } } } }; process.argv.forEach(stache.argvloop);
a544a4a1484f15abd163146f2b6ef55ded820b45
[ "Markdown", "JavaScript" ]
2
Markdown
daxxog/mustache-builder
11ba72ebcd127273f33b29b80e6a006cdff738d1
fa2bed76d8dec93705618cd3d1a48dcbc4bf19c5
refs/heads/master
<file_sep># Inventory-Service Projects Basic REST API (Sping Boot)<file_sep>package com.api.InventoryService.service; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.api.InventoryService.repositories.ProductRepository; import com.api.InventoryService.repositories.CategoryRepository; import com.api.InventoryService.entities.Product; import com.api.InventoryService.entities.Category; @Service public class InventoryService { @Autowired private ProductRepository productRepository; @Autowired private CategoryRepository categoryRepository; public List<Product> getAllProducts() { return productRepository.findAll(); } public List<Category> getAllCategorys() { return categoryRepository.findAll(); } public Optional<Product> getByIdProducts(int id) { return productRepository.findById(id); } } <file_sep>package com.api.InventoryService.repositories; import com.api.InventoryService.entities.Category; import org.springframework.data.jpa.repository.JpaRepository; public interface CategoryRepository extends JpaRepository<Category, Integer> { }
44eda3a2ae348fab936cbc8bce01e6504ee81259
[ "Markdown", "Java" ]
3
Markdown
teerasaknrt/Inventory-Service
51a898889fcdffd1cd31d555e55ef77684da66a8
779ab8fbe1ab18539f10243b2393ceb73bb86498
refs/heads/master
<file_sep>"""Generate a directory of GeoJSON files named after p-codes """ import sys, os, json, argparse parser = argparse.ArgumentParser() parser.add_argument( 'input', type=argparse.FileType('r'), metavar="geojson_file", nargs='?', default=sys.stdin, help="GeoJSON file containing the boundaries and p-codes." ) parser.add_argument( '-d', '--output-dir', default=".", metavar="dir", help="Root of the output directory." ) parser.add_argument( '-c', '--country', required=True, metavar="country_code", help="ISO 3166-1 alpha3 country code for the shapes." ) parser.add_argument( '-p', '--property', required=True, metavar="adm_prop", help="Property name for the ADM code in the GeoJSON." ) args = parser.parse_args() geodata = json.load(args.input) for feature in geodata['features']: if feature.get('type') == 'Feature': properties = feature.get('properties') adm_code = properties.get(args.property) print("Dumping {}".format(adm_code)) # FIXME - make codes safe path = '{}/{}/{}'.format(args.output_dir, args.country, adm_code) if not os.path.exists(path): os.makedirs(path) filename = '{}/shape.json'.format(path) with open(filename, 'w') as fp: json.dump(feature.get('geometry'), fp) <file_sep># p-coder Python script to generate a directory of shape files based on p-codes. Use this script together with the _shp2geojson_ tool from the [GDAL](http://www.gdal.org/) library to convert an ArcGIS shapefile to a directory of individual files that a browser-side script (or similar) can download on demand, from directories named after p-codes (geographical codes). Example: ``` shp2geojson myshapefile-shp.zip | python make-pcodes.py -c NPL -p REG_CODE -d /var/share/www/p-codes ``` The result will be a directory structure like this: /var/share/www/p-codes/NPL/ /var/share/www/p-codes/NPL/524 1/ /var/share/www/p-codes/NPL/524 1/shape.json A client simply needs to know how to construct the URL to download a GeoJSON boundary for a p-code, for use with [Leaflet](http://leafletjs.com/) or similar tools. # Usage ``` usage: make-pcodes.py [-h] [-d dir] -c country_code -p adm_prop [geojson_file] positional arguments: geojson_file GeoJSON file containing the boundaries and p-codes. optional arguments: -h, --help show this help message and exit -d dir, --output-dir dir Root of the output directory. -c country_code, --country country_code ISO 3166-1 alpha3 country code for the shapes. -p adm_prop, --property adm_prop Property name for the ADM code in the GeoJSON. ```
c422d239ea650f0563b66ab6ae7647b5864602aa
[ "Markdown", "Python" ]
2
Python
davidmegginson/p-coder
6b612e6a68deceddedf16fae4c498f9e138006d5
a3ecc64add43afd6ba91e19bb06853dc215fcebc
refs/heads/master
<file_sep>from django.apps import AppConfig class PilatesBookingConfig(AppConfig): name = 'pilates_booking' <file_sep># online_booking register user, create events (using django admin view) and book events (e.g. pilates, physio, etc.) online using a weekly calendar view # run <ul> <li>docker-compose build</li> <li>docker-compose up</li> </ul> <file_sep># Generated by Django 3.0.2 on 2020-05-15 14:30 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('users', '0005_profile_email'), ] operations = [ migrations.RenameField( model_name='profile', old_name='tel', new_name='telefonnummer', ), ] <file_sep>from django.contrib import admin from .models import Booking from datetime import timedelta from django.shortcuts import render from django.http import HttpResponseRedirect from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django.db import models import pandas as pd import pytz def duplicate_booking(self, request, queryset): for counter, object in enumerate(queryset, start=1): object.id = None object.date += timedelta(weeks=1) object.save() if counter == 1: message_bit = "%s booking was" % counter else: message_bit = "%s bookings were" % counter self.message_user(request, "%s duplicated." % message_bit) duplicate_booking.short_description = "Duplicate booking(s) for the following week" def duplicate_booking_until(self, request, queryset): if 'apply' in request.POST: date_until = request.POST['date_until'] date_until = pd.to_datetime(date_until).replace(tzinfo=pytz.UTC) #date_until = date_until.replace(tzinfo=pytz.UTC) # The user clicked submit on the intermediate form. # Perform our update action: for counter, object in enumerate(queryset, start=1): week_count = 0 while object.date + timedelta(weeks=1) <= date_until: week_count += 1 object.id = None object.date += timedelta(weeks=1) object.save() # Redirect to our admin view after our update has # completed with a nice little info message saying # our models have been updated: if counter == 1: message_bit = "%s booking was" % counter else: message_bit = "%s bookings were" % counter self.message_user(request, f"{message_bit} duplicated {week_count} times.") return HttpResponseRedirect(request.get_full_path()) return render(request, 'pilates_booking/booking_intermediate.html', context={'bookings':queryset}) duplicate_booking_until.short_description = "Duplicate booking(s) weekly until specific date" class BookingAdmin(admin.ModelAdmin): list_display = ('title', 'date', 'slots_available', 'get_attendees', 'content') date_hierarchy = 'date' ordering = ['-date'] save_as = True actions = [duplicate_booking, duplicate_booking_until] class BookingInline(admin.StackedInline): model = Booking.attendees.through can_delete = False verbose_name_plural = 'Bookings' fk_name = 'user' #or booking? class CustomUserAdmin(UserAdmin): inlines = (BookingInline, ) list_display = UserAdmin.list_display + ('get_booking_ids',) #def get_attendees(self): # return ", ".join([p.username for p in self.attendees.all()]) def get_booking_ids(self, obj): booking_ids = [p.pk for p in obj.booking_set.all()] booking_ids.sort() return booking_ids get_booking_ids.short_description = 'Bookings (ID)' def get_booking_titles_and_dates(self, obj): return [[p.title, p.date] for p in obj.booking_set.all()] #", ".join(list(*list(zip(titles,dates)))) #", ".join([p.title for p in obj.booking_set.all()]) admin.site.unregister(User) admin.site.register(User, CustomUserAdmin) admin.site.register(Booking, BookingAdmin) <file_sep># Generated by Django 3.0.5 on 2020-04-23 23:54 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('users', '0003_auto_20200423_2215'), ] operations = [ migrations.RenameField( model_name='profile', old_name='nachame', new_name='nachname', ), ] <file_sep>FROM python:3.8 MAINTAINER <EMAIL> COPY ./django_project /django_project WORKDIR /django_project RUN pip install -r requirements.txt CMD ["bash", "run.sh"] <file_sep>from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile from django.contrib.auth.forms import AuthenticationForm, UsernameField class CustomAuthenticationForm(AuthenticationForm): #email = forms.EmailField(required=True) username = UsernameField( label='Email', widget=forms.TextInput(attrs={'autofocus': True}) ) class UserRegisterForm(UserCreationForm): email = forms.EmailField( required = True, label='Email bestätigen', ) vorname = forms.CharField(required=True) nachname = forms.CharField(required=True) adresse = forms.CharField(required=True) telefonnummer = forms.CharField(required=True) username = UsernameField( label='Email', widget=forms.TextInput(attrs={'autofocus': True}) ) class Meta: model = User fields = ['username', 'email', '<PASSWORD>', '<PASSWORD>'] #fields = ['email', 'vorname', 'nachname'] def save(self, *args, **kwargs): super().save(*args, **kwargs) # parent's classe's save function class UserUpdateForm(forms.ModelForm): # email = forms.EmailField(required=True) username = UsernameField( label='Email', widget=forms.TextInput(attrs={'autofocus': True}) ) class Meta: model = User fields = ['username'] # allows us to update username class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] # allows us to update the profile image<file_sep># Generated by Django 3.0.2 on 2020-05-15 14:30 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('pilates_booking', '0002_remove_booking_weekly_event'), ] operations = [ migrations.AlterModelOptions( name='booking', options={'ordering': ['date']}, ), migrations.AlterField( model_name='booking', name='attendees', field=models.ManyToManyField(blank=True, to=settings.AUTH_USER_MODEL), ), ] <file_sep>from django.db import models from django.urls import reverse from django.utils import timezone from datetime import datetime from django.contrib.auth.models import User class Booking(models.Model): title = models.CharField(max_length=1000) date = models.DateTimeField(default=timezone.now) slots_total = models.IntegerField() content = models.TextField(blank=True) #weekly_event = models.BooleanField(default=True) attendees = models.ManyToManyField(User, blank=True) class Meta: ordering = ["date"] def get_attendees(self): return ", ".join([p.username for p in self.attendees.all()]) def slots_available(self): return f"{self.slots_total - len(self.attendees.all())} / {self.slots_total}" def slots_remaining(self): return self.slots_total - len(self.attendees.all()) def __str__(self): return f"{self.title} - ({self.date.date()}; {self.date.time()})" <file_sep>from django.shortcuts import render, get_object_or_404 from django.views.generic import ( ListView, DetailView, DeleteView, CreateView, UpdateView ) from .models import Booking from .admin import CustomUserAdmin from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.contrib.auth.models import User from django.core.paginator import Paginator from django.http import HttpResponse from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.contrib import messages from django.utils.translation import gettext from django.contrib.auth.decorators import login_required from datetime import date, datetime, timedelta, timezone def get_week_list(year_number): max_weeknumber = date( int(year_number) , 12, 28).isocalendar()[1] # check in with weeknumber the last day of the year is in day_of_the_week = range(1,6) week_number = range(1, max_weeknumber+1) current_week = datetime.now().isocalendar()[1] week_list = [] for w in week_number: for d in day_of_the_week: show_date = date.fromisocalendar(int(year_number), w, d) # year, week number, day of the week week_list.append([show_date, show_date.strftime('%A')]) return week_list, max_weeknumber def get_time_range(minh, maxh): timerange_list = [] for hour in range(minh, maxh): timerange_list.append([hour, 0]) # hour and min timerange_list.append([hour, 15]) timerange_list.append([hour, 30]) timerange_list.append([hour, 45]) timerange_list.append([maxh + 1, 0]) return timerange_list def person_registration(request, pk): '''add/removes registration for booking with primary key pk''' booking_slot = Booking.objects.get(pk=pk) user = request.user # currently logged in user week_number = booking_slot.date.isocalendar()[1] # get week number of booking slot try: dummy = booking_slot.attendees.get(username=user.username) # only exists if user has made this booking before if booking_slot.date < datetime.now(timezone.utc) + timedelta(days=1): # if less than 24h until booking time_diff = booking_slot.date - datetime.now(timezone.utc) txt_message = f"Buchung kann nicht mehr storniert werden, weil die Einheit '{booking_slot}' in unter 24 Stunden beginnt" return render(request, 'pilates_booking/booking_change.html', {'txt_message':txt_message, 'week_number':week_number}) booking_slot.attendees.remove(user) booking_slot.save() txt_message = f"Buchung wurde storniert!" except Exception: if booking_slot.date < datetime.now(timezone.utc): # if less than 24h until booking time_diff = booking_slot.date - datetime.now(timezone.utc) txt_message = f"Buchung kann nicht durchgeführt werden, weil die Einheit '{booking_slot}' schon begonnen hat bzw. vorbei ist." return render(request, 'pilates_booking/booking_change.html', {'txt_message':txt_message, 'week_number':week_number}) booking_slot.attendees.add(user) booking_slot.save() txt_message = f"{user.username} hat '{booking_slot}' erfolgreich gebucht!" return render(request, 'pilates_booking/booking_change.html', {'txt_message':txt_message, 'week_number':week_number}) def calendar(request): week_number = request.GET.get('week') if week_number == None: week_number = datetime.now().isocalendar()[1] # current week year_number = request.GET.get('year') if year_number == None: year_number = datetime.now().year # current year week_list, max_weeknumber = get_week_list(year_number) booking_slots = Booking.objects.all() paginator = Paginator(week_list, 5) # 5 days at a time (one week MO-FR) week_obj = paginator.get_page(week_number).object_list user = request.user context = { 'booking_slots': booking_slots, #'hours': get_time_range(6, 19), 'week_list': week_list, # [date, weekday_string] 'week_number': week_number, 'year_number': year_number, 'week_obj': week_obj, # for pagination 'max_weeknumber': max_weeknumber, # to increase year if necessary } return render(request, 'pilates_booking/home.html', context) def admin_calendar(request): week_number = request.GET.get('week') if week_number == None: week_number = datetime.now().isocalendar()[1] # current week year_number = request.GET.get('year') if year_number == None: year_number = datetime.now().year # current year week_list, max_weeknumber = get_week_list(year_number) booking_slots = Booking.objects.all() paginator = Paginator(week_list, 5) # 5 days at a time (one week MO-FR) week_obj = paginator.get_page(week_number).object_list user = request.user context = { 'booking_slots': booking_slots, 'hours': get_time_range(6, 19), 'week_list': week_list, # [date, weekday_string] 'week_number': week_number, 'year_number': year_number, 'week_obj': week_obj, # for pagination 'max_weeknumber': max_weeknumber, # to increase year if necessary } return render(request, 'pilates_booking/admin_calendar.html', context) class BookingSlotsListView(ListView): model = Booking template_name = 'pilates_booking/booking_slots.html' # default: <app>/<model>_<viewtype>.html context_object_name = 'booking_slots' ordering = ['-duration'] class UserBookingListView(LoginRequiredMixin, ListView): model = Booking template_name = 'pilates_booking/user_bookings.html' # default: <app>/<model>_<viewtype>.html context_object_name = 'bookings' def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) print(f"user = {user}") return CustomUserAdmin.get_booking_titles_and_dates(self, user) <file_sep>from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # if user is deleted delete the profile also (but not the other way round) image = models.ImageField(default='default.jpg', upload_to='profile_pics') vorname = models.CharField(max_length=100, default="hans") nachname = models.CharField(max_length=100, default="max") adresse = models.TextField(max_length=500, default="gasse") telefonnummer = models.CharField(max_length=20, default=1234) email = models.EmailField(max_length=50, default="<EMAIL>") def __str__(self): return f"{self.user.username} Profile" def save(self, *args, **kwargs): super().save(*args, **kwargs) # parent's classe's save function img = Image.open(self.image.path) if img.height > 300 or img.width > 300: # resize image if it is too large output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path)<file_sep># Generated by Django 3.0.5 on 2020-04-23 22:14 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.AddField( model_name='profile', name='adresse', field=models.CharField(default='gasse', max_length=500), ), migrations.AddField( model_name='profile', name='nachame', field=models.CharField(default='max', max_length=100), ), migrations.AddField( model_name='profile', name='tel', field=models.CharField(default=1234, max_length=20), ), migrations.AddField( model_name='profile', name='vorname', field=models.CharField(default='hans', max_length=100), ), ] <file_sep># Generated by Django 3.0.5 on 2020-04-23 23:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0004_auto_20200423_2354'), ] operations = [ migrations.AddField( model_name='profile', name='email', field=models.EmailField(default='<EMAIL>', max_length=50), ), ]
7030905bdb8a5c63a986b75c8e0c5bf395fc9ed9
[ "Markdown", "Python", "Dockerfile" ]
13
Python
lpythonl/online_booking
c720333a26bd095f589562b357d7d6b730bad672
5eb925b8b6ff0d5623bad13bc357093977ac8120
refs/heads/master
<repo_name>hertz1/arquiteto-php<file_sep>/app/Listeners/LogExecutedQuery.php <?php namespace App\Listeners; use Illuminate\Database\Events\QueryExecuted; use Illuminate\Support\Facades\Log; class LogExecutedQuery { public function handle(QueryExecuted $query) { Log::channel('stdout')->info( $query->sql, [ 'bidings' => $query->bindings, 'time' => "{$query->time}ms" ] ); } } <file_sep>/database/seeders/AddressesSeeder.php <?php namespace Database\Seeders; use App\Models\Address; use Illuminate\Database\Eloquent\Factories\Sequence; use Illuminate\Database\Seeder; use Illuminate\Support\Str; class AddressesSeeder extends Seeder { protected int $usersAmount = 50; protected int $addressedPerUser = 3; /** * Run the database seeds. * * @return void */ public function run() { Address::factory() ->count(($this->usersAmount * $this->addressedPerUser) + 1) ->state($this->getUsersUuidsSequence()) ->create(); } protected function getUsersUuidsSequence(): Sequence { $uuids = ['3c472ed8-87c8-4fee-a51a-c0401e9507f8']; for ($i = 0; $i < $this->usersAmount; $i++) $uuids[] = (string) Str::uuid(); return new Sequence(...array_map( fn ($uuid) => ['user_uuid' => (string) $uuid], $uuids )); } } <file_sep>/app/Http/Requests/AddressRequest.php <?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class AddressRequest extends FormRequest { /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'user_uuid' => 'required|max:36', 'address_line_1' => 'required|max:256', 'address_line_2' => 'max:256', 'locations' => 'required|array', 'locations.country' => 'required|array' ]; } } <file_sep>/app/Models/User.php <?php namespace App\Models; use Illuminate\Auth\GenericUser; use Illuminate\Database\Eloquent\Factories\HasFactory; /** * App\Models\User * * @property string $uuid */ class User extends GenericUser { use HasFactory; public function getAuthIdentifierName() { return 'uuid'; } } <file_sep>/app/Repositories/AddressRepository.php <?php namespace App\Repositories; use App\Models\Address; use App\Models\Location; use App\Models\LocationType; use App\Services\AddressService; use Illuminate\Database\Eloquent\Collection; use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; use Throwable; class AddressRepository { protected LocationRepository $locationRepository; protected LocationTypeRepository $locationTypeRepository; public function __construct( LocationRepository $locationRepository, LocationTypeRepository $locationTypeRepository ) { $this->locationRepository = $locationRepository; $this->locationTypeRepository = $locationTypeRepository; } /** * Find all address of an user by its UUID * * @param string $uuid * @return Address[]|Collection */ public function findAddressByUserUuid(string $uuid): Collection { return Address::query() ->with(['location.ancestors.type', 'location.type:id,name']) ->whereUserUuid($uuid) ->get(); } /** * Delete an address and its locations * * @param Address $address * @throws Throwable */ public function deleteAddressAndLocations(Address $address): void { $rootLocationTypeForDeletion = Location::getRootLocationTypeForDeletionByCountry( $address->getCountry()->name ); /** @var Location $nodeToDelete */ $nodeToDelete = $address->location->ancestors->first(fn (Location $node) => $node->location_type_id === $rootLocationTypeForDeletion ); DB::transaction(fn () => $nodeToDelete->delete()); } /** * Persist the address and its locations on the database * * @param Address $address * @param array $locations * @param AddressService $addressService * @return mixed * @throws Throwable */ public function persistAddressAndLocations(Address $address, array $locations, AddressService $addressService) { return DB::transaction(function () use ($address, $locations) { $associatedLocation = $this->buildAddressLocationTree($locations); $address->location()->associate($associatedLocation); $address->save(); return $address; }); } /** * Build the address location tree and return the latest location. * * @param $requestLocations * @return Location */ protected function buildAddressLocationTree($requestLocations): Location { $country = $this->locationRepository->getCountryById($requestLocations['country']['id']); $locationTypeOrder = $this->locationTypeRepository ->findAllByIds(Location::getLocationTypeOrderByCountry($country->name)); return $locationTypeOrder->reduce(function (?Location $parent, LocationType $locationType) use ($requestLocations) { $name = Str::snake($locationType->name); $requestLocation = $requestLocations[$name]; $node = isset($requestLocation['id']) ? Location::find($requestLocation['id']) : new Location([ 'name' => $requestLocation['name'], 'location_type_id' => $locationType->id ]); if ($parent) $parent->appendNode($node); return $node; }); } } <file_sep>/app/Models/Address.php <?php namespace App\Models; use Carbon\Carbon; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Kalnoy\Nestedset\Collection; use Rennokki\QueryCache\Traits\QueryCacheable; /** * App\Models\Address * * @property int $id * @property string $user_uuid * @property string $address_line_1 * @property string $address_line_2 * @property int $location_id * @property \Illuminate\Support\Carbon $created_at * @property \Illuminate\Support\Carbon $updated_at * @property-read Location $location * @method static Builder|Address newModelQuery() * @method static Builder|Address newQuery() * @method static Builder|Address query() * @method static Builder|Address whereAddressLine1($value) * @method static Builder|Address whereAddressLine2($value) * @method static Builder|Address whereCreatedAt($value) * @method static Builder|Address whereId($value) * @method static Builder|Address whereLocationId($value) * @method static Builder|Address whereUpdatedAt($value) * @method static Builder|Address whereUserUuid($value) * @mixin \Eloquent */ class Address extends Model { use HasFactory, QueryCacheable; public $guarded = ['location']; public $cacheFor = Carbon::HOURS_PER_DAY * Carbon::MINUTES_PER_HOUR * Carbon::SECONDS_PER_MINUTE; protected static bool $flushCacheOnUpdate = true; /** * The location relationship * @return BelongsTo */ public function location(): BelongsTo { return $this->belongsTo(Location::class); } /** * Get a flat tree representation of the address' locations * @return Collection */ public function getLocationsFlatTree(): Collection { $locations = collect([$this->location]) ->merge($this->location->ancestors->toFlatTree()->reverse()); return new Collection($locations); } /** * Filter by the user uuid * @param Builder $query * @param $uuid */ public function scopeWhereUserUuid(Builder $query, $uuid) { $query->where('user_uuid', $uuid); } /** * Get the associated country of the address * @return Location */ public function getCountry(): Location { return $this->location ->countries() ->first(); } } <file_sep>/app/Http/Resources/LocationResource.php <?php namespace App\Http\Resources; use App\Models\Location; use Illuminate\Http\Request; use Illuminate\Http\Resources\Json\JsonResource; class LocationResource extends JsonResource { /** @var Location */ public $resource; /** * Transform the resource into an array. * * @param Request $request * @return array */ public function toArray($request) { $location = $this->resource; return [ 'id' => $location->id, 'name' => $location->name, 'type' => new LocationTypeResource($location->type) ]; } } <file_sep>/README.md # Adressen ## Sobre _Adressen (endereços)_ é um simples microserviço para gerenciamento de endereços de uma pessoa. ## Instalação ### Ambiente Para rodar a aplicação é necessário ter o *Docker* e *Docker Compose* instalados. Para instalar, basta seguir as instruções de instalação para o [Docker](https://docs.docker.com/get-docker/) e [Docker Compose](https://docs.docker.com/compose/install/). Após a instalação, execute os seguintes comandos para configurar o ambiente da aplicação: > *Obs.: Caso o usuário do sistema operacional tenha um ID diferente de > **1000**, altere a propriedade **UID** no arquivo **.env** para o valor correto. Isso é necessário para configurar corretamente as permissões dos arquivos da aplicação no sistema de arquivos.* ```sh git clone https://github.com/hertz1/arquiteto-php.git cd arquiteto-php cp .env.example .env docker-compose up -d docker exec adressen php artisan key:generate ``` Após o download e construção das imagens o ambiente estará configurado. ### Banco de Dados Para popular as tabelas e dados no banco de dados da aplicação, basta executar o seguinte comando: ```sh docker exec adressen php artisan migrate --seed ``` ## Visão Geral da Arquitetura ### Infraestrutura A aplicação foi construída utilizando a abordagem arquitetural de microsserviços. Essa abordagem proporciona diversos benefícios, como escalabilidade, resiliência, implantações e atualizações mais ágeis, facilidade de desenvolvimento e manutenção, entre outros. Conteinerização através do *Docker* permite a execução da aplicação da maneira fidedigna independente de sistema operacional e hardware. Por fim, orquestração através do *Docker Compose* facilita o gerenciamento dos serviços. ### API Uma API permite integração com outros sistemas de maneira simples, requerendo apenas um *token* de autorização no formato JWT (*Json Web Token*). A documentação da API pode ser vista [neste link](https://app.swaggerhub.com/apis/danilo-azevedo/Adressen). ### Aplicação A aplicação foi desenvolvida na linguagem de programação [PHP](https://www.php.net) com o framework [Laravel](https://laravel.com). Explicações mais detalhadas sobre os componentes da aplicação podem ser encontradas logo a seguir. #### Controllers *Controllers* agrupam lógicas de tratamento de requisição em uma classe. No geral, devem tratar apenas I/O, ou seja, ao receber um [requisição](#requests), devem devolver uma resposta adequada. Não devem conter regras de negócio nem acesso a serviços externos, como bancos de dados, servidores de e-mail, etc. Para isso, utilizamos os [Services](#services). #### Requests ##### Validation & Authorization Toda lógica de validação e autorização deve ser feita utilizando [`Form Requests`](https://laravel.com/docs/validation#form-request-validation) em conjunto com [`Policies`](https://laravel.com/docs/authorization#creating-policies). #### Responses As respostas da aplicação são definidas utilizando [`API Resources`](https://laravel.com/docs/eloquent-resources). São classes responsáveis por definir como uma determinada informação deve ser serializada na resposta. #### Services *Services* são objetos que possuem uma responsabilidade bem definida. Neles são definidas regras de negócio da aplicação e comunicação com serviços externos. #### Models *Models* representam um registro de uma determinada tabela no banco de dados. Também podem ser utilizados para definir regras de negócio específicas para um determinado *Model*. #### Repositories *Repositories* são classes cujo único objetivo é centralizar a comunicação da aplicação com o [Banco de Dados](#banco-de-dados). Como o [ORM](https://pt.wikipedia.org/wiki/Mapeamento_objeto-relacional) padrão do Laravel (Eloquent) utiliza [Active Record](https://pt.wikipedia.org/wiki/Active_record), em tese o uso de *repositories* não se faz necessário, porém é uma forma de centralizar *queries* mais complexas e aplicar uma separação de responsabilidades entre as classes. ### Banco de Dados A modelagem do banco de dados foi feita de forma a suportar a estrutura de endereço de vários países. Por exemplo, no Brasil poderíamos representar a estrutura de um endereço na seguinte árvore: ``` |-- País | |-- Estado | | |-- Município | | | |-- Bairro | | | | |-- Cep ``` O modelo entidade-relacionamento poderia ser desenhado desta forma: ![MER](https://i.imgur.com/jzpG2km.png) Porém, em outro país a estrutura de endereço pode ser completamente diferente. Para solucionar esse problema, ao invés de criar mais tabelas e *desnormalizar* a estrutura do banco de dados, implementamos uma estrutura de [_Nested Set Model_](https://en.wikipedia.org/wiki/Nested_set_model). Dessa forma, desenhamos nossa arquitetura de forma hierárquica, no qual podemos definir uma estrutura de relacionamento entre localidades de forma a atender qualquer estrutura: ![MER](https://i.imgur.com/SJAZv6d.png) O projeto já vem pré-configurado com as localidades brasileiras de UF e Município nesta estrutura, sendo possível estender com Municípios e Bairros de forma simples. ###### *Modelo baseado [neste artigo](https://danielcoding.net/multi-country-address-database-design/).* ### Cache Uma parte importante de qualquer aplicação é o *cache*. Se bem configurado, a carga no banco de dados é drasticamente reduzida, a quantidade de requisições por segundo da aplicação é ampliada e é possível até reduzir custos de infraestrutura. Para o gerenciamento de *cache* da aplicação é utilizado o [Redis](https://redis.io), que é um servidor de armazenamento em rede de dados de chave-valor. É altamente performático, sendo utilizado por diversas aplicações de alta demanda. ## Testando a aplicação Ao executar as instruções contidas na seção [**Banco de Dados**](#banco-de-dados), a base será populada com vários endereços aleatórios. Entre eles, há usuário pré-definido com UUID `3c472ed8-87c8-4fee-a51a-c0401e9507f8`, o qual utilizaremos para testar a aplicação. ### API Token O próximo passo é gerar um token válido para autenticar na aplicação. Como não há integração com um serviço de autenticação, utilizaremos o site [Online JWT Builder](http://jwtbuilder.jamiekurtz.com/) para construir o token. Ao abrir o site, é necessário alterar apenas os seguintes campos: - **Expiration**: Clique em **`in 20 minutes`** para definir que o token expire em 20 minutos após o horário atual. - **Subject**: Aqui definiremos o UUID do usuário do token. Neste caso, será o usuário pré-definido (`3c472ed8-87c8-4fee-a51a-c0401e9507f8`). - **Additional Claims**: Podemos remover todos os *claims*, para isso cliquem em **`clear all`**. - **Key**: Neste campo devemos informar a chave que será utilizada para encriptar o token. Podemos utilizar o valor pré-definido na variável `API_SECRET` no arquivo `.env` ou gerar outra chave. Caso utilize outra chave, é necessário atualizar o valor de `API_SECRET` com a nova chave. O algoritmo utilizado deve ser **`HS512`**. Clique em *`Create Signed JWT`* e guarde o token gerado. ### Realizando requisições Neste exemplo será utilizado o [Postman](https://www.postman.com/) para realizar requisições, mas pode ser utilizado outro utilitário de preferência. #### Autenticação Clique na aba `Authorization`. Em `type`, selecione `Bearer Token` e informe o token gerado no [passo anterior](#api-token). #### Headers Informe o cabeçalho `Accept: application/json` para que a API possa retornar as repostas no formato correto. #### URL Defina uma URL de acordo com a [documentação da API](#api). Ex.: `GET http://localhost/addresses`. Clique em `Send` e a aplicação deve retornar a resposta corretamente. <file_sep>/app/Auth/AuthUserProvider.php <?php /** * Provisiona uma instância de usuário simples para a aplicação. * Como a aplicação não possui dados de usuário e não há uma integração * com um serviço de usuários, uma simples instância do Model é retornada. */ namespace App\Auth; use App\Models\User; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\UserProvider; class AuthUserProvider implements UserProvider { public function retrieveById($identifier) { return new User([ 'uuid' => $identifier ]); } public function retrieveByToken($identifier, $token) { return new User([ 'uuid' => $identifier, 'token' => $token ]); } public function updateRememberToken(Authenticatable $user, $token) { //@TODO: Implementar integração com um serviço de autenticação } public function retrieveByCredentials(array $credentials) { //@TODO: Implementar integração com um serviço de autenticação } public function validateCredentials(Authenticatable $user, array $credentials) { //@TODO: Implementar integração com um serviço de autenticação } } <file_sep>/database/factories/AddressFactory.php <?php namespace Database\Factories; use App\Models\Address; use App\Models\Location; use App\Models\LocationType; use Illuminate\Database\Eloquent\Factories\Factory; class AddressFactory extends Factory { /** * The name of the factory's corresponding model. * * @var string */ protected $model = Address::class; /** * Define the model's default state. * * @return array */ public function definition() { /** @var Location $city */ $city = Location::cities()->inRandomOrder()->first(); $attributes = [ 'location_type_id' => LocationType::DISTRICT, 'name' => $this->faker->streetName, 'children' => [[ 'location_type_id' => LocationType::POSTAL_CODE, 'name' => $this->faker->postcode, ]] ]; $district = Location::create($attributes, $city); $postalCode = $district->descendants->first(); return [ 'address_line_1' => $this->faker->streetAddress, 'address_line_2' => $this->faker->secondaryAddress, 'location_id' => $postalCode->id ]; } } <file_sep>/app/Services/AddressService.php <?php namespace App\Services; use App\Models\Address; use App\Repositories\AddressRepository; use Illuminate\Database\Eloquent\Collection; use Illuminate\Support\Facades\Auth; use Throwable; class AddressService { protected AddressRepository $repository; public function __construct(AddressRepository $repository) { $this->repository = $repository; } /** * Get all the addresses of the authenticated user * * @return Address[]|Collection */ public function getAuthenticatedUserAddresses(): Collection { $user_uuid = Auth::id(); return $this->repository->findAddressByUserUuid($user_uuid); } /** * Create a new address for the authenticated user * * @param array $data * @return Address * @throws Throwable */ public function createAddressForAuthenticatedUser(array $data): Address { $address = new Address($data); return $this->repository->persistAddressAndLocations($address, $data['locations'], $this); } /** * Update an address for the authenticated user * * @param Address $address * @param array $data * @return Address * @throws Throwable */ public function updateAddressForAuthenticatedUser(Address $address, array $data): Address { $address->fill($data); return $this->repository->persistAddressAndLocations($address, $data['locations'], $this); } /** * @param Address $address * @throws Throwable */ public function deleteAddressForAuthenticatedUser(Address $address): void { $this->repository->deleteAddressAndLocations($address); } } <file_sep>/app/Http/Requests/CreateAddressRequest.php <?php namespace App\Http\Requests; class CreateAddressRequest extends AddressRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { $newAddressUserUuid = $this->get('user_uuid'); return $this->user()->uuid === $newAddressUserUuid; } } <file_sep>/app/Auth/JwtGuard.php <?php namespace App\Auth; use Illuminate\Auth\GuardHelpers; use Illuminate\Contracts\Auth\Guard; use Illuminate\Contracts\Auth\UserProvider; use Lcobucci\JWT\Parser; use Lcobucci\JWT\Signer\Hmac\Sha512; use Lcobucci\JWT\Token; class JwtGuard implements Guard { use GuardHelpers; protected Token $token; public function __construct(string $jwt, UserProvider $provider) { $this->token = (new Parser())->parse($jwt); $this->provider = $provider; } public function user() { if (!is_null($this->user)) return $this->user; if ($this->token && $this->verify()) { $id = $this->token->getClaim('sub'); return $this->user = $this->provider->retrieveById($id); } } public function verify() { return $this->token->verify(new Sha512(), env('API_SECRET')); } public function validate(array $credentials = []) { //@TODO: Implementar integração com um serviço de autenticação return false; } } <file_sep>/routes/api.php <?php use App\Http\Controllers\AddressesController; use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ Route::middleware(['auth:api'])->group(function () { Route::get('/addresses', [AddressesController::class, 'index']); Route::post('/address', [AddressesController::class, 'create']); Route::put('/address/{address}', [AddressesController::class, 'update']); Route::delete('/address/{address}', [AddressesController::class, 'delete']); }); <file_sep>/app/Models/LocationType.php <?php namespace App\Models; use Carbon\Carbon; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Rennokki\QueryCache\Traits\QueryCacheable; /** * App\Models\LocationType * * @property int $id * @property string $name * @property \Illuminate\Support\Carbon $created_at * @property \Illuminate\Support\Carbon $updated_at * @method static \Illuminate\Database\Eloquent\Builder|LocationType newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|LocationType newQuery() * @method static \Illuminate\Database\Eloquent\Builder|LocationType query() * @method static \Illuminate\Database\Eloquent\Builder|LocationType whereCreatedAt($value) * @method static \Illuminate\Database\Eloquent\Builder|LocationType whereId($value) * @method static \Illuminate\Database\Eloquent\Builder|LocationType whereName($value) * @method static \Illuminate\Database\Eloquent\Builder|LocationType whereUpdatedAt($value) * @mixin \Eloquent */ class LocationType extends Model { use HasFactory, QueryCacheable; public const COUNTRY = 1; public const STATE = 2; public const CITY = 3; public const DISTRICT = 4; public const POSTAL_CODE = 5; public int $cacheFor = Carbon::HOURS_PER_DAY * Carbon::MINUTES_PER_HOUR * Carbon::SECONDS_PER_MINUTE; } <file_sep>/.env.example APP_NAME=Laravel APP_ENV=local APP_KEY= APP_DEBUG=true APP_URL=http://localhost LOG_CHANNEL=stack DB_CONNECTION=mysql DB_HOST=adressen_db DB_PORT=3306 DB_DATABASE=adressen DB_USERNAME=adressen DB_PASSWORD=<PASSWORD> BROADCAST_DRIVER=log CACHE_DRIVER=redis QUEUE_CONNECTION=sync SESSION_DRIVER=file SESSION_LIFETIME=120 REDIS_HOST=adressen_redis REDIS_PASSWORD=<PASSWORD> REDIS_PORT=6379 MAIL_MAILER=smtp MAIL_HOST=smtp.mailtrap.io MAIL_PORT=2525 MAIL_USERNAME=null MAIL_PASSWORD=<PASSWORD> MAIL_ENCRYPTION=null MAIL_FROM_ADDRESS=null MAIL_FROM_NAME="${APP_NAME}" API_SECRET=<KEY> UID=1000 <file_sep>/app/Providers/AuthServiceProvider.php <?php namespace App\Providers; use App\Auth\AuthUserProvider; use App\Auth\JwtGuard; use App\Models\Address; use App\Policies\AddressPolicy; use Illuminate\Contracts\Auth\Guard; use Illuminate\Contracts\Auth\UserProvider; use Illuminate\Foundation\Application; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class AuthServiceProvider extends ServiceProvider { /** * The policy mappings for the application. * * @var array */ protected $policies = [ Address::class => AddressPolicy::class ]; /** * Register any authentication / authorization services. * * @return void */ public function boot() { $this->registerPolicies(); $this->registerProviders(); $this->registerGuards(); } protected function registerProviders(): void { Auth::provider('auth.user.provider', fn (Application $app, array $config): UserProvider => new AuthUserProvider() ); } protected function registerGuards(): void { Auth::extend('jwt', function (Application $app, $name, array $config): Guard { /** @var Request $request */ $request = $app['request']; return new JwtGuard ($request->bearerToken(), Auth::createUserProvider($config['provider'])); }); } } <file_sep>/database/migrations/2020_09_26_000001_create_locations_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; use Kalnoy\Nestedset\NestedSet; class CreateLocationsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('locations', function (Blueprint $table) { $table->integerIncrements('id'); $table->string('name', 64); $table->unsignedTinyInteger('location_type_id'); $table->nestedSet(); $table->dateTime('created_at')->useCurrent(); $table->dateTime('updated_at')->useCurrent(); $table->foreign('location_type_id') ->references('id') ->on('location_types'); $table->foreign('parent_id') ->references('id') ->on('locations') ->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('locations'); } } <file_sep>/app/Repositories/LocationTypeRepository.php <?php namespace App\Repositories; use App\Models\LocationType; use Illuminate\Database\Eloquent\Collection; class LocationTypeRepository { /** * @param array $ids * @return LocationType[]|Collection */ public function findAllByIds(array $ids): Collection { return LocationType::query() ->whereIn('id', $ids)->get(); } } <file_sep>/app/Http/Controllers/AddressesController.php <?php namespace App\Http\Controllers; use App\Http\Requests\CreateAddressRequest; use App\Http\Requests\DeleteAddressRequest; use App\Http\Requests\UpdateAddressRequest; use App\Http\Resources\AddressResource; use App\Models\Address; use App\Services\AddressService; use Illuminate\Http\Response; use Throwable; class AddressesController extends Controller { protected AddressService $service; public function __construct(AddressService $service) { $this->service = $service; } public function index() { return AddressResource::collection( $this->service->getAuthenticatedUserAddresses() ); } /** * @param CreateAddressRequest $request * @return Response * @throws Throwable */ public function create(CreateAddressRequest $request): Response { $address = $this->service->createAddressForAuthenticatedUser($request->validated()); return response(new AddressResource($address), Response::HTTP_CREATED); } /** * @param UpdateAddressRequest $request * @param Address $address * @return Response * @throws Throwable */ public function update(UpdateAddressRequest $request, Address $address): Response { $address = $this->service->updateAddressForAuthenticatedUser($address, $request->validated()); return response(new AddressResource($address), Response::HTTP_OK); } /** * @param DeleteAddressRequest $request * @param Address $address * @return Response * @throws Throwable */ public function delete(DeleteAddressRequest $request, Address $address): Response { $this->service->deleteAddressForAuthenticatedUser($address); return response(null, Response::HTTP_NO_CONTENT); } } <file_sep>/app/Http/Resources/LocationTypeResource.php <?php namespace App\Http\Resources; use App\Models\LocationType; use Illuminate\Http\Resources\Json\JsonResource; class LocationTypeResource extends JsonResource { /** @var LocationType */ public $resource; /** * Transform the resource into an array. * * @param \Illuminate\Http\Request $request * @return array */ public function toArray($request) { $lt = $this->resource; return [ 'id' => $lt->id, 'name' => $lt->name ]; } } <file_sep>/app/Repositories/LocationRepository.php <?php namespace App\Repositories; use App\Models\Location; use Kalnoy\Nestedset\Collection; class LocationRepository { /** * @param array $ids * @return Location[]|Collection */ public function findAllByIds(array $ids): Collection { return Location::query() ->with('type') ->whereIn('id', $ids)->get(); } /** * Get a country by ID * * @param int $countryId * @return Location */ public function getCountryById(int $countryId): Location { return Location::query() ->countryId($countryId) ->first(); } } <file_sep>/app/Http/Requests/UpdateAddressRequest.php <?php namespace App\Http\Requests; use Illuminate\Support\Facades\Gate; class UpdateAddressRequest extends AddressRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return Gate::allows('update', $this->route('address')); } } <file_sep>/app/Models/Location.php <?php namespace App\Models; use Carbon\Carbon; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Kalnoy\Nestedset\NodeTrait; use Rennokki\QueryCache\Traits\QueryCacheable; /** * App\Models\Location * * @property int $id * @property string $name * @property int $location_type_id * @property int $_lft * @property int $_rgt * @property int|null $parent_id * @property \Illuminate\Support\Carbon $created_at * @property \Illuminate\Support\Carbon $updated_at * @property-read \Kalnoy\Nestedset\Collection|Location[] $children * @property-read int|null $children_count * @property-read Location|null $parent * @property-read LocationType $type * @method static \Kalnoy\Nestedset\Collection|static[] all($columns = ['*']) * @method static Builder|Location cities() * @method static Builder|Location countries() * @method static Builder|Location countryId(int $countryId) * @method static Builder|Location d() * @method static \Kalnoy\Nestedset\Collection|static[] get($columns = ['*']) * @method static \Kalnoy\Nestedset\QueryBuilder|Location newModelQuery() * @method static \Kalnoy\Nestedset\QueryBuilder|Location newQuery() * @method static \Kalnoy\Nestedset\QueryBuilder|Location query() * @method static Builder|Location whereCreatedAt($value) * @method static Builder|Location whereId($value) * @method static Builder|Location whereLft($value) * @method static Builder|Location whereLocationTypeId($value) * @method static Builder|Location whereName($value) * @method static Builder|Location whereParentId($value) * @method static Builder|Location whereRgt($value) * @method static Builder|Location whereUpdatedAt($value) * @mixin \Eloquent */ class Location extends Model { use HasFactory, NodeTrait, QueryCacheable; public $fillable = ['id', 'name', 'location_type_id']; public $cacheFor = Carbon::HOURS_PER_DAY * Carbon::MINUTES_PER_HOUR * Carbon::SECONDS_PER_MINUTE; protected static bool $flushCacheOnUpdate = true; public function type() { return $this->belongsTo(LocationType::class, 'location_type_id'); } public function parent() { return $this->belongsTo(self::class); } public function scopeCountries(Builder $query) { $query->where('location_type_id', LocationType::COUNTRY); } public function scopeCities(Builder $query) { $query->where('location_type_id', LocationType::CITY); } /** * @param Builder|Location $query * @param int $countryId */ public function scopeCountryId(Builder $query, int $countryId) { $query->countries() ->where('id', $countryId); } /** * Retorna a ordem da árvore de localidades por país * * @param string $countryName * @return array */ public static function getLocationTypeOrderByCountry(string $countryName): array { switch (strtoupper($countryName)) { case 'BRAZIL': // No Brasil a cidade já está vinculada a uma árvore, // precisamos apenas vincular o distrito (bairro) e CEP return [LocationType::CITY, LocationType::DISTRICT, LocationType::POSTAL_CODE]; default: return [LocationType::COUNTRY, LocationType::STATE, LocationType::CITY, LocationType::DISTRICT, LocationType::POSTAL_CODE]; } } /** * Retorna o tipo de localidade raíz que será excluído, por nome de país * * @param string $countryName * @return int */ public static function getRootLocationTypeForDeletionByCountry(string $countryName): int { switch (strtoupper($countryName)) { case 'BRAZIL': // No Brasil, removes o nó do distrito (bairro) e filhos return LocationType::DISTRICT; default: return LocationType::STATE; } } } <file_sep>/app/Http/Resources/AddressResource.php <?php namespace App\Http\Resources; use App\Models\Address; use Illuminate\Http\Resources\Json\JsonResource; class AddressResource extends JsonResource { /** @var Address */ public $resource; /** * Transform the resource into an array. * * @param \Illuminate\Http\Request $request * @return array */ public function toArray($request) { $ad = $this->resource; return [ 'id' => $ad->id, 'user_uuid' => $ad->user_uuid, 'address_line_1' => $ad->address_line_1, 'address_line_2' => $ad->address_line_2, 'locations' => LocationResource::collection($ad->getLocationsFlatTree()) ]; } } <file_sep>/database/seeders/LocationTypesSeeder.php <?php namespace Database\Seeders; use App\Models\LocationType; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class LocationTypesSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('location_types')->insert([ ['id' => LocationType::COUNTRY , 'name' => 'Country'], ['id' => LocationType::STATE , 'name' => 'State'], ['id' => LocationType::CITY , 'name' => 'City'], ['id' => LocationType::DISTRICT , 'name' => 'District'], ['id' => LocationType::POSTAL_CODE, 'name' => 'Postal Code'] ]); } }
e9605a38b52deba774a00e115065ae637b3ea238
[ "Markdown", "PHP", "Shell" ]
26
PHP
hertz1/arquiteto-php
84689010564ca2d75eaa7b4846b9bfd7ffa65718
8969526e56bf0bc5c97da2e8543285fd864e7ebf
refs/heads/master
<repo_name>MillissaESi/PocketConsumptionAdviser<file_sep>/pcaservice/api/serializers.py from rest_framework import serializers from .models import Product, Costumer, Question, Answer class ProductSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Product fields = ['name'] class CostumerSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Costumer fields = ['firstname', 'lastname'] class QuestionSerializer(serializers.HyperlinkedModelSerializer): product = ProductSerializer(many=False, required=False) concerned = CostumerSerializer(many=False) class Meta: model = Question fields = ['body', 'product', 'concerned'] class AnswerSerializer(serializers.HyperlinkedModelSerializer): question = QuestionSerializer(many=False) class Meta: model = Answer fields = ['answer', 'question'] <file_sep>/pcaservice/kernel/waste_estimation.py # -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ """ Waste_estimator : returns the estimate the waste. p : product ID answer: 0 if the answer to "Have you consumed all the quantity you bought last time?" is No 1 otherwise. consump_period : the estimated consumption per period of the product. quantity : the quantity of the product bought the last time the customer purchased the product. current_date : current date. last_purchase_date : the date of the last time the customer purchased the product. """ def waste_estimator(p, answer,consump_period, quantity, current_date,last_purchase_date): if (answer == 0): return 0 else: d=(current_date-last_purchase_day).days return quantity-consump*d <file_sep>/README.md # PocketConsumptionAdviser Junction Helsinki 2019: Food wast (GCI &amp; K Group) # Documentation https://millissaesi.github.io/PocketConsumptionAdviser/documentation/#our-api # Access # Migration - python manage.py makemigrations - python manage.py migrate - python manage.py runserver <file_sep>/pcaservice/kernel/README.md # Recommendation system For this prototype, a data set was generated from Junction K group data set by adding randomly a wast quantity number for a given row. Besides, a client ID was generated to develop a close technical solution to the main solution described in Dema. A regression model was used to predict the client behaviour and recommend the right quantity of food to buy. <file_sep>/pcaservice/api/views.py from django.shortcuts import render from rest_framework import viewsets from .serializers import ProductSerializer from .models import Product, Answer, Question, Costumer # Create your views here. class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all().order_by('name') serializer_class = ProductSerializer class CustomerViewSet(viewsets.ModelViewSet): queryset = Costumer.objects.all().order_by('firstname') serializer_class = ProductSerializer class QuestionViewSet(viewsets.ModelViewSet): queryset = Question.objects.all() serializer_class = ProductSerializer class AnswerViewSet(viewsets.ModelViewSet): queryset = Answer.objects.all() serializer_class = ProductSerializer <file_sep>/pcaservice/api/migrations/0002_answer_costumer_question.py # Generated by Django 2.2.7 on 2019-11-17 01:51 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('api', '0001_initial'), ] operations = [ migrations.CreateModel( name='Costumer', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('firstname', models.CharField(max_length=255)), ('lastname', models.CharField(max_length=255)), ], ), migrations.CreateModel( name='Question', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('body', models.CharField(max_length=255)), ('concerned', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='api.Costumer')), ('product', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='api.Product')), ], ), migrations.CreateModel( name='Answer', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('answer', models.CharField(max_length=255)), ('question', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='api.Question')), ], ), ] <file_sep>/pcaservice/api/models.py from django.db import models # Create your models here. class Product(models.Model): objects = None name = models.CharField(max_length=60) def __str__(self): return self.name class Costumer(models.Model): objects = None firstname = models.CharField(max_length=255) lastname = models.CharField(max_length=255) def __str__(self): return self.firstname + " " + self.lastname class Question(models.Model): objects = None body = models.CharField(max_length=255) product = models.ForeignKey(Product, null=True, on_delete=models.CASCADE) concerned = models.ForeignKey(Costumer, null=True, on_delete=models.CASCADE) def __str__(self): return self.body class Answer(models.Model): objects = None # Yes or NO answer = models.CharField(max_length=255) question = models.ForeignKey(Question, null=True, on_delete=models.CASCADE) def __str__(self): return self.answer <file_sep>/documentation/index.html <!DOCTYPE html> <html> <head> <meta charset='utf-8' /> <meta http-equiv='X-UA-Compatible' content='IE=11' /> <title>Docbox</title> <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' /> <link href='css/base.css' rel='stylesheet' /> <link href='css/style.css' rel='stylesheet' /> <link href='css/railscasts.css' rel='stylesheet' /> </head> <body> <!--START--><div id='app'><div class="container unlimiter" data-reactroot="" data-reactid="1" data-react-checksum="224653672"><div class="fixed-top fixed-right space-left16" data-reactid="2"><div class="fill-light col6 pin-right" data-reactid="3"></div></div><div class="space-top5 scroll-styled overflow-auto pad1 width16 sidebar fixed-left fill-dark dark" data-reactid="4"><div class="pad0x small" data-reactid="5"><div class="small pad0x quiet space-top1" data-reactid="6">Introduction</div><a href="#our-api" class="line-height15 pad0x pad00y quiet block " data-reactid="7">Our API</a><div class="small pad0x quiet space-top1" data-reactid="8">Example</div><a href="#pocket-consumption-adviser" class="line-height15 pad0x pad00y quiet block " data-reactid="9">Pocket Consumption Adviser</a></div></div><div class="space-left16" data-reactid="10"><div class="" data-reactid="11"><div class="clearfix" data-reactid="12"><div data-title="Our API" class="keyline-top section contain clearfix " data-reactid="13"><div class="space-bottom8 col6 pad2x prose clip" data-reactid="14"><h2 id="our-api">Our API</h2> <p>Welcome to Pocket Consumption Adviser! This is our API documentation</p> </div></div><div data-title="Pocket Consumption Adviser" class="keyline-top section contain clearfix " data-reactid="15"><div class="space-bottom8 col6 pad2x prose clip" data-reactid="16"><h2 id="pocket-consumption-adviser">Pocket Consumption Adviser</h2> <p>This is our high-quality API. We use this API to request the server to get the best recommendation to reduce the food waste</p> </div></div><div data-title="Get recommendation" class="keyline-top section contain clearfix " data-reactid="17"><div class="space-bottom8 col6 pad2x prose clip" data-reactid="18"><h3 id="get-recommendation">Get recommendation</h3> <p>Get the recommendation for the current user for a given product.</p> <table> <thead> <tr> <th>Property</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code>product</code></td> <td>(required) the id of the product.</td> </tr> <tr> <td><code>qte</code></td> <td>(non required) the quantity of the product.</td> </tr> <tr> <td><code>origin</code></td> <td>(required) (from_scanner, from_new_list, from_online_purchase)</td> </tr> </tbody> </table> <table> <thead> <tr> <th>Property</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code>quantity</code></td> <td>(nullable) a recommended quantity.</td> </tr> <tr> <td><code>duration</code></td> <td>(nullable) an estimation of the consuming duration.</td> </tr> </tbody> </table> </div><div class="space-bottom4 col6 pad2 prose clip fill-light space-top5" data-reactid="19"><div class='endpoint dark fill-dark round '> <div class='round-left pad0y pad1x fill-lighten0 code small endpoint-method'>GET</div> <div class='pad0 code small endpoint-url'>/pca/v1/recommendations/<span class="strong">{product}</span>/<span class="strong">{qte}</span>/<span class="strong">{origin}</span></div> </div> <h4 id="example-request">Example request</h4> <pre class='hljs'>$ curl -H <span class="hljs-string">"Authorization: OAuth &lt;ACCESS_TOKEN&gt;"</span> https://pocket-consumption-adviser.com/pcas/v1/recommendations/{product}/{origin}</pre> <h4 id="example-response">Example response</h4> <pre class='hljs'>{ <span class="hljs-attr">"id"</span>: <span class="hljs-string">"{recommendation_id}"</span>, <span class="hljs-attr">"concerned"</span>: <span class="hljs-string">"{user}"</span>, <span class="hljs-attr">"product"</span>: <span class="hljs-string">"{product}"</span>, <span class="hljs-attr">"quantity"</span>: <span class="hljs-string">"{quantity}"</span>, <span class="hljs-attr">"duration"</span>: <span class="hljs-string">"{duration}"</span>, <span class="hljs-attr">"created"</span>: <span class="hljs-string">"{timestamp}"</span> }</pre> </div></div><div data-title="Get a question" class="keyline-top section contain clearfix " data-reactid="20"><div class="space-bottom8 col6 pad2x prose clip" data-reactid="21"><h3 id="get-a-question">Get a question</h3> <p>Get a question for the the current user about a given product.</p> <table> <thead> <tr> <th>Property</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code>product</code></td> <td>(required) the id of the product</td> </tr> <tr> <td><code>origin</code></td> <td>(required) (from_scanner, from_new_list, from_online_purchase)</td> </tr> </tbody> </table> </div><div class="space-bottom4 col6 pad2 prose clip fill-light space-top5" data-reactid="22"><div class='endpoint dark fill-dark round '> <div class='round-left pad0y pad1x fill-lighten0 code small endpoint-method'>GET</div> <div class='pad0 code small endpoint-url'>/pca/v1/questions/<span class="strong">{product}</span>/<span class="strong">{origin}</span></div> </div> <h4 id="example-request-1">Example request</h4> <pre class='hljs'>$ curl -H <span class="hljs-string">"Authorization: OAuth &lt;ACCESS_TOKEN&gt;"</span> https://pocket-consumption-adviser.com/pcas/v1/questions/{product}/{origin}</pre> <h4 id="example-response-1">Example response</h4> <pre class='hljs'>{ <span class="hljs-attr">"id"</span>: <span class="hljs-string">"{question_id}"</span>, <span class="hljs-attr">"concerned"</span>: <span class="hljs-string">"{user}"</span>, <span class="hljs-attr">"body"</span>: <span class="hljs-string">"{question_body}"</span>, <span class="hljs-attr">"product"</span>: <span class="hljs-string">"{product}"</span>, <span class="hljs-attr">"quantity"</span>: <span class="hljs-string">"{quantity}"</span>, <span class="hljs-attr">"created"</span>: <span class="hljs-string">"{timestamp}"</span> }</pre> </div></div><div data-title="Answer a question" class="keyline-top section contain clearfix " data-reactid="23"><div class="space-bottom8 col6 pad2x prose clip" data-reactid="24"><h3 id="answer-a-question">Answer a question</h3> <p>Answer a given question.</p> </div><div class="space-bottom4 col6 pad2 prose clip fill-light space-top5" data-reactid="25"><div class='endpoint dark fill-dark round '> <div class='round-left pad0y pad1x fill-lighten0 code small endpoint-method'>POST</div> <div class='pad0 code small endpoint-url'>/pcas/v1/questions/<span class="strong">{question}</span>/answer</div> </div> <h4 id="example-request-2">Example request</h4> <pre class='hljs'>curl -X POST https://pocket-consumption-adviser.com/pcas/v1/{question}/answer \ -X PUT \ -d @file.json</pre> <h4 id="example-request-body">Example request body</h4> <pre class='hljs'>{ <span class="hljs-attr">"answer"</span>: <span class="hljs-string">"yes"</span> }</pre> <h4 id="example-response-2">Example response</h4> <pre class='hljs'>{ <span class="hljs-attr">"concerned"</span>: <span class="hljs-string">"{user}"</span>, <span class="hljs-attr">"question"</span>: <span class="hljs-string">"{question_id}"</span>, <span class="hljs-attr">"answer"</span>: <span class="hljs-string">"yes"</span>, <span class="hljs-attr">"created"</span>: <span class="hljs-string">"{timestamp}"</span> }</pre> </div></div></div></div></div><div class="fixed-top space-left16" data-reactid="26"><div class="events fill-light bottom-shadow pad1 col6 pin-topright " data-reactid="27"><div class="space-right1 small quiet inline" data-reactid="28">Show examples in:</div><div class="rounded-toggle inline short" data-reactid="29"><a class="strong active" data-reactid="30">cURL</a><a class="strong " data-reactid="31">cli</a><a class="strong " data-reactid="32">Python</a><a class="strong " data-reactid="33">JS</a><a class="strong " data-reactid="34">Java</a><a class="strong " data-reactid="35">ObjC</a><a class="strong " data-reactid="36">Swift</a></div><div class="fr pad0" data-reactid="37"><a title="Display as 1 column" style="cursor:pointer;" class="icon quiet caret-left pad0 fill-darken0 round" data-reactid="38"></a></div></div></div><div class="fill-dark dark bottom-shadow fixed-top pad0 width16" data-reactid="39"><a href="/" class="active space-top1 space-left1 pin-topleft icon round dark pad0 fill-red" data-reactid="40"></a><div class="strong small pad0 space-left4 line-height15" data-reactid="41">Pocket Consumption Adviser API doc</div></div></div></div><!--STOP--> <script src='bundle.js'></script> </body> </html> <file_sep>/pcaservice/kernel/recommendation_system.py import pandas as pd import random import numpy as np from sklearn import linear_model class recommendationSystem: def __init__(self, data_input, nrows): self.dataSet = self.generateDataSet(data_input, nrows) self.model = self.recommendationModel() def readCSVFile(self, csv_file, nrows): """ reads a CSV file in a pandas dataframe and adds ClientID :param csv_file: input data :param nrows: the max rows to read :return: a pandas dataframe """ data = pd.read_csv(csv_file, sep=";", nrows=nrows) output_data = {"AreaId": [], "Receipt": [], "TransactionDate": [], "EAN": [], "Quantity": []} # convert str to integers for index, row in data.iterrows(): for key in output_data: if key != "Quantity": output_data[key].append(row[key]) else: output_data[key].append(int(row["Quantity"].split(',')[0])) customers = [random.randrange(10, 20, 1) for i in range(nrows)] output_data["ClientID"] = customers return pd.DataFrame(output_data) def generateDataSet(self, csv_file, nLines): """ Generate a wast Food dataset :param csv_file: data set from K Group :param nLines: maximum lines to read from the csv file :return: a pandas dataframe that addes randomly a customer ID and a lost quantity """ input_data = self.readCSVFile(csv_file, nLines) data = [] for index, row in input_data.iterrows(): lostFood = int(row["Quantity"]) - random.randrange(0, 2, 1) if lostFood < 0: lostFood = 0 data.append(lostFood) input_data["LostQuantity"] = data return input_data def recommendationModel(self): """ A Multi-Creteria regression model :return: a multicretaria regression model [clientID, Product , quantity ] vs lost quantit """ dataframe = self.dataSet x = dataframe[['ClientID', 'EAN', 'Quantity']] y = dataframe['LostQuantity'] regr = linear_model.LinearRegression() regr.fit(x, y) return regr def recommendationPredictionBySet(self, csv_file, nrows): """ Predict the lost quantity for a given Client, Product :param csv_file: input data :param nrows: max lines to read from file :return: a recommendation """ model = self.model df = self.readCSVFile(csv_file, nrows) return model.predict(df[['ClientID', 'EAN', 'Quantity']]) def recommendationPredictionByVector(self, ClientID, EAN, quantity, model): """ Predict the lost quantity for a given Client, Product :param csv_file: input data :param model: the regression model :return: a recommendation """ vector = [[ClientID, EAN, quantity]] waste = model.predict(vector) effectve_use = int(quantity - waste[0]) if effectve_use > 0: meg = "It's better to take " + str(effectve_use) + " of " + str(EAN) + "so you waste less" else : meg = "it's better to not purshase this product" return meg print("Test 1") csv_model = "Data/Junction_data_sample.csv" csv_pred = "Data/Junction_data_sample.csv" recom = recommendationSystem(csv_model, 50) print("dataset generated") reg = recom.recommendationModel() print("model generated") pred = recom.recommendationPredictionBySet(csv_pred, 10) print("prediction :") print(pred) print("Test 2") pred = recom.recommendationPredictionByVector(19,6413600017523, 4,reg) print(pred)
0e9c99e5233eb00db67961477fcda0c23b833c3c
[ "Markdown", "Python", "HTML" ]
9
Python
MillissaESi/PocketConsumptionAdviser
2442fcba467f1a1041adcc9cb601a0f170a4e388
0c026da46bb640ab07aae7ba07fcae1591bb56b7
refs/heads/master
<repo_name>cschambers2101/fezhat<file_sep>/fezhat/MainPage.xaml.cs using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; using GIS = GHIElectronics.UWP.Shields; using GHIElectronics.UWP.LowLevelDrivers; using Windows.Devices.Gpio; using Windows.Devices.I2c; using Windows.Devices.Enumeration; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace fezhat { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> /// public sealed partial class MainPage : Page { private enum Channel { Light = 5, Temperature = 4 } public MainPage() { this.InitializeComponent(); setupFezHat(); } private async void setupFezHat() { string I2cDeviceName = "I2C1"; ADS7830 analog = null; PCA9685 pwm = null; var gpioController = GpioController.GetDefault(); var i2cController = (await DeviceInformation.FindAllAsync(I2cDevice.GetDeviceSelector(I2cDeviceName)))[0]; analog = new ADS7830(await I2cDevice.FromIdAsync(i2cController.Id, new I2cConnectionSettings(ADS7830.GetAddress(false, false)))); pwm = new PCA9685(await I2cDevice.FromIdAsync(i2cController.Id, new I2cConnectionSettings(PCA9685.GetAddress(true, true, true, true, true, true))), gpioController.OpenPin(13)); pwm.OutputEnabled = true; pwm.Frequency = 1500; while (true) { double lightLevel = (analog.Read((int)Channel.Light)); double reverseLightLevel = (1 - lightLevel); //hat.D2 = new RgbLed(hat.pwm, 1, 0, 2); pwm.SetDutyCycle(1, reverseLightLevel); //Red pwm.SetDutyCycle(0, reverseLightLevel); //Green pwm.SetDutyCycle(2, reverseLightLevel); //Blue } //hat.D3 = new RgbLed(hat.pwm, 4, 3, 15); } } }
01b616e4dcc3d1ae9cc456493eedb7a55ab5f9d8
[ "C#" ]
1
C#
cschambers2101/fezhat
d1707b6b68addd8ea16bb73b34268b3ab9afe15d
13dc2d5eee8d506b25879b3670337bc6fe9802a8
refs/heads/master
<repo_name>matimarecki/UserIdentityProject<file_sep>/Areas/FileExplorerAdmin/Services/FolderService.cs using System; using System.Collections.Generic; using System.Linq; using Microsoft.EntityFrameworkCore; using UserIdentityProject.Areas.FileExplorerAdmin.Models; using UserIdentityProject.Data; namespace UserIdentityProject.Areas.FileExplorerAdmin.Services { public interface IFolderService { public void AddFolder(FolderModel newFolder); public void CleanseEverything(); public void RemoveFolder (int folderId); public void EditFolder(FolderModel editedFolder); public FolderModel GetRootFolder(); public int CountMyFolders(); public List<FolderModel> ShowAllFolders(); public List<FolderModel> ShowFolders(int parentFolder); public FolderModel GetSpecificFolder(int thatFolderId); public List<FolderModel> ShowPathToFolder(int currentId); } public class FolderService : IFolderService { private readonly ApplicationDbContext _dbContext; public FolderService (ApplicationDbContext dbContext) { this._dbContext = dbContext; } public void AddFolder(FolderModel newFolder) { this._dbContext.Folders.Add(newFolder); this._dbContext.SaveChanges(); } public void CleanseEverything() { foreach (var target in this._dbContext.Folders) { this._dbContext.Folders.Remove(target); } this._dbContext.SaveChanges(); } public void RemoveFolder(int folderId) { FolderModel deletedFolder = this._dbContext.Folders .FirstOrDefault(n => n.Id == folderId); this._dbContext.Folders.Remove(deletedFolder); this._dbContext.SaveChanges(); } public void EditFolder(FolderModel editedFolder) { var result = this._dbContext.Folders .SingleOrDefault(n => n.Id == editedFolder.Id); if (result != null) { Console.WriteLine(result.FolderName); this._dbContext.Entry(result).CurrentValues.SetValues(editedFolder); Console.WriteLine(result.FolderName); this._dbContext.SaveChanges(); } } public FolderModel GetRootFolder() { return this._dbContext.Folders .OrderBy(n=> n.Id) .FirstOrDefault(); } public FolderModel GetSpecificFolder(int thatFolderId) { return this._dbContext.Folders .Include(n => n.Parent) .FirstOrDefault(n => n.Id == thatFolderId); } public int CountMyFolders() { return this._dbContext.Folders.Count(); } public List<FolderModel> ShowAllFolders() { return this._dbContext.Folders.ToList(); } public List<FolderModel> ShowFolders(int parentFolderId) { if (parentFolderId == 0) { return this._dbContext.Folders .Include(n => n.Parent) .Where(n => n.ParentId == null).ToList(); } return this._dbContext.Folders .Include(n => n.Parent) .Where(n => n.Parent.Id == parentFolderId).ToList(); } public List<FolderModel> ShowPathToFolder(int currentId) { FolderModel inspectingFolder = this.GetSpecificFolder(currentId); if (currentId == 0) { return new List<FolderModel>(); } if (inspectingFolder.ParentId == null) { List<FolderModel> firstReturning = new List<FolderModel>(); firstReturning.Add(inspectingFolder); return firstReturning; } else { List<FolderModel> pathReturning = ShowPathToFolder(inspectingFolder.Parent.Id); pathReturning.Add(inspectingFolder); return pathReturning; } } } }<file_sep>/Areas/FileExplorerUser/Models/FileUploaderModel.cs using System; using System.ComponentModel.DataAnnotations.Schema; namespace UserIdentityProject.Areas.FileExplorerUser.Models { public class FileUploaderModel { public string Path { get; set; } public string Name { get; set; } public int? FatherId { get; set; } public DateTime DateCreated { get; set; } [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } } }<file_sep>/Migrations/20210929073547_Optional Password for Folders.cs using Microsoft.EntityFrameworkCore.Migrations; namespace UserIdentityProject.Migrations { public partial class OptionalPasswordforFolders : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<string>( name: "OptionalPassword", schema: "Identity", table: "Folders", type: "TEXT", nullable: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "OptionalPassword", schema: "Identity", table: "Folders"); } } } <file_sep>/Areas/FileExplorerAdmin/Models/FileExplorerFolderModel.cs using System.Collections.Generic; namespace UserIdentityProject.Areas.FileExplorerAdmin.Models { public class FileExplorerFolderModel { public List <FolderModel> GivenFolderList { get; set; } public List <FolderModel> PathFolderList { get; set; } public int CurrParentFolder { get; set; } } }<file_sep>/wwwroot/js/dragndrop.js const dropArea = document.querySelector(".drag-area"), dragText = dropArea.querySelector("header"), button = dropArea.querySelector("button"), theImage = dropArea.querySelector("img"), theFather = dropArea.querySelector("#fatherNumber"), GogoButton = dropArea.querySelector("#getMeThisFile"), input = dropArea.querySelector("#fileInput"); let file; var formData = new FormData(); GogoButton.onclick = () => { formData.set("fatherId", theFather.value); if (formData.getAll("fileInput").length === 0){ console.log("select a freaking file, mon") } else { var url = "FileExplorerUser/Upload"; console.log(url); var request = new XMLHttpRequest(); request.open("POST", url); request.send(formData); request.onload = function (){ window.location.reload(); } } // window.location.reload(); } button.onclick = ()=>{ input.click(); } input.addEventListener("change", function(){ file = this.files[0]; dropArea.classList.add("active"); formData.set("fileInput", file); showFile(); }); dropArea.addEventListener("dragover", (event)=>{ dropArea.classList.add("active"); dragText.textContent = "Release to Upload File"; event.preventDefault(); }); dropArea.addEventListener("dragleave", ()=>{ dropArea.classList.remove("active"); dragText.textContent = "Drag & Drop to Upload File"; }); dropArea.addEventListener("drop", (event)=>{ file = event.dataTransfer.files[0]; formData.set("fileInput", file); showFile(); event.preventDefault(); }); function showFile(){ let fileType = file.type; let validExtensions = ["image/jpeg", "image/jpg", "image/png"]; if(validExtensions.includes(fileType)){ let fileReader = new FileReader(); fileReader.onload = ()=>{ let fileURL = fileReader.result; document.getElementById("fileShower").setAttribute("src", fileURL) document.getElementById("fileShower").setAttribute("alt", "image") let imgTag = `<img src="${fileURL}" alt="image">`; theImage.innerHTML = imgTag; } fileReader.readAsDataURL(file); } else{ alert("This is not an Image File!"); dropArea.classList.remove("active"); dragText.textContent = "Drag & Drop to Upload File"; } }<file_sep>/Areas/FileExplorerUser/Services/UserFolderService.cs using System; using System.Collections.Generic; using System.Linq; using Microsoft.EntityFrameworkCore; using UserIdentityProject.Areas.FileExplorerAdmin.Models; using UserIdentityProject.Data; namespace UserIdentityProject.Areas.FileExplorerUser.Services { public interface IUserFolderService { public FolderModel GetRootFolder(); public int CountMyFolders(); public List<FolderModel> ShowAllFolders(); public List<FolderModel> ShowFolders(int parentFolder); public FolderModel GetSpecificFolder(int thatFolderId); public List<FolderModel> ShowPathToFolder(int currentId); } public class UserFolderService : IUserFolderService { private readonly ApplicationDbContext _dbContext; public UserFolderService (ApplicationDbContext dbContext) { this._dbContext = dbContext; } public FolderModel GetRootFolder() { return this._dbContext.Folders .OrderBy(n=> n.Id) .FirstOrDefault(); } public FolderModel GetSpecificFolder(int thatFolderId) { return this._dbContext.Folders .Include(n => n.Parent) .FirstOrDefault(n => n.Id == thatFolderId); } public int CountMyFolders() { return this._dbContext.Folders.Count(); } public List<FolderModel> ShowAllFolders() { return this._dbContext.Folders.ToList(); } public List<FolderModel> ShowFolders(int parentFolderId) { if (parentFolderId == 0) { return this._dbContext.Folders .Include(n => n.Parent) .Where(n => n.ParentId == null) // .Where(n => n.Accessibility == "Public") .ToList(); } return this._dbContext.Folders .Include(n => n.Parent) .Where(n => n.Parent.Id == parentFolderId) // .Where(n => n.Accessibility == "Public") .ToList(); } public List<FolderModel> ShowPathToFolder(int currentId) { FolderModel inspectingFolder = this.GetSpecificFolder(currentId); if (currentId == 0) { return new List<FolderModel>(); } if (inspectingFolder.ParentId == null) { List<FolderModel> firstReturning = new List<FolderModel>(); firstReturning.Add(inspectingFolder); return firstReturning; } else { List<FolderModel> pathReturning = ShowPathToFolder(inspectingFolder.Parent.Id); pathReturning.Add(inspectingFolder); return pathReturning; } } } }<file_sep>/Areas/FileExplorerAdmin/Controllers/HomeController.cs using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Web; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore.Metadata.Internal; using UserIdentityProject.Areas.FileExplorerAdmin.Models; using UserIdentityProject.Areas.FileExplorerAdmin.Services; using UserIdentityProject.Enums; namespace UserIdentityProject.Areas.FileExplorerAdmin.Controllers{ [Area("FileExplorerAdmin")] [Route("FileExplorerAdmin")] [Authorize(Roles="SuperAdmin,Admin,Moderator")] public class HomeController : Controller { private readonly IFolderService _service; public string MyAccessLevel; public HomeController (IFolderService service) { this._service = service; } public IActionResult Index(int currId = 0) { FileExplorerFolderModel fileExplorer = new FileExplorerFolderModel(); fileExplorer.GivenFolderList = this._service.ShowFolders(currId); fileExplorer.CurrParentFolder = currId; fileExplorer.PathFolderList = this._service.ShowPathToFolder(currId); return View("Index",fileExplorer); } [Route("FolderAdder")] public IActionResult FolderAdder(int papaFolderId) { return View(papaFolderId); } [Route("FolderEditor")] public IActionResult FolderEditor(int editedFolderId) { FolderModel inspectedFolder = this._service.GetSpecificFolder(editedFolderId); return View(inspectedFolder); } [Route("EditFolder")] public IActionResult EditFolder(FolderModel editedFolder) { FolderModel helperFolderModel = this._service.GetSpecificFolder(editedFolder.Id); helperFolderModel.FolderName = editedFolder.FolderName; helperFolderModel.Accessibility = editedFolder.Accessibility; helperFolderModel.OptionalPassword = editedFolder.OptionalPassword; this._service.EditFolder(helperFolderModel); Console.WriteLine(helperFolderModel.ParentId); return RedirectToAction("Index", new{currId = helperFolderModel.ParentId}); } [HttpPost] [Route("AddFolder")] public IActionResult AddFolder(string folderName, string accessibility, int parentId, string optionalPassword) { FolderModel addedFolder = new FolderModel(); if (parentId == 0) { addedFolder.Parent = null; addedFolder.ParentId = null; } else { addedFolder.Parent = this._service.GetSpecificFolder(parentId); addedFolder.ParentId = parentId; } addedFolder.OptionalPassword = <PASSWORD>; addedFolder.Accessibility = accessibility; addedFolder.DateCreated = DateTime.Now; addedFolder.FolderName = folderName; this._service.AddFolder(addedFolder); return RedirectToAction("Index", new {currId = parentId}); } [Route("MoveUpOneFolder")] public IActionResult MoveUpOneFolder(int currentId) { if (currentId == 0) { return RedirectToAction("Index"); } if (this._service.GetSpecificFolder(currentId).ParentId == null) { return RedirectToAction("Index"); } int currFatherId = (int)this._service.GetSpecificFolder(currentId).ParentId; Console.WriteLine(currFatherId); return RedirectToAction("Index", new{currId = currFatherId}); } [Route("CleanseEverything")] public IActionResult CleanseEverything() { this._service.CleanseEverything(); return RedirectToAction("Index"); } [Route("MoveDownToFolder")] public IActionResult MoveDownToFolder(int currentId, string givenPassword) { if (givenPassword == this._service.GetSpecificFolder(currentId).OptionalPassword) { return RedirectToAction("Index", new {currId = currentId}); } else { return RedirectToAction("Index", new {currId = this._service.GetSpecificFolder(currentId).ParentId}); } } [Route("RemoveFolder")] public IActionResult RemoveFolder(int folderId, int fatherId) { if (this._service.ShowFolders(folderId).Count == 0) { this._service.RemoveFolder(folderId); return RedirectToAction("Index", new{currId = fatherId}); } else { Console.WriteLine("Element still contains other Folders, please make sure the element is empty"); return RedirectToAction("Index", new{currId = fatherId}); } } [Route("ShowPath")] public IActionResult ShowPath(int currentId) { List<FolderModel> pathList = this._service.ShowPathToFolder(currentId); foreach (var pathFolder in pathList) { Console.WriteLine(pathFolder.FolderName); } return RedirectToAction("Index", new {currId = currentId}); } } }<file_sep>/Areas/FileExplorerUser/Services/UserFileService.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using UserIdentityProject.Areas.FileExplorerUser.Models; using UserIdentityProject.Data; namespace UserIdentityProject.Areas.FileExplorerUser.Services { public interface IUserFileService { public List<FileUploaderModel> ReturnFilesInFolder(int fatherId); public void AddFileToFolder(int fatherId, IFormFile file); public void RemoveFile(int fileId); } public class UserFileService : IUserFileService { private IWebHostEnvironment _webHostEnvironment; private readonly ApplicationDbContext _dbContext; public UserFileService(ApplicationDbContext dbContext, IWebHostEnvironment webHostEnvironment) { this._dbContext = dbContext; this._webHostEnvironment = webHostEnvironment; } public List<FileUploaderModel> ReturnFilesInFolder(int fatherId) { List<FileUploaderModel> filesInFolder = new List<FileUploaderModel>(); if (fatherId == 0) { filesInFolder = this._dbContext.FilesUploaded .Where(n => n.FatherId == 0) .ToList(); } else { filesInFolder = this._dbContext.FilesUploaded .Where(n => n.FatherId == fatherId) .ToList(); } return filesInFolder; } public void RemoveFile(int fileId) { FileUploaderModel thatFile = this._dbContext.FilesUploaded .SingleOrDefault(n => n.Id == fileId); File.Delete(thatFile.Path); this._dbContext.FilesUploaded.Remove(thatFile); this._dbContext.SaveChanges(); } public void AddFileToFolder(int fatherId, IFormFile file) { string uploads = Path.Combine(this._webHostEnvironment.WebRootPath, "Uploads"); FileUploaderModel newFile = new FileUploaderModel(); if (file.Length > 0) { string filePath = Path.GetFileName(file.FileName); Console.WriteLine(Path.Combine(uploads, filePath)); newFile.Path = Path.Combine(uploads, filePath); newFile.Name = file.FileName; newFile.DateCreated = new DateTime(); newFile.FatherId = fatherId; this._dbContext.Add(newFile); this._dbContext.SaveChanges(); using (FileStream stream = new FileStream(Path.Combine(uploads, filePath), FileMode.Create)) { file.CopyTo(stream); } } } } }<file_sep>/Areas/FileExplorerAdmin/Models/FolderModel.cs using System; using System.ComponentModel.DataAnnotations.Schema; using Microsoft.EntityFrameworkCore; namespace UserIdentityProject.Areas.FileExplorerAdmin.Models { public class FolderModel { public FolderModel? Parent { get; set; } public int? ParentId { get; set; } public string FolderName { get; set; } public DateTime DateCreated { get; set; } public string Accessibility { get; set; } public string OptionalPassword { get; set; } [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } } }<file_sep>/Areas/FileExplorerAdmin/Services/FileExplorerPathingService.cs using System; using System.Collections.Generic; using Microsoft.Extensions.DependencyModel; using UserIdentityProject.Areas.FileExplorerAdmin.Models; namespace UserIdentityProject.Areas.FileExplorerAdmin.Services { public interface IFileExplorerPathingService { public int CurrentId(); public void ChangeCurrId(int newCurrId); public List<FolderModel> ShowCurrentPath (); public void AddFolderToCurrentPath(FolderModel newFolder); public void RemoveFolderFromCurrentPath (FolderModel yeetFolder); } public class FileExplorerPathingService : IFileExplorerPathingService { private int _currParentId; private List<FolderModel> _currPathList; public FileExplorerPathingService() { this._currPathList = new List<FolderModel>(); } public int CurrentId() { return _currParentId; } public void ChangeCurrId(int newCurrId) { this._currParentId = newCurrId; } public List<FolderModel> ShowCurrentPath() { return this._currPathList; } public void AddFolderToCurrentPath(FolderModel newFolder) { this._currPathList.Add(newFolder); } public void RemoveFolderFromCurrentPath(FolderModel yeetFolder) { this._currPathList.Remove(yeetFolder); } } }<file_sep>/Areas/FileExplorerUser/Models/FileExplorerUserModel.cs using System.Collections.Generic; using UserIdentityProject.Areas.FileExplorerAdmin.Models; namespace UserIdentityProject.Areas.FileExplorerUser.Models { public class FileExplorerUserModel { public FileExplorerFolderModel TheFolders { get; set; } public List<FileUploaderModel> TheFiles { get; set; } } }<file_sep>/Areas/FileExplorerUser/Controllers/HomeController.cs using System; using System.Collections.Generic; using System.IO; using System.IO.Enumeration; using System.Linq; using System.Security.Principal; using System.Threading.Tasks; using Microsoft.AspNetCore.Components.Web; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Hosting; using UserIdentityProject.Areas.FileExplorerAdmin.Models; using UserIdentityProject.Areas.FileExplorerAdmin.Services; using UserIdentityProject.Areas.FileExplorerUser.Models; using UserIdentityProject.Areas.FileExplorerUser.Services; namespace UserIdentityProject.Areas.FileExplorerUser.Controllers { [Area("FileExplorerUser")] [Route("FileExplorerUser")] public class HomeController : Controller { private readonly IUserFolderService _service; private IWebHostEnvironment _webHostEnvironment; private readonly IUserFileService _fileService; public HomeController(IUserFolderService service, IWebHostEnvironment webHostEnvironment, IUserFileService fileService) { this._fileService = fileService; this._service = service; this._webHostEnvironment = webHostEnvironment; } public IActionResult Index(int currId = 0) { List<FileUploaderModel> daFilez = this._fileService.ReturnFilesInFolder(currId); FileExplorerFolderModel fileExplorer = new FileExplorerFolderModel(); FileExplorerUserModel fullSet = new FileExplorerUserModel(); fullSet.TheFiles = daFilez; fileExplorer.GivenFolderList = this._service.ShowFolders(currId); fileExplorer.CurrParentFolder = currId; fileExplorer.PathFolderList = this._service.ShowPathToFolder(currId); fullSet.TheFolders = fileExplorer; return View("Index", fullSet); } [HttpPost] [Route("Upload")] public IActionResult Upload(IFormFile fileInput, int fatherId) { string uploads = Path.Combine(this._webHostEnvironment.WebRootPath, "Uploads"); if (!Directory.Exists(uploads)) { Directory.CreateDirectory(uploads); } Console.WriteLine(fileInput.Name); this._fileService.AddFileToFolder(fatherId, fileInput); return RedirectToAction("Index", new{currId = fatherId}); } [Route("MoveUpOneFolder")] public IActionResult MoveUpOneFolder(int currentId) { if (currentId == 0) { return RedirectToAction("Index"); } if (this._service.GetSpecificFolder(currentId).ParentId == null) { return RedirectToAction("Index"); } int currFatherId = (int) this._service.GetSpecificFolder(currentId).ParentId; Console.WriteLine(currFatherId); return RedirectToAction("Index", new {currId = currFatherId}); } [Route("MoveDownToFolder")] public IActionResult MoveDownToFolder(int currentId, string givenPassword) { if (givenPassword == this._service.GetSpecificFolder(currentId).OptionalPassword) { return RedirectToAction("Index", new {currId = currentId}); } else { return RedirectToAction("Index", new {currId = this._service.GetSpecificFolder(currentId).ParentId}); } } [Route("ShowPath")] public IActionResult ShowPath(int currentId) { List<FolderModel> pathList = this._service.ShowPathToFolder(currentId); foreach (var pathFolder in pathList) { Console.WriteLine(pathFolder.FolderName); } return RedirectToAction("Index", new {currId = currentId}); } [Route("CreateNewFile")] public IActionResult CreateNewFile(int fatherId,IFormFile stream) { Console.WriteLine(stream.ContentType); return RedirectToAction("Index", fatherId); } [Route("DelteFile")] public IActionResult DelteFile(int fatherId, int deltedId) { this._fileService.RemoveFile(deltedId); return RedirectToAction("Index", new {currId = fatherId}); } [Route("DownloadFile")] public FileResult DownloadFile(string fileName) { string path = Path.Combine(this._webHostEnvironment.WebRootPath, "Uploads/") + fileName; byte[] bytes = System.IO.File.ReadAllBytes(path); return File(bytes, "appliation/octet-stream", fileName); } } }
18ee6241abd600d600d655746497a484614a1b9b
[ "JavaScript", "C#" ]
12
C#
matimarecki/UserIdentityProject
2d748d6bf2c99d05721220fbbd36cd1d864d5354
cafc0907a5901addad21c7d79d77cbb483accc77
refs/heads/main
<file_sep><?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * PoodLL Anywhere settings. * * @package atto_poodll * @copyright 2014 <NAME> {@link http://www.poodll.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $ADMIN->add('editoratto', new admin_category('atto_gdrivevideos', new lang_string('pluginname', 'atto_gdrivevideos'))); $settings = new admin_settingpage('atto_gdrivevideos_settings', new lang_string('settings', 'atto_gdrivevideos')); if ($ADMIN->fulltree) { //A customizable editor icon for Generico $name = 'atto_gdrivevideos/editoricon'; $title =get_string('editoricon', 'atto_gdrivevideos'); $description = get_string('editoricon_desc', 'atto_gdrivevideos'); $settings->add(new admin_setting_configstoredfile($name, $title, $description, 'editoricon')); } <file_sep># Moodle Atto Plugin for Google Drive Videos Insertion This is a plugin that allows to embed a video from google drive directly in the Atto Editor. The main features are: * Videos are embedded in the moodle page. * Visualization of videos is responsive to screen size. Yet, you can configure the maximum size of video. * Some sanitizing checks are carried out on the video URL provided, to avoid security problems. * In case that the video is not ## Installation Follow these steps to install and configure the plugin: 1. Download the zip bundle from https://github.com/gmacia/moodle-atto_gdrivevideos 2. In your moodle installation (admin account), go to `Site administration / plugins / Install plugins / Install plugin from ZIP file`. 3. Follow the installation instructions and check that there are no errors. 4. Configure the icon button to be shown in atto editor. * Go to `Site Administration / plugins / Atto toolbar settings`. * Go to `toolbar config` at the end of the list of plugins. * Insert the `gdrivevideos` icon in the group that you desire it to be shown. E.g., You can insert in the group of links, so it becomes: `links = link, gdrivevideos`. ## How to use * Step 1. Get a sharing link for your video in google drive. * Step 2. Just use the gdrivevideos icon button in the atto editor and complete the form. You will see how the video is automatically embedded. * Step 3. In case that the sharing of the video is restricted to certain users or group, you must log in to google to visualize it. ## To do In order to publish as a moodle official plugin some things are needed: * Review strings to include both english and spanish strings. * Modify code to take all the strings from atto_gdrivevideos.php strings file. * Review and pulish code. <file_sep><?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Atto text editor integration version file. * * @package atto_gdrivevideos * @copyright COPYRIGHTINFO * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); define('ATTO_GDRIVEVIDEOS_CUSTOMICON_FILEAREA', 'editoricon'); /** * Initialise this plugin * @param string $elementid */ function atto_gdrivevideos_strings_for_js() { global $PAGE; $PAGE->requires->strings_for_js(array('insert', 'cancel', 'chooseinsert', 'fieldsheader', 'nofieldsheader', 'dialogtitle'), 'atto_gdrivevideos'); } /** * Return the js params required for this module. * @return array of additional params to pass to javascript init function for this module. */ function atto_gdrivevideos_params_for_js($elementid, $options, $fpoptions) { global $USER, $COURSE; $config = get_config('atto_gdrivevideos'); //coursecontext $coursecontext = context_course::instance($COURSE->id); //gdrivevideos specific $templates = get_object_vars(get_config('filter_gdrivevideos')); $instructions = array(); $keys = array(); $names = array(); $variables = array(); $defaults = array(); $ends = array(); //get the no. of templates if (!array_key_exists('templatecount', $templates)) { $templatecount = 21; } else { $templatecount = $templates['templatecount'] + 1; } //put our template into a form thats easy to process in JS for ($tempindex = 1; $tempindex < $templatecount; $tempindex++) { if (empty($templates['template_' . $tempindex]) && empty($templates['templatescript_' . $tempindex]) && empty($templates['templatestyle_' . $tempindex]) ) { continue; } //stash the key for this tempalte $keys[] = $templates['templatekey_' . $tempindex]; //stash the name for this template $usename = trim($templates['templatename_' . $tempindex]); if($usename==''){ $names[] = $templates['templatekey_' . $tempindex]; }else{ $names[]=$usename; } //instructions //stash the instructions for this template $instructions[] = rawurlencode($templates['templateinstructions_' . $tempindex]); //NB each of the $allvariables contains an array of variables (not a string) //there might be duplicates where the variable is used multiple times in a template //se we uniqu'ify it. That makes it look complicated. But we are just removing doubles $allvariables = atto_gdrivevideos_fetch_variables($templates['template_' . $tempindex] . $templates['templatescript_' . $tempindex] . $templates['datasetvars_' . $tempindex]); $uniquevariables = array_unique($allvariables); $usevariables = array(); //we need to reallocate array keys if the array size was changed in unique'ifying it //we also take the opportunity to remove user variables, since they aren't needed here. //NB DATASET can be referred to without the : while (count($uniquevariables) > 0) { $tempvar = array_shift($uniquevariables); if (strpos($tempvar, 'COURSE:') === false && strpos($tempvar, 'USER:') === false && strpos($tempvar, 'DATASET:') === false && strpos($tempvar, 'URLPARAM:') === false && $tempvar != 'MOODLEPAGEID' && $tempvar != 'WWWROOT' && $tempvar != 'AUTOID' && $tempvar != 'CLOUDPOODLLTOKEN') { $usevariables[] = $tempvar; } } $variables[] = $usevariables; //stash the defaults for this template //$defaults[] = $templates['templatedefaults_' . $tempindex]; $defaults[] = atto_gdrivevideos_fetch_filter_properties($templates['templatedefaults_' . $tempindex]); $ends[] = $templates['templateend_' . $tempindex]; } if ($config->editoricon) { $customicon = atto_gdrivevideos_custom_icon_url(); }else{ $customicon =false; } //config our array of data $params = array(); $params['customicon']=rawurlencode($customicon); $params['keys'] = $keys; $params['names'] = $names; $params['instructions'] = $instructions; $params['variables'] = $variables; $params['defaults'] = $defaults; $params['ends'] = $ends; //If they don't have permission don't show it $disabled = false; if(!has_capability('atto/gdrivevideos:visible', $coursecontext) ){ $disabled=true; } //add our disabled param $params['disabled'] = $disabled; return $params; } /** * Return an array of variable names * @param string template containing @@variable@@ variables * @return array of variable names parsed from template string */ function atto_gdrivevideos_fetch_variables($template){ $matches = array(); $t = preg_match_all('/@@(.*?)@@/s', $template, $matches); if(count($matches)>1){ return($matches[1]); }else{ return array(); } } function atto_gdrivevideos_fetch_filter_properties($propstring){ //Now we just have our properties string //Lets run our regular expression over them //string should be property=value,property=value //got this regexp from http://stackoverflow.com/questions/168171/regular-expression-for-parsing-name-value-pairs $regexpression='/([^=,]*)=("[^"]*"|[^,"]*)/'; $matches=array(); //here we match the filter string and split into name array (matches[1]) and value array (matches[2]) //we then add those to a name value array. $itemprops = array(); if (preg_match_all($regexpression, $propstring,$matches,PREG_PATTERN_ORDER)){ $propscount = count($matches[1]); for ($cnt =0; $cnt < $propscount; $cnt++){ // echo $matches[1][$cnt] . "=" . $matches[2][$cnt] . " "; $newvalue = $matches[2][$cnt]; //this could be done better, I am sure. WE are removing the quotes from start and end //this wil however remove multiple quotes id they exist at start and end. NG really $newvalue = trim($newvalue,'"'); $itemprops[trim($matches[1][$cnt])]=$newvalue; } } return $itemprops; } function atto_gdrivevideos_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options = array()) { if($filearea === 'editoricon') { return atto_gdrivevideos_setting_file_serve($filearea,$args,$forcedownload, $options); }else { send_file_not_found(); } } /** * Returns URL to the stored file via pluginfile.php. * * @param string $setting * @param string $filearea * @return string protocol relative URL or null if not present */ function atto_gdrivevideos_custom_icon_url() { global $CFG; $config = get_config('atto_gdrivevideos'); $component = 'atto_gdrivevideos'; $itemid = 0; $syscontext = context_system::instance(); $filearea = ATTO_GDRIVEVIDEOS_CUSTOMICON_FILEAREA; $filepath = $config->editoricon; $url = moodle_url::make_file_url("$CFG->wwwroot/pluginfile.php", "/$syscontext->id/$component/$filearea/$itemid".$filepath); return $url; } function atto_gdrivevideos_setting_file_serve($filearea, $args, $forcedownload, $options) { global $CFG; require_once("$CFG->libdir/filelib.php"); $syscontext = context_system::instance(); $component = 'atto_gdrivevideos'; $revision = array_shift($args); if ($revision < 0) { $lifetime = 0; } else { $lifetime = 60*60*24*60; } $fs = get_file_storage(); $relativepath = implode('/', $args); $fullpath = "/{$syscontext->id}/{$component}/{$filearea}/0/{$relativepath}"; $fullpath = rtrim($fullpath, '/'); if ($file = $fs->get_file_by_hash(sha1($fullpath))) { send_stored_file($file, $lifetime, 0, $forcedownload, $options); return true; } else { send_file_not_found(); } }
8a54c942c129256cd334517097823e5f38145c9c
[ "Markdown", "PHP" ]
3
PHP
gmacia/moodle-atto_gdrivevideos
884231d048de54821ad618cb7538a9b0db496ff2
65fc10d69ff0412f54318dd8119e71a955cbbdcf
refs/heads/master
<file_sep># Practice_3D_U-net this is my first attemption in GitHub, so i seed my first code in this. <file_sep>from network import Unet3d from dataset import NiiDataset from torchvision import transforms, utils from torch.utils.data import DataLoader from loss import SoftDiceLoss,dice_coeff import torch import os import sys import utility def train(net,epochs,batch_size,lr,mra_transforms,label_transforms): dir_imgs="./data/after_slice/copy/data/" dir_labels = "./data/after_slice/copy/seg/" dir_model="./model" utility.sureDir(dir_model) #load data dataset=NiiDataset(mra_dir=dir_imgs,label_dir=dir_labels, mra_transforms=mra_transforms, label_transforms=label_transforms) dataloader=DataLoader(dataset,batch_size=batch_size,shuffle=True,num_workers=4) #loss and optimizer criterion=SoftDiceLoss() optimizer=torch.optim.Adam(net.parameters(),lr=lr) #begin train for epoch in range(epochs): print('Starting epoch {}/{}.'.format(epoch + 1, epochs)) print('-' * 10) net.train() dt_size = len(dataloader.dataset) epoch_loss = 0 step = 0 for img,label in dataloader: step+=1 input = img.type(torch.FloatTensor).cuda() #因为前面已经为它们to tensor了 label = label.type(torch.FloatTensor).cuda().squeeze() # .long() # zero the parameter gradients optimizer.zero_grad() output=net(input) out = output[:,1, :, :, :].squeeze()#(75,64,64) print("dice: %0.3f " % dice_coeff(out, label)) loss=criterion(out,label) loss.backward() optimizer.step() epoch_loss+=float(loss.item()) print("%d/%d,train_loss:%0.3f" % (step, dt_size // dataloader.batch_size, loss.item())) print("epoch %d loss:%0.3f" % (epoch, epoch_loss / step)) torch.save(net.state_dict(),dir_model) if __name__ == '__main__': #parameters set # device=torch.device("cuda" if torch.cuda.is_available() else "cpu") epochs=100 batch_size=1 lr=0.001 x_transforms = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))]) y_transforms = transforms.ToTensor() net = Unet3d(in_ch=1,out_ch=2) net.cuda() try: train(net=net, epochs=epochs, batch_size=batch_size, lr=lr, mra_transforms=x_transforms, label_transforms=y_transforms) except KeyboardInterrupt: torch.save(net.state_dict(), 'INTERRUPTED.pth') print('Saved interrupt') try: sys.exit(0) except SystemExit: os._exit(0) <file_sep>from torch import nn import torch import torch.nn.functional as F # class MultiViewConv(nn.Module): # #用来实例化 # def __init__(self,in_ch,out_ch): # super(MultiViewConv, self).__init__() # self.conv_multiview=nn.Conv2d(in_channels=in_ch,out_channels=1,kernel_size=(3,3),stride=1,padding=1) # # self.conv_hc=nn.Conv2d(in_channels=w,out_channels=w,kernel_size=(3,3),stride=1,padding=1) # # self.conv_wc=nn.Conv2d(in_channels=h,out_channels=h,kernel_size=(3,3),stride=1,padding=1) # self.pointwise=nn.Conv3d(in_channels=3,out_channels=out_ch,kernel_size=1,stride=1) # #用来执行动作 # def forward(self,x): # x_hw=x # x_wd=x.permute([0,1,3,4,2]) #[p,c,w,d,h] # x_hd=x.permute([0,1,2,4,3]) #这个函数真让人纠结 [p,c,h,d,w] # out_hw=self.conv_multiview(x_hw) # out_wd=self.conv_multiview(x_wd) # out_hd=self.conv_multiview(x_hd) # # out_hw=out_hw # out_wd=out_wd.permute([0,1,4,2,3]) # out_hd=out_hd.permute([0,1,2,4,3]) # # out=torch.cat((out_hd,out_wd,out_hw),dim=3) # out=self.pointwise(out) # return out class DoubleConv(nn.Module): #类的结构 def __init__(self,in_ch,out_ch): super(DoubleConv, self).__init__() self.conv=nn.Sequential(nn.Conv3d(in_ch,out_ch,3,padding=1), nn.BatchNorm3d(out_ch), nn.ReLU(inplace=True), nn.Conv3d(out_ch,out_ch,3,padding=1), nn.BatchNorm3d(out_ch), nn.ReLU(inplace=True)) #类的动作 def forward(self,x): return self.conv(x) #赵改 # class DoubleConv(nn.Module): # #类的结构 # def __init__(self,in_ch,out_ch): # super(DoubleConv, self).__init__() # self.conv=nn.Sequential(MultiViewConv(in_ch,out_ch), # nn.BatchNorm3d(out_ch), # nn.ReLU(inplace=True), # MultiViewConv(in_ch,out_ch), # nn.BatchNorm3d(out_ch), # nn.ReLU(inplace=True)) # #类的动作 # def forward(self,x): # return self.conv(x) class Unet3d(nn.Module): def __init__(self,in_ch,out_ch): super(Unet3d, self).__init__() self.conv1 = DoubleConv(in_ch, 64) self.pool1 = nn.MaxPool3d(2) self.conv2 = DoubleConv(64, 128) self.pool2 = nn.MaxPool3d(2) self.conv3 = DoubleConv(128, 256) self.pool3 = nn.MaxPool3d(2) self.conv4 = DoubleConv(256, 512) self.pool4 = nn.MaxPool3d(2) self.conv5 = DoubleConv(512, 1024) self.up6 = nn.ConvTranspose3d(1024, 512, 2, stride=2) self.conv6 = DoubleConv(1024, 512) self.up7 = nn.ConvTranspose3d(512, 256, 2, stride=2) self.conv7 = DoubleConv(512, 256) self.up8 = nn.ConvTranspose3d(256, 128, 2, stride=2) self.conv8 = DoubleConv(256, 128) self.up9 = nn.ConvTranspose3d(128, 64, 2, stride=2) self.conv9 = DoubleConv(128, 64) self.conv10 = nn.Conv3d(64,out_ch, 1) def forward(self,x): c1=self.conv1(x) p1=self.pool1(c1) c2=self.conv2(p1) p2=self.pool2(c2) c3=self.conv3(p2) p3=self.pool3(c3) c4=self.conv4(p3) p4=self.pool4(c4) c5=self.conv5(p4) up_6= self.up6(c5) merge6 = torch.cat([up_6, c4], dim=1) c6=self.conv6(merge6) up_7=self.up7(c6) merge7 = torch.cat([up_7, c3], dim=1) c7=self.conv7(merge7) up_8=self.up8(c7) merge8 = torch.cat([up_8, c2], dim=1) c8=self.conv8(merge8) up_9=self.up9(c8) merge9=torch.cat([up_9,c1],dim=1) c9=self.conv9(merge9) c10=self.conv10(c9)#还需要一个softmax out = nn.ReLU()(c10) # out = nn.Softmax(dim=1)(out) # out= torch.max(F.softmax(out, dim=1), dim=1)[1] return out if __name__ == '__main__': net=Unet3d(1,2) print(net)<file_sep>import torch # 首先,新建一个三维的tensor a = torch.tensor([[[3, 3, 3], [3, 3, 3], [3, 3, 3], [3, 3, 3]]]) # 打印出它的形状,这里它的形状为(1,4,3) print(a.shape) # 对该tensor进行维度变换,根据我上面文字详细说的那样 b = a.permute(2, 0, 1) # 打印出变换后a的形状,形状变为(3,1,4) print(b.shape) # a.permute(2,0,1) # b=a.permute(2,0,1) # #打印出变换后a的形状 # print(b.shape) # print(a.permute(2,0,1).shape) <file_sep>import torch.nn as nn def dice_coeff(pred, target): smooth = 1. m1 = pred.flatten() # Flatten m2 = target.flatten() # Flatten intersection = (m1 * m2).sum() return (2. * intersection + smooth) / (m1.sum() + m2.sum() + smooth) class SoftDiceLoss(nn.Module): def __init__(self, weight=None, size_average=True): super(SoftDiceLoss, self).__init__() def forward(self, logits, targets): score = 1 - dice_coeff(logits, targets) return score<file_sep>from time import time import os import numpy as np import SimpleITK as sitk def sureDir(path): # only make new dir when not existing if not os.path.exists(path): os.makedirs(path) else: pass def data_block(): #原数据120*480*480 size = np.array([96, 96, 96]) # 取样的slice数量(patch厚度) stride =np.array([8,32,32]) # 取样的步长(4*13*13) # 用来记录产生的数据的序号 file_index = 0 # 用来统计最终剩下的slice数量 left_slice_list = [] start_time = time() for file in os.listdir("C:/Users/Sharm/Desktop/TF/cyk/dataset/rawdata/imagesTr/"): rowdata = sitk.ReadImage(os.path.join("C:/Users/Sharm/Desktop/TF/cyk/dataset/rawdata/imagesTr/", file), sitk.sitkInt16) rowdata_array = sitk.GetArrayFromImage(rowdata) # seg = sitk.ReadImage(os.path.join("C:/Users/Sharm/Desktop/TF/cyk/dataset/rawdata/labelsTr/", file.replace('data', 'seg')), sitk.sitkInt16) seg = sitk.ReadImage(os.path.join("C:/Users/Sharm/Desktop/TF/cyk/dataset/rawdata/labelsTr/", file), sitk.sitkInt16) seg_array = sitk.GetArrayFromImage(seg) seg_array[seg_array > 0] = 1 # 在轴向上按照一定的步长进行切块取样,并将结果保存为nii数据 start_slice = np.array([0, 0, 0]) end_slice = start_slice + size - 1 while end_slice[0] <= rowdata_array.shape[0] - 1: while end_slice[1] <= rowdata_array.shape[1] - 1: while end_slice[2] <= rowdata_array.shape[2] - 1: new_data_array = rowdata_array[start_slice[0]:end_slice[0] + 1, start_slice[1]:end_slice[1] + 1, start_slice[2]:end_slice[2] + 1] new_seg_array = seg_array[start_slice[0]:end_slice[0] + 1, start_slice[1]:end_slice[1] + 1, start_slice[2]:end_slice[2] + 1] new_mra = sitk.GetImageFromArray(new_data_array) new_mra.SetDirection(rowdata.GetDirection()) new_mra.SetOrigin(rowdata.GetOrigin()) new_mra.SetSpacing(rowdata.GetSpacing()) new_seg = sitk.GetImageFromArray(new_seg_array) new_seg.SetDirection(rowdata.GetDirection()) new_seg.SetOrigin(rowdata.GetOrigin()) new_seg.SetSpacing(rowdata.GetSpacing()) new_mra_name = 'data-' + str(file_index) + '.nii' new_seg_name = 'seg-' + str(file_index) + '.nii' sitk.WriteImage(new_mra, os.path.join("C:/Users/Sharm/Desktop/TF/cyk/dataset/after_slice/imagesTr/", new_mra_name)) sitk.WriteImage(new_seg, os.path.join("C:/Users/Sharm/Desktop/TF/cyk/dataset/after_slice/labelsTr/", new_seg_name)) file_index += 1 start_slice[2] += stride[2] end_slice[2] = start_slice[2] + size[2] - 1 start_slice[2] = 0 end_slice[2] = start_slice[2] + size[2] - 1 start_slice[1] += stride[1] end_slice[1] = start_slice[1] + size[1] - 1 start_slice[2] = 0 end_slice[2] = start_slice[2] + size[2] - 1 start_slice[1] = 0 end_slice[1] = start_slice[1] + size[1] - 1 start_slice[0] += stride[0] end_slice[0] = start_slice[0] + size[0] - 1 print(file_index) print('already use {:.3f} min'.format((time() - start_time) / 60)) print('-----------')<file_sep>""" 这个项目的代码应该是对于利用Pytorch进行网络训练的,最基础的版本了。 由赵志明写于2020年1月 """ from torch.utils.data import Dataset,DataLoader import os import torch import SimpleITK as sitk import numpy as np def get_files_list(mra_dir,seg_dir): imgs=[] masks=[] n=len(os.listdir(mra_dir)) #or file in os.listdir(root) for i in range(n): #for mra_file in os.listdir(mra_dir): img=os.path.join(mra_dir,"data-%d.nii"%i) imgs.append(img) #for seg_file in os.listdir(seg_dir): mask=os.path.join(seg_dir,"seg-%d.nii"%i) #img = os.path.join(root, file) #mask = os.path.join(root, file) masks.append(mask) return imgs,masks class NiiDataset(Dataset): def __init__(self,mra_dir,label_dir,mra_transforms=None,label_transforms=None): imgs,labels=get_files_list(mra_dir,label_dir) self.imgs=imgs self.labels=labels self.imgs_transforms=mra_transforms self.labels_transforms=label_transforms def __getitem__(self, index): x_path, y_path = self.imgs[index],self.labels[index] img_x = sitk.GetArrayFromImage(sitk.ReadImage(x_path, sitk.sitkInt16)).astype(np.float).transpose((1,2,0)) img_y = sitk.GetArrayFromImage(sitk.ReadImage(y_path, sitk.sitkInt16)).astype(np.float).transpose((1,2,0)) if self.imgs_transforms is not None: img_x=self.imgs_transforms(img_x) img_x=torch.unsqueeze(img_x,dim=0) if self.labels_transforms is not None: img_y=self.labels_transforms(img_y) return img_x,img_y def __len__(self): return len(self.imgs)
ef74d4889be1b43ada92e418b65ed6456dd818b9
[ "Markdown", "Python" ]
7
Markdown
Sharm-Zhao/Practice_3D_U-net
7640d7d8dd7e006811736dfddf6bd079dcd9b825
fa0348a1f9022a73373c8c7ef5ede0671dfff8e5
refs/heads/master
<repo_name>ittechsathish/angular-meteor-devcontrolpanel<file_sep>/source2/devcontrolpanel/imports/ui/components/user-profile-image-component/user-profile-image.component.ts //core import import {Component, Input, NgZone, OnInit, OnDestroy, OnChanges} from '@angular/core'; import {Meteor} from 'meteor/meteor'; //common import import {UserProfileUtils} from '../../../common/user-profile-util'; import {IUserProfile} from '../../../common/user-profile-model'; import {AppFactory} from '../../services/config.service'; import { AppComponent } from '../common/app-component'; import {GlobalEventSerice} from '../../services/global-event.service'; import template from './template/user-profile-image.template.html'; @Component({ selector: 'user-profile-image', template }) export class UserProfileImageComponent extends AppComponent implements OnInit, OnDestroy, OnChanges { private isUserImageAvailable: boolean = false; private userImageUrl: string = ''; private userIdSetted: string = null; userProfileWatchHandle: Meteor.LiveQueryHandle = null; constructor( appFactory: AppFactory, ngZone: NgZone, globalEventSerice: GlobalEventSerice) { super(appFactory, globalEventSerice, ngZone); } userProfileChangeCallback(userCursor: Mongo.Cursor<Meteor.User>): void { this.isUserImageAvailable = false; this.userImageUrl = ''; let user = userCursor.fetch(); let userTaken: Meteor.User; if (user && user.length > 0) { userTaken = user[0]; } if (userTaken) { let userProfile: IUserProfile = UserProfileUtils.getUserProfileValues(userTaken); if (userProfile && userProfile.profileImageURL) { if(this.ngZone) { this.ngZone.run(() => { this.userImageUrl = userProfile.profileImageURL; this.isUserImageAvailable = true; }); } } } }; attachUserProfileWatcher() { let userCursor: Mongo.Cursor<Meteor.User> = Meteor.users.find({ _id: this.userIdSetted }); this.userProfileWatchHandle = userCursor.observeChanges({ added: (id, records) => { this.userProfileChangeCallback(userCursor); }, changed: (id, records) => { this.userProfileChangeCallback(userCursor); }, removed: () => { this.userProfileChangeCallback(userCursor); } }); } ngOnInit() { } @Input() set userId(userId: string) { if (this.userProfileWatchHandle) { this.userProfileWatchHandle.stop(); } this.userIdSetted = userId; if (this.userIdSetted) { this.attachUserProfileWatcher(); } else { this.isUserImageAvailable = false; this.userImageUrl = ''; } } @Input() isTinySmall: boolean; @Input() isSmall: boolean; @Input() isTiny: boolean; ngOnDestroy() { } ngOnChanges() { // this.userProfileChangeCallback(); } }<file_sep>/source2/devcontrolpanel/imports/api/server/wall-post/card-methods.ts import {Promise} from 'es6-promise'; import {Meteor} from 'meteor/meteor'; import {WallPostCollection} from '../../../services/wall-post.service'; import {IWallPost, IWallPostSearch} from '../../../common/wall-post.model'; import {SitemapCollection} from '../../../services/sitemap.service'; import {ISitemapCollection} from '../../../common/sitemap.model'; Meteor.methods({ 'getWallPostDetail': (wallPostId: string): IWallPost => { let wallPostDetail: IWallPost = WallPostCollection.findOne({ _id: wallPostId }); return wallPostDetail; } }); Meteor.methods({ 'updateWallPostComment': (wallPostId: string, commentKeyToUpdate: string, commentCreatedTime: string, comment: string) => { return new Promise<boolean>((resolve, reject) => { let findComment = { _id: wallPostId, [commentKeyToUpdate + '.createdBy']: Meteor.userId(), [commentKeyToUpdate + '.createdTime']: commentCreatedTime }; console.log(findComment); WallPostCollection.update(findComment, { $set: { [commentKeyToUpdate + '.comment']: comment } }, { multi: false }, (err, affectedCount) => { if (!err && affectedCount > 0) { resolve(true); } else { resolve(false); } }); }).catch(err => { throw new Meteor.Error(err) }); } }); Meteor.methods({ 'deleteWallPostComment': (wallPostId: string, commentKeyToUpdate: string, commentCreatedTime: string) => { return new Promise<boolean>((resolve, reject) => { let findComment = { _id: wallPostId }; console.log({ [commentKeyToUpdate]: { createdBy: Meteor.userId(), createdTime: commentCreatedTime } }); WallPostCollection.update(findComment, { $pull: { [commentKeyToUpdate]: { createdBy: Meteor.userId(), createdTime: commentCreatedTime } } }, { multi: false }, (err, affectedCount) => { if (!err && affectedCount > 0) { resolve(true); } else { resolve(false); } }); }).catch(err => { throw new Meteor.Error(err) }); }, 'wallPostSearch': (search: IWallPostSearch): string[] => { let result: string[] = [], query = []; //let query = []; if (search.search) { query.push({ '$text': { $search: search.search } }); } if (search.tags && search.tags.length) { _.forEach(search.tags, (tagVal) => { query.push({ 'tag.name': tagVal }); }); } if (search.createdBy && search.createdBy.length) { _.forEach(search.createdBy, (createdByVal) => { query.push({ 'createdBy': createdByVal }); }); } let finalQuery = { $and: query }; //console.log(finalQuery); WallPostCollection.find(finalQuery , { fields: { score: { $meta: 'textScore' } }, sort: { score: { $meta: 'textScore' } } } ).forEach((val) => { result.push(val._id); }); // console.log(result); return result; }, // 'wallPostCrawler': (postId) => { // let userId = Meteor.userId(); // if (userId) { // let wallPost = WallPostCollection.findOne({ _id: postId, createdBy: userId }); // if (wallPost) { // } // } // } }); WallPostCollection.after.insert((userid, wallpost: IWallPost) => { SitemapCollection.insert(<ISitemapCollection>{ contentId: wallpost._id, contentType: 'Wallpost', isRemoved: false }); }); WallPostCollection.before.remove((userid, wallpost: IWallPost) => { SitemapCollection.update({ contentId: wallpost._id, contentType: 'Wallpost' }, { $set: { isRemoved: true } }, { multi: false }); });<file_sep>/source2/devcontrolpanel/imports/services/wall-post.service.ts import { IWallPost, IWallPostTag, IWallPostLike, IWallPostComment, IWallPostPopularPost } from '../common/wall-post.model'; import {Mongo} from 'meteor/mongo'; export let WallPostCollection = new Mongo.Collection<IWallPost>('WallPost'); export let WallPostPopularPostCollection = new Mongo.Collection<IWallPostPopularPost>('WallPostPopularPost'); let userIdLength: number = 200; let trackCreatedByTimeSchema = new SimpleSchema({ // createdBy: { // type: String, // max: userIdLength // }, // createdTime: { // type: Number // } }); let wallPostTag: SimpleSchema<IWallPostTag> = new SimpleSchema<IWallPostTag>({ name: { type: String, max: userIdLength }, order: { type: Number, } }); let wallPostLike = new SimpleSchema<IWallPostLike>([trackCreatedByTimeSchema, { }]); var wallPostComment = new SimpleSchema<IWallPostComment>([trackCreatedByTimeSchema, { comment: { type: String, max: 2000 }, reply: { type: [wallPostComment], optional: true } }]); let wallPostSchema: SimpleSchema<IWallPost> = new SimpleSchema<IWallPost>([trackCreatedByTimeSchema, { content: { type: String, label: 'Content', max: 10000000 }, title: { type: String, label: 'Title', max: 600, optional: true }, tag: { type: [wallPostTag], optional: true }, like: { type: [wallPostLike], optional: true }, comment: { type: [wallPostComment], optional: true } }]); //WallPostCollection.attachSchema(wallPostSchema); if (Meteor.isServer) { WallPostCollection.before.insert((userid, wallpost: IWallPost) => { wallpost.createdTime = Date.now(); wallpost.createdBy = Meteor.userId(); }); WallPostCollection.before.update((userid, doc: IWallPost, fieldNames, modifier) => { if (fieldNames && fieldNames.length == 1 && fieldNames[0] == 'like' && modifier && modifier['$addToSet'] && _.keys(modifier['$addToSet']).length == 1 && modifier['$addToSet'].like) { modifier['$addToSet'].like.createdBy = Meteor.userId(); modifier['$addToSet'].like.createdTime = Date.now(); } //for comment console.log([fieldNames, modifier]); if (fieldNames && fieldNames.length == 1 && _.isString(fieldNames[0]) && fieldNames[0].indexOf('comment') > -1 && modifier && modifier['$addToSet'] && _.keys(modifier['$addToSet']).length == 1 ) { console.log('comment update hook'); let commentRef = modifier['$addToSet'][_.keys(modifier['$addToSet'])[0]]; commentRef.createdBy = Meteor.userId(); commentRef.createdTime = Date.now(); } }); }<file_sep>/source2/devcontrolpanel/imports/ui/components/verify-email-component/verify-email.component.ts //library imports import {Component, AfterViewInit} from '@angular/core'; import { RouteParams, Router } from '@angular/router-deprecated'; import {Accounts} from 'meteor/accounts-base'; //with in the app import {LeftMenuProfileComponent} from '../left-menu-profile-component/left-menu-profile.component'; import template from './template/verify-email.template.html'; @Component({ selector: 'verify-email-page', template, directives: [LeftMenuProfileComponent] }) export class VerifyEmailComponent implements AfterViewInit { isLoading: boolean = false; isEmailVerificationSuccess : boolean = false; emailError: string; constructor(private routeParams: RouteParams, private router : Router){ } ngAfterViewInit(){ let verificationToken = this.routeParams.get('token'); this.emailError = ''; Accounts.verifyEmail(verificationToken, (err) => { if(err){ this.emailError = err.reason; this.isEmailVerificationSuccess = false; } else{ this.isEmailVerificationSuccess = true; } this.isLoading = false; }); } }<file_sep>/source2/devcontrolpanel/typings/globals/custom/index.d.ts /// <reference path="../../../imports/common/user-profile-model.ts" /> interface Window { ga: any, } //custom template // declare module 'template/wall-post-card-comment.template.html'{ // var template : string; // export default template; // } declare var Restivus: any; declare var twitterAPI : any; declare var window: Window; declare var lodash: _.LoDashStatic; declare var ga: any; declare var location: Location; declare var ServiceConfiguration: any; declare module 'meteor/meteor' { export module Meteor { var isDevelopment: boolean; var bindEnvironment: any; } } declare var loadImage: any; declare var hljs: any; //import {IWallPostSavedSearch} from '../../../imports/common/user-profile-model'; declare module 'meteor/meteor' { export module Meteor { interface User { wallPost?: { savedSearch: any[] } } } } declare function ReactiveAggregate(publishMethodRef: any, collection: any, aggregateExpression: { [key: string]: any }[], options?: { [key: string]: string }); declare module "meteor/mongo" { // import {Mongo} from 'meteor/mongo'; export module Mongo { interface FieldSpecifier { [id: string]: Number | { $meta: string }; } interface IMeteorHooks<T> { update(callback: (userId: string, doc?: any, fieldNames?: any, modifier?: any, options?: any) => void); insert(callback: (userId: string, doc?: any) => void); remove(callback: (userId: string, doc?: any) => void); upsert(callback: (userId: string, selector?: any, modifier?: any, options?: any) => void); } interface Collection<T> { aggregate: (param: Selector[]) => any /** * Attaches a SimpleSchema to the collection. */ attachSchema(schema: SimpleSchema<T>, options?: Collection2.SchemaAttachOptions): void; /** * Retrieves the attached SimpleSchema from the collection. */ simpleSchema(): SimpleSchema<T>; before: IMeteorHooks<T>; after: IMeteorHooks<T>; insert(doc: Object, options?: {}, callback?: Function): string; update(selector: Mongo.Selector, modifier: Mongo.Modifier, options?: { multi?: boolean; upsert?: boolean; }, callback?: Function): number; upsert(selector: Mongo.Selector, modifier: Mongo.Modifier, options?: Collection2.UpsertOptions, callback?: Function): { numberAffected?: number; insertedId?: string; }; } } } declare module MeteorSimpleSchema { interface PropertyDefinition { /** * If you set denyUpdate: true, any collection update that modifies the field will fail. */ denyUpdate?: boolean; /** * If you set denyInsert to true, you will need to set optional: true as well. */ denyInsert?: boolean; /** * Use the index option to ensure a MongoDB index for a specific field. * Set to 1 or true for an ascending index. Set to -1 for a descending index. * Or you may set this to another type of specific MongoDB index, such as "2d". * Indexes works on embedded sub-documents as well. * * If you have created an index for a field by mistake and you want to remove it, set index to false. */ index?: number | boolean | string; /** * If a field has the unique option set to true, the MongoDB index will be a unique index as well. Then on the server, * Collection2 will rely on MongoDB to check uniqueness of your field, which is more efficient than our custom checking. */ unique?: boolean; } interface ThisContext { /** * True if it's an insert operation */ isInsert: boolean; /** * True if it's an update operation */ isUpdate: boolean; /** * True if it's an upsert operation (either upsert() or upsert: true) */ isUpsert: boolean; /** * The ID of the currently logged in user. (Always null for server-initiated actions.) */ userId: string; /** * True if the insert, update, or upsert was initiated from trusted (server) code */ isFromTrustedCode: boolean; /** * The _id property of the document being updated. This will be set only for an update or upsert, * and only when the selector includes the _id or when the operation is initiated on the client. */ docId: string; } } declare module Collection2 { interface SchemaAttachOptions { /** * If your validation requires that your doc be transformed using the collection's transform function prior to being validated, * then you must pass the transform: true option to attachSchema when you attach the schema: */ transform?: boolean; /** * By default, if a collection already has a schema attached, attachSchema will combine the new schema with the existing. * Pass the replace: true option to attachSchema to discard any existing schema. */ replace?: boolean; } interface InsertOptions extends MeteorSimpleSchema.BaseCleaningOptions { /** * To use a specific named validation context. */ validationContext?: string; /** * To skip validation, use the validate: false option when calling insert or update. On the client (untrusted code), * this will skip only client-side validation. On the server (trusted code), * it will skip all validation. The object is still cleaned and autoValues are still generated. */ validate?: boolean; } interface UpsertOptions extends InsertOptions { multi?: boolean; } interface UpdateOptions extends UpsertOptions { upsert?: boolean; } } declare var SimpleSchema: SimpleSchemaStatic; interface SimpleSchemaStatic { new <T>(definition: MeteorSimpleSchema.Definition): SimpleSchema<T>; new <T>([SimpleSchema]): SimpleSchema<T>; debug: boolean; RegEx: { Email: RegExp; Domain: RegExp; WeakDomain: RegExp; IP: RegExp; IPv4: RegExp; IPv6: RegExp; Url: RegExp; Id: RegExp; ZipCode: RegExp; }; /** * Adds a custom validation function that is called for all keys in all defined schemas. * All information for the validation is provided in the function's context. * Cast this to SimpleSchema.CustomValidationThis in order to make use of that context */ addValidator(customValidator: Function): void; messages(errorMessages: MeteorSimpleSchema.ErrorMessages): void; } interface SimpleSchema<T> { /** * You can use this method, to alter one or more labels on the fly */ labels(updatedLabels: { [propertyName: string]: string }): void; /** * Returns a label for a property. This method is reactive. */ label(propertyName: string): string /** * The clean method takes the object to be cleaned as its first argument and the following optional options as its second argument. * The object is cleaned in place. That is, the original referenced object will be cleaned. * You do not have to use the return value of the clean method. */ clean(objectOrModifier: T, options?: MeteorSimpleSchema.CleaningOptions): T; /** * The clean method takes the object to be cleaned as its first argument and the following optional options as its second argument. * The object is cleaned in place. That is, the original referenced object will be cleaned. * You do not have to use the return value of the clean method. */ clean(objectOrModifier: Mongo.Modifier, options?: MeteorSimpleSchema.CleaningOptions): Mongo.Modifier; /** * Returns a new unnamed validation context. */ newContext(): MeteorSimpleSchema.ValidationContext<T>; /** * Returns a new named validation context. It's usually best to use a named validation context. * That way, the context is automatically persisted by name, allowing you to easily rely on its reactive methods. */ namedContext(name: string): MeteorSimpleSchema.ValidationContext<T>; /** * Adds a custom validation function that is called for all keys for a specific SimpleSchema instance. * All information for the validation is provided in the function's context. * Cast this to SimpleSchema.CustomValidationThis in order to make use of that context */ addValidator(customValidator: Function): void; schema(): MeteorSimpleSchema.Definition; schema(key: string): MeteorSimpleSchema.PropertyDefinition; messages(errorMessages: MeteorSimpleSchema.ErrorMessages): void; } declare module MeteorSimpleSchema { interface Definition { [propertyName: string]: MeteorSimpleSchema.PropertyDefinition; } interface PropertyDefinition { type: StringConstructor | NumberConstructor | BooleanConstructor | ObjectConstructor | DateConstructor | [StringConstructor] | [NumberConstructor] | [BooleanConstructor] | [ObjectConstructor] | [DateConstructor] | [SimpleSchema<any>]; /** * A string that will be used to refer to this field in validation error messages. * The default is an inflected (humanized) derivation of the key name itself. * For example, the key "firstName" will have a default label of "<NAME>". * * If you require a field that changes its meaning in some circumstances you can provide a callback function as a label. */ label?: string | (() => string); /** * By default, all keys are required. Set optional: true to change that. * * With complex keys, it might be difficult to understand what "required" means. * Here's a brief explanation of how requiredness is interpreted: * * - If type is Array or is an array (any type surrounded by array brackets), * then "required" means that key must have a value, but an empty array is fine. * (If an empty array is not fine, add the minCount: 1 option.) * - For items within an array, or when the key name ends with ".$", the optional option has no effect. * That is, something cannot be "required" to be in an array. * - If a key is required at a deeper level, the key must have a value only if the object it belongs to is present. * - When the object being validated is a Mongo modifier object, * changes that would unset or null a required key result in validation errors. */ optional?: boolean; /** * If type is Number or [Number], these rules define the minimum numeric value. * If type is String or [String], these rules define the minimum string length. * If type is Date or [Date], these rules define the minimum date, inclusive. */ min?: number; /** * If type is Number or [Number], these rules define the maximum numeric value. * If type is String or [String], these rules define the maximum string length. * If type is Date or [Date], these rules define the maximum date, inclusive. */ max?: number; /** * Set to true to indicate that the numeric value, set by min, is to be treated as an exclusive limit. * Set to false (default) to treat limit as inclusive. */ exclusiveMin?: boolean; /** * Set to true to indicate that the numeric value, set by max, is to be treated as an exclusive limit. * Set to false (default) to treat limit as inclusive. */ inclusiveMin?: boolean; /** * Set to true if type is Number or [Number] and you want to allow non-integers. The default is false. */ decimal?: boolean; /** * Define the minimum array length. Used only when type is an array or is Array. */ minCount?: number; /** * Define the maximum array length. Used only when type is an array or is Array. */ maxCount?: number; /** * An array of values that are allowed. A key will be invalid if its value is not one of these. */ allowedValues?: any[]; /** * Any regular expression that must be matched for the key to be valid, * or an array of regular expressions that will be tested in order. */ regEx?: RegExp | RegExp[]; /** * If you have a key with type Object, the properties of the object will be validated as well, * so you must define all allowed properties in the schema. * If this is not possible or you don't care to validate the object's properties, * use the blackbox: true option to skip validation for everything within the object. * * Custom object types are treated as blackbox objects by default. However, when using collection2, * you must ensure that the custom type is not lost between client and server. * This can be done with a transform function that converts the generic Object to the custom object. * Without this transformation, client-side inserts and updates might succeed on the client but then fail on the server. * Alternatively, if you don't care about losing the custom type, * you can explicitly set blackbox: true for a custom object type instead of using a transformation. */ blackbox?: boolean; /** * Set to false if the string value for this key should not be trimmed (i.e., leading and trailing spaces should be kept). * Otherwise, all strings are trimmed when you call mySimpleSchema.clean(). */ trim?: boolean; /** * All information for the validation is provided in the function's context. * Cast this to SimpleSchema.CustomValidationThis in order to make use of that context */ custom?: Function; /** * Set this to any value that you want to be used as the default when an object does not include this field or * has this field set to undefined. This value will be injected into the object by a call to mySimpleSchema.clean(). * Default values are set only when cleaning non-modifier objects. * * Note the following points of confusion: * - A default value itself is not cleaned. So, for example, if your default value is "", * it will not be removed by the removeEmptyStrings operation in the cleaning. * - A default value is always added if there isn't a value set. Even if the property is a child of an optional object, * and the optional object is not present, the object will be added and its property will be set to the default value. * Effectively, this means that if you provide a default value for one property of an object, * you must provide a default value for all properties of that object or risk confusing validation errors. * * If you need more control, use the autoValue option instead. */ defaultValue?: any; /** * The autoValue option allows you to specify a function that is called by mySimpleSchema.clean() to potentially change * the valueof a property in the object being cleaned. This is a powerful feature that allows you to set up either * forced values or default values, potentially based on the values of other fields in the object. * * An autoValue function is passed the document or modifier as its only argument, but you will generally not need it. * Instead, the function context provides a variety of properties and methods to help you determine what you should return. * Cast this to SimpleSchema.AutoValueThis in order to make use of that context * * If an autoValue function does not return anything (i.e., returns undefined), the field's value will be * whatever the document or modifier says it should be. If that field is already in the document or modifier, * it stays in the document or modifier with the same value. If it's not in the document or modifier, it's still not there. * If you don't want it to be in the doc or modifier, you must call this.unset(). * * Any other return value will be used as the field's value. You may also return special pseudo-modifier objects for update operations. * Examples are {$inc: 1} and {$push: new Date}. */ autoValue?: (documentOrModifier: any) => any | void; } interface BaseCleaningOptions { /** * Filter out properties not found in the schema? True by default. */ filter?: boolean; /** * Type convert properties into the correct type where possible? True by default. */ autoConvert?: boolean; /** * Remove keys in normal object or $set where the value is an empty string? True by default. */ removeEmptyStrings?: boolean; /** * Remove all leading and trailing spaces from string values? True by default. */ trimStrings?: boolean; /** * Run autoValue functions and inject automatic and defaultValue values? True by default. */ getAutoValues?: boolean; } interface CleaningOptions extends BaseCleaningOptions { /** * Is the first argument a modifier object? False by default. */ isModifier?: boolean; /** * This object will be added to the this context of autoValue functions. */ extendAutoValueContext?: any; } interface ValidationContext<T> { /** * This method returns true if the object is valid according to the schema or false if it is not. * It also stores a list of invalid fields and corresponding error messages in the context object * and causes the reactive methods to react. */ validate(obj: T | Mongo.Modifier, options?: ValidationOptions): boolean; /** * This works the same way as the validate method, except that only the specified schema key will be validated. * This may cause all of the reactive methods to react. */ validateOne(obj: T | Mongo.Modifier, key: string, options?: ValidationOptions): boolean; /** * You can call it, to see if the object passed into validate() was found to be valid. * This is a reactive method that returns true or false. */ isValid(): boolean; /** * Returns the full array of invalid key data. Each object in the array has two keys: * - name: The schema key as specified in the schema. * - type: The type of error. One of the required*, min*, max* etc. strings listed at Manually Adding a Validation Error. * * This is a reactive method. There is no message property. * Once you see what keys are invalid, you can call ctxt.keyErrorMessage(key) to get a reactive message string. */ invalidKeys(): { name: string; type: string }[]; /** * Returns true if the specified key is currently invalid, or false if it is valid. This is a reactive method. */ keyIsInvalid(key: string): boolean; /** * Teturns the error message for the specified key if it is invalid. If it is valid, this method returns an empty string. * This is a reactive method. */ keyErrorMessage(key: string): string; /** * If you need to reset the validation context, clearing out any invalid field messages and making it valid. */ resetValidation(): void; /** * If you want to reactively display an arbitrary validation error and it is not possible to use a custom validation function * (perhaps you have to call a function onSubmit or wait for asynchronous results), * you can add one or more errors to a validation context at any time. * * - name: The schema key as specified in the schema. * - type: The type of error. Any string you want, or one of the following built-in strings: required, minString, maxString, * minNumber, maxNumber, minDate, maxDate, badDate, minCount, maxCount, noDecimal, notAllowed, expectedString, * expectedNumber, expectedBoolean, expectedArray, expectedObject, expectedConstructor, regEx * - value: Optional. The value that was not valid. Will be used to replace the [value] placeholder in error messages. */ addInvalidKeys(errors: { name: string; type: string; value?: string }[]): void; } interface ValidationOptions { /** * Are you validating a Mongo modifier object? False by default. */ modifier?: boolean; /** * Are you validating a Mongo modifier object potentially containing upsert operators? False by default. */ upser?: boolean; /** * This object will be added to the this context in any custom validation functions that are run during validation. */ extendedCustomContext?: any; } interface ThisContextPropertyInfo { /** * True if the field is already set in the document or modifier */ isSet: boolean; /** * If isSet = true, this contains the field's current (requested) value in the document or modifier. */ value: any; /** * If isSet=true and isUpdate=true, this contains the name of the update operator in the modifier in which this field is being changed. * For example, if the modifier were {$set: {name: "Alice"}}, in the autoValue function for the name field, this.isSet would be true, * this.value would be "Alice", and this.operator would be "$set". */ operator: string; } interface ThisContext extends ThisContextPropertyInfo { /** * Use this method to get information about other fields. Pass a field name (schema key) as the only argument. */ field(name: string): ThisContextPropertyInfo; /** * Use this method to get information about other fields that have the same parent object. */ siblingField(name: string): ThisContextPropertyInfo; } interface AutoValueThis extends ThisContext { /** * Call this method to prevent the original value from being used when you return undefined. */ unset(): void; } interface CustomValidationThis extends ThisContext { /** * The name of the schema key (e.g., "addresses.0.street") */ key: string; /** * The generic name of the schema key (e.g., "addresses.$.street") */ genericKey: string; /** * The schema definition object. */ definition: Definition; } interface ErrorMessages { [errorType: string]: string | ({ msg: string; exp?: RegExp }[]); } }<file_sep>/source2/devcontrolpanel/imports/ui/services/can-activate-route.service.ts import {Meteor} from 'meteor/meteor'; export function canActivateRoute(next: any, prev: any, isAuthenticatedRoute: boolean = false) { if (isAuthenticatedRoute) { return Meteor.userId() ? true : false; } else { return true; } }<file_sep>/source2/devcontrolpanel/imports/ui/directives/app-common.directive.ts import {ActiveMenuDirective} from './active-menu.directive'; import {SemanticCheckbox, SemanticAccordion, SemanticSticky, SemanticHighlightBgElement, SemanticDropdown, SemanticSidebar, SemanticRibbler, SemanticSidebarToggleControl, SemanticPopup, SemanticSortable, SemanticModal } from './semantic.directive'; export const APP_COMMON_DIRECTIVES: any[] = [ ActiveMenuDirective, SemanticCheckbox, SemanticAccordion, SemanticSticky, SemanticHighlightBgElement, SemanticDropdown, SemanticSidebar, SemanticRibbler, SemanticSidebarToggleControl, SemanticPopup, SemanticSortable, SemanticModal ];<file_sep>/source2/devcontrolpanel/imports/ui/components/site-auth-component/model/auth.model.ts import {Injectable} from '@angular/core'; export module AuthModel { @Injectable() export class ResultMessageClassMapValue { success: boolean; negative: boolean; visible: boolean = false hidden: boolean = true; } @Injectable() export class SignUpModel{ name: string = ''; email: string = ''; password: string = ''; retypePassword: string = ''; public isLoading: boolean = false; public isSignupSuccess: boolean = false; public isFormSubmitted: boolean = false; public resultMessage: string; public isFormValid: boolean = true; public resultMessageClassMap: ResultMessageClassMapValue; constructor(_resultMessageClassMap : ResultMessageClassMapValue){ this.resultMessageClassMap = _resultMessageClassMap; } } @Injectable() export class SignInModel { public email: string = ''; public password: string = ''; public isLoading: boolean = false; public isSigninSuccess: boolean = false; public isFormSubmitted: boolean = false; public resultMessage: string; public resultMessageClassMap: ResultMessageClassMapValue; constructor(_resultMessageClassMap : ResultMessageClassMapValue) { this.resultMessageClassMap = _resultMessageClassMap; } } @Injectable() export class ForgotPassword { public email: string = ''; public isLoading: boolean = false; public isForgetPasswordSuccess: boolean = false; public isFormSubmitted: boolean = false; public resultMessage: string; public isVisible: boolean = false; public resultMessageClassMap: ResultMessageClassMapValue; constructor(_resultMessageClassMap : ResultMessageClassMapValue) { this.resultMessageClassMap = _resultMessageClassMap; } } export interface IAuthSigninModel { email : string; password: string; authType: AuthModel.AuthType } export enum AuthErrorCode { EMAIL_TAKEN, USER_CREATION_SUCCESS } export enum AuthType{ CUSTOM, GOOGLE, FACEBOOK, GITHUB, TWITTER } export interface ISigninError{ message ?: string; uid?: string } }<file_sep>/source2/devcontrolpanel/imports/ui/services/global-event.service.ts import { Injectable } from '@angular/core' import { Subject } from 'rxjs/Subject'; import {LinkClickedName, AuthStatus} from './config.service' @Injectable() export class GlobalEventSerice { private _linkClickedEvent = new Subject<number>(); private _authStatusChangeEvent = new Subject<number>(); private _currentUserProfileChangedEvent = new Subject<boolean>(); public linkClickedEvent$ = this._linkClickedEvent.asObservable(); public authStatusChangeEvent$ = this._authStatusChangeEvent.asObservable(); public currentUserProfileChangedEvent$ = this._currentUserProfileChangedEvent.asObservable(); linkClickedEvent(eventName: LinkClickedName) { this._linkClickedEvent.next(eventName); } authStatusChangeEvent(eventName: AuthStatus) { this._authStatusChangeEvent.next(eventName); } currentUserProfileChangedEvent() { this._currentUserProfileChangedEvent.next(true); } }<file_sep>/source2/devcontrolpanel/typings/browser.d.ts /// <reference path="browser/definitions/es6-promise/index.d.ts" /> /// <reference path="globals/lodash/index.d.ts" /> <file_sep>/source2/devcontrolpanel/imports/ui/components/wall-post-component/component/wall-post-detail-component/service/wall-post-detail.service.ts import { } from '@angular/core'; import { WallPostCollection } from '../../../../../../services/wall-post.service'; export class WallPostDetailService { constructor() { } }<file_sep>/source2/devcontrolpanel/imports/common/wall-post.model.ts export interface IWallPostIndex { _id: string, createdTime: number } export interface IWallPostPopularPost{ _id: string; count: number; } export interface IWallPost { _id?: string; content: string; title?: string; tag?: IWallPostTag[]; like?: IWallPostLike[]; comment?: IWallPostComment[]; createdBy?: string; createdTime?: number; } export interface IWallPostTag { name: string, order: number } export interface IWallPostLike { createdBy: string, createdTime: number } export interface IWallPostComment { commentReplyContent: string; comment: string; createdBy: string; createdTime: string; reply?: IWallPostComment[]; } export class WallPostComment implements IWallPostComment { commentReplyContent: string; comment: string; createdBy: string; createdTime: string; reply: IWallPostComment[]; constructor() { this.commentReplyContent = ''; this.comment = '' this.createdBy = ''; this.createdTime = ''; this.reply = []; } } export interface IWallPostSearch{ search: string; tags: string[]; createdBy: string[]; }<file_sep>/source2/devcontrolpanel/imports/ui/directives/ckeditor.directive.ts import { Directive, Input, Output, ElementRef, HostBinding, Renderer, EventEmitter} from '@angular/core'; import {OnInit, AfterViewInit, AfterViewChecked, OnDestroy} from '@angular/core'; @Directive({ selector: '[CKEditor]' }) export class CKEditorDirective implements OnInit, OnDestroy, AfterViewInit, AfterViewChecked { private instanceName: string; private elementRef: ElementRef; private renderer: Renderer; private editor: CKEDITOR.editor; private editorData: string; constructor(elementRef: ElementRef, renderer: Renderer) { this.elementRef = elementRef; this.renderer = renderer; } ngOnInit() { } @Output() editorValueChanged = new EventEmitter(); @Input() set IsReset(value: boolean) { if (value) { if (this.editor) { this.editor.setData(''); } } } ngAfterViewInit() { this.editor = CKEDITOR.replace(this.instanceName); this.editor.on('change', eventInfo => { let data = eventInfo.editor.getData(); this.renderer.setElementProperty(this.elementRef, 'value', data); this.editorValueChanged.emit(data); }); } ngAfterViewChecked() { } @Input() set CKEditor(idOrName: string) { this.instanceName = idOrName; } ngOnDestroy() { // if (CKEDITOR.instances[this.instanceName]) { // CKEDITOR.instances[this.instanceName].destroy(); // } } } <file_sep>/source2/devcontrolpanel/imports/ui/components/my-profile-component/component/my-profile-update-component/my-profile-update.component.ts //library imports import {Component, provide, Inject, NgZone} from '@angular/core'; import { RouterLink } from '@angular/router-deprecated'; import { FORM_DIRECTIVES, FormBuilder, Validators, CORE_DIRECTIVES, ControlGroup} from '@angular/common'; //with in the app import {APP_COMMON_DIRECTIVES} from '../../../../directives/app-common.directive'; import {AppComponent} from '../../../common/app-component'; import {AppFactory} from '../../../../services/config.service'; import {emailValidator} from '../../../../form-validator/validators'; import {GlobalEventSerice} from '../../../../services/global-event.service'; //with in the component import {IUpdateProfileForm} from './model/update-profile.model'; import { Meteor } from 'meteor/meteor'; import template from './template/my-profile-update.template.html'; @Component({ selector: 'my-profile-update', template, directives: [RouterLink, APP_COMMON_DIRECTIVES] }) export class MyProfileUpdateComponent extends AppComponent { updateForm: ControlGroup; updateModel: IUpdateProfileForm; updateError: string; updateSuccess: boolean = false; constructor( private formBuilder: FormBuilder, appFactory: AppFactory, ngZone: NgZone, globalEventSerice: GlobalEventSerice ) { super(appFactory, globalEventSerice, ngZone); this.updateForm = this.formBuilder.group({ name: [this.user.name, Validators.required], email: [this.user.email, Validators.compose([Validators.required, emailValidator])] }); this.updateModel = <IUpdateProfileForm>{ name: this.user.name, email: this.user.email, profilePicture: this.user.profileImageURL, isLoading: false }; this.updateError = ''; } save() { this.updateModel.isLoading = true; this.updateError = ''; this.updateSuccess = false; let updatedModel: any = { 'profile.name': this.updateModel.name, 'emails.0.address': this.updateModel.email }; if (this.previewImageSrc) { updatedModel['profile.profilePicture'] = this.previewImageSrc; this.updateModel.profilePicture = this.previewImageSrc; } Meteor.users.update(this.user.userId, { $set: updatedModel }, null, (error) => { this.updateModel.isLoading = false; if (error) { this.updateError = error; this.updateSuccess = false; } else { this.updateSuccess = true; this.updateError = ''; } }); } profileImageSrc: string; previewImageSrc: string; isProfileImageSrcLoading: boolean; cropperRef: any; chooseProfileImage(e: any) { this.isProfileImageSrcLoading = true; let target = e.dataTransfer || e.target, file = target && target.files && target.files[0], options: any = { canvas: true, maxWidth: 400 }; if (!file) { return; } this.ngZone.runOutsideAngular(() => { // Use the "JavaScript Load Image" functionality to parse the file data loadImage.parseMetaData(file, (data) => { // Get the correct orientation setting from the EXIF Data if (data.exif) { options.orientation = data.exif.get('Orientation'); } // Load the image from disk and inject it into the DOM with the correct orientation loadImage( file, (canvas) => { this.ngZone.run(() => { this.isProfileImageSrcLoading = false var imgDataURL = canvas.toDataURL(); this.profileImageSrc = imgDataURL; setTimeout(() => { if (this.cropperRef) { $(".image-cropper").cropper('destroy'); } this.cropperRef = $(".image-cropper").cropper({ crop: () => { this.previewProfileImage(); } }); // this.cropperRef.on('cropmove.cropper', () => { // }); }, 100); }); }, options ); }); }); } previewProfileImage() { this.ngZone.runOutsideAngular(() => { let canvas = $('.image-cropper'); let cropppedData = canvas.cropper('getCroppedCanvas', { }); this.ngZone.run(() => { this.previewImageSrc = cropppedData.toDataURL(); }); }); } }<file_sep>/source2/devcontrolpanel/.out-of-meteor/typings/index.d.ts /// <reference path="globals/angular-google-analytics/index.d.ts" /> /// <reference path="globals/es6-shim/index.d.ts" /> /// <reference path="modules/blue-tape/index.d.ts" /> /// <reference path="modules/es6-promise/index.d.ts" /> <file_sep>/source2/devcontrolpanel/.out-of-meteor/content/scripts/custom/custom.ts System.config({ packages: { app: { format: 'register', defaultExtension: 'js' } } }); System.import('app/boot').then(null, console.error.bind(console)); jQuery.fn.jScrollIntoView = function() { jQuery('html,body').animate({ scrollTop: $(this).offset().top - 100 }, { duration: 'fast' }); } $(document).on('animationend webkitAnimationEnd MSAnimationEnd oAnimationEnd', '.highlight-bg-element', function() { $(this).removeClass('highlight-bg-element'); }); //google analytics window.ga = window.ga || function() { (ga.q = ga.q || []).push(arguments) }; ga.l = +new Date; ga('create', 'UA-68651093-1', 'auto'); ga('send', 'pageview'); // Test if string is only contains numbers // e.g '1' => true, "'1'" => true function isStringNumber(num) { return /^-?\d+\.?\d*$/.test(num.replace(/["']/g, '')); } //$.param for form post -ajax function serializeData(data) { // If this is not an object, defer to native stringification. if (!angular.isObject(data)) { return ((data == null) ? "" : data.toString()); } var buffer = []; // Serialize each key in the object. for (var name in data) { if (!data.hasOwnProperty(name)) { continue; } var value = data[name]; buffer.push( encodeURIComponent(name) + "=" + encodeURIComponent((value == null) ? "" : value) ); } // Serialize the buffer and clean it up for transportation. var source = buffer.join("&").replace(/%20/g, "+"); return (source); } var parseLocation = function(location) { var pairs = location.substring(0).split("&"); var obj = {}; var pair; var i; for (i in pairs) { if (pairs[i] === "") continue; pair = pairs[i].split("="); obj[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]); } return obj; }; function capitaliseFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } function smallFirstLetter(string) { return string.charAt(0).toLowerCase() + string.slice(1); } var progress; var errorDiv; var progressParent; var selectedFile; function errorHandler(evt) { errorDiv.style.display = "block"; switch (evt.target.error.code) { case evt.target.error.NOT_FOUND_ERR: errorDiv.innerHTML = 'File Not Found!'; break; case evt.target.error.NOT_READABLE_ERR: errorDiv.innerHTML = 'File is not readable'; break; case evt.target.error.ABORT_ERR: errorDiv.innerHTML = 'File is aborted'; break; // noop default: errorDiv.innerHTML = 'An error occurred reading this file.'; }; } function updateProgress(evt) { // evt is an ProgressEvent. if (evt.lengthComputable) { var percentLoaded = Math.round((evt.loaded / evt.total) * 100); // Increase the progress bar length. if (percentLoaded < 100) { progress.style.width = percentLoaded + '%'; // progress.textContent = percentLoaded + '%'; } } } var reader; function uploadFile(ele, evt) { progress = document.getElementById("imageUploadProgressBar"); progressParent = document.getElementById("imageUploadProgress"); errorDiv = document.getElementById("fileReadError"); selectedFile = evt.target.files[0]; // Reset progress indicator on new file selection. progress.style.width = '0%'; // progress.textContent = '0%'; reader = new FileReader(); reader.onerror = errorHandler; reader.onprogress = updateProgress; reader.onabort = function(e) { errorDiv.innerHTML = 'File is not readable'; errorDiv.style.display = 'block'; }; reader.onloadstart = function(e) { progressParent.style.display = 'block'; }; reader.onload = function(e) { // Ensure that the progress bar displays 100% at the end. progress.style.width = '100%'; // progress.textContent = '100%'; //setTimeout(function () { // progressParent.style.display = 'none'; //}, 1000); //Convert ArrayBuffer to BinaryString var data = ""; var bytes = new Uint8Array(reader.result); var length = bytes.byteLength; for (var i = 0; i < length; i++) { data += String.fromCharCode(bytes[i]); } //Encode BinaryString to base64 data = btoa(data); //get the upload service from angularjs var service = angular.element(document.getElementsByTagName('body')).injector().get('commonService.uploadCkEditorFile'); var fileType = selectedFile.type, fileExtention = selectedFile.name.split(".")[1]; service.postImage({ Content: data, ContentType: fileType, Extention: fileExtention }).then( //success callback function(response) { var F = CKEDITOR.dialog.getCurrent(); F.getContentElement('info', 'src').setValue(response); angular.element(document.getElementById(F.getContentElement('info', 'src').domId)).trigger('change'); //hide the loading in ckeditor popup progressParent.style.display = 'none'; }, //failure callback function() { //hide the loading in ckeditor popup progressParent.style.display = 'none'; } ); } // Read in the image file as a binary string. reader.readAsArrayBuffer(selectedFile); } class ImageLib { resizeImageFixedSize(imageData, imageType, resizeWidth, resizeHeight, deferObj) { imageData = this.getImageSourceFormatted(imageType, imageData); // this.resizeImage(imageData, imageType, false, null, resizeWidth, resizeHeight, deferObj); }; getImageSourceFormatted(filetype, data) { return 'data:' + filetype + ';base64,' + data; }; resizeImage(imageData, imageType?: string, isAutoAdjust?: boolean, adjustRatio?: number, resizeWidth?: number, resizeHeight?: number): Promise<string> { return new Promise<string>((resolve, reject) => { var canvas = document.createElement("canvas"); var ctx = canvas.getContext("2d"); var img = new Image(); img.crossOrigin = "Anonymous"; //cors support img.onerror = () => { reject('INVALID_IMAGE_SOURCE'); }; img.onload = () => { var W = img.width; var H = img.height; canvas.width = W; canvas.height = H; ctx.drawImage(img, 0, 0); //draw image if (isAutoAdjust) { //resize by ratio var ratio = adjustRatio || 0.43895525; //from 0 to 1 this.resample_hermite(canvas, W, H, Math.round(W * ratio), Math.round(H * ratio)); } else { resizeWidth = resizeWidth || 300; resizeHeight = resizeHeight || 300; this.resample_hermite(canvas, W, H, resizeWidth, resizeHeight); } if (imageType == 'image/jpg' || imageType == 'image/jpeg') { resolve(canvas.toDataURL("image/jpeg", 0.8)); } else { resolve(canvas.toDataURL("image/png")); } reject('INVALID_FILE_TYPE'); }; img.src = imageData; }); } resample_hermite(canvas, W, H, W2, H2) { var time1 = Date.now(); W2 = Math.round(W2); H2 = Math.round(H2); var img = canvas.getContext("2d").getImageData(0, 0, W, H); var img2 = canvas.getContext("2d").getImageData(0, 0, W2, H2); var data = img.data; var data2 = img2.data; var ratio_w = W / W2; var ratio_h = H / H2; var ratio_w_half = Math.ceil(ratio_w / 2); var ratio_h_half = Math.ceil(ratio_h / 2); for (var j = 0; j < H2; j++) { for (var i = 0; i < W2; i++) { var x2 = (i + j * W2) * 4; var weight = 0; var weights = 0; var weights_alpha = 0; var gx_r = 0, gx_g = 0, gx_b = 0, gx_a = 0; var center_y = (j + 0.5) * ratio_h; for (var yy = Math.floor(j * ratio_h); yy < (j + 1) * ratio_h; yy++) { var dy = Math.abs(center_y - (yy + 0.5)) / ratio_h_half; var center_x = (i + 0.5) * ratio_w; var w0 = dy * dy //pre-calc part of w for (var xx = Math.floor(i * ratio_w); xx < (i + 1) * ratio_w; xx++) { var dx = Math.abs(center_x - (xx + 0.5)) / ratio_w_half; var w = Math.sqrt(w0 + dx * dx); if (w >= -1 && w <= 1) { //hermite filter weight = 2 * w * w * w - 3 * w * w + 1; if (weight > 0) { dx = 4 * (xx + yy * W); //alpha gx_a += weight * data[dx + 3]; weights_alpha += weight; //colors if (data[dx + 3] < 255) weight = weight * data[dx + 3] / 250; gx_r += weight * data[dx]; gx_g += weight * data[dx + 1]; gx_b += weight * data[dx + 2]; weights += weight; } } } } data2[x2] = gx_r / weights; data2[x2 + 1] = gx_g / weights; data2[x2 + 2] = gx_b / weights; data2[x2 + 3] = gx_a / weights_alpha; } } console.log("hermite = " + (Math.round(Date.now() - time1) / 1000) + " s"); canvas.getContext("2d").clearRect(0, 0, Math.max(W, W2), Math.max(H, H2)); canvas.width = W2; canvas.height = H2; canvas.getContext("2d").putImageData(img2, 0, 0); } } _.mixin({ getPureObject: function(firebaseObject) { return _.omit(firebaseObject, function(val, key) { return key.charAt(0) == '$' || key == 'forEach'; }); }, getFirebaseKeys: function(firebaseObject) { return _(firebaseObject).omit(function(val, key) { return key.charAt(0) == '$' || key == 'forEach'; }).keys().value(); } }); <file_sep>/source2/devcontrolpanel/imports/ui/components/wall-post-component/component/wall-post-card-component/component/wall-post-card-comment-component/wall-post-card-comment.component.ts import {Component, Input, AfterViewChecked, OnInit, NgZone, OnDestroy} from '@angular/core'; //from other component import { AppComponent } from '../../../../../common/app-component'; import { UserProfileImageComponent } from '../../../../../user-profile-image-component/user-profile-image.component'; import {IWallPost, IWallPostComment} from '../../../../../../../common/wall-post.model'; import { APP_COMMON_DIRECTIVES } from '../../../../../../directives/app-common.directive'; import { WallPostCollection } from '../../../../../../../services/wall-post.service'; import {GlobalEventSerice} from '../../../../../../services/global-event.service'; import {UserProfileUtils} from '../../../../../../../common/user-profile-util'; import {IUserProfile} from '../../../../../../../common/user-profile-model'; import { AppFactory } from '../../../../../../services/config.service'; import template from './template/wall-post-card-comment.template.html!raw'; @Component({ selector: 'wall-post-card-comment', template, directives: [UserProfileImageComponent, APP_COMMON_DIRECTIVES, WallPostCardCommentComponent], providers: [] }) export class WallPostCardCommentComponent extends AppComponent implements OnInit { commentValue: string; isCommentOwner: boolean = false; editCommentValue: string; isEditComment: boolean = false; constructor(appFactory: AppFactory, ngZone: NgZone, globalEventSerice: GlobalEventSerice ) { super(appFactory, globalEventSerice, ngZone) } ngOnInit() { this.isCommentOwner = this.userId == this.comment.createdBy ? true : false; } @Input() comment: IWallPostComment; @Input() isTopLevelComment: boolean; isReplyBoxVisible: boolean = false; @Input() keyToUpdate: string; @Input() wallPostId: string; reply() { let updateObj: any = {}; this.keyToUpdate += 'reply'; updateObj[this.keyToUpdate] = <IWallPostComment>{ comment: this.commentValue.toString() }; WallPostCollection.update({ _id: this.wallPostId }, { $addToSet: updateObj }); } editCommentClick() { this.isEditComment = true; if (this.comment && this.comment.comment) { this.editCommentValue = this.comment.comment; } else { this.editCommentValue = ''; } } editCommentSubmit() { let keyToUpdate = this.keyToUpdate; keyToUpdate = keyToUpdate.slice(0, -1); Meteor.call('updateWallPostComment', this.wallPostId, keyToUpdate, this.comment.createdTime, this.editCommentValue, (err, result) => { if (!err && result) { // } else { // } }); } deleteCommentSubmit() { let keyToUpdate = this.keyToUpdate; keyToUpdate = keyToUpdate.slice(0, -3); Meteor.call('deleteWallPostComment', this.wallPostId, keyToUpdate, this.comment.createdTime, (err, result) => { if (!err && result) { } else { console.log('remove failed'); } }); } editCommentCancelClick() { this.isEditComment = false; } } <file_sep>/source2/devcontrolpanel/imports/ui/components/site-auth-component/service/auth-user.service.ts //core import {Injectable, Inject} from '@angular/core'; import {Accounts} from 'meteor/accounts-base'; import {Meteor} from 'meteor/meteor'; import {OAppConfig, IAppConfig} from '../../../services/config.service'; //component level import import {AuthModel} from '../model/auth.model'; @Injectable() export class AuthUserService { constructor( @Inject(OAppConfig) private appConfig: IAppConfig) { } public CreateUser(credentials: AuthModel.SignUpModel): Promise<AuthModel.AuthErrorCode> { let promise = new Promise<AuthModel.AuthErrorCode>(resolve => { Accounts.createUser({ email: credentials.email, password: <PASSWORD>, profile: { name: credentials.name, //profilePicture: this.appConfig.AnonymousProfileImageUrl profilePicture: '' } }, (error) => { if (error) { resolve(AuthModel.AuthErrorCode.EMAIL_TAKEN); } else { Meteor.call('sendUserVerificationEmail', (err, res) => { if (!err) { } // debugger; }); resolve(AuthModel.AuthErrorCode.USER_CREATION_SUCCESS); } }); }); return promise; } public AuthWithPassword(authSigninModel: AuthModel.IAuthSigninModel): Promise<AuthModel.ISigninError> { let promise = new Promise<AuthModel.ISigninError> (resolve => { Meteor.loginWithPassword(authSigninModel.email, authSigninModel.password, error => { resolve(error); }); }); return promise; } public updateUserProfileInApp() { } public ThirdPartySignin(provider: string): Promise<any> { let promise = new Promise<any>(resolve => { let providerConcat = 'loginWith' + provider; if (Meteor[providerConcat]) { let thirdPartyOptions = this.getAuthOptionsByProvider(provider); Meteor[providerConcat](thirdPartyOptions, error => { resolve(error); }); } }); return promise; } public getAuthOptionsByProvider(provider: string): any { let result = {}; provider = provider.toLowerCase(); switch (provider) { case 'google': result = { scope: 'profile,email' }; break; case 'facebook': result = { requestPermissions: ['user_friends', 'public_profile', 'email'] }; break; case 'twitter': result = { include_email: true }; break; case 'github': result = { scope: 'user' }; break; } return result; } public messages: { [key: string]: string } = { 'Error: Incorrect password [403]': 'Incorrect password.', 'Error: User not found [403]': 'Email Id is not registered.' } }<file_sep>/source2/devcontrolpanel/imports/ui/components/site-component/site.component.ts //library imports import {Component, provide, Inject, NgZone, OnInit, OnDestroy} from '@angular/core'; import { RouterLink, ROUTER_DIRECTIVES, RouteConfig } from '@angular/router-deprecated'; //with in the app import {LeftMenuProfileComponent} from '../left-menu-profile-component/left-menu-profile.component'; import {APP_COMMON_DIRECTIVES} from '../../directives/app-common.directive'; import {AppFactory} from '../../services/config.service'; import {GlobalEventSerice} from '../../services/global-event.service'; import { AppComponent } from '../common/app-component'; import {LinkClickService} from '../devcontrolpanel/service/link-click.service'; import {TermsAndConditionComponent} from './component/terms-and-condition-component/terms-and-condition.component'; import {AboutUsComponent} from './component/about-us-component/about-us.component'; import {PrivacyPolicyComponent} from './component/privacy-policy-component/privacy-policy.component'; import template from './template/site.template.html'; @Component({ selector: 'site-page', template, directives: [LeftMenuProfileComponent, RouterLink, ROUTER_DIRECTIVES, APP_COMMON_DIRECTIVES] }) @RouteConfig([ { name: 'AboutUs', path: '/about-us', component: AboutUsComponent, useAsDefault: true }, { name: 'TermsAndCondition', path: '/terms-and-condition', component: TermsAndConditionComponent }, { name: 'PrivacyPolicy', path: '/privacy-policy', component: PrivacyPolicyComponent } ]) export class SiteComponent { }<file_sep>/source2/devcontrolpanel/imports/api/server/user/meteor-user-methods.ts import {Meteor} from 'meteor/meteor'; import {Accounts} from 'meteor/accounts-base'; var twitterAPI = require('node-twitter-api'); var githubAPI = require('octonode'); Meteor.methods({ sendUserVerificationEmail: () => { Accounts.sendVerificationEmail(Meteor.userId()); console.log('Verification Email sent'); }, updateThirdPartyUser: () => { let userId = Meteor.userId(); if (userId) { let user = Meteor.users.findOne({ _id: userId }); if (user.services.twitter) { let twitterConfig = Meteor.settings['socialConfig'].twitter; let twitter = new twitterAPI({ consumerKey: twitterConfig.consumerKey, consumerSecret: twitterConfig.secret }); twitter.verifyCredentials(user.services.twitter.accessToken, user.services.twitter.accessTokenSecret, {}, Meteor.bindEnvironment((err, data, response) => { if (!err) { Meteor.users.update({ _id: userId }, { $set: { 'services.twitter.name': data.name, 'services.twitter.profile_image_url_https': data.profile_image_url_https } }); } })); } else if (user.services.github) { var client = githubAPI.client(user.services.github.accessToken); client.get('/user', {}, Meteor.bindEnvironment((err, status, body, headers) => { Meteor.users.update({ _id: userId }, { $set: { 'services.github.name': body.name, 'services.github.picture': body.avatar_url } }); })); } else if (user.services.facebook) { let facebookUrl = 'http://graph.facebook.com/' + user.services.facebook.id + '/picture?type=large&redirect=true&width=500&height=500'; Meteor.users.update({ _id: userId }, { $set: { 'services.facebook.picture': facebookUrl } }); } } } })<file_sep>/source2/devcontrolpanel/imports/ui/directives/highlight-editor.directive.ts import { Directive, Input, ElementRef, Renderer} from '@angular/core'; @Directive({ selector: 'pre > code' }) export class HighlightEditorDirective { private elementRef: ElementRef; private renderer: Renderer; constructor(elementRef: ElementRef, renderer: Renderer) { this.elementRef = elementRef; this.renderer = renderer; hljs.highlightBlock(this.elementRef.nativeElement); } }<file_sep>/source2/devcontrolpanel/imports/api/server/wall-post/tag-methods.ts import {Meteor} from 'meteor/meteor'; import {Mongo} from 'meteor/mongo'; import {WallPostCollection} from '../../../services/wall-post.service'; import {IWallPost} from '../../../common/wall-post.model'; var _ = require('lodash'); Meteor.methods({ 'getUserTags': (): string[] => { let tags: string[][] = WallPostCollection.find({ 'tag.0': { $exists: true } }).fetch().map(data => { return _.map(data.tag, (tag) => { return tag.name; }); }); return _.uniq(_.reduce(tags, (prevResult: string[], currentValue) => { return _.concat(prevResult, currentValue) }, [])); }, 'getAllTags': (): string[] => { let tags: string[][] = WallPostCollection.find({ 'tag.0': { $exists: true } }).fetch().map(data => { return _.map(data.tag, (tag) => { return tag.name; }); }); return _.uniq(_.reduce(tags, (prevResult: string[], currentValue) => { return _.concat(prevResult, currentValue) }, [])); } }); <file_sep>/source2/devcontrolpanel/imports/ui/components/my-profile-component/component/my-profile-reset-password-component/model/reset-password-model.ts export interface IResetPasswordModel{ currentPassword: string; newPassword: string; retypeNewPassword: string; isLoading: boolean; }<file_sep>/source2/devcontrolpanel/server/config/db.ts import {WallPostCollection} from '../../imports/services/wall-post.service'; export function initiateDBQueries() { // WallPostCollection._ensureIndex('wallPostSearch', { // title: 'text', // content: 'text', // weight: { title: 5, content: 10 } // }); } <file_sep>/source2/devcontrolpanel/imports/ui/components/left-menu-profile-component/left-menu-profile.component.ts //library imports import {Component, provide, Inject, NgZone} from '@angular/core'; import { RouterLink } from '@angular/router-deprecated'; import {Meteor} from 'meteor/meteor'; //common diretives import {ActiveMenuDirective} from '../../directives/active-menu.directive'; //within the app import {SemanticSidebar, SemanticRibbler, SemanticSidebarToggleControl} from '../../directives/semantic.directive'; import {AppFactory, OAppConfig, APP_CONFIG, LinkClickedName, IAppConfig} from '../../services/config.service'; import {AppComponent} from '../common/app-component'; import {GlobalEventSerice} from '../../services/global-event.service'; //other module component import {UserProfileImageComponent} from '../user-profile-image-component/user-profile-image.component'; import {LinkClickService} from '../devcontrolpanel/service/link-click.service' import template from './template/left-menu-profile.template.html'; @Component({ selector: 'left-menu-profile', template, directives: [RouterLink, SemanticRibbler, ActiveMenuDirective, UserProfileImageComponent] }) export class LeftMenuProfileComponent extends AppComponent { constructor(appFactory: AppFactory, globalEventSerice: GlobalEventSerice, private linkClickService: LinkClickService ) { super(appFactory, globalEventSerice); } signinClick(){ this.linkClickService.signinLinkClick(); } }<file_sep>/source2/devcontrolpanel/imports/ui/directives/semantic.directive.ts //import 'reflect-metadata'; import { Directive, Input, Output, ElementRef, HostBinding, Renderer, EventEmitter} from '@angular/core'; import {OnInit, AfterViewInit, AfterViewChecked, OnDestroy} from '@angular/core'; @Directive({ selector: '.ui.radio.checkbox' }) export class SemanticCheckbox { private elementRef: ElementRef; private renderer: Renderer; constructor(elementRef: ElementRef, renderer: Renderer) { this.elementRef = elementRef; this.renderer = renderer; } ngAfterViewInit() { jQuery(this.elementRef.nativeElement) .checkbox(); } } @Directive({ selector: '.ui.accordion' }) export class SemanticAccordion { private elementRef: ElementRef; private renderer: Renderer; constructor(elementRef: ElementRef, renderer: Renderer) { this.elementRef = elementRef; this.renderer = renderer; } ngAfterViewInit() { jQuery(this.elementRef.nativeElement) .accordion(); } } @Directive({ selector: '.sticky-element' }) export class SemanticSticky { private elementRef: ElementRef; private renderer: Renderer; settingsValue: any; constructor(elementRef: ElementRef, renderer: Renderer) { this.elementRef = elementRef; this.renderer = renderer; } @Input('semanticStickySettings') set settings(value: string) { this.settingsValue = value; } ngAfterViewInit() { let settings = _.defaults(this.settingsValue || {}, { topSpacing: '4.2em' }); jQuery(this.elementRef.nativeElement) .sticky(settings); } } @Directive({ selector: '.sidebar.icon' }) export class SemanticSidebarToggleControl { private elementRef: ElementRef; private renderer: Renderer; constructor(elementRef: ElementRef, renderer: Renderer) { this.elementRef = elementRef; this.renderer = renderer; } ngAfterViewInit() { jQuery(this.elementRef.nativeElement).on('click', () => { jQuery('div.sidebar').sidebar('toggle'); }); } } @Directive({ selector: 'div.sidebar' }) export class SemanticSidebar { private elementRef: ElementRef; private renderer: Renderer; constructor(elementRef: ElementRef, renderer: Renderer) { this.elementRef = elementRef; this.renderer = renderer; } ngAfterViewInit() { jQuery(this.elementRef.nativeElement) .sidebar({ dimPage: false, closable: false }); } } @Directive({ selector: '.rippler' }) export class SemanticRibbler implements AfterViewInit { private elementRef: ElementRef; private renderer: Renderer; constructor(elementRef: ElementRef, renderer: Renderer) { this.elementRef = elementRef; this.renderer = renderer; } ngAfterViewInit() { //console.log('rippler init'); jQuery(this.elementRef.nativeElement) .rippler({ effectClass: 'rippler-effect' , effectSize: 0 // Default size (width & height) , addElement: 'div' // e.g. 'svg'(feature) , duration: 400 }); } } @Directive({ selector: '.highlight-bg-element' }) export class SemanticHighlightBgElement { private elementRef: ElementRef; private renderer: Renderer; constructor(elementRef: ElementRef, renderer: Renderer) { this.elementRef = elementRef; this.renderer = renderer; } ngAfterViewInit() { setTimeout(() => { jQuery(this.elementRef.nativeElement).removeClass('highlight-bg-element'); }, 7000); } } @Directive({ selector: '.ui.dropdown' }) export class SemanticDropdown { private elementRef: ElementRef; private renderer: Renderer; private dropDownSettings: any; private value: string; private isClearField: boolean; constructor(elementRef: ElementRef, renderer: Renderer) { this.elementRef = elementRef; this.renderer = renderer; } @Input('semanticDropDownSettings') set settings(value: any) { this.dropDownSettings = _.defaults(value || {}, { allowAdditions: false, // onChange: (value, text, $choice) => { // // this.value = jQuery(this.elementRef.nativeElement).val(); // } }); } @Input('semanticDropDownClear') set semanticDropDownClear(value: boolean) { this.isClearField = value; if (this.isClearField) { this.isClearField = false; jQuery(this.elementRef.nativeElement) .dropdown('clear'); jQuery(this.elementRef.nativeElement) .dropdown('restore default value'); } else { this.isClearField = false; } } @Input('semanticDropDownData') set semanticDropDownData(data: string[]) { jQuery(this.elementRef.nativeElement) .dropdown('set exactly', data); } @Input() set initiateSemanticDropdown(value: boolean) { jQuery(this.elementRef.nativeElement) .dropdown(this.dropDownSettings); } ngAfterViewInit() { jQuery(this.elementRef.nativeElement) .dropdown(this.dropDownSettings); } // @HostBinding('value') // get Value() { // return "sathishkumar" // } } // // @Directive({ // selector: '[data-value]' // }) // export class DataValueAttr { // private value: string; // // @Input("data-value") set DataValueAttr(value: string) { // this.value = value; // } // // } @Directive({ selector: '.semantic-popup' }) export class SemanticPopup implements OnDestroy { private elementRef: ElementRef; private renderer: Renderer; private popupSettings: any = {}; private semanticPopupVisibilityValue: boolean; private isViewInitDone: boolean; constructor(elementRef: ElementRef, renderer: Renderer) { this.elementRef = elementRef; this.renderer = renderer; } @Input('semanticPopupSettings') set settings(value: string) { this.popupSettings = value; } @Input() set semanticPopupVisibility(value: boolean) { debugger; if (this.isViewInitDone && value != null) { this.semanticPopupVisibilityValue = value; jQuery(this.elementRef.nativeElement) .popup(this.semanticPopupVisibilityValue ? 'show' : 'hide'); } } ngAfterViewInit() { var settings = _.defaults(this.popupSettings || {}, { on: 'click', hoverable: false, exclusive: true, preserve: true, position: 'top left', transition: 'vertical flip' }); jQuery(this.elementRef.nativeElement) .popup(settings); this.isViewInitDone = true; } ngOnDestroy(){ } } @Directive({ selector: '.semantic-modal' }) export class SemanticModal implements OnDestroy { private elementRef: ElementRef; private renderer: Renderer; private modalSettings: any = {}; private semanticModalVisibilityValue: boolean; private isViewInitDone: boolean; constructor(elementRef: ElementRef, renderer: Renderer) { this.elementRef = elementRef; this.renderer = renderer; } @Output() modalEvent = new EventEmitter(); @Input('semanticModalSettings') set settings(value: string) { this.modalSettings = value; } @Input() set semanticModalVisibility(value: boolean) { if (this.isViewInitDone && value != null) { this.semanticModalVisibilityValue = value; let modelEventType = this.semanticModalVisibilityValue ? 'show' : 'hide'; jQuery(this.elementRef.nativeElement) .modal(modelEventType); this.modalEvent.emit(modelEventType); } } ngAfterViewInit() { var settings = _.defaults(this.modalSettings || {}, { on: 'click', hoverable: false, exclusive: true, preserve: true, position: 'top left', transition: 'vertical flip' }); jQuery(this.elementRef.nativeElement) .popup(settings); this.isViewInitDone = true; } ngOnDestroy(){ } } @Directive({ selector: '.semantic-sortable' }) export class SemanticSortable { private elementRef: ElementRef; private renderer: Renderer; private sortableSettings: any = {}; private isViewInitDone: boolean; constructor(elementRef: ElementRef, renderer: Renderer) { this.elementRef = elementRef; this.renderer = renderer; } @Input() set semanticSortableSettings(value: string) { this.sortableSettings = value; } ngAfterViewInit() { var settings = _.defaults(this.sortableSettings || {}, { }); jQuery(this.elementRef.nativeElement) .sortable(settings); this.isViewInitDone = true; } } // @Directive({ // selector: '[image-cropper]' // }) // export class ImageCropperDirective { // private elementRef: ElementRef; // private renderer: Renderer; // private settings: any = {}; // constructor(elementRef: ElementRef, renderer: Renderer) { // this.elementRef = elementRef; // this.renderer = renderer; // } // @Input() set imageCropperSettings(value: string) { // this.settings = value; // } // ngAfterViewInit() { // // var settings = _.defaults(this.settings || {}, { // // aspectRatio: 16 / 9, // // crop: function (e) { // // // Output the result data for cropping image. // // console.log(e.x); // // console.log(e.y); // // console.log(e.width); // // console.log(e.height); // // console.log(e.rotate); // // console.log(e.scaleX); // // console.log(e.scaleY); // // } // // }); // // jQuery(this.elementRef.nativeElement) // // .cropper(settings); // } // }<file_sep>/source2/devcontrolpanel/imports/ui/components/my-profile-component/component/my-profile-reset-password-component/my-profile-reset-password.component.ts //library imports import {Component, provide, Inject, NgZone} from '@angular/core'; import { RouterLink } from '@angular/router-deprecated'; import { FORM_DIRECTIVES, FormBuilder, Validators, CORE_DIRECTIVES, ControlGroup} from '@angular/common'; import {Accounts} from 'meteor/accounts-base'; //with in the app import {APP_COMMON_DIRECTIVES} from '../../../../directives/app-common.directive'; import {AppFactory} from '../../../../services/config.service'; import {matchingPasswords} from '../../../../form-validator/validators'; //with in the component import {IResetPasswordModel} from './model/reset-password-model'; import template from './template/my-profile-reset-password.template.html' @Component({ selector: 'my-profile-reset-password', template, directives: [RouterLink, APP_COMMON_DIRECTIVES, FORM_DIRECTIVES] }) export class MyProfileResetPasswordComponent { resetPasswordForm: ControlGroup; isFormSubmitLoading: boolean = false; formSubmitError: string = ''; isFormSuccess: boolean = false; // resetPasswordModel: IResetPasswordModel; constructor(private formBuilder: FormBuilder) { //initialize form this.resetPasswordForm = this.formBuilder.group({ currentPassword: ['', Validators.required], newPassword: ['', Validators.required], retypeNewPassword: ['', Validators.required], }, { validator: matchingPasswords('newPassword', 'retypeNewPassword') }); this.isFormSuccess = false; } resetPassword(resetPasswordModel: IResetPasswordModel) { this.isFormSubmitLoading = true; this.formSubmitError = ''; Accounts.changePassword(resetPasswordModel.currentPassword, resetPasswordModel.newPassword, (error) => { this.isFormSubmitLoading = false; if (error) { this.isFormSuccess = false; if (error.message.indexOf('Incorrect password') > -1) { this.formSubmitError = 'Current password is wrong'; } else { this.formSubmitError = error; } } else { this.isFormSuccess = true; this.resetForm(); } }); } onFormChange() { this.formSubmitError = ''; } resetForm() { _.forEach(this.resetPasswordForm.controls, (control, name) => { control.updateValueAndValidity(''); }); } }<file_sep>/source2/devcontrolpanel/imports/ui/components/devcontrolpanel/devcontrolpanel.component.ts //library imports import {Component, provide, Inject, NgZone} from '@angular/core'; import {SemanticSidebar, SemanticRibbler, SemanticSidebarToggleControl} from '../../directives/semantic.directive'; import { ROUTER_DIRECTIVES, RouteConfig, RouterLink, CanActivate } from '@angular/router-deprecated'; import {Meteor} from 'meteor/meteor'; //global imports import {GlobalEventSerice} from '../../services/global-event.service'; import {AppFactory, OAppConfig, APP_CONFIG, LinkClickedName, IAppConfig} from '../../services/config.service'; //common diretives import {APP_COMMON_DIRECTIVES} from '../../directives/app-common.directive'; import {canActivateRoute} from '../../services/can-activate-route.service'; import {UserProfileUtils} from '../../../common/user-profile-util'; //from other components import {SiteAuthComponent} from '../site-auth-component/site-auth.component'; import {WallPostComponent} from '../wall-post-component/wall-post.component'; import {VerifyEmailComponent} from '../verify-email-component/verify-email.component'; import {MyProfileComponent} from '../my-profile-component/my-profile.component'; import {SiteComponent} from '../site-component/site.component'; //component specific import {LinkClickService} from './service/link-click.service'; import {AuthStatusService} from './service/auth-status.service'; import template from './template/devcontrolpanel.template.html' @Component({ selector: 'devcontrolpanel', template, directives: [ SiteAuthComponent, ROUTER_DIRECTIVES, RouterLink, APP_COMMON_DIRECTIVES ], providers: [GlobalEventSerice, LinkClickService, AuthStatusService, UserProfileUtils, AppFactory, provide(OAppConfig, { useValue: APP_CONFIG })] }) @RouteConfig([ { path: '/wall-post/...', name: 'WallpostHome', component: WallPostComponent, useAsDefault: true }, { path: '/my-profile/...', name: 'MyProfile', component: MyProfileComponent }, { path: '/verify-email/:token', name: 'VerifyEmailPage', component: VerifyEmailComponent }, { path: '/site/...', name: 'Site', component: SiteComponent }, { path: '/**', redirectTo: ['WallpostHome'] } ]) @CanActivate((next, prev) => { return canActivateRoute(next, prev, false); }) export class DevcontrolpanelComponent { semanticStickySettings: any = { topSpacing: '4.2em', widthFromWrapper: false }; adContainerId = ''; constructor(private globalEventSerice: GlobalEventSerice, private linkClickService: LinkClickService, private authStatusService: AuthStatusService, @Inject(OAppConfig) private appConfig: IAppConfig, private appFactory: AppFactory, private ngZone: NgZone, private userProfileUtils: UserProfileUtils ) { if (window.CHITIKA === undefined) { window.CHITIKA = { 'units': [] }; }; var unit = { "calltype": "async[2]", "publisher": "ittechsathish", "width": 160, "height": 600, "sid": "Chitika Default" }; this.adContainerId = window.CHITIKA.units.length; window.CHITIKA.units.push(unit); } }<file_sep>/source2/devcontrolpanel/imports/ui/components/devcontrolpanel/service/auth-status.service.ts import {Injectable, NgZone} from '@angular/core'; //global import {GlobalEventSerice} from '../../../services/global-event.service'; import {AppFactory, AuthStatus} from '../../../services/config.service'; //component @Injectable() export class AuthStatusService { constructor( private _globalEventSerice: GlobalEventSerice, private _appFactory: AppFactory, private ngZone: NgZone ) { this.ngZone.runOutsideAngular(() => { //subscribe to the userprofile values from the server Meteor.subscribe("userData", () => { Meteor.subscribe("allUserData", () => { Tracker.autorun(() => { this.ngZone.run(() => { if (Meteor.userId()) { this._globalEventSerice.authStatusChangeEvent(AuthStatus.AUTHENTICATED); } else { this._globalEventSerice.authStatusChangeEvent(AuthStatus.UNAUTHENTICATED); } }); }); }); }); }); } }<file_sep>/source2/devcontrolpanel/imports/api/server/rest/sitemap/sitemap-builder.ts import {SitemapCollection} from '../../../../services/sitemap.service'; import {ISitemapCollection} from '../../../../common/sitemap.model'; let fs = require('fs'); var et = require('elementtree'); export function getSitemap() { var XML = et.XML; var ElementTree = et.ElementTree; var element = et.Element; var subElement = et.SubElement; let root = element('urlset'); root.set('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9'); let getDateFormatted = () => { var dateObj = new Date(); var month = dateObj.getUTCMonth() + 1; //months from 1-12 var day = dateObj.getUTCDate(); var year = dateObj.getUTCFullYear(); return year + "-" + month + "-" + day; } let generateUrlElement = () => { } SitemapCollection.find({}).forEach((doc: ISitemapCollection) => { let urlTag = subElement(root, 'url'); let locationTag = subElement(urlTag, 'loc'); if (doc.contentType == 'Wallpost') { locationTag.text = 'https://www.devcontrolpanel.com/wall-post/detail/' + doc.contentId; if (doc.isRemoved) { let removedTag = subElement(urlTag, 'expires'); removedTag.text = getDateFormatted(); } } }); var etree = new ElementTree(root); var output_xml = etree.write({ 'xml_declaration': true }); return output_xml; } <file_sep>/source2/devcontrolpanel/imports/ui/components/my-profile-component/component/my-profile-info-component/my-profile-info.component.ts //library imports import {Component, provide, Inject, NgZone} from '@angular/core'; import { RouterLink } from '@angular/router-deprecated'; import {Meteor} from 'meteor/meteor'; //with in the app import {SemanticSidebar, SemanticRibbler, SemanticSidebarToggleControl} from '../../../../directives/semantic.directive'; import {IUserProfile, LoginType} from '../../../../../common/user-profile-model'; import {AppFactory} from '../../../../services/config.service'; //other components import {UserProfileImageComponent} from '../../../user-profile-image-component/user-profile-image.component'; import {AppComponent} from '../../../common/app-component'; import {GlobalEventSerice} from '../../../../services/global-event.service'; import template from './template/my-profile-info.template.html'; @Component({ selector: 'my-profile-info', template, directives: [RouterLink, SemanticRibbler, UserProfileImageComponent] }) export class MyProfileInfoComponent extends AppComponent { userId: string; user: IUserProfile; loginType: typeof LoginType = LoginType; constructor( appFactory: AppFactory, globalEventSerice: GlobalEventSerice ) { super(appFactory, globalEventSerice); } }<file_sep>/source2/devcontrolpanel/imports/ui/components/wall-post-component/component/wall-post-card-component/service/wall-post-card.service.ts import {IWallPost} from '../../../../../../common/wall-post.model'; import { WallPostCollection } from '../../../../../../services/wall-post.service'; export class WallPostCardService { // getWallPostDetail(postId: string): Promise<IWallPost> { // return new Promise<IWallPost>((resolve, reject) => { // Meteor.call('getWallPostDetail', postId, (error, data) => { // if(error) // { // reject(error); // } // else{ // resolve(data); // } // }); // }); // } // deletePost(postId: string) : Promise<string>{ // return new Promise<string>((resolve, reject) => { // WallPostCollection.remove({_id : postId}, (err) =>{ // resolve(err); // }); // }); // } }<file_sep>/source2/devcontrolpanel/imports/services/user.service.ts // import {IUserCollection} from '../common/user-profile-model'; // import {Mongo} from 'meteor/mongo'; // export let userCollection = <file_sep>/source2/devcontrolpanel/imports/startups/client/scripts/load-image/load-image.all.min.js /* * JavaScript Load Image * https://github.com/blueimp/JavaScript-Load-Image * * Copyright 2011, <NAME> * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /*global define, module, window, document, URL, webkitURL, FileReader */ ; (function ($) { 'use strict' // Loads an image for a given File object. // Invokes the callback with an img or optional canvas // element (if supported by the browser) as parameter: var loadImage = function (file, callback, options) { var img = document.createElement('img') var url var oUrl img.onerror = callback img.onload = function () { if (oUrl && !(options && options.noRevoke)) { loadImage.revokeObjectURL(oUrl) } if (callback) { callback(loadImage.scale(img, options)) } } if (loadImage.isInstanceOf('Blob', file) || // Files are also Blob instances, but some browsers // (Firefox 3.6) support the File API but not Blobs: loadImage.isInstanceOf('File', file)) { url = oUrl = loadImage.createObjectURL(file) // Store the file type for resize processing: img._type = file.type } else if (typeof file === 'string') { url = file if (options && options.crossOrigin) { img.crossOrigin = options.crossOrigin } } else { return false } if (url) { img.src = url return img } return loadImage.readFile(file, function (e) { var target = e.target if (target && target.result) { img.src = target.result } else { if (callback) { callback(e) } } }) } // The check for URL.revokeObjectURL fixes an issue with Opera 12, // which provides URL.createObjectURL but doesn't properly implement it: var urlAPI = (window.createObjectURL && window) || (window.URL && URL.revokeObjectURL && URL) || (window.webkitURL && webkitURL) loadImage.isInstanceOf = function (type, obj) { // Cross-frame instanceof check return Object.prototype.toString.call(obj) === '[object ' + type + ']' } // Transform image coordinates, allows to override e.g. // the canvas orientation based on the orientation option, // gets canvas, options passed as arguments: loadImage.transformCoordinates = function () { return } // Returns transformed options, allows to override e.g. // maxWidth, maxHeight and crop options based on the aspectRatio. // gets img, options passed as arguments: loadImage.getTransformedOptions = function (img, options) { var aspectRatio = options.aspectRatio var newOptions var i var width var height if (!aspectRatio) { return options } newOptions = {} for (i in options) { if (options.hasOwnProperty(i)) { newOptions[i] = options[i] } } newOptions.crop = true width = img.naturalWidth || img.width height = img.naturalHeight || img.height if (width / height > aspectRatio) { newOptions.maxWidth = height * aspectRatio newOptions.maxHeight = height } else { newOptions.maxWidth = width newOptions.maxHeight = width / aspectRatio } return newOptions } // Canvas render method, allows to implement a different rendering algorithm: loadImage.renderImageToCanvas = function ( canvas, img, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight ) { canvas.getContext('2d').drawImage( img, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight ) return canvas } // This method is used to determine if the target image // should be a canvas element: loadImage.hasCanvasOption = function (options) { return options.canvas || options.crop || !!options.aspectRatio } // Scales and/or crops the given image (img or canvas HTML element) // using the given options. // Returns a canvas object if the browser supports canvas // and the hasCanvasOption method returns true or a canvas // object is passed as image, else the scaled image: loadImage.scale = function (img, options) { options = options || {} var canvas = document.createElement('canvas') var useCanvas = img.getContext || (loadImage.hasCanvasOption(options) && canvas.getContext) var width = img.naturalWidth || img.width var height = img.naturalHeight || img.height var destWidth = width var destHeight = height var maxWidth var maxHeight var minWidth var minHeight var sourceWidth var sourceHeight var sourceX var sourceY var pixelRatio var downsamplingRatio var tmp function scaleUp() { var scale = Math.max( (minWidth || destWidth) / destWidth, (minHeight || destHeight) / destHeight ) if (scale > 1) { destWidth *= scale destHeight *= scale } } function scaleDown() { var scale = Math.min( (maxWidth || destWidth) / destWidth, (maxHeight || destHeight) / destHeight ) if (scale < 1) { destWidth *= scale destHeight *= scale } } if (useCanvas) { options = loadImage.getTransformedOptions(img, options) sourceX = options.left || 0 sourceY = options.top || 0 if (options.sourceWidth) { sourceWidth = options.sourceWidth if (options.right !== undefined && options.left === undefined) { sourceX = width - sourceWidth - options.right } } else { sourceWidth = width - sourceX - (options.right || 0) } if (options.sourceHeight) { sourceHeight = options.sourceHeight if (options.bottom !== undefined && options.top === undefined) { sourceY = height - sourceHeight - options.bottom } } else { sourceHeight = height - sourceY - (options.bottom || 0) } destWidth = sourceWidth destHeight = sourceHeight } maxWidth = options.maxWidth maxHeight = options.maxHeight minWidth = options.minWidth minHeight = options.minHeight if (useCanvas && maxWidth && maxHeight && options.crop) { destWidth = maxWidth destHeight = maxHeight tmp = sourceWidth / sourceHeight - maxWidth / maxHeight if (tmp < 0) { sourceHeight = maxHeight * sourceWidth / maxWidth if (options.top === undefined && options.bottom === undefined) { sourceY = (height - sourceHeight) / 2 } } else if (tmp > 0) { sourceWidth = maxWidth * sourceHeight / maxHeight if (options.left === undefined && options.right === undefined) { sourceX = (width - sourceWidth) / 2 } } } else { if (options.contain || options.cover) { minWidth = maxWidth = maxWidth || minWidth minHeight = maxHeight = maxHeight || minHeight } if (options.cover) { scaleDown() scaleUp() } else { scaleUp() scaleDown() } } if (useCanvas) { pixelRatio = options.pixelRatio if (pixelRatio > 1) { canvas.style.width = destWidth + 'px' canvas.style.height = destHeight + 'px' destWidth *= pixelRatio destHeight *= pixelRatio canvas.getContext('2d').scale(pixelRatio, pixelRatio) } downsamplingRatio = options.downsamplingRatio if (downsamplingRatio > 0 && downsamplingRatio < 1 && destWidth < sourceWidth && destHeight < sourceHeight) { while (sourceWidth * downsamplingRatio > destWidth) { canvas.width = sourceWidth * downsamplingRatio canvas.height = sourceHeight * downsamplingRatio loadImage.renderImageToCanvas( canvas, img, sourceX, sourceY, sourceWidth, sourceHeight, 0, 0, canvas.width, canvas.height ) sourceWidth = canvas.width sourceHeight = canvas.height img = document.createElement('canvas') img.width = sourceWidth img.height = sourceHeight loadImage.renderImageToCanvas( img, canvas, 0, 0, sourceWidth, sourceHeight, 0, 0, sourceWidth, sourceHeight ) } } canvas.width = destWidth canvas.height = destHeight loadImage.transformCoordinates( canvas, options ) return loadImage.renderImageToCanvas( canvas, img, sourceX, sourceY, sourceWidth, sourceHeight, 0, 0, destWidth, destHeight ) } img.width = destWidth img.height = destHeight return img } loadImage.createObjectURL = function (file) { return urlAPI ? urlAPI.createObjectURL(file) : false } loadImage.revokeObjectURL = function (url) { return urlAPI ? urlAPI.revokeObjectURL(url) : false } // Loads a given File object via FileReader interface, // invokes the callback with the event object (load or error). // The result can be read via event.target.result: loadImage.readFile = function (file, callback, method) { if (window.FileReader) { var fileReader = new FileReader() fileReader.onload = fileReader.onerror = callback method = method || 'readAsDataURL' if (fileReader[method]) { fileReader[method](file) return fileReader } } return false } // if (typeof define === 'function' && define.amd) { // define(function () { // return loadImage // }) // } else if (typeof module === 'object' && module.exports) { // module.exports = loadImage // } else { $.loadImage = loadImage // } } (window)) /* * JavaScript Load Image Meta * https://github.com/blueimp/JavaScript-Load-Image * * Copyright 2013, <NAME> * https://blueimp.net * * Image meta data handling implementation * based on the help and contribution of * <NAME>. * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /*global define, module, require, window, DataView, Blob, Uint8Array, console */ ; (function (factory) { 'use strict' // if (typeof define === 'function' && define.amd) { // // Register as an anonymous AMD module: // define(['./load-image'], factory) // } else if (typeof module === 'object' && module.exports) { // factory(require('./load-image')) // } else { // Browser globals: factory(window.loadImage) //} } (function (loadImage) { 'use strict' var hasblobSlice = window.Blob && (Blob.prototype.slice || Blob.prototype.webkitSlice || Blob.prototype.mozSlice) loadImage.blobSlice = hasblobSlice && function () { var slice = this.slice || this.webkitSlice || this.mozSlice return slice.apply(this, arguments) } loadImage.metaDataParsers = { jpeg: { 0xffe1: [] // APP1 marker } } // Parses image meta data and calls the callback with an object argument // with the following properties: // * imageHead: The complete image head as ArrayBuffer (Uint8Array for IE10) // The options arguments accepts an object and supports the following properties: // * maxMetaDataSize: Defines the maximum number of bytes to parse. // * disableImageHead: Disables creating the imageHead property. loadImage.parseMetaData = function (file, callback, options) { options = options || {} var that = this // 256 KiB should contain all EXIF/ICC/IPTC segments: var maxMetaDataSize = options.maxMetaDataSize || 262144 var data = {} var noMetaData = !(window.DataView && file && file.size >= 12 && file.type === 'image/jpeg' && loadImage.blobSlice) if (noMetaData || !loadImage.readFile( loadImage.blobSlice.call(file, 0, maxMetaDataSize), function (e) { if (e.target.error) { // FileReader error console.log(e.target.error) callback(data) return } // Note on endianness: // Since the marker and length bytes in JPEG files are always // stored in big endian order, we can leave the endian parameter // of the DataView methods undefined, defaulting to big endian. var buffer = e.target.result var dataView = new DataView(buffer) var offset = 2 var maxOffset = dataView.byteLength - 4 var headLength = offset var markerBytes var markerLength var parsers var i // Check for the JPEG marker (0xffd8): if (dataView.getUint16(0) === 0xffd8) { while (offset < maxOffset) { markerBytes = dataView.getUint16(offset) // Search for APPn (0xffeN) and COM (0xfffe) markers, // which contain application-specific meta-data like // Exif, ICC and IPTC data and text comments: if ((markerBytes >= 0xffe0 && markerBytes <= 0xffef) || markerBytes === 0xfffe) { // The marker bytes (2) are always followed by // the length bytes (2), indicating the length of the // marker segment, which includes the length bytes, // but not the marker bytes, so we add 2: markerLength = dataView.getUint16(offset + 2) + 2 if (offset + markerLength > dataView.byteLength) { console.log('Invalid meta data: Invalid segment size.') break } parsers = loadImage.metaDataParsers.jpeg[markerBytes] if (parsers) { for (i = 0; i < parsers.length; i += 1) { parsers[i].call( that, dataView, offset, markerLength, data, options ) } } offset += markerLength headLength = offset } else { // Not an APPn or COM marker, probably safe to // assume that this is the end of the meta data break } } // Meta length must be longer than JPEG marker (2) // plus APPn marker (2), followed by length bytes (2): if (!options.disableImageHead && headLength > 6) { if (buffer.slice) { data.imageHead = buffer.slice(0, headLength) } else { // Workaround for IE10, which does not yet // support ArrayBuffer.slice: data.imageHead = new Uint8Array(buffer) .subarray(0, headLength) } } } else { console.log('Invalid JPEG file: Missing JPEG marker.') } callback(data) }, 'readAsArrayBuffer' )) { callback(data) } } })) /* * JavaScript Load Image Exif Parser * https://github.com/blueimp/JavaScript-Load-Image * * Copyright 2013, <NAME> * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /*global define, module, require, window, console */ ; (function (factory) { 'use strict' factory(window.loadImage) } (function (loadImage) { 'use strict' loadImage.ExifMap = function () { return this } loadImage.ExifMap.prototype.map = { 'Orientation': 0x0112 } loadImage.ExifMap.prototype.get = function (id) { return this[id] || this[this.map[id]] } loadImage.getExifThumbnail = function (dataView, offset, length) { var hexData, i, b if (!length || offset + length > dataView.byteLength) { console.log('Invalid Exif data: Invalid thumbnail data.') return } hexData = [] for (i = 0; i < length; i += 1) { b = dataView.getUint8(offset + i) hexData.push((b < 16 ? '0' : '') + b.toString(16)) } return 'data:image/jpeg,%' + hexData.join('%') } loadImage.exifTagTypes = { // byte, 8-bit unsigned int: 1: { getValue: function (dataView, dataOffset) { return dataView.getUint8(dataOffset) }, size: 1 }, // ascii, 8-bit byte: 2: { getValue: function (dataView, dataOffset) { return String.fromCharCode(dataView.getUint8(dataOffset)) }, size: 1, ascii: true }, // short, 16 bit int: 3: { getValue: function (dataView, dataOffset, littleEndian) { return dataView.getUint16(dataOffset, littleEndian) }, size: 2 }, // long, 32 bit int: 4: { getValue: function (dataView, dataOffset, littleEndian) { return dataView.getUint32(dataOffset, littleEndian) }, size: 4 }, // rational = two long values, first is numerator, second is denominator: 5: { getValue: function (dataView, dataOffset, littleEndian) { return dataView.getUint32(dataOffset, littleEndian) / dataView.getUint32(dataOffset + 4, littleEndian) }, size: 8 }, // slong, 32 bit signed int: 9: { getValue: function (dataView, dataOffset, littleEndian) { return dataView.getInt32(dataOffset, littleEndian) }, size: 4 }, // srational, two slongs, first is numerator, second is denominator: 10: { getValue: function (dataView, dataOffset, littleEndian) { return dataView.getInt32(dataOffset, littleEndian) / dataView.getInt32(dataOffset + 4, littleEndian) }, size: 8 } } // undefined, 8-bit byte, value depending on field: loadImage.exifTagTypes[7] = loadImage.exifTagTypes[1] loadImage.getExifValue = function (dataView, tiffOffset, offset, type, length, littleEndian) { var tagType = loadImage.exifTagTypes[type] var tagSize var dataOffset var values var i var str var c if (!tagType) { console.log('Invalid Exif data: Invalid tag type.') return } tagSize = tagType.size * length // Determine if the value is contained in the dataOffset bytes, // or if the value at the dataOffset is a pointer to the actual data: dataOffset = tagSize > 4 ? tiffOffset + dataView.getUint32(offset + 8, littleEndian) : (offset + 8) if (dataOffset + tagSize > dataView.byteLength) { console.log('Invalid Exif data: Invalid data offset.') return } if (length === 1) { return tagType.getValue(dataView, dataOffset, littleEndian) } values = [] for (i = 0; i < length; i += 1) { values[i] = tagType.getValue(dataView, dataOffset + i * tagType.size, littleEndian) } if (tagType.ascii) { str = '' // Concatenate the chars: for (i = 0; i < values.length; i += 1) { c = values[i] // Ignore the terminating NULL byte(s): if (c === '\u0000') { break } str += c } return str } return values } loadImage.parseExifTag = function (dataView, tiffOffset, offset, littleEndian, data) { var tag = dataView.getUint16(offset, littleEndian) data.exif[tag] = loadImage.getExifValue( dataView, tiffOffset, offset, dataView.getUint16(offset + 2, littleEndian), // tag type dataView.getUint32(offset + 4, littleEndian), // tag length littleEndian ) } loadImage.parseExifTags = function (dataView, tiffOffset, dirOffset, littleEndian, data) { var tagsNumber, dirEndOffset, i if (dirOffset + 6 > dataView.byteLength) { console.log('Invalid Exif data: Invalid directory offset.') return } tagsNumber = dataView.getUint16(dirOffset, littleEndian) dirEndOffset = dirOffset + 2 + 12 * tagsNumber if (dirEndOffset + 4 > dataView.byteLength) { console.log('Invalid Exif data: Invalid directory size.') return } for (i = 0; i < tagsNumber; i += 1) { this.parseExifTag( dataView, tiffOffset, dirOffset + 2 + 12 * i, // tag offset littleEndian, data ) } // Return the offset to the next directory: return dataView.getUint32(dirEndOffset, littleEndian) } loadImage.parseExifData = function (dataView, offset, length, data, options) { if (options.disableExif) { return } var tiffOffset = offset + 10 var littleEndian var dirOffset var thumbnailData // Check for the ASCII code for "Exif" (0x45786966): if (dataView.getUint32(offset + 4) !== 0x45786966) { // No Exif data, might be XMP data instead return } if (tiffOffset + 8 > dataView.byteLength) { console.log('Invalid Exif data: Invalid segment size.') return } // Check for the two null bytes: if (dataView.getUint16(offset + 8) !== 0x0000) { console.log('Invalid Exif data: Missing byte alignment offset.') return } // Check the byte alignment: switch (dataView.getUint16(tiffOffset)) { case 0x4949: littleEndian = true break case 0x4D4D: littleEndian = false break default: console.log('Invalid Exif data: Invalid byte alignment marker.') return } // Check for the TIFF tag marker (0x002A): if (dataView.getUint16(tiffOffset + 2, littleEndian) !== 0x002A) { console.log('Invalid Exif data: Missing TIFF marker.') return } // Retrieve the directory offset bytes, usually 0x00000008 or 8 decimal: dirOffset = dataView.getUint32(tiffOffset + 4, littleEndian) // Create the exif object to store the tags: data.exif = new loadImage.ExifMap() // Parse the tags of the main image directory and retrieve the // offset to the next directory, usually the thumbnail directory: dirOffset = loadImage.parseExifTags( dataView, tiffOffset, tiffOffset + dirOffset, littleEndian, data ) if (dirOffset && !options.disableExifThumbnail) { thumbnailData = { exif: {} } dirOffset = loadImage.parseExifTags( dataView, tiffOffset, tiffOffset + dirOffset, littleEndian, thumbnailData ) // Check for JPEG Thumbnail offset: if (thumbnailData.exif[0x0201]) { data.exif.Thumbnail = loadImage.getExifThumbnail( dataView, tiffOffset + thumbnailData.exif[0x0201], thumbnailData.exif[0x0202] // Thumbnail data length ) } } // Check for Exif Sub IFD Pointer: if (data.exif[0x8769] && !options.disableExifSub) { loadImage.parseExifTags( dataView, tiffOffset, tiffOffset + data.exif[0x8769], // directory offset littleEndian, data ) } // Check for GPS Info IFD Pointer: if (data.exif[0x8825] && !options.disableExifGps) { loadImage.parseExifTags( dataView, tiffOffset, tiffOffset + data.exif[0x8825], // directory offset littleEndian, data ) } } // Registers the Exif parser for the APP1 JPEG meta data segment: loadImage.metaDataParsers.jpeg[0xffe1].push(loadImage.parseExifData) // Adds the following properties to the parseMetaData callback data: // * exif: The exif tags, parsed by the parseExifData method // Adds the following options to the parseMetaData method: // * disableExif: Disables Exif parsing. // * disableExifThumbnail: Disables parsing of the Exif Thumbnail. // * disableExifSub: Disables parsing of the Exif Sub IFD. // * disableExifGps: Disables parsing of the Exif GPS Info IFD. })) <file_sep>/source2/devcontrolpanel/imports/services/sitemap.service.ts import {ISitemapCollection} from '../common/sitemap.model'; export let SitemapCollection = new Mongo.Collection<ISitemapCollection>('Sitemap');<file_sep>/source2/devcontrolpanel/imports/startups/server/third-party-config.ts import {Meteor} from 'meteor/meteor'; export function thirdPartyOAuthConfiguration() { // Load and set FACEBOOK app configurations var facebookConfig = Meteor.settings['socialConfig'].facebook; ServiceConfiguration.configurations.upsert( { service: "facebook" }, { $set: { appId: facebookConfig.appId, secret: facebookConfig.secret } }); // Load and set GOOGLE app configurations var googleConfig = Meteor.settings['socialConfig'].google; ServiceConfiguration.configurations.upsert( { service: "google" }, { $set: { clientId: googleConfig.clientId, secret: googleConfig.secret } }); // Load and set TWITTER app configurations var twitterConfig = Meteor.settings['socialConfig'].twitter; ServiceConfiguration.configurations.upsert( { service: "twitter" }, { $set: { consumerKey: twitterConfig.consumerKey, secret: twitterConfig.secret } }); // Load and set TWITTER app configurations var githubConfig = Meteor.settings['socialConfig'].github; ServiceConfiguration.configurations.upsert( { service: "github" }, { $set: { clientId: githubConfig.clientId, secret: githubConfig.secret } }); }<file_sep>/source2/devcontrolpanel/imports/api/server/util/email-util.ts import {Meteor} from 'meteor/meteor'; import {UserProfileUtils} from '../../../common/user-profile-util'; import {IUserProfile} from '../../../common/user-profile-model'; import {EMAIL_TEMPLATES} from '../email-template/email-templates'; var fs = require('fs'); var _ = require('lodash'); export /** * EmailUtility */ class EmailUtility { constructor(private user?: Meteor.User, url?: string) { } getForgotPasswordTemplate(user: Meteor.User, url: string): string { let contents: string = EMAIL_TEMPLATES['production-email-template/forgot-and-reset-password.html']; let userValues: IUserProfile = UserProfileUtils.getUserProfileValues(user); let hasMapValue: { [key: string]: string } = { '@@-dns-name-@@': 'https://www.devcontrolpanel.com', '@@-title-@@': 'Please confirm your email.', '@@-subject-@@': 'Please confirm your email.', '@@-user-name-@@': userValues.name, '@@-mail-content-@@': `<div>Thanks for joining with devcontrolpanel</div><div> Please click on the below "Confirm Email" button to confirm your email.</div>`, '@@-button-label-@@': 'Confirm Email', '@@-button-url-@@': url }; _.forEach(hasMapValue, (value, key) => { contents = contents.replace(new RegExp(key, 'g'), value); }); return contents; } getResetPasswordTemplate(user: Meteor.User, url: string): string { let contents: string = EMAIL_TEMPLATES['production-email-template/forgot-and-reset-password.html']; let userValues: IUserProfile = UserProfileUtils.getUserProfileValues(user); let hasMapValue: { [key: string]: string } = { '@@-dns-name-@@': 'https://www.devcontrolpanel.com', '@@-title-@@': 'Reset Password.', '@@-subject-@@': 'Reset Password.', '@@-user-name-@@': userValues.name, '@@-mail-content-@@': `<div>Please click the below button to reset new password</div>`, '@@-button-label-@@': 'Reset Password', '@@-button-url-@@': url }; _.forEach(hasMapValue, (value, key) => { contents = contents.replace(new RegExp(key, 'g'), value); }); return contents; } notifyAdministrator() { } } <file_sep>/source2/devcontrolpanel/imports/ui/components/site-auth-component/site-auth.component.ts //library import { Component, OnInit, OnDestroy, AfterViewInit, AfterViewChecked, ElementRef, Inject } from '@angular/core'; import { FORM_DIRECTIVES, FormBuilder, Validators, CORE_DIRECTIVES, ControlGroup } from '@angular/common'; import {Router} from '@angular/router-deprecated'; //global import {GlobalEventSerice} from '../../services/global-event.service'; import {LinkClickedName, OAppConfig, IAppConfig} from '../../services/config.service'; import {emailValidator, matchingPasswords} from '../../form-validator/validators'; import {Meteor} from 'meteor/meteor'; import {Accounts} from 'meteor/accounts-base'; //from other components //from local imports import {AuthModel} from './model/auth.model'; import {AuthUserService} from './service/auth-user.service'; import template from './template/site-auth.template.html'; @Component({ selector: 'site-auth-component', template, providers: [ AuthModel.SignInModel, AuthModel.ResultMessageClassMapValue, AuthModel.SignUpModel, AuthModel.ForgotPassword, AuthUserService ] }) export class SiteAuthComponent implements OnInit, OnDestroy, AfterViewInit, AfterViewChecked { isSignningIn: boolean; isPermissionDeniedProfile: boolean; globalEventSericeSubcriber: any; canShowSigninPanel: boolean = true; canShowSignupPanel: boolean = false; modelElement: any; signupFormGroup: ControlGroup; signinFormGroup: ControlGroup; forgotPasswordFormGroup: ControlGroup; linkClickedName: typeof LinkClickedName = LinkClickedName; constructor(private globalEventSerice: GlobalEventSerice, private signInModel: AuthModel.SignInModel, private signUpModel: AuthModel.SignUpModel, private forgotPasswordModel: AuthModel.ForgotPassword, private elementRef: ElementRef, private authUserService: AuthUserService, private formBuilder: FormBuilder, @Inject(OAppConfig) private appConfig: IAppConfig, private router: Router ) { this.globalEventSericeSubcriber = this.globalEventSerice.linkClickedEvent$.subscribe(linkName => { if (linkName == LinkClickedName.SIGNIN) { this.toggleAuthModel(LinkClickedName.SIGNIN); } else if (linkName == LinkClickedName.SIGNUP) { this.toggleAuthModel(LinkClickedName.SIGNUP); } else if (linkName == LinkClickedName.SIGNOUT) { Meteor.logout(); // setTimeout(() => { this.router.navigate(['WallpostHome']); // }, 2000) } }); this.signupFormGroup = this.formBuilder.group({ name: ['', Validators.required], email: ['', Validators.compose([Validators.required, emailValidator])], password: ['', Validators.required], retypePassword: ['', Validators.required], }, { validator: matchingPasswords('password', '<PASSWORD>') }); this.signinFormGroup = this.formBuilder.group({ email: ['', Validators.compose([Validators.required, emailValidator])], password: ['', Validators.required] }); this.forgotPasswordFormGroup = this.formBuilder.group({ email: ['', Validators.compose([Validators.required, emailValidator])] }); } ngOnInit() { } ngAfterViewInit() { this.modelElement = jQuery(this.elementRef.nativeElement).find('.ui.modal'); this.modelElement.modal('setting', 'transition', 'vertical flip'); } signinClick() { this.isSignningIn = true; this.signInModel.isFormSubmitted = true; this.signInModel.isLoading = true; var credential: AuthModel.IAuthSigninModel = <AuthModel.IAuthSigninModel>{ email: this.signInModel.email, password: this.signInModel.password }; this.authUserService.AuthWithPassword(credential).then((message: string) => { this.signUpModel.isLoading = false; this.signUpModel.resultMessage = ''; if (Meteor.userId()) { //sipin success this.updateSigninMessage(true); this.hideAuthModal(); } else if (message) { //signin failure - show the message this.isSignningIn = false; this.updateSigninMessage(false); this.signInModel.resultMessage = this.authUserService.messages[message]; } else { this.signInModel.resultMessage = 'Unknown Error'; } }); } signupClick() { this.toggleAuthModel(LinkClickedName.SIGNUP); this.signUpModel.isFormSubmitted = true; this.signUpModel.isLoading = true; this.authUserService.CreateUser(this.signUpModel).then(createUserResult => { this.signUpModel.isLoading = false; this.signUpModel.resultMessage = ''; if (createUserResult == AuthModel.AuthErrorCode.EMAIL_TAKEN) { this.signUpModel.resultMessage = 'Email Id Already Exists'; this.updateSignupMessage(false); } else if (createUserResult == AuthModel.AuthErrorCode.USER_CREATION_SUCCESS) { this.signUpModel.resultMessage = 'Signup Succeeded'; this.updateSignupMessage(true); this.isSignningIn = true; this.authUserService.updateUserProfileInApp(); this.hideAuthModal(); } else { this.signUpModel.resultMessage = 'Unknown Error'; this.updateSignupMessage(false); } }); } forgotPasswordClick() { if (this.forgotPasswordModel.email) { this.forgotPasswordModel.isLoading = true; Accounts.forgotPassword({ email: this.forgotPasswordModel.email }, (error) => { console.log('forgot password response' + error); this.forgotPasswordModel.isLoading = false; this.canShowSignupPanel = false; this.canShowSigninPanel = false; this.forgotPasswordModel.isVisible = false; if (error) { this.forgotPasswordModel.resultMessage = error; this.forgotPasswordModel.isForgetPasswordSuccess = false; this.updateForgotPasswordMessage(true); } else { this.forgotPasswordModel.isForgetPasswordSuccess = true; this.forgotPasswordModel.email = ''; this.forgotPasswordModel.resultMessage = ''; this.updateForgotPasswordMessage(false); } }) } } hideAuthModal() { this.isSignningIn = false; this.forgotPasswordModel.isForgetPasswordSuccess = false; this.modelElement.modal('hide'); } thirdPartySignin(thirdPartyName: string) { this.authUserService.ThirdPartySignin(thirdPartyName).then(error => { if (error) { } else { this.hideAuthModal(); Meteor.call('updateThirdPartyUser'); } }); } toggleSignInErrorMessage(isVisible: boolean): void { this.signInModel.resultMessageClassMap.visible = isVisible; this.signInModel.resultMessageClassMap.hidden = !isVisible; } toggleSignUpErrorMessage(isVisible: boolean): void { this.signUpModel.resultMessageClassMap.visible = isVisible; this.signUpModel.resultMessageClassMap.hidden = !isVisible; } toggleForgotPasswordErrorMessage(isVisible: boolean): void { this.forgotPasswordModel.resultMessageClassMap.visible = isVisible; this.forgotPasswordModel.resultMessageClassMap.hidden = !isVisible; } updateSigninMessage(isSuccess): void { this.signInModel.resultMessageClassMap.negative = !isSuccess; this.signInModel.resultMessageClassMap.success = isSuccess; this.toggleSignInErrorMessage(true); } updateSignupMessage(isSuccess): void { this.signUpModel.resultMessageClassMap.negative = !isSuccess; this.signUpModel.resultMessageClassMap.success = isSuccess; this.toggleSignUpErrorMessage(true); } updateForgotPasswordMessage(isSuccess: boolean): void { this.forgotPasswordModel.resultMessageClassMap.negative = !isSuccess; this.forgotPasswordModel.resultMessageClassMap.success = isSuccess; this.toggleForgotPasswordErrorMessage(true); } toggleAuthModel(panelName: LinkClickedName) { this.toggleSignInErrorMessage(false); this.toggleSignUpErrorMessage(false); this.forgotPasswordModel.isForgetPasswordSuccess = false; this.modelElement.modal('show'); if (panelName == LinkClickedName.SIGNIN) { //show signin panel this.canShowSigninPanel = true; this.canShowSignupPanel = false; this.forgotPasswordModel.isVisible = false; } else if (panelName == LinkClickedName.SIGNUP) { //show signup panel this.canShowSigninPanel = false; this.canShowSignupPanel = true; this.forgotPasswordModel.isVisible = false; } else if (panelName == LinkClickedName.FORGOT_PASSWORD) { this.canShowSigninPanel = false; this.canShowSignupPanel = false; this.forgotPasswordModel.isVisible = true; } } ngAfterViewChecked() { this.modelElement.modal('refresh'); } ngOnDestroy() { this.globalEventSericeSubcriber.unsubscribe(); } }<file_sep>/source2/devcontrolpanel/imports/ui/components/wall-post-component/component/wall-post-detail-component/wall-post-detail.component.ts //lib import import {Component, Input, OnInit, NgZone, AfterViewInit} from '@angular/core'; import { Router, RouteParams, ROUTER_DIRECTIVES } from '@angular/router-deprecated'; //within the app //common import { AppComponent } from '../../../common/app-component'; import { AppFactory } from '../../../../services/config.service'; //other components import { UserProfileImageComponent } from '../../../user-profile-image-component/user-profile-image.component'; import {WallPostCardComponent} from '../wall-post-card-component/wall-post-card.component'; import {GlobalEventSerice} from '../../../../services/global-event.service'; //within the component import {WallPostDetailService} from './service/wall-post-detail.service'; import template from './template/wall-post-detail.template.html'; @Component({ selector: 'wall-post-detail', template, directives: [UserProfileImageComponent, WallPostCardComponent, ROUTER_DIRECTIVES] }) export class WallPostDetailComponent extends AppComponent implements AfterViewInit, OnInit { wallPostId: string; isWallPostVisible: boolean = false; constructor( appFactory: AppFactory, private routeParams: RouteParams, ngZone: NgZone, private router: Router, globalEventSerice: GlobalEventSerice ) { super(appFactory, globalEventSerice, ngZone) this.wallPostId = this.routeParams.get('wallPostId'); //waiting for the router issue to solve setTimeout(() => { this.ngZone.run(() => { this.isWallPostVisible = true; }); }, 100); } ngOnInit() { } ngAfterViewInit() { } @Input() name: string; }<file_sep>/source2/devcontrolpanel/imports/common/user-profile-util.ts import {IUserProfile, LoginType} from './user-profile-model'; import {Meteor} from 'meteor/meteor'; export class UserProfileUtils { static loginType: typeof LoginType = LoginType; static getCurrentUserProfileValues(): IUserProfile { let user: Meteor.User = Meteor.user(); let userProfile: IUserProfile = UserProfileUtils.getUserProfileValues(user); return userProfile; } static getUserProfileValuesFromUserId(userId: string): IUserProfile { let user: Meteor.User = Meteor.users.findOne({ _id: userId }); let userProfile: IUserProfile = UserProfileUtils.getUserProfileValues(user); return userProfile; } static getUserProfileValuesFromUserProfile(user: Meteor.User): IUserProfile { let userProfile: IUserProfile = UserProfileUtils.getUserProfileValues(user); return userProfile; } static getUserProfileValues(user: Meteor.User): IUserProfile { let userProfile: IUserProfile; if (user) { let pictureUrl: string = '', email: string = '', loginType: LoginType, name: string = ''; pictureUrl = user.profile ? user.profile.profilePicture : '' if (user.emails) { loginType = UserProfileUtils.loginType.DEVCONTROLPANEL; if (user.emails && user.emails.length > 0) { email = user.emails[0].address; } name = user.profile && user.profile.name; } else if (user.services) { if (user.services.facebook) { pictureUrl = user.services.facebook.picture; loginType = UserProfileUtils.loginType.FACEBOOK; name = user.services.facebook.name; email = user.services.facebook.email; } else if (user.services.google) { pictureUrl = user.services.google.picture; email = user.services.google.email; loginType = UserProfileUtils.loginType.GOOGLE; name = user.services.google.name; } else if (user.services.twitter) { name = user.services.twitter.name; pictureUrl = user.services.twitter.profile_image_url_https; loginType = UserProfileUtils.loginType.TWITTER; email = user.services.twitter.email; } else if (user.services.github) { name = user.services.github.name; pictureUrl = user.services.github ? user.services.github.picture : ''; loginType = UserProfileUtils.loginType.GITHUB; email = user.services.github.email; } } userProfile = <IUserProfile>{ name: name, profileImageURL: pictureUrl, userId: user._id, email: email, loginType: loginType, wallPost: user.wallPost, isUserAuthenticated: true, themeName: '', wallPostCustom: { savedSearch: [] } }; if (userProfile.wallPost && userProfile.wallPost.savedSearch && userProfile.wallPost.savedSearch.length) { userProfile.wallPostCustom.savedSearch = _.map(userProfile.wallPost.savedSearch, (value) => { let objKeys = _.keys(value); return objKeys && objKeys.length ? objKeys[0] : ''; }); } } else { userProfile = <IUserProfile>{ name: 'Anonymous', profileImageURL: null }; } return userProfile; } }<file_sep>/source2/devcontrolpanel/imports/api/server/rest/sitemap/sitemap.ts import {getSitemap} from './sitemap-builder'; if (Meteor.isServer) { // Global API configuration let Api = new Restivus({ useDefaultAuth: false, prettyJson: false }); Api.addRoute('sitemap.xml', { authRequired: false }, { get: function () { return { statusCode: 200, headers: { 'Content-Type': 'text/xml', }, 'Access-Control-Allow-Origin': '*', body: getSitemap() } } }); }<file_sep>/source2/devcontrolpanel/imports/ui/components/site-component/component/terms-and-condition-component/terms-and-condition.component.ts import {Component, provide, Inject, NgZone, OnInit, OnDestroy} from '@angular/core'; import { RouterLink, ROUTER_DIRECTIVES, RouteConfig } from '@angular/router-deprecated'; import template from './template/terms-and-condition.template.html'; @Component({ selector: 'terms-and-condition', template, directives: [RouterLink, ROUTER_DIRECTIVES] }) export class TermsAndConditionComponent { } <file_sep>/source2/devcontrolpanel/imports/api/server/publish/profile/user-profile.ts import {Meteor} from 'meteor/meteor'; import {Accounts} from 'meteor/accounts-base'; import {Mongo} from 'meteor/mongo'; var _ = require('lodash'); Meteor.publish('userData', function () { return Meteor.users.find({ _id: this.userId }, { fields: { //google 'services.google.email': 1, 'services.google.name': 1, 'services.google.picture': 1, //facebook 'services.facebook.email': 1, 'services.facebook.name': 1, 'services.facebook.picture': 1, //twitter 'services.twitter.name': 1, 'services.twitter.profile_image_url_https': 1, 'services.twitter.email': 1, //github 'services.github.email': 1, 'services.github.name': 1, 'services.github.picture': 1, //app auth 'emails': 1, 'profile.name': 1, 'profile.profilePicture': 1, 'wallPost': 1 } }); }); Meteor.publish('allUserData', function () { return Meteor.users.find({}, { fields: { '_id': 1, 'profile.name': 1, 'profile.profilePicture': 1, //google 'services.google.name': 1, 'services.google.picture': 1, //facebook 'services.facebook.name': 1, 'services.facebook.picture': 1, //twitter 'services.twitter.name': 1, 'services.twitter.profile_image_url_https': 1, //github 'services.github.name': 1, 'services.github.picture': 1, } }); }); Accounts.onCreateUser(function (options, user) { user.wallPost = { savedSearch: [] }; return user; }); Meteor.users.allow({ insert: (userId, doc) => { return false; }, update: (userId, doc, fields, modifier) => { let whitelistProperty = ['profile', 'emails', 'wallPost']; let whitelistModifiersFor$set = ['profile.name', 'profile.profilePicture', 'emails.0.address']; let whitelistModifiersFor$addToSet = ['wallPost.savedSearch']; if (userId && (doc._id === userId) && (_.difference(fields, whitelistProperty).length === 0)) { if (modifier.$set && (_.difference(_.keys(modifier.$set), whitelistModifiersFor$set).length === 0)) { return true; } else if (modifier.$addToSet && (_.difference(_.keys(modifier.$addToSet), whitelistModifiersFor$addToSet).length === 0)) { return true; } else { return false; } } else { return false; } }, remove: (userId, doc) => { return false; } }); <file_sep>/source2/devcontrolpanel/imports/ui/directives/router-authorize.directive.ts // //import core directives // import { Directive } from '@angular/core'; // import { RouterOutlet } from '@angular/router-deprecated'; // @Directive({ // selector: 'router-outlet' // }) // export class RouterAuthorizeDirective extends RouterOutlet { // } //writing the above as suitable for my app // //example // @Directive({ // selector: 'router-outlet' // }) // export class LoggedInRouterOutlet extends RouterOutlet { // publicRoutes: Array; // private parentRouter: Router; // private userService: UserService; // constructor( // _elementRef: ElementRef, _loader: DynamicComponentLoader, // _parentRouter: Router, @Attribute('name') nameAttr: string, // userService: UserService // ) { // super(_elementRef, _loader, _parentRouter, nameAttr); // this.parentRouter = _parentRouter; // this.userService = userService; // this.publicRoutes = [ // '', 'login', 'signup' // ]; // } // activate(instruction: ComponentInstruction) { // if (this._canActivate(instruction.urlPath)) { // return super.activate(instruction); // } // this.parentRouter.navigate(['Login']); // } // _canActivate(url) { // return this.publicRoutes.indexOf(url) !== -1 || this.userService.isLoggedIn() // } // }<file_sep>/source2/devcontrolpanel/imports/ui/directives/element-visible.directive.ts import { Directive, Input, Output, ElementRef, HostBinding, Renderer, EventEmitter} from '@angular/core'; import {OnInit, AfterViewInit, AfterViewChecked, OnDestroy} from '@angular/core'; @Directive({ selector: '[ElementVisible]' }) export class ElementVisibleDirective { private elementRef: ElementRef; private renderer: Renderer; private timerId: any = 0; constructor(elementRef: ElementRef, renderer: Renderer) { this.elementRef = elementRef; this.renderer = renderer; } ngAfterViewInit() { jQuery(window).on('scroll', () => { this.windowScrollEvent(); }); } windowScrollEvent() { if (this.timerId > 0) { clearTimeout(this.timerId); } this.timerId = setTimeout(() => { this.emitEvent(); }, 200); } emitEvent() { let isVisible = jQuery(this.elementRef.nativeElement).visible(true); this.ElementVisibleOnScreen.emit(isVisible); } @Output() ElementVisibleOnScreen = new EventEmitter(); }<file_sep>/source2/devcontrolpanel/imports/ui/components/wall-post-component/wall-post.component.ts //library imports import {Component, provide, Inject, NgZone, OnInit, OnDestroy} from '@angular/core'; import { RouterLink, ROUTER_DIRECTIVES, RouteConfig } from '@angular/router-deprecated'; //with in the app import {LeftMenuProfileComponent} from '../left-menu-profile-component/left-menu-profile.component'; import {APP_COMMON_DIRECTIVES} from '../../directives/app-common.directive'; import {AppFactory} from '../../services/config.service'; import {GlobalEventSerice} from '../../services/global-event.service'; import { AppComponent } from '../common/app-component'; import {LinkClickService} from '../devcontrolpanel/service/link-click.service'; import {WallPostPopularPostCollection} from '../../../services/wall-post.service'; //with in the component import {WallPostCardComponent} from './component/wall-post-card-component/wall-post-card.component'; import {WallPostWriteComponent} from './component/wall-post-write-component/wall-post-write.component'; import {WallPostDetailComponent} from './component/wall-post-detail-component/wall-post-detail.component'; import {WallPostDisplayComponent} from './component/wall-post-display-component/wall-post-display.component'; import template from './template/wall-post.template.html'; @Component({ selector: 'wall-post-page', template, directives: [LeftMenuProfileComponent, RouterLink, ROUTER_DIRECTIVES, APP_COMMON_DIRECTIVES, WallPostCardComponent] }) @RouteConfig([ { name: 'WallPostDisplay', path: '/display', component: WallPostDisplayComponent, useAsDefault: true }, { name: 'WallPostDisplayByTagName', path: '/display-by-tag/:tagName', component: WallPostDisplayComponent }, { name: 'WallPostDisplayBySearchName', path: '/display-by-search/:searchName', component: WallPostDisplayComponent }, { name: 'WallPostDisplayMine', path: '/display-my-post', component: WallPostDisplayComponent }, { name: 'WallPostDetail', path: '/detail/:wallPostId', component: WallPostDetailComponent }, { name: 'WallPostWrite', path: '/write', component: WallPostWriteComponent }, { name: 'WallPostEdit', path: '/edit/:wallPostId', component: WallPostWriteComponent } ]) export class WallPostComponent extends AppComponent implements OnInit, OnDestroy { savedSearch: string[]; popularPost: { tagName: string, count: number }[]; WallPostPopularPostCursor; WallPostPopularPostCursorHandle: Meteor.LiveQueryHandle; constructor(appFactory: AppFactory, globalEventSerice: GlobalEventSerice, private linkClickService: LinkClickService) { super(appFactory, globalEventSerice) } writeNewPostClick() { this.linkClickService.signinLinkClick(); } ngOnInit() { this.WallPostPopularPostCursorHandle = Meteor.subscribe('WallPostPopularPost'); let updateOnPopularPostCallback = () => { this.updatePopularPost(); }; WallPostPopularPostCollection.find().observeChanges({ added: updateOnPopularPostCallback, removed: updateOnPopularPostCallback, changed: updateOnPopularPostCallback }); } updatePopularPost() { this.popularPost = []; WallPostPopularPostCollection.find().forEach((val) => { this.popularPost.push({ tagName: val._id, count: val.count }); }); } ngOnDestroy() { if (this.WallPostPopularPostCursorHandle) { this.WallPostPopularPostCursorHandle.stop(); } } }<file_sep>/source2/devcontrolpanel/imports/ui/components/wall-post-component/component/wall-post-display-component/wall-post-display.component.ts //lib import import {Component, Input, AfterViewInit, NgZone, OnInit, OnDestroy} from '@angular/core'; import { Router, RouteParams, ROUTER_DIRECTIVES, CanReuse } from '@angular/router-deprecated'; //within the app //common import { AppComponent } from '../../../common/app-component'; import { AppFactory } from '../../../../services/config.service'; import { IUserProfile } from '../../../../../common/user-profile-model'; import { UserProfileUtils } from '../../../../../common/user-profile-util'; import {IWallPostSearch} from '../../../../../common/wall-post.model'; //other components import { UserProfileImageComponent } from '../../../user-profile-image-component/user-profile-image.component'; import {WallPostCardComponent} from '../wall-post-card-component/wall-post-card.component'; import {WallPostCollection} from '../../../../../services/wall-post.service'; import {ElementVisibleDirective} from '../../../../directives/element-visible.directive'; import {GlobalEventSerice} from '../../../../services/global-event.service'; import {APP_COMMON_DIRECTIVES} from '../../../../directives/app-common.directive'; import {WallPostService} from '../../service/wall-post.service'; //within the component import template from './template/wall-post-display.template.html'; @Component({ selector: 'wall-post-card', template, directives: [UserProfileImageComponent, WallPostCardComponent, ElementVisibleDirective, APP_COMMON_DIRECTIVES], providers: [WallPostService] }) export class WallPostDisplayComponent extends AppComponent implements AfterViewInit, OnInit, OnDestroy, CanReuse { isNewDataElementVisible: boolean; isLazyLoadElementVisible: boolean; isDataLazyLoaded: boolean; isNoMoreDataToLazyLoad: boolean; isSearchResultDisplaying: boolean; totalRecordsToDisplayInput: number = 5; allPostCount: number = 0; totalRecordsToLoad: number; totalRecordsLoaded: number; wallPostDisplayDataLoaded: string[]; wallPostDisplayDataIndex: string[] = []; wallPostDisplayDataIndexCursor: any; //wallpost subscribe wallPostSubscribe: Meteor.LiveQueryHandle; //advanced search isAdvancedSearchVisible: boolean = false; searchContent: string; isSearchStarted: boolean = false; saveSearchName: string = ''; searchByAllTag: { allTags: string[], clearField: boolean, data: string[], tagChanged: (value: string) => void, tagsChoosen: string[] } = { allTags: [], clearField: false, data: [], tagsChoosen: [], tagChanged: (tags) => { this.searchByAllTag.tagsChoosen = tags.split(','); } }; searchByUser: { allUsers: IUserProfile[], clearField: boolean, data: string[], tagChanged: (value: string) => void, userChoosen: string[] } = { allUsers: [], clearField: false, data: [], userChoosen: [], tagChanged: (user) => { this.searchByUser.userChoosen = user.split(','); } }; userProfileChangedTimer: any; isSearchResultFromRouteCalled: boolean = false; constructor( appFactory: AppFactory, ngZone: NgZone, globalEventSerice: GlobalEventSerice, private wallPostService: WallPostService, private router: Router, private routerParam: RouteParams ) { super(appFactory, globalEventSerice, ngZone) this.wallPostService.getAllTags().then((tags) => { this.searchByAllTag.allTags = tags; }); Tracker.autorun(() => { this.ngZone.run(() => { this.searchByUser.allUsers = []; Meteor.users.find({}).forEach((user: Meteor.User) => { this.searchByUser.allUsers .push(UserProfileUtils.getUserProfileValuesFromUserProfile(user)); }); }); }); this.isSearchResultFromRouteCalled = false; globalEventSerice.currentUserProfileChangedEvent$.subscribe(() => { if (this.userProfileChangedTimer) { clearTimeout(this.userProfileChangedTimer); } this.ngZone.runOutsideAngular(() => { this.userProfileChangedTimer = setTimeout(() => { this.ngZone.run(() => { this.userProfileChange(); }); }, 500); }); }); } userProfileChange() { if (!this.isSearchResultFromRouteCalled) { if (_.includes(location.pathname.split('/'), 'display-by-search')) { let searchName = this.routerParam.get('searchName'), searchValue = this.getSavedSearchParam(searchName); if (searchValue) { this.searchWallPost(searchValue); } this.isSearchResultFromRouteCalled = true; } } } routerCanReuse() { return false; } ngAfterViewInit() { } ngOnInit() { this.isNewDataElementVisible = true; this.showAllPost(); this.updateNoMoreDataFlag(); $("html,body").scrollTop(0); } ngAfterViewChecked() { } newPostElementVisible(isVisible: boolean): void { this.isNewDataElementVisible = isVisible; this.updateNoMoreDataFlag(); if (isVisible && !this.isLazyLoadElementVisible) { // if (this.isDataLazyLoaded) { this.isDataLazyLoaded = false; this.updateNewData(); // } } } updateNoMoreDataFlag() { if (this.wallPostDisplayDataLoaded && this.wallPostDisplayDataIndex && this.wallPostDisplayDataIndex.length <= this.totalRecordsToDisplayInput) { this.isNoMoreDataToLazyLoad = true; } else { this.isNoMoreDataToLazyLoad = false; } } loadingIconVisible(isVisible: boolean): void { if (isVisible) { //find the last element in wall data let lastWallPostId: string = _.last(this.wallPostDisplayDataLoaded); if (lastWallPostId) { if (this.wallPostDisplayDataIndex && this.wallPostDisplayDataIndex.length) { let lastWallPostIdIndex = _.findIndex(this.wallPostDisplayDataIndex, postId => postId == lastWallPostId); if (lastWallPostIdIndex != -1) { lastWallPostIdIndex += 1; let latestDataIndex = this.wallPostDisplayDataIndex.slice(lastWallPostIdIndex, (lastWallPostIdIndex + this.totalRecordsToDisplayInput)); if (latestDataIndex.length > 0) { //this.isDataLazyLoaded = true; this.isNoMoreDataToLazyLoad = false; this.refreshView(); this.updateWallPostData(latestDataIndex, true); } else { this.isNoMoreDataToLazyLoad = true; } } } } } } updateNewData() { this.allPostCount = (this.wallPostDisplayDataIndex && this.wallPostDisplayDataIndex.length) || 0 this.updateNoMoreDataFlag(); let dataIndex: string[]; if (this.wallPostDisplayDataIndex && this.wallPostDisplayDataIndex.length) { let latestDataIndex = this.wallPostDisplayDataIndex.slice(0, this.totalRecordsToDisplayInput); let displayedIndex = this.wallPostDisplayDataLoaded ? this.wallPostDisplayDataLoaded.slice(0, this.totalRecordsToDisplayInput) : []; dataIndex = _.filter(latestDataIndex, index => { return _.find(displayedIndex, (val) => { return val == index }) ? false : true; }).reverse(); this.updateWallPostData(dataIndex); } } updateWallPostData(index: string[], isAppend: boolean = false) { this.totalRecordsToLoad = index.length; if (isAppend) { let totalRecordsCanAccupy: number = (this.totalRecordsToDisplayInput * 2); let spliceLength: number = (this.wallPostDisplayDataLoaded.length - totalRecordsCanAccupy); if (spliceLength > 0) { this.wallPostDisplayDataLoaded.splice(0, spliceLength); } index.forEach(indexVal => { this.wallPostDisplayDataLoaded.push(indexVal); }); } else { if (this.isSearchResultDisplaying) { this.wallPostDisplayDataLoaded = []; this.isSearchResultDisplaying = false; } index.forEach(indexVal => { this.totalRecordsLoaded++; this.wallPostDisplayDataLoaded.unshift(indexVal); this.wallPostDisplayDataLoaded.splice(this.totalRecordsToDisplayInput); }); } } loadLatestData() { //alert from the test 1 } refreshView() { this.ngZone.run(() => { }); } refreshNewDataIndex() { if (this.isNewDataElementVisible) { this.ngZone.run(() => { this.updateNewData(); }); } } searchWallPost(searchParamInput?: IWallPostSearch) { this.isSearchStarted = true; let searchParam: IWallPostSearch; if (searchParamInput) { searchParam = searchParamInput; } else { searchParam = { search: this.searchContent, tags: this.searchByAllTag.tagsChoosen || [], createdBy: this.searchByUser.userChoosen || [] } } this.clearWallPostDisplay(); Meteor.call('wallPostSearch', searchParam, (err, result) => { this.wallPostDisplayDataIndex = result || []; this.refreshNewDataIndex(); }); } clearWallPostDisplay() { if (this.wallPostSubscribe) { this.wallPostSubscribe.stop(); } this.wallPostDisplayDataIndex = []; this.wallPostDisplayDataLoaded = []; } clearSearchFields() { this.searchByAllTag.clearField = true; this.searchByUser.clearField = true; this.searchContent = ''; } showAllPost() { this.clearSearchFields(); this.isSearchStarted = false; this.clearWallPostDisplay(); this.wallPostSubscribe = Meteor.subscribe('WallpostIndex'); let findOption = {}; // debugger; if (_.includes(location.pathname.split('/'), 'display-my-post')) { findOption['createdBy'] = this.userId; } if (_.includes(location.pathname.split('/'), 'display-by-tag')) { findOption['tag.name'] = { $eq: this.routerParam.get('tagName') } } if (_.includes(location.pathname.split('/'), 'display-by-search')) { let searchName = this.routerParam.get('searchName'), searchValue = this.getSavedSearchParam(searchName); if (searchValue) { this.searchWallPost(searchValue); } return; } this.wallPostDisplayDataIndexCursor = WallPostCollection.find(findOption, { fields: { _id: 1, createdTime: 1 }, sort: { createdTime: -1 } }); this.wallPostDisplayDataIndexCursor.observeChanges({ added: (id, doc) => { if (!this.isSearchStarted) { this.wallPostDisplayDataIndex = this.wallPostDisplayDataIndexCursor.map(data => data._id) || []; this.refreshNewDataIndex(); } }, removed: (id, doc) => { if (!this.isSearchStarted) { _.remove(this.wallPostDisplayDataIndex, data => data == id); this.refreshNewDataIndex(); } } }); } getSavedSearchParam(searchName): IWallPostSearch { if (this.user.wallPost && this.user.wallPost.savedSearch && this.user.wallPost.savedSearch) { let resultFound: { [key: string]: IWallPostSearch } = _.find(this.user.wallPost.savedSearch, (val, index) => { return _.keys(val)[0] == searchName; }); if (resultFound) { return <IWallPostSearch>_.values(resultFound)[0]; } else { return null; } } else { return null; } } saveSearch() { if (this.saveSearchName) { let savedSearchParam = { [this.saveSearchName]: { search: this.searchContent, tags: this.searchByAllTag.tagsChoosen || [], createdBy: this.searchByUser.userChoosen || [] } }; Meteor.users.update(this.userId, { $addToSet: { 'wallPost.savedSearch': savedSearchParam } }); } } ngOnDestroy() { this.clearWallPostDisplay(); } }<file_sep>/source2/devcontrolpanel/imports/ui/components/wall-post-component/component/wall-post-write-component/wall-post-write.component.ts //lib import import {Component, Input, NgZone, OnInit} from '@angular/core'; import { Router, RouteParams, CanActivate } from '@angular/router-deprecated'; import {Mongo} from 'meteor/mongo'; //within the app //common import { AppComponent } from '../../../common/app-component'; import { AppFactory } from '../../../../services/config.service'; import {CKEditorDirective} from '../../../../directives/ckeditor.directive'; import {APP_COMMON_DIRECTIVES} from '../../../../directives/app-common.directive'; import { UserProfileImageComponent } from '../../../user-profile-image-component/user-profile-image.component'; import '../../../../../startups/client/scripts/ckeditor/ckeditor.js'; //within the app import {Lib} from '../../../../../startups/client/scripts/custom/custom'; import {IWallPost, IWallPostIndex, IWallPostTag} from '../../../../../common/wall-post.model'; import { WallPostCollection } from '../../../../../services/wall-post.service'; import {GlobalEventSerice} from '../../../../services/global-event.service'; import {canActivateRoute} from '../../../../services/can-activate-route.service'; //within the component import {WallPostWriteService} from './service/wall-post-write.service'; import {WallPostService} from '../../service/wall-post.service'; import template from './template/wall-post-write.template.html'; @Component({ selector: 'wall-post-card', template, directives: [UserProfileImageComponent, CKEditorDirective, APP_COMMON_DIRECTIVES], providers: [WallPostWriteService, WallPostService] }) @CanActivate((next, prev) => { return canActivateRoute(next, prev, true); }) export class WallPostWriteComponent extends AppComponent implements OnInit { wallPostModel: IWallPost; wallPostIndex: IWallPostIndex[]; isPostSubmitting: boolean = false; isPostDescriptionExit: boolean = false; isPostValidated: boolean = false; wallPostTags: string[] = []; clearTagField: boolean = false; semanticDropDownData: string[]; currentPost: IWallPost; isEditPost: boolean = false; wallPostId: string; wallPostDetail: IWallPost; wallPostCollectionIndex: Mongo.Cursor<IWallPostIndex>; constructor(appFactory: AppFactory, private wallPostWriteService: WallPostWriteService, private router: Router, ngZone: NgZone, private wallPostService: WallPostService, private routeParams: RouteParams, globalEventSerice: GlobalEventSerice ) { super(appFactory, globalEventSerice, ngZone) this.currentPost = { title: '', content: '', tag: [] }; this.wallPostWriteService.getUserTags().then((tags) => { this.wallPostTags = tags; }); this.wallPostId = this.routeParams.get('wallPostId'); } ngOnInit() { if (this.wallPostId) { this.wallPostService.getWallPostDetail(this.wallPostId).then( (data) => { this.currentPost = data; //update CKEditor content if (CKEDITOR.instances['shareonWall']) { CKEDITOR.instances['shareonWall'].ui.editor.setData(this.currentPost.content); } //update tag dropdown this.semanticDropDownData = _.map(this.currentPost.tag, data => { return data.name; }); //check for the form validation this.isPostDescriptionExit = true; // postChange(_.map(this.currentPost.tag, data => { // return data.name; // })); this.updatePostButtonEnableStatus(); }, (error) => { } ); this.isEditPost = true; } else { if (CKEDITOR.instances['shareonWall']) { // CKEDITOR.instances['shareonWall'].ui.editor.setData(''); } } } updatePostButtonEnableStatus() { if (this.isPostDescriptionExit && this.currentPost.title && this.currentPost.tag && this.currentPost.tag.length > 0) { this.isPostValidated = true; } else { this.isPostValidated = false; } } postChange(data: string) { this.ngZone.run(() => { if (Lib.stripHtml(data).trim()) { this.currentPost.content = data; this.isPostDescriptionExit = true; } else { this.currentPost.content = ''; this.isPostDescriptionExit = false; } this.updatePostButtonEnableStatus(); }); } tagChanged(tags: string) { let wallpostTag: IWallPostTag[] = []; if (tags) { let order = 0; _.forEach(tags.split(','), (tagName) => { wallpostTag.push({ name: tagName, order: order++ }); }); } else { } this.currentPost.tag = wallpostTag; this.updatePostButtonEnableStatus(); } updatePost() { WallPostCollection.update({ _id: this.wallPostId }, { $set: { title: this.currentPost.title, content: this.currentPost.content, tag: this.currentPost.tag } }, (error, success) => { if (success) { this.router.navigate(['WallPostDetail', { wallPostId: this.wallPostId }]); } }); } createPost() { WallPostCollection.insert(this.currentPost, (error, postId) => { if (postId) { // Meteor.call('wallPostCrawler', postId); this.router.navigate(['WallPostDetail', { wallPostId: postId }]); } else { } }); } titleBlurred() { CKEDITOR.instances['shareonWall'].focus(); } }<file_sep>/source2/devcontrolpanel/imports/ui/components/devcontrolpanel/service/current-user-profile-change.service.ts // import {Injectable} from '@angular/core'; // //global // import {GlobalEventSerice} from '../../../services/global-event.service'; // import {AppFactory, LinkClickedName} from '../../../services/config.service'; // //component // @Injectable() // export class CurrentUserProfileChangeService { // constructor(private _globalEventSerice: GlobalEventSerice, private _appFactory: AppFactory) { // } // userProfileChange(){ // this._globalEventSerice. // } // }<file_sep>/source2/devcontrolpanel/imports/api/server/publish/wall-post/wall-post.ts import {Meteor} from 'meteor/meteor'; import {Mongo} from 'meteor/mongo'; import {WallPostCollection} from '../../../../services/wall-post.service'; var _ = require('lodash'); Meteor.publish('WallpostIndex', (options: Object) => { options = options || {} return WallPostCollection.find(options, { fields: { _id: 1, createdTime: 1, createdBy: 1, tag: 1 }, sort: { createdTime: -1 } }); }); // Meteor.publish('MyWallpostIndex', () => { // // options = options || {} // return WallPostCollection.find({ // createdBy: Meteor.userId() // }, { fields: { _id: 1, createdTime: 1, createdBy: 1 }, sort: { createdTime: -1 } }); // }); Meteor.publish('WallpostDetail', (postId: string) => { return WallPostCollection.find({ _id: postId }); }); Meteor.publish('WallPostPopularPost', function () { ReactiveAggregate(this, WallPostCollection, [ { $unwind: '$tag' }, { $group: { _id: '$tag.name', count: { $sum: 1 } } }, { $sort: { count: -1 } } ] , { clientCollection: 'WallPostPopularPost' }) }); //allow deny rule for wall-post-write WallPostCollection.allow({ insert: (userId, Doc) => { let canInsert = false; if (userId) { return true; } return canInsert; }, update: (userId, doc, fieldNames, modifier) => { let canUpdate = false; //validation for like if (userId && fieldNames && fieldNames.length == 1 && fieldNames[0] == 'like' && modifier && modifier['$addToSet'] && _.keys(modifier['$addToSet']).length == 1 && modifier['$addToSet'].like) { var existingLikedUsers = _.map(doc.like, 'createdBy'); if (_.includes(existingLikedUsers, userId)) { return false; } else { return true; } } //rules for unlike if (userId && fieldNames && fieldNames.length == 1 && fieldNames[0] == 'like' && modifier && modifier['$pull'] && _.keys(modifier['$pull']).length == 1 && modifier['$pull'].like) { var existingLikedUsers = _.map(doc.like, 'createdBy'); if (_.includes(existingLikedUsers, userId)) { return true; } else { return false; } } console.log(fieldNames, modifier); //validation for comment if (userId && fieldNames && fieldNames.length == 1 && _.isString(fieldNames[0]) && fieldNames[0].indexOf('comment') > -1 && modifier && modifier['$addToSet'] && _.isObject(modifier['$addToSet']) && _.keys(modifier['$addToSet']).length == 1 && _.isString(modifier['$addToSet'][_.keys(modifier['$addToSet'])[0]].comment) && modifier['$addToSet'][_.keys(modifier['$addToSet'])[0]].comment.length > 1 ) { return true; } //validation for comment update if (userId && fieldNames && fieldNames.length == 1 && _.isString(fieldNames[0]) && fieldNames[0].indexOf('comment') > -1 && modifier && modifier['$set'] && _.isObject(modifier['$set']) && _.keys(modifier['$set']).length == 1 && _.isString(modifier['set'][_.keys(modifier['$set'])[0]].comment) && modifier['$set'][_.keys(modifier['$set'])[0]].comment.length > 1 && modifier['$set'][_.keys(modifier['$set'])[0]].comment.createdBy == userId ) { return true; } //validation for post update let whitelistModifiers: string[] = ['title', 'content', 'tag']; if (userId && doc.createdBy == userId && modifier && modifier['$set'] && _.difference(_.keys(modifier['$set']), whitelistModifiers).length == 0) { return true; } return canUpdate; }, remove: (userId, doc) => { if (userId == doc.createdBy) { return true; } else { return false; } } });<file_sep>/source2/devcontrolpanel/.out-of-meteor/content/scripts/es-shim/app-component/app.component.ts import {Component, EventEmitter, Output, enableProdMode} from 'angular2/core'; import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router'; import {COMMON_PIPES} from 'angular2/common'; import {SiteAuthComponent} from '../site-auth-component/site-auth.component'; import {SiteMenuComponent} from '../site-menu-component/site-menu.component'; import {SiteMenuEventService} from '../services/site-events.service'; import {AppSettingService} from '../services/app-settings'; import {SiteEventParam, SiteEventServiceType, SiteEventService} from '../services/site-events.service'; import {HomePageComponent} from '../home-component/home.component'; import {AboutUsComponent} from '../about-us-component/about-us.component'; if (location.host == 'www.devcontrolpanel.com' || location.hostname == 'www.devcontrolpanel.com') { enableProdMode(); } @Component({ selector: 'dev-control-panel-app', templateUrl: 'app/app-component/template/app.template.html', directives: [ROUTER_DIRECTIVES, SiteAuthComponent, SiteMenuComponent], pipes: [COMMON_PIPES], }) @RouteConfig([ { path: '/', name: 'HomePage', component: HomePageComponent, useAsDefault: true }, { path: '/wallpost/post/:postId', name: 'HomePageWithPost', component: HomePageComponent }, { path: '/about-us', name: 'AboutUs', component: AboutUsComponent } ]) export class DevControlPanelApp { public name: string; public wallPostFirebaseRef: string; public appSettingService: AppSettingService; private siteEventService: SiteEventService; constructor(siteMenuEventService: SiteMenuEventService, appSettingService: AppSettingService, siteEventService: SiteEventService) { this.appSettingService = appSettingService; this.siteEventService = siteEventService; } }<file_sep>/source2/devcontrolpanel/client/main.ts import { Blaze } from 'meteor/blaze'; import {Template} from 'meteor/templating'; import 'jquery/dist/jquery.min.js'; import '../imports/startups/client/scripts/jquery-ext/jquery.ext.min.js'; import '../imports/startups/client/scripts/lodash/lodash.min.js'; import '../imports/startups/client/scripts/custom/custom'; import '../imports/startups/client/scripts/semantic/semantic.min.js'; import '../imports/startups/client/scripts/ripple/jquery.rippler.min.js'; import '../imports/startups/client/scripts/img-cropper/img-cropper.min.js'; import '../imports/startups/client/scripts/load-image/load-image.all.min.js'; import '../imports/startups/client/scripts/sticky/jquery.sticky.js'; import '../imports/startups/client/scripts/ckeditor/highlight.pack.js'; _ = lodash; //core import { bootstrap } from '@angular/platform-browser-dynamic'; import { provide, enableProdMode } from '@angular/core'; import { APP_BASE_HREF } from '@angular/common'; import { ROUTER_PROVIDERS } from '@angular/router-deprecated'; //within the app import {DevcontrolpanelComponent} from '../imports/ui/components/devcontrolpanel/devcontrolpanel.component'; if (location.hostname == 'www.devcontrolpanel.com') { enableProdMode(); } bootstrap(DevcontrolpanelComponent, [ROUTER_PROVIDERS, provide(APP_BASE_HREF, { useValue: '/' })]); if (location.hostname != 'www.devcontrolpanel.com') { setTimeout(() => { Meteor.startup(function () { Meteor.defer(function () { Blaze.render(Template['Mongol'], document.body); }); }); }, 7000); }<file_sep>/source2/devcontrolpanel/server/config/account-config.ts import { Accounts } from 'meteor/accounts-base'; import {EmailUtility} from '../../imports/api/server/util/email-util'; let emailUtility = new EmailUtility(); Accounts.emailTemplates.siteName = "Devcontrolpanel"; Accounts.emailTemplates.from = "<EMAIL>"; Accounts.emailTemplates.verifyEmail.subject = (user) => { return 'Email Confirmation | Devcontrolpanel'; }; Accounts.emailTemplates.verifyEmail.html = (user, url) => { url = url.replace('#/', ''); var template = emailUtility.getForgotPasswordTemplate(user, url); return template; }; Accounts.emailTemplates.resetPassword.html = (user, url) => { url = url.replace('#/', ''); var template = emailUtility.getResetPasswordTemplate(user, url); return template; }; <file_sep>/source2/devcontrolpanel/imports/ui/components/my-profile-component/component/my-profile-update-component/model/update-profile.model.ts export interface IUpdateProfileForm{ name : string; email: string; profilePicture?: string; isLoading: boolean; }<file_sep>/source2/devcontrolpanel/imports/ui/directives/active-menu.directive.ts import {Directive, ElementRef, HostBinding, Renderer, AfterViewInit, Input} from '@angular/core'; import {Router, RouteParams} from '@angular/router-deprecated'; @Directive({ selector: 'a' }) export class ActiveMenuDirective implements AfterViewInit { private elementRef: ElementRef; private renderer: Renderer; private router: Router; private routeParams: RouteParams; private noHrefIndexOfValue: boolean; constructor(elementRef: ElementRef, renderer: Renderer, router: Router) { this.elementRef = elementRef; this.renderer = renderer; this.router = router; } @HostBinding('class.active') get valid() { // let href: string = this.elementRef.nativeElement.getAttribute('href') || '', pathNameOrinal: string = location.pathname.toLowerCase(); // href = href && href.toLowerCase(); // let pathName = pathNameOrinal.substring(0, pathNameOrinal.lastIndexOf('/')); // let isCurrentUrl = (jQuery(this.elementRef.nativeElement).hasClass('noHrefIndexOf') && pathName == href) || pathNameOrinal == href; let href: string = (this.elementRef.nativeElement.getAttribute('href') || '').toLowerCase(), pathName = location.pathname.toLocaleLowerCase(); if (jQuery(this.elementRef.nativeElement).hasClass('parent-link-ele')) { let hrefFirstRouteName = href.split('/')[1], locationFirstRouteName = pathName.split('/')[1]; return (hrefFirstRouteName == locationFirstRouteName); } else { return (href == pathName); } } ngAfterViewInit() { } } <file_sep>/source2/devcontrolpanel/imports/ui/components/my-profile-component/my-profile.component.ts //library imports import {Component, provide, Inject, NgZone} from '@angular/core'; import { ROUTER_DIRECTIVES, RouteConfig, RouterLink, CanActivate } from '@angular/router-deprecated'; import { Meteor } from 'meteor/meteor'; //with in the app import {LeftMenuProfileComponent} from '../left-menu-profile-component/left-menu-profile.component'; import {APP_COMMON_DIRECTIVES} from '../../directives/app-common.directive'; import {canActivateRoute} from '../../services/can-activate-route.service'; import { IUserProfile, LoginType } from '../../../common/user-profile-model'; import {AppComponent} from '../common/app-component'; import {AppFactory} from '../../services/config.service'; import {GlobalEventSerice} from '../../services/global-event.service'; //within the component import {MyProfileInfoComponent} from './component/my-profile-info-component/my-profile-info.component'; import {MyProfileUpdateComponent} from './component/my-profile-update-component/my-profile-update.component'; import {MyProfileResetPasswordComponent} from './component/my-profile-reset-password-component/my-profile-reset-password.component'; import template from './template/my-profile.template.html'; @Component({ selector: 'my-profile', template, directives: [ROUTER_DIRECTIVES, RouterLink, LeftMenuProfileComponent, APP_COMMON_DIRECTIVES] }) @CanActivate((next, prev) => { return canActivateRoute(next, prev, true); }) @RouteConfig([ { name: 'MyInfo', path: '/info', component: MyProfileInfoComponent, useAsDefault: true }, { name: 'MyProfileUpdate', path: '/update-info', component: MyProfileUpdateComponent }, { name: 'MyProfileResetPassword', path: '/reset-password', component: MyProfileResetPasswordComponent } ]) export class MyProfileComponent extends AppComponent { constructor(appFactory: AppFactory, globalEventSerice: GlobalEventSerice) { super(appFactory, globalEventSerice); //other code here } }<file_sep>/source2/devcontrolpanel/server/main.ts import { Meteor } from 'meteor/meteor'; Meteor.isDevelopment = process.env.ROOT_URL.indexOf('localhost') != -1; import './config/account-config'; import {initiateDBQueries} from './config/db'; import '../imports/api/server/user/meteor-user-methods'; import {thirdPartyOAuthConfiguration} from '../imports/startups/server/third-party-config'; import '../imports/services/wall-post.service'; import '../imports/api/server/wall-post/tag-methods'; import '../imports/api/server/wall-post/card-methods'; //security rules should at last import '../imports/api/server/publish/profile/user-profile'; import '../imports/api/server/publish/wall-post/wall-post'; //rest api files import '../imports/api/server/rest/sitemap/sitemap'; Meteor.startup(() => { // code to run on server at startup initiateDBQueries(); process.env.MAIL_FROM_ADDRESS = '<EMAIL>'; process.env.MAIL_URL = Meteor.settings['galaxy.meteor.com']['env']['MAIL_URL']; thirdPartyOAuthConfiguration(); }); <file_sep>/source2/devcontrolpanel/imports/ui/components/common/app-component.ts //core import {OnInit, OnDestroy, NgZone} from '@angular/core'; import {Meteor} from 'meteor/meteor'; import { MeteorComponent } from 'angular2-meteor'; import { IUserProfile, LoginType } from '../../../common/user-profile-model'; import {AppFactory, AuthStatus} from '../../services/config.service'; import {GlobalEventSerice} from '../../services/global-event.service'; import {UserProfileUtils} from '../../../common/user-profile-util'; export class AppComponent extends MeteorComponent implements OnInit, OnDestroy { loginType: typeof LoginType = LoginType; user: IUserProfile; userId: string; authStatusChangeSubscriber: any; currentUserCursor: Mongo.Cursor<Meteor.User>; currentUserCursorHandle: Meteor.LiveQueryHandle; otherUserCursor: { [key: string]: Mongo.Cursor<Meteor.User> } = {}; otherUserCursorHandle: { [key: string]: Meteor.LiveQueryHandle } = {}; otherUserProfile: { [key: string]: IUserProfile } = {}; constructor(private appFactory: AppFactory, private globalEventSerice: GlobalEventSerice, public ngZone?: NgZone ) { super(); this.user = this.appFactory.userProfile; this.userId = Meteor.userId(); this.otherUserProfile = {}; this.authStatusChangeSubscriber = globalEventSerice.authStatusChangeEvent$.subscribe((authStatus) => { if (authStatus == AuthStatus.AUTHENTICATED) { this.userId = Meteor.userId(); this.currentUserCursor = Meteor.users.find({ _id: this.userId }); this.stopWatchingCurrentUserProfile(); this.currentUserCursorHandle = this.currentUserCursor.observeChanges({ added: () => { this.updateCurrentUserProfile(); }, changed: () => { this.updateCurrentUserProfile(); }, removed: () => { this.updateCurrentUserProfile(); } }); } else { this.stopWatchingCurrentUserProfile(); this.user = null; this.userId = null; } }); } stopWatchingCurrentUserProfile() { if (this.currentUserCursorHandle) { this.currentUserCursorHandle.stop(); } } updateCurrentUserProfile() { this.user = UserProfileUtils.getCurrentUserProfileValues(); this.globalEventSerice.currentUserProfileChangedEvent(); } //for any user stopWatchingOtherUserProfile(userId: string) { if (this.otherUserCursorHandle[userId]) { this.otherUserCursorHandle[userId] } } updateOtherUserProfile(userId: string) { if (this.ngZone) { this.ngZone.run(() => { this.otherUserProfile[userId] = UserProfileUtils.getUserProfileValuesFromUserId(userId); }); } else { this.otherUserProfile[userId] = UserProfileUtils.getUserProfileValuesFromUserId(userId); } } watchOtherUserProfile(userId: string) { if (userId && !this.otherUserCursorHandle[userId]) { this.otherUserCursor[userId] = Meteor.users.find({ _id: userId }); this.stopWatchingOtherUserProfile(userId); this.otherUserCursorHandle[userId] = this.otherUserCursor[userId].observeChanges({ added: () => { this.updateOtherUserProfile(userId); }, changed: () => { this.updateOtherUserProfile(userId); }, removed: () => { this.updateOtherUserProfile(userId); } }); } } ngOnInit() { } ngOnDestroy() { this.authStatusChangeSubscriber.unsubscribe(); this.stopWatchingCurrentUserProfile(); _.forEach(this.otherUserCursorHandle, (value, key) => { this.stopWatchingOtherUserProfile(key); }); } }<file_sep>/source2/devcontrolpanel/imports/ui/services/config.service.ts import {OpaqueToken, NgZone, Injectable} from '@angular/core'; import {Meteor} from 'meteor/meteor'; import {Tracker} from 'meteor/tracker'; //with in the app import {UserProfileUtils} from '../../common/user-profile-util'; import {IUserProfile} from '../../common/user-profile-model'; export let OAppConfig = new OpaqueToken('app.config'); export interface IAppConfig { AnonymousProfileImageUrl: string; } export enum AuthStatus{ AUTHENTICATED, UNAUTHENTICATED } export enum LinkClickedName { SIGNIN, SIGNUP, SIGNOUT, FORGOT_PASSWORD } export const APP_CONFIG: IAppConfig = { AnonymousProfileImageUrl: '' }; @Injectable() export class AppFactory { private ngZone: NgZone; constructor(_ngZone: NgZone, private userProfileUtils: UserProfileUtils) { this.ngZone = _ngZone; this.updateUserSigninStatus(); } linkClickedName: LinkClickedName; isUserSigned: boolean = false; userProfile: IUserProfile; updateUserSigninStatus() { this.ngZone.runOutsideAngular(() => { Tracker.autorun(() => { this.ngZone.run(() => { //update the user profile value this.userProfile = UserProfileUtils.getCurrentUserProfileValues(); if (Meteor.userId()) { this.isUserSigned = true; } else { this.isUserSigned = false; } }); }); }); } }<file_sep>/source2/devcontrolpanel/imports/common/user-profile-model.ts import {Meteor} from 'meteor/meteor'; export enum LoginType{ DEVCONTROLPANEL, FACEBOOK, GOOGLE, TWITTER, GITHUB } export interface IWallPostSavedSearch{ search: string; tags: string[], createdBy: string[]; } export interface IUserProfile extends Meteor.User { name: string; email: string; profileImageURL: string; isUserAuthenticated: boolean; themeName: string; userId: string; loginType: LoginType, wallPostCustom: { savedSearch: string[] } } export interface IServiceProfileInfo { email: string; name: string; picture: string; } export interface IUserCollection { _id: string; profile?: IServiceProfileInfo; services?: { google: IServiceProfileInfo, facebook: IServiceProfileInfo, twitter: IServiceProfileInfo github: IServiceProfileInfo } }<file_sep>/source2/devcontrolpanel/imports/ui/components/devcontrolpanel/service/link-click.service.ts import {Injectable} from '@angular/core'; //global import {GlobalEventSerice} from '../../../services/global-event.service'; import {AppFactory, LinkClickedName} from '../../../services/config.service'; //component @Injectable() export class LinkClickService { constructor(private _globalEventSerice: GlobalEventSerice, private _appFactory: AppFactory) { } signinLinkClick(): void { this._globalEventSerice.linkClickedEvent(LinkClickedName.SIGNIN); } signupLinkClick(): void { this._globalEventSerice.linkClickedEvent(LinkClickedName.SIGNUP); } signoutLinkClick(): void { this._globalEventSerice.linkClickedEvent(LinkClickedName.SIGNOUT); } }<file_sep>/source2/devcontrolpanel/imports/common/sitemap.model.ts export interface ISitemapCollection{ _id?: string; contentId: string; contentType: string, isRemoved: boolean; }<file_sep>/source2/devcontrolpanel/imports/ui/components/wall-post-component/component/wall-post-write-component/service/wall-post-write.service.ts import {Meteor} from 'meteor/meteor'; import {IWallPost, IWallPostIndex, IWallPostTag} from '../../../../../../common/wall-post.model'; export class WallPostWriteService { constructor() { } getUserTags(): Promise<string[]> { return new Promise<string[]>((resolve, reject) => { Meteor.call('getUserTags', (error, tags) => { resolve(tags); }); }); } }<file_sep>/source2/devcontrolpanel/imports/ui/components/wall-post-component/component/wall-post-card-component/wall-post-card.component.ts //lib import import {Component, Input, AfterViewChecked, OnInit, NgZone, OnDestroy} from '@angular/core'; import {Meteor} from 'meteor/meteor'; import { RouteParams, RouterLink, Router } from '@angular/router-deprecated'; //within the app //common import { AppComponent } from '../../../common/app-component'; import { AppFactory } from '../../../../services/config.service'; import {IWallPost, IWallPostComment, WallPostComment} from '../../../../../common/wall-post.model'; import { UserProfileImageComponent } from '../../../user-profile-image-component/user-profile-image.component'; import {HighlightEditorDirective} from '../../../../directives/highlight-editor.directive'; import { APP_COMMON_DIRECTIVES } from '../../../../directives/app-common.directive'; import { WallPostCollection } from '../../../../../services/wall-post.service'; import {GlobalEventSerice} from '../../../../services/global-event.service'; import {UserProfileUtils} from '../../../../../common/user-profile-util'; import {IUserProfile} from '../../../../../common/user-profile-model'; //within the component import {WallPostService} from '../../service/wall-post.service'; import {WallPostCardCommentComponent} from './component/wall-post-card-comment-component/wall-post-card-comment.component'; import template from './template/wall-post-card.template.html'; @Component({ selector: 'wall-post-card', template, directives: [UserProfileImageComponent, HighlightEditorDirective, RouterLink, APP_COMMON_DIRECTIVES, WallPostCardCommentComponent], providers: [WallPostService] }) export class WallPostCardComponent extends AppComponent implements AfterViewChecked, OnInit, OnDestroy { wallPostDetail: IWallPost; wallPostDetailCursor: Mongo.Cursor<IWallPost>; wallPostDetailCursorHandle: Meteor.LiveQueryHandle; wallPostDeleteModalVisiblity: boolean = false; isPostDeleting: boolean = false; isDeleteCompleted: boolean = false; isPostDeleteSuccess: boolean = false; deletePostErrorMessage: string = ''; isPostOwner: boolean = false; userFullName: string = ''; isUserLikedPost: boolean = false; likeCount: number = 0; postOwnerProfile: IUserProfile; //comment variables isCommentVisible: boolean = false; commentCount: number = 0; replyTopComment: string = ''; constructor(appFactory: AppFactory, private wallPostCardService: WallPostService, private routeParams: RouteParams, ngZone: NgZone, private router: Router, globalEventSerice: GlobalEventSerice ) { super(appFactory, globalEventSerice, ngZone) this.wallPostDetail = <IWallPost>{}; this.postOwnerProfile = <IUserProfile>{ name: '' }; this.replyTopComment = ''; } updatePostDetail() { } resetDeletePostFlags() { this.isPostDeleting = false; this.isDeleteCompleted = false; this.isPostDeleteSuccess = false; this.deletePostErrorMessage = ''; } deletePost() { this.isPostDeleting = true; this.wallPostCardService.deletePost(this.wallPostId).then((error) => { this.isDeleteCompleted = true; this.isPostDeleting = false; if (error) { this.deletePostErrorMessage = error; this.isPostDeleteSuccess = false; } else { this.deletePostErrorMessage = ''; this.isPostDeleteSuccess = true; } }); } modelEvent(modelEventType) { if (modelEventType == 'hide' && this.isPostDeleteSuccess) { this.router.navigate(['WallPostDisplay']); } } updateWallPostDetail() { let wallPostFetched: IWallPost[] = this.wallPostDetailCursor.fetch(); if (wallPostFetched && wallPostFetched.length > 0) { this.wallPostDetail = wallPostFetched[0]; if (this.wallPostDetail && this.ngZone) { this.ngZone.run(() => { this.isPostOwner = this.wallPostDetail.createdBy == this.userId ? true : false; this.likeCount = this.wallPostDetail.like ? this.wallPostDetail.like.length : 0; if (this.likeCount > 0) { this.isUserLikedPost = _.some(this.wallPostDetail.like, (val) => { return val.createdBy == this.userId; }) } else { this.isUserLikedPost = false; } if (!this.wallPostDetail.comment) { this.wallPostDetail.comment = []; this.wallPostDetail.comment.push(new WallPostComment()); } }); if (this.wallPostDetail.createdBy) { this.watchOtherUserProfile(this.wallPostDetail.createdBy); } } } } ngOnInit() { if (this.wallPostId) { this.subscribe('WallpostDetail', this.wallPostId); this.wallPostDetailCursor = WallPostCollection.find({ _id: this.wallPostId }); this.updateWallPostDetail(); this.wallPostDetailCursorHandle = this.wallPostDetailCursor.observeChanges({ added: () => { this.updateWallPostDetail(); }, removed: () => { this.updateWallPostDetail(); }, changed: () => { this.updateWallPostDetail(); } }); } else { } } @Input() wallPostId: string; @Input() isFirst: boolean = false; @Input() isDetailView: boolean = false; initHeightlightJS() { jQuery("pre code").each(function () { let ele = jQuery(this); if (!ele.hasClass('hljs')) { hljs.highlightBlock(ele[0]); } }); } ngAfterViewChecked() { this.initHeightlightJS(); } //like starts likePost() { WallPostCollection.update({ _id: this.wallPostId }, { $addToSet: { like: { createdBy: this.userId } } }); } //unlike post unlikePost() { WallPostCollection.update({ _id: this.wallPostId }, { $pull: { like: { createdBy: this.userId } } }); } //comment addComment() { let updateObj: any = {}; let keyToUpdate = 'comment'; updateObj[keyToUpdate] = <IWallPostComment>{ comment: this.replyTopComment }; WallPostCollection.update({ _id: this.wallPostId }, { $addToSet: updateObj },{}, (error) => { if (!error) { this.replyTopComment = ''; } }); } destroyWallPostWatchHandle() { if (this.wallPostDetailCursorHandle) { this.wallPostDetailCursorHandle.stop(); } } //like ends ngOnDestroy() { this.destroyWallPostWatchHandle(); } }<file_sep>/source2/devcontrolpanel/typings/index.d.ts /// <reference path="globals/angular-google-analytics/index.d.ts" /> /// <reference path="globals/custom/index.d.ts" /> /// <reference path="globals/es6-shim/index.d.ts" /> /// <reference path="globals/jquery/index.d.ts" /> /// <reference path="globals/lodash/index.d.ts" /> /// <reference path="globals/meteor/index.d.ts" /> /// <reference path="globals/node/index.d.ts" /> /// <reference path="modules/blue-tape/index.d.ts" /> /// <reference path="modules/es6-promise/index.d.ts" />
7df7349ddf68e2041f0d26f94b13f592c5489a7a
[ "JavaScript", "TypeScript" ]
65
TypeScript
ittechsathish/angular-meteor-devcontrolpanel
11b0b363b9465a93ffe43d75cd6aaef1af99bf06
e28671e12253bc5b326af948b5ae8723e20cfab4
refs/heads/master
<repo_name>pianoza/lms<file_sep>/lib/SYSLOG.class.php <?php define('SYSLOG_RES_USER', 1); define('SYSLOG_RES_ASSIGN', 2); define('SYSLOG_RES_LIAB', 3); define('SYSLOG_RES_NODEASSIGN', 4); define('SYSLOG_RES_NODE', 5); define('SYSLOG_RES_MAC', 6); define('SYSLOG_RES_CUST', 7); define('SYSLOG_RES_CUSTCONTACT', 8); define('SYSLOG_RES_IMCONTACT', 9); define('SYSLOG_RES_CUSTGROUP', 10); define('SYSLOG_RES_CUSTASSIGN', 11); define('SYSLOG_RES_TARIFF', 12); define('SYSLOG_RES_NODEGROUP', 13); define('SYSLOG_RES_NODEGROUPASSIGN', 14); define('SYSLOG_RES_TAX', 15); define('SYSLOG_RES_NUMPLAN', 16); define('SYSLOG_RES_NUMPLANASSIGN', 17); define('SYSLOG_RES_DIV', 18); define('SYSLOG_RES_COUNTRY', 19); define('SYSLOG_RES_STATE', 20); define('SYSLOG_RES_ZIP', 21); define('SYSLOG_RES_HOST', 22); define('SYSLOG_RES_DAEMONINST', 23); define('SYSLOG_RES_DAEMONCONF', 24); define('SYSLOG_RES_CASHSOURCE', 25); define('SYSLOG_RES_UICONF', 26); define('SYSLOG_RES_PROMO', 27); define('SYSLOG_RES_PROMOSCHEMA', 28); define('SYSLOG_RES_PROMOASSIGN', 29); define('SYSLOG_RES_EXCLGROUP', 30); define('SYSLOG_RES_DBBACKUP', 31); define('SYSLOG_RES_PAYMENT', 32); define('SYSLOG_RES_CASHIMPORT', 33); define('SYSLOG_RES_SOURCEFILE', 34); define('SYSLOG_RES_CASH', 35); define('SYSLOG_RES_DOC', 36); define('SYSLOG_RES_INVOICECONT', 37); define('SYSLOG_RES_RECEIPTCONT', 38); define('SYSLOG_RES_DNOTECONT', 39); define('SYSLOG_RES_CASHREG', 40); define('SYSLOG_RES_CASHRIGHT', 41); define('SYSLOG_RES_CASHREGHIST', 42); define('SYSLOG_RES_NETWORK', 43); define('SYSLOG_RES_NETDEV', 44); define('SYSLOG_RES_NETLINK', 45); define('SYSLOG_RES_MGMTURL', 46); define('SYSLOG_RES_TMPL', 47); $SYSLOG_RESOURCES = array( SYSLOG_RES_USER => trans('user<!syslog>'), SYSLOG_RES_ASSIGN => trans('assignment<!syslog>'), SYSLOG_RES_LIAB => trans('liability<!syslog>'), SYSLOG_RES_NODEASSIGN => trans('node assignment<!syslog>'), SYSLOG_RES_NODE => trans('node<!syslog>'), SYSLOG_RES_MAC => trans('mac<!syslog>'), SYSLOG_RES_CUST => trans('customer<!syslog>'), SYSLOG_RES_CUSTCONTACT => trans('customer contact<!syslog>'), SYSLOG_RES_IMCONTACT => trans('IM contact<!syslog>'), SYSLOG_RES_CUSTGROUP => trans('customer group<!syslog>'), SYSLOG_RES_CUSTASSIGN => trans('customer assignment<!syslog>'), SYSLOG_RES_TARIFF => trans('tariff<!syslog>'), SYSLOG_RES_NODEGROUP => trans('node group<!syslog>'), SYSLOG_RES_NODEGROUPASSIGN => trans('node group assignment<!syslog>'), SYSLOG_RES_TAX => trans('tax rate<!syslog>'), SYSLOG_RES_NUMPLAN => trans('number plan<!syslog>'), SYSLOG_RES_NUMPLANASSIGN => trans('number plan assignment<!syslog>'), SYSLOG_RES_DIV => trans('division<!syslog>'), SYSLOG_RES_COUNTRY => trans('country<!syslog>'), SYSLOG_RES_STATE => trans('state<!syslog>'), SYSLOG_RES_ZIP => trans('zip code<!syslog>'), SYSLOG_RES_HOST => trans('host<!syslog>'), SYSLOG_RES_DAEMONINST => trans('daemon instance<!syslog>'), SYSLOG_RES_DAEMONCONF => trans('daemon instance setting<!syslog>'), SYSLOG_RES_CASHSOURCE => trans('cash import source<!syslog>'), SYSLOG_RES_UICONF => trans('configuration setting<!syslog>'), SYSLOG_RES_PROMO => trans('promotion<!syslog>'), SYSLOG_RES_PROMOSCHEMA => trans('promotion schema<!syslog>'), SYSLOG_RES_PROMOASSIGN => trans('promotion schema assignment<!syslog>'), SYSLOG_RES_EXCLGROUP => trans('customer group exclusion<!syslog>'), SYSLOG_RES_DBBACKUP => trans('database backup<!syslog>'), SYSLOG_RES_PAYMENT => trans('payment<!syslog>'), SYSLOG_RES_CASHIMPORT => trans('imported financial operation<!syslog>'), SYSLOG_RES_SOURCEFILE => trans('imported file with financial operations<!syslog>'), SYSLOG_RES_CASH => trans('financial operation<!syslog>'), SYSLOG_RES_DOC => trans('document<!syslog>'), SYSLOG_RES_INVOICECONT => trans('invoice contents<!syslog>'), SYSLOG_RES_RECEIPTCONT => trans('receipt contents<!syslog>'), SYSLOG_RES_DNOTECONT => trans('debit note contents<!syslog>'), SYSLOG_RES_CASHREG => trans('cash registry<!syslog>'), SYSLOG_RES_CASHRIGHT => trans('cash registry rights<!syslog>'), SYSLOG_RES_CASHREGHIST => trans('cash registry history<!syslog>'), SYSLOG_RES_NETWORK => trans('network<!syslog>'), SYSLOG_RES_NETDEV => trans('network device<!syslog>'), SYSLOG_RES_NETLINK => trans('network link<!syslog>'), SYSLOG_RES_MGMTURL => trans('management url<!syslog>'), SYSLOG_RES_TMPL => trans('template<!syslog>'), ); $SYSLOG_RESOURCE_KEYS = array( SYSLOG_RES_USER => 'userid', SYSLOG_RES_ASSIGN => 'assignmentid', SYSLOG_RES_LIAB => 'liabilityid', SYSLOG_RES_NODEASSIGN => 'nodeassignmentid', SYSLOG_RES_NODE => 'nodeid', SYSLOG_RES_MAC => 'macid', SYSLOG_RES_CUST => 'customerid', SYSLOG_RES_CUSTCONTACT => 'customercontactid', SYSLOG_RES_IMCONTACT => 'imessengerid', SYSLOG_RES_CUSTGROUP => 'customergroupid', SYSLOG_RES_CUSTASSIGN => 'customerassignmentid', SYSLOG_RES_TARIFF => 'tariffid', SYSLOG_RES_NODEGROUP => 'nodegroupid', SYSLOG_RES_NODEGROUPASSIGN => 'nodegroupassignmentid', SYSLOG_RES_TAX => 'taxrateid', SYSLOG_RES_NUMPLAN => 'numberplanid', SYSLOG_RES_NUMPLANASSIGN => 'numberplanassignmentid', SYSLOG_RES_DIV => 'divisionid', SYSLOG_RES_COUNTRY => 'countryid', SYSLOG_RES_STATE => 'stateid', SYSLOG_RES_ZIP => 'zipcodeid', SYSLOG_RES_HOST => 'hostid', SYSLOG_RES_DAEMONINST => 'daemoninstanceid', SYSLOG_RES_DAEMONCONF => 'daemonconfigid', SYSLOG_RES_CASHSOURCE => 'cashsourceid', SYSLOG_RES_UICONF => 'uiconfigid', SYSLOG_RES_PROMO => 'promotionid', SYSLOG_RES_PROMOSCHEMA => 'promotionschemaid', SYSLOG_RES_PROMOASSIGN => 'promotionassignmentid', SYSLOG_RES_EXCLGROUP => 'excludedgroupid', SYSLOG_RES_DBBACKUP => null, SYSLOG_RES_PAYMENT => 'paymentid', SYSLOG_RES_CASHIMPORT => 'importid', SYSLOG_RES_SOURCEFILE => 'sourcefileid', SYSLOG_RES_CASH => 'cashid', SYSLOG_RES_DOC => 'documentid', SYSLOG_RES_INVOICECONT => null, SYSLOG_RES_RECEIPTCONT => null, SYSLOG_RES_DNOTECONT => 'debitnotecontentid', SYSLOG_RES_CASHREG => 'cashregistryid', SYSLOG_RES_CASHRIGHT => 'cashrightid', SYSLOG_RES_CASHREGHIST => 'cashreghistoryid', SYSLOG_RES_NETWORK => 'networkid', SYSLOG_RES_NETDEV => 'networkdeviceid', SYSLOG_RES_NETLINK => 'networklinkid', SYSLOG_RES_MGMTURL => 'managementurlid', SYSLOG_RES_TMPL => 'templateid', ); ?>
ba02fe88535d5980a67df28203ff5ab38a1e77b1
[ "PHP" ]
1
PHP
pianoza/lms
7e716a21ef44c18b9fceb46debd0a3b23b293bdc
1e281d9050416418fcba035dd8027f1dc359da53
refs/heads/master
<repo_name>anujthapa/storybook<file_sep>/storybook-static/precache-manifest.4a63a98efd10b447b73f6f64b973e947.js self.__precacheManifest = (self.__precacheManifest || []).concat([ { "revision": "991809201dbf7ca0e9fb73c36508a8f2", "url": "iframe.html" }, { "url": "main.099725663f186595344e.bundle.js" }, { "url": "runtime~main.099725663f186595344e.bundle.js" }, { "url": "vendors~main.099725663f186595344e.bundle.js" } ]);<file_sep>/src/components/main/Index.jsx import React, { Component } from "react"; import Textinput from "../common/Textinput"; import Button from "../common/Button"; class Index extends Component { state = [ { fname: "", lname: "", age: "", phone: "", email: "", details: "" }, ] onChangeHandaler = e => { this.setState({[e.target.name]:e.target.value}) }; render() { return ( <div> <form onSubmit> <Textinput type="text" value={this.state.fname} name="fname" palceholder="please enter your first name" onchange={this.onChnageHandaler} /> <Textinput type="text" value={this.state.lname} name="lname" palceholder="please enter your last name" onchange={this.onChnageHandaler} /> <Textinput type="number" value={this.state.age} name="age" name="age" palceholder="please enter your age" onchange={this.onChnageHandaler} /> <Textinput type="number" value={this.state.phone} name="phone" palceholder="please enter your phone number" onchange={this.onChnageHandaler} /> <Textinput type="email" value={this.state.email} name="email" palceholder="please enter your email" onchange={this.onChnageHandaler} /> <Button content="Save" /> </form> </div> ); } } export default Index; <file_sep>/src/stories/index.js import React from "react"; import { storiesOf } from "@storybook/react"; import { action } from "@storybook/addon-actions"; import App from "../App"; import Textinput from "../components/common/Textinput"; import Button from "../components/common/Button"; import Index from "../components/main/Index"; storiesOf("App", module).add("App", () => <App />); storiesOf("Common", module) .add("Textinput", () => ( <Textinput value="" onchange={action("hshaj")} type="number" placeholder="please enter your text" /> )) .add("Button", () => ( <Button onclick={action("hello")} content="click Me!" type="submit" /> )); storiesOf("main", module).add("Main", () => <Index />);
234dbe3148bff53b7549a65998c0a61a9a9a2678
[ "JavaScript" ]
3
JavaScript
anujthapa/storybook
963773b5b6cdf830bfad26c0ff5ddd526d80626a
f9cc3f2bc6f92158e4b80a9da235c8428dfc5deb
refs/heads/master
<file_sep> #include "pruntime.h" BEGIN_PEEFY_NAMESPACE END_PEEFY_NAMESPACE <file_sep> #ifndef __P_JIT_H__ #define __P_JIT_H__ // peefy JIT即时编译(just-in-time compilation) #include "util.h" BEGIN_PEEFY_NAMESPACE END_PEEFY_NAMESPACE #endif <file_sep> #ifndef __P_UTF8_LIB_H__ #define __P_UTF8_LIB_H__ // peefy utf8编码库 #include "util.h" BEGIN_PEEFY_NAMESPACE END_PEEFY_NAMESPACE #endif <file_sep> #ifndef __P_IO_BUFFER_H__ #define __P_IO_BUFFER_H__ // peefy 输入输出缓存库 #include "util.h" BEGIN_PEEFY_NAMESPACE class PBuffer { private: /* data */ public: PBuffer(/* args */); ~PBuffer(); }; PBuffer::PBuffer(/* args */) { } PBuffer::~PBuffer() { } class PIOBuffer : public PBuffer { private: /* data */ public: PIOBuffer(/* args */); ~PIOBuffer(); }; PIOBuffer::PIOBuffer(/* args */) { } PIOBuffer::~PIOBuffer() { } class PFileBuffer : public PIOBuffer { private: char _nextchar; public: PFileBuffer() : _nextchar('\0') {} ~PFileBuffer(); char nextChar(); }; PFileBuffer::PFileBuffer(/* args */) { } PFileBuffer::~PFileBuffer() { } END_PEEFY_NAMESPACE #endif <file_sep> #include <stdio.h> int main(int argc, char **argv) { int b; int c; b = 1; c = b * 2; printf("test file\n"); return -1; } <file_sep> #include "perror.h" BEGIN_PEEFY_NAMESPACE END_PEEFY_NAMESPACE <file_sep> #include "pjit.h" BEGIN_PEEFY_NAMESPACE END_PEEFY_NAMESPACE <file_sep> #include "pmath.h" BEGIN_PEEFY_NAMESPACE END_PEEFY_NAMESPACE <file_sep> #ifndef __SYMBOL_H__ #define __SYMBOL_H__ // tokens and classes 标记和类(运算符放在最后且按优先级顺序排列) enum { Num = 128, Fun, Sys, Glo, Loc, Id, Char, Else, Enum, If, Int, Return, Sizeof, While, Assign, Cond, Lor, Lan, Or, Xor, And, Eq, Ne, Lt, Gt, Le, Ge, Shl, Shr, Add, Sub, Mul, Div, Mod, Inc, Dec, Brak }; // operator codes (运算符代码) enum { LEA, IMM, JMP, JSR, BZ, BNZ, ENT, ADJ, LEV, LI, LC, SI, SC, PSH, OR, XOR, AND, EQ, NE, LT, GT, LE, GE, SHL, SHR, ADD, SUB, MUL, DIV, MOD, OPEN, READ, CLOS, PRTF, MALC, FREE, MSET, MCMP, EXIT }; // source types (源代码类型) enum { CHAR, INT, PTR }; // identitiers offsets (since we can't create an ident struct) enum { Tk, Hash, Name, Class, Type, Val, HClass, Htype, HVal, Idsz }; #endif <file_sep> #ifndef __P_ERROR_H__ #define __P_ERROR_H__ // peefy 命令行参数库 PFlag #include "util.h" #include <string> #include <unordered_map> #include <unordered_set> using namespace std; BEGIN_PEEFY_NAMESPACE template <typename T> struct PFlag { T val; T defaultVal; T* ptr; string description; inline bool operator==(T& other) { return val == other; } inline bool operator!=(T& other) { return val != other; } }; class PCmdFlag { private: static unordered_map<string, string> symtb; public: PCmdFlag(/* args */); ~PCmdFlag(); public: static PFlag<string> newString(const char * paras) { return PFlag<string>(); } static PFlag<bool> newBoolean(const char * paras) { return PFlag<bool>(); } }; PCmdFlag::PCmdFlag(/* args */) { } PCmdFlag::~PCmdFlag() { } END_PEEFY_NAMESPACE #endif <file_sep> #include "prexpr.h" BEGIN_PEEFY_NAMESPACE END_PEEFY_NAMESPACE <file_sep> #ifndef __P_FA_H__ #define __P_FA_H__ // peefy 不确定和确定的有穷自动机 // 不确定的有穷自动机 NFA // 确定的有穷自动机 DFA #include "util.h" BEGIN_PEEFY_NAMESPACE END_PEEFY_NAMESPACE #endif <file_sep> #include "psymtable.h" BEGIN_PEEFY_NAMESPACE void init_table() { } END_PEEFY_NAMESPACE <file_sep> #include "plexical.h" // 词法分析器 #include "util.h" BEGIN_PEEFY_NAMESPACE PlexicalState::PlexicalState() { } PlexicalState::~PlexicalState() { } PTokenValue PlexicalState::nextToken() { while (true) { break; } return PTokenValue(); } END_PEEFY_NAMESPACE <file_sep> #ifndef __P_AST_H__ #define __P_AST_H__ // peefy 抽象语法树AST库 #include "util.h" #include <vector> using namespace std; BEGIN_PEEFY_NAMESPACE class AstTreeNode { private: public: AstTreeNode() = default; virtual ~AstTreeNode() = default; }; class AstTree { private: public: AstTree() = default; AstTree(AstTree& ohther) = default; AstTree& operator=(AstTree& ohther) = default; virtual ~AstTree() = default; private: bool _isAbstract; public: AstTreeNode* root; vector<AstTreeNode*> nodes; void inOrder() { return; } }; END_PEEFY_NAMESPACE #endif <file_sep> #ifndef __P_VM_H__ #define __P_VM_H__ // peefy 虚拟机 #include "util.h" BEGIN_PEEFY_NAMESPACE enum class PVMCommandType { LEA , IMM , // 跳转指令 JMP , JSR , BZ , BNZ , ENT , ADJ , LEV , LI , LC , SI , SC , // 压栈 PSH , OR , XOR , AND , EQ , NE , LT , GT , LE , GE , SHL , SHR , // 加 ADD , // 减 SUB , // 乘 MUL , // 除 DIV , // 求余 MOD , OPEN,READ,CLOS,PRTF,MALC,FREE,MSET,MCMP,EXIT, }; struct PVMCommand { public: PVMCommand() noexcept = default; virtual ~PVMCommand() noexcept = default; constexpr PVMCommand(PVMCommand& token) noexcept = default; constexpr PVMCommand& operator=(PVMCommand& token) noexcept = default; constexpr PVMCommand& operator=(PVMCommand& token) noexcept = default; public: PVMCommandType command; }; class PVirtulMachine { private: /* data */ public: PVirtulMachine(/* args */); PVirtulMachine(); }; PVirtulMachine::PVirtulMachine(/* args */) { } PVirtulMachine::PVirtulMachine() { } END_PEEFY_NAMESPACE #endif <file_sep> #include "pfunction.h" // 函数模块 BEGIN_PEEFY_NAMESPACE END_PEEFY_NAMESPACE <file_sep> #include "poperator.h" BEGIN_PEEFY_NAMESPACE END_PEEFY_NAMESPACE <file_sep> #include "pobject.h" // 对象 BEGIN_PEEFY_NAMESPACE END_PEEFY_NAMESPACE <file_sep> #ifndef __P_PARISER_H__ #define __P_PARISER_H__ // peefy 语法分析器 #include "util.h" BEGIN_PEEFY_NAMESPACE class PPariser { private: public: PPariser() noexcept = default; virtual ~PPariser() = default; }; END_PEEFY_NAMESPACE #endif <file_sep> #ifndef __P_TYPE_H__ #define __P_TYPE_H__ // peefy 类型推导库 #include "util.h" BEGIN_PEEFY_NAMESPACE enum class PType { }; END_PEEFY_NAMESPACE #endif <file_sep> #ifndef __P_OPERATOR_H__ #define __P_OPERATOR_H__ // peefy 操作符库 #include "util.h" BEGIN_PEEFY_NAMESPACE class POperator { private: public: POperator() = default; virtual ~POperator() = default; }; POperator::POperator() { } POperator::~POperator() { } END_PEEFY_NAMESPACE #endif <file_sep> #ifndef __P_RUNTIME_H__ #define __P_RUNTIME_H__ // peefy 运行时环境 #include "util.h" BEGIN_PEEFY_NAMESPACE END_PEEFY_NAMESPACE #endif <file_sep> #include "ppariser.h" #include "util.h" // 语法分析器 BEGIN_PEEFY_NAMESPACE END_PEEFY_NAMESPACE <file_sep> #ifndef __P_TOKEN_H__ #define __P_TOKEN_H__ // peefy 标识符 #include <string> #include <unordered_map> #include <unordered_set> #include "util.h" #include "psymtable.h" using namespace std; BEGIN_PEEFY_NAMESPACE template<typename T> struct PIdentifier { public: constexpr PIdentifier() noexcept = default; virtual ~PIdentifier() noexcept = default; constexpr PIdentifier(PIdentifier& token) noexcept = default; constexpr PIdentifier& operator=(PIdentifier& token) noexcept = default; constexpr PIdentifier& operator=(PIdentifier& token) noexcept = default; public: T value; private: }; struct PKeyword : public PIdentifier<string> { public: explicit PKeyword(string& val) noexcept { this->value = val; } explicit PKeyword(string&& val) noexcept { this->value = val; } private: PKeyword() = default; public: inline bool operator== (PKeyword& other) { return this->value == other.value; } inline bool operator!= (PKeyword& other) { return this->value != other.value; } inline int compare(PKeyword& other) { return strcmp(this->value.c_str(), other.value.c_str()); } private: }; using SymbolTable = SymbolTableBase<peefy::SymbolTableEntry, peefy::PKeyword>; END_PEEFY_NAMESPACE #endif <file_sep> #ifndef __PEEFY_H__ #define __PEEFY_H__ #define PEEFY_MAJOR_VERSION "0" #define PEEFY_MINOR_VERSION "0" #define PEEFY_RELEASE_VERSION "1" #define PEEFY_VERSION "v" PEEFY_MAJOR_VERSION "." PEEFY_MINOR_VERSION "." PEEFY_RELEASE_VERSION #endif <file_sep> #include "ptype.h" BEGIN_PEEFY_NAMESPACE END_PEEFY_NAMESPACE <file_sep> #ifndef __UTIL_H__ #define __UTIL_H__ // 字符是否是十进制的数字字符 #define IS_DIGIT(c) ((c) >= '0' && (c) <= '9') // 字符是否是八进制的数字字符 #define IS_DIGIT_OCTAL(c) ((c) >= '0' && (c) <= '7') // 字符是否是八进制的数字字符 #define IS_DIGIT_HEX(c) (IS_DIGIT(c) || ((c) >= 'a' && (c) <= 'f') || ((c) >= 'A' && (c) <= 'F')) // 字符是否是大写字母 #define IS_UPPER_CHAR(c) ((c) >= 'A' && (c) <= 'Z') // 字符是否是小写字母 #define IS_LOWER_CHAR(c) ((c) >= 'a' && (c) <= 'z') // 字符是否是英文字母 #define IS_ALPHA(c) (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z')) // 是否为换行符 #define IS_NEW_LINE(c) ((c) == '\n' || (c) == '\r') // 是否是空白字符 #define IS_WHITE_SPACE(c) ((c) == ' ' || (c) == '\f' || (c) == '\t' || (c) == '\v') // 求数组的大小 #define ARR_SIZE(arr) (sizeof(arr) / sizeof(arr[0])) #define and && #define or || #define xor ^ #define bitand & #define bitor | #define mod % #define div / #define mul * #define add + #define sub - #define MAIN_FUNC_RETURN_VAL -1 #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 1 #endif #define BEGIN_PEEFY_NAMESPACE namespace peefy { #define END_PEEFY_NAMESPACE } #endif <file_sep> #include "phash.h" BEGIN_PEEFY_NAMESPACE END_PEEFY_NAMESPACE <file_sep> #include "pcmdflag.h" BEGIN_PEEFY_NAMESPACE END_PEEFY_NAMESPACE <file_sep> #ifndef __P_REXPR_H__ #define __P_REXPR_H__ // peefy 正则表达式库 #include "util.h" #define RE_ID "([a-zA-Z]){1}([a-z|A-Z|0-9|_]){*}" #define RE_NUM "[0-9]+(.[0-9])?(E(+|-)?[0-9]+)?" BEGIN_PEEFY_NAMESPACE END_PEEFY_NAMESPACE #endif <file_sep> #ifndef __P_LEXICAL_H__ #define __P_LEXICAL_H__ // peefy 词法分析器 /* * 状态机: * 状态转移图: */ #include "util.h" #include "ptoken.h" BEGIN_PEEFY_NAMESPACE // 词法分析状态机 class PlexicalState { private: public: PlexicalState(); ~PlexicalState(); public: int current_char; int line_number; int last_line; PTokenValue current_token; //输入字符/词素流 PTokenValue lookahead; // string source; // 当前源名称 string enbn; // 环境变量名称 public: PTokenValue nextToken(); }; END_PEEFY_NAMESPACE #endif <file_sep> #ifndef __P_STMT_H__ #define __P_STMT_H__ // peefy 语句库 #include "util.h" BEGIN_PEEFY_NAMESPACE END_PEEFY_NAMESPACE #endif <file_sep> #ifndef __CONFIG_H_ #define __CONFIG_H_ #define DUGU_VERSION "v0.0.0.1" #define COMPLIER_NAME "dugu" #define PARA_SRC "-s" #define PARA_DEBUG "-d" #define POOL_SIZE (256 * 1024) #endif <file_sep> #include "piobuffer.h" BEGIN_PEEFY_NAMESPACE END_PEEFY_NAMESPACE <file_sep> #include "pgc.h" // 垃圾回收器 BEGIN_PEEFY_NAMESPACE END_PEEFY_NAMESPACE <file_sep>package main type SymbolTableEntry struct { str string token int } type SymbolTableBase struct { table map[string] SymbolTableEntry } func (s *SymbolTableBase) Insert(item SymbolTableEntry) { s.table = make(map[string] SymbolTableEntry, 0) } func (s *SymbolTableBase) Find(item SymbolTableEntry) bool { s.table = make(map[string] SymbolTableEntry, 0) return false } <file_sep> #ifndef __P_HASH_H__ #define __P_HASH_H__ // peefy 哈希hash库 #include "util.h" BEGIN_PEEFY_NAMESPACE END_PEEFY_NAMESPACE #endif <file_sep> #ifndef __P_OBJECT_H__ #define __P_OBJECT_H__ // peefy 对象库 #include <stdint.h> #include <string> #include "util.h" using namespace std; BEGIN_PEEFY_NAMESPACE struct PObject { public: PObject* next; int intpreter; bool isMarked; private: int _private_count; }; template <typename T> struct PObjcetWithT : public PObject { public: uint64_t refrence_count; uint64_t hashval; constexpr PObjcetWithT() : refrence_count(0), hashval(0) { } T value; private: }; struct PObject : public PObjcetBase<int> { private: PObject* next; }; END_PEEFY_NAMESPACE #endif <file_sep> #include <string> #include <memory> #include <mutex> template<typename _TableValue, typename _SymbolValue> class SymbolTableBase { public: using tablebval_type = _TableValue; using id_type = _SymbolValue; typedef shared_ptr<SymbolTableBase<tablebval_type, id_type> > Ptr; private: unordered_set<PKeyword> _table; static mutex _mutex; static Ptr _self; private: SymbolTableBase() = default; SymbolTableBase(SymbolTableBase&) = delete; SymbolTableBase& operator=(const SymbolTableBase&) = delete; public: virtual ~SymbolTableBase() = default; public: bool insert(tablebval_type& val); bool isintable(tablebval_type& val); static Ptr& instance() { lock_guard<mutex> lk(_mutex); if (_self == nullptr) { _self = make_shared<SymbolTableBase<_TableValue> >(); } return _self; } }; template<typename _TableValue, typename _SymbolValue> SymbolTableBase<_TableValue, _SymbolValue>::Ptr SymbolTableBase<_TableValue, _SymbolValue>::_self = nullptr; template<typename _TableValue, typename _SymbolValue> bool SymbolTableBase<_TableValue, _SymbolValue>::insert(tablebval_type& val) { return false; } template<typename _TableValue, typename _SymbolValue> bool SymbolTableBase<_TableValue, _SymbolValue>::isintable(tablebval_type& val) { return false; } <file_sep> #ifndef __P_API_H__ #define __P_API_H__ // Peefy Compiler C API #include <stdint.h> #include <string> using std::string; using std::wstring; #define pint8 int8_t #define pint16 int16_t #define pint32 int32_t #define puint8 uint8_t #define puint16 uint16_t #define puint32 uint32_t #define pstring string #define wstring wstring #include "util.h" #define PEEFY_API extern extern "C" { PEEFY_API int peefy_init(); } #endif <file_sep># PeefyCompiler ## How to use > make > make r [compiler_source_code](https://github.com/Peefy/PeefyCompiler/blob/master/src/compiler.c) ## Use c4 > make c4 > make r4 [c4_source_code](https://github.com/Peefy/PeefyCompiler/blob/master/third_party/c4/c4.c) ## Use Visual Studio and MSVC > open the vs solution in the ./vs/PeefyCompilerVS/PeefyCompilerVS.sln ## VB 24-line Compiler Demo [link](https://github.com/Peefy/PeefyCompiler/blob/master/third_party/VB_24line_complier/VB_complier_24line.c) ## Thanks [c4](https://github.com/rswier/c4) <file_sep> #ifndef __P_SYMBOL_TABLE_H__ #define __P_SYMBOL_TABLE_H__ // peefy 符号表库 #include <string> #include <memory> #include <mutex> #include <type_traits> #include "pidentifier.h" #include "util.h" using namespace std; BEGIN_PEEFY_NAMESPACE struct SymbolTableEntry { string str; int token; }; template<typename _TableValue, typename _SymbolValue> class SymbolTableBase { public: using tablebval_type = _TableValue; using symbol_type = _SymbolValue; using self_type = SymbolTableBase<tablebval_type, symbol_type>; typedef shared_ptr<SymbolTableBase<tablebval_type, symbol_type> > Ptr; private: unordered_set<string> _table; static mutex _mutex; static Ptr _self; private: SymbolTableBase() noexcept = default; SymbolTableBase(SymbolTableBase&) noexcept = delete; SymbolTableBase& operator=(const SymbolTableBase&) noexcept = delete; public: virtual ~SymbolTableBase() = default; public: inline bool insert(tablebval_type& val); inline bool isintable(tablebval_type& val); constexpr static Ptr& instance() { lock_guard<mutex> lk(_mutex); if (_self == nullptr) { _self = make_shared<self_type >(); } return _self; } }; template<typename _TableValue, typename _SymbolValue> SymbolTableBase<_TableValue, _SymbolValue>::Ptr SymbolTableBase<_TableValue, _SymbolValue>::_self = nullptr; template<typename _TableValue, typename _SymbolValue> inline bool SymbolTableBase<_TableValue, _SymbolValue>::insert(tablebval_type& val) { this->_table.insert(static_cast<string>(val.str)); return true; } template<typename _TableValue, typename _SymbolValue> inline bool SymbolTableBase<_TableValue, _SymbolValue>::isintable(tablebval_type& val) { return this->_table.find(val) != this->_table.end(); } END_PEEFY_NAMESPACE #endif <file_sep> #include "util.h" int main(int argc, char * argv[]) { printf("Hello peefy cpp compiler!\n"); return CONSOLE_SUCCESS; } <file_sep> #include "pvm.h" // 虚拟机模块 // 均用四个字母表示的虚拟机指令或者汇编指令 static char* vm_command = "LEA ,IMM ,JMP ,JSR ,BZ ,BNZ ,ENT ,ADJ ,LEV ,LI ,LC ,SI ,SC ,PSH ," "OR ,XOR ,AND ,EQ ,NE ,LT ,GT ,LE ,GE ,SHL ,SHR ,ADD ,SUB ,MUL ,DIV ,MOD ," "OPEN,READ,CLOS,PRTF,MALC,FREE,MSET,MCMP,EXIT," <file_sep> #include "putf8lib.h" BEGIN_PEEFY_NAMESPACE END_PEEFY_NAMESPACE <file_sep> #include "pexpr.h" BEGIN_PEEFY_NAMESPACE END_PEEFY_NAMESPACE <file_sep> #ifndef __P_GC_H__ #define __P_GC_H__ // peefy 垃圾回收器GC库 #include "util.h" BEGIN_PEEFY_NAMESPACE END_PEEFY_NAMESPACE #endif <file_sep> #ifndef __P_TOKEN_H__ #define __P_TOKEN_H__ // peefy 记号token库 #include "util.h" #include <string> using namespace std; BEGIN_PEEFY_NAMESPACE // 记号类型 enum class PTokenType { // 错误,什么都不是 None = -1, // 标识符 (变量名、数组名、函数名等) Identifier = 257, // 数字(整数) Integer, // 数字(浮点数) Float, // 字符 Char, // 字符串 String, // 操作符 @ $ # % ^ & * + - * / ++ -- += -= *= /= && || ~ ** ? . ' " Operator, // 关键字 Keyword, // () [] {} <> Brakets, // 换行 Endline, // 句尾 Over, // 注释 Comment, // 空白 WhiteSpace, // 赋值 = Assign, // 函数 Function, // 系统指令 System, // 全局变量 GlobalVaribale, // 局部变量 LocalVaribale, // 枚举 Enum, // 条件运算符 if If, // 条件运算符 else Else, // 循环运算符 for For, // 循环运算符while While, // 按位或 | Lor, // 按位与 & Lan, // 按位取反 ~ Lnon, // 逻辑取反 ! Non, // 逻辑或 || Or, // 按位异或 ^ Xor, // 逻辑与 && And, // 是否等于 == Eq, // 是否不等 != Ne, // 小于 < Lt, // 大于 > Gt, // 小于等于 <= Le, // 大于等于 >= Ge, // 按位左移动 << Shl, // 按位右移动 >> Shr, // 加法运算符 + Add, // 减法运算符 - Sub, // 乘法运算符 * Mul, // 除法运算符 / Div, // 求余运算符 % Mod, // 自加运算符 ++ Inc, // 自减运算符 -- Dec, // 乘方运算符 ** Pow, // ~ ++ -- += -= *= /= ? : ?? // 返回 Return, // 类型大小 Sizeof, }; // 语义信息 struct SemInfo { double r; int i; string ts; int value; }; // 词法分析的记号 template<typename T> struct PToken { public: PToken() noexcept = default; virtual ~PToken() noexcept = default; constexpr PToken(PToken& token) noexcept = default; constexpr PToken& operator=(PToken& token) noexcept = default; constexpr PToken& operator=(PToken& token) noexcept = default; public: PTokenType type; T value; bool isSingleByteSymbol; private: public: static PTokenType OneChar(int c1); static PTokenType TwoChar(int c1, int c2); static PTokenType ThreeChar(int c1, int c2, int c3); static PTokenType FromChars(int * chars, int n); }; template<typename T> PTokenType PToken<T>::OneChar(int c1) { PTokenType type = PTokenType::None; switch (c1) { case '=': type = PTokenType::Assign; break; default: type = PTokenType::Assign; break; } return type; } template<typename T> PTokenType PToken<T>::TwoChar(int c1, int c2) { return PTokenType::None; } template<typename T> PTokenType PToken<T>::ThreeChar(int c1, int c2, int c3) { return PTokenType::None; } template<typename T> PTokenType PToken<T>::FromChars(int * chars, int n) { PTokenType type = PTokenType::None; switch (n) { case 0: type = PToken<T>::OneChar(chars[0]); break; case 1: type = PToken<T>::TwoChar(chars[0], chars[1]); break; case 2: type = PToken<T>::ThreeChar(chars[0], chars[1], chars[2]); break; default: return PTokenType::None; break; } return type; } using PTokenValue = PToken<SemInfo>; END_PEEFY_NAMESPACE #endif <file_sep>package main type PObject struct { refrence_count uint hashval uint value uint } <file_sep> CC=gcc SRCS=./src/peefyc4/compiler.c SRCS_C4=./third_party/c4/c4.c SRCS_PEEFY=./src/peefycpp/peefy.cpp SRCS_PEEFY_GO=./src/peefygo/peefy.go TESTSRC=./test/test.c OBJS=$(SRCS:.cpp=.o) OBJS_C4=$(SRCS_C4:.cpp=.o) OBJS_PEEFY=$(SRCS_PEEFY:.cpp=.o) EXEC=dugu EXEC_C4=c4 EXEC_PEEFY=peefy all:start run clean peefy:peefyc peefyr start:$(OBJS) $(CC) -o $(EXEC) $(OBJS) c4:$(OBJS_C4) $(CC) -o $(EXEC_C4) $(OBJS_C4) .cpp.o: $(CC) -o $@ -c $< -DMYLINUX .PHONY:clean clean: -rm -rf $(OBJS) run: ./$(EXEC) r: ./$(EXEC) -s-d $(TESTSRC) r4: ./$(EXEC_C4) -s-d $(TESTSRC) peefyc:$(OBJS_PEEFY) g++ -o $(EXEC_PEEFY) $(OBJS_PEEFY) peefyr: ./$(EXEC_PEEFY) peefygo: go run $(SRCS_PEEFY_GO) <file_sep> #include <stdio.h> #include <stdlib.h> #include <memory.h> #include <fcntl.h> #include <stdint.h> #include "../src/type.h" #include "../src/config.h" void test_cmd_para() { } <file_sep> #include "pfa.h" BEGIN_PEEFY_NAMESPACE END_PEEFY_NAMESPACE <file_sep> #include "papi.h" PEEFY_API int peefy_init() { return 0; } <file_sep> #ifndef __P_ERROR_H__ #define __P_ERROR_H__ // peefy 编译器错误处理库 /* * 1. 词法错误 * 2. 语法错误 * 3. 语义错误 * 4. 逻辑错误 */ #include "util.h" BEGIN_PEEFY_NAMESPACE END_PEEFY_NAMESPACE #endif <file_sep> #ifndef __P_EXPR_H__ #define __P_EXPR_H__ // peefy 表达式和文法库 #include "util.h" BEGIN_PEEFY_NAMESPACE END_PEEFY_NAMESPACE #endif <file_sep> #ifndef __P_MATH_H__ #define __P_MATH_H__ // peefy 数学库 #include "util.h" BEGIN_PEEFY_NAMESPACE END_PEEFY_NAMESPACE #endif <file_sep> #ifndef __TYPE_H__ #define __TYPE_H__ typedef struct { int src; // print source and assembly flag int debug; // print executed instructions }cmd_para_t; #endif <file_sep> #include "pidentifier.h" #include <regex> #define IS_ID_START_CHAR(c) (\ (c >= 'a' && c <= 'z')\ || (c >= 'A' && c <= 'Z')\ || c == '_'\ || (c >= 128)) #define IS_ID_CHAR(c) (\ (c >= 'a' && c <= 'z')\ || (c >= 'A' && c <= 'Z')\ || (c >= '0' && c <= '9')\ || c == '_'\ || (c >= 128)) BEGIN_PEEFY_NAMESPACE // 关键字标识符,变量的命名不能与标识符重合 static const char* const keywords[] = { "char", "else", "enum", " if", "int", "return", "sizeof", "while", "for", "do", "switch", "case", "open", "read", "close", "printf", "malloc", "free", "memset", "memcmp", "exit", "void", "main", "var", "auto", "where", "in", "out", "typedef", "typename", "nameof", "string", "float", "double", "uint", "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "float32", "float64" "try", "catch", "throw", "raise", "except", "error", "operator", "nil", "none", "null", "nullptr", "None", "override", "virtual", "async", "await", "export", "import", "do", "repeat", "until", "do", "begin", "end", "goto", "pass", "require", "from", "to", "in", "out", "final", "const", "static", "local" "::", "!=", "==", "<=", ">=", "<<", ">>", "||", "&&" }; // 符号表 END_PEEFY_NAMESPACE <file_sep> #include "pstmt.h" BEGIN_PEEFY_NAMESPACE END_PEEFY_NAMESPACE <file_sep> #ifndef __P_FUNCTION_H__ #define __P_FUNCTION_H__ // peefy 函数库 #include "util.h" BEGIN_PEEFY_NAMESPACE END_PEEFY_NAMESPACE #endif <file_sep> #include "ptoken.h" // token 记号模块
0c18c776835e51c1b0b1198e0a5370c84aaf8e83
[ "Markdown", "Makefile", "C", "Go", "C++" ]
62
C++
Peefy/PeefyCompiler
b54252ad43e8ff7be10f97bda3196137936ba4b6
f769459b0f698403b0538fd46e46a340af0882ae
refs/heads/master
<repo_name>seadiaz/swarm-migration<file_sep>/src/networks/create-network-step.js const logger = require('winston') const highland = require('highland') class CreateNetworkStep { constructor ({docker}) { logger.silly('creating instance of %s', this.constructor.name) this._docker = docker } start (stream) { return stream.consume((err, message, push, next) => { if (err) { return } if (message === highland.nil) { push(null, message) return } this._process(message) .then((value) => { next() logger.info('service %s migrated', message.name) push(null, message) }) .catch((err) => { logger.warn('[create-network-step] network %s warning: %s', message.name, JSON.stringify(err.message), JSON.stringify(err.response.data)) next() }) }) } _process (message) { return new Promise((resolve, reject) => { this._docker.networks.create(message.toSwarm()) .then((value) => { logger.info('[create-network-step] create response:', JSON.stringify(value)) resolve() }) .catch((err) => { reject(err) }) }) } } module.exports = CreateNetworkStep <file_sep>/src/services/domain/restart-policy.js const logger = require('winston') const _ = require('lodash') class RestartPolicy { constructor () { logger.silly('creating instance of %s', this.constructor.name) this.condition = '' this.delay = 0 this.maxAttempts = 0 } static fromSwarm (obj) { let response = new this() response.condition = _.get(obj, 'Condition') response.delay = _.get(obj, 'Delay') response.maxAttempts = _.get(obj, 'MaxAttempts') return response } toSwarm () { return { Condition: this.condition, Delay: this.delay, MaxAttempts: this.maxAttempts } } } module.exports = RestartPolicy <file_sep>/src/services/domain/resources.js const logger = require('winston') const _ = require('lodash') const Resource = require('./resource') class Resources { constructor () { logger.silly('creating instance of %s', this.constructor.name) this.limits = new Resource() this.reservations = new Resource() } static fromSwarm (obj) { let response = new this() response.limits = Resource.fromSwarm(_.get(obj, 'Limits')) response.reservations = Resource.fromSwarm(_.get(obj, 'Reservations')) return response } toSwarm () { return { Limits: this.limits.toSwarm(), Reservations: this.reservations.toSwarm() } } } module.exports = Resources <file_sep>/src/services/add-network-map-step.js const logger = require('winston') const _ = require('lodash') class FindNetworkByIdStep { constructor ({origin, destination}) { logger.silly('creating instance of %s', this.constructor.name) this._origin = origin this._destination = destination } start (stream) { return stream.consume((err, item, push, next) => { if (err) { return } this._process(item) .then((value) => { next() _.set(item, '_metadata.networks', value) push(null, item) }) .catch((err) => { logger.warn('[find-network-by-id-step] Service %s warning: %s', item.name, err.message) next() }) }) } _process (item) { return new Promise((resolve, reject) => { Promise.all([ this._getOriginList(), this._getDestinationList() ]) .then((values) => { let response = {} _(values[0]).reject(['Driver', 'host']).reject(['Driver', 'null']).forEach((originNetwork) => { let destinationNetwork = _.find(values[1], ['Name', originNetwork.Name]) if (destinationNetwork) { response[originNetwork.Id] = { type: 'network', name: originNetwork.Name, side: 'origin', peer: destinationNetwork.Id } } }) resolve(response) }) .catch((err) => { reject(err) }) }) } _getOriginList () { return new Promise((resolve, reject) => { if (this._originList) { resolve(this._originList) } this._origin.networks.list() .then((value) => { this._originList = value resolve(value) }) .catch((err) => { logger.error('[add-network-map-step] error getting origin network list') reject(err) }) }) } _getDestinationList () { return new Promise((resolve, reject) => { if (this._destinationList) { resolve(this._destinationList) } this._destination.networks.list() .then((value) => { this._destinationList = value resolve(value) }) .catch((err) => { logger.error('[add-network-map-step] error getting destination network list', err.message) reject(err) }) }) } } module.exports = FindNetworkByIdStep <file_sep>/src/services/domain/replicated.js const logger = require('winston') const _ = require('lodash') class Replicated { constructor () { logger.silly('creating instance of %s', this.constructor.name) this.replicas = 0 } static fromSwarm (obj) { let response = new this() response.replicas = _.get(obj, 'Replicas') return response } toSwarm () { return { Replicas: this.replicas } } } module.exports = Replicated <file_sep>/README.md # Swarm Migration Migrate all services from one swarm cluster to another. This tools was created with the propose to support inmutable server strategy for creation of docker swarm cluster. One way to accomplish is that every change that you need to make, ## Configuration As this tools use node config library you must to have a configuration file located in ./config/default.EXT. As file extension could be many different options I invited you to [see more...](https://github.com/lorenwest/node-config). Yaml configuration file example ```Yaml docker: origin: url: "http://my.docker.tld/path" apiKey: "<KEY>" destination: url: "http://my.docker.tld/path" apiKey: "<KEY>" registry: username: username password: <PASSWORD> serveraddress: "https://my.docker-registry.tld" logging: level: info ``` ## Examples In order to migrate services from one cluster to another you must... ### Migrate networks ### Migrate services ## Roadmap - [x] Use private registry according to image name - [ ] Add support for %HOME/.swamigrc config file <file_sep>/src/index.js #!/usr/bin/env node const yargs = require('yargs') yargs .usage('Usage: $0 <command> [options]') .commandDir('commands') .demand(1) .help() .wrap(yargs.terminalWidth()) .parse() <file_sep>/src/networks/domain/network.js const _ = require('lodash') const IPAM = require('./ipam') class Network { constructor () { this.id = '' this.name = '' this.scope = '' this.driver = '' this.enableIPv6 = false this.ipam = new IPAM() this.internal = false this.attachable = true this.ingress = false this.configFrom = undefined this.configOnly = false this.containers = null this.options = null this.labels = {} } static fromSwarm (obj) { let response = new this() response.id = _.get(obj, 'Id') response.name = _.get(obj, 'Name') response.scope = _.get(obj, 'Scope') response.driver = _.get(obj, 'Driver') response.enableIPv6 = _.get(obj, 'EnableIPv6') response.ipam = IPAM.fromSwarm(_.get(obj, 'IPAM')) response.internal = _.get(obj, 'Internal') response.attachable = _.get(obj, 'Attachable') response.ingress = _.get(obj, 'Ingress') response.configFrom = _.get(obj, 'ConfigFrom') response.configOnly = _.get(obj, 'ConfigOnly') response.containers = _.get(obj, 'Containers') response.options = _.get(obj, 'Options') response.labels = _.get(obj, 'Labels') return response } toSwarm () { return { Id: this.id, Name: this.name, Scope: this.scope, Driver: this.driver, EnableIPv6: this.enableIPv6, IPAM: this.ipam.toSwarm(), Internal: this.internal, Attachable: this.attachable, Ingress: this.ingress, ConfigFrom: this.configFrom, ConfigOnly: this.configOnly, Containers: this.containers, Options: this.options, Labels: this.labels } } } module.exports = Network <file_sep>/src/services/remove-service-step.js const logger = require('winston') const highland = require('highland') const Service = require('./domain/service') class RemoveServiceStep { constructor ({docker}) { logger.silly('creating instance of %s', this.constructor.name) this._docker = docker } start (stream) { return stream.consume((err, message, push, next) => { if (err) { return } if (message === highland.nil) { push(null, message) return } this._process(message) .then(() => { next() push(null, message) }) .catch((err) => { logger.error('[remove-service-step] Service %s warning: %s', message.name, JSON.stringify(err.message)) next() }) }) } _process (message) { return new Promise((resolve, reject) => { this._docker.services.findByName(message.name) .then((value) => { if (!value) { resolve() return } return this._docker.services.delete(Service.fromSwarm(value)) }) .then(() => { logger.info('%s removed!', message.name) resolve() }) .catch((err) => { reject(err) }) }) } } module.exports = RemoveServiceStep <file_sep>/src/services/domain/mode.js const logger = require('winston') const _ = require('lodash') const Replicated = require('./replicated') class Mode { constructor () { logger.silly('creating instance of %s', this.constructor.name) this.replicated = undefined this.global = undefined } static fromSwarm (obj) { let response = new this() if (_.has(obj, 'Replicated')) { response.replicated = Replicated.fromSwarm(_.get(obj, 'Replicated')) } if (_.has(obj, 'Global')) { response.global = {} } return response } toSwarm () { return { Replicated: this.replicated ? this.replicated.toSwarm() : undefined, Global: this.global } } } module.exports = Mode <file_sep>/src/services/domain/network.js const logger = require('winston') const _ = require('lodash') class Network { constructor () { logger.silly('creating instance of %s', this.constructor.name) this.target = '' this.aliases = [] } static fromSwarm (obj) { let response = new this() response.target = _.get(obj, 'Target') response.aliases = _.get(obj, 'Aliases') return response } toSwarm () { return { Target: this.target, Aliases: this.aliases } } } module.exports = Network <file_sep>/src/networks/domain/ipam.js const _ = require('lodash') class IPAM { constructor () { this.driver = '' this.options = '' this.config = '' } static fromSwarm (obj) { let response = new this() response.driver = _.get(obj, 'Driver') response.options = _.get(obj, 'Options') response.config = _.get(obj, 'Config') return response } toSwarm () { return {} } } module.exports = IPAM <file_sep>/src/services/domain/mounts.js const logger = require('winston') const BindOptions = require('./bind-options') class Mounts { constructor () { logger.silly('creating instance of %s', this.constructor.name) this.target = '' this.source = '' this.type = '' this.readOnly = false this.bindOptions = new BindOptions() } } module.exports = Mounts <file_sep>/src/services/domain/log-driver.js const logger = require('winston') const _ = require('lodash') class LogDriver { constructor () { logger.silly('creating instance of %s', this.constructor.name) this.name = '' this.options = {} } static fromSwarm (obj) { let response = new this() response.name = _.get(obj, 'Name') response.options = _.get(obj, 'Options') return response } toSwarm () { return { Name: this.name, Options: this.options } } } module.exports = LogDriver <file_sep>/src/services/find-services-step.js const logger = require('winston') const _ = require('lodash') const highland = require('highland') const Service = require('./domain/service') class FindServicesStep { constructor ({docker}) { logger.silly('creating instance of %s', this.constructor.name) this._docker = docker } start (stream) { return stream.consume((err, message, push, next) => { if (err) { return } if (message === highland.nil) { push(null, message) return } this._process() .then((value) => { _.forEach(value, (item) => { push(null, Service.fromSwarm(item)) }) next() }) .catch((err) => { logger.warn('warning: %s', err) next() }) }) } _process () { return new Promise((resolve, reject) => { this._docker.services.list() .then((value) => { resolve(value) }) .catch((err) => { reject(err) }) }) } } module.exports = FindServicesStep <file_sep>/src/services/filter-step.js const logger = require('winston') class FilterStep { constructor ({includes}) { logger.silly('creating instance of %s', this.constructor.name) this._includes = new RegExp(includes) } start (stream) { return stream.consume((err, message, push, next) => { if (err) { return } this._process(message) .then(() => { next() push(null, message) }) .catch((err) => { logger.debug('[filter-step] Service %s warning: %s', message.name, err.message) next() }) }) } _process (message) { return new Promise((resolve, reject) => { if (!this._includes.test(message.name)) { reject(new Error('service filtered')) return } logger.info('%s included!', message.name) resolve() }) } } module.exports = FilterStep <file_sep>/src/services/domain/service.js const _ = require('lodash') const logger = require('winston') const TaskTemplate = require('./task-template') const UpdateConfig = require('./update-config') const EndpointSpec = require('./endpoint-spec') const RollbackConfig = require('./rollback-config') const Mode = require('./mode') class Service { constructor () { logger.silly('creating instance of %s', this.constructor.name) this.id = '' this.name = '' this.labels = {} this.taskTemplate = new TaskTemplate() this.mode = new Mode() this.updateConfig = new UpdateConfig() this.rollbackConfig = new RollbackConfig() this.networks = [] this.endpointSpec = new EndpointSpec() } static fromSwarm (obj) { let response = new this() response.id = _.get(obj, 'ID') response.name = _.get(obj, 'Spec.Name') response.labels = _.get(obj, 'Spec.Labels') response.taskTemplate = TaskTemplate.fromSwarm(_.get(obj, 'Spec.TaskTemplate')) response.updateConfig = UpdateConfig.fromSwarm(_.get(obj, 'Spec.UpdateConfig')) response.rollbackConfig = RollbackConfig.fromSwarm(_.get(obj, 'Spec.RollbackConfig')) response.mode = Mode.fromSwarm(_.get(obj, 'Spec.Mode')) response.networks = _.get(obj, 'Networks') response.endpointSpec = EndpointSpec.fromSwarm(_.get(obj, 'Spec.EndpointSpec')) return response } toSwarm () { return { Name: this.name, Labels: this.labels, TaskTemplate: this.taskTemplate.toSwarm(), UpdateConfig: this.updateConfig.toSwarm(), RollbackConfig: this.rollbackConfig.toSwarm(), Mode: this.mode.toSwarm(), Networks: this.networks, EndpointSpec: this.endpointSpec.toSwarm() } } } module.exports = Service <file_sep>/src/services/domain/resource.js const logger = require('winston') const _ = require('lodash') class Resource { constructor () { logger.silly('creating instance of %s', this.constructor.name) this.memoryBytes = 0 this.nanoCPUs = 0 } static fromSwarm (obj) { let response = new this() response.memoryBytes = _.get(obj, 'MemoryBytes') response.nanoCPUs = _.get(obj, 'NanoCPUs') return response } toSwarm () { return { MemoryBytes: this.memoryBytes, NanoCpUs: this.nanoCPUs } } } module.exports = Resource <file_sep>/src/commands/migrate.js const MigrationServiceExpert = require('../services/migration-service-expert') const MigrationNetworkExpert = require('../networks/migration-network-expert') exports.command = 'migrate <type> [includes]' exports.describe = 'Migrate object from one cluster to another' exports.builder = { type: { default: 'service', choices: ['service', 'network'] }, includes: { default: '.*', type: 'string', description: 'includes only that match the regex' }, replace: { type: 'boolean', description: 'replace if exists' }, dry: { type: 'boolean', description: 'do not create anything, just show output to console' }, 'config-file': { type: 'string', default: './swamig.yaml' } } exports.handler = function (argv) { if (argv.type === 'service') { new MigrationServiceExpert({includes: argv.includes, replace: argv.replace, dry: argv.dry, configFile: argv.configFile}).run() } if (argv.type === 'network') { new MigrationNetworkExpert().run() } } <file_sep>/src/services/domain/bind-options.js const logger = require('winston') class BindOptions { constructor () { logger.silly('creating instance of %s', this.constructor.name) this.propagation = '' } } module.exports = BindOptions <file_sep>/src/networks/find-networks-step.js const logger = require('winston') const _ = require('lodash') const highland = require('highland') const Network = require('./domain/network') class FindNetworksStep { constructor ({docker}) { logger.silly('creating instance of %s', this.constructor.name) this._docker = docker } start (stream) { return stream.consume((err, message, push, next) => { if (err) { return } if (message === highland.nil) { push(null, message) return } this._process() .then((value) => { _.forEach(value, (item) => { push(null, Network.fromSwarm(item)) }) next() }) .catch((err) => { logger.warn('warning: %s', JSON.stringify(err)) next() }) }) } _process () { return new Promise((resolve, reject) => { this._docker.networks.list() .then((value) => { resolve(value) }) .catch((err) => { reject(err) }) }) } } module.exports = FindNetworksStep <file_sep>/src/services/domain/port.js const logger = require('winston') const _ = require('lodash') class Port { constructor () { logger.silly('creating instance of %s', this.constructor.name) this.protocol = '' this.publishedPort = 0 this.targetPort = 0 this.publishMode = undefined } static fromSwarm (obj) { let response = new this() response.protocol = _.get(obj, 'Protocol') response.publishedPort = _.get(obj, 'PublishedPort') response.targetPort = _.get(obj, 'TargetPort') response.publishMode = _.get(obj, 'PublishMode') return response } toSwarm () { return { Protocol: this.protocol, PublishedPort: this.publishedPort, TargetPort: this.targetPort, PublishMode: this.publishMode } } } module.exports = Port <file_sep>/src/services/ignore-service-step.js const logger = require('winston') const highland = require('highland') class IgnoreServiceStep { constructor ({docker}) { logger.silly('creating instance of %s', this.constructor.name) this._docker = docker } start (stream) { return stream.consume((err, message, push, next) => { if (err) { return } if (message === highland.nil) { push(null, message) return } this._process(message) .then(() => { next() push(null, message) }) .catch(() => { next() }) }) } _process (message) { return new Promise((resolve, reject) => { this._docker.services.findByName(message.name) .then((value) => { if (value) { logger.warn('%s ignored!', message.name) reject(new Error()) return } resolve() }) .catch((err) => { reject(err) }) }) } } module.exports = IgnoreServiceStep <file_sep>/src/services/domain/update-config.js const logger = require('winston') const _ = require('lodash') class UpdateConfig { constructor () { logger.silly('creating instance of %s', this.constructor.name) this.parallelism = 0 this.delay = 0 this.failureAction = '' this.monitor = 0 this.maxFailureRatio = 0 this.order = undefined } static fromSwarm (obj) { let response = new this() response.parallelism = _.get(obj, 'Parallelism') response.delay = _.get(obj, 'Delay') response.failureAction = _.get(obj, 'FailureAction') response.monitor = _.get(obj, 'Monitor') response.maxFailureRatio = _.get(obj, 'MaxFailureRatio') response.order = _.get(obj, 'Order') return response } toSwarm () { return { Parallelism: this.parallelism, Delay: this.delay, FailureAction: this.failureAction, Monitor: this.monitor, MaxFailureRatio: this.maxFailureRatio, Order: this.order } } } module.exports = UpdateConfig <file_sep>/src/services/domain/task-template.js const logger = require('winston') const _ = require('lodash') const ContainerSpec = require('./container-spec') const LogDriver = require('./log-driver') const Resources = require('./resources') const RestartPolicy = require('./restart-policy') const Placement = require('./placement') const Network = require('./network') class TaskTemplate { constructor () { logger.silly('creating instance of %s', this.constructor.name) this.containerSpec = new ContainerSpec() this.logDriver = new LogDriver() this.placement = new Placement() this.networks = [] this.forceUpdate = 0 this.resources = new Resources() this.restartPolicy = new RestartPolicy() } static fromSwarm (obj) { let response = new this() response.containerSpec = ContainerSpec.fromSwarm(_.get(obj, 'ContainerSpec')) response.logDriver = LogDriver.fromSwarm(_.get(obj, 'LogDriver')) response.placement = Placement.fromSwarm(_.get(obj, 'Placement')) response.networks = _.map(_.get(obj, 'Networks', []), (item) => { return Network.fromSwarm(item) }) response.forceUpdate = _.get(obj, 'ForceUpdate') response.resources = Resources.fromSwarm(_.get(obj, 'Resources')) response.restartPolicy = RestartPolicy.fromSwarm(_.get(obj, 'RestartPolicy')) return response } toSwarm () { return { ContainerSpec: this.containerSpec.toSwarm(), LogDriver: this.logDriver.toSwarm(), Placement: this.placement.toSwarm(), Networks: _.map(this.networks, (item) => { return item.toSwarm() }), ForceUpdate: this.forceUpdate, Resources: this.resources.toSwarm(), RestartPolicy: this.restartPolicy.toSwarm() } } } module.exports = TaskTemplate <file_sep>/src/services/domain/container-spec.js const _ = require('lodash') const logger = require('winston') const Privileges = require('./privileges') class ContainerSpec { constructor () { logger.silly('creating instance of %s', this.constructor.name) this.image = '' this.command = '' this.args = [] this.env = [] this.dir = '' this.user = '' this.labels = {} this.mounts = [] this.privileges = new Privileges() this.isolation = 'default' } static fromSwarm (obj) { let response = new this() response.image = ContainerSpec._getImageWithoutSHA(obj) response.command = _.get(obj, 'Command') response.args = _.get(obj, 'Args') response.env = _.get(obj, 'Env') response.dir = _.get(obj, 'Dir') response.user = _.get(obj, 'User') response.labels = _.get(obj, 'Labels') response.mounts = _.get(obj, 'Mounts') response.isolation = _.get(obj, 'Isolation') return response } toSwarm () { return { Image: this.image, Command: this.command, Args: this.args, Env: this.env, Dir: this.dir, User: this.user, Labels: this.labels, Mounts: this.mounts, Isolation: this.isolation } } static _getImageWithoutSHA (obj) { return _.get(obj, 'Image').replace(/@.*/, '') } } module.exports = ContainerSpec <file_sep>/src/docker/client.js const logger = require('winston') const axios = require('axios') const Service = require('./service') const Network = require('./network') class Client { constructor ({socketPath, baseURL, apiKey, registries}) { logger.silly('creating instance of %s', this.constructor.name) this._client = axios.create({ socketPath: socketPath, baseURL: baseURL, timeout: 5000, headers: { 'Api-Key': apiKey || 'dummy' } }) this._registries = registries } get services () { if (!this._services) { this._services = new Service(this._client, this._registries) } return this._services } get networks () { if (!this._networks) { this._networks = new Network(this._client) } return this._networks } } module.exports = Client <file_sep>/src/services/domain/privileges.js const logger = require('winston') const _ = require('lodash') class Privileges { constructor () { logger.silly('creating instance of %s', this.constructor.name) this.credentialSpec = null this.seLinuxContext = null } static fromSwarm (obj) { let response = new this() response.credentialSpec = _.get(obj, 'CredentialSpec') response.seLinuxContext = _.get(obj, 'SELinuxContext') return response } } module.exports = Privileges <file_sep>/src/services/migration-service-expert.js const logger = require('winston') const highland = require('highland') const FindServicesStep = require('./find-services-step') const FilterStep = require('./filter-step') const AddNetworkMapStep = require('./add-network-map-step') const RemoveServiceStep = require('./remove-service-step') const IgnoreServiceStep = require('./ignore-service-step') const CreateServiceStep = require('./create-service-step') const DockerClient = require('../docker/client') const Config = require('../config') class MigrationServiceExpert { constructor ({includes, replace, dry, configFile}) { logger.silly('creating instance of %s', this.constructor.name) this._config = Config.fromPath(configFile) this._originDocker = new DockerClient({ baseURL: this._config.get('docker.origin.url'), apiKey: this._config.get('docker.origin.apiKey') }) this._destinationDocker = new DockerClient({ baseURL: this._config.get('docker.destination.url'), apiKey: this._config.get('docker.destination.apiKey'), registries: this._config.get('docker.registries') }) this._includes = includes this._replace = replace this._dry = dry } run () { return new Promise((resolve, reject) => { let inputStream = highland() let outputSream = new FindServicesStep({docker: this._originDocker}).start(inputStream) if (this._includes) { outputSream = new FilterStep({includes: this._includes}).start(outputSream) } outputSream = new AddNetworkMapStep({origin: this._originDocker, destination: this._destinationDocker}).start(outputSream) if (!this._dry) { if (this._replace) { outputSream = new RemoveServiceStep({docker: this._destinationDocker}).start(outputSream) } else { outputSream = new IgnoreServiceStep({docker: this._destinationDocker}).start(outputSream) } outputSream = new CreateServiceStep({docker: this._destinationDocker}).start(outputSream) } else { outputSream = outputSream.consume((err, item, push, next) => { if (err) { return } logger.info('final:', JSON.stringify(item, null, 2)) next() }) } outputSream.resume() inputStream.write() inputStream.write(highland.nil) }) } } module.exports = MigrationServiceExpert
a6effa43e0ad332c2c53d46f602f1a012d84632a
[ "JavaScript", "Markdown" ]
29
JavaScript
seadiaz/swarm-migration
feadb5b50a0f7c75b11b15f88b51b9c3bb420879
09637f64402e4d1f48a722b69a8d2e837e6db95f
refs/heads/master
<file_sep>class Solution { public: int minOperationsMaxProfit(vector<int>& customers, int boardingCost, int runningCost) { int total = 0; for (auto c : customers) { total += c; } int onboard = 0, redundent = 0, maxProfits = 0, temp = 0, order = 0; int round = customers.size(); for (size_t i = 0; i < round; i++) { if (customers[i] + redundent >= 4) { onboard += 4; redundent = total - onboard; } else { onboard += customers[i]; } temp = onboard * boardingCost - (i + 1) * runningCost; if (temp > maxProfits) { maxProfits = temp; order = i + 1; } } while (redundent > 0) { if (redundent < 4) { onboard += redundent; } else { onboard += 4; } round++; temp = onboard * boardingCost - round * runningCost; if (temp > maxProfits) { maxProfits = temp; order = round; } redundent -= 4; } if (order == 0) { return -1; } return order; } };<file_sep>/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* middleNode(ListNode* head) { int size = 0; for (auto curr = head; curr != nullptr; curr = curr->next) { size++; } int middle = size / 2; int cnt = 0; for (auto curr = head; curr != nullptr; curr = curr->next) { if (cnt == middle) { return curr; } cnt++; } return new ListNode(0); } };<file_sep>class Solution { public: string modifyString(string s) { if (s[0] == '?') { if (s[1] == '?') {s[0] = 'a';} int d = 0; do { s[0] = static_cast<char>('a' + d); d++; } while (s[0] == s[1]); } for (size_t i = 1; i < s.size(); i++) { if (s[i] != '?') { continue; } int d = 0; do { s[i] = static_cast<char>('a' + d); d++; } while ((s[i] == s[i-1]) || (s[i] == s[i+1])); } return s; } }; <file_sep>class Solution { public: string transformWords(string s, int idx) { if (s[0] == 'a' || s[0] == 'e' || s[0] == 'i' || s[0] == 'o' || s[0] == 'u'|| s[0] == 'A'|| s[0] == 'E'|| s[0] == 'I'||s[0] == 'O' || s[0] == 'U') { s += "ma"; } else { s = s.substr(1, s.size()-1) + s[0] + "ma"; } for (int j = 0; j < idx; j++) { s += "a"; } return s; } string toGoatLatin(string S) { vector<int> space; string result; int size = S.size(); for (size_t i = 0; i < size; i++) { if (!isalnum(S[i])) { space.push_back(i); } } if (space.size() == 0) { return transformWords(S, 1); } int idx = 1; string temp; for (size_t i = 0; i < space.size(); i++) { if (i == 0) { temp = S.substr(0, space[i]); result += transformWords(temp, idx) + " "; } else { temp = S.substr(space[i-1]+1, space[i] - space[i-1] -1); result += transformWords(temp, idx) + " "; } idx++; temp = ""; } temp = S.substr(space[space.size()-1]+1, size); result += transformWords(temp, idx); return result; } };<file_sep># My LeetCode - ## **Goat Latin (824)** 1. Get the index of space 2. Fetch each word 3. Transform those words in 3 rules 4. Concatenate them **check out the code** [here](https://github.com/ccjameslai/MyLeetCode/blob/master/code/GoatLatin.cpp) - ## **Two Sum (1)** 1. Two for loops to find two elements, which adding these numbers equals the target **check out the code** [here](https://github.com/ccjameslai/MyLeetCode/blob/master/code/TwoSum.cpp) - ## **Replace All ?'s to Avoid Consecutive Repeating Characters (1576)** 1. Check the first char. If it is a question mark and the next char is also a question mark, directly assign to 'a'. 2. If the next char is not a question mark, replace the first char not the same as the next. 3. Do the similiar thing at step 1 and 2. However, there is a little different thing at step 2. It not only checks the next char, but also the previous. **check out the code** [here](https://github.com/ccjameslai/MyLeetCode/blob/master/code/ReplaceQuestionMark.cpp) - ## **Reverse Only Letters (917)** 1. Given a iterator i from head to tail and another iterator j from tail to head. 2. Check if i is larger than j. If it is positive, then stop the iteration. 3. Check if the i_th element of the string is alphabet. If it is negative, then continue the loop. 4. Check if the j_th element of the string is alphabet. If it is negative, then assign the previous index to j. 5. Swap the char of i_th and j_th. **check out the code** [here](https://github.com/ccjameslai/MyLeetCode/blob/master/code/ReverseOnlyLetters.cpp) - ## **Add Two Numbers (2)** 1. Determine the value of l1 and l2. If l1 or l2 is nullptr, the value is 0. 2. Add up l1 and l2 node by node. Be aware of the carry. **check out the code** [here](https://github.com/ccjameslai/MyLeetCode/blob/master/code/AddTwoNumbers.cpp) - ## **Middle of the Linked List (876)** 1. Find the size of the linked list, and calculate the value(index) of the middle. 2. For loop the linked list until the step equals the value(index) of the middle. **check out the code** [here](https://github.com/ccjameslai/MyLeetCode/blob/master/code/MiddleoftheLinkedList.cpp) - ## **Crawler Log Folder (1598)** 1. Increase one step if the string is neither "./" nor "../". 2. Decrease one step if the string is "../". **check out the code** [here](https://github.com/ccjameslai/MyLeetCode/blob/master/code/CrawlerLogFolder.cpp) - ## **Maximum Profit of Operating a Centennial Wheel (1599)** 1. Calculate profit and the number of people who are inlined and record the number of the rest of people for each loop in existed vector length. 2. Add up the profit of the rest of people if they existed. **check out the code** [here](https://github.com/ccjameslai/MyLeetCode/blob/master/code/MaxProfitofWheel.cpp) - ## **Pow(x, n) (50)** - recursive version 1. Set the boundary condition. 2. Split two sub-operation, Pow(x,a) * Pow(x,b) = Pow(x,n). **check out the code** [here](https://github.com/ccjameslai/MyLeetCode/blob/master/code/Pow.cpp) - ## **Teemo Attacking (495)** 1. if the difference between current value and next in the vector is less than the duration, the result is added the difference. 2. if the difference between current value and next in the vector is greater than the duration, the result is added the duration. 3. at last, return the summation of the result and the duration **check out the code** [here](https://github.com/ccjameslai/MyLeetCode/blob/master/code/TeemoAttacking.cpp) - ## **Valid Parentheses (20)** 1. Use stack to store left parentheses. 2. if the stack is empty and right parentheses exist, return false 3. if the stack is not empty but the top of stack can't match the current parentheses, return false. 4. pop out the top item if it matches the current parentheses. 5. finally, if the stack is empty, then return true. **check out the code** [here](https://github.com/ccjameslai/MyLeetCode/blob/master/code/ValidParentheses.cpp) <file_sep>class Solution { public: int minOperations(vector<string>& logs) { int step = 0; for (size_t i = 0; i < logs.size(); i++) { if (logs[i] == "../" && i >= 1) { if (step != 0) { step--; } } else if (logs[i] != "./" && logs[i] != "../") { step++; } } return step; } };<file_sep>class Solution { public: bool isValid(string s) { if (s.size()%2 != 0) { return false; } stack<char> parens; for (auto& p : s) { if (p == '(' || p == '[' || p == '{') { parens.push(p); continue; } if (parens.empty()) return false; if (p == ')' && parens.top() != '(') return false; if (p == ']' && parens.top() != '[') return false; if (p == '}' && parens.top() != '{') return false; parens.pop(); } return parens.empty(); } };<file_sep>class Solution { public: unordered_map<int, double> cache; double myPow(double x, int n) { if (n == 0) return 1; if (n == 1) return x; if (n == 2) return x * x; int a = 0, b = 0; if (n < 0) { x = 1 / x; a = -1 * (n / 2); b = -1 * (n + a); } else { a = n / 2; b = n - a; } auto p = cache.find(n); if (p != end(cache)) return p->second; cache[n] = myPow(x, a) * myPow(x, b); return cache[n]; } };<file_sep>class Solution { public: int findPoisonedDuration(vector<int>& timeSeries, int duration) { if (timeSeries.size() == 0) { return 0; } int init = timeSeries[0]; int diff = 0; int PoisonedDuration = 0; for (int t = 1; t < timeSeries.size(); t++) { diff = timeSeries[t] - init; if (diff < duration) { PoisonedDuration += diff; } else { PoisonedDuration += duration; } init = timeSeries[t]; } return PoisonedDuration + duration; } };<file_sep>class Solution { public: string reverseOnlyLetters(string S) { if (S.size() <= 1) { return S; } size_t j = S.size() - 1; for (size_t i = 0; i < S.size(); i++) { if (i >= j) { break; } if (!isalpha(S[i])) { continue; } while (!isalpha(S[j])) { j--; } swap(S[i], S[j]); j--; } return S; } };<file_sep>/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode* head = new ListNode(0); ListNode* curr = head; int sum = 0, v1 = 0, v2 = 0, temp = 0; while (l1 || l2) { v1 = l1 != nullptr ? l1->val : 0; v2 = l2 != nullptr ? l2->val : 0; sum = v1 + v2 + temp; temp = 0; if (sum >= 10) { sum -= 10; temp = 1; } curr->next = new ListNode(sum); curr = curr->next; if (l1) {l1 = l1->next;} if (l2) {l2 = l2->next;} } if (temp == 1) { curr->next = new ListNode(1);; } return head->next; } };
a28389580ca44d568b5c81965acbe2984124b4de
[ "Markdown", "C++" ]
11
C++
ccjameslai/MyLeetCode
0c7667668238034f40929f1ae767d91f9d4fc03c
1b3f3e6efcb542d97c0994ace37c28f1b20722f8
refs/heads/master
<repo_name>zhenglaizhang/rails-quest<file_sep>/scripts/hello.rb #!/usr/bin/ruby def fact(n) if n == 0 1 else n * fact(n - 1) end end def sum(a, b) a + b end puts fact(ARGV[0].to_i) puts sum(1, 2) puts sum('a', 'b') puts "It is now #{Time.now}" 10.times do puts 'hello world!' end 10.times {puts 'hello world'} # error # print '2+3 is equal to ' + 2 + 3 puts '2+3 is equal to ' + (2 + 3).to_s puts "2+3 is equal to #{2 + 3}" puts (10 / 3) puts (10.to_f / 3.to_f) puts (10.0 / 3) class Pet # attributes attr_accessor :name, :age, :gender, :color def to_s "Pet(name=#{name}, age=#{age}, gender=#{gender}), color=#{color}}" end end class Cat < Pet end class Dog < Pet def bark(i) i.times {puts 'Woof!'} end end class Snake < Pet attr_accessor :length end obj = Dog.new obj.age = 12 puts obj obj.bark(12) # Kernel is a special class (actually, a module—but don’t worry about that until Chapter 6!) whose methods are made available in every class and scope throughout Ruby puts 1.class puts true.class p 'abcD'.swapcase 1.upto(3) {|i| print i} puts 1.downto(-1) {|i| print i} puts 0.step(50, 5) {|i| print i} puts 1.upto(2) {puts 'hello'} puts # todo basic multi line string multi_line = %q{This is multile line end } puts multi_line multi_line = 'THis is another line end' puts multi_line # here document x = <<END_STR first line second line END_STR puts x puts 'abc' * 5 puts 'abc' > 'abd' puts 'x'.ord # sec: regular expression puts 'foo bar foo'.sub('foo', 'bar') puts 'foo bar foo'.gsub('foo', 'bar') # /^../ means “any two characters immediately after the start of a line. puts 'foo bar foo'.sub(/^../, 'hell') puts 'foo bar foo bar'.gsub(/^../, 'hell') puts 'foo bar foo bar'.gsub(/\A../, 'hell') # If you want to anchor to the absolute start or end of a string, you can use \A and \z, respectively, # whereas ^ and $ anchor to the starts and ends of lines within a string 'xyz'.scan(/./) {|letter| puts letter} 'This is a test'.scan(/../) {|x| puts x} 2.times { puts } 'This is a test'.scan(/\w\w/) {|x| puts x} 'The car costs $1000 and the cat costs $10'.scan(/\d+/) {|d| puts d} # build env. require 'rbconfig' include RbConfig puts CONFIG.keys puts CONFIG['host'] puts CONFIG['libdir'] <file_sep>/app/controllers/articles_controller.rb class ArticlesController < ApplicationController # only public methods can be actions for controllers def new end # Rails by default returns 204 No Content response for an action if we don't specify what the response should be def create # render plain: params[:article].inspect # every Rails model can be initialized with its respective attributes, which are automatically mapped to the respective database columns. @article = Article.new(params.require(:article).permit(:title, :text)) @article.save redirect_to @article end end <file_sep>/scripts/vowel_finder.rb class VowlerFinder include Enumerable def initialize(string) @string = string end def each @string.scan(/[aeiou]/) {|vowel| yield vowel} end end vf = VowlerFinder.new('the quick brown for jumped') p vf.inject(:+) <file_sep>/config/routes.rb Rails.application.routes.draw do # create store_index_path & store_index_url accessor methods root 'store#index', as: 'store_index' resources :products # root 'welcome#index' get 'welcome/index' get 'say/hello' resources :articles get 'say/goodbye' # todo where to put root route?? order matters?? # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end <file_sep>/scripts/ts_shoulda.rb require 'test/unit' require 'shoulda' class DemoTest < Test::Unit::TestCase end <file_sep>/scripts/module.rb class Triangle SIDES = 3 def area end end class Square SIDES = 5 def initialize(side_length) @side_length = side_length end def area @side_length * @side_length end end puts "A rectangle has #{Triangle::SIDES} sides" sq = Square.new(3) puts "Area of square=#{sq.area}" puts Math::E puts Math.sin(Math::PI / 6.0) ## sec module p [1, 2, 3, 4].inject(:+) p ('a'..'m').inject(:+) module Summable def sum inject(:+) end end class Array include Summable end class Range include Summable end require_relative 'vowel_finder' class VowlerFinder include Summable end p [1, 2, 3, 4].sum p ('a'..'m').sum <file_sep>/app/controllers/concerns/current_cart.rb module CurrentCart # prevent Rails from ever making it available as an action on the controller private def set_cart @cart = Cart.find(session[:cart_id]) rescue ActiveRecord::RecordNotFound @cart = Cart.create session[:cart_id] = @cart.id end end # todo https://signalvnoise.com/posts/3372-put-chubby-models-on-a-diet-with-concerns # share common code among controllers <file_sep>/scripts/Rakefile def delete(patten) files = Dir[patten] rm(files, verbose: true) unless files.empty? end desc 'Remove files whose names end with a tilde' task :delete_unix_backups do delete '*~' end desc 'Remove files with a .bak extension' task :delete_windows_backups do delete '*.bak' end desc 'Remove Unix & Windows backup files' task :delete_backups => [:delete_unix_backups, :delete_windows_backups] do puts 'All backups deleted' end <file_sep>/scripts/tests.rb require 'test/unit' class DemoTest < Test::Unit::TestCase def test_simple assert_equal('i', 'i') assert_equal(1, 1) end end <file_sep>/scripts/meta.rb # todo https://www.toptal.com/ruby/ruby-metaprogramming-cooler-than-it-sounds class Developer p self # class method def self.backend # Inside class methods, self refers to the class itself 'I am a backend developer' end # instance method def frontend 'I am a frontend developer' self end end # class Developer is actually an object # Developer is an instance, it is an instance of class Class # see https://uploads.toptal.io/blog/image/91785/toptal-blog-image-1446120487914-384fae8f419347d455a43dab6e20cf25.jpg p Developer.class # Class p Class.superclass # Module p Module.superclass # Object p Object.superclass # BasicObject Developer.new.frontend # Every piece of code executed in Ruby is executed against a particular self. When the Ruby interpreter executes any code it always keeps track of the value self for any given line. self is always referring to some object but that object can change based on the code executed. For example, inside a class definition, the self refers to the class itself which is an instance of class Class. # Every object in Ruby has its own metaclass also known as singleton class and eigenclass. Class method frontend that we defined earlier is nothing but an instance method defined in the metaclass for the object Developer # A metaclass is essentially a class that Ruby creates and inserts into the inheritance hierarchy to hold class methods, thus not interfering with instances that are created from the class. # The difference between class methods and singleton methods is that class methods are available to all instances of a class object while singleton methods are available only to that single instance ex = 'a string obj' def ex.something self.upcase end p ex.something # same as: # todo fix it # ex2 = 'another string obj' # class << ex2 # def ex2.anotherthing # self.upcase # end # end # # p ex2.anotherthing <file_sep>/scripts/ts_spec.rb # expectations, not assertions describe 'TennisScorer', 'basic scoring' do let(:ts) {Time.now} before(:each) do puts 'before each' ts.should == 1 end after(:each) do puts 'after each' end it 'should do aaaa' do 1.should == 2 end it 'should do bbbb' do end it 'should do ccc' it 'should do dddd' end <file_sep>/doc/lianji-rails-style.md # 序幕 这份指南旨在提供一系列 Ruby on Rails 4 开发的最佳实践和风格惯例。本指南与社区驱动并制定的 [Ruby 编码风格指南](https://github.com/bbatsov/ruby-style-guide)可以互为补充。 本文中的一些建议只适用于 Rails 4.0+ 版本。 你可以使用 [Transmuter](https://github.com/TechnoGate/transmuter) 来生成本文的 PDF 或 HTML 版本。 本指南同时有以下语言的翻译版: * [英文原版](https://github.com/JuanitoFatas/rails-style-guide/blob/master/README.md) * [繁體中文](https://github.com/JuanitoFatas/rails-style-guide/blob/master/README-zhTW.md) * [日语](https://github.com/satour/rails-style-guide/blob/master/README-jaJA.md) * [俄语](https://github.com/arbox/rails-style-guide/blob/master/README-ruRU.md) * [土耳其语](https://github.com/tolgaavci/rails-style-guide/blob/master/README-trTR.md) # Rails 风格指南 这份 Rails 风格指南推荐的是 Rails 的最佳实践,现实世界中的 Rails 程序员据此可以写出可维护的高质量代码。我们只说实际使用中的用法。指南再好,但里面说的过于理想化结果大家拒绝使用或者可能根本没人用,又有何意义。 本指南分为几个小节,每一小节由几条相关的规则构成。我尽力在每条规则后面说明理由(如果省略了说明,那是因为其理由显而易见)。 这些规则不是我凭空想象出来的——它们中的绝大部分来自我多年以来作为职业软件工程师的经验,来自 Rails 社区成员的反馈和建议,以及许多备受推崇的 Rails 编程资源。 ## 目录 * [配置](#配置) * [路由](#路由) * [控制器](#控制器) * [模型](#模型) * [ActiveRecord](#activerecord) * [ActiveRecord 查询](#activerecord-查询) * [迁移](#迁移) * [视图](#视图) * [国际化](#国际化) * [Assets](#assets) * [Mailers](#mailers) * [Time](#time) * [Bundler](#bundler) * [有缺陷的 Gem](#有缺陷的-gem) * [进程管理](#进程管理) ## 配置 * 自定义的初始化代码应放在 `config/initializers` 目录下。 Initializers 目录中的代码在应用启动时被执行。 * 每个 gem 的初始化代码应放在单独的文件中,并且文件名应与 gem 的名称相同。例如: `carrierwave.rb`, `active_admin.rb`。 * 相应地调整开发环境、测试环境及生产环境的配置(修改 `config/environments/` 目录下对应的文件) * 添加需要预编译的额外静态资源文件(如果有的话): ```Ruby # config/environments/production.rb # 预编译额外的静态资源文件(application.js, application.css, 以及所有已经被加入的非 JS 或 CSS 的文件) config.assets.precompile += %w( rails_admin/rails_admin.css rails_admin/rails_admin.js ) ``` * 将所有环境下都通用的配置放在 `config/application.rb` 文件中。 * 创建一个与生产环境高度相似的 `staging` 环境。 * 其它配置应保存在 YAML 文件中,存放在 `config/` 目录下。 从 Rails 4.2 开始,可以通过 `config_for` 这个新方法轻松地加载 YAML 配置文件: ```Ruby Rails::Application.config_for(:yaml_file) ``` ## 路由 * 当需要为一个 RESTful 资源添加动作时(你真的需要吗?),应使用 `member` 路由和 `collection` 路由。 ```Ruby # 差 get 'subscriptions/:id/unsubscribe' resources :subscriptions # 好 resources :subscriptions do get 'unsubscribe', on: :member end # 差 get 'photos/search' resources :photos # 好 resources :photos do get 'search', on: :collection end ``` * 当需要定义多个 `member/collection` 路由时,应使用块结构。 ```Ruby resources :subscriptions do member do get 'unsubscribe' # 更多路由 end end resources :photos do collection do get 'search' # 更多路由 end end ``` * 使用嵌套路由(nested routes),它可以更有效地表现 ActiveRecord 模型之间的关系。 ```Ruby class Post < ActiveRecord::Base has_many :comments end class Comments < ActiveRecord::Base belongs_to :post end # routes.rb resources :posts do resources :comments end ``` * 使用命名空间路由来归类相关的动作。 ```Ruby namespace :admin do # 将请求 /admin/products/* 交由 Admin::ProductsController 处理 # (app/controllers/admin/products_controller.rb) resources :products end ``` * 不要使用旧式的控制器路由。这种路由会让控制器的所有动作都通过 GET 请求调用。 ```Ruby # 非常差 match ':controller(/:action(/:id(.:format)))' ``` * 不要使用 `match` 来定义任何路由,除非确实需要将多种请求映射到某个动作,这时可以通过 `via` 选项来指定请求类型,如 `[:get, :post, :patch, :put, :delete]`。 ## 控制器 * 控制器应该保持苗条 ― 它们应该只为视图层提供数据,不应包含任何业务逻辑(所有业务逻辑都应当放在模型里)。 * 每个控制器的动作(理论上)应当只调用一个除了初始的 find 或 new 之外的方法。 * 控制器与视图之间共享不超过两个实例变量。 ## 模型 * 自由地引入不是 ActiveRecord 的模型类。 * 模型的命名应有意义(但简短)且不含缩写。 * 如果需要模型类有与 ActiveRecord 类似的行为(如验证),但又不想有 ActiveRecord 的数据库功能,应使用 [ActiveAttr](https://github.com/cgriego/active_attr) 这个 gem。 ```Ruby class Message include ActiveAttr::Model attribute :name attribute :email attribute :content attribute :priority attr_accessible :name, :email, :content validates_presence_of :name validates_format_of :email, :with => /\A[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}\z/i validates_length_of :content, :maximum => 500 end ``` 更完整的示例请参考 [RailsCast on the subject](http://railscasts.com/episodes/326-activeattr)。 ### ActiveRecord * 避免改动缺省的 ActiveRecord 惯例(表的名字、主键等),除非你有一个充分的理由(比如,不受你控制的数据库)。 ```Ruby # 差 - 如果你能更改数据库的 schema,那就不要这样写 class Transaction < ActiveRecord::Base self.table_name = 'order' ... end ``` * 把宏风格的方法调用(`has_many`, `validates` 等)放在类定义语句的最前面。 ```Ruby class User < ActiveRecord::Base # 默认的 scope 放在最前(如果有的话) default_scope { where(active: true) } # 接下来是常量初始化 COLORS = %w(red green blue) # 然后是 attr 相关的宏 attr_accessor :formatted_date_of_birth attr_accessible :login, :first_name, :last_name, :email, :password # 紧接着是与关联有关的宏 belongs_to :country has_many :authentications, dependent: :destroy # 以及与验证有关的宏 validates :email, presence: true validates :username, presence: true validates :username, uniqueness: { case_sensitive: false } validates :username, format: { with: /\A[A-Za-z][A-Za-z0-9._-]{2,19}\z/ } validates :password, format: { with: /\A\S{8,128}\z/, allow_nil: true} # 下面是回调方法 before_save :cook before_save :update_username_lower # 其它的宏(如 devise)应放在回调方法之后 ... end ``` * `has_many :through` 优于 `has_and_belongs_to_many`。 使用 `has_many :through` 允许 join 模型有附加的属性及验证。 ```Ruby # 不太好 - 使用 has_and_belongs_to_many class User < ActiveRecord::Base has_and_belongs_to_many :groups end class Group < ActiveRecord::Base has_and_belongs_to_many :users end # 更好 - 使用 has_many :through class User < ActiveRecord::Base has_many :memberships has_many :groups, through: :memberships end class Membership < ActiveRecord::Base belongs_to :user belongs_to :group end class Group < ActiveRecord::Base has_many :memberships has_many :users, through: :memberships end ``` * `self[:attribute]` 比 `read_attribute(:attribute)` 更好。 ```Ruby # 差 def amount read_attribute(:amount) * 100 end # 好 def amount self[:amount] * 100 end ``` * `self[:attribute] = value` 优于 `write_attribute(:attribute, value)`。 ```Ruby # 差 def amount write_attribute(:amount, 100) end # 好 def amount self[:amount] = 100 end ``` * 总是使用新式的 ["sexy" 验证](http://thelucid.com/2010/01/08/sexy-validation-in-edge-rails-rails-3/)。 ```Ruby # 差 validates_presence_of :email validates_length_of :email, maximum: 100 # 好 validates :email, presence: true, length: { maximum: 100 } ``` * 当一个自定义的验证规则使用次数超过一次时,或该验证规则是基于正则表达式时,应该创建一个自定义的验证规则文件。 ```Ruby # 差 class Person validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i } end # 好 class EmailValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) record.errors[attribute] << (options[:message] || 'is not a valid email') unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i end end class Person validates :email, email: true end ``` * 自定义验证规则应放在 `app/validators` 目录下。 * 如果你在维护数个相关的应用,或验证规则本身足够通用,可以考虑将自定义的验证规则抽象为一个共用的 gem。 * 自由地使用命名 scope。 ```Ruby class User < ActiveRecord::Base scope :active, -> { where(active: true) } scope :inactive, -> { where(active: false) } scope :with_orders, -> { joins(:orders).select('distinct(users.id)') } end ``` * 当一个由 lambda 和参数定义的命名 scope 太过复杂时, 更好的方式是创建一个具有同样用途并返回 `ActiveRecord::Relation` 对象的类方法。这很可能让 scope 更加精简。 ```Ruby class User < ActiveRecord::Base def self.with_orders joins(:orders).select('distinct(users.id)') end end ``` 注意这种方式不允许命名 scope 那样的链式调用。例如: ```Ruby # 不能链式调用 class User < ActiveRecord::Base def User.old where('age > ?', 80) end def User.heavy where('weight > ?', 200) end end ``` 这种方式下 `old` 和 `heavy` 可以单独工作,但不能执行 `User.old.heavy`。 若要链式调用,请使用下面的代码: ```Ruby # 可以链式调用 class User < ActiveRecord::Base scope :old, -> { where('age > 60') } scope :heavy, -> { where('weight > 200') } end ``` * 注意 [`update_attribute`](http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-update_attribute) 方法的行为。它不运行模型验证(与 `update_attributes` 不同),因此可能弄乱模型的状态。 * 应使用对用户友好的 URL。URL 中应显示模型的一些具有描述性的属性,而不是仅仅显示 `id`。有多种方法可以达到这个目的: * 重写模型的 `to_param` 方法。Rails 使用该方法为对象创建 URL。该方法默认会以字符串形式返回记录的 `id` 项。 可以重写该方法以包含其它可读性强的属性。 ```Ruby class Person def to_param "#{id} #{name}".parameterize end end ``` 为了将结果转换为一个 URL 友好的值,字符串应该调用 `parameterize` 方法。 对象的 `id` 属性值需要位于 URL 的开头,以便使用 ActiveRecord 的 `find` 方法查找对象。 * 使用 `friendly_id` 这个 gem。它允许使用对象的一些描述性属性而非 `id` 来创建可读性强的 URL。 ```Ruby class Person extend FriendlyId friendly_id :name, use: :slugged end ``` 查看 [gem documentation](https://github.com/norman/friendly_id) 以获得更多 `friendly_id` 的使用信息。 * 应使用 `find_each` 来迭代一系列 ActiveRecord 对象。用循环来处理数据库中的记录集(如 `all` 方法)是非常低效率的,因为循环试图一次性得到所有对象。而批处理方法允许一批批地处理记录,因此需要占用的内存大幅减少。 ```Ruby # 差 Person.all.each do |person| person.do_awesome_stuff end Person.where('age > 21').each do |person| person.party_all_night! end # 好 Person.find_each do |person| person.do_awesome_stuff end Person.where('age > 21').find_each do |person| person.party_all_night! end ``` * 因为 [Rails 为有依赖关系的关联添加了回调方法](https://github.com/rails/rails/issues/3458),应总是调用 `before_destroy` 回调方法,调用该方法并启用 `prepend: true` 选项会执行验证。 ```Ruby # 差——即使 super_admin 返回 true,roles 也会自动删除 has_many :roles, dependent: :destroy before_destroy :ensure_deletable def ensure_deletable fail "Cannot delete super admin." if super_admin? end # 好 has_many :roles, dependent: :destroy before_destroy :ensure_deletable, prepend: true def ensure_deletable fail "Cannot delete super admin." if super_admin? end ``` ### ActiveRecord 查询 * 不要在查询中使用字符串插值,它会使你的代码有被 SQL 注入攻击的风险。 ```Ruby # 差——插值的参数不会被转义 Client.where("orders_count = #{params[:orders]}") # 好——参数会被适当转义 Client.where('orders_count = ?', params[:orders]) ``` * 当查询中有超过 1 个占位符时,应考虑使用名称占位符,而非位置占位符。 ```Ruby # 一般般 Client.where( 'created_at >= ? AND created_at <= ?', params[:start_date], params[:end_date] ) # 好 Client.where( 'created_at >= :start_date AND created_at <= :end_date', start_date: params[:start_date], end_date: params[:end_date] ) ``` * 当只需要通过 id 查询单个记录时,优先使用 `find` 而不是 `where`。 ```Ruby # 差 User.where(id: id).take # 好 User.find(id) ``` * 当只需要通过属性查询单个记录时,优先使用 `find_by` 而不是 `where`。 ```Ruby # 差 User.where(first_name: 'Bruce', last_name: 'Wayne').first # 好 User.find_by(first_name: 'Bruce', last_name: 'Wayne') ``` * 当需要处理多条记录时,应使用 `find_each`。 ```Ruby # 差——一次性加载所有记录 # 当 users 表有成千上万条记录时,非常低效 User.all.each do |user| NewsMailer.weekly(user).deliver_now end # 好——分批检索记录 User.find_each do |user| NewsMailer.weekly(user).deliver_now end ``` * `where.not` 比书写 SQL 更好。 ```Ruby # 差 User.where("id != ?", id) # 好 User.where.not(id: id) ``` ## 迁移 * 应使用版本控制工具记录 `schema.rb` (或 `structure.sql` )的变化。 * 应使用 `rake db:scheme:load` 而不是 `rake db:migrate` 来初始化空数据库。 * 应在迁移文件中设置默认值,而不是在应用层面设置。 ```Ruby # 差——在应用中设置默认值 def amount self[:amount] or 0 end ``` 虽然许多 Rails 开发者建议在 Rails 中强制使用表的默认值,但这会使数据受到许多应用 bug 的影响,因而导致应用极其难以维护。考虑到大多数有一定规模的 Rails 应用都与其它应用共享数据库,保持应用的数据完整性几乎是不可能的。 * 务必使用外键约束。在 Rails 4.2 中,ActiveRecord 本身已经支持外键约束。 * 书写建设性的迁移(添加表或列)时,应使用 `change` 方法而不是 `up` 或 `down` 方法。 ```Ruby # 老式写法 class AddNameToPeople < ActiveRecord::Migration def up add_column :people, :name, :string end def down remove_column :people, :name end end # 新式写法(更好) class AddNameToPeople < ActiveRecord::Migration def change add_column :people, :name, :string end end ``` * 不要在迁移中使用模型类。由于模型的变化,模型类也一直处在变化当中,过去运行正常的迁移可能不知什么时候就不能正常进行了。 ## 视图 * 不要直接从视图调用模型层。 * 复杂的格式化不应放在视图中,而应提取为视图 helper 或模型中的方法。 * 应使用 partial 模版与布局来减少代码重复。 ## 国际化 * 不应在视图、模型或控制器里添加语言相关的设置,应在 `config/locales` 目录下进行设置。 * 当 ActiveRecord 模型的标签需要被翻译时,应使用`activerecord` scope: ``` en: activerecord: models: user: Member attributes: user: name: "Full name" ``` 然后 `User.model_name.human` 会返回 "Member" ,而 `User.human_attribute_name("name")` 会返回 "Full name"。这些属性的翻译会作为视图中的标签。 * 把在视图中使用的文字与 ActiveRecord 的属性翻译分开。把模型使用的语言文件放在 `models` 目录下,把视图使用的文字放在 `views` 目录下。 * 当使用额外目录来设置语言文件时,应在 `application.rb` 文件里列出这些目录以加载设置。 ```Ruby # config/application.rb config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')] ``` * 把共享的本地化选项,如日期或货币格式,放在 `locales` 的根目录下。 * 应使用精简形式的 I18n 方法: 使用 `I18n.t` 而非 `I18n.translate`; 使用 `I18n.l` 而非 `I18n.localize`。 * 应使用 "懒惰" 查询来获取视图中使用的文本。假设我们有以下结构: ``` en: users: show: title: "User details page" ``` `users.show.title` 的数值能这样被 `app/views/users/show.html.haml` 获取: ```Ruby = t '.title' ``` * 应在控制器与模型中使用点分隔的键,而非指定 `:scope` 选项。点分隔的调用更容易阅读,也更易追踪层级关系。 ```Ruby # 差 I18n.t :record_invalid, :scope => [:activerecord, :errors, :messages] # 好 I18n.t 'activerecord.errors.messages.record_invalid' ``` * 更详细的 Rails i18n 信息可以在 [Rails Guides](http://guides.rubyonrails.org/i18n.html) 找到。 ## Assets 应使用 [assets pipeline](http://guides.rubyonrails.org/asset_pipeline.html) 来管理应用的资源结构。 * 自定义的样式表、JavaScript 文件或图片文件,应放在 `app/assets` 目录下。 * 把自己开发但不好归类的库文件,应放在 `lib/assets/` 目录下。 * 第三方代码,如 [jQuery](http://jquery.com/) 或 [bootstrap](http://twitter.github.com/bootstrap/),应放在 `vendor/assets` 目录下。 * 尽可能使用资源的 gem 版。例如: [jquery-rails](https://github.com/rails/jquery-rails), [jquery-ui-rails](https://github.com/joliss/jquery-ui-rails), [bootstrap-sass](https://github.com/thomas-mcdonald/bootstrap-sass), [zurb-foundation](https://github.com/zurb/foundation) ## Mailers * 应将 mailer 命名为 `SomethingMailer`。若没有 Mailer 后缀,不能立即断定它是否为一个 mailer,也不能断定哪个视图与它有关。 * 提供 HTML 与纯文本两份视图模版。 * 在开发环境下应显示发信失败错误。这些错误默认是关闭的。 ```Ruby # config/environments/development.rb config.action_mailer.raise_delivery_errors = true ``` * 在开发环境下使用诸如 [Mailcatcher](https://github.com/sj26/mailcatcher) 的本地 SMTP 服务器。 ```Ruby # config/environments/development.rb config.action_mailer.smtp_settings = { address: 'localhost', port: 1025, # 更多设置 } ``` * 为域名设置默认项。 ```Ruby # config/environments/development.rb config.action_mailer.default_url_options = { host: "#{local_ip}:3000" } # config/environments/production.rb config.action_mailer.default_url_options = { host: 'your_site.com' } # 在 mailer 类中 default_url_options[:host] = 'your_site.com' ``` * 若需要在邮件中添加到网站的超链接,应总是使用 `_url` 方法,而非 `_path` 方法。`_url` 方法产生的超链接包含域名,而 `_path` 方法产生相对链接。 ```Ruby # 差 You can always find more info about this course <%= link_to 'here', course_path(@course) %> # 好 You can always find more info about this course <%= link_to 'here', course_url(@course) %> ``` * 正确地设置寄件人与收件人地址的格式。应使用下列格式: ```Ruby # 在你的 mailer 类中 default from: '<NAME> <<EMAIL>>' ``` * 确保测试环境下的 email 发送方法设置为 `test`: ```Ruby # config/environments/test.rb config.action_mailer.delivery_method = :test ``` * 开发环境和生产环境下的发送方法应设置为 `smtp`: ```Ruby # config/environments/development.rb, config/environments/production.rb config.action_mailer.delivery_method = :smtp ``` * 当发送 HTML 邮件时,所有样式应为行内样式,这是因为某些客户端不能正确显示外部样式。然而,这使得邮件难以维护理并会导致代码重复。有两个类似的 gem 可以转换样式,并将样式放在对应的 html 标签里: [premailer-rails3](https://github.com/fphilipe/premailer-rails3) 和 [roadie](https://github.com/Mange/roadie)。 * 避免在产生页面响应的同时发送邮件。若有多个邮件需要发送,这会导致页面加载延迟甚至请求超时。有鉴于此,应使用 [sidekiq](https://github.com/mperham/sidekiq) 这个 gem 在后台发送邮件。 ## Time * 在 `application.rb` 里设置相应的时区。 ```Ruby config.time_zone = 'Eastern European Time' # 可选配置——注意取值只能是 :utc 或 :local 中的一个(默认为 :utc) config.active_record.default_timezone = :local ``` * 不要使用 `Time.parse`。 ```Ruby # 差 Time.parse('2015-03-02 19:05:37') # => 会假设时间是基于操作系统的时区。 # 好 Time.zone.parse('2015-03-02 19:05:37') # => Mon, 02 Mar 2015 19:05:37 EET +02:00 ``` * 不要使用 `Time.now`。 ```Ruby # 差 Time.now # => 无视所配置的时区,返回操作系统时间。 # 好 Time.zone.now # => Fri, 12 Mar 2014 22:04:47 EET +02:00 Time.current # 结果同上,但更简洁 ``` ## Bundler * 只在开发环境或测试环境下使用的 gem 应进行适当的分组。 * 在项目中只使用广为人知的 gem。如果你考虑引入某些鲜为人所知的 gem,应该先仔细检查一下其源代码。 * 关于多个开发者使用不同操作系统的项目,与操作系统有关的 gem 默认情况下会产生经常变动的 `Gemfile.lock`。 在 Gemfile 文件里,所有与 OS X 相关的 gem 放在 `darwin` 群组,而所有与 Linux 有关的 gem 应放在 `linux` 群组: ```Ruby # Gemfile group :darwin do gem 'rb-fsevent' gem 'growl' end group :linux do gem 'rb-inotify' end ``` 要在正确的环境下加载合适的 gem,需添加以下代码至 `config/application.rb` : ```Ruby platform = RUBY_PLATFORM.match(/(linux|darwin)/)[0].to_sym Bundler.require(platform) ``` * 不要把 `Gemfile.lock` 文件从版本控制里移除。这可不是一个随机产生的文件——它的目的是确保你所有的团队成员执行 `bundle install` 时,获得相同版本的 gem 。 ## 有缺陷的 Gem 这是一个有问题的或有更好替代物的 gem 列表。不要在项目中使用它们。 * [rmagick](http://rmagick.rubyforge.org/) - 这个 gem 因大量消耗内存而臭名昭著。应使用 [minimagick](https://github.com/probablycorey/mini_magick) 来替代它。 * [autotest](http://www.zenspider.com/ZSS/Products/ZenTest/) - 测试自动化的过时方案,远不及 [guard](https://github.com/guard/guard) 和 [watchr](https://github.com/mynyml/watchr)。 * [rcov](https://github.com/relevance/rcov) - 代码覆盖率工具,不兼容 Ruby 1.9。应使用 [SimpleCov](https://github.com/colszowka/simplecov) 来替代它。 * [therubyracer](https://github.com/cowboyd/therubyracer) - 内存杀手,强烈不建议在生产环境中使用。建议使用 `node.js` 来替代它。 这仍是一个完善中的列表,欢迎添加流行但有缺陷的 gem。 ## 进程管理 * 如果项目依赖各种外界的进程,应使用 [foreman](https://github.com/ddollar/foreman) 来管理它们。 # 延伸阅读 以下是几个极好的讲述 Rails 风格的资源,闲暇时可以考虑延伸阅读: * [The Rails 4 Way](http://www.amazon.com/The-Rails-Addison-Wesley-Professional-Ruby/dp/0321944275) * [Ruby on Rails Guides](http://guides.rubyonrails.org/) * [The RSpec Book](http://pragprog.com/book/achbd/the-rspec-book) * [The Cucumber Book](http://pragprog.com/book/hwcuc/the-cucumber-book) * [Everyday Rails Testing with RSpec](https://leanpub.com/everydayrailsrspec) * [Better Specs for RSpec](http://betterspecs.org) <file_sep>/README.md # Agile Web Development with Rails ### TODOs - code analysis - formatting tool - fix tests - `RDoc` ## Guidelines - Don't Repeat Yourself - Every piece of knowledge must have a single, unambiguous, authoritative representation within a system - Convention over configuration - Consistent code style - Code Analysis tools applied - Property based tests - Cache high-traffic area - Use Cucumber & RSpec(behavior-driven, user stories focused) & TDD to drive better design and code quality - executable specifications - Use RSpec(behavior-driven, user stories focused) & TDD to drive better design and code quality - problem domain => automated acceptance tests => specification for both: documentation + tests ### This README would normally document whatever steps are necessary to get the application up and running. Things you may want to cover: * Ruby version * System dependencies * Configuration * Database creation * Database initialization * How to run the test suite * Services (job queues, cache servers, search engines, etc.) * Deployment instructions * ... ### Run & Test ```shell bin/rails seed bin/rails test bin/rails server # browse http://localhost:3000/ ``` ### Development ```shell # new controller bin/rails generate controller Welcome index # new resources # update config/routes.rb with `resources` DSL bin/rails routes # generate related controller bin/rails generate controller Articles # new model bin/rails generate model Article title:string text:text # run migration bin/rails db:migrate bin/rails db:migrate RAILS_ENV=production # new scaffold bin/rails generate scaffold Product title:string description:text image_url:string price:decimal # enable development mode cache bin/rails dev:cache ``` ### Environment (ARCH Linux) ```shell pac ruby sqlite3 nodejs ruby -v sqlite3 --version gem install rails rails --version # rails new rails-quest ``` ## Study Plan - [ ] ruby culture - [ ] pure ruby - [ ] ruby tooling (`irb`, `ruby`) - [ ] functional ruby - [ ] functional ruby ## How to learn Ruby - `irb` ### Doc ```shell export RI="--format ansi --width 70" ri GC ri GC::eanble ri assoc ``` ### Rake > https://martinfowler.com/articles/rake.html ```shell cd scripts rake delete_backups rake -T ``` ### Basic Testing ```shell gem install rspec cucumber shoulda rspec ts_spec.rb ``` <file_sep>/doc/lianji-git-style.md # 联极Git 风格指南 ## Host * 统一采用[Bitbucket](https://bitbucket.org)来管理代码,它提供了一个高可靠且私密的基于git协议的代码管理服务。 ## Branches * 选择*简短*和*具有描述性*的名字来命名分支: ```shell # 好 $ git checkout -b oauth-migration # 不好,过于模糊 $ git checkout -b login_fix ``` * 来自外部的标识符也适合用作分支的名字,例如来自 github/bitbucket 的 Issue 序号。 * 用破折号分割单词。 * 当不同的人围绕同一个特性开发时,维护整个团队的特性分支与每个人的独立分支是比较方便的做法。使用如下的命名方式: ```shell $ git checkout -b f-a/master # team-wide branch $ git checkout -b f-a/maria # Maria's branch $ git checkout -b f-a/nick # Nick's branch ``` ## Commits * 每个提交应当只包含一个简单的逻辑改动,不要在一个提交里包含多个逻辑改动。比如,如果一个补丁修复了一个 Bug,又优化了一个特性的性能,就将其拆分。 * 不要将一个逻辑改动拆分提交。例如一个功能的实现及其对应的测试应当一并提交。 * 尽早、尽快提交。出问题时,短小、完整的提交更容易发现并修正。 * 提交应当依*逻辑*排序。例如,如果 X 提交依赖于 Y,那么 Y 提交应该在 X 前面。 * 擅用`git squash`和`git rebase`确保git提交历史记录干净整齐可追述 ## Merging * **不要篡改提交历史.**仓库的历史本身就很宝贵,重要的是它能够还原*实际发生了什么*。对任何参与项目的人来说,修改历史是万恶之源。 * 尽管如此,有些时候还是可以重写历史,例如: * 你一个人孤军奋战,而且你的代码不会被人看到。 * 你希望整理分支(例如使用 squash),以便日后合并。 最重要的,*不要重写你的 master 分支历史* 或者任何有特殊意义的分支(例如发布分支或 CI 分支)。 * 保持你的提交历史*干净*、*简单*。*在你 merge* 你的分支之前: 1. 确保它符合风格指南,如果不符合就执行相应操作,比如 squash 或重写提交信息。 2. 将其 rebase 到目标分支: ```shell [my-branch] $ git fetch [my-branch] $ git rebase origin/master # then merge ``` 这样会在 master 后直接添加一个新版本,令提交历史更简洁。 *(这个策略更适合较短生命周期的分支,否则还是最好经常合并而不是 rebase。)* * 如果你的分支包含多个 commmit , 不要使用快进模式。 ```shell # 好;注意添加合并信息 $ git merge --no-ff my-branch # 不好 $ git merge my-branch ``` ## Misc. * *保持统一*, 这涉及到从工作流到你的提交信息,分支名还有标签。 在整个 Repository 中保持统一的命名风格有助于辨认工作进度。 * *push 前测试*, 不要提交未完成的工作。 * 使用 [annotated tags](http://git-scm.com/book/en/v2/Git-Basics-Tagging#Annotated-Tags) 标记发布版本或者其他重要的时间点。 个人开发可以使用 [lightweight tags](http://git-scm.com/book/en/v2/Git-Basics-Tagging#Lightweight-Tags),例如为以后参考做标记。 * 定期维护,保证你的仓库状态良好,包括本地还有远程的仓库。
ce15f406664f71f85d86776e687fa13ca3fda786
[ "Markdown", "Ruby" ]
14
Ruby
zhenglaizhang/rails-quest
8cb36388996359be5523562526984b290575dfd0
6a8c9fd144df17c29e306ca8e2a13927163f1824
refs/heads/master
<repo_name>ontheplains/Mongoose-Blog<file_sep>/server/api/post/postModel.js // Create a post schema that will have a ref for categories and author ref
be76d7899d517ece24b387bcaee96d192eeaf1a0
[ "JavaScript" ]
1
JavaScript
ontheplains/Mongoose-Blog
284882802795263139c68641735346f198f421e4
611f7365c123c618fc823ce4beff392558853bfc
refs/heads/master
<file_sep>class Player def hand # コンソールを入力待ち状態にし、プレイヤーがコンソールから打ち込んだ値を出力する処理のメソッドの処理をこの中に作成する menu = ["1: グー", "2: チョキ", "3: パー"] menu.each do |m| puts m end player_hand = gets.to_i end end class Enemy def hand # グー、チョキ、パーの値をランダムに出力するメソッドの処理をこの中に作成する enemy_hand = rand(3) end end class Janken def pon(player_hand, enemy_hand) # プレイヤーが打ち込んだ値と、Enemyがランダムに出した値でじゃんけんをさせ、その結果をコンソール上に出力するメソッドをこの中に作成する # その際、あいこもしくはグー、チョキ、パー以外の値入力時には、もう一度ジャンケンをする # 相手がグー、チョキ、パーのうち、何を出したのかも表示させる hands = ["グー", "チョキ", "パー"] if player_hand == 0 || player_hand > hands.length puts "無効な値です。もう1回!" Janken.new.pon(Player.new.hand, Enemy.new.hand) elsif (player_hand - 1 - enemy_hand + 3) % 3 == 2 puts "相手の手は#{hands[enemy_hand]}です。あなたの勝ちです" elsif (player_hand - 1 - enemy_hand + 3) % 3 == 1 puts "相手の手は#{hands[enemy_hand]}です。あなたの負けです" elsif (player_hand - 1 - enemy_hand + 3) % 3 == 0 puts "あいこで" Janken.new.pon(Player.new.hand, Enemy.new.hand) end end end player = Player.new enemy = Enemy.new janken = Janken.new puts "じゃんけんゲームです(^ ^)\n数字を入力して下さい。" # 下記の記述で、ジャンケンメソッドが起動される janken.pon(player.hand, enemy.hand) # hands = ["グー", "チョキ", "パー"] # while true # menu = ["数字を入力してください", "0: グー", "1: チョキ", "2: パー"] # menu.each do |m| # puts m # end # player_hand = gets.to_i # enemy_hand = rand(hands.length) # if player_hand > hands.length # puts "無効な数字です。もう1回" # elsif (player_hand - enemy_hand + 3) % 3 == 2 # break judge = "勝ち" # elsif (player_hand - enemy_hand + 3) % 3 == 1 # break judge = "負け" # elsif (player_hand - enemy_hand + 3) % 3 == 0 # puts "あいこで" # end # end # puts "相手の手は#{hands[enemy_hand]}です。あなたの#{judge}です"
d23bf087f8895b25e2ca4858173f7b3733bd7e02
[ "Ruby" ]
1
Ruby
Romu-Muroga/janken
5105e5e3549b4f0ebd205f9ea920bef3046cd688
1c5af583485a4e7684353237a25f2564061e3f56
refs/heads/master
<file_sep># springboot-dubbo-demo (1)dubbo-provider,dubbo-consumer,dubbo-interface是被测工程,是一个整体。 (2)dubbo-test是对(1)中的工程进行测试的demo。 <file_sep> server.port=8331 spring.dubbo.application.name=dubbo-test spring.dubbo.application.registry=zookeeper://127.0.0.1:2181 <file_sep>package com.dubbo.order_service; import com.alibaba.dubbo.config.annotation.Reference; import com.alibaba.dubbo.spring.boot.annotation.EnableDubboConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.testng.Assert; import org.testng.annotations.Test; import top.snailclimb.service.OrderService; import top.snailclimb.vo.OrderVO; @SpringBootApplication @EnableDubboConfiguration public class QueryOrder1 extends UpdateOrder { @Reference private OrderService orderService; @Test(description = "正常场景:传入正确的orderId,调用接口,返回OrderInfo,检查返回字段") public void queryOrderByCorrectId(){ OrderVO result = orderService.queryOrder(1l); Assert.assertEquals(result.getCustomerAddress().toString(),"武汉市"); Assert.assertEquals(result.getCustomerName().toString(),"张三"); Assert.assertEquals(result.getOrderId().toString(),"1"); } @Test(description = "异常场景:传入非法的orderId,调用接口,返回errorCode") public void queryOrderByValidId(){ OrderVO result = orderService.queryOrder(-1l); System.out.println("Response result is:" + result.getCustomerAddress().toString()); Assert.assertNull(result.getCustomerAddress()); } } <file_sep>package top.snailclimb.service.impl; import com.alibaba.dubbo.common.utils.Assert; import com.alibaba.dubbo.config.annotation.Service; import org.springframework.stereotype.Component; import top.snailclimb.service.OrderService; import top.snailclimb.vo.OrderVO; @Component @Service public class OrderServiceImpl implements OrderService { @Override public OrderVO queryOrder(Long orderId) { Assert.notNull(orderId, "orderId can not be null"); OrderVO orderVO = new OrderVO(); orderVO.setOrderId(orderId); orderVO.setOrderSn("201912150001"); orderVO.setAmount(1000L); orderVO.setCustomerName("张三"); orderVO.setCustomerPhone("135456789xx"); orderVO.setCustomerAddress("武汉市"); return orderVO; } @Override public String orderQuery(String id) { return "OrderInfo" + id; } } <file_sep>package com.dubbo.util; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; public class WorkBookEhi { /** * 创建 workbook * * @param filePath excel文件路径 * @return Workbook 对象 * @throws IOException */ public static Workbook getWorkbook(String filePath) { Workbook wb = null; try { if (filePath.endsWith(".xls")) { File file = new File(filePath); InputStream is = new FileInputStream(file); wb = new HSSFWorkbook(is); } else if (filePath.endsWith(".xlsx") || filePath.endsWith(".xlsm")) { wb = new XSSFWorkbook(filePath); } } catch (IOException e) { e.printStackTrace(); } return wb; } } <file_sep>package com.dubbo.util; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import java.util.ArrayList; import java.util.HashMap; public class ReadExcel { /** * @param file 读取某个excel文件 * @return Object */ public Object[][] testData(String file) { ArrayList<String> arrkey = new ArrayList<String>(); Workbook workbook = WorkBookEhi.getWorkbook(file); Sheet sheet = workbook.getSheetAt(0); // 获取总行数 int rowTotalNum = sheet.getLastRowNum()+1; // 总列数 int columns = sheet.getRow(0).getPhysicalNumberOfCells(); HashMap<String, String>[][] map = new HashMap[rowTotalNum - 1][1]; // 对数组中所有元素hashmap进行初始化 if (rowTotalNum > 1) { for (int i = 0; i < rowTotalNum - 1; i++) { map[i][0] = new HashMap(); } } else { System.out.println("测试的Excel" + file + "中没有数据"); } // 获得首行的列名,作为hashmap的key值 for (int c = 0; c < columns; c++) { String cellvalue = CellUnit.getCellValue(sheet, 0, c); arrkey.add(cellvalue); } // 遍历所有的单元格的值添加到hashmap中 for (int r = 1; r < rowTotalNum; r++) { for (int c = 0; c < columns; c++) { String cellvalue = CellUnit.getCellValue(sheet, r, c); map[r - 1][0].put(arrkey.get(c), cellvalue); } } return map; } }
79d7dfc10941deeb56605bf1d8a4333cf2ace6d5
[ "Markdown", "Java", "INI" ]
6
Markdown
pingchen001/springboot-dubbo-demo
34dd30308be1dd2005a30668ae767da1f46e2fda
d282476fcf0befbcb12b59f65fc133d9eee1c08b
refs/heads/master
<repo_name>digitalepidemiologylab/global-commons<file_sep>/map/unit.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package map; import java.awt.Graphics; import java.awt.Point; /** * Interface for a generic object on a map * @author toddbodnar */ public interface unit { public unit copy(); public void setLocation(Point p); public Point getLocation(); public void draw(Graphics g); public void draw(Graphics g, int width, int height); @Override public boolean equals(Object o); } <file_sep>/Main.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.IOException; import java.util.Vector; import javax.swing.JFrame; import map.*; /** * * @author toddbodnar */ public class Main { public static void main(String args[]) throws InterruptedException, IOException { //default distances, can be replaced in the args float play = 1000.0f, peer = 1000.0f, pool = 1000.0f, learn = 1000.0f; //extra settings: verbose outputs each generation instead of just at the end //graphics displays a window //disable allows the user to disable individual strategies boolean verbose = false, graphics = false, emulate = false, disable[]; disable = new boolean[5]; for(int ct=0;ct<5;ct++) disable[ct]=false; graph g = new graph(); int width = (int)Math.sqrt(settings.population); boolean secondOrder = false; try { if (args.length > 0) { play = Float.parseFloat(args[0]); peer = Float.parseFloat(args[1]); pool = Float.parseFloat(args[2]); learn = Float.parseFloat(args[3]); width = Integer.parseInt(args[4]); secondOrder = Integer.parseInt(args[5]) == 1; String flags = ""; //The rest of the args do not require a certain order for (int ct = 6; ct < args.length; ct++) { flags += args[ct]; } if (flags.contains("v")) verbose = true; if (flags.contains("n")) disable[0] = true; if (flags.contains("d")) disable[1] = true; if (flags.contains("c")) disable[2] = true; if (flags.contains("P")) disable[3] = true; if (flags.contains("p")) disable[4] = true; if (flags.contains("g")) graphics = true; if (flags.contains("e")) emulate = true; } } catch (Exception e) { System.out.println("Error could not format text."); System.out.println("Requires either 0, 1, 6 or 7 args"); System.out.println("\nZero args: \tsets play = 1, peer = 1, pool = 1, learn = 1,\n\t\t width = 10, no second round coop"); System.out.println("1 arg:\tPrints this help info"); System.out.println("6 args:\n\nArg Number\tDescription"); System.out.println("0\t\tPlay distance"); System.out.println("1\t\tPeer Punish distance"); System.out.println("2\t\tPool Punish distance"); System.out.println("3\t\tLearning Distance"); System.out.println("4\t\tWidth/height of the playing field"); System.out.println("5\t\tSet to 1 for second order punishment, otherwise only 1st order"); System.out.println("6\t\tFlags (See below)"); System.out.println("\n\nFlags:"); System.out.println("n\tDisable non-participants"); System.out.println("c\tDisable simple cooperators"); System.out.println("p\tDisable pool punishers"); System.out.println("P\tDisable peer punishers"); System.out.println("d\tDisable defectors"); System.out.println("v\tVerbose mode"); System.out.println("g\tEnable graphics"); System.out.println("e\tRun sims with a given coverage cooeficient"); System.exit(-1); } map world = new gridTorus(width, width); int gamesPerGen = width * width , playersPerMatch = 5; JFrame f = null; if (verbose) { System.out.println(width * width + " players"); System.out.println("Play Distance = " + play); System.out.println("Pool Punish Distance = " + pool); System.out.println("Peer Punish Distance = " + peer); System.out.println("Learn Distance = " + learn); System.out.println("Second Order? " + secondOrder); System.out.println("\nDisable..."); System.out.println("\tNon-Players? " + disable[0]); System.out.println("\tDefectors? " + disable[1]); System.out.println("\tCooperators? " + disable[2]); System.out.println("\tPeer Punishers? " + disable[3]); System.out.println("\tPool Punishers? " + disable[4]); } if (disable[0] && disable[1] && disable[2] && disable[3] && disable[4]) { System.out.println("Error! Cannot Disable All Strategies"); System.exit(-5); } double emuDistance = pool; if(emulate) { pool = 99999; play = 99999; peer = 99999; pggPlayer.B *= emuDistance; pggPlayer.Beta *= emuDistance; pggPlayer.gamma *= emuDistance; } JFrame fr = new JFrame(); fr.add(g); if(graphics) fr.setVisible(true); world.fillAll(new pggPlayer(null, world, pggPlayer.DEF, play, peer, pool, learn, secondOrder)); if (graphics) { if (verbose) { System.out.println("Giving a view window"); } f = new JFrame(); f.add(new mapPanel(world)); f.setVisible(true); f.setSize(400, 400); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Thread.sleep(1000); } //either keep a running total //or the current time step's total (if verbose is on) double no = 0, def = 0, peerc = 0, poolc = 0, coop = 0; long timeStep = 0; for (timeStep = 0; timeStep < settings.ROUNDS; timeStep++) { Vector<unit> v = world.getAllUnits(); // ((pggPlayer)v.firstElement()).strategy=pggPlayer.DEF; //play games for (int ct = 0; ct < gamesPerGen; ct++) { pggPlayer p = (pggPlayer) v.get((int) (Math.random() * v.size())); p.playOnMyCenter(playersPerMatch); } //everyone punishes at the end of the round for (unit u : v) { ((pggPlayer) u).punish(); } Vector<pggPlayer> nextGeneration = new Vector<pggPlayer>(); int thisChange = 0; for (int ct = 0; ct < v.size(); ct++) { pggPlayer parent = (pggPlayer) v.get(ct); pggPlayer child = (pggPlayer) parent.copy(); int bestStrat = parent.getBestOfTwoStrategy(); if (bestStrat != parent.getStrategy()) { thisChange++; } child.setStrategy(bestStrat); child.score = 0; child.playDistance = parent.playDistance; if (settings.random.nextDouble() < settings.mutation) { int newstrat; do { newstrat = settings.random.nextInt(5); } while (disable[newstrat]); child.setStrategy(newstrat); } nextGeneration.add(child); } if (graphics) { f.repaint(0, 0, 9999, 9999); // Thread.sleep(1000); } //replace the current players with the next generation of players for (int ct = 0; ct < nextGeneration.size(); ct++) { world.set(nextGeneration.get(ct)); } v = world.getAllUnits(); if (verbose) { no = def = coop = peerc = poolc = 0; } if (timeStep >= settings.SKIP) { for (int ct = 0; ct < v.size(); ct++) { pggPlayer p = (pggPlayer) v.get(ct); if (p.isNoPlayer()) { no++; } if (p.isDefector()) { def++; } if (p.isSimpleCoop()) { coop++; } if (p.isPeerPunisher()) { peerc++; } if (p.isPoolPunisher()) { poolc++; } } if (verbose) { g.set((int)timeStep, (int)no, (int)coop, (int)def, (int)peerc, (int)poolc); fr.repaint(1000, 0, 0, 1000, 1000); System.out.println(timeStep + "," + play + "," + peer + "," + pool + "," + learn + "," + width * width + "," + secondOrder + "," + 0 + "," + 0 + "," + no + "," + def + "," + coop + "," + peerc + "," + poolc); } } } if (verbose) { System.out.println("Done!"); } else { if(emulate) System.out.println(emuDistance+","+secondOrder +","+no + "," + def + "," + coop + "," + peerc + "," + poolc); else System.out.println(play + "," + peer + "," + pool + "," + learn + "," + width * width + "," + secondOrder + "," + 0 + "," + 0 + "," + no + "," + def + "," + coop + "," + peerc + "," + poolc); } } }
0f831eee9cae023ccf181eebff59afdfa48bf43e
[ "Java" ]
2
Java
digitalepidemiologylab/global-commons
fbba72279abfb8bb1ddc76cad7e97a6ebb755852
3efc0a32bc765193ab52671e4439c115a7cc129a
refs/heads/master
<file_sep>import java.util.Scanner; public class Recursion { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); System.out.println(sumOdds(n)); System.out.println(sumEvens(n)); } //definition of FACTORIAL n*(n-1)*(n-2)*...*1 OR //n!= n*(n-1)! public static int multiply(int n)//this is essentially the count function { if(n==0) { return 0; } else { return 12+multiply(n-1); //multiplier+recursion } //return rooms*students, rooms=12, students=20 //recursion is the thing above, where n=students, and multiplier=rooms //and recursion is calling itself //definition of multiplication of n*x //add n to itself x times} } public static int sumOdds(int n)//GOOD, sumEvens would be switch the things { if(n<=1)//1 is lowest odd, STOPPING CONDITION { return 1;//0 } else if (n%2==1)//n%2==0, RECURSION IF ODD { return n+sumOdds(n-2); } else //if even, RECURSION IF EVEN { return sumOdds(n-1);//does nothing except for make n an odd forever } } public static int sumEvens(int n) { if (n<=2)//2 is lowest even { return 2; } else if (n%2==0) { return n+sumEvens(n-2); } else { return sumEvens(n-1); } } public static int sumEvensAndOdds(int n) { if (n<=2) { return n; } else { return n+sumEvensAndOdds(n-2); } } }<file_sep>public class Unquiz { public static void main(String[] args) { //int[] array = {-1, -2, -3, 4, 5, -6};//should return 3, does //int[] array = {0,1,2,3,4,5,6};//should return 1, does int[] array = {-1,-2,-3,-4,-5,-6};//should return nothing, gives error int i = 0; while (array[i] <=0) { i++; } int location = i; System.out.println(location); } }
7022e5dbbf0f4b19c4752efdd1cf76e0112d2040
[ "Java" ]
2
Java
dnguyen2204/ArrayExamples
c074c807936d054729ef7116bc37fc06781ca668
2822172f77914046f831f64a56a0fde979165522
refs/heads/master
<file_sep>import os import logging import torch import torchvision import torchvision.transforms as transforms def get_logger(log_path): fh = logging.FileHandler(log_path, 'w') fh.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s') ch.setFormatter(formatter) fh.setFormatter(formatter) log = logging.getLogger('logger') log.setLevel(logging.DEBUG) log.addHandler(ch) log.addHandler(fh) return log class AverageMeter(object): def __init__(self): self.reset() @property def avg(self): return self.sum / self.count def reset(self): self.sum = 0 self.count = 0 def update(self, val, n=1): self.sum += val * n self.count += n def make_datasets(batch_size, root='./data'): transform_train = transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)), ]) transform_test = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)), ]) train_dataset = torchvision.datasets.CIFAR10( root=root, train=True, download=True, transform=transform_train) test_dataset = torchvision.datasets.CIFAR10( root=root, train=False, download=True, transform=transform_test) train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=batch_size, shuffle=True, num_workers=2) test_loader = torch.utils.data.DataLoader( test_dataset, batch_size=batch_size, shuffle=False, num_workers=2) return {'train': train_loader, 'test': test_loader} def get_lr(optimizer): for param_group in optimizer.param_groups: return param_group['lr']<file_sep># benchmark-pytorch This is a repository for testing Multi-GPU environments. ## How to run on a single GPU. ```:bash $ cd cifar10 $ python3 single_gpu.py ``` ## How to run distributed training on multi GPUs. 1. Login to the management node as user. ``` $ ssh user@host ``` 2. Clone repository. ``` user@gpu-node:~/workspace$ git clone https://github.com/aizawan/benchmark-pytorch.git ``` 3. Create job scripts of SBATCH. (You need to pull a pytorch image from nvidia gpu cloud in advance.) - Sample script when using all of the available GPUs. ``` #!/bin/bash #SBATCH -p defq #SBATCH -n 1 #SBATCH -J benchmark-cifar10 #SBATCH -o logs/stdout.%J #SBATCH -e logs/stderr.%J docker run --rm --runtime=nvidia --shm-size=32G -v /home/aizawa/workspace:/workspace nvcr.io/nvidia/pytorch:19.10-py3 python /workspace/benchmark-pytorch/cifar10/multi_gpu.py ``` - Sample script when using the manually specified GPUs. ``` #!/bin/bash #SBATCH -p defq #SBATCH -n 1 #SBATCH -J benchmark-cifar10 #SBATCH -o logs/stdout.%J #SBATCH -e logs/stderr.%J docker run --rm --runtime=nvidia -e CUDA_VISIBLE_DEVICES=0,1,3,6,9 --shm-size=32G -v /home/aizawa/workspace:/workspace nvcr.io/nvidia/pytorch:19.10-py3 python /workspace/benchmark-pytorch/cifar10/multi_gpu.py ``` <file_sep>import os import time import argparse import random import logging import numpy as np import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler from torchvision import models import torch.backends.cudnn as cudnn from utils import get_logger, AverageMeter, make_datasets, get_lr seed = 1234 parser = argparse.ArgumentParser(description='PyTorch Benchmarking') parser.add_argument('--prefix', type=str, default='Prefix') parser.add_argument('--model_name', type=str, default='resnet18') parser.add_argument('--pretrained', action='store_true', default=False) parser.add_argument('--lr', default=0.1, type=float) parser.add_argument('--momentum', default=0.9, type=float) parser.add_argument('--batch_size', default=100, type=int) parser.add_argument('--epochs', default=100, type=int) parser.add_argument('--step_size', default=30, type=int) parser.add_argument('--gamma', default=0.1, type=float) args = parser.parse_args() root = 'benchmark-pytorch' classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck') def build_model(model_name, pretrained): model = models.__dict__[model_name](num_classes=10, pretrained=pretrained) return model class Trainer(object): def __init__(self, model, loader, optimizer, criterion, scheduler, device, **kwargs): model = model.to(device) if device == "cuda": model = torch.nn.DataParallel(model) cudnn.benchmark = True self.model = model self.loader = loader self.optimizer = optimizer self.criterion = criterion self.scheduler = scheduler self.device = device self.output_dir = '{}/output/{}-{}-{}'.format( root, args.prefix, self.model.__class__.__name__, os.getpid()) if not os.path.exists(self.output_dir): os.makedirs(self.output_dir) self.logger = get_logger(os.path.join(self.output_dir, 'train.log')) self.logger.info('Build Trainer...') self.logger.info('Available gpu device count: {}'.format(torch.cuda.device_count())) self.logger.info(self.output_dir) self.logger.info('Batch size: {}'.format(loader['train'].batch_size)) self.logger.info('Initial learning rate: {}'.format(optimizer.defaults['lr'])) self.logger.info('Momentum: {}'.format(optimizer.defaults['momentum'])) self.logger.info('Step size: {}'.format(scheduler.step_size)) self.logger.info('Gamma: {}'.format(scheduler.gamma)) def train(self, epochs): best_acc = 0.0 train_acc, train_loss = [], [] test_acc, test_loss = [], [] duration = [] start = time.time() self.logger.info('Start training!') for epoch in range(1, epochs + 1): train_log = self.train_single_step() test_log = self.test() self.scheduler.step(epoch) msg = '[TRAIN {}] Epoch: {}/{}'.format( self.model.__class__.__name__, epoch, epochs) for k, v in train_log.items(): msg += ' - {}: {:.3f}'.format(k, v) self.logger.info(msg) train_acc.append(train_log['accuracy']) train_loss.append(train_log['loss']) duration.append(train_log['duration']) msg = '[TEST {}] Epoch: {}/{}'.format( self.model.__class__.__name__, epoch, epochs) for k, v in test_log.items(): msg += ' - {}: {:.3f}'.format(k, v) self.logger.info(msg) test_acc.append(test_log['accuracy']) test_loss.append(test_log['loss']) if test_log['accuracy'] > best_acc: self.logger.debug('Saving...') state = { 'model': model.state_dict(), 'accuracy': test_log['accuracy'], 'epoch': epoch, } torch.save(state, os.path.join(self.output_dir, 'ckpt.pth')) best_acc = test_log['accuracy'] self.save_logs(train_acc, train_loss, test_acc, test_loss) self.logger.info('Finish training!') self.logger.info('Best test accuracy: {}'.format(best_acc)) self.logger.info('Elapsed time per epoch: {} sec.'.format(np.mean(duration))) self.logger.info('Total training time: {} min.'.format((time.time() - start) / 60.)) def save_logs(self, train_acc, train_loss, test_acc, test_loss): fig = plt.figure() ax1 = fig.add_subplot(211) x = np.arange(len(train_acc)) ax1.plot(x, train_acc, label='Train set') ax1.plot(x, test_acc, label='Test set') ax1.set_xlabel('Epoch') ax1.set_ylabel('Accuracy') ax1.set_title('Accuracy curve.') ax1.legend(loc='best') ax2 = fig.add_subplot(212) ax2.plot(x, train_loss, label='Train set') ax2.plot(x, test_loss, label='Test set') ax2.set_xlabel('Epoch') ax2.set_ylabel('Loss') ax2.set_title('Loss curve.') ax2.legend(loc='best') plt.tight_layout() save_path = os.path.join(self.output_dir, 'training_curve.png') plt.savefig(save_path, transparent=True) np.save(os.path.join(self.output_dir, 'train_acc.npy'), train_acc) np.save(os.path.join(self.output_dir, 'train_loss.npy'), train_loss) np.save(os.path.join(self.output_dir, 'test_acc.npy'), test_acc) np.save(os.path.join(self.output_dir, 'test_loss.npy'), test_loss) def train_single_step(self): running_loss = 0.0 correct = 0 total = 0 duration = [] start = time.time() acc_meter = AverageMeter() loss_meter = AverageMeter() for i, (x, t) in enumerate(self.loader['train']): x, t = x.to(self.device), t.to(self.device) self.optimizer.zero_grad() y = self.model(x) loss = self.criterion(y, t) loss.backward() self.optimizer.step() _, pred = torch.max(y.data, 1) total += t.size(0) correct += (pred == t).sum().item() acc = 100 * correct / total acc_meter.update(acc, t.size(0)) loss_meter.update(loss.item(), t.size(0)) return {'loss': loss_meter.avg, 'accuracy': acc_meter.avg, 'duration': time.time() - start, 'lr': get_lr(self.optimizer)} def test(self): correct = 0 total = 0 acc_meter = AverageMeter() loss_meter = AverageMeter() with torch.no_grad(): for i, (x, t) in enumerate(self.loader['test']): x, t = x.to(self.device), t.to(self.device) y = self.model(x) loss = self.criterion(y, t) _, pred = torch.max(y.data, 1) total += t.size(0) correct += (pred == t).sum().item() acc = 100 * correct / total acc_meter.update(acc, t.size(0)) loss_meter.update(loss.item(), t.size(0)) return {'loss': loss_meter.avg, 'accuracy': acc_meter.avg} if __name__ == '__main__': random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) device = 'cuda' if torch.cuda.is_available() else 'cpu' loader = make_datasets(batch_size=args.batch_size, root=os.path.join(root, 'data')) model = build_model(args.model_name, args.pretrained) criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum) scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=args.step_size, gamma=args.gamma) trainer = Trainer(model, loader, optimizer, criterion, scheduler, device) trainer.train(args.epochs)
88fbbcd31b1702007c732bcd6ebef42d8a1a550d
[ "Markdown", "Python" ]
3
Python
aizawan/benchmark-pytorch
1e979b4f71f3be73ae94fb5592755df95f1a0510
f3c85a46528c6519c9c6fff35b02632211b1b8d5
refs/heads/main
<file_sep>from django.shortcuts import render, get_object_or_404 import requests from .forms import WeatherForm AUTH_TOKEN = "<KEY>" # # res = requests.get('https://ipinfo.io/') # data = res.json() # city = data['city'] # location = data['loc'].split[','] # latitude = location[0] # longitude = location[1] # # print("Latitude: ", latitude) # print("Longitude: ", longitude) # print("City: ", city) # latitude = 54.4609 # longitude = views.py # latitude = 0 # longitude = 0 # #url = 'https://api.openweathermap.org/data/2.5/weather?q=Berlin&APPID=<KEY>' # url = 'https://api.openweathermap.org/data/2.5/weather?lat={}&lon={}&APPID=<KEY>'.format(latitude,longitude) # res = requests.get(url) # data = res.json() # temp_min = data['main']['temp_min'] # temp_max = data['main']['temp_max'] # humidity = data['main']['humidity'] # wind_speed = data['wind']['speed'] # latitude = data['coord']['lat'] # longitude = data['coord']['lon'] # description = data['weather'][0]['description'] # city = data['name'] # # print('Temperature Min : {} degree celcius'.format(temp_min)) # print('Temperature Max : {} degree celcius'.format(temp_max)) # print('Humidity : {}'.format(humidity)) # print('Wind Speed : {} m/s'.format(wind_speed)) # print('Latitude : {}'.format(latitude)) # print('Longitude : {}'.format(longitude)) # print('Description: {}'.format(description)) # print('City: {}'.format(city)) # Create your views here. def weather(request): # url = 'https://api.openweathermap.org/data/2.5/weather?lat={}&lon={}&APPID=<KEY>'.format( # latitude, longitude) # res = requests.get(url) # data = res.json() # temp_min = data['main']['temp_min'] # temp_max = data['main']['temp_max'] # humidity = data['main']['humidity'] # wind_speed = data['wind']['speed'] # latitude = data['coord']['lat'] # longitude = data['coord']['lon'] # description = data['weather'][0]['description'] latitude = 0 longitude = 0 if request.POST: form = WeatherForm(request.POST) if form.is_valid(): latitude = form.cleaned_data['latitude'] longitude = form.cleaned_data['longitude'] url = 'https://api.openweathermap.org/data/2.5/weather?lat={}&lon={}&APPID=<KEY>'.format( latitude, longitude) res = requests.get(url) data = res.json() temp_min = data['main']['temp_min'] temp_max = data['main']['temp_max'] humidity = data['main']['humidity'] wind_speed = data['wind']['speed'] description = data['weather'][0]['description'] city = data['name'] # else: # latitude = 0 # longitude = 0 # temp_min = 0 # temp_max = 0 # humidity = 0 # wind_speed = 0 # description = '' # city = '' form = WeatherForm() return render(request, 'form.html', {'form': form, 'latitude': latitude, 'longitude': longitude, 'temp_min': temp_min, 'temp_max': temp_max, 'humidity': humidity, 'wind_speed': wind_speed, 'description': description, 'city': city}) def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'weatherapp/index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'weatherapp/detail.html', {'question': question}) def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'weatherapp/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('weatherapp:results', args=(question.id,))) def results(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'weatherapp/results.html', {'question': question}) def authenticate(token): if token == AUTH_TOKEN: return True else: return False<file_sep>from django import forms class WeatherForm(forms.Form): latitude = forms.CharField(required=True) longitude = forms.CharField(required=True) # temp_min = forms.IntegerField(required=False) # temp_min = forms.IntegerField(required=False) # humidity = forms.IntegerField(required=False) # wind_speed = forms.IntegerField(required=False) # description = forms.CharField(required=False) # def __init__(self, *args, **kwargs): # super(WeatherForm, self).__init__(*args, **kwargs) # self.fields['latitude'].initial = 0 # self.fields['longitude'].initial = 0
4baefc05a4b92c2347ab1c63bc3000a9d69aff8e
[ "Python" ]
2
Python
cmzcool/Weatherapp
e1a1e925662d8cec53f63c2932beb1b8e356aa45
06666306de2f4ecb07cf9bda5127033410c9ca7c
refs/heads/main
<repo_name>Munther007/Second-task<file_sep>/README.md # Second-task The second task of Yanhad's program <file_sep>/python_pass.py class StringOperations: def __init__(self, to_be_reversed): self.to_be_reversed = to_be_reversed def reverse(self): return self.to_be_reversed[::-1] raise NotImplemented( 'This is the method need to be implemented') class ReveredString(StringOperations): def __init__(self): word = input("Enter any word to reverse it : ") StringOperations.__init__(self, word) ReverseWord = ReveredString() print(ReverseWord.reverse())
5d274e394c092080001d637e22b6618c1ccfeb7e
[ "Markdown", "Python" ]
2
Markdown
Munther007/Second-task
da2ac8349e781b83ddd81fc666a57ee054221ae4
a4fc1f7a0594423caa2b08b980b6d773ba0c32e2
refs/heads/master
<repo_name>elefant/platform_system_nfcd<file_sep>/src/NfcGonkMessage.h /* * Copyright (C) 2013-2014 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef NFC_GONK_MESSAGE_H #define NFC_GONK_MESSAGE_H #ifdef __cplusplus extern "C" { #endif /** * NFC parcel format. * * NFC Request: * 4 bytes of parcel size. (Big-Endian) * 4 byte of request type. Value will be one of NfcRequestType. * (Parcel size - 4) bytes of request data. * * NFC Response: * 4 bytes of parcel size. (Big-Endian) * 4 byte of response type. * 4 bytes of error code. Value will be one of NfcErrorCode. * (Parcel size - 8) bytes of response data. * * NFC Notification: * 4 bytes of parcel size. (Big-endian) * 4 bytes of notification type. Value will one of NfcNotificationType. * (Parcel size - 4) bytes of notification data. * * Except Parcel size is encoded in Big-Endian, other data will be encoded in * Little-Endian. */ /** * Message types sent from NFCC (NFC Controller) */ typedef enum { NFCC_MESSAGE_RESPONSE = 0, NFCC_MESSAGE_NOTIFICATION = 1 } NFCCMessageType; /** * Error code. */ typedef enum { NFC_SUCCESS = 0, NFC_ERROR_IO = -1, NFC_ERROR_CANCELLED = -2, NFC_ERROR_TIMEOUT = -3, NFC_ERROR_BUSY = -4, NFC_ERROR_CONNECT = -5, NFC_ERROR_DISCONNECT = -6, NFC_ERROR_READ = -7, NFC_ERROR_WRITE = -8, NFC_ERROR_INVALID_PARAM = -9, NFC_ERROR_INSUFFICIENT_RESOURCES = -10, NFC_ERROR_SOCKET_CREATION = -11, NFC_ERROR_SOCKET_NOT_CONNECTED = -12, NFC_ERROR_BUFFER_TOO_SMALL = -13, NFC_ERROR_SAP_USED = -14, NFC_ERROR_SERVICE_NAME_USED = -15, NFC_ERROR_SOCKET_OPTIONS = -16, NFC_ERROR_FAIL_ENABLE_DISCOVERY = -17, NFC_ERROR_FAIL_DISABLE_DISCOVERY = -18, NFC_ERROR_NOT_INITIALIZED = -19, NFC_ERROR_INITIALIZE_FAIL = -20, NFC_ERROR_DEINITIALIZE_FAIL = -21, NFC_ERROR_SE_CONNECTED = -22, NFC_ERROR_NO_SE_CONNECTED = -23, NFC_ERROR_NOT_SUPPORTED = -24, NFC_ERROR_BAD_SESSION_ID = -25, NFC_ERROR_LOST_TECH = -26, NFC_ERROR_BAD_TECH_TYPE = -27, NFC_ERROR_SELECT_SE_FAIL = -28, NFC_ERROR_DESELECT_SE_FAIL = -29, NFC_ERROR_FAIL_ENABLE_LOW_POWER_MODE = -30, NFC_ERROR_FAIL_DISABLE_LOW_POWER_MODE = -31, } NfcErrorCode; /** * Power saving mode. */ typedef enum { /** * No action, a no-op to be able to mimic optional parameters once * additional config parameters will be introduced. */ NFC_POWER_NO_OP = -1, /** * Turn off NFC chip */ NFC_POWER_OFF = 0, /** * Request NFC chip to goto low-power mode. */ NFC_POWER_LOW = 1, /** * Request NFC chip to goto full-power mode. */ NFC_POWER_FULL = 2, } NfcPowerLevel; /** * NFC technologies. */ typedef enum { NFC_TECH_UNKNOWN = -1, NFC_TECH_NDEF = 0, NFC_TECH_NDEF_WRITABLE = 1, NFC_TECH_NDEF_FORMATABLE = 2, NFC_TECH_P2P = 3, NFC_TECH_NFCA = 4, NFC_TECH_NFCB = 5, NFC_TECH_NFCF = 6, NFC_TECH_NFCV = 7, NFC_TECH_ISO_DEP = 8, NFC_TECH_MIFARE_CLASSIC = 9, NFC_TECH_MIFARE_ULTRALIGHT = 10, NFC_TECH_BARCODE = 11 } NfcTechnology; /** * NDEF Record * @see NFCForum-TS-NDEF, clause 3.2 */ typedef struct { uint32_t tnf; uint32_t typeLength; uint8_t* type; uint32_t idLength; uint8_t* id; uint32_t payloadLength; uint8_t* payload; } NdefRecordPdu; /** * NDEF Message. */ typedef struct { uint32_t numRecords; NdefRecordPdu* records; } NdefMessagePdu; /** * Session Id. */ typedef uint32_t NfcSessionId; typedef struct { NfcPowerLevel powerLevel; } NfcConfigRequest; typedef struct { /** * possible values are : TODO */ uint32_t status; } NfcConfigResponse; typedef struct { /** * The sessionId must correspond to that of a prior * NfcNotificationTechDiscovered. */ NfcSessionId sessionId; uint8_t technology; } NfcConnectRequest; typedef struct { /** * The sessionId must correspond to that of a prior * NfcNotificationTechDiscovered. */ NfcSessionId sessionId; //TODO Parcel doesn't have API for boolean, should we use bit-wise for this? /** * The NDEF is read-only or not. */ uint8_t isReadOnly; /** * The NDEF can be configured to read-only or not. */ uint8_t canBeMadeReadonly; /** * Maximum length of the NDEF. */ uint32_t maxNdefLength; } NfcGetDetailsResponse; typedef struct { /** * The sessionId must correspond to that of a prior * NfcNotificationTechDiscovered. */ NfcSessionId sessionId; /** * NDEF Message to be transmitted. */ NdefMessagePdu ndef; } NfcNdefReadWritePdu; typedef enum { /** * NFC_REQUEST_CONFIG * * Config NFCD options. * * data is NfcConfigRequest. * * response is NfcConfigResponse. */ NFC_REQUEST_CONFIG = 0, /** * NFC_REQUEST_CONNECT * * Connect to a specific NFC-compatible technology. * * data is NfcConnectRequest. * * response is NULL. */ NFC_REQUEST_CONNECT = 1, /** * NFC_REQUEST_CLOSE * * Close an open connection that must have been opened with a prior * NfcConnectRequest. * * data is NfcSessionId, which is correlates to a technology that was * previously discovered with NFC_NOTIFICATION_TECH_DISCOVERED. * * response is NULL. */ NFC_REQUEST_CLOSE = 2, /** * NFC_REQUEST_GET_DETAILS * * Request the NDEF meta-data. The 'technology' field in * NfcNotificationTechDiscovered must include NFC_TECH_NDEF. * * data is NfcSessionId, which is correlates to a technology that was * previously discovered with NFC_NOTIFICATION_TECH_DISCOVERED. * * respose is NfcGetDetailsResponse. */ NFC_REQUEST_GET_DETAILS = 3, /** * NFC_REQUEST_READ_NDEF * * Request the scanned NDEF message. The 'technology' field in * NfcNotificationTechDiscovered must include NFC_TECH_NDEF. * * data is NfcSessionId, which is correlates to a technology that was * previously discovered with NFC_NOTIFICATION_TECH_DISCOVERED. * * response is NfcNdefReadWritePdu. */ NFC_REQUEST_READ_NDEF = 4, /** * NFC_REQUEST_WRITE_NDEF * * Write a NDEF message. The 'technology' field in * NfcNotificationTechDiscovered must include NFC_TECH_NDEF_WRITABLE or * NFC_TECH_P2P. * * data is NfcNdefReadWritePdu. * * response is NULL. */ NFC_REQUEST_WRITE_NDEF = 5, /** * NFC_REQUEST_MAKE_NDEF_READ_ONLY * * Make the NDEF message is read-only. The 'technology' field in * NfcNotificationTechDiscovered must include NFC_TECH_NDEF_WRITABLE. * * data is NfcSessionId, which is correlates to a technology that was * previously discovered with NFC_NOTIFICATION_TECH_DISCOVERED. * * response is NULL. */ NFC_REQUEST_MAKE_NDEF_READ_ONLY = 6, } NfcRequestType; typedef enum { NFC_RESPONSE_GENERAL = 1000, NFC_RESPONSE_CONFIG = 1001, NFC_RESPONSE_READ_NDEF_DETAILS = 1002, NFC_RESPONSE_READ_NDEF = 1003, } NfcResponseType; typedef struct { uint32_t status; uint32_t majorVersion; uint32_t minorVersion; } NfcNotificationInitialized; typedef struct { NfcSessionId sessionId; uint32_t numOfTechnogies; uint8_t* technology; uint32_t numOfNdefMsgs; NdefMessagePdu* ndef; } NfcNotificationTechDiscovered; typedef enum { NFC_NOTIFICATION_BASE = 1999, /** * NFC_NOTIFICATION_INITIALIZED * * To notify nfcd is initialized after startup. * * data is NfcNotificationInitialized. */ NFC_NOTIFICATION_INITIALIZED = 2000, /** * NFC_NOTIFICATION_TECH_DISCOVERED * * To notify a NFC-compatible technology has been discovered. * * data is NfcNotificationTechDiscovered. */ NFC_NOTIFICATION_TECH_DISCOVERED = 2001, /** * NFC_NOTIFICATION_TECH_LOST * * To notify whenever a NFC-compatible technology is removed from the field of * the NFC reader. * * data is char* sessionId, which is correlates to a technology that was * previously discovered with NFC_NOTIFICATION_TECH_DISCOVERED. */ NFC_NOTIFICATION_TECH_LOST = 2002, /** * NFC_NOTIFICATION_TRANSACTION_EVENT * * To notify a transaction event from secure element. * * data is [origin type][origin index][aid length][aid][payload length][payload] */ NFC_NOTIFICATION_TRANSACTION_EVENT = 2003, } NfcNotificationType; /** * The origin of the transaction event. */ typedef enum { NFC_EVT_TRANSACTION_SIM = 0, NFC_EVT_TRANSACTION_ESE = 1, NFC_EVT_TRANSACTION_ASSD = 2, } NfcEvtTransactionOrigin; #ifdef __cplusplus } #endif #endif // NFC_GONK_MESSAGE_H <file_sep>/src/nci/SecureElement.cpp /* * Copyright (C) 2014 Mozilla Foundation * * 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. */ #include "SecureElement.h" #include "PowerSwitch.h" #include "config.h" #include "NfcUtil.h" #include "DeviceHost.h" #include "NfcManager.h" #undef LOG_TAG #define LOG_TAG "NfcNci" #include <cutils/log.h> SecureElement SecureElement::sSecElem; const char* SecureElement::APP_NAME = "nfc"; SecureElement::SecureElement() : mActiveEeHandle(NFA_HANDLE_INVALID) , mNfaHciHandle(NFA_HANDLE_INVALID) , mIsInit(false) , mActualNumEe(0) , mNumEePresent(0) , mbNewEE(true) // by default we start w/thinking there are new EE , mActiveSeOverride(0) , mIsPiping(false) , mCurrentRouteSelection(NoRoute) , mActivatedInListenMode(false) , mRfFieldIsOn(false) { memset(&mEeInfo, 0, sizeof(mEeInfo)); memset(&mUiccInfo, 0, sizeof(mUiccInfo)); memset(&mLastRfFieldToggle, 0, sizeof(mLastRfFieldToggle)); } SecureElement::~SecureElement() { } SecureElement& SecureElement::getInstance() { return sSecElem; } void SecureElement::setActiveSeOverride(uint8_t activeSeOverride) { ALOGD("%s, seid=0x%X", __FUNCTION__, activeSeOverride); mActiveSeOverride = activeSeOverride; } bool SecureElement::initialize(NfcManager* pNfcManager) { tNFA_STATUS nfaStat; unsigned long num = 0; // active SE, if not set active all SEs. if (GetNumValue("ACTIVE_SE", &num, sizeof(num))) { mActiveSeOverride = num; } ALOGD("%s: Active SE override: 0x%X", __FUNCTION__, mActiveSeOverride); mNfcManager = pNfcManager; mActiveEeHandle = NFA_HANDLE_INVALID; mNfaHciHandle = NFA_HANDLE_INVALID; mActualNumEe = MAX_NUM_EE; mbNewEE = true; mRfFieldIsOn = false; mActivatedInListenMode = false; mCurrentRouteSelection = NoRoute; mNumEePresent = 0; mIsPiping = false; memset(mEeInfo, 0, sizeof(mEeInfo)); memset(&mUiccInfo, 0, sizeof(mUiccInfo)); // Get Fresh EE info. if (!getEeInfo()) { return false; } { SyncEventGuard guard(mEeRegisterEvent); ALOGD("%s: try ee register", __FUNCTION__); nfaStat = NFA_EeRegister(nfaEeCallback); if (nfaStat != NFA_STATUS_OK) { ALOGE("%s: fail ee register; error=0x%X", __FUNCTION__, nfaStat); return false; } mEeRegisterEvent.wait(); } // If the controller has an HCI Network, register for that. for (size_t i = 0; i < mActualNumEe; i++) { if ((mEeInfo[i].num_interface <= 0) || (mEeInfo[i].ee_interface[0] != NCI_NFCEE_INTERFACE_HCI_ACCESS)) { continue; } ALOGD("%s: Found HCI network, try hci register", __FUNCTION__); SyncEventGuard guard(mHciRegisterEvent); nfaStat = NFA_HciRegister(const_cast<char*>(APP_NAME), nfaHciCallback, true); if (nfaStat != NFA_STATUS_OK) { ALOGE("%s: fail hci register; error=0x%X", __FUNCTION__, nfaStat); return false; } mHciRegisterEvent.wait(); break; } mRouteDataSet.initialize(); mRouteDataSet.import(); //read XML file. mIsInit = true; return true; } void SecureElement::finalize() { ALOGD("%s: enter", __FUNCTION__); NFA_EeDeregister(nfaEeCallback); if (mNfaHciHandle != NFA_HANDLE_INVALID) { NFA_HciDeregister(const_cast<char*>(APP_NAME)); } mIsInit = false; mActualNumEe = 0; } bool SecureElement::getEeInfo() { ALOGD("%s: enter; mbNewEE=%d, mActualNumEe=%d", __FUNCTION__, mbNewEE, mActualNumEe); tNFA_STATUS nfaStat = NFA_STATUS_FAILED; if (!mbNewEE) { return (mActualNumEe != 0); } // If mbNewEE is true then there is new EE info. mActualNumEe = MAX_NUM_EE; if ((nfaStat = NFA_EeGetInfo(&mActualNumEe, mEeInfo)) != NFA_STATUS_OK) { ALOGE("%s: fail get info; error=0x%X", __FUNCTION__, nfaStat); mActualNumEe = 0; return false; } mbNewEE = false; ALOGD("%s: num EEs discovered: %u", __FUNCTION__, mActualNumEe); for (uint8_t i = 0; i < mActualNumEe; i++) { if ((mEeInfo[i].num_interface != 0) && (mEeInfo[i].ee_interface[0] != NCI_NFCEE_INTERFACE_HCI_ACCESS)) { mNumEePresent++; } ALOGD("%s: EE[%u] Handle: 0x%04x Status: %s Num I/f: %u: (0x%02x, 0x%02x) Num TLVs: %u", __FUNCTION__, i, mEeInfo[i].ee_handle, eeStatusToString(mEeInfo[i].ee_status), mEeInfo[i].num_interface, mEeInfo[i].ee_interface[0], mEeInfo[i].ee_interface[1], mEeInfo[i].num_tlvs); for (size_t j = 0; j < mEeInfo[i].num_tlvs; j++) { ALOGD("%s: EE[%u] TLV[%u] Tag: 0x%02x Len: %u Values[]: 0x%02x 0x%02x 0x%02x ...", __FUNCTION__, i, j, mEeInfo[i].ee_tlv[j].tag, mEeInfo[i].ee_tlv[j].len, mEeInfo[i].ee_tlv[j].info[0], mEeInfo[i].ee_tlv[j].info[1], mEeInfo[i].ee_tlv[j].info[2]); } } ALOGD("%s: exit; mActualNumEe=%d, mNumEePresent=%d", __FUNCTION__, mActualNumEe, mNumEePresent); return (mActualNumEe != 0); } /** * Computes time difference in milliseconds. */ static uint32_t TimeDiff(timespec start, timespec end) { end.tv_sec -= start.tv_sec; end.tv_nsec -= start.tv_nsec; if (end.tv_nsec < 0) { end.tv_nsec += 10e8; end.tv_sec -=1; } return (end.tv_sec * 1000) + (end.tv_nsec / 10e5); } bool SecureElement::isRfFieldOn() { AutoMutex mutex(mMutex); if (mRfFieldIsOn) { return true; } struct timespec now; int ret = clock_gettime(CLOCK_MONOTONIC, &now); if (ret == -1) { ALOGE("isRfFieldOn(): clock_gettime failed"); return false; } // If it was less than 50ms ago that RF field // was turned off, still return ON. return (TimeDiff(mLastRfFieldToggle, now) < 50); } bool SecureElement::isActivatedInListenMode() { return mActivatedInListenMode; } void SecureElement::getListOfEeHandles(std::vector<uint32_t>& listSe) { ALOGD("%s: enter", __FUNCTION__); if (mNumEePresent == 0 || !mIsInit || !getEeInfo()) { return; } int cnt = 0; for (int i = 0; i < mActualNumEe && cnt < mNumEePresent; i++) { ALOGD("%s: %u = 0x%X", __FUNCTION__, i, mEeInfo[i].ee_handle); if ((mEeInfo[i].num_interface == 0) || (mEeInfo[i].ee_interface[0] == NCI_NFCEE_INTERFACE_HCI_ACCESS)) { continue; } uint32_t handle = mEeInfo[i].ee_handle & ~NFA_HANDLE_GROUP_EE; listSe.push_back(handle); cnt++; } } bool SecureElement::activate() { int numActivatedEe = 0; ALOGD("%s: enter;", __FUNCTION__); if (!mIsInit) { ALOGE("%s: not init", __FUNCTION__); return false; } if (mActiveEeHandle != NFA_HANDLE_INVALID) { ALOGD("%s: already active", __FUNCTION__); return true; } // Get Fresh EE info if needed. if (!getEeInfo()) { ALOGE("%s: no EE info", __FUNCTION__); return false; } uint16_t overrideEeHandle = mActiveSeOverride ? NFA_HANDLE_GROUP_EE | mActiveSeOverride : 0; if (mRfFieldIsOn) { ALOGE("%s: RF field indication still on, resetting", __FUNCTION__); mRfFieldIsOn = false; } ALOGD("%s: override ee h=0x%X", __FUNCTION__, overrideEeHandle); //activate every discovered secure element for (int index = 0; index < mActualNumEe; index++) { tNFA_EE_INFO& eeItem = mEeInfo[index]; if ((eeItem.ee_handle != EE_HANDLE_0xF3) && (eeItem.ee_handle != EE_HANDLE_0xF4) && (eeItem.ee_handle != EE_HANDLE_0x01) && (eeItem.ee_handle != EE_HANDLE_0x02)) { continue; } if (overrideEeHandle != eeItem.ee_handle) { continue; // do not enable all SEs; only the override one } if (eeItem.ee_status != NFC_NFCEE_STATUS_INACTIVE) { ALOGD("%s: h=0x%X already activated", __FUNCTION__, eeItem.ee_handle); numActivatedEe++; continue; } { tNFA_STATUS nfaStat = NFA_STATUS_FAILED; SyncEventGuard guard(mEeSetModeEvent); ALOGD("%s: set EE mode activate; h=0x%X", __FUNCTION__, eeItem.ee_handle); if ((nfaStat = NFA_EeModeSet(eeItem.ee_handle, NFA_EE_MD_ACTIVATE)) == NFA_STATUS_OK) { mEeSetModeEvent.wait(); //wait for NFA_EE_MODE_SET_EVT if (eeItem.ee_status == NFC_NFCEE_STATUS_ACTIVE) { numActivatedEe++; } }else { ALOGE("%s: NFA_EeModeSet failed; error=0x%X", __FUNCTION__, nfaStat); } } //for } mActiveEeHandle = getDefaultEeHandle(); ALOGD("%s: exit; active ee h=0x%X", __FUNCTION__, mActiveEeHandle); return mActiveEeHandle != NFA_HANDLE_INVALID; } bool SecureElement::deactivate() { bool retval = false; ALOGD("%s: enter; mActiveEeHandle=0x%X", __FUNCTION__, mActiveEeHandle); if (!mIsInit) { ALOGE ("%s: not init", __FUNCTION__); return retval; } // if the controller is routing to sec elems or piping, // then the secure element cannot be deactivated if (isBusy()) { ALOGE ("%s: still busy", __FUNCTION__); return retval; } else if (mActiveEeHandle == NFA_HANDLE_INVALID) { ALOGE("%s: invalid EE handle", __FUNCTION__); return retval; } mActiveEeHandle = NFA_HANDLE_INVALID; retval = true; ALOGD("%s: exit; ok=%u", __FUNCTION__, retval); return retval; } void SecureElement::notifyTransactionEvent(const uint8_t* aid, uint32_t aidLen, const uint8_t* payload, uint32_t payloadLen) { if (aidLen == 0) { return; } TransactionEvent* pTransaction = new TransactionEvent(); // TODO: For now, we dodn't have a solution to get aid origin from nfcd. // So use SIM1 as dfault value. pTransaction->originType = TransactionEvent::SIM; pTransaction->originIndex = 1; pTransaction->aidLen = aidLen; pTransaction->aid = new uint8_t[aidLen]; memcpy(pTransaction->aid, aid, aidLen); pTransaction->payloadLen = payloadLen; pTransaction->payload = new uint8_t[payloadLen]; memcpy(pTransaction->payload, payload, payloadLen); mNfcManager->notifyTransactionEvent(pTransaction); } void SecureElement::notifyListenModeState(bool isActivated) { ALOGD("%s: enter; listen mode active=%u", __FUNCTION__, isActivated); // TODO Implement notify. mActivatedInListenMode = isActivated; } void SecureElement::notifyRfFieldEvent(bool isActive) { ALOGD("%s: enter; is active=%u", __FUNCTION__, isActive); // TODO Implement mMutex.lock(); int ret = clock_gettime(CLOCK_MONOTONIC, &mLastRfFieldToggle); if (ret == -1) { ALOGE("%s: clock_gettime failed", __FUNCTION__); // There is no good choice here... } mRfFieldIsOn = isActive; mMutex.unlock(); } void SecureElement::resetRfFieldStatus () { ALOGD ("%s: enter;", __FUNCTION__); mMutex.lock(); mRfFieldIsOn = false; int ret = clock_gettime(CLOCK_MONOTONIC, &mLastRfFieldToggle); if (ret == -1) { ALOGE("%s: clock_gettime failed", __FUNCTION__); // There is no good choice here... } mMutex.unlock(); } void SecureElement::storeUiccInfo (tNFA_EE_DISCOVER_REQ& info) { ALOGD("%s: Status: %u Num EE: %u", __FUNCTION__, info.status, info.num_ee); SyncEventGuard guard(mUiccInfoEvent); memcpy(&mUiccInfo, &info, sizeof(mUiccInfo)); for (uint8_t i = 0; i < info.num_ee; i++) { //for each technology (A, B, F, B'), print the bit field that shows //what protocol(s) is support by that technology ALOGD("%s EE[%u] Handle: 0x%04x techA: 0x%02x techB: 0x%02x techF: 0x%02x techBprime: 0x%02x", __FUNCTION__, i, info.ee_disc_info[i].ee_handle, info.ee_disc_info[i].la_protocol, info.ee_disc_info[i].lb_protocol, info.ee_disc_info[i].lf_protocol, info.ee_disc_info[i].lbp_protocol); } mUiccInfoEvent.notifyOne(); } void SecureElement::adjustRoutes(RouteSelection selection) { ALOGD("%s: enter; selection=%u", __FUNCTION__, selection); mCurrentRouteSelection = selection; adjustProtocolRoutes(selection); adjustTechnologyRoutes(selection); NFA_EeUpdateNow(); //apply new routes now. } void SecureElement::adjustProtocolRoutes(RouteSelection routeSelection) { ALOGD("%s: enter", __FUNCTION__); tNFA_STATUS nfaStat = NFA_STATUS_FAILED; const tNFA_PROTOCOL_MASK protoMask = NFA_PROTOCOL_MASK_ISO_DEP; /** * delete route to host */ { ALOGD("%s: delete route to host", __FUNCTION__); SyncEventGuard guard(mRoutingEvent); if ((nfaStat = NFA_EeSetDefaultProtoRouting(NFA_EE_HANDLE_DH, 0, 0, 0)) == NFA_STATUS_OK) { mRoutingEvent.wait(); } else { ALOGE("%s: fail delete route to host; error=0x%X", __FUNCTION__, nfaStat); } } /** * delete route to every sec elem */ for (int i = 0; i < mActualNumEe; i++) { if ((mEeInfo[i].num_interface != 0) && (mEeInfo[i].ee_interface[0] != NFC_NFCEE_INTERFACE_HCI_ACCESS) && (mEeInfo[i].ee_status == NFA_EE_STATUS_ACTIVE)) { ALOGD("%s: delete route to EE h=0x%X", __FUNCTION__, mEeInfo[i].ee_handle); SyncEventGuard guard(mRoutingEvent); if ((nfaStat = NFA_EeSetDefaultProtoRouting(mEeInfo[i].ee_handle, 0, 0, 0)) == NFA_STATUS_OK) { mRoutingEvent.wait(); } else { ALOGE("%s: fail delete route to EE; error=0x%X", __FUNCTION__, nfaStat); } } } /** * if route database is empty, setup a default route. */ if (true) { tNFA_HANDLE eeHandle = (routeSelection == SecElemRoute) ? mActiveEeHandle : NFA_EE_HANDLE_DH; ALOGD ("%s: route to default EE h=0x%X", __FUNCTION__, eeHandle); SyncEventGuard guard(mRoutingEvent); nfaStat = NFA_EeSetDefaultProtoRouting(eeHandle, protoMask, 0, 0); if (nfaStat == NFA_STATUS_OK) { mRoutingEvent.wait(); } else { ALOGE ("%s: fail route to EE; error=0x%X", __FUNCTION__, nfaStat); } } ALOGD("%s: exit", __FUNCTION__); } void SecureElement::adjustTechnologyRoutes(RouteSelection routeSelection) { ALOGD("%s: enter", __FUNCTION__); tNFA_STATUS nfaStat = NFA_STATUS_FAILED; const tNFA_TECHNOLOGY_MASK techMask = NFA_TECHNOLOGY_MASK_A | NFA_TECHNOLOGY_MASK_B; /** * delete route to host. */ { ALOGD("%s: delete route to host", __FUNCTION__); SyncEventGuard guard(mRoutingEvent); if ((nfaStat = NFA_EeSetDefaultTechRouting(NFA_EE_HANDLE_DH, 0, 0, 0)) == NFA_STATUS_OK) { mRoutingEvent.wait(); } else { ALOGE("%s: fail delete route to host; error=0x%X", __FUNCTION__, nfaStat); } } /** * delete route to every sec elem. */ for (int i = 0; i < mActualNumEe; i++) { if ((mEeInfo[i].num_interface != 0) && (mEeInfo[i].ee_interface[0] != NFC_NFCEE_INTERFACE_HCI_ACCESS) && (mEeInfo[i].ee_status == NFA_EE_STATUS_ACTIVE)) { ALOGD("%s: delete route to EE h=0x%X", __FUNCTION__, mEeInfo[i].ee_handle); SyncEventGuard guard(mRoutingEvent); if ((nfaStat = NFA_EeSetDefaultTechRouting (mEeInfo[i].ee_handle, 0, 0, 0)) == NFA_STATUS_OK) { mRoutingEvent.wait(); } else { ALOGE("%s: fail delete route to EE; error=0x%X", __FUNCTION__, nfaStat); } } } /** * if route database is empty, setup a default route. */ if (true) { tNFA_HANDLE eeHandle = (routeSelection == SecElemRoute) ? mActiveEeHandle : NFA_EE_HANDLE_DH; ALOGD("%s: route to default EE h=0x%X", __FUNCTION__, eeHandle); SyncEventGuard guard(mRoutingEvent); nfaStat = NFA_EeSetDefaultTechRouting(eeHandle, techMask, 0, 0); if (nfaStat == NFA_STATUS_OK) { mRoutingEvent.wait(); } else { ALOGE("%s: fail route to EE; error=0x%X", __FUNCTION__, nfaStat); } } } void SecureElement::nfaEeCallback(tNFA_EE_EVT event, tNFA_EE_CBACK_DATA* eventData) { ALOGD("%s: event=0x%X", __FUNCTION__, event); switch (event) { case NFA_EE_REGISTER_EVT: { SyncEventGuard guard (sSecElem.mEeRegisterEvent); ALOGD("%s: NFA_EE_REGISTER_EVT; status=%u", __FUNCTION__, eventData->ee_register); sSecElem.mEeRegisterEvent.notifyOne(); break; } case NFA_EE_MODE_SET_EVT: { ALOGD ("%s: NFA_EE_MODE_SET_EVT; status: 0x%04X handle: 0x%04X mActiveEeHandle: 0x%04X", __FUNCTION__, eventData->mode_set.status, eventData->mode_set.ee_handle, sSecElem.mActiveEeHandle); if (eventData->mode_set.status == NFA_STATUS_OK) { tNFA_EE_INFO *pEE = sSecElem.findEeByHandle (eventData->mode_set.ee_handle); if (pEE) { pEE->ee_status ^= 1; ALOGD("%s: NFA_EE_MODE_SET_EVT; pEE->ee_status: %s (0x%04x)", __FUNCTION__, SecureElement::eeStatusToString(pEE->ee_status), pEE->ee_status); } else { ALOGE("%s: NFA_EE_MODE_SET_EVT; EE: 0x%04x not found. mActiveEeHandle: 0x%04x", __FUNCTION__, eventData->mode_set.ee_handle, sSecElem.mActiveEeHandle); } } SyncEventGuard guard(sSecElem.mEeSetModeEvent); sSecElem.mEeSetModeEvent.notifyOne(); break; } case NFA_EE_SET_TECH_CFG_EVT: { ALOGD("%s: NFA_EE_SET_TECH_CFG_EVT; status=0x%X", __FUNCTION__, eventData->status); SyncEventGuard guard(sSecElem.mRoutingEvent); sSecElem.mRoutingEvent.notifyOne(); break; } case NFA_EE_SET_PROTO_CFG_EVT: { ALOGD("%s: NFA_EE_SET_PROTO_CFG_EVT; status=0x%X", __FUNCTION__, eventData->status); SyncEventGuard guard(sSecElem.mRoutingEvent); sSecElem.mRoutingEvent.notifyOne(); break; } case NFA_EE_ACTION_EVT: { tNFA_EE_ACTION& action = eventData->action; if (action.trigger == NFC_EE_TRIG_SELECT) { ALOGD("%s: NFA_EE_ACTION_EVT; h=0x%X; trigger=select (0x%X)", __FUNCTION__, action.ee_handle, action.trigger); } break; } case NFA_EE_DISCOVER_REQ_EVT: { ALOGD("%s: NFA_EE_DISCOVER_REQ_EVT; status=0x%X; num ee=%u", __FUNCTION__, eventData->discover_req.status, eventData->discover_req.num_ee); sSecElem.storeUiccInfo(eventData->discover_req); break; } case NFA_EE_NO_CB_ERR_EVT: { ALOGD("%s: NFA_EE_NO_CB_ERR_EVT status=%u", __FUNCTION__, eventData->status); break; } case NFA_EE_ADD_AID_EVT: { ALOGD("%s: NFA_EE_ADD_AID_EVT status=%u", __FUNCTION__, eventData->status); SyncEventGuard guard(sSecElem.mAidAddRemoveEvent); sSecElem.mAidAddRemoveEvent.notifyOne(); break; } case NFA_EE_REMOVE_AID_EVT: { ALOGD("%s: NFA_EE_REMOVE_AID_EVT status=%u", __FUNCTION__, eventData->status); SyncEventGuard guard(sSecElem.mAidAddRemoveEvent); sSecElem.mAidAddRemoveEvent.notifyOne(); break; } case NFA_EE_NEW_EE_EVT: { ALOGD ("%s: NFA_EE_NEW_EE_EVT h=0x%X; status=%u", __FUNCTION__, eventData->new_ee.ee_handle, eventData->new_ee.ee_status); // Indicate there are new EE sSecElem.mbNewEE = true; break; } default: ALOGE("%s: unknown event=%u ????", __FUNCTION__, event); break; } } tNFA_EE_INFO *SecureElement::findEeByHandle(tNFA_HANDLE eeHandle) { for (uint8_t i = 0; i < mActualNumEe; i++) { if (mEeInfo[i].ee_handle == eeHandle) { return &mEeInfo[i]; } } return (NULL); } void SecureElement::nfaHciCallback(tNFA_HCI_EVT event, tNFA_HCI_EVT_DATA* eventData) { ALOGD("%s: event=0x%X", __FUNCTION__, event); switch (event) { case NFA_HCI_REGISTER_EVT: { ALOGD("%s: NFA_HCI_REGISTER_EVT; status=0x%X; handle=0x%X", __FUNCTION__, eventData->hci_register.status, eventData->hci_register.hci_handle); SyncEventGuard guard(sSecElem.mHciRegisterEvent); sSecElem.mNfaHciHandle = eventData->hci_register.hci_handle; sSecElem.mHciRegisterEvent.notifyOne(); break; } case NFA_HCI_EVENT_RCVD_EVT: { ALOGD("%s: NFA_HCI_EVENT_RCVD_EVT; code: 0x%X; pipe: 0x%X; data len: %u", __FUNCTION__, eventData->rcvd_evt.evt_code, eventData->rcvd_evt.pipe, eventData->rcvd_evt.evt_len); if (eventData->rcvd_evt.evt_code == NFA_HCI_EVT_TRANSACTION) { uint8_t aidLen = 0; uint8_t payloadLen = 0; ALOGD ("%s: NFA_HCI_EVENT_RCVD_EVT; NFA_HCI_EVT_TRANSACTION", __FUNCTION__); // If we got an AID, notify any listeners. if ((eventData->rcvd_evt.evt_len > 3) && (eventData->rcvd_evt.p_evt_buf[0] == 0x81)) { aidLen = eventData->rcvd_evt.p_evt_buf[1]; } if ((eventData->rcvd_evt.evt_len > (3 + aidLen)) && (eventData->rcvd_evt.p_evt_buf[2 + aidLen] == 0x82)) { payloadLen = eventData->rcvd_evt.p_evt_buf[3 + aidLen]; } if (aidLen) { sSecElem.notifyTransactionEvent( eventData->rcvd_evt.p_evt_buf + 2, aidLen, eventData->rcvd_evt.p_evt_buf + 4 + aidLen, payloadLen ); } } break; } default: ALOGE("%s: unknown event code=0x%X ????", __FUNCTION__, event); break; } } tNFA_HANDLE SecureElement::getDefaultEeHandle() { uint16_t overrideEeHandle = NFA_HANDLE_GROUP_EE | mActiveSeOverride; // Find the first EE that is not the HCI Access i/f. for (uint8_t i = 0; i < mActualNumEe; i++) { if (mActiveSeOverride && (overrideEeHandle != mEeInfo[i].ee_handle)) { continue; //skip all the EE's that are ignored } if ((mEeInfo[i].num_interface != 0) && (mEeInfo[i].ee_interface[0] != NCI_NFCEE_INTERFACE_HCI_ACCESS) && (mEeInfo[i].ee_status != NFC_NFCEE_STATUS_INACTIVE)) { return mEeInfo[i].ee_handle; } } ALOGE("%s: ee handle not found", __FUNCTION__); return NFA_HANDLE_INVALID; } const char* SecureElement::eeStatusToString(uint8_t status) { switch (status) { case NFC_NFCEE_STATUS_ACTIVE: return "Connected/Active"; case NFC_NFCEE_STATUS_INACTIVE: return "Connected/Inactive"; case NFC_NFCEE_STATUS_REMOVED: return "Removed"; default: return "?? Unknown ??"; } } void SecureElement::connectionEventHandler(uint8_t event, tNFA_CONN_EVT_DATA* /*eventData*/) { switch (event) { case NFA_CE_UICC_LISTEN_CONFIGURED_EVT: { SyncEventGuard guard(mUiccListenEvent); mUiccListenEvent.notifyOne(); break; } } } bool SecureElement::routeToSecureElement() { ALOGD("%s: enter", __FUNCTION__); tNFA_STATUS nfaStat = NFA_STATUS_FAILED; tNFA_TECHNOLOGY_MASK tech_mask = NFA_TECHNOLOGY_MASK_A | NFA_TECHNOLOGY_MASK_B; bool retval = false; if (!mIsInit) { ALOGE("%s: not init", __FUNCTION__); return false; } if (mCurrentRouteSelection == SecElemRoute) { ALOGE("%s: already sec elem route", __FUNCTION__); return true; } if (mActiveEeHandle == NFA_HANDLE_INVALID) { ALOGE("%s: invalid EE handle", __FUNCTION__); return false; } adjustRoutes(SecElemRoute); { unsigned long num = 0; if (GetNumValue("UICC_LISTEN_TECH_MASK", &num, sizeof(num))) { tech_mask = num; } ALOGD("%s: start UICC listen; h=0x%X; tech mask=0x%X", __FUNCTION__, mActiveEeHandle, tech_mask); SyncEventGuard guard(mUiccListenEvent); nfaStat = NFA_CeConfigureUiccListenTech(mActiveEeHandle, tech_mask); if (nfaStat == NFA_STATUS_OK) { mUiccListenEvent.wait(); retval = true; } else { ALOGE("%s: fail to start UICC listen", __FUNCTION__); } } return retval; } bool SecureElement::routeToDefault() { tNFA_STATUS nfaStat = NFA_STATUS_FAILED; bool retval = false; ALOGD("%s: enter", __FUNCTION__); if (!mIsInit) { ALOGE("%s: not init", __FUNCTION__); return false; } if (mCurrentRouteSelection == DefaultRoute) { ALOGD("%s: already default route", __FUNCTION__); return true; } if (mActiveEeHandle != NFA_HANDLE_INVALID) { ALOGD("%s: stop UICC listen; EE h=0x%X", __FUNCTION__, mActiveEeHandle); SyncEventGuard guard(mUiccListenEvent); nfaStat = NFA_CeConfigureUiccListenTech(mActiveEeHandle, 0); if (nfaStat == NFA_STATUS_OK) { mUiccListenEvent.wait(); retval = true; } else { ALOGE("%s: fail to stop UICC listen", __FUNCTION__); } } else { retval = true; } adjustRoutes(DefaultRoute); ALOGD("%s: exit; ok=%u", __FUNCTION__, retval); return retval; } bool SecureElement::isBusy() { bool retval = (mCurrentRouteSelection == SecElemRoute) || mIsPiping; ALOGD("%s: %u", __FUNCTION__, retval); return retval; } <file_sep>/src/interface/NdefRecord.h /* * Copyright (C) 2013-2014 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef mozilla_nfcd_NdefRecord_h #define mozilla_nfcd_NdefRecord_h #include <vector> class NdefRecord { public: // Type Name Format, defined in NFC forum "NFC Data Exchange Format (NDEF)" spec static const uint8_t TNF_EMPTY = 0x00; static const uint8_t TNF_WELL_KNOWN = 0x01; static const uint8_t TNF_MIME_MEDIA = 0x02; static const uint8_t TNF_ABSOLUTE_URI = 0x03; static const uint8_t TNF_EXTERNAL_TYPE = 0x04; static const uint8_t TNF_UNKNOWN = 0x05; static const uint8_t TNF_UNCHANGED = 0x06; static const uint8_t TNF_RESERVED = 0x07; /** * Default constructor. */ NdefRecord(); /** * Constructor with type, id, payload as input parameter. */ NdefRecord(uint8_t tnf, std::vector<uint8_t>& type, std::vector<uint8_t>& id, std::vector<uint8_t>& payload); /** * Constructor with type, id, payload as input parameter. */ NdefRecord(uint8_t tnf, uint32_t typeLength, uint8_t* type, uint32_t idLength, uint8_t* id, uint32_t payloadLength, uint8_t* payload); /** * Destructor. */ ~NdefRecord(); /** * Utility function to fill NdefRecord. * * @param buf Input buffer contains raw NDEF data. * @param ignoreMbMe Set if only want to parse single NdefRecord and do not care about Mb,Me field. * @param records Output formatted NdefRecord parsed from buf. * @return True if the buffer can be correctly parsed. */ static bool parse(std::vector<uint8_t>& buf, bool ignoreMbMe, std::vector<NdefRecord>& records); /** * Utility function to fill NdefRecord. * * @param buf Input buffer contains raw NDEF data. * @param ignoreMbMe Set if only want to parse single NdefRecord and do not care about Mb,Me field. * @param records Output formatted NdefRecord parsed from buf. * @param offset Indicate the start position of buffer to be parsed. * @return True if the buffer can be correctly parsed. */ static bool parse(std::vector<uint8_t>& buf, bool ignoreMbMe, std::vector<NdefRecord>& records, int offset); /** * Write current Ndefrecord to byte buffer. MB,ME bit is specified in parameter. * * @param buf Output raw buffer. * @param mb Message begine bit of NDEF record. * @param me Message end bit of NDEF record. * @return None. */ void writeToByteBuffer(std::vector<uint8_t>& buf, bool mb, bool me); // MB, ME, CF, SR, IL. uint8_t mFlags; // Type name format. uint8_t mTnf; // Payload type. std::vector<uint8_t> mType; // Identifier. std::vector<uint8_t> mId; // NDEF payload. std::vector<uint8_t> mPayload; }; #endif <file_sep>/src/interface/NdefRecord.cpp /* * Copyright (C) 2013-2014 Mozilla Foundation * * 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. */ #include "NdefRecord.h" #undef LOG_TAG #define LOG_TAG "nfcd" #include <utils/Log.h> static bool ensureSanePayloadSize(long size); static bool validateTnf(uint8_t tnf, std::vector<uint8_t>& type, std::vector<uint8_t>& id, std::vector<uint8_t>& payload); static const uint8_t FLAG_MB = 0x80; static const uint8_t FLAG_ME = 0x40; static const uint8_t FLAG_CF = 0x20; static const uint8_t FLAG_SR = 0x10; static const uint8_t FLAG_IL = 0x08; // 10 MB payload limit. static const int MAX_PAYLOAD_SIZE = 10 * (1 << 20); NdefRecord::NdefRecord(uint8_t tnf, std::vector<uint8_t>& type, std::vector<uint8_t>& id, std::vector<uint8_t>& payload) { mTnf = tnf; for(uint32_t i = 0; i < type.size(); i++) mType.push_back(type[i]); for(uint32_t i = 0; i < id.size(); i++) mId.push_back(id[i]); for(uint32_t i = 0; i < payload.size(); i++) mPayload.push_back(payload[i]); } NdefRecord::NdefRecord(uint8_t tnf, uint32_t typeLength, uint8_t* type, uint32_t idLength, uint8_t* id, uint32_t payloadLength, uint8_t* payload) { mTnf = tnf; for (uint32_t i = 0; i < typeLength; i++) mType.push_back((uint8_t)type[i]); for (uint32_t i = 0; i < idLength; i++) mId.push_back((uint8_t)id[i]); for (uint32_t i = 0; i < payloadLength; i++) mPayload.push_back((uint8_t)payload[i]); } NdefRecord::~NdefRecord() { } bool NdefRecord::parse(std::vector<uint8_t>& buf, bool ignoreMbMe, std::vector<NdefRecord>& records) { return NdefRecord::parse(buf, ignoreMbMe, records, 0); } bool NdefRecord::parse(std::vector<uint8_t>& buf, bool ignoreMbMe, std::vector<NdefRecord>& records, int offset) { bool inChunk = false; uint8_t chunkTnf = -1; bool me = false; uint32_t index = offset; while(!me) { std::vector<uint8_t> type; std::vector<uint8_t> id; std::vector<uint8_t> payload; std::vector<std::vector<uint8_t> > chunks; uint8_t flag = buf[index++]; bool mb = (flag & FLAG_MB) != 0; me = (flag & FLAG_ME) != 0; bool cf = (flag & FLAG_CF) != 0; bool sr = (flag & FLAG_SR) != 0; bool il = (flag & FLAG_IL) != 0; uint8_t tnf = flag & 0x07; if (!mb && records.size() == 0 && !inChunk && !ignoreMbMe) { ALOGE("expected MB flag"); return false; } else if (mb && records.size() != 0 && !ignoreMbMe) { ALOGE("unexpected MB flag"); return false; } else if (inChunk && il) { ALOGE("unexpected IL flag in non-leading chunk"); return false; } else if (cf && me) { ALOGE("unexpected ME flag in non-trailing chunk"); return false ; } else if (inChunk && tnf != NdefRecord::TNF_UNCHANGED) { ALOGE("expected TNF_UNCHANGED in non-leading chunk"); return false ; } else if (!inChunk && tnf == NdefRecord::TNF_UNCHANGED) { ALOGE("unexpected TNF_UNCHANGED in first chunk or unchunked record"); return false; } uint32_t typeLength = buf[index++] & 0xFF; if (!tnf && typeLength != 0) { ALOGE("expected zero-length type in empty NDEF message"); return false; } uint32_t payloadLength; if (sr) { payloadLength = buf[index++] & 0xFF; } else { payloadLength = ((uint32_t)buf[index] << 24) | ((uint32_t)buf[index + 1] << 16) | ((uint32_t)buf[index + 2] << 8) | ((uint32_t)buf[index + 3]); index += 4; } if (!tnf && payloadLength != 0) { ALOGE("expected zero-length payload in empty NDEF message"); return false; } uint32_t idLength = il ? (buf[index++] & 0xFF) : 0; if (!tnf && idLength != 0) { ALOGE("expected zero-length id in empty NDEF message"); return false; } if (inChunk && typeLength != 0) { ALOGE("expected zero-length type in non-leading chunk"); return false; } if (!inChunk) { for (uint32_t idx = 0; idx < typeLength; idx++) { type.push_back(buf[index++]); } for (uint32_t idx = 0; idx < idLength; idx++) { id.push_back(buf[index++]); } } if (!ensureSanePayloadSize(payloadLength)) { return false; } for (uint32_t idx = 0; idx < payloadLength; idx++) { payload.push_back(buf[index++]); } if (cf && !inChunk) { // first chunk. chunks.clear(); chunkTnf = tnf; } if (cf || inChunk) { // any chunk. chunks.push_back(payload); } if (!cf && inChunk) { // last chunk, flatten the payload. payloadLength = 0; for (uint32_t idx = 0; idx < chunks.size(); idx++) { payloadLength += chunks[idx].size(); } if (!ensureSanePayloadSize(payloadLength)) { return false; } for(uint32_t i = 0; i < chunks.size(); i++) { for(uint32_t j = 0; j < chunks[i].size(); j++) { payload.push_back(chunks[i][j]); } } tnf = chunkTnf; } if (cf) { // more chunks to come. inChunk = true; continue; } else { inChunk = false; } bool isValid = validateTnf(tnf, type, id, payload); if (isValid == false) { return false; } NdefRecord record(tnf, type, id, payload); records.push_back(record); if (ignoreMbMe) { // for parsing a single NdefRecord. break; } } return true; } bool ensureSanePayloadSize(long size) { if (size > MAX_PAYLOAD_SIZE) { ALOGE("payload above max limit: %d > ", MAX_PAYLOAD_SIZE); return false; } return true; } bool validateTnf(uint8_t tnf, std::vector<uint8_t>& type, std::vector<uint8_t>& id, std::vector<uint8_t>& payload) { bool isValid = true; switch (tnf) { case NdefRecord::TNF_EMPTY: if (type.size() != 0 || id.size() != 0 || payload.size() != 0) { ALOGE("unexpected data in TNF_EMPTY record"); isValid = false; } break; case NdefRecord::TNF_WELL_KNOWN: case NdefRecord::TNF_MIME_MEDIA: case NdefRecord::TNF_ABSOLUTE_URI: case NdefRecord::TNF_EXTERNAL_TYPE: break; case NdefRecord::TNF_UNKNOWN: case NdefRecord::TNF_RESERVED: if (type.size() != 0) { ALOGE("unexpected type field in TNF_UNKNOWN or TNF_RESERVEd record"); isValid = false; } break; case NdefRecord::TNF_UNCHANGED: ALOGE("unexpected TNF_UNCHANGED in first chunk or logical record"); isValid = false; break; default: ALOGE("unexpected tnf value"); isValid = false; break; } return isValid; } void NdefRecord::writeToByteBuffer(std::vector<uint8_t>& buf, bool mb, bool me) { bool sr = mPayload.size() < 256; bool il = mId.size() > 0; uint8_t flags = (uint8_t)((mb ? FLAG_MB : 0) | (me ? FLAG_ME : 0) | (sr ? FLAG_SR : 0) | (il ? FLAG_IL : 0) | mTnf); buf.push_back(flags); buf.push_back((uint8_t)mType.size()); if (sr) { buf.push_back((uint8_t)mPayload.size()); } else { buf.push_back((mPayload.size() >> 24) & 0xff); buf.push_back((mPayload.size() >> 16) & 0xff); buf.push_back((mPayload.size() >> 8) & 0xff); buf.push_back(mPayload.size() & 0xff); } if (il) { buf.push_back((uint8_t)mId.size()); } for (uint32_t i = 0; i < mType.size(); i++) buf.push_back(mType[i]); for (uint32_t i = 0; i < mId.size(); i++) buf.push_back(mId[i]); for (uint32_t i = 0; i < mPayload.size(); i++) buf.push_back(mPayload[i]); } <file_sep>/src/interface/DeviceHost.cpp /* * Copyright (C) 2013-2014 Mozilla Foundation * * 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. */ #include "DeviceHost.h" #include "NfcService.h" #define LOG_TAG "nfcd" #include <cutils/log.h> void DeviceHost::notifyTagDiscovered(INfcTag* pTag) { NfcService::notifyTagDiscovered(pTag); } void DeviceHost::notifyTargetDeselected() { ALOGE("%s: not implement", __FUNCTION__); } void DeviceHost::notifyTransactionEvent(TransactionEvent* pEvent) { NfcService::notifySETransactionEvent(pEvent); } void DeviceHost::notifyLlcpLinkActivated(IP2pDevice* pDevice) { NfcService::notifyLlcpLinkActivated(pDevice); } void DeviceHost::notifyLlcpLinkDeactivated(IP2pDevice* pDevice) { NfcService::notifyLlcpLinkDeactivated(pDevice); } void DeviceHost::notifyLlcpLinkFirstPacketReceived() { ALOGE("%s: not implement", __FUNCTION__); } void DeviceHost::notifySeFieldActivated() { ALOGE("%s: not implement", __FUNCTION__); } void DeviceHost::notifySeFieldDeactivated() { ALOGE("%s: not implement", __FUNCTION__); } TransactionEvent::TransactionEvent() : originType(TransactionEvent::SIM) , originIndex(-1) , aidLen(0) , aid(NULL) , payloadLen(0) , payload(NULL) { } TransactionEvent::~TransactionEvent() { delete aid; delete payload; } <file_sep>/src/MessageHandler.h /* * Copyright (C) 2014 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef mozilla_nfcd_MessageHandler_h #define mozilla_nfcd_MessageHandler_h #include <stdio.h> #include "NfcGonkMessage.h" #include "TagTechnology.h" #include <binder/Parcel.h> class NfcIpcSocket; class NfcService; class NdefMessage; class MessageHandler { public: MessageHandler(NfcService* service): mService(service) {}; void processRequest(const uint8_t* data, size_t length); void processResponse(NfcResponseType response, NfcErrorCode error, void* data); void processNotification(NfcNotificationType notification, void* data); void setOutgoingSocket(NfcIpcSocket* socket); private: void notifyInitialized(android::Parcel& parcel); void notifyTechDiscovered(android::Parcel& parcel, void* data); void notifyTechLost(android::Parcel& parcel, void* data); void notifyTransactionEvent(android::Parcel& parcel, void* data); bool handleConfigRequest(android::Parcel& parcel); bool handleReadNdefDetailRequest(android::Parcel& parcel); bool handleReadNdefRequest(android::Parcel& parcel); bool handleWriteNdefRequest(android::Parcel& parcel); bool handleConnectRequest(android::Parcel& parcel); bool handleCloseRequest(android::Parcel& parcel); bool handleMakeNdefReadonlyRequest(android::Parcel& parcel); bool handleConfigResponse(android::Parcel& parcel, void* data); bool handleReadNdefDetailResponse(android::Parcel& parcel, void* data); bool handleReadNdefResponse(android::Parcel& parcel, void* data); bool handleResponse(android::Parcel& parcel); void sendResponse(android::Parcel& parcel); bool sendNdefMsg(android::Parcel& parcel, NdefMessage* ndef); NfcIpcSocket* mSocket; NfcService* mService; }; struct TechDiscoveredEvent { int sessionId; uint32_t techCount; void* techList; uint32_t ndefMsgCount; NdefMessage* ndefMsg; }; #endif // mozilla_nfcd_MessageHandler_h <file_sep>/src/nci/LlcpServiceSocket.cpp /* * Copyright (C) 2014 Mozilla Foundation * * 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. */ #include "LlcpServiceSocket.h" #include "LlcpSocket.h" #include "ILlcpSocket.h" #include "PeerToPeer.h" #define LOG_TAG "NfcNci" #include <cutils/log.h> LlcpServiceSocket::LlcpServiceSocket(uint32_t handle, int localLinearBufferLength, int localMiu, int localRw) : mHandle(handle) , mLocalLinearBufferLength(localLinearBufferLength) , mLocalMiu(localMiu) , mLocalRw(localRw) { } LlcpServiceSocket::~LlcpServiceSocket() { } ILlcpSocket* LlcpServiceSocket::accept() { ALOGD("%s: enter", __FUNCTION__); const uint32_t serverHandle = mHandle; const uint32_t connHandle = PeerToPeer::getInstance().getNewHandle(); bool stat = false; stat = PeerToPeer::getInstance().accept(serverHandle, connHandle, mLocalMiu, mLocalRw); if (!stat) { ALOGE("%s: fail accept", __FUNCTION__); return NULL; } LlcpSocket* clientSocket = new LlcpSocket(connHandle, mLocalMiu, mLocalRw); ALOGD("%s: exit", __FUNCTION__); return static_cast<ILlcpSocket*>(clientSocket); } bool LlcpServiceSocket::close() { ALOGD("%s: enter", __FUNCTION__); const uint32_t serverHandle = mHandle; bool stat = false; stat = PeerToPeer::getInstance().deregisterServer(serverHandle); if (!stat) { ALOGE("%s: fail deregister server", __FUNCTION__); return NULL; } ALOGD("%s: exit", __FUNCTION__); return true; } <file_sep>/src/NfcService.h /* * Copyright (C) 2013-2014 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef mozilla_nfcd_NfcService_h #define mozilla_nfcd_NfcService_h #include "utils/List.h" #include "IpcSocketListener.h" #include "NfcManager.h" #include "NfcGonkMessage.h" class NdefMessage; class MessageHandler; class NfcEvent; class INfcManager; class INfcTag; class IP2pDevice; class P2pLinkManager; class NfcService : public IpcSocketListener { public: ~NfcService(); void initialize(NfcManager* pNfcManager, MessageHandler* msgHandler); static NfcService* Instance(); static INfcManager* getNfcManager(); static void notifyLlcpLinkActivated(IP2pDevice* pDevice); static void notifyLlcpLinkDeactivated(IP2pDevice* pDevice); static void notifyTagDiscovered(INfcTag* pTag); static void notifyTagLost(int sessionId); static void notifySEFieldActivated(); static void notifySEFieldDeactivated(); static void notifySETransactionEvent(TransactionEvent* pEvent); static bool handleDisconnect(); void* eventLoop(); void handleTagDiscovered(NfcEvent* event); void handleTagLost(NfcEvent* event); void handleTransactionEvent(NfcEvent* event); void handleLlcpLinkActivation(NfcEvent* event); void handleLlcpLinkDeactivation(NfcEvent* event); void handleConnect(int technology); bool handleConfigRequest(int powerLevel); void handleConfigResponse(NfcEvent* event); bool handleReadNdefDetailRequest(); void handleReadNdefDetailResponse(NfcEvent* event); bool handleReadNdefRequest(); void handleReadNdefResponse(NfcEvent* event); bool handleWriteNdefRequest(NdefMessage* ndef); void handleWriteNdefResponse(NfcEvent* event); void handleCloseRequest(); void handleCloseResponse(NfcEvent* event); bool handlePushNdefRequest(NdefMessage* ndef); void handlePushNdefResponse(NfcEvent* event); bool handleMakeNdefReadonlyRequest(); void handleMakeNdefReadonlyResponse(NfcEvent* event); bool handleEnterLowPowerRequest(bool enter); void handleEnterLowPowerResponse(NfcEvent* event); bool handleEnableRequest(bool enable); void handleEnableResponse(NfcEvent* event); void handleReceiveNdefEvent(NfcEvent* event); void onConnected(); void onP2pReceivedNdef(NdefMessage* ndef); NfcErrorCode enableNfc(); NfcErrorCode disableNfc(); private: NfcService(); NfcErrorCode setLowPowerMode(bool low); NfcErrorCode enableSE(); NfcErrorCode disableSE(); uint32_t mState; static NfcService* sInstance; static NfcManager* sNfcManager; android::List<NfcEvent*> mQueue; MessageHandler* mMsgHandler; P2pLinkManager* mP2pLinkManager; }; #endif // mozilla_nfcd_NfcService_h <file_sep>/src/nci/LlcpSocket.cpp /* * Copyright (C) 2014 Mozilla Foundation * * 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. */ #include "LlcpSocket.h" #include "PeerToPeer.h" #define LOG_TAG "NfcNci" #include <cutils/log.h> LlcpSocket::LlcpSocket(unsigned int handle, int sap, int miu, int rw) : mHandle(handle) , mSap(sap) , mLocalMiu(miu) , mLocalRw(rw) { } LlcpSocket::LlcpSocket(unsigned int handle, int miu, int rw) : mHandle(handle) , mLocalMiu(miu) , mLocalRw(rw) { } LlcpSocket::~LlcpSocket() { } /** * Interface. */ bool LlcpSocket::connectToSap(int sap) { return LlcpSocket::doConnect(sap); } bool LlcpSocket::connectToService(const char* serviceName) { return LlcpSocket::doConnectBy(serviceName); } void LlcpSocket::close() { LlcpSocket::doClose(); } bool LlcpSocket::send(std::vector<uint8_t>& data) { return LlcpSocket::doSend(data); } int LlcpSocket::receive(std::vector<uint8_t>& recvBuff) { return LlcpSocket::doReceive(recvBuff);; } int LlcpSocket::getRemoteMiu() const { return LlcpSocket::doGetRemoteSocketMIU(); } int LlcpSocket::getRemoteRw() const { return LlcpSocket::doGetRemoteSocketRW(); } /** * Private function. */ bool LlcpSocket::doConnect(int nSap) { ALOGD("%s: enter; sap=%d", __FUNCTION__, nSap); bool stat = PeerToPeer::getInstance().connectConnOriented(mHandle, nSap); if (!stat) { ALOGE("%s: fail connect oriented", __FUNCTION__); } ALOGD("%s: exit", __FUNCTION__); return stat; } bool LlcpSocket::doConnectBy(const char* sn) { ALOGD("%s: enter; sn = %s", __FUNCTION__, sn); if (!sn) { return false; } bool stat = PeerToPeer::getInstance().connectConnOriented(mHandle, sn); if (!stat) { ALOGE("%s: fail connect connection oriented", __FUNCTION__); } ALOGD("%s: exit", __FUNCTION__); return stat; } bool LlcpSocket::doClose() { ALOGD("%s: enter", __FUNCTION__); bool stat = PeerToPeer::getInstance().disconnectConnOriented(mHandle); if (!stat) { ALOGE("%s: fail disconnect connection oriented", __FUNCTION__); } ALOGD("%s: exit", __FUNCTION__); return true; // TODO: stat? } bool LlcpSocket::doSend(std::vector<uint8_t>& data) { UINT8* raw_ptr = new UINT8[data.size()]; for(uint32_t i = 0; i < data.size(); i++) raw_ptr[i] = (UINT8)data[i]; bool stat = PeerToPeer::getInstance().send(mHandle, raw_ptr, data.size()); if (!stat) { ALOGE("%s: fail send", __FUNCTION__); } delete[] raw_ptr; return stat; } int LlcpSocket::doReceive(std::vector<uint8_t>& recvBuff) { const uint16_t MAX_BUF_SIZE = 4096; uint16_t actualLen = 0; UINT8* raw_ptr = new UINT8[MAX_BUF_SIZE]; bool stat = PeerToPeer::getInstance().receive(mHandle, raw_ptr, MAX_BUF_SIZE, actualLen); int retval = 0; if (stat && (actualLen > 0)) { for (uint16_t i = 0; i < actualLen; i++) recvBuff.push_back(raw_ptr[i]); retval = actualLen; } else { retval = -1; } delete[] raw_ptr; return retval; } int LlcpSocket::doGetRemoteSocketMIU() const { ALOGD("%s: enter", __FUNCTION__); int miu = PeerToPeer::getInstance().getRemoteMaxInfoUnit(mHandle); ALOGD("%s: exit", __FUNCTION__); return miu; } int LlcpSocket::doGetRemoteSocketRW() const { ALOGD("%s: enter", __FUNCTION__); int rw = PeerToPeer::getInstance().getRemoteRecvWindow(mHandle); ALOGD("%s: exit", __FUNCTION__); return rw; } <file_sep>/src/snep/SnepServer.cpp /* * Copyright (C) 2013-2014 Mozilla Foundation * * 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. */ #include <pthread.h> #include <semaphore.h> #include <stdlib.h> #include "NfcService.h" #include "NfcManager.h" #include "SnepServer.h" #include "ISnepCallback.h" #include "NfcDebug.h" // Well-known LLCP SAP Values defined by NFC forum. const char* SnepServer::DEFAULT_SERVICE_NAME = "urn:nfc:sn:snep"; // Connection thread, used to handle incoming connections. void* SnepConnectionThreadFunc(void* arg) { ALOGD("%s: connection thread enter", FUNC); SnepConnectionThread* pConnectionThread = reinterpret_cast<SnepConnectionThread*>(arg); if (!pConnectionThread) { ALOGE("%s: invalid parameter", FUNC); return NULL; } ISnepCallback* ICallback = pConnectionThread->mCallback; while(pConnectionThread->isServerRunning()) { // Handle message. if (!SnepServer::handleRequest(pConnectionThread->mMessenger, ICallback)) { break; } } if (pConnectionThread->mSock) pConnectionThread->mSock->close(); // TODO : is this correct ?? delete pConnectionThread; ALOGD("%s: connection thread exit", FUNC); return NULL; } /** * Connection thread is created when Snep server accept a connection request. */ SnepConnectionThread::SnepConnectionThread( SnepServer* server,ILlcpSocket* socket, int fragmentLength, ISnepCallback* ICallback) : mSock(socket) , mCallback(ICallback) , mServer(server) { mMessenger = new SnepMessenger(false, socket, fragmentLength); } SnepConnectionThread::~SnepConnectionThread() { delete mMessenger; } void SnepConnectionThread::run() { pthread_t tid; if(pthread_create(&tid, NULL, SnepConnectionThreadFunc, this) != 0) { ALOGE("%s: pthread_create fail", FUNC); abort(); } } bool SnepConnectionThread::isServerRunning() const { return mServer->mServerRunning; } /** * Server thread, used to listen for incoming connection request. */ void* snepServerThreadFunc(void* arg) { SnepServer* pSnepServer = reinterpret_cast<SnepServer*>(arg); if (!pSnepServer) { ALOGE("%s: invalid parameter", FUNC); return NULL; } ILlcpServerSocket* serverSocket = pSnepServer->mServerSocket; ISnepCallback* ICallback = pSnepServer->mCallback; const int fragmentLength = pSnepServer->mFragmentLength; if (!serverSocket) { ALOGE("%s: no server socket", FUNC); return NULL; } while(pSnepServer->mServerRunning) { if (!serverSocket) { ALOGD("%s: server socket shut down", FUNC); return NULL; } ILlcpSocket* communicationSocket = serverSocket->accept(); if (communicationSocket) { const int miu = communicationSocket->getRemoteMiu(); const int length = (fragmentLength == -1) ? miu : miu < fragmentLength ? miu : fragmentLength; SnepConnectionThread* pConnectionThread = new SnepConnectionThread(pSnepServer, communicationSocket, length, ICallback); pConnectionThread->run(); } } return NULL; } SnepServer::SnepServer(ISnepCallback* ICallback) : mServerSocket(NULL) , mCallback(ICallback) , mServerRunning(false) , mServiceName(DEFAULT_SERVICE_NAME) , mServiceSap(DEFAULT_PORT) , mFragmentLength(-1) , mMiu(DEFAULT_MIU) , mRwSize(DEFAULT_RW_SIZE) { } SnepServer::SnepServer(const char* serviceName, int serviceSap, ISnepCallback* ICallback) : mServerSocket(NULL) , mCallback(ICallback) , mServerRunning(false) , mServiceName(serviceName) , mServiceSap(serviceSap) , mFragmentLength(-1) , mMiu(DEFAULT_MIU) , mRwSize(DEFAULT_RW_SIZE) { } SnepServer::SnepServer(ISnepCallback* ICallback, int miu, int rwSize) : mServerSocket(NULL) , mCallback(ICallback) , mServerRunning(false) , mServiceName(DEFAULT_SERVICE_NAME) , mServiceSap(DEFAULT_PORT) , mFragmentLength(-1) , mMiu(miu) , mRwSize(rwSize) { } SnepServer::SnepServer(const char* serviceName, int serviceSap, int fragmentLength, ISnepCallback* ICallback) : mServerSocket(NULL) , mCallback(ICallback) , mServerRunning(false) , mServiceName(serviceName) , mServiceSap(serviceSap) , mFragmentLength(fragmentLength) , mMiu(DEFAULT_MIU) , mRwSize(DEFAULT_RW_SIZE) { } SnepServer::~SnepServer() { stop(); } void SnepServer::start() { ALOGD("%s: enter", FUNC); INfcManager* pINfcManager = NfcService::getNfcManager(); mServerSocket = pINfcManager->createLlcpServerSocket(mServiceSap, mServiceName, mMiu, mRwSize, 1024); if (!mServerSocket) { ALOGE("%s: cannot create llcp server socket", FUNC); abort(); } pthread_t tid; if(pthread_create(&tid, NULL, snepServerThreadFunc, this) != 0) { ALOGE("%s: pthread_create failed", FUNC); abort(); } mServerRunning = true; ALOGD("%s: exit", FUNC); } void SnepServer::stop() { // TODO : need to kill thread here if (mServerSocket) { mServerSocket->close(); delete mServerSocket; mServerSocket = NULL; } mServerRunning = false; // Use pthread_join here to make sure all thread is finished ? } bool SnepServer::handleRequest(SnepMessenger* messenger, ISnepCallback* callback) { if (!messenger || !callback) { ALOGE("%s:: invalid parameter", FUNC); return false; } SnepMessage* request = messenger->getMessage(); SnepMessage* response = NULL; if (!request) { /** * Response Codes : BAD REQUEST * The request could not be understood by the server due to malformed syntax. */ ALOGE("%s: bad snep message", FUNC); response = SnepMessage::getMessage(SnepMessage::RESPONSE_BAD_REQUEST); if (response) { messenger->sendMessage(*response); delete response; } return false; } if (((request->getVersion() & 0xF0) >> 4) != SnepMessage::VERSION_MAJOR) { /** * Response Codes : UNSUPPORTED VERSION * The server does not support, or refuses to support, the SNEP protocol * version that was used in the request message. */ ALOGE("%s: unsupported version", FUNC); response = SnepMessage::getMessage(SnepMessage::RESPONSE_UNSUPPORTED_VERSION); } else if (request->getField() == SnepMessage::REQUEST_GET) { NdefMessage* ndef = request->getNdefMessage(); response = callback->doGet(request->getAcceptableLength(), ndef); } else if (request->getField() == SnepMessage::REQUEST_PUT) { NdefMessage* ndef = request->getNdefMessage(); response = callback->doPut(ndef); } else { ALOGE("%s: bad request", FUNC); response = SnepMessage::getMessage(SnepMessage::RESPONSE_BAD_REQUEST); } delete request; if (response) { messenger->sendMessage(*response); delete response; } else { ALOGE("%s: no response message is generated", FUNC); return false; } return true; } <file_sep>/src/interface/INfcManager.h /* * Copyright (C) 2013-2014 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef mozilla_nfcd_INfcManager_h #define mozilla_nfcd_INfcManager_h #include "ILlcpServerSocket.h" #include "ILlcpSocket.h" class INfcManager { public: virtual ~INfcManager() {}; /** * To get a specific interface from NfcManager. * * @param name Interface name. * @return Return specific interface if exist, null if cannot find. */ virtual void* queryInterface(const char* name) = 0; /** * Turn on NFC. * * @return True if ok. */ virtual bool initialize() = 0; /** * Turn off NFC. * * @return True if ok. */ virtual bool deinitialize() = 0; /** * Start polling and listening for devices. * * @return True if ok. */ virtual bool enableDiscovery() = 0; /** * Stop polling and listening for devices. * * @return True if ok. */ virtual bool disableDiscovery() = 0; /** * Start polling for devices. * * @return True if ok. */ virtual bool enablePolling() = 0; /** * Stop polling for devices. * * @return True if ok. */ virtual bool disablePolling() = 0; /** * Start peer-to-peer listening for devices. * * @return True if ok. */ virtual bool enableP2pListening() = 0; /** * Stop peer-to-peer listening for devices. * * @return True if ok. */ virtual bool disableP2pListening() = 0; /** * Check Llcp connection. * * @return True if ok. */ virtual bool checkLlcp() = 0; /** * Activate Llcp connection. * * @return True if ok. */ virtual bool activateLlcp() = 0; /** * Create a LLCP connection-oriented socket. * * @param sap Service access point. * @param miu Maximum information unit. * @param rw Receive window size. * @param linearBufferLength Max buffer size. * @return ILlcpSocket interface. */ virtual ILlcpSocket* createLlcpSocket(int sap, int miu, int rw, int linearBufferLength) = 0; /** * Create a new LLCP server socket. * * @param nSap Service access point. * @param sn Service name. * @param miu Maximum information unit. * @param rw Receive window size. * @param linearBufferLength Max buffer size. * @return ILlcpServerSocket interface. */ virtual ILlcpServerSocket* createLlcpServerSocket(int sap, const char* sn, int miu, int rw, int linearBufferLength) = 0; /** * Create a new LLCP server socket. * * @param nSap Service access point. * @param sn Service name. * @param miu Maximum information unit. * @param rw Receive window size. * @param linearBufferLength Max buffer size. * @return ILlcpServerSocket interface. */ virtual void setP2pInitiatorModes(int modes) = 0; /** * Set P2P target's activation modes. * * @param modes Active and/or passive modes. * @return None. */ virtual void setP2pTargetModes(int modes) = 0; /** * Get default Llcp connection maxumum information unit. * * @return Default MIU. */ virtual int getDefaultLlcpMiu() const = 0; /** * Get default Llcp connection receive window size. * * @return Default receive window size. */ virtual int getDefaultLlcpRwSize() const = 0; /** * NFC controller starts routing data in listen mode. * * @return True if ok. */ virtual bool doSelectSecureElement() = 0; /** * NFC controller stops routing data in listen mode. * * @return True if ok. */ virtual bool doDeselectSecureElement() = 0; }; #endif <file_sep>/src/NfcIpcSocket.cpp /* * Copyright (C) 2013-2014 Mozilla Foundation * * 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. */ #include <stdio.h> #include <fcntl.h> #include <errno.h> #include <poll.h> #include <pwd.h> #include <netinet/in.h> #include <sys/un.h> #include <sys/socket.h> #include <sys/stat.h> #include <linux/prctl.h> #include <cutils/sockets.h> #include <cutils/record_stream.h> #include <unistd.h> #include <queue> #include <string> #include "IpcSocketListener.h" #include "NfcIpcSocket.h" #include "MessageHandler.h" #include "NfcDebug.h" #define NFCD_SOCKET_NAME "nfcd" #define MAX_COMMAND_BYTES (8 * 1024) using android::Parcel; static int nfcdRw; MessageHandler* NfcIpcSocket::sMsgHandler = NULL; /** * NfcIpcSocket */ NfcIpcSocket* NfcIpcSocket::sInstance = NULL; NfcIpcSocket* NfcIpcSocket::Instance() { if (!sInstance) sInstance = new NfcIpcSocket(); return sInstance; } NfcIpcSocket::NfcIpcSocket() { } NfcIpcSocket::~NfcIpcSocket() { } void NfcIpcSocket::initialize(MessageHandler* msgHandler) { initSocket(); sMsgHandler = msgHandler; } void NfcIpcSocket::initSocket() { mSleep_spec.tv_sec = 0; mSleep_spec.tv_nsec = 500 * 1000; mSleep_spec_rem.tv_sec = 0; mSleep_spec_rem.tv_nsec = 0; } int NfcIpcSocket::getListenSocket() { const int nfcdConn = android_get_control_socket(NFCD_SOCKET_NAME); if (nfcdConn < 0) { ALOGE("Could not connect to %s socket: %s\n", NFCD_SOCKET_NAME, strerror(errno)); return -1; } if (listen(nfcdConn, 4) != 0) { return -1; } return nfcdConn; } void NfcIpcSocket::setSocketListener(IpcSocketListener* listener) { mListener = listener; } void NfcIpcSocket::loop() { bool connected = false; int nfcdConn = -1; int ret; while(1) { struct sockaddr_un peeraddr; socklen_t socklen = sizeof (peeraddr); if (!connected) { nfcdConn = getListenSocket(); if (nfcdConn < 0) { nanosleep(&mSleep_spec, &mSleep_spec_rem); continue; } } nfcdRw = accept(nfcdConn, (struct sockaddr*)&peeraddr, &socklen); if (nfcdRw < 0 ) { ALOGE("Error on accept() errno:%d", errno); /* start listening for new connections again */ continue; } ret = fcntl(nfcdRw, F_SETFL, O_NONBLOCK); if (ret < 0) { ALOGE ("Error setting O_NONBLOCK errno:%d", errno); } ALOGD("Socket connected"); connected = true; RecordStream *rs = record_stream_new(nfcdRw, MAX_COMMAND_BYTES); mListener->onConnected(); struct pollfd fds[1]; fds[0].fd = nfcdRw; fds[0].events = POLLIN; fds[0].revents = 0; while(connected) { poll(fds, 1, -1); if(fds[0].revents > 0) { fds[0].revents = 0; void* data; size_t dataLen; int ret = record_stream_get_next(rs, &data, &dataLen); ALOGD(" %d of bytes to be sent... data=%p ret=%d", dataLen, data, ret); if (ret == 0 && data == NULL) { // end-of-stream break; } else if (ret < 0) { break; } writeToIncomingQueue((uint8_t*)data, dataLen); } } record_stream_free(rs); close(nfcdRw); } return; } // Write NFC data to Gecko // Outgoing queue contain the data should be send to gecko // TODO check thread, this should run on the NfcService thread. void NfcIpcSocket::writeToOutgoingQueue(uint8_t* data, size_t dataLen) { ALOGD("%s enter, data=%p, dataLen=%d", __func__, data, dataLen); if (data == NULL || dataLen == 0) { return; } size_t writeOffset = 0; int written = 0; ALOGD("Writing %d bytes to gecko ", dataLen); while (writeOffset < dataLen) { do { written = write (nfcdRw, data + writeOffset, dataLen - writeOffset); } while (written < 0 && errno == EINTR); if (written >= 0) { writeOffset += written; } else { ALOGE("Response: unexpected error on write errno:%d", errno); break; } } } // Write Gecko data to NFC // Incoming queue contains // TODO check thread, this should run on top of main thread of nfcd. void NfcIpcSocket::writeToIncomingQueue(uint8_t* data, size_t dataLen) { ALOGD("%s enter, data=%p, dataLen=%d", __func__, data, dataLen); if (data != NULL && dataLen > 0) { sMsgHandler->processRequest(data, dataLen); } } <file_sep>/src/nfcd.cpp /* * Copyright (C) 2013-2014 Mozilla Foundation * * 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. */ #include "nfcd.h" #include "NfcManager.h" #include "NfcService.h" #include "NfcIpcSocket.h" #include "DeviceHost.h" #include "MessageHandler.h" #include "SnepServer.h" int main() { // Create NFC Manager and do initialize. NfcManager* pNfcManager = new NfcManager(); // Create service thread to receive message from nfc library. NfcService* service = NfcService::Instance(); MessageHandler* msgHandler = new MessageHandler(service); service->initialize(pNfcManager, msgHandler); // Create IPC socket & main thread will enter while loop to read data from socket. NfcIpcSocket* socket = NfcIpcSocket::Instance(); socket->initialize(msgHandler); socket->setSocketListener(service); msgHandler->setOutgoingSocket(socket); socket->loop(); //TODO delete NfcIpcSocket, NfcService delete msgHandler; delete pNfcManager; //exit(0); } <file_sep>/src/snep/SnepMessage.cpp /* * Copyright (C) 2013-2014 Mozilla Foundation * * 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. */ #include "SnepMessage.h" #include "NdefMessage.h" #include "NfcDebug.h" SnepMessage::SnepMessage() : mNdefMessage(NULL) { } SnepMessage::~SnepMessage() { delete mNdefMessage; } SnepMessage::SnepMessage(std::vector<uint8_t>& buf) { int ndefOffset = 0; int ndefLength = 0; int idx = 0; mVersion = buf[idx++]; mField = buf[idx++]; mLength = ((uint32_t)buf[idx] << 24) | ((uint32_t)buf[idx + 1] << 16) | ((uint32_t)buf[idx + 2] << 8) | (uint32_t)buf[idx + 3]; idx += 4 ; if (mField == SnepMessage::REQUEST_GET) { mAcceptableLength = ((uint32_t)buf[idx] << 24) | ((uint32_t)buf[idx + 1] << 16) | ((uint32_t)buf[idx + 2] << 8) | (uint32_t)buf[idx + 3]; idx += 4; ndefOffset = SnepMessage::HEADER_LENGTH + 4; ndefLength = mLength - 4; } else { mAcceptableLength = -1; ndefOffset = SnepMessage::HEADER_LENGTH; ndefLength = mLength; } if (ndefLength > 0) { mNdefMessage = new NdefMessage(); // TODO : Need to check idx is correct. mNdefMessage->init(buf, idx); } else { mNdefMessage = NULL; } } SnepMessage::SnepMessage(uint8_t version, uint8_t field, int length, int acceptableLength, NdefMessage* ndefMessage) { mVersion = version; mField = field; mLength = length; mAcceptableLength = acceptableLength; mNdefMessage = new NdefMessage(ndefMessage); } bool SnepMessage::isValidFormat(std::vector<uint8_t>& buf) { int size = buf.size(); // version(1), field(1), length(4) if (size < SnepMessage::HEADER_LENGTH) { return false; } // acceptable length(0 or 4) if (buf[1] == SnepMessage::REQUEST_GET && size < SnepMessage::HEADER_LENGTH + 4) { return false; } return true; } SnepMessage* SnepMessage::getGetRequest(int acceptableLength, NdefMessage& ndef) { std::vector<uint8_t> buf; ndef.toByteArray(buf); return new SnepMessage(SnepMessage::VERSION, SnepMessage::REQUEST_GET, 4 + buf.size(), acceptableLength, &ndef); } SnepMessage* SnepMessage::getPutRequest(NdefMessage& ndef) { std::vector<uint8_t> buf; ndef.toByteArray(buf); return new SnepMessage(SnepMessage::VERSION, SnepMessage::REQUEST_PUT, buf.size(), 0, &ndef); } SnepMessage* SnepMessage::getMessage(uint8_t field) { return new SnepMessage(SnepMessage::VERSION, field, 0, 0, NULL); } SnepMessage* SnepMessage::getSuccessResponse(NdefMessage* ndef) { if (!ndef) { return new SnepMessage(SnepMessage::VERSION, SnepMessage::RESPONSE_SUCCESS, 0, 0, NULL); } else { std::vector<uint8_t> buf; ndef->toByteArray(buf); return new SnepMessage(SnepMessage::VERSION, SnepMessage::RESPONSE_SUCCESS, buf.size(), 0, ndef); } } SnepMessage* SnepMessage::fromByteArray(std::vector<uint8_t>& buf) { return SnepMessage::isValidFormat(buf) ? new SnepMessage(buf) : NULL; } SnepMessage* SnepMessage::fromByteArray(uint8_t* pBuf, int size) { std::vector<uint8_t> buf; for (int i = 0; i < size; i++) { buf[i] = pBuf[i]; } return fromByteArray(buf); } void SnepMessage::toByteArray(std::vector<uint8_t>& buf) { if (mNdefMessage) { mNdefMessage->toByteArray(buf); } std::vector<uint8_t> snepHeader; snepHeader.push_back(mVersion); snepHeader.push_back(mField); if (mField == SnepMessage::REQUEST_GET) { uint32_t len = buf.size() + 4; snepHeader.push_back((len >> 24) & 0xFF); snepHeader.push_back((len >> 16) & 0xFF); snepHeader.push_back((len >> 8) & 0xFF); snepHeader.push_back( len & 0xFF); snepHeader.push_back((mAcceptableLength >> 24) & 0xFF); snepHeader.push_back((mAcceptableLength >> 16) & 0xFF); snepHeader.push_back((mAcceptableLength >> 8) & 0xFF); snepHeader.push_back( mAcceptableLength & 0xFF); } else { uint32_t len = buf.size(); snepHeader.push_back((len >> 24) & 0xFF); snepHeader.push_back((len >> 16) & 0xFF); snepHeader.push_back((len >> 8) & 0xFF); snepHeader.push_back( len & 0xFF); } buf.insert(buf.begin(), snepHeader.begin(), snepHeader.end()); } <file_sep>/src/NfcService.cpp /* * Copyright (C) 2013-2014 Mozilla Foundation * * 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. */ #include <pthread.h> #include <semaphore.h> #include <stdlib.h> #include <memory> #include "MessageHandler.h" #include "INfcManager.h" #include "INfcTag.h" #include "IP2pDevice.h" #include "DeviceHost.h" #include "NfcService.h" #include "NfcUtil.h" #include "NfcDebug.h" #include "P2pLinkManager.h" #include "SessionId.h" using namespace android; typedef enum { MSG_UNDEFINED = 0, MSG_LLCP_LINK_ACTIVATION, MSG_LLCP_LINK_DEACTIVATION, MSG_TAG_DISCOVERED, MSG_TAG_LOST, MSG_SE_FIELD_ACTIVATED, MSG_SE_FIELD_DEACTIVATED, MSG_SE_NOTIFY_TRANSACTION_EVENT, MSG_READ_NDEF_DETAIL, MSG_READ_NDEF, MSG_WRITE_NDEF, MSG_CLOSE, MSG_SOCKET_CONNECTED, MSG_PUSH_NDEF, MSG_NDEF_TAG_LIST, MSG_CONFIG, MSG_MAKE_NDEF_READONLY, MSG_LOW_POWER, MSG_ENABLE, MSG_RECEIVE_NDEF_EVENT } NfcEventType; typedef enum { STATE_NFC_OFF = 0, STATE_NFC_ON, STATE_NFC_ON_LOW_POWER, } NfcState; class NfcEvent { public: NfcEvent (NfcEventType type) :mType(type) {} NfcEventType getType() { return mType; } int arg1; int arg2; void* obj; private: NfcEventType mType; }; class PollingThreadParam { public: INfcTag* pINfcTag; int sessionId; }; static pthread_t thread_id; static sem_t thread_sem; NfcService* NfcService::sInstance = NULL; NfcManager* NfcService::sNfcManager = NULL; NfcService::NfcService() : mState(STATE_NFC_OFF) { mP2pLinkManager = new P2pLinkManager(this); } NfcService::~NfcService() { delete mP2pLinkManager; } static void *serviceThreadFunc(void *arg) { pthread_setname_np(pthread_self(), "NFCService thread"); NfcService* service = reinterpret_cast<NfcService*>(arg); return service->eventLoop(); } void NfcService::initialize(NfcManager* pNfcManager, MessageHandler* msgHandler) { if (sem_init(&thread_sem, 0, 0) == -1) { ALOGE("%s: init_nfc_service Semaphore creation failed", FUNC); abort(); } if (pthread_create(&thread_id, NULL, serviceThreadFunc, this) != 0) { ALOGE("%s: init_nfc_service pthread_create failed", FUNC); abort(); } mMsgHandler = msgHandler; sNfcManager = pNfcManager; } void NfcService::notifyLlcpLinkActivated(IP2pDevice* pDevice) { ALOGD("%s: enter", FUNC); NfcEvent *event = new NfcEvent(MSG_LLCP_LINK_ACTIVATION); event->obj = reinterpret_cast<void*>(pDevice); NfcService::Instance()->mQueue.push_back(event); sem_post(&thread_sem); } void NfcService::notifyLlcpLinkDeactivated(IP2pDevice* pDevice) { ALOGD("%s: enter", FUNC); NfcEvent *event = new NfcEvent(MSG_LLCP_LINK_DEACTIVATION); event->obj = reinterpret_cast<void*>(pDevice); NfcService::Instance()->mQueue.push_back(event); sem_post(&thread_sem); } void NfcService::notifyTagDiscovered(INfcTag* pTag) { ALOGD("%s: enter", FUNC); NfcEvent *event = new NfcEvent(MSG_TAG_DISCOVERED); event->obj = reinterpret_cast<void*>(pTag); NfcService::Instance()->mQueue.push_back(event); sem_post(&thread_sem); } void NfcService::notifyTagLost(int sessionId) { ALOGD("%s: enter", FUNC); NfcEvent *event = new NfcEvent(MSG_TAG_LOST); event->obj = reinterpret_cast<void*>(sessionId); NfcService::Instance()->mQueue.push_back(event); sem_post(&thread_sem); } void NfcService::notifySEFieldActivated() { ALOGD("%s: enter", FUNC); NfcEvent *event = new NfcEvent(MSG_SE_FIELD_ACTIVATED); NfcService::Instance()->mQueue.push_back(event); sem_post(&thread_sem); } void NfcService::notifySEFieldDeactivated() { ALOGD("%s: enter", FUNC); NfcEvent *event = new NfcEvent(MSG_SE_FIELD_DEACTIVATED); NfcService::Instance()->mQueue.push_back(event); sem_post(&thread_sem); } void NfcService::notifySETransactionEvent(TransactionEvent* pEvent) { ALOGD("%s: enter", FUNC); NfcEvent *event = new NfcEvent(MSG_SE_NOTIFY_TRANSACTION_EVENT); event->obj = reinterpret_cast<void*>(pEvent); NfcService::Instance()->mQueue.push_back(event); sem_post(&thread_sem); } void NfcService::handleLlcpLinkDeactivation(NfcEvent* event) { ALOGD("%s: enter", FUNC); void* pDevice = event->obj; IP2pDevice* pIP2pDevice = reinterpret_cast<IP2pDevice*>(pDevice); if (pIP2pDevice->getMode() == NfcDepEndpoint::MODE_P2P_TARGET) { pIP2pDevice->disconnect(); } mP2pLinkManager->onLlcpDeactivated(); mMsgHandler->processNotification(NFC_NOTIFICATION_TECH_LOST, NULL); } void NfcService::handleLlcpLinkActivation(NfcEvent* event) { ALOGD("%s: enter", FUNC); void* pDevice = event->obj; IP2pDevice* pIP2pDevice = reinterpret_cast<IP2pDevice*>(pDevice); if (pIP2pDevice->getMode() == NfcDepEndpoint::MODE_P2P_TARGET || pIP2pDevice->getMode() == NfcDepEndpoint::MODE_P2P_INITIATOR) { if (pIP2pDevice->getMode() == NfcDepEndpoint::MODE_P2P_TARGET) { if (pIP2pDevice->connect()) { ALOGD("%s: Connected to device!", FUNC); } else { ALOGE("%s: Cannot connect remote Target. Polling loop restarted.", FUNC); } } INfcManager* pINfcManager = NfcService::getNfcManager(); bool ret = pINfcManager->checkLlcp(); if (ret == true) { ret = pINfcManager->activateLlcp(); if (ret == true) { ALOGD("%s: Target Activate LLCP OK", FUNC); } else { ALOGE("%s: doActivateLLcp failed", FUNC); } } else { ALOGE("%s: doCheckLLcp failed", FUNC); } } else { ALOGE("%s: Unknown LLCP P2P mode", FUNC); //stop(); } mP2pLinkManager->onLlcpActivated(); TechDiscoveredEvent* data = new TechDiscoveredEvent(); data->sessionId = SessionId::generateNewId(); data->techCount = 1; uint8_t techs[] = { NFC_TECH_P2P }; data->techList = &techs; data->ndefMsgCount = 0; data->ndefMsg = NULL; mMsgHandler->processNotification(NFC_NOTIFICATION_TECH_DISCOVERED, data); delete data; ALOGD("%s: exit", FUNC); } static void *pollingThreadFunc(void *arg) { PollingThreadParam* param = reinterpret_cast<PollingThreadParam*>(arg); INfcTag* pINfcTag = param->pINfcTag; int sessionId = param->sessionId; // TODO : check if check tag presence here is correct // For android. it use startPresenceChecking API in INfcTag.java while (pINfcTag->presenceCheck()) { sleep(1); } pINfcTag->disconnect(); NfcService::Instance()->notifyTagLost(sessionId); delete param; return NULL; } void NfcService::handleTagDiscovered(NfcEvent* event) { void* pTag = event->obj; INfcTag* pINfcTag = reinterpret_cast<INfcTag*>(pTag); // To get complete tag information, need to call read ndef first. // In readNdef function, it will add NDEF related info in NfcTagManager. NdefMessage* pNdefMessage = pINfcTag->readNdef(); // Do the following after read ndef. std::vector<TagTechnology>& techList = pINfcTag->getTechList(); int techCount = techList.size(); uint8_t* gonkTechList = new uint8_t[techCount]; for(int i = 0; i < techCount; i++) { gonkTechList[i] = (uint8_t)NfcUtil::convertTagTechToGonkFormat(techList[i]); } TechDiscoveredEvent* data = new TechDiscoveredEvent(); data->sessionId = SessionId::generateNewId(); data->techCount = techCount; data->techList = gonkTechList; data->ndefMsgCount = pNdefMessage ? 1 : 0; data->ndefMsg = pNdefMessage; mMsgHandler->processNotification(NFC_NOTIFICATION_TECH_DISCOVERED, data); PollingThreadParam* param = new PollingThreadParam(); param->sessionId = data->sessionId; param->pINfcTag = pINfcTag; delete gonkTechList; delete data; pthread_t tid; pthread_create(&tid, NULL, pollingThreadFunc, param); } void NfcService::handleTagLost(NfcEvent* event) { mMsgHandler->processNotification(NFC_NOTIFICATION_TECH_LOST, event->obj); } void NfcService::handleTransactionEvent(NfcEvent* event) { mMsgHandler->processNotification(NFC_NOTIFICATION_TRANSACTION_EVENT, event->obj); } void* NfcService::eventLoop() { ALOGD("%s: NFCService started", FUNC); while(true) { if(sem_wait(&thread_sem)) { ALOGE("%s: Failed to wait for semaphore", FUNC); abort(); } while (!mQueue.empty()) { NfcEvent* event = *mQueue.begin(); mQueue.erase(mQueue.begin()); NfcEventType eventType = event->getType(); ALOGD("%s: NFCService msg=%d", FUNC, eventType); switch(eventType) { case MSG_LLCP_LINK_ACTIVATION: handleLlcpLinkActivation(event); break; case MSG_LLCP_LINK_DEACTIVATION: handleLlcpLinkDeactivation(event); break; case MSG_TAG_DISCOVERED: handleTagDiscovered(event); break; case MSG_TAG_LOST: handleTagLost(event); break; case MSG_SE_NOTIFY_TRANSACTION_EVENT: handleTransactionEvent(event); break; case MSG_CONFIG: handleConfigResponse(event); break; case MSG_READ_NDEF_DETAIL: handleReadNdefDetailResponse(event); break; case MSG_READ_NDEF: handleReadNdefResponse(event); break; case MSG_WRITE_NDEF: handleWriteNdefResponse(event); break; case MSG_CLOSE: handleCloseResponse(event); break; case MSG_SOCKET_CONNECTED: mMsgHandler->processNotification(NFC_NOTIFICATION_INITIALIZED , NULL); break; case MSG_PUSH_NDEF: handlePushNdefResponse(event); break; case MSG_MAKE_NDEF_READONLY: handleMakeNdefReadonlyResponse(event); break; case MSG_LOW_POWER: handleEnterLowPowerResponse(event); break; case MSG_ENABLE: handleEnableResponse(event); break; case MSG_RECEIVE_NDEF_EVENT: handleReceiveNdefEvent(event); break; default: ALOGE("%s: NFCService bad message", FUNC); abort(); } //TODO delete event->data? delete event; } } } NfcService* NfcService::Instance() { if (!sInstance) sInstance = new NfcService(); return sInstance; } INfcManager* NfcService::getNfcManager() { return reinterpret_cast<INfcManager*>(NfcService::sNfcManager); } bool NfcService::handleDisconnect() { INfcTag* pINfcTag = reinterpret_cast<INfcTag*> (sNfcManager->queryInterface(INTERFACE_TAG_MANAGER)); bool result = pINfcTag->disconnect(); return result; } void NfcService::handleConnect(int tech) { INfcTag* pINfcTag = reinterpret_cast<INfcTag*> (sNfcManager->queryInterface(INTERFACE_TAG_MANAGER)); NfcErrorCode code = !!pINfcTag ? (pINfcTag->connect(tech) ? NFC_SUCCESS : NFC_ERROR_CONNECT) : NFC_ERROR_NOT_SUPPORTED; mMsgHandler->processResponse(NFC_RESPONSE_GENERAL, code, NULL); } bool NfcService::handleConfigRequest(int powerLevel) { NfcEvent *event = new NfcEvent(MSG_CONFIG); mQueue.push_back(event); sem_post(&thread_sem); return true; } bool NfcService::handleReadNdefDetailRequest() { NfcEvent *event = new NfcEvent(MSG_READ_NDEF_DETAIL); mQueue.push_back(event); sem_post(&thread_sem); return true; } void NfcService::handleConfigResponse(NfcEvent* event) { mMsgHandler->processResponse(NFC_RESPONSE_CONFIG, NFC_SUCCESS, NULL); } void NfcService::handleReadNdefDetailResponse(NfcEvent* event) { NfcResponseType resType = NFC_RESPONSE_READ_NDEF_DETAILS; INfcTag* pINfcTag = reinterpret_cast<INfcTag*> (sNfcManager->queryInterface(INTERFACE_TAG_MANAGER)); if (!pINfcTag) { mMsgHandler->processResponse(resType, NFC_ERROR_NOT_SUPPORTED, NULL); return; } std::auto_ptr<NdefDetail> pNdefDetail(pINfcTag->readNdefDetail()); if (!pNdefDetail.get()) { mMsgHandler->processResponse(resType, NFC_ERROR_READ, NULL); return; } mMsgHandler->processResponse(resType, NFC_SUCCESS, pNdefDetail.get()); } bool NfcService::handleReadNdefRequest() { NfcEvent *event = new NfcEvent(MSG_READ_NDEF); mQueue.push_back(event); sem_post(&thread_sem); return true; } void NfcService::handleReadNdefResponse(NfcEvent* event) { NfcResponseType resType = NFC_RESPONSE_READ_NDEF; INfcTag* pINfcTag = reinterpret_cast<INfcTag*>(sNfcManager->queryInterface(INTERFACE_TAG_MANAGER)); if (!pINfcTag) { mMsgHandler->processResponse(resType, NFC_ERROR_NOT_SUPPORTED, NULL); return; } std::auto_ptr<NdefMessage> pNdefMessage(pINfcTag->readNdef()); if (!pNdefMessage.get()) { mMsgHandler->processResponse(resType, NFC_ERROR_READ, NULL); return; } mMsgHandler->processResponse(resType, NFC_SUCCESS, pNdefMessage.get()); } void NfcService::handleReceiveNdefEvent(NfcEvent* event) { NdefMessage* ndef = reinterpret_cast<NdefMessage*>(event->obj); TechDiscoveredEvent* data = new TechDiscoveredEvent(); data->sessionId = SessionId::getCurrentId(); data->techCount = 2; uint8_t techs[] = { NFC_TECH_P2P, NFC_TECH_NDEF }; data->techList = &techs; data->ndefMsgCount = ndef ? 1 : 0; data->ndefMsg = ndef; mMsgHandler->processNotification(NFC_NOTIFICATION_TECH_DISCOVERED, data); delete data; delete ndef; } bool NfcService::handleWriteNdefRequest(NdefMessage* ndef) { NfcEvent *event = new NfcEvent(MSG_WRITE_NDEF); event->obj = ndef; mQueue.push_back(event); sem_post(&thread_sem); return true; } void NfcService::handleWriteNdefResponse(NfcEvent* event) { NfcResponseType resType = NFC_RESPONSE_GENERAL; NfcErrorCode code = NFC_SUCCESS; std::auto_ptr<NdefMessage> pNdef(reinterpret_cast<NdefMessage*>(event->obj)); if (!pNdef.get()) { mMsgHandler->processResponse(resType, NFC_ERROR_INVALID_PARAM, NULL); return; } // Use single API wirte to send data. // nfcd check current connection is p2p or tag. if (mP2pLinkManager->isLlcpActive()) { mP2pLinkManager->push(*pNdef.get()); } else { INfcTag* pINfcTag = reinterpret_cast<INfcTag*> (sNfcManager->queryInterface(INTERFACE_TAG_MANAGER)); code = !!pINfcTag ? (pINfcTag->writeNdef(*pNdef.get()) ? NFC_SUCCESS : NFC_ERROR_IO) : NFC_ERROR_NOT_SUPPORTED; } mMsgHandler->processResponse(resType, code, NULL); } void NfcService::handleCloseRequest() { NfcEvent *event = new NfcEvent(MSG_CLOSE); mQueue.push_back(event); sem_post(&thread_sem); } void NfcService::handleCloseResponse(NfcEvent* event) { // TODO : If we call tag disconnect here, will keep trggering tag discover notification // Need to check with DT what should we do here mMsgHandler->processResponse(NFC_RESPONSE_GENERAL, NFC_SUCCESS, NULL); } void NfcService::onConnected() { NfcEvent *event = new NfcEvent(MSG_SOCKET_CONNECTED); mQueue.push_back(event); sem_post(&thread_sem); } bool NfcService::handlePushNdefRequest(NdefMessage* ndef) { NfcEvent *event = new NfcEvent(MSG_PUSH_NDEF); event->obj = ndef; mQueue.push_back(event); sem_post(&thread_sem); return true; } void NfcService::handlePushNdefResponse(NfcEvent* event) { NfcResponseType resType = NFC_RESPONSE_GENERAL; std::auto_ptr<NdefMessage> pNdef(reinterpret_cast<NdefMessage*>(event->obj)); if (!pNdef.get()) { mMsgHandler->processResponse(resType, NFC_ERROR_INVALID_PARAM, NULL); return; } mP2pLinkManager->push(*pNdef.get()); mMsgHandler->processResponse(resType, NFC_SUCCESS, NULL); } bool NfcService::handleMakeNdefReadonlyRequest() { NfcEvent *event = new NfcEvent(MSG_MAKE_NDEF_READONLY); mQueue.push_back(event); sem_post(&thread_sem); return true; } void NfcService::handleMakeNdefReadonlyResponse(NfcEvent* event) { INfcTag* pINfcTag = reinterpret_cast<INfcTag*> (sNfcManager->queryInterface(INTERFACE_TAG_MANAGER)); NfcErrorCode code = !!pINfcTag ? (pINfcTag->makeReadOnly() ? NFC_SUCCESS : NFC_ERROR_IO) : NFC_ERROR_NOT_SUPPORTED; mMsgHandler->processResponse(NFC_RESPONSE_GENERAL, code, NULL); } bool NfcService::handleEnterLowPowerRequest(bool enter) { NfcEvent *event = new NfcEvent(MSG_LOW_POWER); event->arg1 = enter; mQueue.push_back(event); sem_post(&thread_sem); return true; } void NfcService::handleEnterLowPowerResponse(NfcEvent* event) { bool low = event->arg1; NfcErrorCode code = setLowPowerMode(low); mMsgHandler->processResponse(NFC_RESPONSE_CONFIG, code, NULL); } bool NfcService::handleEnableRequest(bool enable) { NfcEvent *event = new NfcEvent(MSG_ENABLE); event->arg1 = enable; mQueue.push_back(event); sem_post(&thread_sem); return true; } /** * There are two case for enable: * 1. NFC is off -> enable NFC and then enable discovery. * 2. NFC is already on but discovery mode is off -> enable discovery. */ void NfcService::handleEnableResponse(NfcEvent* event) { NfcErrorCode code = NFC_SUCCESS; bool enable = event->arg1; if (enable) { // Disable low power mode if already in low power mode if (mState == STATE_NFC_ON_LOW_POWER) { code = setLowPowerMode(false); } else if (mState == STATE_NFC_OFF) { code = enableNfc(); if (code != NFC_SUCCESS) { goto TheEnd; } code = enableSE(); } } else { code = disableSE(); if (code != NFC_SUCCESS) { goto TheEnd; } code = disableNfc(); } TheEnd: mMsgHandler->processResponse(NFC_RESPONSE_CONFIG, code, NULL); } NfcErrorCode NfcService::enableNfc() { ALOGD("Enable NFC"); if (mState != STATE_NFC_OFF) { return NFC_SUCCESS; } if (!sNfcManager->initialize()) { return NFC_ERROR_INITIALIZE_FAIL; } if (mP2pLinkManager) { mP2pLinkManager->enableDisable(true); } if (!sNfcManager->enableDiscovery()) { return NFC_ERROR_FAIL_ENABLE_DISCOVERY; } mState = STATE_NFC_ON; return NFC_SUCCESS; } NfcErrorCode NfcService::disableNfc() { ALOGD("Disable NFC"); if (mState == STATE_NFC_OFF) { return NFC_SUCCESS; } if (mP2pLinkManager) { mP2pLinkManager->enableDisable(false); } if (!sNfcManager->deinitialize()) { return NFC_ERROR_DEINITIALIZE_FAIL; } if (!sNfcManager->disableDiscovery()) { return NFC_ERROR_FAIL_DISABLE_DISCOVERY; } mState = STATE_NFC_OFF; return NFC_SUCCESS; } NfcErrorCode NfcService::setLowPowerMode(bool low) { if ((low && mState != STATE_NFC_ON) || (!low && mState == STATE_NFC_ON)) { return NFC_SUCCESS; } if (low) { if (!sNfcManager->disableP2pListening() || !sNfcManager->disablePolling()) { return NFC_ERROR_FAIL_ENABLE_LOW_POWER_MODE; } mState = STATE_NFC_ON_LOW_POWER; } else { if (!sNfcManager->enableP2pListening() || !sNfcManager->enablePolling()) { return NFC_ERROR_FAIL_DISABLE_LOW_POWER_MODE; } mState = STATE_NFC_ON; } return NFC_SUCCESS; } // TODO: Emulator doesn't support SE now. // So always return sucess to pass testcase. NfcErrorCode NfcService::enableSE() { ALOGD("Enable secure element"); if (!sNfcManager->doSelectSecureElement()) { ALOGE("Enable secure element fail"); } return NFC_SUCCESS; } // TODO: Emulator doesn't support SE now. // So always return sucess to pass testcase. NfcErrorCode NfcService::disableSE() { ALOGD("Disable secure element"); if (!sNfcManager->doDeselectSecureElement()) { ALOGE("Disable secure element fail"); } return NFC_SUCCESS; } void NfcService::onP2pReceivedNdef(NdefMessage* ndef) { NfcEvent *event = new NfcEvent(MSG_RECEIVE_NDEF_EVENT); event->obj = ndef ? new NdefMessage(ndef) : NULL; mQueue.push_back(event); sem_post(&thread_sem); } <file_sep>/src/nci/NfcTagManager.cpp /* * Copyright (C) 2014 Mozilla Foundation * * 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. */ #include "NfcTagManager.h" #include <semaphore.h> #include <errno.h> #include <time.h> #include <signal.h> #include "NdefMessage.h" #include "TagTechnology.h" #include "NfcUtil.h" #include "NfcTag.h" #include "config.h" #include "Mutex.h" #include "IntervalTimer.h" #include "Pn544Interop.h" extern "C" { #include "nfa_api.h" #include "nfa_rw_api.h" #include "ndef_utils.h" #include "rw_api.h" } #undef LOG_TAG #define LOG_TAG "NfcNci" #include <cutils/log.h> extern bool nfcManager_isNfcActive(); extern int gGeneralTransceiveTimeout; // Flag for nfa callback indicating we are deactivating for RF interface switch. bool gIsTagDeactivating = false; // Flag for nfa callback indicating we are selecting for RF interface switch. bool gIsSelectingRfInterface = false; // Pre-defined tag type values. These must match the values in // framework Ndef.java for Google public NFC API. #define NDEF_UNKNOWN_TYPE -1 #define NDEF_TYPE1_TAG 1 #define NDEF_TYPE2_TAG 2 #define NDEF_TYPE3_TAG 3 #define NDEF_TYPE4_TAG 4 #define NDEF_MIFARE_CLASSIC_TAG 101 #define STATUS_CODE_TARGET_LOST 146 // This error code comes from the service. static uint32_t sCheckNdefCurrentSize = 0; static tNFA_STATUS sCheckNdefStatus = 0; // Whether tag already contains a NDEF message. static bool sCheckNdefCapable = false; // Whether tag has NDEF capability. static tNFA_HANDLE sNdefTypeHandlerHandle = NFA_HANDLE_INVALID; static tNFA_INTF_TYPE sCurrentRfInterface = NFA_INTERFACE_ISO_DEP; static uint8_t* sTransceiveData = NULL; static uint32_t sTransceiveDataLen = 0; static bool sWaitingForTransceive = false; static bool sNeedToSwitchRf = false; static Mutex sRfInterfaceMutex; static uint32_t sReadDataLen = 0; static uint8_t* sReadData = NULL; static bool sIsReadingNdefMessage = false; static SyncEvent sReadEvent; static sem_t sWriteSem; static sem_t sFormatSem; static SyncEvent sTransceiveEvent; static SyncEvent sReconnectEvent; static sem_t sCheckNdefSem; static sem_t sPresenceCheckSem; static sem_t sMakeReadonlySem; static IntervalTimer sSwitchBackTimer; // Timer used to tell us to switch back to ISO_DEP frame interface. static bool sWriteOk = false; static bool sWriteWaitingForComplete = false; static bool sFormatOk = false; static bool sConnectOk = false; static bool sConnectWaitingForComplete = false; static bool sGotDeactivate = false; static uint32_t sCheckNdefMaxSize = 0; static bool sCheckNdefCardReadOnly = false; static bool sCheckNdefWaitingForComplete = false; static int sCountTagAway = 0; // Count the consecutive number of presence-check failures. static tNFA_STATUS sMakeReadonlyStatus = NFA_STATUS_FAILED; static bool sMakeReadonlyWaitingForComplete = false; static void ndefHandlerCallback(tNFA_NDEF_EVT event, tNFA_NDEF_EVT_DATA *eventData) { ALOGD("%s: event=%u, eventData=%p", __FUNCTION__, event, eventData); switch (event) { case NFA_NDEF_REGISTER_EVT: { tNFA_NDEF_REGISTER& ndef_reg = eventData->ndef_reg; ALOGD("%s: NFA_NDEF_REGISTER_EVT; status=0x%X; h=0x%X", __FUNCTION__, ndef_reg.status, ndef_reg.ndef_type_handle); sNdefTypeHandlerHandle = ndef_reg.ndef_type_handle; break; } case NFA_NDEF_DATA_EVT: { ALOGD("%s: NFA_NDEF_DATA_EVT; data_len = %lu", __FUNCTION__, eventData->ndef_data.len); sReadDataLen = eventData->ndef_data.len; sReadData = (uint8_t*) malloc(sReadDataLen); memcpy(sReadData, eventData->ndef_data.p_data, eventData->ndef_data.len); break; } default: ALOGE("%s: Unknown event %u ????", __FUNCTION__, event); break; } } NfcTagManager::NfcTagManager() { pthread_mutex_init(&mMutex, NULL); } NfcTagManager::~NfcTagManager() { } NdefDetail* NfcTagManager::doReadNdefDetail() { int ndefinfo[2]; int status; NdefDetail* pNdefDetail = NULL; status = doCheckNdef(ndefinfo); if (status != 0) { ALOGE("%s: Check NDEF Failed - status = %d", __FUNCTION__, status); } else { int ndefType = getNdefType(getConnectedLibNfcType()); pNdefDetail = new NdefDetail(); pNdefDetail->maxSupportedLength = ndefinfo[0]; pNdefDetail->isReadOnly = (ndefinfo[1] == NDEF_MODE_READ_ONLY); pNdefDetail->canBeMadeReadOnly = (ndefType == NDEF_TYPE1_TAG || ndefType == NDEF_TYPE2_TAG); } return pNdefDetail; } NdefMessage* NfcTagManager::doReadNdef() { NdefMessage* ndefMsg = NULL; bool foundFormattable = false; int formattableHandle = 0; int formattableLibNfcType = 0; int status; for(uint32_t techIndex = 0; techIndex < mTechList.size(); techIndex++) { // Have we seen this handle before? for (uint32_t i = 0; i < techIndex; i++) { if (mTechHandles[i] == mTechHandles[techIndex]) { continue; // Don't check duplicate handles. } } status = connectWithStatus(mTechList[techIndex]); if (status != 0) { ALOGE("%s: Connect Failed - status = %d", __FUNCTION__, status); if (status == STATUS_CODE_TARGET_LOST) { break; } continue; // Try next handle. } else { ALOGI("Connect Succeeded! (status = %d)", status); } // Check if this type is NDEF formatable if (!foundFormattable) { if (doIsNdefFormatable()) { foundFormattable = true; formattableHandle = getConnectedHandle(); formattableLibNfcType = getConnectedLibNfcType(); // We'll only add formattable tech if no ndef is // found - this is because libNFC refuses to format // an already NDEF formatted tag. } // TODO : check why Android call reconnect here //reconnect(); } int ndefinfo[2]; status = doCheckNdef(ndefinfo); if (status != 0) { ALOGE("%s: Check NDEF Failed - status = %d", __FUNCTION__, status); if (status == STATUS_CODE_TARGET_LOST) { break; } continue; // Try next handle. } else { ALOGI("Check Succeeded! (status = %d)", status); } // Found our NDEF handle. bool generateEmptyNdef = false; int supportedNdefLength = ndefinfo[0]; int cardState = ndefinfo[1]; std::vector<uint8_t> buf; doRead(buf); if (buf.size() != 0) { ndefMsg = new NdefMessage(); if (ndefMsg->init(buf)) { addTechnology(NDEF, getConnectedHandle(), getConnectedLibNfcType()); // TODO : check why android call reconnect here //reconnect(); } else { generateEmptyNdef = true; } } else { generateEmptyNdef = true; } if (cardState == NDEF_MODE_READ_WRITE) { addTechnology(NDEF_WRITABLE, getConnectedHandle(), getConnectedLibNfcType()); } if (generateEmptyNdef == true) { delete ndefMsg; ndefMsg = NULL; addTechnology(NDEF, getConnectedHandle(), getConnectedLibNfcType()); //reconnect(); } break; } if (!ndefMsg && foundFormattable) { // Tag is not NDEF yet, and found a formattable target, // so add formattable tech to tech list. addTechnology(NDEF_FORMATABLE, formattableHandle, formattableLibNfcType); } return ndefMsg; } int NfcTagManager::reconnectWithStatus() { ALOGD("%s: enter", __FUNCTION__); int retCode = NFCSTATUS_SUCCESS; NfcTag& natTag = NfcTag::getInstance(); if (natTag.getActivationState() != NfcTag::Active) { ALOGD("%s: tag already deactivated", __FUNCTION__); retCode = NFCSTATUS_FAILED; goto TheEnd; } // Special case for Kovio. if (NfcTag::getInstance().mTechList [0] == TARGET_TYPE_KOVIO_BARCODE) { ALOGD("%s: fake out reconnect for Kovio", __FUNCTION__); goto TheEnd; } // This is only supported for type 2 or 4 (ISO_DEP) tags. if (natTag.mTechLibNfcTypes[0] == NFA_PROTOCOL_ISO_DEP) retCode = reSelect(NFA_INTERFACE_ISO_DEP); else if (natTag.mTechLibNfcTypes[0] == NFA_PROTOCOL_T2T) retCode = reSelect(NFA_INTERFACE_FRAME); TheEnd: ALOGD("%s: exit 0x%X", __FUNCTION__, retCode); return retCode; } int NfcTagManager::reconnectWithStatus(int technology) { int status = -1; status = doConnect(technology); return status; } int NfcTagManager::connectWithStatus(int technology) { int status = -1; for (uint32_t i = 0; i < mTechList.size(); i++) { if (mTechList[i] == technology) { // Get the handle and connect, if not already connected. if (mConnectedHandle != mTechHandles[i]) { // We're not yet connected, there are a few scenario's // here: // 1) We are not connected to anything yet - allow // 2) We are connected to a technology which has // a different handle (multi-protocol tag); we support // switching to that. // 3) We are connected to a technology which has the same // handle; we do not support connecting at a different // level (libnfc auto-activates to the max level on // any handle). // 4) We are connecting to the ndef technology - always // allowed. if (mConnectedHandle == -1) { // Not connected yet. status = doConnect(i); } else { // Connect to a tech with a different handle. ALOGD("%s: Connect to a tech with a different handle", __FUNCTION__); status = reconnectWithStatus(i); } if (status == 0) { mConnectedHandle = mTechHandles[i]; mConnectedTechIndex = i; } } else { // 1) We are connected to a technology which has the same // handle; we do not support connecting at a different // level (libnfc auto-activates to the max level on // any handle). // 2) We are connecting to the ndef technology - always // allowed. if ((technology == NDEF) || (technology == NDEF_FORMATABLE)) { i = 0; } status = reconnectWithStatus(i); if (status == 0) { mConnectedTechIndex = i; } } break; } } return status; } void NfcTagManager::doRead(std::vector<uint8_t>& buf) { ALOGD("%s: enter", __FUNCTION__); tNFA_STATUS status = NFA_STATUS_FAILED; sReadDataLen = 0; if (sReadData != NULL) { free(sReadData); sReadData = NULL; } if (sCheckNdefCurrentSize > 0) { { SyncEventGuard g(sReadEvent); sIsReadingNdefMessage = true; status = NFA_RwReadNDef(); sReadEvent.wait(); // Wait for NFA_READ_CPLT_EVT. } sIsReadingNdefMessage = false; if (sReadDataLen > 0) { // If stack actually read data from the tag. ALOGD("%s: read %u bytes", __FUNCTION__, sReadDataLen); for(uint32_t idx = 0; idx < sReadDataLen; idx++) { buf.push_back(sReadData[idx]); } } } else { ALOGD("%s: create emtpy buffer", __FUNCTION__); sReadDataLen = 0; sReadData = (uint8_t*) malloc(1); buf.push_back(sReadData[0]); } if (sReadData) { free(sReadData); sReadData = NULL; } sReadDataLen = 0; ALOGD("%s: exit", __FUNCTION__); return; } void NfcTagManager::doWriteStatus(bool isWriteOk) { if (sWriteWaitingForComplete != false) { sWriteWaitingForComplete = false; sWriteOk = isWriteOk; sem_post(&sWriteSem); } } int NfcTagManager::doCheckNdef(int ndefInfo[]) { tNFA_STATUS status = NFA_STATUS_FAILED; ALOGD("%s: enter", __FUNCTION__); // Special case for Kovio. if (NfcTag::getInstance().mTechList [0] == TARGET_TYPE_KOVIO_BARCODE) { ALOGD("%s: Kovio tag, no NDEF", __FUNCTION__); ndefInfo[0] = 0; ndefInfo[1] = NDEF_MODE_READ_ONLY; return NFA_STATUS_FAILED; } // Special case for Kovio. if (NfcTag::getInstance().mTechList [0] == TARGET_TYPE_KOVIO_BARCODE) { ALOGD("%s: Kovio tag, no NDEF", __FUNCTION__); ndefInfo[0] = 0; ndefInfo[1] = NDEF_MODE_READ_ONLY; return NFA_STATUS_FAILED; } // Create the write semaphore. if (sem_init(&sCheckNdefSem, 0, 0) == -1) { ALOGE("%s: Check NDEF semaphore creation failed (errno=0x%08x)", __FUNCTION__, errno); return false; } if (NfcTag::getInstance().getActivationState() != NfcTag::Active) { ALOGE("%s: tag already deactivated", __FUNCTION__); goto TheEnd; } ALOGD("%s: try NFA_RwDetectNDef", __FUNCTION__); sCheckNdefWaitingForComplete = true; status = NFA_RwDetectNDef(); if (status != NFA_STATUS_OK) { ALOGE("%s: NFA_RwDetectNDef failed, status = 0x%X", __FUNCTION__, status); goto TheEnd; } // Wait for check NDEF completion status. if (sem_wait(&sCheckNdefSem)) { ALOGE("%s: Failed to wait for check NDEF semaphore (errno=0x%08x)", __FUNCTION__, errno); goto TheEnd; } if (sCheckNdefStatus == NFA_STATUS_OK) { // Stack found a NDEF message on the tag. if (NfcTag::getInstance().getProtocol() == NFA_PROTOCOL_T1T) ndefInfo[0] = NfcTag::getInstance().getT1tMaxMessageSize(); else ndefInfo[0] = sCheckNdefMaxSize; if (sCheckNdefCardReadOnly) ndefInfo[1] = NDEF_MODE_READ_ONLY; else ndefInfo[1] = NDEF_MODE_READ_WRITE; status = NFA_STATUS_OK; } else if (sCheckNdefStatus == NFA_STATUS_FAILED) { // Stack did not find a NDEF message on the tag. if (NfcTag::getInstance().getProtocol() == NFA_PROTOCOL_T1T) ndefInfo[0] = NfcTag::getInstance().getT1tMaxMessageSize(); else ndefInfo[0] = sCheckNdefMaxSize; if (sCheckNdefCardReadOnly) ndefInfo[1] = NDEF_MODE_READ_ONLY; else ndefInfo[1] = NDEF_MODE_READ_WRITE; status = NFA_STATUS_FAILED; } else if (sCheckNdefStatus == NFA_STATUS_TIMEOUT) { pn544InteropStopPolling(); status = sCheckNdefStatus; } else { ALOGD("%s: unknown status 0x%X", __FUNCTION__, sCheckNdefStatus); status = sCheckNdefStatus; } TheEnd: // Destroy semaphore. if (sem_destroy(&sCheckNdefSem)) { ALOGE("%s: Failed to destroy check NDEF semaphore (errno=0x%08x)", __FUNCTION__, errno); } sCheckNdefWaitingForComplete = false; ALOGD("%s: exit; status=0x%X", __FUNCTION__, status); return status; } void NfcTagManager::doAbortWaits() { ALOGD("%s", __FUNCTION__); { SyncEventGuard g(sReadEvent); sReadEvent.notifyOne(); } sem_post(&sWriteSem); sem_post(&sFormatSem); { SyncEventGuard g(sTransceiveEvent); sTransceiveEvent.notifyOne(); } { SyncEventGuard g (sReconnectEvent); sReconnectEvent.notifyOne(); } sem_post(&sCheckNdefSem); sem_post(&sPresenceCheckSem); sem_post(&sMakeReadonlySem); } void NfcTagManager::doReadCompleted(tNFA_STATUS status) { ALOGD("%s: status=0x%X; is reading=%u", __FUNCTION__, status, sIsReadingNdefMessage); if (sIsReadingNdefMessage == false) return; // Not reading NDEF message right now, so just return. if (status != NFA_STATUS_OK) { sReadDataLen = 0; if (sReadData) free (sReadData); sReadData = NULL; } SyncEventGuard g(sReadEvent); sReadEvent.notifyOne(); } void NfcTagManager::doConnectStatus(bool isConnectOk) { if (sConnectWaitingForComplete != false) { sConnectWaitingForComplete = false; sConnectOk = isConnectOk; SyncEventGuard g(sReconnectEvent); sReconnectEvent.notifyOne(); } } void NfcTagManager::doDeactivateStatus(int status) { sGotDeactivate = (status == 0); SyncEventGuard g(sReconnectEvent); sReconnectEvent.notifyOne(); } void NfcTagManager::doResetPresenceCheck() { sCountTagAway = 0; } void NfcTagManager::doPresenceCheckResult(tNFA_STATUS status) { if (status == NFA_STATUS_OK) sCountTagAway = 0; else sCountTagAway++; if (sCountTagAway > 0) ALOGD("%s: sCountTagAway=%d", __FUNCTION__, sCountTagAway); sem_post(&sPresenceCheckSem); } bool NfcTagManager::doNdefFormat() { ALOGD("%s: enter", __FUNCTION__); tNFA_STATUS status = NFA_STATUS_OK; sem_init(&sFormatSem, 0, 0); sFormatOk = false; status = NFA_RwFormatTag(); if (status == NFA_STATUS_OK) { ALOGD("%s: wait for completion", __FUNCTION__); sem_wait(&sFormatSem); status = sFormatOk ? NFA_STATUS_OK : NFA_STATUS_FAILED; } else { ALOGE("%s: error status=%u", __FUNCTION__, status); } sem_destroy(&sFormatSem); ALOGD("%s: exit", __FUNCTION__); return status == NFA_STATUS_OK; } void NfcTagManager::doCheckNdefResult(tNFA_STATUS status, uint32_t maxSize, uint32_t currentSize, uint8_t flags) { // This function's flags parameter is defined using the following macros // in nfc/include/rw_api.h; // #define RW_NDEF_FL_READ_ONLY 0x01 /* Tag is read only */ // #define RW_NDEF_FL_FORMATED 0x02 /* Tag formated for NDEF */ // #define RW_NDEF_FL_SUPPORTED 0x04 /* NDEF supported by the tag */ // #define RW_NDEF_FL_UNKNOWN 0x08 /* Unable to find if tag is ndef capable/formated/read only */ // #define RW_NDEF_FL_FORMATABLE 0x10 /* Tag supports format operation */ if (status == NFC_STATUS_BUSY) { ALOGE("%s: stack is busy", __FUNCTION__); return; } if (!sCheckNdefWaitingForComplete) { ALOGE("%s: not waiting", __FUNCTION__); return; } if (flags & RW_NDEF_FL_READ_ONLY) ALOGD("%s: flag read-only", __FUNCTION__); if (flags & RW_NDEF_FL_FORMATED) ALOGD("%s: flag formatted for ndef", __FUNCTION__); if (flags & RW_NDEF_FL_SUPPORTED) ALOGD("%s: flag ndef supported", __FUNCTION__); if (flags & RW_NDEF_FL_UNKNOWN) ALOGD("%s: flag all unknown", __FUNCTION__); if (flags & RW_NDEF_FL_FORMATABLE) ALOGD("%s: flag formattable", __FUNCTION__); sCheckNdefWaitingForComplete = false; sCheckNdefStatus = status; sCheckNdefCapable = false; // Assume tag is NOT ndef capable. if (sCheckNdefStatus == NFA_STATUS_OK) { // NDEF content is on the tag. sCheckNdefMaxSize = maxSize; sCheckNdefCurrentSize = currentSize; sCheckNdefCardReadOnly = flags & RW_NDEF_FL_READ_ONLY; sCheckNdefCapable = true; } else if (sCheckNdefStatus == NFA_STATUS_FAILED) { // No NDEF content on the tag. sCheckNdefMaxSize = 0; sCheckNdefCurrentSize = 0; sCheckNdefCardReadOnly = flags & RW_NDEF_FL_READ_ONLY; if ((flags & RW_NDEF_FL_UNKNOWN) == 0) { // If stack understands the tag. if (flags & RW_NDEF_FL_SUPPORTED) { // If tag is ndef capable. sCheckNdefCapable = true; } } } else { ALOGE("%s: unknown status=0x%X", __FUNCTION__, status); sCheckNdefMaxSize = 0; sCheckNdefCurrentSize = 0; sCheckNdefCardReadOnly = false; } sem_post(&sCheckNdefSem); } void NfcTagManager::doMakeReadonlyResult(tNFA_STATUS status) { if (sMakeReadonlyWaitingForComplete != false) { sMakeReadonlyWaitingForComplete = false; sMakeReadonlyStatus = status; sem_post(&sMakeReadonlySem); } } bool NfcTagManager::doMakeReadonly() { bool result = false; tNFA_STATUS status; ALOGD("%s", __FUNCTION__); // Create the make_readonly semaphore. if (sem_init(&sMakeReadonlySem, 0, 0) == -1) { ALOGE("%s: Make readonly semaphore creation failed (errno=0x%08x)", __FUNCTION__, errno); return false; } sMakeReadonlyWaitingForComplete = true; // Hard-lock the tag (cannot be reverted). status = NFA_RwSetTagReadOnly(true); if (status != NFA_STATUS_OK) { ALOGE("%s: NFA_RwSetTagReadOnly failed, status = %d", __FUNCTION__, status); goto TheEnd; } // Wait for check NDEF completion status. if (sem_wait(&sMakeReadonlySem)) { ALOGE("%s: Failed to wait for make_readonly semaphore (errno=0x%08x)", __FUNCTION__, errno); goto TheEnd; } if (sMakeReadonlyStatus == NFA_STATUS_OK) { result = true; } TheEnd: // Destroy semaphore. if (sem_destroy(&sMakeReadonlySem)) { ALOGE("%s: Failed to destroy read_only semaphore (errno=0x%08x)", __FUNCTION__, errno); } sMakeReadonlyWaitingForComplete = false; return result; } // Register a callback to receive NDEF message from the tag // from the NFA_NDEF_DATA_EVT. void NfcTagManager::doRegisterNdefTypeHandler() { ALOGD("%s", __FUNCTION__); sNdefTypeHandlerHandle = NFA_HANDLE_INVALID; NFA_RegisterNDefTypeHandler(TRUE, NFA_TNF_DEFAULT, (UINT8 *) "", 0, ndefHandlerCallback); } void NfcTagManager::doDeregisterNdefTypeHandler() { ALOGD("%s", __FUNCTION__); NFA_DeregisterNDefTypeHandler(sNdefTypeHandlerHandle); sNdefTypeHandlerHandle = NFA_HANDLE_INVALID; } int NfcTagManager::doConnect(int targetHandle) { ALOGD("%s: targetHandle = %d", __FUNCTION__, targetHandle); int i = targetHandle; NfcTag& natTag = NfcTag::getInstance(); int retCode = NFCSTATUS_SUCCESS; sNeedToSwitchRf = false; if (i >= NfcTag::MAX_NUM_TECHNOLOGY) { ALOGE("%s: Handle not found", __FUNCTION__); retCode = NFCSTATUS_FAILED; goto TheEnd; } if (natTag.getActivationState() != NfcTag::Active) { ALOGE("%s: tag already deactivated", __FUNCTION__); retCode = NFCSTATUS_FAILED; goto TheEnd; } if (natTag.mTechLibNfcTypes[i] != NFC_PROTOCOL_ISO_DEP) { ALOGD("%s() Nfc type = %d, do nothing for non ISO_DEP", __FUNCTION__, natTag.mTechLibNfcTypes[i]); retCode = NFCSTATUS_SUCCESS; goto TheEnd; } if (natTag.mTechList[i] == TARGET_TYPE_ISO14443_3A || natTag.mTechList[i] == TARGET_TYPE_ISO14443_3B) { ALOGD("%s: switching to tech: %d need to switch rf intf to frame", __FUNCTION__, natTag.mTechList[i]); // Connecting to NfcA or NfcB don't actually switch until/unless we get a transceive. sNeedToSwitchRf = true; } else { // Connecting back to IsoDep or NDEF. return (switchRfInterface(NFA_INTERFACE_ISO_DEP) ? NFCSTATUS_SUCCESS : NFCSTATUS_FAILED); } TheEnd: ALOGD("%s: exit 0x%X", __FUNCTION__, retCode); return retCode; } bool NfcTagManager::doPresenceCheck() { ALOGD("%s", __FUNCTION__); tNFA_STATUS status = NFA_STATUS_OK; bool isPresent = false; // Special case for Kovio. The deactivation would have already occurred // but was ignored so that normal tag opertions could complete. Now we // want to process as if the deactivate just happened. if (NfcTag::getInstance().mTechList [0] == TARGET_TYPE_KOVIO_BARCODE) { ALOGD("%s: Kovio, force deactivate handling", __FUNCTION__); tNFA_DEACTIVATED deactivated = {NFA_DEACTIVATE_TYPE_IDLE}; NfcTag::getInstance().setDeactivationState(deactivated); doResetPresenceCheck(); NfcTag::getInstance().connectionEventHandler(NFA_DEACTIVATED_EVT, NULL); doAbortWaits(); NfcTag::getInstance().abort(); return false; } if (nfcManager_isNfcActive() == false) { ALOGD("%s: NFC is no longer active.", __FUNCTION__); return false; } if (NfcTag::getInstance().getActivationState() != NfcTag::Active) { ALOGD("%s: tag already deactivated", __FUNCTION__); return false; } if (sem_init(&sPresenceCheckSem, 0, 0) == -1) { ALOGE("%s: semaphore creation failed (errno=0x%08x)", __FUNCTION__, errno); return false; } status = NFA_RwPresenceCheck(); if (status == NFA_STATUS_OK) { if (sem_wait(&sPresenceCheckSem)) { ALOGE("%s: failed to wait (errno=0x%08x)", __FUNCTION__, errno); } else { isPresent = (sCountTagAway > 3) ? false : true; } } if (sem_destroy(&sPresenceCheckSem)) { ALOGE("%s: Failed to destroy check NDEF semaphore (errno=0x%08x)", __FUNCTION__, errno); } if (isPresent == false) ALOGD("%s: tag absent ????", __FUNCTION__); return isPresent; } int NfcTagManager::reSelect(tNFA_INTF_TYPE rfInterface) { ALOGD("%s: enter; rf intf = %d", __FUNCTION__, rfInterface); NfcTag& natTag = NfcTag::getInstance(); tNFA_STATUS status; int rVal = 1; do { // If tag has shutdown, abort this method. if (NfcTag::getInstance().isNdefDetectionTimedOut()) { ALOGD("%s: ndef detection timeout; break", __FUNCTION__); rVal = STATUS_CODE_TARGET_LOST; break; } { SyncEventGuard g(sReconnectEvent); gIsTagDeactivating = true; sGotDeactivate = false; ALOGD("%s: deactivate to sleep", __FUNCTION__); if (NFA_STATUS_OK != (status = NFA_Deactivate(TRUE))) { // Deactivate to sleep state. ALOGE("%s: deactivate failed, status = %d", __FUNCTION__, status); break; } if (sReconnectEvent.wait(1000) == false) { // If timeout occurred. ALOGE("%s: timeout waiting for deactivate", __FUNCTION__); } } if (NfcTag::getInstance().getActivationState() != NfcTag::Sleep) { ALOGD("%s: tag is not in sleep", __FUNCTION__); rVal = STATUS_CODE_TARGET_LOST; break; } gIsTagDeactivating = false; { SyncEventGuard g2 (sReconnectEvent); sConnectWaitingForComplete = true; ALOGD("%s: select interface %u", __FUNCTION__, rfInterface); gIsSelectingRfInterface = true; if (NFA_STATUS_OK != (status = NFA_Select(natTag.mTechHandles[0], natTag.mTechLibNfcTypes[0], rfInterface))) { ALOGE("%s: NFA_Select failed, status = %d", __FUNCTION__, status); break; } sConnectOk = false; if (sReconnectEvent.wait(1000) == false) { // If timeout occured. ALOGE("%s: timeout waiting for select", __FUNCTION__); break; } } ALOGD("%s: select completed; sConnectOk=%d", __FUNCTION__, sConnectOk); if (NfcTag::getInstance().getActivationState() != NfcTag::Active) { ALOGD("%s: tag is not active", __FUNCTION__); rVal = STATUS_CODE_TARGET_LOST; break; } rVal = (sConnectOk) ? 0 : 1; } while (0); sConnectWaitingForComplete = false; gIsTagDeactivating = false; gIsSelectingRfInterface = false; ALOGD("%s: exit; status=%d", __FUNCTION__, rVal); return rVal; } bool NfcTagManager::switchRfInterface(tNFA_INTF_TYPE rfInterface) { ALOGD("%s: rf intf = %d", __FUNCTION__, rfInterface); NfcTag& natTag = NfcTag::getInstance(); if (natTag.mTechLibNfcTypes[0] != NFC_PROTOCOL_ISO_DEP) { ALOGD("%s: protocol: %d not ISO_DEP, do nothing", __FUNCTION__, natTag.mTechLibNfcTypes[0]); return true; } sRfInterfaceMutex.lock(); ALOGD("%s: new rf intf = %d, cur rf intf = %d", __FUNCTION__, rfInterface, sCurrentRfInterface); bool rVal = true; if (rfInterface != sCurrentRfInterface) { if ((rVal = (0 == reSelect(rfInterface)))) { sCurrentRfInterface = rfInterface; } } sRfInterfaceMutex.unlock(); return rVal; } int NfcTagManager::getNdefType(int libnfcType) { int ndefType = NDEF_UNKNOWN_TYPE; // For NFA, libnfcType is mapped to the protocol value received // in the NFA_ACTIVATED_EVT and NFA_DISC_RESULT_EVT event. switch (libnfcType) { case NFA_PROTOCOL_T1T: ndefType = NDEF_TYPE1_TAG; break; case NFA_PROTOCOL_T2T: ndefType = NDEF_TYPE2_TAG; break; case NFA_PROTOCOL_T3T: ndefType = NDEF_TYPE3_TAG; break; case NFA_PROTOCOL_ISO_DEP: ndefType = NDEF_TYPE4_TAG; break; case NFA_PROTOCOL_ISO15693: ndefType = NDEF_UNKNOWN_TYPE; break; case NFA_PROTOCOL_INVALID: ndefType = NDEF_UNKNOWN_TYPE; break; default: ndefType = NDEF_UNKNOWN_TYPE; break; } return ndefType; } void NfcTagManager::addTechnology(TagTechnology tech, int handle, int libnfctype) { mTechList.push_back(tech); mTechHandles.push_back(handle); mTechLibNfcTypes.push_back(libnfctype); } int NfcTagManager::getConnectedLibNfcType() { if (mConnectedTechIndex != -1 && mConnectedTechIndex < (int)mTechLibNfcTypes.size()) { return mTechLibNfcTypes[mConnectedTechIndex]; } else { return 0; } } bool NfcTagManager::doDisconnect() { ALOGD("%s: enter", __FUNCTION__); tNFA_STATUS nfaStat = NFA_STATUS_OK; gGeneralTransceiveTimeout = DEFAULT_GENERAL_TRANS_TIMEOUT; if (NfcTag::getInstance().getActivationState() != NfcTag::Active) { ALOGD("%s: tag already deactivated", __FUNCTION__); goto TheEnd; } nfaStat = NFA_Deactivate(FALSE); if (nfaStat != NFA_STATUS_OK) ALOGE("%s: deactivate failed; error=0x%X", __FUNCTION__, nfaStat); TheEnd: ALOGD("%s: exit", __FUNCTION__); return (nfaStat == NFA_STATUS_OK) ? true : false; } void NfcTagManager::formatStatus(bool isOk) { sFormatOk = isOk; sem_post(&sFormatSem); } bool NfcTagManager::doWrite(std::vector<uint8_t>& buf) { bool result = false; tNFA_STATUS status = 0; const int maxBufferSize = 1024; UINT8 buffer[maxBufferSize] = { 0 }; UINT32 curDataSize = 0; uint8_t* p_data = reinterpret_cast<uint8_t*>(malloc(buf.size())); for (uint8_t idx = 0; idx < buf.size(); idx++) p_data[idx] = buf[idx]; ALOGD("%s: enter; len = %zu", __FUNCTION__, buf.size()); // Create the write semaphore. if (sem_init(&sWriteSem, 0, 0) == -1) { ALOGE("%s: semaphore creation failed (errno=0x%08x)", __FUNCTION__, errno); free(p_data); return false; } sWriteWaitingForComplete = true; if (sCheckNdefStatus == NFA_STATUS_FAILED) { // If tag does not contain a NDEF message // and tag is capable of storing NDEF message. if (sCheckNdefCapable) { ALOGD("%s: try format", __FUNCTION__); sem_init(&sFormatSem, 0, 0); sFormatOk = false; status = NFA_RwFormatTag(); sem_wait(&sFormatSem); sem_destroy(&sFormatSem); if (sFormatOk == false) // If format operation failed. goto TheEnd; } ALOGD("%s: try write", __FUNCTION__); status = NFA_RwWriteNDef(p_data, buf.size()); } else if (buf.size() == 0) { // If (NXP TagWriter wants to erase tag) then create and write an empty ndef message. NDEF_MsgInit(buffer, maxBufferSize, &curDataSize); status = NDEF_MsgAddRec(buffer, maxBufferSize, &curDataSize, NDEF_TNF_EMPTY, NULL, 0, NULL, 0, NULL, 0); ALOGD("%s: create empty ndef msg; status=%u; size=%lu", __FUNCTION__, status, curDataSize); status = NFA_RwWriteNDef(buffer, curDataSize); } else { ALOGD("%s: NFA_RwWriteNDef", __FUNCTION__); status = NFA_RwWriteNDef(p_data, buf.size()); } if (status != NFA_STATUS_OK) { ALOGE("%s: write/format error=%d", __FUNCTION__, status); goto TheEnd; } // Wait for write completion status sWriteOk = false; if (sem_wait(&sWriteSem)) { ALOGE("%s: wait semaphore (errno=0x%08x)", __FUNCTION__, errno); goto TheEnd; } result = sWriteOk; TheEnd: // Destroy semaphore if (sem_destroy(&sWriteSem)) { ALOGE("%s: failed destroy semaphore (errno=0x%08x)", __FUNCTION__, errno); } sWriteWaitingForComplete = false; ALOGD("%s: exit; result=%d", __FUNCTION__, result); free(p_data); return result; } bool NfcTagManager::doIsNdefFormatable() { bool isFormattable = false; switch (NfcTag::getInstance().getProtocol()) { case NFA_PROTOCOL_T1T: case NFA_PROTOCOL_ISO15693: isFormattable = true; break; case NFA_PROTOCOL_T2T: isFormattable = NfcTag::getInstance().isMifareUltralight() ? true : false; } ALOGD("%s: is formattable=%u", __FUNCTION__, isFormattable); return isFormattable; } bool NfcTagManager::connect(int technology) { pthread_mutex_lock(&mMutex); int status = connectWithStatus(technology); pthread_mutex_unlock(&mMutex); return NFCSTATUS_SUCCESS == status; } bool NfcTagManager::disconnect() { bool result = false; mIsPresent = false; pthread_mutex_lock(&mMutex); result = doDisconnect(); pthread_mutex_unlock(&mMutex); mConnectedTechIndex = -1; mConnectedHandle = -1; mTechList.clear(); mTechHandles.clear(); mTechLibNfcTypes.clear(); mTechPollBytes.clear(); mTechActBytes.clear(); mUid.clear(); return result; } bool NfcTagManager::reconnect() { pthread_mutex_lock(&mMutex); int status = reconnectWithStatus(); pthread_mutex_unlock(&mMutex); return NFCSTATUS_SUCCESS == status; } bool NfcTagManager::presenceCheck() { bool result; pthread_mutex_lock(&mMutex); result = doPresenceCheck(); pthread_mutex_unlock(&mMutex); return result; } NdefMessage* NfcTagManager::readNdef() { pthread_mutex_lock(&mMutex); NdefMessage* ndef = doReadNdef(); pthread_mutex_unlock(&mMutex); return ndef; } NdefDetail* NfcTagManager::readNdefDetail() { pthread_mutex_lock(&mMutex); NdefDetail* ndefDetail = doReadNdefDetail(); pthread_mutex_unlock(&mMutex); return ndefDetail; } bool NfcTagManager::writeNdef(NdefMessage& ndef) { bool result; std::vector<uint8_t> buf; ndef.toByteArray(buf); pthread_mutex_lock(&mMutex); result = doWrite(buf); pthread_mutex_unlock(&mMutex); return result; } bool NfcTagManager::makeReadOnly() { bool result; pthread_mutex_lock(&mMutex); result = doMakeReadonly(); pthread_mutex_unlock(&mMutex); return result; } bool NfcTagManager::isNdefFormatable() { return doIsNdefFormatable(); } bool NfcTagManager::formatNdef() { bool result; pthread_mutex_lock(&mMutex); result = doNdefFormat(); pthread_mutex_unlock(&mMutex); return result; } <file_sep>/src/interface/TagTechnology.h /* * Copyright (C) 2013-2014 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef mozilla_nfcd_TagTechnology_h #define mozilla_nfcd_TagTechnology_h // Used by getTechList() of INfcTag. // Define the tag technology. typedef enum { NFC_A = 0, NFC_B = 1, NFC_ISO_DEP = 2, NFC_F = 3, NFC_V = 4, NDEF = 5, NDEF_FORMATABLE = 6, NDEF_WRITABLE = 7, MIFARE_CLASSIC = 8, MIFARE_ULTRALIGHT = 9, NFC_BARCODE = 10, UNKNOWN_TECH = 11 } TagTechnology; #endif <file_sep>/src/nci/PeerToPeer.h /* * Copyright (C) 2014 Mozilla Foundation * * 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. */ #pragma once #include <utils/RefBase.h> #include <utils/StrongPointer.h> #include <string> #include "SyncEvent.h" extern "C" { #include "nfa_p2p_api.h" } class NfcManager; class P2pServer; class P2pClient; class NfaConn; #define MAX_NFA_CONNS_PER_SERVER 5 /** * Communicate with a peer using NFC-DEP, LLCP, SNEP. */ class PeerToPeer { public: PeerToPeer(); ~PeerToPeer(); /** * Get the singleton PeerToPeer object. * * @return Singleton PeerToPeer object. */ static PeerToPeer& getInstance(); /** * Initialize member variables. * * @return None. */ void initialize(NfcManager* pNfcManager); /** * Receive LLLCP-activated event from stack. * * @param activated Event data. * @return None. */ void llcpActivatedHandler(tNFA_LLCP_ACTIVATED& activated); /** * Receive LLLCP-deactivated event from stack. * * @param deactivated Event data. * @return None. */ void llcpDeactivatedHandler(tNFA_LLCP_DEACTIVATED& deactivated); void llcpFirstPacketHandler(); /** * Receive events from the stack. * * @param event Event code. * @param eventData Event data. * @return None. */ void connectionEventHandler(UINT8 event, tNFA_CONN_EVT_DATA* eventData); /** * Let a server start listening for peer's connection request. * * @param handle Connection handle. * @param serviceName Server's service name. * @return True if ok. */ bool registerServer(unsigned int handle, const char* serviceName); /** * Stop a P2pServer from listening for peer. * * @param handle Connection handle. * @return True if ok. */ bool deregisterServer(unsigned int handle); /** * Accept a peer's request to connect * * @param serverHandle Server's handle. * @param connHandle Connection handle. * @param maxInfoUnit Maximum information unit. * @param recvWindow Receive window size. * @return True if ok. */ bool accept(unsigned int serverHandle, unsigned int connHandle, int maxInfoUnit, int recvWindow); /** * Create a P2pClient object for a new out-bound connection. * * @param handle Connection handle. * @param miu Maximum information unit. * @param rw Receive window size. * @return True if ok. */ bool createClient(unsigned int handle, UINT16 miu, UINT8 rw); /** * Estabish a connection-oriented connection to a peer. * * @param handle Connection handle. * @param serviceName Peer's service name. * @return True if ok. */ bool connectConnOriented(unsigned int handle, const char* serviceName); /** * Estabish a connection-oriented connection to a peer. * * @param handle Connection handle. * @param destinationSap Peer's service access point. * @return True if ok. */ bool connectConnOriented(unsigned int handle, UINT8 destinationSap); /** * Send data to peer. * * @param handle Handle of connection. * @param buffer Buffer of data. * @param bufferLen Length of data. * @return True if ok. */ bool send(unsigned int handle, UINT8* buffer, UINT16 bufferLen); /** * Receive data from peer. * * @param handle Handle of connection. * @param buffer Buffer to store data. * @param bufferLen Max length of buffer. * @param actualLen Actual length received. * @return True if ok. */ bool receive(unsigned int handle, UINT8* buffer, UINT16 bufferLen, UINT16& actualLen); /** * Disconnect a connection-oriented connection with peer. * * @param handle Handle of connection. * @return True if ok. */ bool disconnectConnOriented(unsigned int handle); /** * Get peer's max information unit. * * @param handle Handle of the connection. * @return Peer's max information unit. */ UINT16 getRemoteMaxInfoUnit(unsigned int handle); /** * Get peer's receive window size. * * @param handle Handle of the connection. * @return Peer's receive window size. */ UINT8 getRemoteRecvWindow(unsigned int handle); /** * Sets the p2p listen technology mask. * * @param p2pListenMask The p2p listen mask to be set? * @return None. */ void setP2pListenMask(tNFA_TECHNOLOGY_MASK p2pListenMask); /** * Start/stop polling/listening to peer that supports P2P. * * @param isEnable Is enable polling/listening? * @return True if ok. */ bool enableP2pListening(bool isEnable); /** * Handle events related to turning NFC on/off by the user. * * @param isOn Is NFC turning on? * @return None. */ void handleNfcOnOff(bool isOn); /** * Get a new handle. * * @return A new handle */ unsigned int getNewHandle(); /** * Receive LLCP-related events from the stack. * * @param p2pEvent Event code. * @param eventData Event data. * @return None. */ static void nfaServerCallback(tNFA_P2P_EVT p2pEvent, tNFA_P2P_EVT_DATA *eventData); /** * Receive LLCP-related events from the stack. * * @param p2pEvent Event code. * @param eventData Event data. * @return None. */ static void nfaClientCallback(tNFA_P2P_EVT p2pEvent, tNFA_P2P_EVT_DATA *eventData); private: static const int sMax = 10; static PeerToPeer sP2p; // Variables below only accessed from a single thread. UINT16 mRemoteWKS; // Peer's well known services. bool mIsP2pListening; // If P2P listening is enabled or not. tNFA_TECHNOLOGY_MASK mP2pListenTechMask; // P2P Listen mask. // Variable below is protected by mNewHandleMutex. unsigned int mNextHandle; // Variables below protected by mMutex. // A note on locking order: mMutex in PeerToPeer is *ALWAYS*. // locked before any locks / guards in P2pServer / P2pClient. Mutex mMutex; android::sp<P2pServer> mServers [sMax]; android::sp<P2pClient> mClients [sMax]; // Synchronization variables. // Completion event for NFA_SetP2pListenTech(). SyncEvent mSetTechEvent; // Completion event for NFA_SnepStartDefaultServer(), NFA_SnepStopDefaultServer(). SyncEvent mSnepDefaultServerStartStopEvent; // Completion event for NFA_SnepRegisterClient(). SyncEvent mSnepRegisterEvent; // Synchronize the disconnect operation. Mutex mDisconnectMutex; // Synchronize the creation of a new handle. Mutex mNewHandleMutex; NfcManager* mNfcManager; static void ndefTypeCallback (tNFA_NDEF_EVT event, tNFA_NDEF_EVT_DATA *evetnData); android::sp<P2pServer> findServerLocked(tNFA_HANDLE nfaP2pServerHandle); android::sp<P2pServer> findServerLocked(unsigned int handle); android::sp<P2pServer> findServerLocked(const char *serviceName); void removeServer(unsigned int handle); void removeConn(unsigned int handle); bool createDataLinkConn(unsigned int handle, const char* serviceName, UINT8 destinationSap); android::sp<P2pClient> findClient(tNFA_HANDLE nfaConnHandle); android::sp<P2pClient> findClient(unsigned int handle); android::sp<P2pClient> findClientCon(tNFA_HANDLE nfaConnHandle); android::sp<NfaConn> findConnection(tNFA_HANDLE nfaConnHandle); android::sp<NfaConn> findConnection(unsigned int handle); }; class NfaConn : public android::RefBase { public: tNFA_HANDLE mNfaConnHandle; // NFA handle of the P2P connection. unsigned int mHandle; // Handle of the P2P connection. UINT16 mMaxInfoUnit; UINT8 mRecvWindow; UINT16 mRemoteMaxInfoUnit; UINT8 mRemoteRecvWindow; SyncEvent mReadEvent; // Event for reading. SyncEvent mCongEvent; // Event for congestion. SyncEvent mDisconnectingEvent; // Event for disconnecting. NfaConn(); }; class P2pServer : public android::RefBase { public: static const std::string sSnepServiceName; tNFA_HANDLE mNfaP2pServerHandle; // NFA p2p handle of local server unsigned int mHandle; // Handle SyncEvent mRegServerEvent; // For NFA_P2pRegisterServer() SyncEvent mConnRequestEvent; // For accept() std::string mServiceName; P2pServer(unsigned int handle, const char* serviceName); bool registerWithStack(); bool accept(unsigned int serverHandle, unsigned int connHandle, int maxInfoUnit, int recvWindow); void unblockAll(); android::sp<NfaConn> findServerConnection(tNFA_HANDLE nfaConnHandle); android::sp<NfaConn> findServerConnection(unsigned int handle); bool removeServerConnection(unsigned int handle); private: Mutex mMutex; // mServerConn is protected by mMutex. android::sp<NfaConn> mServerConn[MAX_NFA_CONNS_PER_SERVER]; android::sp<NfaConn> allocateConnection(unsigned int handle); }; class P2pClient : public android::RefBase { public: tNFA_HANDLE mNfaP2pClientHandle; // NFA p2p handle of client. bool mIsConnecting; // Set true while connecting. android::sp<NfaConn> mClientConn; SyncEvent mRegisteringEvent; // For client registration. SyncEvent mConnectingEvent; // For NFA_P2pConnectByName or Sap(). SyncEvent mSnepEvent; // To wait for SNEP completion. P2pClient(); ~P2pClient(); void unblock(); }; <file_sep>/src/nci/NfcTagManager.h /* * Copyright (C) 2014 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef mozilla_nfcd_NfcTagManager_h #define mozilla_nfcd_NfcTagManager_h #include <pthread.h> #include <vector> #include "INfcTag.h" extern "C" { #include "nfa_rw_api.h" } class NfcTagManager : public INfcTag { public: NfcTagManager(); virtual ~NfcTagManager(); // INfcTag interface. bool connect(int technology); bool disconnect(); bool reconnect(); NdefMessage* readNdef(); NdefDetail* readNdefDetail(); bool writeNdef(NdefMessage& ndef); bool presenceCheck(); bool makeReadOnly(); bool formatNdef(); std::vector<TagTechnology>& getTechList() { return mTechList; }; std::vector<int>& getTechHandles() { return mTechHandles; }; std::vector<int>& getTechLibNfcTypes() { return mTechLibNfcTypes; }; std::vector<std::vector<uint8_t> >& getTechPollBytes() { return mTechPollBytes; }; std::vector<std::vector<uint8_t> >& getTechActBytes() { return mTechActBytes; }; std::vector<std::vector<uint8_t> >& getUid() { return mUid; }; int& getConnectedHandle() { return mConnectedHandle; }; /** * Does the tag contain a NDEF message? * * @param ndefInfo NDEF info. * @return Status code; 0 is success. */ static int doCheckNdef(int ndefInfo[]); /** * Read the NDEF message on the tag. * * @param buf NDEF message read from tag. * @return None. */ static void doRead(std::vector<uint8_t>& buf); /** * Write a NDEF message to the tag. * * @param buf Contains a NDEF message. * @return True if ok. */ static bool doWrite(std::vector<uint8_t>& buf); /** * Unblock all thread synchronization objects. * * @return None. */ static void doAbortWaits(); /** * Receive the completion status of read operation. Called by * NFA_READ_CPLT_EVT. * * @param status Status of operation. * @return None. */ static void doReadCompleted(tNFA_STATUS status); /** * Receive the completion status of write operation. Called by * NFA_WRITE_CPLT_EVT. * * @param isWriteOk Status of operation. * @return None. */ static void doWriteStatus(bool isWriteOk); /** * Receive the completion status of connect operation. * * @param isConnectOk Status of the operation. * @return None. */ static void doConnectStatus(bool isConnectOk); /** * Receive the completion status of deactivate operation. * * @return None. */ static void doDeactivateStatus(int status); /** * Connect to the tag in RF field. * * @param targetHandle Handle of the tag. * @return Must return NXP status code, which NFC service expects. */ static int doConnect(int targetHandle); /** * Reset variables related to presence-check. * * @return None. */ static void doResetPresenceCheck(); /** * Receive the result of presence-check. * * @param status Result of presence-check. * @return None. */ static void doPresenceCheckResult(tNFA_STATUS status); /** * Receive the result of checking whether the tag contains a NDEF * message. Called by the NFA_NDEF_DETECT_EVT. * * @param status Status of the operation. * @param maxSize Maximum size of NDEF message. * @param currentSize Current size of NDEF message. * @param flags Indicate various states. * @return None. */ static void doCheckNdefResult(tNFA_STATUS status, uint32_t maxSize, uint32_t currentSize, uint8_t flags); /** * Register a callback to receive NDEF message from the tag * from the NFA_NDEF_DATA_EVT. * * @return None. */ static void doRegisterNdefTypeHandler(); /** * No longer need to receive NDEF message from the tag. * * @return None. */ static void doDeregisterNdefTypeHandler(); /** * Check if the tag is in the RF field. * * @return None. */ static bool doPresenceCheck(); /** * Deactivate the RF field. * * @return True if ok. */ static bool doDisconnect(); /** * Receive the result of making a tag read-only. Called by the * NFA_SET_TAG_RO_EVT. * * @param status Status of the operation. * @return None. */ static void doMakeReadonlyResult(tNFA_STATUS status); /** * Make the tag read-only. * * @return True if ok. */ static bool doMakeReadonly(); /** * Receive the completion status of format operation. Called by NFA_FORMAT_CPLT_EVT. * * @param isOk Status of operation. * @return None. */ static void formatStatus(bool isOk); /** * Format a tag so it can store NDEF message. * * @return True if ok. */ static bool doNdefFormat(); static bool doIsNdefFormatable(); int connectWithStatus(int technology); int reconnectWithStatus(int technology); int reconnectWithStatus(); NdefMessage* doReadNdef(); NdefDetail* doReadNdefDetail(); bool isNdefFormatable(); private: pthread_mutex_t mMutex; std::vector<TagTechnology> mTechList; std::vector<int> mTechHandles; std::vector<int> mTechLibNfcTypes; std::vector<std::vector<uint8_t> > mTechPollBytes; std::vector<std::vector<uint8_t> > mTechActBytes; std::vector<std::vector<uint8_t> > mUid; // mConnectedHandle stores the *real* libnfc handle // that we're connected to. int mConnectedHandle; // mConnectedTechIndex stores to which technology // the upper layer stack is connected. Note that // we may be connected to a libnfchandle without being // connected to a technology - technology changes // may occur runtime, whereas the underlying handle // could stay present. Usually all technologies are on the // same handle, with the exception of multi-protocol // tags. int mConnectedTechIndex; // Index in mTechHandles. bool mIsPresent; // Whether the tag is known to be still present. /** * Deactivates the tag and re-selects it with the specified * rf interface. * * @param rfInterface Type of RF interface. * @return Status code, 0 on success, 1 on failure, * 146 (defined in service) on tag lost. */ static int reSelect(tNFA_INTF_TYPE rfInterface); /** * Switch controller's RF interface to frame, ISO-DEP, or NFC-DEP. * * @param rfInterface Type of RF interface. * @return True if ok. */ static bool switchRfInterface(tNFA_INTF_TYPE rfInterface); int getNdefType(int libnfcType); void addTechnology(TagTechnology tech, int handle, int libnfctype); int getConnectedLibNfcType(); }; #endif // mozilla_nfcd_NfcTagManager_h <file_sep>/src/NfcUtil.cpp /* * Copyright (C) 2013-2014 Mozilla Foundation * * 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. */ #include "NfcUtil.h" void NfcUtil::convertNdefPduToNdefMessage(NdefMessagePdu& ndefPdu, NdefMessage* ndefMessage) { for (uint32_t i = 0; i < ndefPdu.numRecords; i++) { NdefRecordPdu& record = ndefPdu.records[i]; ndefMessage->mRecords.push_back(NdefRecord( record.tnf, record.typeLength, record.type, record.idLength, record.id, record.payloadLength, record.payload)); } } NfcTechnology NfcUtil::convertTagTechToGonkFormat(TagTechnology tagTech) { switch(tagTech) { case NFC_A: return NFC_TECH_NFCA; case NFC_B: return NFC_TECH_NFCB; case NFC_ISO_DEP: return NFC_TECH_ISO_DEP; case NFC_F: return NFC_TECH_NFCF; case NFC_V: return NFC_TECH_NFCV; case NDEF: return NFC_TECH_NDEF; case NDEF_FORMATABLE: return NFC_TECH_NDEF_FORMATABLE; case NDEF_WRITABLE: return NFC_TECH_NDEF_WRITABLE; case MIFARE_CLASSIC: return NFC_TECH_MIFARE_CLASSIC; case MIFARE_ULTRALIGHT: return NFC_TECH_MIFARE_ULTRALIGHT; case NFC_BARCODE: return NFC_TECH_MIFARE_ULTRALIGHT; case UNKNOWN_TECH: default: return NFC_TECH_UNKNOWN; } return NFC_TECH_NFCA; } NfcEvtTransactionOrigin NfcUtil::convertOriginType(TransactionEvent::OriginType type) { switch (type) { case TransactionEvent::SIM: return NFC_EVT_TRANSACTION_SIM; case TransactionEvent::ESE: return NFC_EVT_TRANSACTION_ESE; case TransactionEvent::ASSD: return NFC_EVT_TRANSACTION_ASSD; default: return NFC_EVT_TRANSACTION_SIM; } } <file_sep>/src/NfcIpcSocket.h /* * Copyright (C) 2013-2014 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef mozilla_nfcd_NfcIpcSocket_h #define mozilla_nfcd_NfcIpcSocket_h #include <pthread.h> #include <time.h> #include <binder/Parcel.h> class MessageHandler; class IpcSocketListener; class NfcIpcSocket{ private: static NfcIpcSocket* sInstance; public: ~NfcIpcSocket(); static NfcIpcSocket* Instance(); void initialize(MessageHandler* msgHandler); void loop(); void setSocketListener(IpcSocketListener* lister); void writeToOutgoingQueue(uint8_t *data, size_t dataLen); void writeToIncomingQueue(uint8_t *data, size_t dataLen); private: NfcIpcSocket(); timespec mSleep_spec; timespec mSleep_spec_rem; static MessageHandler* sMsgHandler; IpcSocketListener* mListener; void initSocket(); int getListenSocket(); }; #endif // mozilla_nfcd_NfcIpcSocket_h <file_sep>/src/interface/NdefMessage.h /* * Copyright (C) 2013-2014 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef mozilla_nfcd_NdefMessage_h #define mozilla_nfcd_NdefMessage_h #include "NdefRecord.h" #include <vector> class NdefMessage{ public: NdefMessage(); NdefMessage(NdefMessage* ndef); ~NdefMessage(); /** * Initialize NDEF meesage with NDEF binary data. * * @param buf Input buffer contains raw NDEF data. * @return True if the buffer can be correctly parsed. */ bool init(std::vector<uint8_t>& buf); /** * Initialize NDEF meesage with NDEF binary data. * * @param buf Input buffer contains raw NDEF data. * @param offset Indicate the start position of buffer to be parsed. * @return True if the buffer can be correctly parsed. */ bool init(std::vector<uint8_t>& buf, int offset); /** * Write current NdefMessage to byte buffer. * * @param buf Output raw buffer. * @return None. */ void toByteArray(std::vector<uint8_t>& buf); // Array of NDEF records. std::vector<NdefRecord> mRecords; }; /** * NdefDetail structure contains the information should be returned by readNdefDetail of INfcTag. */ class NdefDetail { public: int maxSupportedLength; bool isReadOnly; bool canBeMadeReadOnly; }; #endif <file_sep>/src/nci/NfcUtil.h /* * Copyright (C) 2014 Mozilla Foundation * * 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. */ #pragma once #include <pthread.h> /** * Discovery modes -- keep in sync with NFCManager.DISCOVERY_MODE_* */ #define DISCOVERY_MODE_TAG_READER 0 #define DISCOVERY_MODE_NFCIP1 1 #define DISCOVERY_MODE_CARD_EMULATION 2 #define DISCOVERY_MODE_TABLE_SIZE 3 #define DISCOVERY_MODE_DISABLED 0 #define DISCOVERY_MODE_ENABLED 1 //#define MODE_P2P_TARGET 0 //#define MODE_P2P_INITIATOR 1 /** * Properties values. */ #define PROPERTY_LLCP_LTO 0 #define PROPERTY_LLCP_MIU 1 #define PROPERTY_LLCP_WKS 2 #define PROPERTY_LLCP_OPT 3 #define PROPERTY_NFC_DISCOVERY_A 4 #define PROPERTY_NFC_DISCOVERY_B 5 #define PROPERTY_NFC_DISCOVERY_F 6 #define PROPERTY_NFC_DISCOVERY_15693 7 #define PROPERTY_NFC_DISCOVERY_NCFIP 8 /** * Error codes. */ #define ERROR_BUFFER_TOO_SMALL -12 #define ERROR_INSUFFICIENT_RESOURCES -9 /** * Pre-defined tag type values. These must match the values in * Ndef.java in the framework. */ #define NDEF_UNKNOWN_TYPE -1 #define NDEF_TYPE1_TAG 1 #define NDEF_TYPE2_TAG 2 #define NDEF_TYPE3_TAG 3 #define NDEF_TYPE4_TAG 4 #define NDEF_MIFARE_CLASSIC_TAG 101 /** * Pre-defined card read/write state values. These must match the values in * Ndef.java in the framework. */ #define NDEF_MODE_READ_ONLY 1 #define NDEF_MODE_READ_WRITE 2 #define NDEF_MODE_UNKNOWN 3 /** * Name strings for target types. These *must* match the values in TagTechnology.java. */ #define TARGET_TYPE_UNKNOWN -1 #define TARGET_TYPE_ISO14443_3A 1 #define TARGET_TYPE_ISO14443_3B 2 #define TARGET_TYPE_ISO14443_4 3 #define TARGET_TYPE_FELICA 4 #define TARGET_TYPE_ISO15693 5 #define TARGET_TYPE_NDEF 6 #define TARGET_TYPE_NDEF_FORMATABLE 7 #define TARGET_TYPE_MIFARE_CLASSIC 8 #define TARGET_TYPE_MIFARE_UL 9 #define TARGET_TYPE_KOVIO_BARCODE 10 // Define a few NXP error codes that NFC service expects. // See external/libnfc-nxp/src/phLibNfcStatus.h. // See external/libnfc-nxp/inc/phNfcStatus.h. #define NFCSTATUS_SUCCESS (0x0000) #define NFCSTATUS_FAILED (0x00FF) // Default general trasceive timeout in millisecond. #define DEFAULT_GENERAL_TRANS_TIMEOUT 1000 struct nfc_data { // Thread handle. pthread_t thread; int running; // Reference to the NFCManager instance. void* manager; // Secure Element selected. int seId; // LLCP params. int lto; int miu; int wks; int opt; int tech_mask; // Tag detected. void* tag; int tHandle; int tProtocols[16]; int handles[16]; }; <file_sep>/src/MessageHandler.cpp /* * Copyright (C) 2013-2014 Mozilla Foundation * * 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. */ #include "MessageHandler.h" #include <arpa/inet.h> // for htonl #include "NfcService.h" #include "NfcIpcSocket.h" #include "NfcUtil.h" #include "NdefMessage.h" #include "NdefRecord.h" #include "SessionId.h" #include "NfcDebug.h" #define MAJOR_VERSION (1) #define MINOR_VERSION (8) using android::Parcel; void MessageHandler::notifyInitialized(Parcel& parcel) { parcel.writeInt32(0); // status parcel.writeInt32(MAJOR_VERSION); parcel.writeInt32(MINOR_VERSION); sendResponse(parcel); } void MessageHandler::notifyTechDiscovered(Parcel& parcel, void* data) { TechDiscoveredEvent *event = reinterpret_cast<TechDiscoveredEvent*>(data); parcel.writeInt32(event->sessionId); parcel.writeInt32(event->techCount); void* dest = parcel.writeInplace(event->techCount); memcpy(dest, event->techList, event->techCount); parcel.writeInt32(event->ndefMsgCount); sendNdefMsg(parcel, event->ndefMsg); sendResponse(parcel); } void MessageHandler::notifyTechLost(Parcel& parcel, void* data) { parcel.writeInt32(reinterpret_cast<int>(data)); sendResponse(parcel); } void MessageHandler::notifyTransactionEvent(Parcel& parcel, void* data) { TransactionEvent *event = reinterpret_cast<TransactionEvent*>(data); parcel.writeInt32(NfcUtil::convertOriginType(event->originType)); parcel.writeInt32(event->originIndex); parcel.writeInt32(event->aidLen); void* aid = parcel.writeInplace(event->aidLen); memcpy(aid, event->aid, event->aidLen); parcel.writeInt32(event->payloadLen); void* payload = parcel.writeInplace(event->payloadLen); memcpy(payload, event->payload, event->payloadLen); sendResponse(parcel); delete event; } void MessageHandler::processRequest(const uint8_t* data, size_t dataLen) { Parcel parcel; int32_t sizeLe, size, request; uint32_t status; ALOGD("%s enter data=%p, dataLen=%d", FUNC, data, dataLen); parcel.setData((uint8_t*)data, dataLen); status = parcel.readInt32(&request); if (status != 0) { ALOGE("Invalid request block"); return; } switch (request) { case NFC_REQUEST_CONFIG: handleConfigRequest(parcel); break; case NFC_REQUEST_GET_DETAILS: handleReadNdefDetailRequest(parcel); break; case NFC_REQUEST_READ_NDEF: handleReadNdefRequest(parcel); break; case NFC_REQUEST_WRITE_NDEF: handleWriteNdefRequest(parcel); break; case NFC_REQUEST_CONNECT: handleConnectRequest(parcel); break; case NFC_REQUEST_CLOSE: handleCloseRequest(parcel); break; case NFC_REQUEST_MAKE_NDEF_READ_ONLY: handleMakeNdefReadonlyRequest(parcel); break; default: ALOGE("Unhandled Request %d", request); break; } } void MessageHandler::processResponse(NfcResponseType response, NfcErrorCode error, void* data) { ALOGD("%s enter response=%d, error=%d", FUNC, response, error); Parcel parcel; parcel.writeInt32(0); // Parcel Size. parcel.writeInt32(response); parcel.writeInt32(error); switch (response) { case NFC_RESPONSE_CONFIG: handleConfigResponse(parcel, data); break; case NFC_RESPONSE_READ_NDEF_DETAILS: handleReadNdefDetailResponse(parcel, data); break; case NFC_RESPONSE_READ_NDEF: handleReadNdefResponse(parcel, data); break; case NFC_RESPONSE_GENERAL: handleResponse(parcel); break; default: ALOGE("Not implement"); break; } } void MessageHandler::processNotification(NfcNotificationType notification, void* data) { ALOGD("processNotificaton notification=%d", notification); Parcel parcel; parcel.writeInt32(0); // Parcel Size. parcel.writeInt32(notification); switch (notification) { case NFC_NOTIFICATION_INITIALIZED : notifyInitialized(parcel); break; case NFC_NOTIFICATION_TECH_DISCOVERED: notifyTechDiscovered(parcel, data); break; case NFC_NOTIFICATION_TECH_LOST: notifyTechLost(parcel, data); break; case NFC_NOTIFICATION_TRANSACTION_EVENT: notifyTransactionEvent(parcel, data); break; default: ALOGE("Not implement"); break; } } void MessageHandler::setOutgoingSocket(NfcIpcSocket* socket) { mSocket = socket; } void MessageHandler::sendResponse(Parcel& parcel) { parcel.setDataPosition(0); uint32_t sizeBE = htonl(parcel.dataSize() - sizeof(int)); parcel.writeInt32(sizeBE); mSocket->writeToOutgoingQueue(const_cast<uint8_t*>(parcel.data()), parcel.dataSize()); } bool MessageHandler::handleConfigRequest(Parcel& parcel) { // TODO, what does NFC_POWER_FULL mean // - OFF -> ON? // - Low Power -> Full Power? int powerLevel = parcel.readInt32(); bool value; switch (powerLevel) { case NFC_POWER_OFF: // Fall through. case NFC_POWER_FULL: value = powerLevel == NFC_POWER_FULL; return mService->handleEnableRequest(value); case NFC_POWER_LOW: value = powerLevel == NFC_POWER_LOW; return mService->handleEnterLowPowerRequest(value); } return false; } bool MessageHandler::handleReadNdefDetailRequest(Parcel& parcel) { int sessionId = parcel.readInt32(); //TODO check SessionId return mService->handleReadNdefDetailRequest(); } bool MessageHandler::handleReadNdefRequest(Parcel& parcel) { int sessionId = parcel.readInt32(); //TODO check SessionId return mService->handleReadNdefRequest(); } bool MessageHandler::handleWriteNdefRequest(Parcel& parcel) { NdefMessagePdu ndefMessagePdu; NdefMessage* ndefMessage = new NdefMessage(); int sessionId = parcel.readInt32(); //TODO check SessionId uint32_t numRecords = parcel.readInt32(); ndefMessagePdu.numRecords = numRecords; ndefMessagePdu.records = new NdefRecordPdu[numRecords]; for (uint32_t i = 0; i < numRecords; i++) { ndefMessagePdu.records[i].tnf = parcel.readInt32(); uint32_t typeLength = parcel.readInt32(); ndefMessagePdu.records[i].typeLength = typeLength; ndefMessagePdu.records[i].type = new uint8_t[typeLength]; const void* data = parcel.readInplace(typeLength); memcpy(ndefMessagePdu.records[i].type, data, typeLength); uint32_t idLength = parcel.readInt32(); ndefMessagePdu.records[i].idLength = idLength; ndefMessagePdu.records[i].id = new uint8_t[idLength]; data = parcel.readInplace(idLength); memcpy(ndefMessagePdu.records[i].id, data, idLength); uint32_t payloadLength = parcel.readInt32(); ndefMessagePdu.records[i].payloadLength = payloadLength; ndefMessagePdu.records[i].payload = new uint8_t[payloadLength]; data = parcel.readInplace(payloadLength); memcpy(ndefMessagePdu.records[i].payload, data, payloadLength); } NfcUtil::convertNdefPduToNdefMessage(ndefMessagePdu, ndefMessage); for (uint32_t i = 0; i < numRecords; i++) { delete[] ndefMessagePdu.records[i].type; delete[] ndefMessagePdu.records[i].id; delete[] ndefMessagePdu.records[i].payload; } delete[] ndefMessagePdu.records; return mService->handleWriteNdefRequest(ndefMessage); } bool MessageHandler::handleConnectRequest(Parcel& parcel) { int sessionId = parcel.readInt32(); //TODO check SessionId //TODO should only read 1 octet here. int32_t techType = parcel.readInt32(); ALOGD("%s techType=%d", FUNC, techType); mService->handleConnect(techType); return true; } bool MessageHandler::handleCloseRequest(Parcel& parcel) { mService->handleCloseRequest(); return true; } bool MessageHandler::handleMakeNdefReadonlyRequest(Parcel& parcel) { mService->handleMakeNdefReadonlyRequest(); return true; } bool MessageHandler::handleConfigResponse(Parcel& parcel, void* data) { sendResponse(parcel); return true; } bool MessageHandler::handleReadNdefDetailResponse(Parcel& parcel, void* data) { NdefDetail* ndefDetail = reinterpret_cast<NdefDetail*>(data); parcel.writeInt32(SessionId::getCurrentId()); if (!ndefDetail) { sendResponse(parcel); return true; } bool isReadOnly = ndefDetail->isReadOnly; bool canBeMadeReadOnly = ndefDetail->canBeMadeReadOnly; bool params[] = {isReadOnly, canBeMadeReadOnly}; void* dest = parcel.writeInplace(sizeof(params)); memcpy(dest, params, sizeof(params)); parcel.writeInt32(ndefDetail->maxSupportedLength); sendResponse(parcel); return true; } bool MessageHandler::handleReadNdefResponse(Parcel& parcel, void* data) { NdefMessage* ndef = reinterpret_cast<NdefMessage*>(data); parcel.writeInt32(SessionId::getCurrentId()); sendNdefMsg(parcel, ndef); sendResponse(parcel); return true; } bool MessageHandler::handleResponse(Parcel& parcel) { parcel.writeInt32(SessionId::getCurrentId()); sendResponse(parcel); return true; } bool MessageHandler::sendNdefMsg(Parcel& parcel, NdefMessage* ndef) { if (!ndef) return false; int numRecords = ndef->mRecords.size(); ALOGD("numRecords=%d", numRecords); parcel.writeInt32(numRecords); for (int i = 0; i < numRecords; i++) { NdefRecord &record = ndef->mRecords[i]; ALOGD("tnf=%u",record.mTnf); parcel.writeInt32(record.mTnf); uint32_t typeLength = record.mType.size(); ALOGD("typeLength=%u",typeLength); parcel.writeInt32(typeLength); void* dest = parcel.writeInplace(typeLength); if (dest == NULL) { ALOGE("writeInplace returns NULL"); return false; } memcpy(dest, &record.mType.front(), typeLength); uint32_t idLength = record.mId.size(); ALOGD("idLength=%d",idLength); parcel.writeInt32(idLength); dest = parcel.writeInplace(idLength); memcpy(dest, &record.mId.front(), idLength); uint32_t payloadLength = record.mPayload.size(); ALOGD("payloadLength=%u",payloadLength); parcel.writeInt32(payloadLength); dest = parcel.writeInplace(payloadLength); memcpy(dest, &record.mPayload.front(), payloadLength); for (uint32_t j = 0; j < payloadLength; j++) { ALOGD("mPayload %d = %u", j, record.mPayload[j]); } } return true; }
d42a2c2ffa4e6ff048cfe3b06b231ff00c65ab12
[ "C", "C++" ]
24
C
elefant/platform_system_nfcd
54a712b46fe937dacdaed9b1261c63847129a719
50e9ffd24bf6b96d54304a487fcd2559ac4209d2
refs/heads/main
<file_sep><?php get_header(); $dados = explode(";", $_GET['param']); $destino = $dados[0]; $data_inicio = $dados[1]; $data_final = $dados[2]; $adt = $dados[3]; $chd = $dados[4]; $qts = $dados[5]; if ($chd == 0) { $crianca = ''; $idades = ''; }else{ if ($chd == 1) { $crianca = ' e '.$chd.' criança'; }else{ $crianca = ' e '.$chd.' crianças'; } $valor_idades = explode("-", $dados[6]); $idades .= '<br><strong>Idade das crianças: </strong><br>'; for ($i=0; $i < $chd; $i++) { $idades .= 'Criança '.($i+1).': '.$valor_idades[$i].' '.($valor_idades[$i] == 1 ? 'ano' : 'anos').'<br>'; } } $pax = $adt.' '.($adt > 1 ? 'adultos' : 'adulto').' '.$crianca; $propriedade = $dados[7]; $data_inicio = new DateTime(implode("-", array_reverse(explode("-", $data_inicio)))); $data_fim = new DateTime(implode("-", array_reverse(explode("-", $data_final)))); // Resgata diferença entre as datas $diferenca_data = $data_inicio->diff($data_fim); if ($diferenca_data->days == 1) { $diaria = '1 diária'; }else{ $diaria = $diferenca_data->days.' diárias'; } ?> <!-- Blog Section with Sidebar --> <style type="text/css"> .page-builder { display: none } .page-title-section { display: none } .attachment-post-thumbnail{ display: block; max-width: 100%; height: 250px;} .collapse { padding: 0; height: 0px } .collapse.in { padding: 20px; height: 168px } </style> <div class="page-builder2" style="background-color: #eaeaea"> <link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet"> <style type="text/css"> .input-group{ position: relative; display: -webkit-box; display: -ms-flexbox; display: flex; -ms-flex-wrap: wrap; flex-wrap: wrap; -webkit-box-align: stretch; -ms-flex-align: stretch; align-items: stretch; width: 100%; } .input-group-prepend { margin-right: -1px; } .input-group-append, .input-group-prepend { display: -webkit-box; display: -ms-flexbox; display: flex; } .input-group-text { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-align: center; -ms-flex-align: center; align-items: center; padding: .375rem .75rem; margin-bottom: 0; font-size: 1rem; font-weight: 400; line-height: 1.5; color: #495057; text-align: center; white-space: nowrap; background-color: #e9ecef; border: 1px solid #ced4da; border-radius: .25rem; } .input-group>.custom-file, .input-group>.custom-select, .input-group>.form-control { position: relative; -webkit-box-flex: 1; -ms-flex: 1 1 auto; flex: 1 1 auto; width: 1%; margin-bottom: 0; } @media(max-width: 800px){ .navbar-brand img{ height: 42px } .img-div-responsive{ padding: 0 0px 9px 0px !important; } .exibirComputador{ display: none !important; } .exibirCelular{ display: block !important; } .titulo{ font-size: 1.5rem !important; font-weight: 700 !important; } .subtitulo{ font-size: 1.0rem !important; } .carousel{ margin: 10px !important } .filtro{ padding-right: 15px !important } .hotel{ padding: 14px } .centeri{ text-align: center; } .borderC{ border: 1px solid #ddd; margin: 0px 17px 0px 14px; height: auto !important; } } .exibirComputador{ visibility: initial; } .exibirCelular{ display: none; } .titulo{ font-size: 2.8rem;font-weight: 400; } .subtitulo{ font-size: 1.4rem;font-weight: 400 } .font{ font-family: 'Raleway', sans-serif !important; } .nofont{ font-family: 'Arial', sans-serif !important; } .carousel{ margin-left: 10px;margin-right: -12px;margin-top: 10px; } .btn-primary{ background-color: #2f4050 !important; border-color: #2f4050 !important; } .btn-primary:hover{ background-color: #fff !important; border-color: #2f4050 !important; color: #2f4050 !important; } .filtro{ padding-right: 0 } .infoBox { background-color: #FFF; width: 300px; font-size: 14px; border: 1px solid #3fa7d8; border-radius: 3px; margin-top: 10px } .infoBox p { padding: 6px } .infoBox:before { border-left: 10px solid transparent; border-right: 10px solid transparent; border-bottom: 10px solid #3fa7d8; top: -10px; content: ""; height: 0; position: absolute; width: 0; left: 138px } html { position: relative; min-height: 100%; } body { /* Margin bottom by footer height */ margin-bottom: 60px; } .footer { position: absolute; bottom: 0; width: 100%; /* Set the fixed height of the footer here */ height: 50px; line-height: 46px; /* Vertically center the text there */ background-color: #585858; border-top: 4px solid;border-color: #999; } .text-muted{ color: #999999 !important;font-size:16px; } .esconde{ display: none; } .exibe{ display: block; } @media(max-width: 959px){ .imgHotel{ width: 93%; } } @media(min-width: 960px) and (max-width: 961px){ .imgHotel{ width: 97%; } } @media(min-width: 411px) and (max-width: 559px){ .footer { text-align: center !important; line-height: 20px; } .text-muted{ text-align: center !important; } .exibeCelular{ bottom: auto !important; } } @media(max-width: 400px){ .footer { text-align: center !important; line-height: 20px; } .text-muted{ text-align: center !important; } .exibeCelular{ bottom: auto !important; } } @media(min-width: 600px){ .text-muted{ float: right; } .exibirComputador{ display: block !important; } } .navbar-light .navbar-nav .nav-link { color: rgba(0,0,0,.5) !important; } #google_translate_element { display: none; } .goog-te-banner-frame { display: none !important; } .exibirComputador{ display: none; } .tooltip.show { opacity: .9; z-index: 0; margin-left: 5px; } .qty .count, .qty .count_child, .qty .count_quartos { color: #000; display: inline-block; vertical-align: top; font-size: 22px; font-weight: 700; line-height: 30px; padding: 0 2px ;min-width: 35px; text-align: center; margin-top: -11px; } .qty .plus, .qty .plus_child, .qty .plus_quartos { cursor: pointer; display: inline-block; vertical-align: top; color: white; width: 26px; height: 26px; font: 25px/1 Arial,sans-serif; text-align: center; border-radius: 50%; } .qty .minus, .qty .minus_child, .qty .minus_quartos { cursor: pointer; display: inline-block; vertical-align: top; color: white; width: 26px; height: 26px; font: 25px/1 Arial,sans-serif; text-align: center; border-radius: 50%; background-clip: padding-box; } .minus, .minus_child, .minus_quartos{ background-color: #aaa !important; } .plus, .plus_child, .plus_quartos{ background-color: #aaa !important; } .minus:hover, .minus_child:hover, .minus_quartos:hover{ background-color: #e8b90d !important; } .plus:hover, .plus_child:hover, .plus_quartos:hover{ background-color: #e8b90d !important; } /*Prevent text selection*/ span{ -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; } .input_number{ border: 0; width: 2%; } nput::-webkit-outer-spin-button, input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } input:disabled{ background-color:white; } .xpi__content__wrappergray { background: #f5f5f5; } .xpi__content__wrapper { background: #002f72; margin-bottom: 24px; border-bottom: 1px solid #e6e6e6; } .xpi__searchbox { padding: 44px 5px; position: relative; } .xpi__searchbox { max-width: 1110px; padding: 40px 5px 16px; margin: 0 auto; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .xpi__content__wrappergray .xpi__searchbox .sb-searchbox__title, .xpi__content__wrappergray .xpi__searchbox .sb-searchbox__subtitle-text { color: #333; } .xpi__searchbox .sb-searchbox__title { font-size: 24px; line-height: 32px; font-weight: 600; font-weight: 600; } .sb-searchbox__title { margin: 0; padding: 0; font-size: 26px; font-weight: normal; } .xpi__content__wrappergray .xpi__searchbox .sb-searchbox__title, .xpi__content__wrappergray .xpi__searchbox .sb-searchbox__subtitle-text { color: #333; } .xpi__searchbox .sb-searchbox__title { font-size: 24px; line-height: 32px; font-weight: 600; font-weight: 600; } .xpi__searchbox .sb-searchbox__subtitle-text { font-size: 14px; line-height: 20px; font-weight: 400; } .sb-searchbox--painted { font-size: 14px; line-height: 20px; font-weight: 400; background: 0; border-radius: 0; border: 0; padding: 0; } .xp__fieldset { color: #333; border: 0; display: table; background-color: #febb02; padding: 4px; border-radius: 4px; margin: 24px 0 16px; position: relative; width: 100%; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } @media(max-width: 320px){ .marginGallery{ margin: 0px 9px 0px -4px !important; } .imgWidth{ width: 160% !important; } .tituloHotel{ font-size: 1.5rem !important; margin-top: 16px!important; } .paddingRow{ padding: 0 15px 0 15px !important; } .fontSizeP{ font-size: 14px !important; } .fontSizePreco{ font-size: .805rem !important; } .paddingCelular{ padding-left: 4px !important;; } .colNomeCelular { margin: 0 -7px 0 -14px !important; } .col1Celular{ margin: 0 -9px 0 -14px !important; } .col2Celular{ margin: 0 9px 0 4px !important; } .borderCelular{ border-right: none !important; } } @media (min-width: 350px) and (max-width: 414px){ .imgWidth{ width: 130% !important; } .marginGallery { margin: 0px 8px 0px -4px !important; } .tituloHotel{ font-size: 1.5rem !important; margin-top: 16px!important; } .paddingRow{ padding: 0 15px 0 15px !important; } .fontSizeP{ font-size: .805rem !important; } .fontSizePreco{ font-size: .805rem !important; } .paddingCelular{ padding-left: 8px !important; } .colNomeCelular{ margin: 0 -4px 0 -5px !important; } } @media(min-width: 1650px){ .imgHotel{ width: 100% !important; height: 252px !important; } .imgWidth{ width: 130% !important; } } .marginGallery{ margin: 0px -3px 0px -4px; } .imgWidth{ width: 160%; } .tituloHotel{ font-size: 2rem; margin-top: 4px; } .paddingRow{ padding: 0; } .fontSizeP{ font-size: 14px; } .fontSizePreco{ font-size: 14px; } .borderCelular{ border-right: 1px solid #ddd; } .centerizar{ display: -webkit-flex !important; display: flex !important; -webkit-align-items: center !important; align-items: center !important; } .row { display: -ms-flexbox; display: flex; -ms-flex-wrap: wrap; flex-wrap: wrap; margin-right: -15px; margin-left: -15px; } .justify-content-center { -ms-flex-pack: center!important; justify-content: center!important; } </style> <div class="container"> <br><br> <div class="row justify-content-center font hotel" > <div class="col-lg-9 col-xs-12"> <h4><strong>Falta pouco! Complete seus dados e finalize sua compra.</strong></h4> <div style="background-color: #fff;padding: 20px"> <h4><strong>Complete com os dados do cartão</strong></h4> <div class="row"> <div class="col-lg-6 col-xs-12"> <label style="font-size: 13px;color: #0b0b0b"><strong>NÚMERO</strong></label> <input type="text" class="form-control numero_cartao" placeholder="Número do cartão" name="" maxlength="20"> </div> <div class="col-lg-6 col-xs-12"> <label style="font-size: 13px;color: #0b0b0b"><strong>TITULAR</strong></label> <input type="text" class="form-control titular" placeholder="Como aparece no cartão" name=""> </div> </div> <br> <div class="row"> <div class="col-lg-3 col-xs-6"> <label style="font-size: 13px;color: #0b0b0b"><strong>VENCIMENTO</strong></label> <input type="text" class="form-control vencimento_cartao" placeholder="MM/AA" name="" maxlength="5"> </div> <div class="col-lg-3 col-xs-6"> <label style="font-size: 13px;color: #0b0b0b"><strong>CÓD. SEGURANÇA</strong></label> <input type="password" class="form-control cod_cartao" placeholder="" name="" maxlength="4"> </div> <div class="col-lg-6 col-xs-12"> <label style="font-size: 13px;color: #0b0b0b"><strong>CPF</strong></label> <input type="text" class="form-control cpf_cartao" placeholder="Ex. 123.456.789-00" name="" maxlength="14"> </div> </div> <br> <hr> <div class="row"> <div class="col-lg-12 col-xs-12"> <div class="accordion" id="accordionExample" style=" background-color: #ddd;"> <div class="card"> <div class="card-header" id="headingOne"> <h2 class="" style="margin-bottom: 0"> <button class="btn btn-link" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne" style="color: #7f7f7f"> <strong>Selecione em quantas parcelas você quer pagar</strong> </button> </h2> </div> <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordionExample" style=""> <div class="card-body"> <input type="radio" name="check_parcelas" value="0" style="margin-right: 6px"> <strong style="color: #7f7f7f">A vista</strong> <hr style="margin-top: 4px;margin-bottom: 4px"> <input type="radio" name="check_parcelas" value="1" style="margin-right: 6px"> <strong style="color: #7f7f7f">1x de 0.00</strong> <hr style="margin-top: 4px;margin-bottom: 4px"> <input type="radio" name="check_parcelas" value="2" style="margin-right: 6px"> <strong style="color: #7f7f7f">2x de 0.00</strong> <hr style="margin-top: 4px;margin-bottom: 4px"> <input type="radio" name="check_parcelas" value="3" style="margin-right: 6px"> <strong style="color: #7f7f7f">3x de 0.00</strong> </div> </div> </div> </div> </div> </div> </div> <br> <div style="background-color: #fff;padding: 20px"> <h4><strong>Quem será o titular da reserva?</strong></h4> <div class="row"> <div class="col-lg-7 col-xs-12"> <h5 style="margin-bottom: 0">Adulto 1</h5> <small>Será o responsável por fazer check-in e check-out na hospedagem.</small> <br> <label style="font-size: 13px;color: #0b0b0b"><strong>NOME</strong></label> <input type="text" class="form-control" placeholder="Insira o nome do passageiro" name="" maxlength="30" style="margin-bottom: 8px"> <label style="font-size: 13px;color: #0b0b0b"><strong>ÚLTIMO SOBRENOME</strong></label> <input type="text" class="form-control" placeholder="Insira o último sobrenome do passageiro" name="" maxlength="30"> </div> </div> </div> <div class="row" style="padding: 19px;"> <div class="col-lg-12 col-xs-12" style="color: #3a3a3a;"> <input type="checkbox" name="" style="margin-right: 8px"> Li e aceito a política de privacidade. </div> </div> </div> <div class="col-lg-3 col-xs-12"> <div style="color: #3a3a3a;background-color: #fff;padding: 16px"> <strong style="color: #3a3a3a">Dados da sua reserva</strong> <div class="row" style="margin-top: 9px;margin-bottom: 9px"> <div class="col-lg-6 col-xs-12" style="border-right: 1px solid #aaa;color: #3a3a3a;font-size: 14px;line-height: 1.5;"> <small>Entrada</small><br> <strong>ter, 28 de abr de 2021</strong><br> 14:00 - 22:00 </div> <div class="col-lg-6 col-xs-12" style="color: #3a3a3a;font-size: 14px;line-height: 1.5;"> <small>Saída</small><br> <strong>sex, 23 de abr de 2021</strong><br> 08:00 - 12:00 </div> </div> <small>Duração total da hospedagem</small><br> <small><strong>3 diárias</strong></small> <hr style="margin-top: 15px;margin-bottom: 15px"> <small><strong>Você selecionou:</strong></small><br> <small>Quarto duplo standard</small> <hr style="margin-top: 15px;margin-bottom: 15px"> <small><strong>Resumo do preço</strong></small><br> <div class="row" style="margin-top: 9px;margin-bottom: 9px"> <div class="col-lg-8 col-xs-8" style="color: #3a3a3a;font-size: 14px;line-height: 1.5;"> <small>Quarto duplo standard</small><br> <small>5% ISS</small><br> </div> <div class="col-lg-4 col-xs-4" style="color: #3a3a3a;font-size: 14px;line-height: 1.5;text-align: right;"> <small style="font-size: 14px">250,00</small><br> <small style="font-size: 14px">12,50</small><br> </div> </div> <div class="row" style="margin-top: 9px;margin-bottom: 9px;background-color: #d7ebff;padding-top: 10px;padding-bottom: 10px;"> <div class="col-lg-8 col-xs-8" style="color: #3a3a3a;font-size: 14px;line-height: 1.5;"> <small><strong>Preço</strong></small><br> <small>(2 hóspedes e 3 diárias)</small><br> </div> <div class="col-lg-4 col-xs-4" style="color: #3a3a3a;font-size: 14px;line-height: 1.5;text-align: right;"> <small style="font-size: 14px"><strong>262,50</strong></small><br> </div> </div> </div> </div> </div> <br> </div> <br><br> </div> <input type="hidden" id="uri" name="" value="<?=$_SERVER['REQUEST_URI']?>"> <script src="<?=plugins_url( '../assets/js/mask.js', __FILE__ )?>"></script> <script type="text/javascript"> function show_div_count(){ jQuery(".dropdown").toggle(500); } jQuery(".numero_cartao").mask("0000 0000 0000 0000"); jQuery(".vencimento_cartao").mask("00/00"); jQuery(".cod_cartao").mask("000"); jQuery(".cpf_cartao").mask("000.000.000-00"); jQuery(document).ready(function(){ jQuery('.count').prop('disabled', true); jQuery(document).on('click','.plus',function(){ var valor = parseInt(jQuery('.count').val()) + 1; jQuery('.count').val(valor); jQuery("#count_adultos").html("<strong>"+valor+" adultos</strong>"); }); jQuery(document).on('click','.minus',function(){ var valor = parseInt(jQuery('.count').val()) - 1; jQuery('.count').val(valor); jQuery("#count_adultos").html("<strong>"+valor+" adultos</strong>"); if (jQuery('.count').val() == 0 || jQuery('.count').val() == 1) { jQuery('.count').val(1); jQuery("#count_adultos").html("<strong>1 adulto</strong>"); } }); jQuery('.count_child').prop('disabled', true); jQuery(document).on('click','.plus_child',function(){ var valor = parseInt(jQuery('.count_child').val()) + 1; jQuery('.count_child').val(valor); jQuery("#count_criancas").html("<strong>"+valor+" crianças</strong>"); if (jQuery('.count_child').val() == 1) { jQuery('.count_child').val(1); jQuery("#count_criancas").html("<strong>1 criança</strong>"); } }); jQuery(document).on('click','.minus_child',function(){ var valor = parseInt(jQuery('.count_child').val()) - 1; jQuery('.count_child').val(valor); jQuery("#count_criancas").html("<strong>"+valor+" crianças</strong>"); if (jQuery('.count_child').val() == 0) { jQuery('.count_child').val(1); jQuery("#count_criancas").html("<strong>0 criança</strong>"); } if (jQuery('.count_child').val() == 1) { jQuery('.count_child').val(1); jQuery("#count_criancas").html("<strong>1 criança</strong>"); } }); jQuery('.count_quartos').prop('disabled', true); jQuery(document).on('click','.plus_quartos',function(){ var valor = parseInt(jQuery('.count_quartos').val()) + 1; jQuery('.count_quartos').val(valor); jQuery("#count_quartos").html("<strong>"+valor+" quartos</strong>"); }); jQuery(document).on('click','.minus_quartos',function(){ var valor = parseInt(jQuery('.count_quartos').val()) - 1; jQuery('.count_quartos').val(valor); jQuery("#count_quartos").html("<strong>"+valor+" quartos</strong>"); if (jQuery('.count_quartos').val() == 0 || jQuery('.count_quartos').val() == 1) { jQuery('.count_quartos').val(1); jQuery("#count_quartos").html("<strong>1 quarto</strong>"); } }); }); function AtribuiValorHotel(id){ var dados = jQuery("#nameHotel"+id).val(); var uri = jQuery("#uri").val(); dados = dados.split(";"); jQuery("#uri").val('/apto/?param=Comfort-Vista-Mar;343;hotel-copacabana-palace'); } function enviarFormTodos(){ var uri = jQuery("#uri").val(); window.location.href = uri; } </script> <!-- /Blog Section with Sidebar --> <?php get_footer(); ?><file_sep><?php session_start(); $_SESSION['hostBanco'] = 'montenegroev_FrontOfficeMaiorca.sqlserver.dbaas.com.br'; $_SESSION['nomeBanco'] = 'montenegroev_FrontOfficeMaiorca'; $_SESSION['userBanco'] = 'montenegroev_FrontOfficeMaiorca'; $_SESSION['senhaBanco'] = 'Maiorca#2021'; require_once('v2/Functions/conexaoCliente.php'); function cron_job_maiorca(){ try{ $con = conectDB(); $stmt = $con->prepare("EXEC FD_Executa_Todas_Procedures"); if($stmt->execute()){ $stmt_exec = $con->prepare("EXEC FD_Executa_Todas_Procedures"); $stmt_exec->execute(); $stmt_exec1 = $con->prepare("EXEC FD_Executa_Todas_Procedures"); $stmt_exec1->execute(); $stmt_exec2 = $con->prepare("EXEC FD_Executa_Todas_Procedures"); $stmt_exec2->execute(); $stmt = $con->prepare("update fd_faturas set Excluir = 'SIM', Status = 'Recebida' WHERE Fatura = 'FT00184488'"); $stmt->execute(); $stmt2 = $con->prepare("update fd_faturas set Excluir = 'SIM', Status = 'Recebida' WHERE Fatura = 'FT00184285'"); $stmt2->execute(); $stmt3 = $con->prepare("update fd_faturas set Excluir = 'SIM', Status = 'Recebida' WHERE Fatura = 'FT00184284'"); $stmt3->execute(); $stmt4 = $con->prepare("update fd_faturas set Excluir = 'SIM', Status = 'Recebida' WHERE Fatura = 'FT00183706'"); $stmt4->execute(); $stmt5 = $con->prepare("update fd_faturas set Excluir = 'SIM', Status = 'Recebida' WHERE Fatura = 'FT00182899'"); $stmt5->execute(); $stmt6 = $con->prepare("update fd_faturas set Excluir = 'SIM', Status = 'Recebida' WHERE Fatura = 'FT00183702'"); $stmt6->execute(); $stmt7 = $con->prepare("update fd_faturas set Excluir = 'SIM', Status = 'Recebida' WHERE Fatura = 'FT00184220'"); $stmt7->execute(); $stmt8 = $con->prepare("update fd_faturas set Excluir = 'SIM', Status = 'Recebida' WHERE Fatura = 'FT00184232'"); $stmt8->execute(); $stmt9 = $con->prepare("update fd_faturas set Excluir = 'SIM', Status = 'Recebida' WHERE Fatura = 'FT00184222'"); $stmt9->execute(); $stmt10 = $con->prepare("update fd_faturas set Excluir = 'SIM', Status = 'Recebida' WHERE Fatura = 'FT00184204'"); $stmt10->execute(); $stmt11 = $con->prepare("update fd_faturas set Excluir = 'SIM', Status = 'Recebida' WHERE Fatura = 'FT00184228'"); $stmt11->execute(); $stmt12 = $con->prepare("update fd_faturas set Excluir = 'SIM', Status = 'Recebida' WHERE Fatura = 'FT00184488'"); $stmt12->execute(); $stmt13 = $con->prepare("update fd_faturas set Excluir = 'SIM', Status = 'Recebida' WHERE Fatura = 'FT00184285'"); $stmt13->execute(); $stmt14 = $con->prepare("update fd_faturas set Excluir = 'SIM', Status = 'Recebida' WHERE Fatura = 'FT00184284'"); $stmt14->execute(); }else{ return false; } }catch (PDOException $e){ echo "Error" . $e->getMessage(); } } cron_job_maiorca(); ?><file_sep>jQuery(document).ready(function(){ jQuery("#shortcode").html('Shortcode para confirmação: <span><input type="text" value="[LGPD_NEWSLETTERS]" id="myInput" style="width: 36%;background-color: #ddd;font-weight: 700;border: none;cursor: not-allowed;color:#72777c;" onclick="return copy_text_lgpd()" placeholder="[LGPD_NEWSLETTERS]"> <button type="button" onclick="return copy_text_lgpd()" class="button button-secondary btn_copy_text">Copiar</button> </span>'); }); function copy_text_lgpd() { jQuery("#myInput").select(); document.execCommand("copy"); /* Alert the copied text */ jQuery(".btn_copy_text").html("<i class='fa fa-check'></i> Copiado"); jQuery("#myInput").attr("style", "width: 36%;background-color: #ddd;font-weight: 700;border: none;cursor: not-allowed;color:#72777c"); setTimeout(function(){ jQuery(".term-name-wrap").removeClass("form-invalid"); }, 10); setTimeout(function(){ jQuery(".btn_copy_text").html("Copiar"); jQuery("#myInput").attr("style", "width: 36%;background-color: #ddd;font-weight: 700;border: none;cursor: not-allowed;color:#72777c"); }, 2000); } <file_sep><?php get_header(); session_start(); global $woocommerce; $woocommerce->cart->empty_cart(); $_SESSION['teste'] = $_POST['periodo']; $_SESSION['valor_taxas'] = $_POST['valor_taxas']; $dados = explode(";", $_GET['param']); $the_slug = $dados[2]; $args = array( 'name' => $the_slug, 'post_type' => 'ttbooking', 'post_status' => 'publish', 'numberposts' => 1 ); $my_posts = get_posts($args); $title = $my_posts[0]->post_title; $description = $my_posts[0]->post_content; $id = $my_posts[0]->ID; $thumb_id = get_post_thumbnail_id($id); $thumb_url = wp_get_attachment_image_src($thumb_id,'thumbnail-size', true); $url = $thumb_url[0]; $localizacao = ''; $cat_terms = get_terms( array('localizacao'), array( 'hide_empty' => false, 'orderby' => 'name', 'order' => 'ASC', 'number' => 6 //specify yours ) ); if( $cat_terms ){ foreach( $cat_terms as $term ) { $args = array( 'post_type' => 'ttbooking', 'posts_per_page' => 10, //specify yours 'post_status' => 'publish', 'tax_query' => array( array( 'taxonomy' => 'localizacao', 'field' => 'slug', 'terms' => $term->slug, ), ), 'ignore_sticky_posts' => true //caller_get_posts is deprecated since 3.1 ); $_posts = new WP_Query( $args ); if( $_posts->have_posts() ) : while( $_posts->have_posts() ) : $_posts->the_post(); $post = get_post(); if ($post->ID == $id) { $localizacao .= '<i class="fa fa-map"></i> <span style="margin-right:8px;">'.$term->name.'</span>'; } ?> <?php endwhile; endif; wp_reset_postdata(); //important } } /************************************************************************/ $servicos = ''; $cat_terms = get_terms( array('servicos'), array( 'hide_empty' => false, 'orderby' => 'name', 'order' => 'ASC', 'number' => 50 //specify yours ) ); if( $cat_terms ){ $contador = 0; foreach( $cat_terms as $term ) { $args = array( 'post_type' => 'ttbooking', 'posts_per_page' => 50, //specify yours 'post_status' => 'publish', 'tax_query' => array( array( 'taxonomy' => 'servicos', 'field' => 'slug', 'terms' => $term->slug, ), ), 'ignore_sticky_posts' => true //caller_get_posts is deprecated since 3.1 ); $_posts = new WP_Query( $args ); if( $_posts->have_posts() ) : while( $_posts->have_posts() ) : $_posts->the_post(); $post = get_post(); if ($post->ID == $id) { $contador++; $servicos .= '<span style="background-color:#eaeaea;padding:5px"><i class="fa fa-info" style="font-size: 13px;"></i> <span style="margin-right:8px;margin-left: 6px;margin-top: -4px;font-size: 13px;">'.$term->name.'</span></span> '; if (0 == ($contador % 6)){ $servicos .= '<br>'; } } ?> <?php endwhile; endif; wp_reset_postdata(); //important } } $query_args = array( 'post_type' => 'product', 'meta_query' => array( array( 'key' => 'demo_product_info', 'value' => str_replace("-", " ", $dados[0]), ), ) ); $query = new WP_Query( $query_args ); $apartamentos = []; $id_produto = $dados[1]; $periodo_product_info_inicial = get_post_meta( $id_produto, 'periodo_product_info', true ); $tar_periodo_product_info_inicial = get_post_meta( $id_produto, 'tar_periodo_product_info', true ); $tar_periodo_final_product_info_inicial = get_post_meta( $id_produto, 'tar_periodo_final_product_info', true ); $tar_valor_final_product_info_inicial = get_post_meta( $id_produto, 'tar_valor_final_product_info', true ); $periodo_product_info2 = get_post_meta( $id_produto, 'periodo_product_info1', true ); $tar_periodo_product_info2 = get_post_meta( $id_produto, 'tar_periodo_product_info1', true ); $tar_periodo_final_product_info2 = get_post_meta( $id_produto, 'tar_periodo_final_product_info1', true ); $tar_valor_final_product_info2 = get_post_meta( $id_produto, 'tar_valor_final_product_info1', true ); $periodo_product_info3 = get_post_meta( $id_produto, 'periodo_product_info2', true ); $tar_periodo_product_info3 = get_post_meta( $id_produto, 'tar_periodo_product_info2', true ); $tar_periodo_final_product_info3 = get_post_meta( $id_produto, 'tar_periodo_final_product_info2', true ); $tar_valor_final_product_info3 = get_post_meta( $id_produto, 'tar_valor_final_product_info2', true ); $diarias .= '{ "start": "'.$tar_periodo_product_info_inicial.'", "end": "'.$tar_periodo_final_product_info_inicial.'", "valor": "'.str_replace(",", ".", str_replace(".", "", $tar_valor_final_product_info_inicial)).'" },'; $contador = 0; for ($i=0; $i < 10; $i++) { $tar_periodo_product_info = get_post_meta( $id_produto, 'tar_periodo_product_info'.$i, true ); $tar_periodo_final_product_info = get_post_meta( $id_produto, 'tar_periodo_final_product_info'.$i, true ); $tar_valor_final_product_info = get_post_meta( $id_produto, 'tar_valor_final_product_info'.$i, true ); if (!empty(get_post_meta( $id_produto, 'tar_periodo_product_info'.$i, true ))) { $diarias .= '{ "start": "'.$tar_periodo_product_info.'", "end": "'.$tar_periodo_final_product_info.'", "valor": "'.str_replace(",", ".", str_replace(".", "", $tar_valor_final_product_info)).'" },'; } } $valores_datas = '['.$diarias.']'; ?> <!-- Blog Section with Sidebar --> <style type="text/css"> .page-builder, .error-section { display: none !important } .page-title-section { display: none } .attachment-post-thumbnail{ display: block; max-width: 100%; height: 250px;} </style> <div class="page-builder2"> <input type='hidden' id='diarias' value='[<?=substr($diarias, 0, -1)?>]'> <link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet"> <style type="text/css"> .input-group{ position: relative; display: -webkit-box; display: -ms-flexbox; display: flex; -ms-flex-wrap: wrap; flex-wrap: wrap; -webkit-box-align: stretch; -ms-flex-align: stretch; align-items: stretch; width: 100%; } .input-group-prepend { margin-right: -1px; } .input-group-append, .input-group-prepend { display: -webkit-box; display: -ms-flexbox; display: flex; } .input-group-text { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-align: center; -ms-flex-align: center; align-items: center; padding: .375rem .75rem; margin-bottom: 0; font-size: 1rem; font-weight: 400; line-height: 1.5; color: #495057; text-align: center; white-space: nowrap; background-color: #e9ecef; border: 1px solid #ced4da; border-radius: .25rem; } .input-group>.custom-file, .input-group>.custom-select, .input-group>.form-control { position: relative; -webkit-box-flex: 1; -ms-flex: 1 1 auto; flex: 1 1 auto; width: 1%; margin-bottom: 0; } @media(max-width: 800px){ .navbar-brand img{ height: 42px } .img-div-responsive{ padding: 0 0px 9px 0px !important; } .exibirComputador{ display: none !important; } .exibirCelular{ display: block !important; } .titulo{ font-size: 1.5rem !important; font-weight: 700 !important; } .subtitulo{ font-size: 1.0rem !important; } .carousel{ margin: 10px !important } .filtro{ padding-right: 15px !important } .hotel{ padding: 14px } .centeri{ text-align: center; } .borderC{ border: 1px solid #ddd; margin: 0px 17px 0px 14px; height: auto !important; } } .exibirComputador{ visibility: initial; } .exibirCelular{ display: none; } .titulo{ font-size: 2.8rem;font-weight: 400; } .subtitulo{ font-size: 1.4rem;font-weight: 400 } .font{ font-family: 'Raleway', sans-serif !important; } .nofont{ font-family: 'Arial', sans-serif !important; } .carousel{ margin-left: 10px;margin-right: -12px;margin-top: 10px; } .btn-primary{ background-color: #2f4050 !important; border-color: #2f4050 !important; } .btn-primary:hover{ background-color: #fff !important; border-color: #2f4050 !important; color: #2f4050 !important; } .filtro{ padding-right: 0 } .infoBox { background-color: #FFF; width: 300px; font-size: 14px; border: 1px solid #3fa7d8; border-radius: 3px; margin-top: 10px } .infoBox p { padding: 6px } .infoBox:before { border-left: 10px solid transparent; border-right: 10px solid transparent; border-bottom: 10px solid #3fa7d8; top: -10px; content: ""; height: 0; position: absolute; width: 0; left: 138px } html { position: relative; min-height: 100%; } body { /* Margin bottom by footer height */ margin-bottom: 60px; } .footer { position: absolute; bottom: 0; width: 100%; /* Set the fixed height of the footer here */ height: 50px; line-height: 46px; /* Vertically center the text there */ background-color: #585858; border-top: 4px solid;border-color: #999; } .text-muted{ color: #999999 !important;font-size:16px; } .esconde{ display: none; } .exibe{ display: block; } @media(max-width: 959px){ .imgHotel{ width: 93%; } } @media(min-width: 960px) and (max-width: 961px){ .imgHotel{ width: 97%; } } @media(min-width: 411px) and (max-width: 559px){ .footer { text-align: center !important; line-height: 20px; } .text-muted{ text-align: center !important; } .exibeCelular{ bottom: auto !important; } } @media(max-width: 400px){ .footer { text-align: center !important; line-height: 20px; } .text-muted{ text-align: center !important; } .exibeCelular{ bottom: auto !important; } } @media(min-width: 600px){ .text-muted{ float: right; } .exibirComputador{ display: block !important; } } .navbar-light .navbar-nav .nav-link { color: rgba(0,0,0,.5) !important; } #google_translate_element { display: none; } .goog-te-banner-frame { display: none !important; } .exibirComputador{ display: none; } .tooltip.show { opacity: .9; z-index: 0; margin-left: 5px; } .qty .count, .qty .count_child, .qty .count_quartos { color: #000; display: inline-block; vertical-align: top; font-size: 22px; font-weight: 700; line-height: 30px; padding: 0 2px ;min-width: 35px; text-align: center; margin-top: -11px; } .qty .plus, .qty .plus_child, .qty .plus_quartos { cursor: pointer; display: inline-block; vertical-align: top; color: white; width: 26px; height: 26px; font: 25px/1 Arial,sans-serif; text-align: center; border-radius: 50%; } .qty .minus, .qty .minus_child, .qty .minus_quartos { cursor: pointer; display: inline-block; vertical-align: top; color: white; width: 26px; height: 26px; font: 25px/1 Arial,sans-serif; text-align: center; border-radius: 50%; background-clip: padding-box; } .minus, .minus_child, .minus_quartos{ background-color: #aaa !important; } .plus, .plus_child, .plus_quartos{ background-color: #aaa !important; } .minus:hover, .minus_child:hover, .minus_quartos:hover{ background-color: #e8b90d !important; } .plus:hover, .plus_child:hover, .plus_quartos:hover{ background-color: #e8b90d !important; } /*Prevent text selection*/ span{ -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; } .input_number{ border: 0; width: 2%; } nput::-webkit-outer-spin-button, input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } input:disabled{ background-color:white; } .xpi__content__wrappergray { background: #f5f5f5; } .xpi__content__wrapper { background: #002f72; margin-bottom: 24px; border-bottom: 1px solid #e6e6e6; } .xpi__searchbox { padding: 44px 5px; position: relative; } .xpi__searchbox { max-width: 1110px; padding: 40px 5px 16px; margin: 0 auto; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .xpi__content__wrappergray .xpi__searchbox .sb-searchbox__title, .xpi__content__wrappergray .xpi__searchbox .sb-searchbox__subtitle-text { color: #333; } .xpi__searchbox .sb-searchbox__title { font-size: 24px; line-height: 32px; font-weight: 600; font-weight: 600; } .sb-searchbox__title { margin: 0; padding: 0; font-size: 26px; font-weight: normal; } .xpi__content__wrappergray .xpi__searchbox .sb-searchbox__title, .xpi__content__wrappergray .xpi__searchbox .sb-searchbox__subtitle-text { color: #333; } .xpi__searchbox .sb-searchbox__title { font-size: 24px; line-height: 32px; font-weight: 600; font-weight: 600; } .xpi__searchbox .sb-searchbox__subtitle-text { font-size: 14px; line-height: 20px; font-weight: 400; } .sb-searchbox--painted { font-size: 14px; line-height: 20px; font-weight: 400; background: 0; border-radius: 0; border: 0; padding: 0; } .xp__fieldset { color: #333; border: 0; display: table; background-color: #febb02; padding: 4px; border-radius: 4px; margin: 24px 0 16px; position: relative; width: 100%; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } @media(max-width: 320px){ .marginGallery{ margin: 0px 9px 0px -4px !important; } .imgWidth{ width: 160% !important; } .tituloHotel{ font-size: 1.5rem !important; margin-top: 16px!important; } .paddingRow{ padding: 0 15px 0 15px !important; } .fontSizeP{ font-size: 14px !important; } .fontSizePreco{ font-size: .805rem !important; } .paddingCelular{ padding-left: 4px !important;; } .colNomeCelular { margin: 0 -7px 0 -14px !important; } .col1Celular{ margin: 0 -9px 0 -14px !important; } .col2Celular{ margin: 0 9px 0 4px !important; } .borderCelular{ border-right: none !important; } } @media (min-width: 350px) and (max-width: 414px){ .imgWidth{ width: 130% !important; } .marginGallery { margin: 0px 8px 0px -4px !important; } .tituloHotel{ font-size: 1.5rem !important; margin-top: 16px!important; } .paddingRow{ padding: 0 15px 0 15px !important; } .fontSizeP{ font-size: .805rem !important; } .fontSizePreco{ font-size: .805rem !important; } .paddingCelular{ padding-left: 8px !important; } .colNomeCelular{ margin: 0 -4px 0 -5px !important; } } @media(min-width: 1650px){ .imgHotel{ width: 100% !important; height: 252px !important; } .imgWidth{ width: 130% !important; } } .marginGallery{ margin: 0px -3px 0px -4px; } .imgWidth{ width: 160%; } .tituloHotel{ font-size: 2rem; margin-top: 4px; } .paddingRow{ padding: 0; } .fontSizeP{ font-size: 14px; } .fontSizePreco{ font-size: 14px; } .borderCelular{ border-right: 1px solid #ddd; } .centerizar{ display: -webkit-flex !important; display: flex !important; -webkit-align-items: center !important; align-items: center !important; } .row { display: -ms-flexbox; display: flex; -ms-flex-wrap: wrap; flex-wrap: wrap; margin-right: -15px; margin-left: -15px; } .justify-content-center { -ms-flex-pack: center!important; justify-content: center!important; } /*** Bootstrap Line Tabs by @keenthemes A component of Metronic Theme - #1 Selling Bootstrap 3 Admin Theme in Themeforest: http://j.mp/metronictheme Licensed under MIT ***/ /* Tabs panel */ /* Default mode */ .tabbable-line > .nav-tabs { border: none; margin: 0px; } .tabbable-line > .nav-tabs > li { margin-right: 2px; } .tabbable-line > .nav-tabs > li > a { border: 0; margin-right: 0; color: #737373; } .tabbable-line > .nav-tabs > li > a > i { color: #a6a6a6; } .tabbable-line > .nav-tabs > li.open, .tabbable-line > .nav-tabs > li:hover { border-bottom: 4px solid #fbcdcf; } .tabbable-line > .nav-tabs > li.open > a, .tabbable-line > .nav-tabs > li:hover > a { border: 0; background: none !important; color: #333333; } .tabbable-line > .nav-tabs > li.open > a > i, .tabbable-line > .nav-tabs > li:hover > a > i { color: #a6a6a6; } .tabbable-line > .nav-tabs > li.open .dropdown-menu, .tabbable-line > .nav-tabs > li:hover .dropdown-menu { margin-top: 0px; } .tabbable-line > .nav-tabs > li.active { border-bottom: 4px solid #f3565d; position: relative; } .tabbable-line > .nav-tabs > li.active > a { border: 0; color: #333333; } .tabbable-line > .nav-tabs > li.active > a > i { color: #404040; } .tabbable-line > .tab-content { margin-top: -3px; background-color: #fff; border: 0; padding: 15px 0; } .portlet .tabbable-line > .tab-content { padding-bottom: 0; } /* Below tabs mode */ .tabbable-line.tabs-below > .nav-tabs > li { border-top: 4px solid transparent; } .tabbable-line.tabs-below > .nav-tabs > li > a { margin-top: 0; } .tabbable-line.tabs-below > .nav-tabs > li:hover { border-bottom: 0; border-top: 4px solid #fbcdcf; } .tabbable-line.tabs-below > .nav-tabs > li.active { margin-bottom: -2px; border-bottom: 0; border-top: 4px solid #f3565d; } .tabbable-line.tabs-below > .tab-content { margin-top: -10px; border-top: 0; border-bottom: 1px solid #eee; padding-bottom: 15px; } .daterangepicker{ display: block !important; } .datepicker-inline{ margin: 0 auto !important } .datepicker-panel > ul > li:not(.disabled){ background-color: #1ab394 !important; color: #fff !important; border-radius: 4px !important; } .datepicker-panel > ul > li{ font-size: 14px !important } .datepicker-panel > ul[data-view="week"] > li, .datepicker-panel > ul[data-view="week"] > li:hover { background-color: #fff !important; color: #aaa !important; } .datepicker-panel > ul > li.picked, .datepicker-panel > ul > li.picked:hover { color: #fff !important; background-color: #1ab394; } .datepicker-panel > ul > li[data-view="years prev"], .datepicker-panel > ul > li[data-view="year prev"], .datepicker-panel > ul > li[data-view="month prev"], .datepicker-panel > ul > li[data-view="years next"], .datepicker-panel > ul > li[data-view="year next"], .datepicker-panel > ul > li[data-view="month next"], .datepicker-panel > ul > li[data-view="next"] { background-color: #e8e8e8 !important; color: #000 !important; } .datepicker-panel > ul > li[data-view="day disabled"], .datepicker-panel > ul > li[data-view="day disabled"], .datepicker-panel > ul > li[data-view="day disabled"] { color: #ccc !important; } .datepicker-panel > ul > li[data-view="years current"], .datepicker-panel > ul > li[data-view="year current"], .datepicker-panel > ul > li[data-view="month current"] { background-color: #e8e8e8 !important; color: #737373 !important; } .fotorama__wrap--css3 .fotorama__html, .fotorama__wrap--css3 .fotorama__stage .fotorama__img{ width: 100% !important; } .daterangepicker td.available{ background-color: #eee } .fotorama__nav-wrap{ background-color: #eee; } .fotorama__nav__frame{ padding: 7px !important; } .fotorama__thumb-border{ margin-top: 7px !important } .daterangepicker .drp-calendar.right { display: none !important; } </style> <div class="container"> <br><br> <div class="row justify-content-center font hotel" > <div class="col-lg-9 col-12"> <h3><?= ucwords(str_replace("-", " ", $dados[0])) ?> <small style="font-size: 13px"><?=$localizacao?></small></h3> <div> <button class="btn btn-md btn-primary" style="font-weight: 700"><i class="fa fa-money" style="margin-right: 8px"></i> <?=$tar_valor_final_product_info_inicial?> <small style="font-size: 11px;margin-left: 10px;"><?=$periodo_product_info_inicial ?></small></button> <?php if (!empty($tar_valor_final_product_info2)) { ?> <button class="btn btn-md btn-info" style="font-weight: 700"><i class="fa fa-money" style="margin-right: 8px"></i> <?=$tar_valor_final_product_info2?> <small style="font-size: 11px;margin-left: 10px;"><?=$periodo_product_info2?></small></button> <?php } ?> <?php if (!empty($tar_valor_final_product_info3)) { ?> <button class="btn btn-md btn-warning" style="font-weight: 700"><i class="fa fa-money" style="margin-right: 8px"></i> <?=$tar_valor_final_product_info3?> <small style="font-size: 11px;margin-left: 10px;"><?=$periodo_product_info3?></small></button> <?php } ?> </div> <br> <div class="fotorama" data-nav="thumbs" data-thumbwidth="90" data-thumbheight="90"> <img src="<?=$url?>" style="width: 100%"> <?php //an array with all the images (ba meta key). The same array has to be in custom_postimage_meta_box_save($post_id) as well. $meta_keys = array('featured_image0','featured_image1','featured_image2','featured_image3','featured_image4','featured_image5','featured_image6','featured_image7','featured_image8','featured_image9','featured_image10','featured_image11','featured_image12','featured_image13','featured_image14','featured_image15','featured_image16','featured_image17','featured_image18','featured_image19','featured_image20'); foreach($meta_keys as $meta_key){ $image_meta_val=get_post_meta( $id, $meta_key, true); if (!empty($image_meta_val)) { ?> <a href="<?=wp_get_attachment_image_src( $image_meta_val, 'full' )[0]?>"><img src="<?=wp_get_attachment_image_src( $image_meta_val, 'full' )[0]?>" alt="" width="90" height="90" data-thumbwidth="90" data-thumbheight="90"></a> <?php } ?> <?php } ?> </div> <div class="" style="padding-top: 10px"> <?=$description;?> </div> <br> <div class="tabbable-panel"> <div class="tabbable-line"> <ul class="nav nav-tabs "> <li class="active"> <a href="#tab_default_1" data-toggle="tab"> Serviços </a> </li> </ul> <div class="tab-content"> <div class="tab-pane active" id="tab_default_1"> <p style="line-height: 2.3;"> <?=$servicos?> </p> </div> </div> </div> </div> </div> <div class="col-lg-3 col-12" style="border: 1px solid #ddd;padding:0"> <div style="text-align: center;"> <h5 style="margin: 13px"><strong>Valores</strong></h5> <div style="height: 50px;background-color: #c9f3e1;padding: 15px 0px;"> <h4><strong><?=get_woocommerce_currency_symbol ();?> <?=$tar_valor_final_product_info_inicial?></strong> <small style="font-size: 13px">por dia</small></h4> <br> <div id="div_date"> <input type="text" id="select-delivery-date-input" style="height: 2px;border: none;color:#fff"> </div> </div> </div> <div style="text-align: right;margin-top: 125%;padding: 0px 10px;"> <span style="float: left;font-size: 13px"><strong style="font-size: 13px">Período: </strong><?=$_POST['periodo']?></span> <?php $woocommerce_currency = get_post_meta( $id_produto, 'woocommerce_currency', true); ?> <?php $_SESSION['texto_descritivo'] = '<br><strong style="float: left;font-size: 17px;">'.$_POST['acomodacao'].'</strong><br><strong style="float: left;color: green;font-weight: 500;">'.$_POST['regime'].'</strong><br><span style="font-weight: 500;">'.$_POST['pax'].'</span><br>'; ?> <br> <strong style="float: left"><?=$_POST['acomodacao']?></strong><br> <?php if (!empty($_POST['regime'])) { ?> <strong style="float: left;color: green"><?=$_POST['regime']?></strong><br> <?php } ?> <br> <span id="validacao_diaria" style="color:red;display:none"><strong>Período não encontrado.</strong></span> <span id="diarias_exibicao"><?=$_POST['diaria']?></span> <br><?=$_POST['pax']?> <br> <?php $woocommerce_currency = get_post_meta( $id_produto, 'woocommerce_currency', true); ?> <span id="exibicao_valor" style="font-size: 22px"> <?=$woocommerce_currency?> <?=$_POST['valor']?></span> <br> <?=$_POST['taxas']?> <br> <strong style="font-size: 13px;<?=($_POST['qtd_quartos'] <= 5 ? 'color:red' : '')?>"><?=$_POST['qtd_quartos']?> quartos disponíveis</strong> <br> <br> <input type="hidden" id="id_produto" value="<?=$id_produto?>" name=""> <input type="hidden" id="diarias_int" value="2" name=""> <button class="btn btn-primary btn-checkout single_add_to_cart_button" style="width: 100%">Reservar</button> </div> <br> <div style="padding: 0px 10px;"> <?php setlocale(LC_TIME, 'pt_BR', 'pt_BR.utf-8', 'pt_BR.utf-8', 'portuguese'); date_default_timezone_set('America/Sao_Paulo'); ?> <h4 style="border-bottom: 1px solid #ddd;padding-bottom: 7px;">PERÍODOS</h4> <strong><?=$periodo_product_info_inicial?></strong><br> <span>De <?= strftime('%d de %B', strtotime(implode("-", array_reverse(explode("/", $tar_periodo_product_info_inicial))))) ?> a <?=strftime('%d de %B', strtotime(implode("-", array_reverse(explode("/", $tar_periodo_final_product_info_inicial)))))?></span> <?php if (!empty($periodo_product_info2)) { ?> <br> <br> <strong><?=$periodo_product_info2?></strong><br> <span>De <?=strftime('%d de %B', strtotime(implode("-", array_reverse(explode("/", $tar_periodo_product_info2)))))?> a <?=strftime('%d de %B', strtotime(implode("-", array_reverse(explode("/", $tar_periodo_final_product_info2)))))?></span> <?php } ?> <?php if (!empty($periodo_product_info3)) { ?> <br> <br> <strong><?=$periodo_product_info3?></strong><br> <span>De <?=strftime('%d de %B', strtotime(implode("-", array_reverse(explode("/", $tar_periodo_product_info3)))))?> a <?=strftime('%d de %B', strtotime(implode("-", array_reverse(explode("/", $tar_periodo_final_product_info3)))))?></span> <?php } ?> </div> <br> <div style="padding: 0px 10px;"> <h4 style="border-bottom: 1px solid #ddd;padding-bottom: 7px;">TERMOS DE RESERVA</h4> <?php $cat_terms = get_terms( array('termos'), array( 'hide_empty' => false, 'orderby' => 'name', 'order' => 'ASC', 'number' => 50 //specify yours ) ); if( $cat_terms ){ foreach( $cat_terms as $term ) { $args = array( 'post_type' => 'ttbooking', 'posts_per_page' => 50, //specify yours 'post_status' => 'publish', 'tax_query' => array( array( 'taxonomy' => 'termos', 'field' => 'slug', 'terms' => $term->slug, ), ), 'ignore_sticky_posts' => true //caller_get_posts is deprecated since 3.1 ); $_posts = new WP_Query( $args ); if( $_posts->have_posts() ) : while( $_posts->have_posts() ) : $_posts->the_post(); $post = get_post(); if ($post->ID == $id) { echo $post->post_content.'<hr>'; } ?> <?php endwhile; endif; wp_reset_postdata(); //important } } ?> </div> </div> </div> <br> </div> <br><br> <input type="hidden" id="inicio_calendario" value="<?=$tar_periodo_product_info_inicial?>" name=""> <input type="hidden" id="fim_calendario" value="<?=$tar_periodo_final_product_info_inicial?>" name=""> <input type="hidden" id="valor_calendario" value="<?=str_replace(",", ".", str_replace(".", "", $tar_valor_final_product_info_inicial))?>" name=""> <input type="hidden" id="currency" value="<?=get_woocommerce_currency_symbol ();?>" name=""> </div> <input type="hidden" id="uri" name="" value="<?=$_SERVER['REQUEST_URI']?>"> <script src="<?=plugins_url( '../assets/js/mask.js', __FILE__ )?>"></script> <script type="text/javascript"> function show_div_count(){ jQuery(".dropdown").toggle(500); } jQuery("#telefone").mask('(00) 00000-0000'); jQuery("#chegada").mask('00/00/0000'); jQuery("#saida").mask('00/00/0000'); jQuery(document).ready(function(){ jQuery('.count').prop('disabled', true); jQuery(document).on('click','.plus',function(){ var valor = parseInt(jQuery('.count').val()) + 1; jQuery('.count').val(valor); jQuery("#count_adultos").html("<strong>"+valor+" adultos</strong>"); }); jQuery(document).on('click','.minus',function(){ var valor = parseInt(jQuery('.count').val()) - 1; jQuery('.count').val(valor); jQuery("#count_adultos").html("<strong>"+valor+" adultos</strong>"); if (jQuery('.count').val() == 0 || jQuery('.count').val() == 1) { jQuery('.count').val(1); jQuery("#count_adultos").html("<strong>1 adulto</strong>"); } }); jQuery('.count_child').prop('disabled', true); jQuery(document).on('click','.plus_child',function(){ var valor = parseInt(jQuery('.count_child').val()) + 1; jQuery('.count_child').val(valor); jQuery("#count_criancas").html("<strong>"+valor+" crianças</strong>"); if (jQuery('.count_child').val() == 1) { jQuery('.count_child').val(1); jQuery("#count_criancas").html("<strong>1 criança</strong>"); } }); jQuery(document).on('click','.minus_child',function(){ var valor = parseInt(jQuery('.count_child').val()) - 1; jQuery('.count_child').val(valor); jQuery("#count_criancas").html("<strong>"+valor+" crianças</strong>"); if (jQuery('.count_child').val() == 0) { jQuery('.count_child').val(1); jQuery("#count_criancas").html("<strong>0 criança</strong>"); } if (jQuery('.count_child').val() == 1) { jQuery('.count_child').val(1); jQuery("#count_criancas").html("<strong>1 criança</strong>"); } }); jQuery('.count_quartos').prop('disabled', true); jQuery(document).on('click','.plus_quartos',function(){ var valor = parseInt(jQuery('.count_quartos').val()) + 1; jQuery('.count_quartos').val(valor); jQuery("#count_quartos").html("<strong>"+valor+" quartos</strong>"); }); jQuery(document).on('click','.minus_quartos',function(){ var valor = parseInt(jQuery('.count_quartos').val()) - 1; jQuery('.count_quartos').val(valor); jQuery("#count_quartos").html("<strong>"+valor+" quartos</strong>"); if (jQuery('.count_quartos').val() == 0 || jQuery('.count_quartos').val() == 1) { jQuery('.count_quartos').val(1); jQuery("#count_quartos").html("<strong>1 quarto</strong>"); } }); }); function AtribuiValorHotel(id){ var dados = jQuery("#nameHotel"+id).val(); var uri = jQuery("#uri").val(); dados = dados.split(";"); jQuery("#uri").val('/apto?param='+dados[0]+';'+dados[1]+';'+dados[2]); } function enviarFormTodos(){ var uri = jQuery("#uri").val(); window.location.href = uri; } </script> <!-- /Blog Section with Sidebar --> <?php session_write_close(); ?> <?php get_footer(); ?><file_sep><?php require('Trend.php'); $trendHotel = new Trend(); $testar_cancelamento = false; $pegar_destinos = false; ///////////////////////////////////// ///////// manageToken ///////////// ///////////////////////////////////// if($trendHotel->manageToken() === true) { if($pegar_destinos == true) { $trendHotel->productSearchFilterDestines(); echo '<br><b>trend productSearchFilterDestines :</b><br>'; for ($i=0; $i < count($trendHotel->response->Body->DestinationListResponse->Destination); $i++) { echo $trendHotel->response->Body->DestinationListResponse->Destination[$i]->attributes()[0].' - '.$trendHotel->response->Body->DestinationListResponse->Destination[$i]->attributes()[1].'<br>'; } } } $id_hotel = $_POST['id']; if ($_POST['chd'] > 0) { for ($i=0; $i < $_POST['chd']; $i++) { $idades = '12,'; } $idades_chd = substr($idades, 0, -1); $pax = array(array('adt' => $_POST['adt'], 'idadeschd' => array($idades_chd))); }else{ $pax = array(array('adt' => $_POST['adt'])); } if ($_POST['chd'] == 0) { $crianca = ''; }else{ if ($_POST['chd'] == 1) { $crianca = ' e '.$_POST['chd'].' criança'; }else{ $crianca = ' e '.$_POST['chd'].' crianças'; } } $desc_pax = $_POST['adt'].' '.($_POST['adt'] > 1 ? 'adultos' : 'adulto').' '.$crianca; $data_inicio = new DateTime(implode("-", array_reverse(explode("-", $_POST['data_inicio'])))); $data_fim = new DateTime(implode("-", array_reverse(explode("-", $_POST['data_final'])))); // Resgata diferença entre as datas $diferenca_data = $data_inicio->diff($data_fim); if ($diferenca_data->days == 1) { $diaria = '1 diária'; }else{ $diaria = (intval($diferenca_data->days)+1).' diárias'; } $args = [ 'destination' => $_POST['destination'], // '5238' = 'SAO' 'checkin' => implode("-", array_reverse(explode("-", $_POST['data_inicio']))), 'checkout' => implode("-", array_reverse(explode("-", $_POST['data_final']))), 'quartos' => $pax ]; $trendHotel->productSearch($args); $response = json_decode(json_encode($trendHotel), true); $hoteis = $response["response"]["Body"]["ProductSearchRS"]["ProductSearchResult"]["HotelResult"]["ListHotelGroup"]["HotelGroup"]["Hotel"]; if (count($hoteis) >= 1) { function tirarAcentos($string){ return preg_replace(array("/(á|à|ã|â|ä)/","/(Á|À|Ã|Â|Ä)/","/(é|è|ê|ë)/","/(É|È|Ê|Ë)/","/(í|ì|î|ï)/","/(Í|Ì|Î|Ï)/","/(ó|ò|õ|ô|ö)/","/(Ó|Ò|Õ|Ô|Ö)/","/(ú|ù|û|ü)/","/(Ú|Ù|Û|Ü)/","/(ñ)/","/(Ñ)/","/(ç)/","/(Ç)/"),explode(" ","a A e E i I o O u U n N c C"),$string); } for ($i=0; $i < count($hoteis); $i++) { $id = $hoteis[$i]["HotelInfo"]["@attributes"]["Id"]; if ($id == $id_hotel) { //nome, foto, descrição, preço $foto = $hoteis[$i]["HotelInfo"]["@attributes"]["ThumbImage"]; $descricao = $hoteis[$i]["HotelInfo"]["Description"]; for ($x=0; $x < count($hoteis[$i]["ListRoom"]["Room"]); $x++) { $nome = $hoteis[$i]["ListRoom"]["Room"][$x]["RoomInfo"]["@attributes"]["Description"]; $preco = $hoteis[$i]["ListRoom"]["Room"][$x]["RoomComlInfo"]["@attributes"]["AvrNightPrice"]; $dados_hoteis[] = array("id" => $id, "nome" => tirarAcentos($nome), "foto" => str_replace("/", "-", $foto), "descricao" => tirarAcentos($descricao), "preco" => $preco, "fornecedor" => "Trend", "acomodacao" => tirarAcentos($hoteis[$i]["ListRoom"]["Room"][$x]["RoomInfo"]["@attributes"]["AccomodationTypeDescription"]), "tipo" => tirarAcentos($hoteis[$i]["ListRoom"]["Room"][$x]["RoomInfo"]["@attributes"]["RoomTypeDescription"]), "pax" => tirarAcentos($desc_pax), "regime" => tirarAcentos($hoteis[$i]["ListRoom"]["Room"][$x]["RoomInfo"]["@attributes"]["BoardBaseDescription"]), "checkin" => $_POST['data_inicio'], "checkout" => $_POST['data_final'], "diarias" => tirarAcentos($diaria)); } } } echo str_replace("\"", "%s;", json_encode($dados_hoteis)); }else{ echo '0'; } ?><file_sep> $('.single_add_to_cart_button').click(function(e) { e.preventDefault(); var p_id = $("#id_produto").val(); var quantity = $("#diarias_int").val(); addToCart(p_id, quantity); return false; }); function addToCart(p_id, quantity) { $.get('/?post_type=product&add-to-cart=' + p_id +'&quantity=' + quantity, function(response) { window.location.href = '/finalizar-compra'; }); }<file_sep><?php /* Plugin Name: Voucher Tec - Integração de hotéis Plugin URI: https://github.com/TravelTec/bookinghotels GitHub Plugin URI: https://github.com/TravelTec/bookinghotels Description: Voucher Tec - Integração de hotéis é um plugin desenvolvido para agências e operadoras de turismo que precisam tratar diárias de hospedagem de fornecedores. Version: 1.0.1 Author: <NAME> Author URI: https://traveltec.com.br License: GPLv2 */ /* * Plugin Update Checker * * Note: If you're using the Composer autoloader, you don't need to explicitly require the library. * @link https://github.com/YahnisElsts/plugin-update-checker */ require_once 'plugin-update-checker-4.10/plugin-update-checker.php'; require_once plugin_dir_path(__FILE__) . 'includes/reserva-integracao-functions.php'; require_once plugin_dir_path(__FILE__) . 'includes/config-integracao-functions.php'; /* * Plugin Update Checker Setting * * @see https://github.com/YahnisElsts/plugin-update-checker for more details. */ class TTBookingIntegracao { function __construct() { $this->options = get_option( 'config_ttbookingintegracao' ); $this->plugin_file = __FILE__; $this->plugin_basename = plugin_basename( $this->plugin_file ); add_action( 'admin_init', array( &$this, 'integracao_update_checker_setting') ); add_shortcode('TTBOOKING_MOTOR_RESERVA', array( &$this, 'funcaoParaShortcodeIntegracao') ); } /** * Get specific option from the options table * * @param string $option Name of option to be used as array key for retrieving the specific value * @return mixed * @since 0.1 */ function get_option( $option, $options = null ) { if ( is_null( $options ) ) $options = &$this->options; if ( isset( $options[$option] ) ) return $options[$option]; else return false; } function integracao_update_checker_setting() { if ( ! is_admin() || ! class_exists( 'Puc_v4_Factory' ) ) { return; } $myUpdateChecker = Puc_v4_Factory::buildUpdateChecker( 'https://github.com/TravelTec/integracao-hoteis', __FILE__, 'integracao-hoteis' ); // (Opcional) Set the branch that contains the stable release. $myUpdateChecker->setBranch('main'); } function funcaoParaShortcodeIntegracao($atts){ $propriedade = $atts['propriedade']; $tipo_propriedade = []; $cat_terms = get_terms( array('tipo_propriedades_integracao'), array( 'hide_empty' => false, 'orderby' => 'name', 'order' => 'ASC', 'number' => 50 //specify yours ) ); if( $cat_terms ){ foreach( $cat_terms as $term ) { $propriedades[] = array("tipo_propriedade" => $term->slug); } } for ($i=0; $i < count($propriedades); $i++) { if ($propriedade == $propriedades[$i]["tipo_propriedade"]) { $texto_motor = $this->get_option( 'texto_motor'.$i ); $chechbox_motor = $this->get_option( 'chechbox_motor'.$i ); $tipo_motor = $propriedades[$i]["tipo_propriedade"]; } } $localizacao = []; $cat_terms = get_terms( array('localizacao_integracao'), array( 'hide_empty' => false, 'orderby' => 'name', 'order' => 'ASC', 'number' => 50 //specify yours ) ); if( $cat_terms ){ foreach( $cat_terms as $term ) { $locais[] = array("name_local" => $term->name, "name_hotel" => "", "id" => "", "destination" => ""); } } $dados = get_option( 'config_ttbookingintegracao' ); for ($i=0; $i < 21; $i++) { if(!empty($dados['hotel_trend_nh'.$i])){ $hotelaria[] = array("name_local" => "", "name_hotel" => $dados['hotel_trend_nh'.$i], "id" => $dados['id_hotel_trend_nh'.$i], "destination" => $dados['destination_hotel_trend_nh'.$i]); } } if (empty($locais)) { $total = $hotelaria; }else if (empty($hotelaria)) { $total = $locais; }else{ $total = array_merge($locais, $hotelaria); } echo "<input type='hidden' id='destinos_motor' value='".json_encode($total)."'>"; echo "<input type='hidden' id='propriedade' value='".$propriedade."'>"; echo "<input type='hidden' id='tipo_motor' value='".$tipo_motor."'>"; echo "<input type='hidden' id='chechbox_motor' value='".$chechbox_motor."'>"; echo "<input type='hidden' id='hotelaria_motor' value='".$hotelaria_motor."'>"; $options = $this->options; $retorno = ''; $retorno .= '<div class="row font hotel" style="background-color: '.(empty($options['cor_fundo_texto']) ? "#fff" : $options['cor_fundo_texto']).';min-height: 100px;padding-top: 20px;"> <div class="col-lg-1"></div> <div class="col-lg-10"> <h4 style="margin-bottom: 17px !important;margin-left: -15px !important;font-size: 23px;color: '.(empty($options['cor_texto']) ? "#000" : $options['cor_texto']).' !important">'.$texto_motor.'</h4> <div class="row grid" style=" ">'; if($chechbox_motor == "on"){ }else{ $retorno .= '<div class="col-lg-4 col-xs-12" style="padding: 0;border: 3px solid '.(empty($options['cor_bordas']) ? "#ddd" : $options['cor_bordas']).';"> <div class="input-group" style="height:45px;border-radius: 0;"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1" style=" background-color: #fff; border-color: transparent; "><i class="fa fa-bed" style="font-size:15px"></i></span> </div> <input type="hidden" name="destino_pesquisa" id="destino_pesquisa" value=""> <input type="hidden" name="id_hotel" id="id_hotel" value=""> <input type="hidden" name="id_destination_hotel" id="id_destination_hotel" value=""> <input type="hidden" name="destino_hotel" id="destino_hotel" value=""> <input type="text" class="form-control" id="destino" placeholder="Para onde você vai?" style=" border-radius: 0; border: none; font-size: 13px; font-weight: 700; height: 45px " onkeypress="exibe_destino()" onclick="limpar_campo()" onfocus="remove_drop_pax()" autocomplete="off"> <div id="valida_campo_destino" style="display:none;margin: 0 !important;padding: 3px 10px;font-size: 10px;color: #fff;background-color: #ab0808;top: 34px;position: absolute;z-index: 99999;"> <p style=" margin: 0 !important; font-size: 10px; color: #fff; ">É necessário informar um destino para efetuar a pesquisa.</p> </div> <div id="dados" style="display:none; position: absolute; width: 100%; top: 48px; background-color: #fff;"> <ul style=" padding: 0px 10px; "> </ul> </div> </div> </div>'; } $retorno .= '<div class="'.($chechbox_motor == "on" ? "col-lg-3" : "col-lg-2").' col-xs-12" style="box-shadow: 0px 0px 7px #888585;padding: 0;border: 3px solid '.(empty($options['cor_bordas']) ? "#ddd" : $options['cor_bordas']).';"> <div class="input-group" style="height:45px;border-radius: 0;"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1" style=" background-color: #fff; border-color: transparent; "><i class="fa fa-calendar" style="font-size:15px"></i></span> </div> <input type="hidden" name="validar_data" id="validar_data" value=""> <input type="text" id="sandbox-container" class="form-control" placeholder="Check-in - Check-out" style="border-radius: 0;border: none;font-size: 13px;font-weight: 700;height: 45px" onfocus="remove_drop_pax()" autocomplete="off"> <div id="valida_campo_data" style="display:none;margin: 0 !important;padding: 3px 10px;font-size: 10px;color: #fff;background-color: #ab0808;top: 34px;position: absolute;z-index: 99999;"> <p style=" margin: 0 !important; font-size: 10px; color: #fff; ">Necessário informar a data.</p> </div> </div> </div> <div class="col-lg-4 col-xs-12" style="box-shadow: 0px 0px 7px #888585;padding: 0;border: 3px solid '.(empty($options['cor_bordas']) ? "#ddd" : $options['cor_bordas']).';"> <div class="input-group" style="height:45px;border-radius: 0;background-color:#fff" onfocusout="remove_drop_pax()" > <div class="input-group-prepend" style="" onclick="show_div_count()" onfocusout="remove_drop_pax()" > <span class="input-group-text" id="basic-addon1" style=" background-color: #fff; border-color: transparent; height: 45px; " onfocusout="remove_drop_pax()" ><i class="fa fa-user" style="font-size:15px"></i></span> </div> <div style=" padding: 13px; font-size: 13px; " onclick="show_div_count()"> <span id="count_adultos"><strong style="color:#aaa">2 adultos</strong></span> </div> <div style=" padding: 13px; font-size: 13px; " onclick="show_div_count()"> <span id="count_criancas"><strong style="color:#aaa">0 criança</strong></span> </div> <div style=" padding: 13px; font-size: 13px; " onclick="show_div_count()"> <span id="count_quartos"><strong style="color:#aaa">1 quarto</strong></span> </div> <div style=" padding: 13px; font-size: 13px; " onclick="show_div_count()"> </div> <div style=" padding: 13px; font-size: 13px; " onclick="show_div_count()"> <strong><i class="fa fa-arrow-down"></i></strong> </div> <div class="dropdown" style=" display:none; position: relative; top:-2px; background-color: #fff; padding: 16px; box-shadow: 0px 0px 5px #868585; z-index: 99999999; width: 100%; "> <div class="row" style="height:40px"> <div class="col-lg-6 col-xs-6 text-left"> <strong style="font-size:14px;color: #444444;">Adultos</strong> </div> <div class="col-lg-6 col-xs-6 text-right"> <div class="qty"> <span class="minus bg-dark">-</span> <input type="number" class="count input_number" name="qty" value="2" disabled=""> <span class="plus bg-dark">+</span> </div> </div> </div> <div class="row" style="height:40px"> <div class="col-lg-6 col-xs-6 text-left"> <strong style="font-size:14px;color: #444444;">Crianças</strong> </div> <div class="col-lg-6 col-xs-6 text-right"> <div class="qty"> <span class="minus_child bg-dark">-</span> <input type="number" class="count_child input_number" name="qty" value="0" disabled=""> <span class="plus_child bg-dark">+</span> </div> </div> </div> <div class="row" style="height:40px"> <div class="col-lg-6 col-xs-6 text-left"> <strong style="font-size:14px;color: #444444;">Quartos</strong> </div> <div class="col-lg-6 col-xs-6 text-right"> <div class="qty"> <span class="minus_quartos bg-dark">-</span> <input type="number" class="count_quartos input_number" name="qty" value="1" disabled=""> <span class="plus_quartos bg-dark">+</span> </div> </div> </div> <div class="row" id="crianca1" style="display:none"> <div class="col-lg-12 col-xs-12"> <strong style="font-size:14px;color: #444444;">Idade das crianças</strong> <select class="form-control" id="idade_crianca1"> <option value="">Idade na data do check-out</option> <option value="0">0 anos de idade</option> <option value="1">1 ano de idade</option> <option value="2">2 anos de idade</option> <option value="3">3 anos de idade</option> <option value="4">4 anos de idade</option> <option value="5">5 anos de idade</option> <option value="6">6 anos de idade</option> <option value="7">7 anos de idade</option> <option value="8">8 anos de idade</option> <option value="9">9 anos de idade</option> <option value="10">a0 anos de idade</option> <option value="11">11 anos de idade</option> <option value="12" selected>12 anos de idade</option> <option value="13">13 anos de idade</option> <option value="14">14 anos de idade</option> <option value="15">15 anos de idade</option> <option value="16">16 anos de idade</option> <option value="17">17 anos de idade</option> </select> </div> </div> <div class="row" id="crianca2" style="display:none"> <div class="col-lg-12 col-xs-12"> <select class="form-control" id="idade_crianca2"> <option value="">Idade na data do check-out</option> <option value="0">0 anos de idade</option> <option value="1">1 ano de idade</option> <option value="2">2 anos de idade</option> <option value="3">3 anos de idade</option> <option value="4">4 anos de idade</option> <option value="5">5 anos de idade</option> <option value="6">6 anos de idade</option> <option value="7">7 anos de idade</option> <option value="8">8 anos de idade</option> <option value="9">9 anos de idade</option> <option value="10">a0 anos de idade</option> <option value="11">11 anos de idade</option> <option value="12" selected>12 anos de idade</option> <option value="13">13 anos de idade</option> <option value="14">14 anos de idade</option> <option value="15">15 anos de idade</option> <option value="16">16 anos de idade</option> <option value="17">17 anos de idade</option> </select> </div> </div> <div class="row" id="crianca3" style="display:none"> <div class="col-lg-12 col-xs-12"> <select class="form-control" id="idade_crianca3"> <option value="">Idade na data do check-out</option> <option value="0">0 anos de idade</option> <option value="1">1 ano de idade</option> <option value="2">2 anos de idade</option> <option value="3">3 anos de idade</option> <option value="4">4 anos de idade</option> <option value="5">5 anos de idade</option> <option value="6">6 anos de idade</option> <option value="7">7 anos de idade</option> <option value="8">8 anos de idade</option> <option value="9">9 anos de idade</option> <option value="10">a0 anos de idade</option> <option value="11">11 anos de idade</option> <option value="12" selected>12 anos de idade</option> <option value="13">13 anos de idade</option> <option value="14">14 anos de idade</option> <option value="15">15 anos de idade</option> <option value="16">16 anos de idade</option> <option value="17">17 anos de idade</option> </select> </div> </div> <div class="row" id="crianca4" style="display:none"> <div class="col-lg-12 col-xs-12"> <select class="form-control" id="idade_crianca4"> <option value="">Idade na data do check-out</option> <option value="0">0 anos de idade</option> <option value="1">1 ano de idade</option> <option value="2">2 anos de idade</option> <option value="3">3 anos de idade</option> <option value="4">4 anos de idade</option> <option value="5">5 anos de idade</option> <option value="6">6 anos de idade</option> <option value="7">7 anos de idade</option> <option value="8">8 anos de idade</option> <option value="9">9 anos de idade</option> <option value="10">a0 anos de idade</option> <option value="11">11 anos de idade</option> <option value="12" selected>12 anos de idade</option> <option value="13">13 anos de idade</option> <option value="14">14 anos de idade</option> <option value="15">15 anos de idade</option> <option value="16">16 anos de idade</option> <option value="17">17 anos de idade</option> </select> </div> </div> <div class="row" id="crianca5" style="display:none"> <div class="col-lg-12 col-xs-12"> <select class="form-control" id="idade_crianca5"> <option value="">Idade na data do check-out</option> <option value="0">0 anos de idade</option> <option value="1">1 ano de idade</option> <option value="2">2 anos de idade</option> <option value="3">3 anos de idade</option> <option value="4">4 anos de idade</option> <option value="5">5 anos de idade</option> <option value="6">6 anos de idade</option> <option value="7">7 anos de idade</option> <option value="8">8 anos de idade</option> <option value="9">9 anos de idade</option> <option value="10">a0 anos de idade</option> <option value="11">11 anos de idade</option> <option value="12" selected>12 anos de idade</option> <option value="13">13 anos de idade</option> <option value="14">14 anos de idade</option> <option value="15">15 anos de idade</option> <option value="16">16 anos de idade</option> <option value="17">17 anos de idade</option> </select> </div> </div> <div class="row" id="crianca6" style="display:none"> <div class="col-lg-12 col-xs-12" id="idade_crianca6"> <select class="form-control"> <option value="">Idade na data do check-out</option> <option value="0">0 anos de idade</option> <option value="1">1 ano de idade</option> <option value="2">2 anos de idade</option> <option value="3">3 anos de idade</option> <option value="4">4 anos de idade</option> <option value="5">5 anos de idade</option> <option value="6">6 anos de idade</option> <option value="7">7 anos de idade</option> <option value="8">8 anos de idade</option> <option value="9">9 anos de idade</option> <option value="10">a0 anos de idade</option> <option value="11">11 anos de idade</option> <option value="12" selected>12 anos de idade</option> <option value="13">13 anos de idade</option> <option value="14">14 anos de idade</option> <option value="15">15 anos de idade</option> <option value="16">16 anos de idade</option> <option value="17">17 anos de idade</option> </select> </div> </div> <div class="row" id="crianca7" style="display:none"> <div class="col-lg-12 col-xs-12"> <select class="form-control"> <option value="">Idade na data do check-out</option> <option value="0">0 anos de idade</option> <option value="1">1 ano de idade</option> <option value="2">2 anos de idade</option> <option value="3">3 anos de idade</option> <option value="4">4 anos de idade</option> <option value="5">5 anos de idade</option> <option value="6">6 anos de idade</option> <option value="7">7 anos de idade</option> <option value="8">8 anos de idade</option> <option value="9">9 anos de idade</option> <option value="10">a0 anos de idade</option> <option value="11">11 anos de idade</option> <option value="12" selected>12 anos de idade</option> <option value="13">13 anos de idade</option> <option value="14">14 anos de idade</option> <option value="15">15 anos de idade</option> <option value="16">16 anos de idade</option> <option value="17">17 anos de idade</option> </select> </div> </div> <div class="row" id="crianca8" style="display:none"> <div class="col-lg-12 col-xs-12"> <select class="form-control"> <option value="">Idade na data do check-out</option> <option value="0">0 anos de idade</option> <option value="1">1 ano de idade</option> <option value="2">2 anos de idade</option> <option value="3">3 anos de idade</option> <option value="4">4 anos de idade</option> <option value="5">5 anos de idade</option> <option value="6">6 anos de idade</option> <option value="7">7 anos de idade</option> <option value="8">8 anos de idade</option> <option value="9">9 anos de idade</option> <option value="10">a0 anos de idade</option> <option value="11">11 anos de idade</option> <option value="12" selected>12 anos de idade</option> <option value="13">13 anos de idade</option> <option value="14">14 anos de idade</option> <option value="15">15 anos de idade</option> <option value="16">16 anos de idade</option> <option value="17">17 anos de idade</option> </select> </div> </div> <div class="row" id="crianca9" style="display:none"> <div class="col-lg-12 col-xs-12"> <select class="form-control"> <option value="">Idade na data do check-out</option> <option value="0">0 anos de idade</option> <option value="1">1 ano de idade</option> <option value="2">2 anos de idade</option> <option value="3">3 anos de idade</option> <option value="4">4 anos de idade</option> <option value="5">5 anos de idade</option> <option value="6">6 anos de idade</option> <option value="7">7 anos de idade</option> <option value="8">8 anos de idade</option> <option value="9">9 anos de idade</option> <option value="10">a0 anos de idade</option> <option value="11">11 anos de idade</option> <option value="12" selected>12 anos de idade</option> <option value="13">13 anos de idade</option> <option value="14">14 anos de idade</option> <option value="15">15 anos de idade</option> <option value="16">16 anos de idade</option> <option value="17">17 anos de idade</option> </select> </div> </div> </div> </div> </div> <div class="col-lg-2 col-xs-12" style="box-shadow: 0px 0px 7px #888585;padding: 0;border: 3px solid '.(empty($options['cor_bordas']) ? "#ddd" : $options['cor_bordas']).';"> <a onclick="redirect_hotel()"><button class="btn btn-primary btn_pesquisa_aereo" style="width:100%;height: 45px;border-radius:0;background-color:'.(empty($options['cor_botao']) ? "#1ab394" : $options['cor_botao']).' !important;border-color: '.(empty($options['cor_botao']) ? "#1ab394" : $options['cor_botao']).' !important">Pesquisar</button></a> </div> </div> <div class="div_resultados" style="display:none; background-color: #eee; " class="row"> <h4 style=" margin: 0px !important; padding: 14px; ">Nenhum resultado encontrado com os critérios informados.</h4> </div> <br> </div> <div class="col-lg-1"></div> </div>'; return $retorno; } } new TTBookingIntegracaoAdmin(); <file_sep><?php get_header(); $dados = explode(";", $_GET['param']); $destino = $dados[0]; $data_inicio = $dados[1]; $data_final = $dados[2]; $adt = $dados[3]; $chd = $dados[4]; $qts = $dados[5]; $pax_pesquisa_inicial = $adt; $pax_pesquisa_total = intval($adt)+intval($chd); if ($qts > 1) { $quartos = ', '.$qts.' quartos'; }else{ $quartos = ', '.$qts.' quarto'; } if ($chd == 0) { $crianca = ''; $idades = ''; }else{ if ($chd == 1) { $crianca = ' e '.$chd.' criança'; }else{ $crianca = ' e '.$chd.' crianças'; } $valor_idades = explode("-", $dados[6]); $idades .= '<br><strong>Idade das crianças: </strong><br>'; for ($i=0; $i < $chd; $i++) { $idades .= 'Criança '.($i+1).': '.$valor_idades[$i].' '.($valor_idades[$i] == 1 ? 'ano' : 'anos').'<br>'; } } $idade_crianca = ($valor_idades[0] >= '10' ? $valor_idades[0] : str_replace("0", "", $valor_idades[0])); $pax = $adt.' '.($adt > 1 ? 'adultos' : 'adulto').' '.$crianca; $propriedade = $dados[7]; $data_inicio = new DateTime(implode("-", array_reverse(explode("-", $data_inicio)))); $data_fim = new DateTime(implode("-", array_reverse(explode("-", $data_final)))); // Resgata diferença entre as datas $diferenca_data = $data_inicio->diff($data_fim); if ($diferenca_data->days == 1) { $diaria = '1 diária'; }else{ $diaria = (intval($diferenca_data->days)+1).' diárias'; } ?> <!-- Blog Section with Sidebar --> <style type="text/css"> .page-builder { display: none } .page-title-section { display: none } .attachment-post-thumbnail{ display: block; max-width: 100%; height: 250px;} .fotorama__wrap--css3 .fotorama__html, .fotorama__wrap--css3 .fotorama__stage .fotorama__img{ width: 100% !important; } .daterangepicker td.available{ background-color: #eee } .fotorama__nav-wrap{ background-color: #eee; } .fotorama__nav__frame{ padding: 7px !important; } .fotorama__thumb-border{ margin-top: 7px !important } </style> <div class="page-builder2"> <div class="page-title-section" style="display: block !important;"> <div class="overlay"> <div class="container-fluid"> <div class="row"> <div class="col-md-1 col-lg-1"></div> <div class="col-md-5 col-lg-5"> <div class="page-title"> <h1>Hotéis em <?= $destino ?></h1> </div> </div> <div class="col-md-5 col-lg-5"> <ul class="page-breadcrumb"> <li><a href="/">Início</a> &nbsp; / &nbsp;</li> <li class="active">Hotéis em <?= $destino ?></li> </ul> </div> <div class="col-md-1 col-lg-1"></div> </div> </div> </div> </div> <link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet"> <style type="text/css"> .input-group{ position: relative; display: -webkit-box; display: -ms-flexbox; display: flex; -ms-flex-wrap: wrap; flex-wrap: wrap; -webkit-box-align: stretch; -ms-flex-align: stretch; align-items: stretch; width: 100%; } .input-group-prepend { margin-right: -1px; } .input-group-append, .input-group-prepend { display: -webkit-box; display: -ms-flexbox; display: flex; } .input-group-text { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-align: center; -ms-flex-align: center; align-items: center; padding: .375rem .75rem; margin-bottom: 0; font-size: 1rem; font-weight: 400; line-height: 1.5; color: #495057; text-align: center; white-space: nowrap; background-color: #e9ecef; border: 1px solid #ced4da; border-radius: .25rem; } .input-group>.custom-file, .input-group>.custom-select, .input-group>.form-control { position: relative; -webkit-box-flex: 1; -ms-flex: 1 1 auto; flex: 1 1 auto; width: 1%; margin-bottom: 0; } @media(max-width: 800px){ .navbar-brand img{ height: 42px } .img-div-responsive{ padding: 0 0px 9px 0px !important; } .exibirComputador{ display: none !important; } .exibirCelular{ display: block !important; } .titulo{ font-size: 1.5rem !important; font-weight: 700 !important; } .subtitulo{ font-size: 1.0rem !important; } .carousel{ margin: 10px !important } .filtro{ padding-right: 15px !important } .hotel{ padding: 14px } .centeri{ text-align: center; } .borderC{ border: 1px solid #ddd; margin: 0px 17px 0px 14px; height: auto !important; } } .exibirComputador{ visibility: initial; } .exibirCelular{ display: none; } .titulo{ font-size: 2.8rem;font-weight: 400; } .subtitulo{ font-size: 1.4rem;font-weight: 400 } .font{ font-family: 'Raleway', sans-serif !important; } .nofont{ font-family: 'Arial', sans-serif !important; } .carousel{ margin-left: 10px;margin-right: -12px;margin-top: 10px; } .btn-primary{ background-color: #2f4050 !important; border-color: #2f4050 !important; } .btn-primary:hover{ background-color: #fff !important; border-color: #2f4050 !important; color: #2f4050 !important; } .filtro{ padding-right: 0 } .infoBox { background-color: #FFF; width: 300px; font-size: 14px; border: 1px solid #3fa7d8; border-radius: 3px; margin-top: 10px } .infoBox p { padding: 6px } .infoBox:before { border-left: 10px solid transparent; border-right: 10px solid transparent; border-bottom: 10px solid #3fa7d8; top: -10px; content: ""; height: 0; position: absolute; width: 0; left: 138px } html { position: relative; min-height: 100%; } body { /* Margin bottom by footer height */ margin-bottom: 60px; } .footer { position: absolute; bottom: 0; width: 100%; /* Set the fixed height of the footer here */ height: 50px; line-height: 46px; /* Vertically center the text there */ background-color: #585858; border-top: 4px solid;border-color: #999; } .text-muted{ color: #999999 !important;font-size:16px; } .esconde{ display: none; } .exibe{ display: block; } @media(max-width: 959px){ .imgHotel{ width: 93%; } } @media(min-width: 960px) and (max-width: 961px){ .imgHotel{ width: 97%; } } @media(min-width: 411px) and (max-width: 559px){ .footer { text-align: center !important; line-height: 20px; } .text-muted{ text-align: center !important; } .exibeCelular{ bottom: auto !important; } } @media(max-width: 400px){ .footer { text-align: center !important; line-height: 20px; } .text-muted{ text-align: center !important; } .exibeCelular{ bottom: auto !important; } } @media(min-width: 600px){ .text-muted{ float: right; } .exibirComputador{ display: block !important; } } .navbar-light .navbar-nav .nav-link { color: rgba(0,0,0,.5) !important; } #google_translate_element { display: none; } .goog-te-banner-frame { display: none !important; } .exibirComputador{ display: none; } .tooltip.show { opacity: .9; z-index: 0; margin-left: 5px; } .qty .count, .qty .count_child, .qty .count_quartos { color: #000; display: inline-block; vertical-align: top; font-size: 22px; font-weight: 700; line-height: 30px; padding: 0 2px ;min-width: 35px; text-align: center; margin-top: -11px; } .qty .plus, .qty .plus_child, .qty .plus_quartos { cursor: pointer; display: inline-block; vertical-align: top; color: white; width: 26px; height: 26px; font: 25px/1 Arial,sans-serif; text-align: center; border-radius: 50%; } .qty .minus, .qty .minus_child, .qty .minus_quartos { cursor: pointer; display: inline-block; vertical-align: top; color: white; width: 26px; height: 26px; font: 25px/1 Arial,sans-serif; text-align: center; border-radius: 50%; background-clip: padding-box; } .minus, .minus_child, .minus_quartos{ background-color: #aaa !important; } .plus, .plus_child, .plus_quartos{ background-color: #aaa !important; } .minus:hover, .minus_child:hover, .minus_quartos:hover{ background-color: #e8b90d !important; } .plus:hover, .plus_child:hover, .plus_quartos:hover{ background-color: #e8b90d !important; } /*Prevent text selection*/ span{ -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; } .input_number{ border: 0; width: 2%; } nput::-webkit-outer-spin-button, input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } input:disabled{ background-color:white; } .xpi__content__wrappergray { background: #f5f5f5; } .xpi__content__wrapper { background: #002f72; margin-bottom: 24px; border-bottom: 1px solid #e6e6e6; } .xpi__searchbox { padding: 44px 5px; position: relative; } .xpi__searchbox { max-width: 1110px; padding: 40px 5px 16px; margin: 0 auto; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .xpi__content__wrappergray .xpi__searchbox .sb-searchbox__title, .xpi__content__wrappergray .xpi__searchbox .sb-searchbox__subtitle-text { color: #333; } .xpi__searchbox .sb-searchbox__title { font-size: 24px; line-height: 32px; font-weight: 600; font-weight: 600; } .sb-searchbox__title { margin: 0; padding: 0; font-size: 26px; font-weight: normal; } .xpi__content__wrappergray .xpi__searchbox .sb-searchbox__title, .xpi__content__wrappergray .xpi__searchbox .sb-searchbox__subtitle-text { color: #333; } .xpi__searchbox .sb-searchbox__title { font-size: 24px; line-height: 32px; font-weight: 600; font-weight: 600; } .xpi__searchbox .sb-searchbox__subtitle-text { font-size: 14px; line-height: 20px; font-weight: 400; } .sb-searchbox--painted { font-size: 14px; line-height: 20px; font-weight: 400; background: 0; border-radius: 0; border: 0; padding: 0; } .xp__fieldset { color: #333; border: 0; display: table; background-color: #febb02; padding: 4px; border-radius: 4px; margin: 24px 0 16px; position: relative; width: 100%; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } @media(max-width: 320px){ .marginGallery{ margin: 0px 9px 0px -4px !important; } .imgWidth{ width: 160% !important; } .tituloHotel{ font-size: 1.5rem !important; margin-top: 16px!important; } .paddingRow{ padding: 0 15px 0 15px !important; } .fontSizeP{ font-size: 14px !important; } .fontSizePreco{ font-size: .805rem !important; } .paddingCelular{ padding-left: 4px !important;; } .colNomeCelular { margin: 0 -7px 0 -14px !important; } .col1Celular{ margin: 0 -9px 0 -14px !important; } .col2Celular{ margin: 0 9px 0 4px !important; } .borderCelular{ border-right: none !important; } } @media (min-width: 350px) and (max-width: 414px){ .imgWidth{ width: 130% !important; } .marginGallery { margin: 0px 8px 0px -4px !important; } .tituloHotel{ font-size: 1.5rem !important; margin-top: 16px!important; } .paddingRow{ padding: 0 15px 0 15px !important; } .fontSizeP{ font-size: .805rem !important; } .fontSizePreco{ font-size: .805rem !important; } .paddingCelular{ padding-left: 8px !important; } .colNomeCelular{ margin: 0 -4px 0 -5px !important; } } @media(min-width: 1650px){ .imgHotel{ width: 100% !important; height: 252px !important; } .imgWidth{ width: 130% !important; } } .marginGallery{ margin: 0px -3px 0px -4px; } .imgWidth{ width: 160%; } .tituloHotel{ font-size: 2rem; margin-top: 4px; } .paddingRow{ padding: 0; } .fontSizeP{ font-size: 14px; } .fontSizePreco{ font-size: 14px; } .borderCelular{ border-right: 1px solid #ddd; } .centerizar{ display: -webkit-flex !important; display: flex !important; -webkit-align-items: center !important; align-items: center !important; } .row { display: -ms-flexbox; display: flex; -ms-flex-wrap: wrap; flex-wrap: wrap; margin-right: -15px; margin-left: -15px; } .justify-content-center { -ms-flex-pack: center!important; justify-content: center!important; } </style> <div class="container-fluid"> <br><br> <?php $the_slug = $slug; $args = array( 'post_type' => 'ttbooking', 'post_status' => 'publish', 'numberposts' => 100 ); $my_posts = new WP_Query( $args ); $local = strtolower(str_replace(" ", "-", $destino)); $localizacao = ''; $cat_terms = get_terms( array('localizacao'), array( 'hide_empty' => false, 'orderby' => 'name', 'order' => 'ASC', 'number' => 6 //specify yours ) ); if( $cat_terms ){ foreach( $cat_terms as $term ) { $args = array( 'post_type' => 'ttbooking', 'posts_per_page' => 10, //specify yours 'post_status' => 'publish', 'tax_query' => array( array( 'taxonomy' => 'localizacao', 'field' => 'slug', 'terms' => $term->slug, ), array( 'taxonomy' => 'tipo_propriedades', 'field' => 'slug', 'terms' => $propriedade, ), ), 'ignore_sticky_posts' => true //caller_get_posts is deprecated since 3.1 ); $_posts = new WP_Query( $args ); if( $_posts->have_posts() ) : while( $_posts->have_posts() ) : $_posts->the_post(); $post = get_post(); $title = $post->post_title; $slug = $post->post_name; $id = $post->ID; $description = $post->post_content; $thumb_id = get_post_thumbnail_id(); $thumb_url = wp_get_attachment_image_src($thumb_id,'thumbnail-size', true); $url = $thumb_url[0]; if ($term->slug === $local) { $localizacao = '<i class="fa fa-map"></i> <span style="margin-right:8px;">'.$term->name.'</span>'; $servicos = ''; $cat_terms1 = get_terms( array('servicos'), array( 'hide_empty' => false, 'orderby' => 'name', 'order' => 'ASC', 'number' => 100 //specify yours ) ); if( $cat_terms1 ){ $contador = 0; foreach( $cat_terms1 as $term1 ) { $args1 = array( 'post_type' => 'ttbooking', 'posts_per_page' => 10, //specify yours 'post_status' => 'publish', 'tax_query' => array( array( 'taxonomy' => 'servicos', 'field' => 'slug', 'terms' => $term1->slug, ), ), 'ignore_sticky_posts' => true //caller_get_posts is deprecated since 3.1 ); $_posts1 = new WP_Query( $args1 ); if( $_posts1->have_posts() ) : while( $_posts1->have_posts() ) : $_posts1->the_post(); $post1 = get_post(); if ($post1->ID == $id) { $contador++; $servicos .= ' <span style="background-color:#eaeaea;padding:5px;"><i class="fa fa-info" style="font-size: 13px;"></i> <span style="margin-right:8px;margin-left: 6px;margin-top: -4px;font-size: 13px;">'.$term1->name.'</span></span>'; if (0 == ($contador % 3)){ $servicos .= '<br>'; } } endwhile; endif; } } $query_args = array( 'post_type' => 'product', 'meta_query' => array( array( 'key' => 'est_product_info', 'value' => $title, ), ) ); $query = new WP_Query( $query_args ); $apartamentos = []; if ( $query->posts ) { foreach ( $query->posts as $key => $post_id ) { $nome_apartamento = $post_id->post_title; $id_produto = $post_id->ID; $meta_acomodacao = get_post_meta( $id_produto, 'demo_product_info', true ); $meta_pessoas_acomodacao = get_post_meta( $id_produto, 'pessoas_demo_product_info', true ); $apto_demo_product_info = get_post_meta( $id_produto, 'apto_demo_product_info', true ); $tar_periodo_inicio_product_info = get_post_meta( $id_produto, 'tar_periodo_product_info', true ); $tar_periodo_final_product_info = get_post_meta( $id_produto, 'tar_periodo_final_product_info', true ); if ($meta_pessoas_acomodacao == 1) { $tipo = 'Single'; }else if ($meta_pessoas_acomodacao == 2) { $tipo = 'Duplo'; }else if ($meta_pessoas_acomodacao == 3) { $tipo = 'Triplo'; } $meta_valor_inicial_acomodacao = get_post_meta( $id_produto, 'tar_valor_final_product_info', true ); $tar_periodo_product_info = get_post_meta( $id_produto, 'periodo_product_info', true ); //regime_product_info $regime_product_info = get_post_meta( $id_produto, 'regime_product_info', true ); $check_taxas = get_post_meta( $id_produto, 'check_taxas', true ); $valor_taxas_exibicao = get_post_meta( $id_produto, 'valor_taxas', true ); $valor_taxas = get_post_meta( $id_produto, 'valor_taxas', true ); if (empty($valor_taxas) || $valor_taxas == 0 || $valor_taxas == "0,00") { $taxas = 'Valor das taxas inclusas'; }else{ $taxas = '+ '.get_woocommerce_currency_symbol ().' '.$valor_taxas.' em taxas e impostos'; } if ($meta_pessoas_acomodacao == $pax_pesquisa_inicial || $meta_pessoas_acomodacao == $pax_pesquisa_total) { $apartamentos[] = array("nome" => $nome_apartamento, "acomodacao" => $meta_acomodacao, "tipo" => $tipo, "pax" => $meta_pessoas_acomodacao, "valor" => $meta_valor_inicial_acomodacao, "id_produto" => $id_produto, "regime" => $regime_product_info, 'taxas' => $taxas, "nome_hotel" => $title, "descricao_hotel" => $description, "foto" => $url, "servicos" => $servicos, "qtd_quartos" => $apto_demo_product_info, "periodo" => $tar_periodo_product_info, "data_inicial" => implode("-", array_reverse(explode("/", $tar_periodo_inicio_product_info))), "data_fim" => implode("-", array_reverse(explode("/", $tar_periodo_final_product_info))), "valor_taxas_exibicao" => $valor_taxas_exibicao, "slug" => $slug); } if ($chd > 0) { for ($i=1; $i < 30; $i++) { $meta_valor_inicial_acomodacao = get_post_meta( $id_produto, 'tar_valor_final_product_info'.$i, true ); $regime_product_info = get_post_meta( $id_produto, 'regime_product_info'.$i, true ); $check_taxas = get_post_meta( $id_produto, 'check_taxas'.$i, true ); $valor_taxas = get_post_meta( $id_produto, 'valor_taxas'.$i, true ); $tar_periodo_product_info = get_post_meta( $id_produto, 'periodo_product_info'.$i, true ); $valor_taxas_exibicao = get_post_meta( $id_produto, 'valor_taxas'.$i, true ); if (empty($valor_taxas) || $valor_taxas == 0 || $valor_taxas == "0,00") { $valor_taxas = 0; $taxas = 'Valor das taxas incluso'; }else{ $taxas = '+ '.get_woocommerce_currency_symbol ().' '.$valor_taxas.' em taxas e impostos'; } $tar_periodo_inicio_product_info = get_post_meta( $id_produto, 'tar_periodo_product_info'.$i, true ); $tar_periodo_final_product_info = get_post_meta( $id_produto, 'tar_periodo_final_product_info'.$i, true ); $tar_check_crianca_product_info = get_post_meta( $id_produto, 'tar_check_crianca_product_info'.$i, true ); $tar_idade_crianca_product_info = get_post_meta( $id_produto, 'tar_idade_crianca_product_info'.$i, true ); if (!empty($meta_valor_inicial_acomodacao)) { if ($meta_pessoas_acomodacao == $pax_pesquisa_inicial || $meta_pessoas_acomodacao == $pax_pesquisa_total) { if ($tar_check_crianca_product_info === "on") { if ($tar_idade_crianca_product_info >= $idade_crianca) { $apartamentos[] = array("nome" => $nome_apartamento, "acomodacao" => $meta_acomodacao, "tipo" => $tipo, "pax" => $meta_pessoas_acomodacao, "valor" => $meta_valor_inicial_acomodacao, "id_produto" => $id_produto, "regime" => $regime_product_info, 'taxas' => $taxas, "nome_hotel" => $title, "descricao_hotel" => $description, "foto" => $url, "servicos" => $servicos, "qtd_quartos" => $apto_demo_product_info, "periodo" => $tar_periodo_product_info, "data_inicial" => implode("-", array_reverse(explode("/", $tar_periodo_inicio_product_info))), "data_fim" => implode("-", array_reverse(explode("/", $tar_periodo_final_product_info))), "valor_taxas_exibicao" => $valor_taxas_exibicao, "slug" => $slug); } } } } } }else{ for ($i=1; $i < 30; $i++) { $meta_valor_inicial_acomodacao = get_post_meta( $id_produto, 'tar_valor_final_product_info'.$i, true ); $regime_product_info = get_post_meta( $id_produto, 'regime_product_info'.$i, true ); $check_taxas = get_post_meta( $id_produto, 'check_taxas'.$i, true ); $valor_taxas = get_post_meta( $id_produto, 'valor_taxas'.$i, true ); $tar_periodo_product_info = get_post_meta( $id_produto, 'periodo_product_info'.$i, true ); $valor_taxas_exibicao = get_post_meta( $id_produto, 'valor_taxas'.$i, true ); if (empty($valor_taxas) || $valor_taxas == 0 || $valor_taxas == "0,00") { $valor_taxas = 0; $taxas = 'Valor das taxas incluso'; }else{ $taxas = '+ '.get_woocommerce_currency_symbol ().' '.$valor_taxas.' em taxas e impostos'; } $tar_periodo_inicio_product_info = get_post_meta( $id_produto, 'tar_periodo_product_info'.$i, true ); $tar_periodo_final_product_info = get_post_meta( $id_produto, 'tar_periodo_final_product_info'.$i, true ); $tar_check_crianca_product_info = get_post_meta( $id_produto, 'tar_check_crianca_product_info'.$i, true ); $tar_idade_crianca_product_info = get_post_meta( $id_produto, 'tar_idade_crianca_product_info'.$i, true ); if (!empty($meta_valor_inicial_acomodacao)) { if ($meta_pessoas_acomodacao == $pax_pesquisa_inicial) { $apartamentos[] = array("nome" => $nome_apartamento, "acomodacao" => $meta_acomodacao, "tipo" => $tipo, "pax" => $meta_pessoas_acomodacao, "valor" => $meta_valor_inicial_acomodacao, "id_produto" => $id_produto, "regime" => $regime_product_info, 'taxas' => $taxas, "nome_hotel" => $title, "descricao_hotel" => $description, "foto" => $url, "servicos" => $servicos, "qtd_quartos" => $apto_demo_product_info, "periodo" => $tar_periodo_product_info, "data_inicial" => implode("-", array_reverse(explode("/", $tar_periodo_inicio_product_info))), "data_fim" => implode("-", array_reverse(explode("/", $tar_periodo_final_product_info))), "valor_taxas_exibicao" => $valor_taxas_exibicao, "slug" => $slug); } } } } } $contador = 0; for ($x=0; $x < count($apartamentos); $x++) { ?> <?php if(strtotime(implode("-", array_reverse(explode("-", $dados[1])))) >= strtotime($apartamentos[$x]['data_inicial']) && strtotime(implode("-", array_reverse(explode("-", $dados[2])))) <= strtotime($apartamentos[$x]['data_fim'])){ ?> <?php $contador++; ?> <div class="row justify-content-center font hotel" > <div class="col-md-10 col-lg-10 col-xs-12"> <div class="row gallery0" style="background-color: #fff;box-shadow: 7px 14px 8px #ccc;border-radius: 8px;border: 1px solid #ccc;"> <div class="col-lg-4 col-xs-12 centeri img-div-responsive" style=" text-align: center; padding: 0 0px 9px 15px; "> <a class="imggallery0 vai" href=""><img src="<?=$apartamentos[$x]['foto']?>" class="img-responsive img-fluid imgHotel" style="margin:11px;display: none"></a> <div class="fotorama" data-nav="thumbs" data-thumbwidth="40" data-thumbheight="40" style="margin-top: 12px !important"> <img src="<?=$apartamentos[$x]['foto']?>" class="img-responsive img-fluid imgHotel" style="margin-top: 11px;"> <?php //an array with all the images (ba meta key). The same array has to be in custom_postimage_meta_box_save($post_id) as well. $meta_keys = array('featured_image0','featured_image1','featured_image2','featured_image3','featured_image4','featured_image5','featured_image6','featured_image7','featured_image8','featured_image9','featured_image10','featured_image11','featured_image12','featured_image13','featured_image14','featured_image15','featured_image16','featured_image17','featured_image18','featured_image19','featured_image20'); foreach($meta_keys as $meta_key){ $image_meta_val=get_post_meta( $id, $meta_key, true); if (!empty($image_meta_val)) { ?> <a href="<?=wp_get_attachment_image_src( $image_meta_val, 'full' )[0]?>"><img src="<?=wp_get_attachment_image_src( $image_meta_val, 'full' )[0]?>" alt="" width="90" height="90" data-thumbwidth="90" data-thumbheight="90"></a> <?php } ?> <?php } ?> </div> </div> <div class="col-lg-5 col-xs-12" style=""> <h3 class="tituloHotel" style="color: #0069a7!important;font-weight: 400;margin-bottom: 0;font-size: 28px;margin-top:6px"> <?=$apartamentos[$x]['nome_hotel']?> <br class="exibirCelular"></h3> <span><small style="font-size: 12px;color: #424242"><?=$localizacao?></small></span> <span class="exibirComputador" style="margin-right: 7px;margin-left: 7px;border-right: 1px solid #ccc;"></span> <br class="exibirCelular"> <hr style="margin-bottom: 5px;margin-top: 5px;"> <p style="line-height: 1.6;text-align: justify;"> <?=$apartamentos[$x]['descricao_hotel']?> </p> <?php if (!empty($apartamentos[$x]['servicos'])) { ?> <p style="font-weight: 700;font-size: 12px;margin-bottom: 0">SERVIÇOS DO HOTEL </p> <div class="row" style="margin-left: -1px;margin-bottom: 11px;"> <p style="line-height: 2.3;"> <?=$servicos?> </p> </div> <?php } ?> </div> <div class="col-lg-3 col-xs-12 borderC" style="/* padding-top: 24px; */margin-top: 11px;"> <br class="exibirComputador"> <p class="exibirComputador" style="margin-bottom: 9px;"><br></p> <div class="row" style="margin-bottom: 8px;padding-top: 4px;padding-bottom: 3px;"> <div class="col-lg-12 col-xs-12 paddingCelular" style="margin-right: -7px;text-align: right;"> <span style="float: left;font-size: 13px"><strong style="font-size: 13px">Período: </strong><?=str_replace("-", "/", $dados[1]) ?> a <?=str_replace("-", "/", $dados[2])?></span> <br> <strong style="float: left"><?=$apartamentos[$x]['acomodacao']?></strong><br> <?php if (!empty($apartamentos[$x]['regime'])) { ?> <strong style="float: left;color: green"><?=$apartamentos[$x]['regime']?></strong><br> <?php } ?> <br> <?=$diaria?> <br> <?=$pax?><?=$quartos?> <?= $idades?> <br> <?php $valor_diaria = str_replace(",", ".", str_replace(".", "", $apartamentos[$x]['valor'])); $valor_total_sem_taxa = (intval($diferenca_data->days)+1)*floatval($valor_diaria); ?> <span style="font-size: 22px"><?=get_woocommerce_currency_symbol ();?> <?=number_format($valor_total_sem_taxa, 2, ',', '.') ?></span> <br> <?=$apartamentos[$x]['taxas']?> <br> <strong style="font-size: 13px;<?=($apartamentos[$x]['qtd_quartos'] <= 5 ? 'color:red' : '')?>"><?=$apartamentos[$x]['qtd_quartos']?> quartos disponíveis</strong> </div> </div> <br> <form action="/apto/?param=<?=str_replace(" ", "-", $apartamentos[$x]['acomodacao'])?>;<?=$apartamentos[$x]['id_produto']?>;<?=strtolower($apartamentos[$x]['slug'])?>" method="POST"> <input type="hidden" name="periodo" value="<?=str_replace("-", "/", $dados[1]) ?> a <?=str_replace("-", "/", $dados[2])?>"> <input type="hidden" name="acomodacao" value="<?=$apartamentos[$x]['acomodacao']?>"> <input type="hidden" name="regime" value="<?=$apartamentos[$x]['regime']?>"> <input type="hidden" name="diaria" value="<?=$diaria?>"> <input type="hidden" name="por_dia" value="<?= $apartamentos[$x]['valor']?>"> <input type="hidden" name="pax" value="<?=$pax?><?=$quartos?>"> <input type="hidden" name="valor" value="<?=get_woocommerce_currency_symbol ();?> <?=number_format($valor_total_sem_taxa, 2, ',', '.')?>"> <input type="hidden" name="valor_calendario_sem_formatacao" value="<?=$apartamentos[$x]['valor']?>"> <input type="hidden" name="taxas" value="<?=$apartamentos[$x]['taxas']?>"> <input type="hidden" name="valor_taxas" value="<?=$apartamentos[$x]['valor_taxas_exibicao']?>"> <input type="hidden" name="qtd_quartos" value="<?=$apartamentos[$x]['qtd_quartos']?>"> <button class="btn btn-primary" style="float: right;width: 100%;font-size: 17px;margin-bottom: 14px;"><i class="fas fa-calendar-alt"></i> Ver disponibilidade</button> </form> <br><br> </div> </div> </div> </div> <br> <?php } } } } endwhile; endif; } } if ($contador == 0) { ?> <div class="row justify-content-center font hotel" > <h4>Nenhum resultado disponível.</h4> </div> <?php } ?> <br> </div> <br><br> </div> <input type="hidden" id="uri" name="" value="<?=$_SERVER['REQUEST_URI']?>"> <script type="text/javascript"> function show_div_count(){ jQuery(".dropdown").toggle(500); } jQuery(document).ready(function(){ jQuery('.count').prop('disabled', true); jQuery(document).on('click','.plus',function(){ var valor = parseInt(jQuery('.count').val()) + 1; jQuery('.count').val(valor); jQuery("#count_adultos").html("<strong>"+valor+" adultos</strong>"); }); jQuery(document).on('click','.minus',function(){ var valor = parseInt(jQuery('.count').val()) - 1; jQuery('.count').val(valor); jQuery("#count_adultos").html("<strong>"+valor+" adultos</strong>"); if (jQuery('.count').val() == 0 || jQuery('.count').val() == 1) { jQuery('.count').val(1); jQuery("#count_adultos").html("<strong>1 adulto</strong>"); } }); jQuery('.count_child').prop('disabled', true); jQuery(document).on('click','.plus_child',function(){ var valor = parseInt(jQuery('.count_child').val()) + 1; jQuery('.count_child').val(valor); jQuery("#count_criancas").html("<strong>"+valor+" crianças</strong>"); if (jQuery('.count_child').val() == 1) { jQuery('.count_child').val(1); jQuery("#count_criancas").html("<strong>1 criança</strong>"); } }); jQuery(document).on('click','.minus_child',function(){ var valor = parseInt(jQuery('.count_child').val()) - 1; jQuery('.count_child').val(valor); jQuery("#count_criancas").html("<strong>"+valor+" crianças</strong>"); if (jQuery('.count_child').val() == 0) { jQuery('.count_child').val(1); jQuery("#count_criancas").html("<strong>0 criança</strong>"); } if (jQuery('.count_child').val() == 1) { jQuery('.count_child').val(1); jQuery("#count_criancas").html("<strong>1 criança</strong>"); } }); jQuery('.count_quartos').prop('disabled', true); jQuery(document).on('click','.plus_quartos',function(){ var valor = parseInt(jQuery('.count_quartos').val()) + 1; jQuery('.count_quartos').val(valor); jQuery("#count_quartos").html("<strong>"+valor+" quartos</strong>"); }); jQuery(document).on('click','.minus_quartos',function(){ var valor = parseInt(jQuery('.count_quartos').val()) - 1; jQuery('.count_quartos').val(valor); jQuery("#count_quartos").html("<strong>"+valor+" quartos</strong>"); if (jQuery('.count_quartos').val() == 0 || jQuery('.count_quartos').val() == 1) { jQuery('.count_quartos').val(1); jQuery("#count_quartos").html("<strong>1 quarto</strong>"); } }); }); function AtribuiValorHotel(id){ var dados = jQuery("#nameHotel"+id).val(); var uri = jQuery("#uri").val(); dados = dados.split(";"); jQuery("#uri").val('/apto/?param=Comfort-Vista-Mar;343;hotel-copacabana-palace'); } function enviarFormTodos(){ var uri = jQuery("#uri").val(); window.location.href = uri; } </script> <!-- /Blog Section with Sidebar --> <?php get_footer(); ?><file_sep><link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <!------ Include the above in your HEAD tag ----------> <style type="text/css"> body{ background-color: #f1f1f1 !important; } </style> <div class="container"> <div class="row"> <div class="col-lg-12"> <h1 style="font-size: 22px">Visão geral do calendário</h1> </div> </div> <div class="row"> <div class="col-lg-12" style=""> <div style=""> <a><button class="btn btn-default" style="margin-right: -5px;background-color: #797979;color: #fff;margin-bottom: -1px;border-radius: 5px 5px 0px 0px;padding: 5px 15px;font-size: 13px;"><i class="fa fa-fire"></i> <strong>Ações</strong></button></a> </div> </div> <div class="col-lg-12" style=""> <div style="padding: 10px;border: 1px solid #ccc;"> <a onclick="diminui_mes()"><button class="btn btn-default btn_minus" style="margin-right: -5px;"><i class="fa fa-arrow-left"></i></button></a> <input type="text" name="" id="description_month" disabled="" style="text-align: center;height: 34px;width: 250px;font-size: 18px;font-weight: 600;position: relative;top: 2px;" value="Abril/2021"> <a onclick="acrescenta_mes()"><button class="btn btn-default btn_plus" style="margin-left: -5px;"><i class="fa fa-arrow-right"></i></button></a> <input type="hidden" name="" id="month" value="4"> </div> </div> </div> <br> <?php for ($x=1; $x < 13; $x++) { ?> <?php if ($x < 10) { $conta_mes = "0".$x; }else{ $conta_mes = $x; } if ($conta_mes == "01") { $conta_dias = 32; }else if ($conta_mes == "02") { $conta_dias = 29; }else if ($conta_mes == "03") { $conta_dias = 32; }else if ($conta_mes == "04") { $conta_dias = 31; }else if ($conta_mes == "05") { $conta_dias = 32; }else if ($conta_mes == "06") { $conta_dias = 31; }else if ($conta_mes == "07") { $conta_dias = 32; }else if ($conta_mes == "08") { $conta_dias = 32; }else if ($conta_mes == "09") { $conta_dias = 31; }else if ($conta_mes == "10") { $conta_dias = 32; }else if ($conta_mes == "11") { $conta_dias = 31; }else if ($conta_mes == "01") { $conta_dias = 32; } ?> <div id="<?=$conta_mes?>" style="background-color: #fff;padding-bottom: 14px;<?=($conta_mes == date("m") ? 'display:block' : 'display: none')?>"> <div id="head" style="background-color: #fff;padding-top: 10px"> <div class="row" id="<?=$conta_mes?>" style="height: 35px"> <div class='col-lg-2' style="border-right: 2px solid #b90c0c;height: 35px;"></div> <div class="col-lg-10"> <table> <tbody> <tr> <?php for ($y=1; $y < $conta_dias; $y++) { ?> <td style="padding: 0px 7.2px;border: 1px solid #bbb;height: 35px;"><?=$y?></td> <?php } ?> </tr> </tbody> </table> </div> </div> </div> <?php $args = array( 'post_type' => 'shop_order', 'post_status' => 'wc-completed, wc-processing', 'numberposts' => 100 ); $my_posts = new WP_Query( $args ); $contador = 0; if( $my_posts->have_posts() ) : while( $my_posts->have_posts() ) : $my_posts->the_post(); $post = get_post(); $title = $post->post_title; $id = $post->ID; $order = wc_get_order( $id ); $order_id = $order->get_id(); $data = $order->get_data(); $dados = array_values($data['line_items'])[0]->get_data(); $meta_data = $dados['meta_data']; for ($i=0; $i < count($meta_data); $i++) { $data = $meta_data[$i]->get_data(); if ($data['key'] == 'datas') { $periodo = explode(" - ", $data['value']); $data_inicial = explode("/", $periodo[0]); $data_final = explode("/", $periodo[1]); } } if($data_inicial[1] == $conta_mes){ $contador++; ?> <div class="row" style="height: 35px"> <div class='col-lg-2' style="border-right: 2px solid #b90c0c;height: 35px;"> <a href="/wp-admin/post.php?post=<?=$id?>&action=edit"><h4 style="margin: 0;font-size: 18px;padding: 6px 10px;">Reserva nº <?=$id?></h4></a> </div> <div class="col-lg-10"> <table> <tbody> <tr> <?php for ($i=1; $i < $conta_dias; $i++) { ?> <?php if ($i >= intval($data_inicial[0]) && $i <= intval($data_final[0])) { ?> <td style="padding: 0px 7.2px;border: 1px solid #3355fd;height: 35px;background-color: #3355fd;color: #3355fd;font-size: 14px;"><?=$i?></td> <?php }else{ ?> <td style="padding: 0px 7.2px;border: 1px solid #bbb;height: 35px;color: #d4d4d4;font-size: 14px;"><?=$i?></td> <?php } ?> <?php } ?> </tr> </tbody> </table> </div> </div> <?php } endwhile; endif; if ($contador == 0) { ?> <div class="row" style="height: 35px"> <div class='col-lg-12 text-center' style="height: 35px;"> <h5 style="margin-top: 15px">Nenhuma reserva encontrada para o mês selecionado.</h5> </div> </div> <?php } ?> </div> <?php } ?> </div> <script type="text/javascript"> function acrescenta_mes(){ var month = $("#month").val(); $(".btn_minus").prop("disabled", false); $(".btn_plus").prop("disabled", false); if (month == "00" || month == "01") { $(".btn_minus").prop("disabled", true); $("#description_month").val("Janeiro/2021"); $("#01").attr("style", "background-color: #fff;padding-bottom: 14px;display:block"); $("#02").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#03").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#04").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#05").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#06").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#07").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#08").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#09").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#10").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#11").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#12").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); }else if (month == "02") { $("#description_month").val("Fevereiro/2021"); $("#01").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#02").attr("style", "background-color: #fff;padding-bottom: 14px;display:block"); $("#03").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#04").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#05").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#06").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#07").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#08").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#09").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#10").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#11").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#12").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); }else if (month == "03") { $("#description_month").val("Março/2021"); $("#01").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#02").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#03").attr("style", "background-color: #fff;padding-bottom: 14px;display:block"); $("#04").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#05").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#06").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#07").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#08").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#09").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#10").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#11").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#12").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); }else if (month == "04") { $("#description_month").val("Abril/2021"); $("#01").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#02").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#03").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#04").attr("style", "background-color: #fff;padding-bottom: 14px;display:block"); $("#05").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#06").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#07").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#08").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#09").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#10").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#11").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#12").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); }else if (month == "05") { $("#description_month").val("Maio/2021"); $("#01").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#02").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#03").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#04").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#05").attr("style", "background-color: #fff;padding-bottom: 14px;display:block"); $("#06").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#07").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#08").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#09").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#10").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#11").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#12").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); }else if (month == "06") { $("#description_month").val("Junho/2021"); $("#01").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#02").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#03").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#04").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#05").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#06").attr("style", "background-color: #fff;padding-bottom: 14px;display:block"); $("#07").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#08").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#09").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#10").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#11").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#12").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); }else if (month == "07") { $("#description_month").val("Julho/2021"); $("#01").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#02").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#03").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#04").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#05").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#06").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#07").attr("style", "background-color: #fff;padding-bottom: 14px;display:block"); $("#08").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#09").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#10").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#11").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#12").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); }else if (month == "08") { $("#description_month").val("Agosto/2021"); $("#01").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#02").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#03").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#04").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#05").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#06").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#07").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#08").attr("style", "background-color: #fff;padding-bottom: 14px;display:block"); $("#09").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#10").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#11").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#12").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); }else if (month == "09") { $("#description_month").val("Setembro/2021"); $("#01").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#02").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#03").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#04").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#05").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#06").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#07").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#08").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#09").attr("style", "background-color: #fff;padding-bottom: 14px;display:block"); $("#10").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#11").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#12").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); }else if (month == "10") { $("#description_month").val("Outubro/2021"); $("#01").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#02").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#03").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#04").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#05").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#06").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#07").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#08").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#09").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#10").attr("style", "background-color: #fff;padding-bottom: 14px;display:block"); $("#11").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#12").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); }else if (month == "11") { $("#description_month").val("Novembro/2021"); $("#01").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#02").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#03").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#04").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#05").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#06").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#07").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#08").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#09").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#10").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#11").attr("style", "background-color: #fff;padding-bottom: 14px;display:block"); $("#12").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); }else if (month == "12") { $(".btn_plus").prop("disabled", true); $("#description_month").val("Dezembro/2021"); $("#01").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#02").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#03").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#04").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#05").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#06").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#07").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#08").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#09").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#10").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#11").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#12").attr("style", "background-color: #fff;padding-bottom: 14px;display:block"); } if (month == 0) { $("#month").val("01"); }else{ if (month < 10) { month = parseInt(month)+1; $("#month").val("0"+month); }else{ month = parseInt(month)+1; $("#month").val(month); } } } function diminui_mes(){ var month = $("#month").val(); $(".btn_minus").prop("disabled", false); $(".btn_plus").prop("disabled", false); if (month == "00" || month == "01") { $(".btn_minus").prop("disabled", true); $("#description_month").val("Janeiro/2021"); $("#01").attr("style", "background-color: #fff;padding-bottom: 14px;display:block"); $("#02").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#03").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#04").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#05").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#06").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#07").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#08").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#09").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#10").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#11").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#12").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); }else if (month == "02") { $("#description_month").val("Fevereiro/2021"); $("#01").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#02").attr("style", "background-color: #fff;padding-bottom: 14px;display:block"); $("#03").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#04").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#05").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#06").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#07").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#08").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#09").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#10").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#11").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#12").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); }else if (month == "03") { $("#description_month").val("Março/2021"); $("#01").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#02").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#03").attr("style", "background-color: #fff;padding-bottom: 14px;display:block"); $("#04").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#05").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#06").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#07").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#08").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#09").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#10").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#11").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#12").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); }else if (month == "04") { $("#description_month").val("Abril/2021"); $("#01").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#02").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#03").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#04").attr("style", "background-color: #fff;padding-bottom: 14px;display:block"); $("#05").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#06").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#07").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#08").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#09").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#10").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#11").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#12").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); }else if (month == "05") { $("#description_month").val("Maio/2021"); $("#01").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#02").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#03").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#04").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#05").attr("style", "background-color: #fff;padding-bottom: 14px;display:block"); $("#06").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#07").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#08").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#09").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#10").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#11").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#12").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); }else if (month == "06") { $("#description_month").val("Junho/2021"); $("#01").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#02").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#03").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#04").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#05").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#06").attr("style", "background-color: #fff;padding-bottom: 14px;display:block"); $("#07").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#08").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#09").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#10").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#11").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#12").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); }else if (month == "07") { $("#description_month").val("Julho/2021"); $("#01").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#02").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#03").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#04").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#05").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#06").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#07").attr("style", "background-color: #fff;padding-bottom: 14px;display:block"); $("#08").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#09").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#10").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#11").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#12").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); }else if (month == "08") { $("#description_month").val("Agosto/2021"); $("#01").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#02").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#03").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#04").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#05").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#06").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#07").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#08").attr("style", "background-color: #fff;padding-bottom: 14px;display:block"); $("#09").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#10").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#11").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#12").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); }else if (month == "09") { $("#description_month").val("Setembro/2021"); $("#01").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#02").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#03").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#04").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#05").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#06").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#07").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#08").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#09").attr("style", "background-color: #fff;padding-bottom: 14px;display:block"); $("#10").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#11").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#12").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); }else if (month == "10") { $("#description_month").val("Outubro/2021"); $("#01").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#02").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#03").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#04").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#05").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#06").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#07").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#08").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#09").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#10").attr("style", "background-color: #fff;padding-bottom: 14px;display:block"); $("#11").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#12").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); }else if (month == "11") { $("#description_month").val("Novembro/2021"); $("#01").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#02").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#03").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#04").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#05").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#06").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#07").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#08").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#09").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#10").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#11").attr("style", "background-color: #fff;padding-bottom: 14px;display:block"); $("#12").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); }else if (month == "12") { $(".btn_plus").prop("disabled", true); $("#description_month").val("Dezembro/2021"); $("#01").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#02").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#03").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#04").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#05").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#06").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#07").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#08").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#09").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#10").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#11").attr("style", "background-color: #fff;padding-bottom: 14px;display:none"); $("#12").attr("style", "background-color: #fff;padding-bottom: 14px;display:block"); } if (month == 0) { $("#month").val("01"); }else{ if (month < 10) { month = parseInt(month)-1; $("#month").val("0"+month); }else{ month = parseInt(month)-1; $("#month").val(month); } } } </script> <file_sep><?php $id_hotel = $_POST['id']; if ($_POST['chd'] > 0) { for ($i=0; $i < $_POST['chd']; $i++) { $idades = '12,'; } $idades_chd = substr($idades, 0, -1); $pax = array(array('adt' => $_POST['adt'], 'idadeschd' => array($idades_chd))); }else{ $pax = array(array('adt' => $_POST['adt'])); } if ($_POST['chd'] == 0) { $crianca = ''; $idades = 0; }else{ if ($_POST['chd'] == 1) { $crianca = ' e '.$_POST['chd'].' criança'; }else{ $crianca = ' e '.$_POST['chd'].' crianças'; for ($i=0; $i < $_POST['chd']; $i++) { $idade .= '12,'; } $idades = substr($idade, 0, -1); } } $desc_pax = $_POST['adt'].' '.($_POST['adt'] > 1 ? 'adultos' : 'adulto').' '.$crianca; $data_inicio = new DateTime(implode("-", array_reverse(explode("-", $_POST['data_inicio'])))); $data_fim = new DateTime(implode("-", array_reverse(explode("-", $_POST['data_final'])))); // Resgata diferença entre as datas $diferenca_data = $data_inicio->diff($data_fim); $qtd_diarias = $diferenca_data->days; if ($diferenca_data->days == 1) { $diaria = '1 diária'; }else{ $diaria = (intval($diferenca_data->days)+1).' diárias'; } $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://quasar.e-htl.com.br/oauth/access_token", CURLOPT_RETURNTRANSFER => TRUE, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => "username=91355&password=<PASSWORD>", CURLOPT_HTTPHEADER => array( "cache-control: no-cache", "x-detailed-error: " ), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { echo "cURL Error #:" . $err; } else { $itens = json_decode($response, true); $token = $itens["access_token"]; } function tirarAcentos($string){ return preg_replace(array("/(á|à|ã|â|ä)/","/(Á|À|Ã|Â|Ä)/","/(é|è|ê|ë)/","/(É|È|Ê|Ë)/","/(í|ì|î|ï)/","/(Í|Ì|Î|Ï)/","/(ó|ò|õ|ô|ö)/","/(Ó|Ò|Õ|Ô|Ö)/","/(ú|ù|û|ü)/","/(Ú|Ù|Û|Ü)/","/(ñ)/","/(Ñ)/"),explode(" ","a A e E i I o O u U n N"),$string); } $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'https://quasar.e-htl.com.br/booking/hotels-availabilities', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => '{"data": {"attributes": { "destinationId": "'.$_POST['destination'].'", "checkin": "'.implode("-", array_reverse(explode("-", $_POST['data_inicio']))).'", "nights": '.$qtd_diarias.', "roomsAmount": '.$_POST['qts'].', "rooms": [{"adults": '.$_POST['adt'].', "children": '.$_POST['chd'].', "childrenages": ['.$idades.']}], "signsInvoice": 0, "onlyAvailable": true}}}', CURLOPT_HTTPHEADER => array( "authorization: Bearer ".$token, "cache-control: no-cache", "content-type: application/json" ), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { echo "cURL Error #:" . $err; } else { $itens = json_decode($response, true); $hoteis = $itens['data']; } $contador = 0; for ($i=0; $i < count($hoteis); $i++) { $id = $hoteis[$i]["id"]; if ($id == $id_hotel) { $contador = 1; //nome, foto, descrição, preço $foto = $hoteis[$i]["attributes"]["hotelImages"][0]; $descricao = $hoteis[$i]["attributes"]["hotelDescription"]; for ($x=0; $x < 9; $x++) { $nome = $hoteis[$i]["attributes"]["hotelRooms"][$x]["roomsDetail"][0]["roomName"]; $preco = $hoteis[$i]["attributes"]["hotelRooms"][$x]["roomsDetail"][0]["dailyPrices"][0]["price"]; $dados_hoteis[] = array("id" => $id, "nome" => ucfirst(tirarAcentos(strtolower($nome))), "foto" => str_replace("/", "%u;", $foto), "descricao" => tirarAcentos($descricao), "preco" => $preco, "fornecedor" => "Ehtl", "acomodacao" => ucfirst(tirarAcentos(strtolower($hoteis[$i]["attributes"]["hotelRooms"][$x]["roomsDetail"][0]["roomName"]))), "tipo" => ucfirst(tirarAcentos(strtolower($hoteis[$i]["attributes"]["hotelRooms"][$x]["roomsDetail"][0]["roomName"]))), "pax" => tirarAcentos($desc_pax), "regime" => ucfirst(tirarAcentos(strtolower($hoteis[$i]["attributes"]["hotelRooms"][$x]["roomsDetail"][0]["regime"]))), "checkin" => $_POST['data_inicio'], "checkout" => $_POST['data_final'], "diarias" => ucfirst(tirarAcentos(strtolower($diaria)))); } } } if ($contador == 1) { echo str_replace("\"", "%s;", json_encode($dados_hoteis)); }else{ echo "0"; } ?><file_sep><script src="<?=plugin_dir_path(__FILE__)?>/includes/assets/js/scripts.js"></script><file_sep>jQuery(document).ready(function(){ jQuery(".demo_options").attr("style", "display:none"); jQuery(".est_options").attr("style", "display:none"); jQuery(".tar_options").attr("style", "display:none"); jQuery(".acomodacao_options").attr("style", "display:none"); jQuery("#tar_valor_final_product_info2").attr("onKeyPress", "return(moeda(this,\".\",\",\",event))"); jQuery("#tar_idade_crianca_product_info").mask("00"); jQuery("#tar_idade_crianca_product_info1").mask("00"); jQuery("#tar_idade_crianca_product_info2").mask("00"); jQuery("#tar_idade_crianca_product_info3").mask("00"); jQuery("#tar_idade_crianca_product_info4").mask("00"); jQuery("#tar_idade_crianca_product_info5").mask("00"); jQuery("#tar_idade_crianca_product_info6").mask("00"); jQuery("#tar_idade_crianca_product_info7").mask("00"); jQuery("#tar_idade_crianca_product_info8").mask("00"); jQuery("#tar_idade_crianca_product_info9").mask("00"); jQuery("#tar_qtd_limite").mask("00"); jQuery("#tar_qtd_limite1").mask("00"); jQuery("#tar_qtd_limite2").mask("00"); jQuery("#tar_qtd_limite3").mask("00"); jQuery("#tar_qtd_limite4").mask("00"); jQuery("#tar_qtd_limite5").mask("00"); jQuery("#tar_qtd_limite6").mask("00"); jQuery("#tar_qtd_limite7").mask("00"); jQuery("#tar_qtd_limite8").mask("00"); jQuery("#tar_qtd_limite9").mask("00"); jQuery("#tar_periodo_product_info").attr("autocomplete", "off"); jQuery("#tar_periodo_final_product_info").attr("autocomplete", "off"); jQuery("#tar_periodo_product_info1").attr("autocomplete", "off"); jQuery("#tar_periodo_final_product_info1").attr("autocomplete", "off"); jQuery("#tar_periodo_product_info2").attr("autocomplete", "off"); jQuery("#tar_periodo_final_product_info2").attr("autocomplete", "off"); jQuery("#tar_periodo_product_info3").attr("autocomplete", "off"); jQuery("#tar_periodo_final_product_info3").attr("autocomplete", "off"); jQuery("#tar_periodo_product_info4").attr("autocomplete", "off"); jQuery("#tar_periodo_final_product_info4").attr("autocomplete", "off"); jQuery("#tar_periodo_product_info5").attr("autocomplete", "off"); jQuery("#tar_periodo_final_product_info5").attr("autocomplete", "off"); jQuery("#tar_periodo_product_info6").attr("autocomplete", "off"); jQuery("#tar_periodo_final_product_info6").attr("autocomplete", "off"); jQuery('.valor').mask('00.000.000,00', { reverse: true }); jQuery('#tar_valor_final_product_info1').mask('00.000.000,00', { reverse: true }); jQuery('#tar_valor_final_product_info2').mask('00.000.000,00', { reverse: true }); jQuery('#tar_valor_final_product_info3').mask('00.000.000,00', { reverse: true }); jQuery('#tar_valor_final_product_info4').mask('00.000.000,00', { reverse: true }); jQuery('#tar_valor_final_product_info5').mask('00.000.000,00', { reverse: true }); jQuery('#valor_taxas').mask('00.000.000,00', { reverse: true }); jQuery('#valor_taxas1').mask('00.000.000,00', { reverse: true }); jQuery('#valor_taxas2').mask('00.000.000,00', { reverse: true }); jQuery('#valor_taxas3').mask('00.000.000,00', { reverse: true }); jQuery('#valor_taxas4').mask('00.000.000,00', { reverse: true }); jQuery('#valor_taxas5').mask('00.000.000,00', { reverse: true }); jQuery('#valor_taxas6').mask('00.000.000,00', { reverse: true }); jQuery('#valor_taxas7').mask('00.000.000,00', { reverse: true }); jQuery(document).on('focusout','#tar_valor_final_product_info',function(){ if (jQuery('#tar_valor_final_product_info').val() == 0 || jQuery('#tar_valor_final_product_info').val() == '0,00') { alert("O valor da diária não pode ser zerado."); } }); jQuery(document).on('focusout','#tar_valor_final_product_info1',function(){ if (jQuery('#tar_valor_final_product_info1').val() == 0 || jQuery('#tar_valor_final_product_info1').val() == '0,00') { alert("O valor da diária não pode ser zerado."); } }); jQuery(document).on('focusout','#tar_valor_final_product_info2',function(){ if (jQuery('#tar_valor_final_product_info2').val() == 0 || jQuery('#tar_valor_final_product_info2').val() == '0,00') { alert("O valor da diária não pode ser zerado."); } }); jQuery(document).on('focusout','#tar_valor_final_product_info3',function(){ if (jQuery('#tar_valor_final_product_info3').val() == 0 || jQuery('#tar_valor_final_product_info3').val() == '0,00') { alert("O valor da diária não pode ser zerado."); } }); jQuery(document).on('focusout','#tar_valor_final_product_info4',function(){ if (jQuery('#tar_valor_final_product_info4').val() == 0 || jQuery('#tar_valor_final_product_info4').val() == '0,00') { alert("O valor da diária não pode ser zerado."); } }); }); jQuery(document).on('change','#product-type',function(){ var tipo = jQuery("#product-type").val(); if (tipo == "demo") { jQuery(".general_options").attr("style", "display:none"); jQuery(".shipping_options").attr("style", "display:none"); jQuery(".linked_product_options").attr("style", "display:none"); jQuery(".attribute_options").attr("style", "display:none"); jQuery(".advanced_options").attr("style", "position: absolute;top: 123px;z-index: 1;width: 100%;"); jQuery(".demo_options").attr("style", ""); jQuery(".est_options").attr("style", ""); jQuery(".tar_options").attr("style", ""); jQuery(".acomodacao_options").attr("style", ""); jQuery(".demo_options").addClass("active"); // Panels jQuery("#general_product_data").attr("style", "display:none"); jQuery("#inventory_product_data").attr("style", "display:none"); jQuery("#variable_product_options").attr("style", "display:none"); jQuery("#advanced_product_data").attr("style", "display:none"); jQuery("#product_attributes").attr("style", "display:none"); jQuery("#linked_product_data").attr("style", "display:none"); jQuery("#shipping_product_data").attr("style", "display:none"); jQuery("#demo_product_options").attr("style", "display:block"); } } ); function exibe_div_table(){ jQuery(".div_dias").toggle(2200); } function exibe_div_table_append(contador){ jQuery(".div_dias"+contador).toggle(2200); } function remove_div(contador){ jQuery(".dados_tarifario"+contador).remove(); } function adicionar_tarifa(){ var iti_index = 0 < jQuery("#table_append_repeater").length ? jQuery("#table_append_repeater").length + 1 : 1; var template = wp.template("wc-add-tarifa-row"); jQuery("#table_append_repeater_holder").append( template({ key: iti_index }) ); jQuery("#tar_valor_final_product_info"+iti_index).addClass("valor"); jQuery('#tar_periodo_product_info'+iti_index) .datepicker({ language: 'pt-BR', minDate: new Date(), autoClose: true, dateFormat: 'dd/mm/yy', onSelect: function (selectedDate) { //Limpamos a segunda data, para evitar problemas do usuário ficar trocando a data do primeiro datepicker e acabar burlando as regras definidas. jQuery.datepicker._clearDate(jQuery("#tar_periodo_final_product_info"+iti_index)); //Aqui está a "jogada" para somar os 7 dias para o próximo datepicker. var data = jQuery.datepicker.parseDate('dd/mm/yy', selectedDate); jQuery("#tar_periodo_final_product_info"+iti_index).datepicker("option", "minDate", data); //Aplica a data } }); jQuery('#tar_periodo_final_product_info'+iti_index) .datepicker({ language: 'pt-BR', autoClose: true, dateFormat: 'dd/mm/yy', }); jQuery('#tar_periodo_product_info'+iti_index).mask("00/00/0000"); jQuery('#tar_periodo_final_product_info'+iti_index).mask("00/00/0000"); jQuery('#tar_valor_final_product_info'+iti_index).mask('00.000.000,00', { reverse: true }); jQuery("#tar_idade_crianca_product_info"+iti_index).mask("00"); jQuery("#tar_qtd_limite"+iti_index).mask("00"); ++iti_index; } jQuery(function() { jQuery('#tar_periodo_product_info') .datepicker({ language: 'pt-BR', minDate: new Date(), autoClose: true, dateFormat: 'dd/mm/yy', onSelect: function (selectedDate) { //Limpamos a segunda data, para evitar problemas do usuário ficar trocando a data do primeiro datepicker e acabar burlando as regras definidas. jQuery.datepicker._clearDate(jQuery("#tar_periodo_final_product_info")); //Aqui está a "jogada" para somar os 7 dias para o próximo datepicker. var data = jQuery.datepicker.parseDate('dd/mm/yy', selectedDate); jQuery("#tar_periodo_final_product_info").datepicker("option", "minDate", data); //Aplica a data } }); jQuery('#tar_periodo_final_product_info') .datepicker({ language: 'pt-BR', autoClose: true, dateFormat: 'dd/mm/yy', }); jQuery('#tar_periodo_product_info').mask("00/00/0000"); jQuery('#tar_periodo_final_product_info').mask("00/00/0000"); jQuery('#tar_periodo_product_info1') .datepicker({ language: 'pt-BR', minDate: new Date(), autoClose: true, dateFormat: 'dd/mm/yy', onSelect: function (selectedDate) { //Limpamos a segunda data, para evitar problemas do usuário ficar trocando a data do primeiro datepicker e acabar burlando as regras definidas. jQuery.datepicker._clearDate(jQuery("#tar_periodo_final_product_info1")); //Aqui está a "jogada" para somar os 7 dias para o próximo datepicker. var data = jQuery.datepicker.parseDate('dd/mm/yy', selectedDate); jQuery("#tar_periodo_final_product_info1").datepicker("option", "minDate", data); //Aplica a data } }); jQuery('#tar_periodo_final_product_info1') .datepicker({ language: 'pt-BR', autoClose: true, dateFormat: 'dd/mm/yy', }); jQuery('#tar_periodo_product_info1').mask("00/00/0000"); jQuery('#tar_periodo_final_product_info1').mask("00/00/0000"); jQuery('#tar_periodo_product_info2') .datepicker({ language: 'pt-BR', minDate: new Date(), autoClose: true, dateFormat: 'dd/mm/yy', onSelect: function (selectedDate) { //Limpamos a segunda data, para evitar problemas do usuário ficar trocando a data do primeiro datepicker e acabar burlando as regras definidas. jQuery.datepicker._clearDate(jQuery("#tar_periodo_final_product_info2")); //Aqui está a "jogada" para somar os 7 dias para o próximo datepicker. var data = jQuery.datepicker.parseDate('dd/mm/yy', selectedDate); jQuery("#tar_periodo_final_product_info2").datepicker("option", "minDate", data); //Aplica a data } }); jQuery('#tar_periodo_final_product_info2') .datepicker({ language: 'pt-BR', autoClose: true, dateFormat: 'dd/mm/yy', }); jQuery('#tar_periodo_product_info2').mask("00/00/0000"); jQuery('#tar_periodo_final_product_info2').mask("00/00/0000"); jQuery('#tar_periodo_product_info3') .datepicker({ language: 'pt-BR', minDate: new Date(), autoClose: true, dateFormat: 'dd/mm/yy', onSelect: function (selectedDate) { //Limpamos a segunda data, para evitar problemas do usuário ficar trocando a data do primeiro datepicker e acabar burlando as regras definidas. jQuery.datepicker._clearDate(jQuery("#tar_periodo_final_product_info3")); //Aqui está a "jogada" para somar os 7 dias para o próximo datepicker. var data = jQuery.datepicker.parseDate('dd/mm/yy', selectedDate); jQuery("#tar_periodo_final_product_info3").datepicker("option", "minDate", data); //Aplica a data } }); jQuery('#tar_periodo_final_product_info3') .datepicker({ language: 'pt-BR', autoClose: true, dateFormat: 'dd/mm/yy', }); jQuery('#tar_periodo_product_info3').mask("00/00/0000"); jQuery('#tar_periodo_final_product_info3').mask("00/00/0000"); jQuery('#tar_periodo_product_info4') .datepicker({ language: 'pt-BR', minDate: new Date(), autoClose: true, dateFormat: 'dd/mm/yy', onSelect: function (selectedDate) { //Limpamos a segunda data, para evitar problemas do usuário ficar trocando a data do primeiro datepicker e acabar burlando as regras definidas. jQuery.datepicker._clearDate(jQuery("#tar_periodo_final_product_info4")); //Aqui está a "jogada" para somar os 7 dias para o próximo datepicker. var data = jQuery.datepicker.parseDate('dd/mm/yy', selectedDate); jQuery("#tar_periodo_final_product_info4").datepicker("option", "minDate", data); //Aplica a data } }); jQuery('#tar_periodo_final_product_info4') .datepicker({ language: 'pt-BR', autoClose: true, dateFormat: 'dd/mm/yy', }); jQuery('#tar_periodo_product_info4').mask("00/00/0000"); jQuery('#tar_periodo_final_product_info4').mask("00/00/0000"); jQuery('#tar_periodo_product_info5') .datepicker({ language: 'pt-BR', minDate: new Date(), autoClose: true, dateFormat: 'dd/mm/yy', onSelect: function (selectedDate) { //Limpamos a segunda data, para evitar problemas do usuário ficar trocando a data do primeiro datepicker e acabar burlando as regras definidas. jQuery.datepicker._clearDate(jQuery("#tar_periodo_final_product_info5")); //Aqui está a "jogada" para somar os 7 dias para o próximo datepicker. var data = jQuery.datepicker.parseDate('dd/mm/yy', selectedDate); jQuery("#tar_periodo_final_product_info5").datepicker("option", "minDate", data); //Aplica a data } }); jQuery('#tar_periodo_final_product_info5') .datepicker({ language: 'pt-BR', autoClose: true, dateFormat: 'dd/mm/yy', }); jQuery('#tar_periodo_product_info5').mask("00/00/0000"); jQuery('#tar_periodo_final_product_info5').mask("00/00/0000"); jQuery('#tar_periodo_product_info6') .datepicker({ language: 'pt-BR', minDate: new Date(), autoClose: true, dateFormat: 'dd/mm/yy', onSelect: function (selectedDate) { //Limpamos a segunda data, para evitar problemas do usuário ficar trocando a data do primeiro datepicker e acabar burlando as regras definidas. jQuery.datepicker._clearDate(jQuery("#tar_periodo_final_product_info6")); //Aqui está a "jogada" para somar os 7 dias para o próximo datepicker. var data = jQuery.datepicker.parseDate('dd/mm/yy', selectedDate); jQuery("#tar_periodo_final_product_info6").datepicker("option", "minDate", data); //Aplica a data } }); jQuery('#tar_periodo_final_product_info6') .datepicker({ language: 'pt-BR', autoClose: true, dateFormat: 'dd/mm/yy', }); jQuery('#tar_periodo_product_info6').mask("00/00/0000"); jQuery('#tar_periodo_final_product_info6').mask("00/00/0000"); jQuery('#tar_periodo_product_info7') .datepicker({ language: 'pt-BR', minDate: new Date(), autoClose: true, dateFormat: 'dd/mm/yy', }); jQuery('#tar_periodo_final_product_info7') .datepicker({ language: 'pt-BR', autoClose: true, dateFormat: 'dd/mm/yy', }); jQuery('#tar_periodo_product_info7').mask("00/00/0000"); jQuery('#tar_periodo_final_product_info7').mask("00/00/0000"); }); function moeda(a, e, r, t) { let n = "" , h = j = 0 , u = tamanho2 = 0 , l = ajd2 = "" , o = window.Event ? t.which : t.keyCode; a.value = a.value.replace('R$ ',''); if (n = String.fromCharCode(o), -1 == "0123456789".indexOf(n)) return !1; for (u = a.value.replace('R$ ','').length, h = 0; h < u && ("0" == a.value.charAt(h) || a.value.charAt(h) == r); h++) ; for (l = ""; h < u; h++) -1 != "0123456789".indexOf(a.value.charAt(h)) && (l += a.value.charAt(h)); if (l += n, 0 == (u = l.length) && (a.value = ""), 1 == u && (a.value = "0" + r + "0" + l), 2 == u && (a.value = "0" + r + l), u > 2) { for (ajd2 = "", j = 0, h = u - 3; h >= 0; h--) 3 == j && (ajd2 += e, j = 0), ajd2 += l.charAt(h), j++; for (a.value = "", tamanho2 = ajd2.length, h = tamanho2 - 1; h >= 0; h--) a.value += ajd2.charAt(h); a.value += r + l.substr(u - 2, u) } return !1 } function toggle_input_valor_taxa(){ jQuery("#valor_taxas").toggle(1500); } function toggle_input_valor_taxa1(){ jQuery("#valor_taxas1").toggle(1500); } function toggle_input_valor_taxa2(){ jQuery("#valor_taxas2").toggle(1500); } function toggle_input_valor_taxa3(){ jQuery("#valor_taxas3").toggle(1500); } function toggle_input_valor_taxa4(){ jQuery("#valor_taxas4").toggle(1500); } function toggle_input_valor_taxa5(){ jQuery("#valor_taxas5").toggle(1500); } function toggle_input_valor_taxa6(){ jQuery("#valor_taxas6").toggle(1500); } function toggle_input_valor_taxa7(){ jQuery("#valor_taxas7").toggle(1500); }<file_sep><?php class Trend { private $WS; private $username = "xmlusrmonte"; private $password = "<PASSWORD>"; private $accessCode = "400111"; private $endPointManageToken= "http://soa.stg-1.trendoperadora.com.br/Security/v4_0/Resources/wsdl/TokenManager/CreateToken"; private $endPointProductSearch= "http://soa.stg-1.trendoperadora.com.br/soa/sales/productsearch/v4_0/ProductSearch"; private $endPointProductSearchDetail= "http://soa.stg-1.trendoperadora.com.br/soa/sales/productsearch/v4_0/ProductSearch/ProductDetail"; private $endPointProductSearchFilter = "http://soa.stg-1.trendoperadora.com.br/soa/sales/productsearch/v4_0/SearchFilter"; private $endPointBooking ="http://soa.stg-1.trendoperadora.com.br/soa/sales/booking/v4_0/Booking"; Public $request = ""; Public $response = ""; Public $erro; private $securityToken = ""; public $transactionToken= ""; private $currencyCode = ''; private $issuingName = ''; private $email = ''; private $issuerId = ''; private $userName = ''; private $domain = ''; private $agencyId = ''; public function _construct() { } public function WS() { $headers = array( "Content-type: application/json;charset=utf-8", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache", "SOAPAction: \'run\'", "Content-length: ".strlen($this->request) ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$this->endPoint); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 60); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $this->request); curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate'); $data = curl_exec($ch); if (curl_errno($ch)) { print "Error: " . curl_error($ch); return false; } else { curl_close($ch); $this->response = simplexml_load_string(self::limpa_response($data)); return true; } } public function manageToken() { $this->endPoint = $this->endPointManageToken; $this->request = self::preparaXMLManageToken(); if(self::WS()) { $this->securityToken = $this->response->Body->CreateTokenRS->TokenSecurity->Token; $this->agencyId = $this->response->Body->CreateTokenRS->TokenSecurity->TokenDetail->attributes()[0]; $this->domain = $this->response->Body->CreateTokenRS->TokenSecurity->TokenDetail->attributes()[1]; $this->userName = $this->response->Body->CreateTokenRS->TokenSecurity->TokenDetail->attributes()[2]; $this->issuerId = $this->response->Body->CreateTokenRS->TokenSecurity->TokenDetail->attributes()[3]; $this->email = $this->response->Body->CreateTokenRS->TokenSecurity->TokenDetail->attributes()[4]; $this->issuingName = $this->response->Body->CreateTokenRS->TokenSecurity->TokenDetail->attributes()[5]; $this->currencyCode = $this->response->Body->CreateTokenRS->TokenSecurity->TokenDetail->attributes()[6]; return true; } else { $this->erro = " - manageToken"; return false; } } public function productSearchFilterDestines() { $this->endPoint = $this->endPointProductSearchFilter; $this->request = self::preparaXMLProductSearchFilter(); if(self::WS()) { return true; } else { $this->erro = " - productSearchFilterDestines"; return false; } } public function productSearch($args) { $this->endPoint = $this->endPointProductSearch; $this->request = self::preparaXMLproductSearch($args); if(self::WS()) { $this->transactionToken = $this->response->Body->ProductSearchRS->ProductSearchResult->HotelResult->ListHotelGroup->HotelGroup->TransactionToken; return true; } else { $this->erro = " - productSearch"; return false; } } public function productDetail($args) { $this->endPoint = $this->endPointProductSearchDetail; $this->request = self::preparaXMLProductDetail($args); echo '<br>xxx2:productDetail REQUEST<br>'; var_dump($this->request); if(self::WS()) { return true; } else { $this->erro = " - productDetail"; return false; } } public function bookingRules($args) { $this->endPoint = $this->endPointBooking; $this->request = self::preparaXMLBookingRules($args); echo '<br>xxx2:bookingRules REQUEST<br>'; var_dump($this->request); if(self::WS()) { return true; } else { $this->erro = " - bookingRules"; return false; } } public function bookingCommit($args) { $this->endPoint = $this->endPointBooking; $this->request = self::preparaXMLBookingCommit($args); if(self::WS()) { return true; } else { $this->erro = " - bookingCommit"; return false; } } public function cancellation($args) { $this->endPoint = $this->endPointBooking; $this->request = self::preparaXMLCancellation($args); if(self::WS()) { return true; } else { $this->erro = " - cancellation"; return false; } } public function preparaXMLManageToken() { return '<?xml version="1.0"?><soapenv:Envelope xmlns:sec="http://www.trendoperadora.com.br/v4_0/Security" xmlns:ser="http://www.trendoperadora.com.br/v4_0/Services" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Header/><soapenv:Body><ser:CreateTokenRQ><sec:Login><sec:AccessCode>'.$this->accessCode.'</sec:AccessCode><sec:UserName>'.$this->username.'</sec:UserName><sec:Password Encrypted="false">'.$this->password.'</sec:Password></sec:Login><ser:TokenCreate UserName="'.$this->username.'"/></ser:CreateTokenRQ></soapenv:Body></soapenv:Envelope>'; } private function preparaXMLproductSearch($args) { $quartos = ''; $chds = ''; foreach ($args['quartos'] as $key => $value) { foreach ($value as $key2 => $value2) { if(is_array($value2)){ $chds = '<com:Guest Type="CHD" Quantity="'.count($value2).'">'; foreach ($value2 as $key3 => $value3) { $chds = $chds.'<com:Age value="'.$value3.'"/>'; } $chds = $chds.'</com:Guest>'; $quartos = str_replace('#_CHD', $chds, $quartos); }else{ $quartos = str_replace('#_CHD', '', $quartos); $quartos = $quartos.'<com:PaxGroupCandidate><com:Guest Type="ADT" Quantity="'.$value2.'"/>#_CHD</com:PaxGroupCandidate>'; } } $quartos = str_replace('#_CHD', '', $quartos); } return '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sec="http://www.trendoperadora.com.br/v4_0/Security" xmlns:ser="http://www.trendoperadora.com.br/v4_0/Services" xmlns:com="http://www.trendoperadora.com.br/v4_0/Common"> <soapenv:Header> <sec:Info> <sec:Pos Domain="'.$this->domain.'" RequestorId="'.$this->userName.'" Language = "pt-BR"/> <sec:Security> <sec:Token>'.$this->securityToken.'</sec:Token> </sec:Security> </sec:Info> </soapenv:Header> <soapenv:Body> <ser:ProductSearchRQ> <com:CommonParam SystemId="5" ClientId="'.$this->agencyId.'" AvailableOnly="true"/> <com:PaxCandidates>'.$quartos.' </com:PaxCandidates> <ser:SearchParams> <ser:ListHotelParam> <ser:HotelParam> <com:Destination Id="'.$args['destination'].'"/> <com:DateRange> <com:Checkin>'.$args['checkin'].'</com:Checkin> <com:Checkout>'.$args['checkout'].'</com:Checkout> </com:DateRange> </ser:HotelParam> </ser:ListHotelParam> </ser:SearchParams> </ser:ProductSearchRQ> </soapenv:Body> </soapenv:Envelope>'; } public function preparaXMLProductDetail($args) { $productTokens = ''; foreach ($args['productTokens'] as $key => $value) { $productTokens = $productTokens.'<com:ProductToken>'.$value['productToken'].'</com:ProductToken>'; } return '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sec="http://www.trendoperadora.com.br/v4_0/Security" xmlns:ser="http://www.trendoperadora.com.br/v4_0/Services" xmlns:com="http://www.trendoperadora.com.br/v4_0/Common"> <soapenv:Header> <sec:Info> <sec:Pos Domain="'.$this->domain.'" Language="pt-BR" RequestorId="'.$this->userName.'"/> <sec:Security> <sec:Token>'.$this->securityToken.'</sec:Token> </sec:Security> </sec:Info> </soapenv:Header> <soapenv:Body> <ser:ProductDetailRQ> <ser:HotelParam> '.$productTokens.' </ser:HotelParam> </ser:ProductDetailRQ> </soapenv:Body> </soapenv:Envelope>'; } public function preparaXMLBookingRules($args) { $productTokens = ''; foreach ($args['productTokens'] as $key => $value) { $productTokens = $productTokens.'<com:ProductToken>'.$value['productToken'].'</com:ProductToken>'; } return '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sec="http://www.trendoperadora.com.br/v4_0/Security" xmlns:ser="http://www.trendoperadora.com.br/v4_0/Services" xmlns:hot="http://www.trendoperadora.com.br/v4_0/Hotel" xmlns:com="http://www.trendoperadora.com.br/v4_0/Common"> <soapenv:Header> <sec:Info> <sec:Pos Domain="'.$this->domain.'" RequestorId="'.$this->userName.'" Language="pt-BR"/> <sec:Security> <sec:Token>'.$this->securityToken.'</sec:Token> </sec:Security> </sec:Info> </soapenv:Header> <soapenv:Body> <ser:BookingRulesRQ> <ser:ProductParams> <hot:ListHotelParam> <hot:HotelParam> <com:TransactionToken>'. $args['transactionToken'].' </com:TransactionToken> <com:ListProductToken> '.$productTokens.' </com:ListProductToken> </hot:HotelParam> </hot:ListHotelParam> </ser:ProductParams> </ser:BookingRulesRQ> </soapenv:Body> </soapenv:Envelope>'; } public function preparaXMLBookingCommit($args) { $rph = 1; $listPaxBooking = ''; $listHotelBooking = ''; foreach ($args['quartos'] as $key => $value) { $listPaxRPH = ''; $paxRPH = ''; foreach ($value as $key2 => $value2) { if($key2 == 'pax') { foreach ($value2 as $key3 => $value3) { $listPaxBooking .= '<book:PaxBooking RPH="'.$rph.'"> <com:Pax Id="'.$rph.'" FirstName="'.$value3['firstName'].'" LastName="'.$value3['lastName'].'" Type="'.$value3['type'].'"/> </book:PaxBooking>'; $paxRPH = $paxRPH.' <com:PaxRPH RPH="'.$rph.'"/>'; $rph++; } $listHotelBooking = str_replace('#_PAXRPH', $paxRPH, $listHotelBooking); }else if($key2 == 'productToken'){ $listHotelBooking.= '<book:HotelBooking> <hot:RoomParam> <com:TransactionToken>'.$this->transactionToken.'</com:TransactionToken> <com:ProductToken>'.$value2.'</com:ProductToken> </hot:RoomParam> <com:ListPaxRPH> #_PAXRPH </com:ListPaxRPH> </book:HotelBooking>'; } } } return '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sec="http://www.trendoperadora.com.br/v4_0/Security" xmlns:ser="http://www.trendoperadora.com.br/v4_0/Services" xmlns:hot="http://www.trendoperadora.com.br/v4_0/Hotel" xmlns:com="http://www.trendoperadora.com.br/v4_0/Common" xmlns:book="http://www.trendoperadora.com.br/v4_0/Booking"> <soapenv:Header> <sec:Info> <sec:Pos Domain="'.$this->domain.'" Language = "pt-BR" Currency="'.$this->currencyCode.'" RequestorId="'.$this->userName.'" IssuingId="'.$this->issuerId.'"/> <sec:Security> <sec:Token>'.$this->securityToken.'</sec:Token> </sec:Security> </sec:Info> </soapenv:Header> <soapenv:Body> <ser:BookingCommitRQ> <ser:BookingRQ> <book:ListPaxBooking> '.$listPaxBooking.' </book:ListPaxBooking> <ser:ListHotelBookingDetail> <book:HotelBookingDetail> <book:BookingDetailSimple Type="NOR"/> <book:ListBookingDetailObservation/> <book:ListHotelBooking>' .$listHotelBooking.' </book:ListHotelBooking> </book:HotelBookingDetail> </ser:ListHotelBookingDetail><ser:BookingParam IgnoreDuplicity="true" PaymentId="'.$args['paymentId'].'" OfflineBooking="'.$args['offlineBooking'].'"/> <ser:Issuing Id="'.$this->issuerId.'"/> </ser:BookingRQ> <ser:CommitRQ> <com:TransactionToken>'.$this->transactionToken.'</com:TransactionToken> <ser:Commit Id="'.$this->issuerId.'" CustomerId="'.$this->agencyId.'" CurrencyTotalSales="'.$args['currencyTotalSales'].'"/> <ser:Contractors> <ser:ContractorCommit> <ser:Payments> <ser:Payment> <ser:PaymentCommit Id="'.$args['paymentId'].'"/> <ser:PaymentPlan Id="'.$args['paymentId'].'" TotalPrice="'.$args['currencyTotalSales'].'"/> </ser:Payment> </ser:Payments> </ser:ContractorCommit> </ser:Contractors> </ser:CommitRQ> </ser:BookingCommitRQ> </soapenv:Body> </soapenv:Envelope>'; } public function preparaXMLCancellation($args) { $bookingDetailIds = ''; foreach ($args['bookingDetailIds'] as $key => $value) { $bookingDetailIds = $bookingDetailIds.'<ser:Detail BookingDetailId="'.$value['bookingDetailId'].'"/>'; } return '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sec="http://www.trendoperadora.com.br/v4_0/Security" xmlns:ser="http://www.trendoperadora.com.br/v4_0/Services" xmlns:book="http://www.trendoperadora.com.br/v4_0/Booking" xmlns:com="http://www.trendoperadora.com.br/v4_0/Common"> <soapenv:Header> <sec:Info> <sec:Pos Domain="'.$this->domain.'" RequestorId="'.$this->userName.'"/> <sec:Security> <sec:Token>'.$this->securityToken.'</sec:Token> </sec:Security> </sec:Info> </soapenv:Header> <soapenv:Body> <ser:CancellationRQ> <ser:Cancellation> <ser:MasterBookingId>'.$args['masterBookingId'].'</ser:MasterBookingId> <ser:Reason>'.$args['reason'].'</ser:Reason> <ser:ListDetail> '.$bookingDetailIds.' </ser:ListDetail> </ser:Cancellation> </ser:CancellationRQ> </soapenv:Body> </soapenv:Envelope>'; } public function preparaXMLProductSearchFilter() { return '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sec="http://www.trendoperadora.com.br/v4_0/Security" xmlns:ser="http://www.trendoperadora.com.br/v4_0/Services"> <soapenv:Header> <sec:Info> <sec:Pos Domain="'.$this->domain.'" Language="pt-BR" Currency="'.$this->currencyCode.'" RequestorId="'.$this->userName.'" IssuingId="'.$this->issuerId.'"/> <sec:Security> <sec:Token>'.$this->securityToken.'</sec:Token> </sec:Security> </sec:Info> </soapenv:Header> <soapenv:Body> <ser:DestinationListRequest/> </soapenv:Body> </soapenv:Envelope>'; } private function limpa_response($data) { $data = str_replace("<s:","<",$data); $data = str_replace("</s:","</",$data); $data = str_replace("<env:","<",$data); $data = str_replace("</env:","</",$data); $data = str_replace("<wsa:","<",$data); $data = str_replace("</wsa:","</",$data); $data = str_replace("<instra:","<",$data); $data = str_replace("</instra:","</",$data); $data = str_replace("<svc:","<",$data); $data = str_replace("</svc:","</",$data); $data = str_replace("<ns2:","<",$data); $data = str_replace("</ns2:","</",$data); $data = str_replace("<ns4:","<",$data); $data = str_replace("</ns4:","</",$data); $data = str_replace("<ns5:","<",$data); $data = str_replace("</ns5:","</",$data); $data = str_replace("<ns6:","<",$data); $data = str_replace("</ns6:","</",$data); $data = str_replace("<ns7:","<",$data); $data = str_replace("</ns7:","</",$data); $data = str_replace("<ns8:","<",$data); $data = str_replace("</ns8:","</",$data); $data = str_replace("<ns9:","<",$data); $data = str_replace("</ns9:","</",$data); $data = str_replace("<ns11:","<",$data); $data = str_replace("</ns11:","</",$data); $data = str_replace("<ns12:","<",$data); $data = str_replace("</ns12:","</",$data); $data = str_replace("<ns13:","<",$data); $data = str_replace("</ns13:","</",$data); $data = str_replace("<ns16:","<",$data); $data = str_replace("</ns16:","</",$data); $data = str_replace("<com:","<",$data); $data = str_replace("</com:","</",$data); $data = str_replace("<ser:","<",$data); $data = str_replace("</ser:","</",$data); $data = str_replace("<soapenv:","<",$data); $data = str_replace("</soapenv:","</",$data); return $data; } }<file_sep><?php get_header(); $dados = explode("/", $_SERVER['REQUEST_URI']); $categoria = $dados[1]; $slug = $dados[2]; $descricao_slug = ucwords(str_replace("-", " ", $dados[2])); if (!empty($dados[3])) { $descricao_slug = ucwords(str_replace("-", " ", $dados[2])).' — '.ucwords(str_replace("-", " ", $dados[3])); $slug = $dados[3]; } $cat_terms = get_terms( array('categoria_apto'), array( 'hide_empty' => false, 'orderby' => 'name', 'order' => 'ASC', 'number' => 6 //specify yours ) ); $args = array( 'post_type' => 'ttbooking', 'posts_per_page' => 10, //specify yours 'post_status' => 'publish', 'tax_query' => array( array( 'taxonomy' => $categoria, 'field' => 'slug', 'terms' => $slug, ), ), 'ignore_sticky_posts' => true //caller_get_posts is deprecated since 3.1 ); $_posts = new WP_Query( $args ); ?> <!-- Blog Section with Sidebar --> <style type="text/css"> .page-builder { margin: 0px; padding: 0; } .attachment-post-thumbnail{ display: block; max-width: 100%; height: 250px;} </style> <div class="page-builder"> <div class="page-title-section" style="display: block !important;"> <div class="overlay"> <div class="container"> <div class="row"> <div class="col-md-6"> <div class="page-title"> <h1><?= $descricao_slug; ?></h1> </div> </div> <div class="col-md-6"> <ul class="page-breadcrumb"> <li><a href="https://wp02.montenegroev.com.br">Início</a> &nbsp; / &nbsp;</li><li class="active"><?= $descricao_slug; ?></li> </ul> </div> </div> </div> </div> </div> <div class="container"> <div class="row"> <br><br> <?php if( $_posts->have_posts() ) : while( $_posts->have_posts() ) : $_posts->the_post(); ?> <div class="col-lg-4 col-12"> <div class="panel panel-default"> <div class="panel-body" style="padding: 0"> <?=the_post_thumbnail();?> <br> <h3 style="padding: 0px 15px"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> <div style="height: 250px;padding: 0px 15px"><?php the_excerpt( __( 'Read More' , 'appointment' ) ); ?></div> </div> <div class="panel-footer"> <a href="<?php the_permalink(); ?>" class="more-link">Veja mais »</a> </div> </div> </div> <?php endwhile; endif; wp_reset_postdata(); //important ?> </div> </div> <br><br> </div> <!-- /Blog Section with Sidebar --> <?php get_footer(); ?><file_sep><?php session_start(); unset($_SESSION['teste']); $_SESSION['teste'] = '<span style="font-weight: 500"> Período: '.$_POST['start'].' a '.$_POST['end'].'</span>'; $_SESSION['datas'] = $_POST['start'].' - '.$_POST['end']; echo $_SESSION['teste']; session_write_close(); ?><file_sep>jQuery(window).on("load", function () { atualiza_cadastro(); }); function atualiza_cadastro() { var email = jQuery("#email").val(); var token = jQuery("#token").val(); if (email == "") { swal({ title: "Acesso não permitido.", text: "Você será redirecionado para a página inicial.", type: "warning", }).then((value) => { window.location.href = "/"; }); } else { var token = jQuery("#token").val(); var settings = { async: true, crossDomain: true, url: "https://api.traveltec.com.br/serv/marketing/atualiza_cadastro", method: "POST", headers: { token: token, email: email, "cache-control": "no-cache", }, }; jQuery.ajax(settings).done(function (response) { jQuery("#loader").attr("style", "display:none"); jQuery("#message").attr("style", "display:block"); setTimeout(function () { window.location = "/"; }, 6000); }); } } <file_sep><?php class TTBookingIntegracaoAdmin extends TTBookingIntegracao { /** * Setup backend functionality in WordPress * * @return none * @since 0.1 */ function __construct() { TTBookingIntegracao::__construct(); // Load localizations if available load_plugin_textdomain( 'config_ttbookingintegracao' , false , 'config_ttbookingintegracao/languages' ); // Activation hook register_activation_hook( $this->plugin_file, array( &$this, 'init' ) ); // Hook into admin_init and register settings and potentially register an admin_notice add_action( 'admin_init', array( &$this, 'admin_init' ) ); // Activate the options page add_filter( 'admin_menu', array( &$this , 'books_register_ref_page' ) ); // Register an AJAX action for testing mail sending capabilities add_action( 'wp_ajax_config_ttbookingintegracao-test', array( &$this, 'ajax_send_test' ) ); } /** * Initialize the default options during plugin activation * * @return none * @since 0.1 */ function init() { $defaults = array( 'chechbox_preco' => '', 'codigo_trend_n' => '', 'usuario_trend_n' => '', 'senha_trend_n' => '', 'hotel_trend_nh0' => '', 'hotel_trend_nh1' => '', 'hotel_trend_nh2' => '', 'hotel_trend_nh3' => '', 'hotel_trend_nh4' => '', 'hotel_trend_nh5' => '', 'hotel_trend_nh6' => '', 'hotel_trend_nh7' => '', 'hotel_trend_nh8' => '', 'hotel_trend_nh9' => '', 'hotel_trend_nh10' => '', 'hotel_trend_nh11' => '', 'hotel_trend_nh12' => '', 'hotel_trend_nh13' => '', 'hotel_trend_nh14' => '', 'hotel_trend_nh15' => '', 'hotel_trend_nh16' => '', 'hotel_trend_nh17' => '', 'hotel_trend_nh18' => '', 'hotel_trend_nh19' => '', 'hotel_trend_nh20' => '', 'id_hotel_trend_nh0' => '', 'id_hotel_trend_nh1' => '', 'id_hotel_trend_nh2' => '', 'id_hotel_trend_nh3' => '', 'id_hotel_trend_nh4' => '', 'id_hotel_trend_nh5' => '', 'id_hotel_trend_nh6' => '', 'id_hotel_trend_nh7' => '', 'id_hotel_trend_nh8' => '', 'id_hotel_trend_nh9' => '', 'id_hotel_trend_nh10' => '', 'id_hotel_trend_nh11' => '', 'id_hotel_trend_nh12' => '', 'id_hotel_trend_nh13' => '', 'id_hotel_trend_nh14' => '', 'id_hotel_trend_nh15' => '', 'id_hotel_trend_nh16' => '', 'id_hotel_trend_nh17' => '', 'id_hotel_trend_nh18' => '', 'id_hotel_trend_nh19' => '', 'id_hotel_trend_nh20' => '', 'destination_hotel_trend_nh0' => '', 'destination_hotel_trend_nh1' => '', 'destination_hotel_trend_nh2' => '', 'destination_hotel_trend_nh3' => '', 'destination_hotel_trend_nh4' => '', 'destination_hotel_trend_nh5' => '', 'destination_hotel_trend_nh6' => '', 'destination_hotel_trend_nh7' => '', 'destination_hotel_trend_nh8' => '', 'destination_hotel_trend_nh9' => '', 'destination_hotel_trend_nh10' => '', 'destination_hotel_trend_nh11' => '', 'destination_hotel_trend_nh12' => '', 'destination_hotel_trend_nh13' => '', 'destination_hotel_trend_nh14' => '', 'destination_hotel_trend_nh15' => '', 'destination_hotel_trend_nh16' => '', 'destination_hotel_trend_nh17' => '', 'destination_hotel_trend_nh18' => '', 'destination_hotel_trend_nh19' => '', 'destination_hotel_trend_nh20' => '', 'codigo_hotel_trend_n' => '', 'usuario_ehtl' => '', 'senha_ehtl' => '', 'texto_motor0' => '', 'texto_motor1' => '', 'texto_motor2' => '', 'texto_motor3' => '', 'texto_motor4' => '', 'texto_motor5' => '', 'texto_motor6' => '', 'texto_motor7' => '', 'texto_motor8' => '', 'texto_motor9' => '', 'chechbox_motor0' => '', 'chechbox_motor1' => '', 'chechbox_motor2' => '', 'chechbox_motor3' => '', 'chechbox_motor4' => '', 'chechbox_motor5' => '', 'chechbox_motor6' => '', 'chechbox_motor7' => '', 'chechbox_motor8' => '', 'chechbox_motor9' => '', ); add_option( 'config_ttbookingintegracao', $defaults ); } /** * Add the options page * * @return none * @since 0.1 */ public function TESTE() { require plugin_dir_path(dirname(__FILE__)) . 'includes/backend/submenu/configuracao.php'; } function books_register_ref_page() { add_submenu_page('edit.php?post_type=integracaohoteis', 'WP Travel Engine Admin Settings', 'Configurações', 'manage_options', 'config_ttbookingintegracao', array($this, 'TESTE')); } /** * Enqueue javascript required for the admin settings page * * @return none * @since 0.1 */ function admin_js() { wp_enqueue_script( 'jquery' ); } /** * Output JS to footer for enhanced admin page functionality * * @since 0.1 */ function admin_footer_js() { ?> <script type="text/javascript"> /* <![CDATA[ */ var formModified = false; jQuery().ready(function() { jQuery('#config_ttbookingintegracao-test').click(function(e) { e.preventDefault(); if ( formModified ) { var doTest = confirm('<?php _e( 'The SmtpLocaweb plugin configuration has changed since you last saved. Do you wish to test anyway?\n\nClick "Cancel" and then "Save Changes" if you wish to save your changes.', 'config_ttbookingintegracao'); ?>'); if ( ! doTest ) { return false; } } jQuery(this).val('<?php _e( 'Testing...', 'config_ttbookingintegracao' ); ?>'); jQuery("#config_ttbookingintegracao-test-result").text(''); jQuery.get( ajaxurl, { action: 'config_ttbookingintegracao-test', _wpnonce: '<?php echo wp_create_nonce(); ?>' } ) .complete(function() { jQuery("#config_ttbookingintegracao-test").val('<?php _e( 'Test Configuration', 'config_ttbookingintegracao' ); ?>'); }) .success(function(data) { alert('SmtpLocaweb ' + data.method + ' Test ' + data.message); }) .error(function() { alert('SmtpLocaweb Test <?php _e( 'Failure', 'config_ttbookingintegracao' ); ?>'); }); }); jQuery("#config_ttbookingintegracao-form").change(function() { formModified = true; }); }); /* ]]> */ </script> <?php } /** * Output the options page * * @return none * @since 0.1 */ function options_page() { if ( ! @include( 'options-page.php' ) ) { printf( __( '<div id="message" class="updated fade"><p>The options page for the <strong>SmtpLocaweb</strong>'. 'plugin cannot be displayed. The file <strong>%s</strong> is missing. Please reinstall the plugin.'. '</p></div>', 'config_ttbookingintegracao'), dirname( __FILE__ ) . '/options-page.php' ); } } /** * Wrapper function hooked into admin_init to register settings * and potentially register an admin notice if the plugin hasn't * been configured yet * * @return none * @since 0.1 */ function admin_init() { $this->register_settings(); } /** * Whitelist the config_ttbookingintegracao options * * @since 0.1 * @return none */ function register_settings() { register_setting( 'config_ttbookingintegracao', 'config_ttbookingintegracao', array( &$this, 'validation' ) ); } /** * Data validation callback function for options * * @param array $options An array of options posted from the options page * @return array * @since 0.1 */ function validation( $options ) { $id_conta = trim( $options['id_conta'] ); if ( ! empty( $id_conta ) ) { $id_conta = preg_replace( '/@.+$/', '', $id_conta ); $options['id_conta'] = $id_conta; } foreach ( $options as $key => $value ) $options[$key] = trim( $value ); $this->options = $options; return $options; } /** * Function to output an admin notice when the plugin has not * been configured yet * * @return none * @since 0.1 */ function admin_notices() { $screen = get_current_screen(); if ( $screen->id == $this->hook_suffix ) return; ?> <div id='config_ttbookingintegracao-warning' class='updated fade'><p><strong><?php _e( 'SmtpLocaweb is almost ready. ', 'config_ttbookingintegracao' ); ?></strong><?php printf( __( 'You must <a href="%1$s">configure SmtpLocaweb</a> for it to work.', 'config_ttbookingintegracao' ), menu_page_url( 'config_ttbookingintegracao' , false ) ); ?></p></div> <?php } /** * Add a settings link to the plugin actions * * @param array $links Array of the plugin action links * @return array * @since 0.1 */ function filter_plugin_actions( $links ) { $settings_link = '<a href="' . menu_page_url( 'config_ttbookingintegracao', false ) . '">' . __( 'Settings', 'config_ttbookingintegracao' ) . '</a>'; array_unshift( $links, $settings_link ); return $links; } /** * AJAX callback function to test mail sending functionality * * @return string * @since 0.1 */ function ajax_send_test() { nocache_headers(); header( 'Content-Type: application/json' ); if ( ! current_user_can( 'manage_options' ) || ! wp_verify_nonce( $_GET[ '_wpnonce' ] ) ) { die( json_encode( array( 'message' => __( 'Unauthorized', 'config_ttbookingintegracao' ), 'method' => null ) ) ); } $secure = ( defined( 'config_ttbookingintegracao_SECURE' ) && config_ttbookingintegracao_SECURE ) ? config_ttbookingintegracao_SECURE : $this->get_option( 'secure' ); $method = ( (bool) $secure ) ? __( 'Secure SMTP', 'config_ttbookingintegracao' ) : __( 'SMTP', 'config_ttbookingintegracao' ); $admin_email = get_option( 'admin_email' ); ob_start(); $GLOBALS['smtp_debug'] = true; $result = wp_mail( $admin_email, __( 'SmtpLocaweb WordPress Plugin Test', 'config_ttbookingintegracao' ), sprintf( __( "This is a test email generated by the SmtpLocaweb WordPress plugin.\n\nIf you have received this message, the requested test has succeeded.\n\nThe method used to send this email was: %s.", 'config_ttbookingintegracao' ), $method ) ); $GLOBALS['phpmailer']->smtpClose(); $output = ob_get_clean(); if ( $result ) { die( json_encode( array( 'message' => __( 'Success', 'config_ttbookingintegracao' ), 'method' => $method ) ) ); } else { die( json_encode( array( 'message' => __( 'Failure', 'config_ttbookingintegracao' ) .", debug: ". $output, 'method' => $method ) ) ); } } } <file_sep><?php get_header(); $dados = explode("/", $_SERVER['REQUEST_URI']); $categoria = $dados[1]; $slug = $dados[2]; $descricao_slug = ucwords(str_replace("-", " ", $dados[2])); if (!empty($dados[3])) { $descricao_slug = ucwords(str_replace("-", " ", $dados[2])).' — '.ucwords(str_replace("-", " ", $dados[3])); $slug = $dados[3]; } $the_slug = $slug; $args = array( 'name' => $the_slug, 'post_type' => 'ttbooking', 'post_status' => 'publish', 'numberposts' => 1 ); $my_posts = get_posts($args); $title = $my_posts[0]->post_title; $description = $my_posts[0]->post_content; $id = $my_posts[0]->ID; $thumb_id = get_post_thumbnail_id(); $thumb_url = wp_get_attachment_image_src($thumb_id,'thumbnail-size', true); $url = $thumb_url[0]; $localizacao = ''; $cat_terms = get_terms( array('localizacao'), array( 'hide_empty' => false, 'orderby' => 'name', 'order' => 'ASC', 'number' => 6 //specify yours ) ); if( $cat_terms ){ foreach( $cat_terms as $term ) { $args = array( 'post_type' => 'ttbooking', 'posts_per_page' => 10, //specify yours 'post_status' => 'publish', 'tax_query' => array( array( 'taxonomy' => 'localizacao', 'field' => 'slug', 'terms' => $term->slug, ), ), 'ignore_sticky_posts' => true //caller_get_posts is deprecated since 3.1 ); $_posts = new WP_Query( $args ); if( $_posts->have_posts() ) : while( $_posts->have_posts() ) : $_posts->the_post(); $post = get_post(); if ($post->ID == $id) { $localizacao .= '<i class="fa fa-map"></i> <span style="margin-right:8px;">'.$term->name.'</span>'; } ?> <?php endwhile; endif; wp_reset_postdata(); //important } } /************************************************************************/ $servicos = ''; $cat_terms = get_terms( array('servicos'), array( 'hide_empty' => false, 'orderby' => 'name', 'order' => 'ASC', 'number' => 6 //specify yours ) ); if( $cat_terms ){ foreach( $cat_terms as $term ) { $args = array( 'post_type' => 'ttbooking', 'posts_per_page' => 10, //specify yours 'post_status' => 'publish', 'tax_query' => array( array( 'taxonomy' => 'servicos', 'field' => 'slug', 'terms' => $term->slug, ), ), 'ignore_sticky_posts' => true //caller_get_posts is deprecated since 3.1 ); $_posts = new WP_Query( $args ); if( $_posts->have_posts() ) : while( $_posts->have_posts() ) : $_posts->the_post(); $post = get_post(); if ($post->ID == $id) { $servicos .= '<i class="fa fa-info" style="font-size: 13px;"></i> <span style="margin-right:8px;margin-left: 6px;margin-top: -4px;font-size: 13px;">'.$term->name.'</span><br>'; } ?> <?php endwhile; endif; wp_reset_postdata(); //important } } $query_args = array( 'post_type' => 'product', 'meta_query' => array( array( 'key' => 'est_product_info', 'value' => $title, ), ) ); $query = new WP_Query( $query_args ); $apartamentos = []; if ( $query->posts ) { foreach ( $query->posts as $key => $post_id ) { $nome_apartamento = $post_id->post_title; $id_produto = $post_id->ID; $meta_acomodacao = get_post_meta( $id_produto, 'demo_product_info', true ); $meta_pessoas_acomodacao = get_post_meta( $id_produto, 'pessoas_demo_product_info', true ); if ($meta_pessoas_acomodacao == 1) { $tipo = 'Single'; }else if ($meta_pessoas_acomodacao == 2) { $tipo = 'Duplo'; }else if ($meta_pessoas_acomodacao == 3) { $tipo = 'Triplo'; } $meta_valor_inicial_acomodacao = get_post_meta( $id_produto, 'tar_valor_final_product_info', true ); $apartamentos[] = array("nome" => $nome_apartamento, "acomodacao" => $meta_acomodacao, "tipo" => $tipo, "pax" => $meta_pessoas_acomodacao, "valor" => $meta_valor_inicial_acomodacao, "id_produto" => $id_produto); } } ?> <!-- Blog Section with Sidebar --> <style type="text/css"> .page-builder { margin: 0px; padding: 0; } .attachment-post-thumbnail{ display: block; max-width: 100%; height: 250px;} </style> <div class="page-builder"> <div class="page-title-section" style="display: block !important;"> <div class="overlay"> <div class="container-fluid"> <div class="row"> <div class="col-md-1 col-lg-1"></div> <div class="col-md-5 col-lg-5"> <div class="page-title"> <h1><?= $descricao_slug; ?></h1> </div> </div> <div class="col-md-5 col-lg-5"> <ul class="page-breadcrumb"> <li><a href="https://wp02.montenegroev.com.br">Início</a> &nbsp; / &nbsp;</li> <li class="active"><?= $descricao_slug; ?></li> </ul> </div> <div class="col-md-1 col-lg-1"></div> </div> </div> </div> </div> <link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet"> <style type="text/css"> .input-group{ position: relative; display: -webkit-box; display: -ms-flexbox; display: flex; -ms-flex-wrap: wrap; flex-wrap: wrap; -webkit-box-align: stretch; -ms-flex-align: stretch; align-items: stretch; width: 100%; } .input-group-prepend { margin-right: -1px; } .input-group-append, .input-group-prepend { display: -webkit-box; display: -ms-flexbox; display: flex; } .input-group-text { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-align: center; -ms-flex-align: center; align-items: center; padding: .375rem .75rem; margin-bottom: 0; font-size: 1rem; font-weight: 400; line-height: 1.5; color: #495057; text-align: center; white-space: nowrap; background-color: #e9ecef; border: 1px solid #ced4da; border-radius: .25rem; } .input-group>.custom-file, .input-group>.custom-select, .input-group>.form-control { position: relative; -webkit-box-flex: 1; -ms-flex: 1 1 auto; flex: 1 1 auto; width: 1%; margin-bottom: 0; } @media(max-width: 800px){ .navbar-brand img{ height: 42px } .img-div-responsive{ padding: 0 0px 9px 0px !important; } .exibirComputador{ display: none !important; } .exibirCelular{ display: block !important; } .titulo{ font-size: 1.5rem !important; font-weight: 700 !important; } .subtitulo{ font-size: 1.0rem !important; } .carousel{ margin: 10px !important } .filtro{ padding-right: 15px !important } .hotel{ padding: 14px } .centeri{ text-align: center; } .borderC{ border: 1px solid #ddd; margin: 0px 17px 0px 14px; height: auto !important; } } .exibirComputador{ visibility: initial; } .exibirCelular{ display: none; } .titulo{ font-size: 2.8rem;font-weight: 400; } .subtitulo{ font-size: 1.4rem;font-weight: 400 } .font{ font-family: 'Raleway', sans-serif !important; } .nofont{ font-family: 'Arial', sans-serif !important; } .carousel{ margin-left: 10px;margin-right: -12px;margin-top: 10px; } .btn-primary{ background-color: #2f4050 !important; border-color: #2f4050 !important; } .btn-primary:hover{ background-color: #fff !important; border-color: #2f4050 !important; color: #2f4050 !important; } .filtro{ padding-right: 0 } .infoBox { background-color: #FFF; width: 300px; font-size: 14px; border: 1px solid #3fa7d8; border-radius: 3px; margin-top: 10px } .infoBox p { padding: 6px } .infoBox:before { border-left: 10px solid transparent; border-right: 10px solid transparent; border-bottom: 10px solid #3fa7d8; top: -10px; content: ""; height: 0; position: absolute; width: 0; left: 138px } html { position: relative; min-height: 100%; } body { /* Margin bottom by footer height */ margin-bottom: 60px; } .footer { position: absolute; bottom: 0; width: 100%; /* Set the fixed height of the footer here */ height: 50px; line-height: 46px; /* Vertically center the text there */ background-color: #585858; border-top: 4px solid;border-color: #999; } .text-muted{ color: #999999 !important;font-size:16px; } .esconde{ display: none; } .exibe{ display: block; } @media(max-width: 959px){ .imgHotel{ width: 93%; } } @media(min-width: 960px) and (max-width: 961px){ .imgHotel{ width: 97%; } } @media(min-width: 411px) and (max-width: 559px){ .footer { text-align: center !important; line-height: 20px; } .text-muted{ text-align: center !important; } .exibeCelular{ bottom: auto !important; } } @media(max-width: 400px){ .footer { text-align: center !important; line-height: 20px; } .text-muted{ text-align: center !important; } .exibeCelular{ bottom: auto !important; } } @media(min-width: 600px){ .text-muted{ float: right; } .exibirComputador{ display: block !important; } } .navbar-light .navbar-nav .nav-link { color: rgba(0,0,0,.5) !important; } #google_translate_element { display: none; } .goog-te-banner-frame { display: none !important; } .exibirComputador{ display: none; } .tooltip.show { opacity: .9; z-index: 0; margin-left: 5px; } .qty .count, .qty .count_child, .qty .count_quartos { color: #000; display: inline-block; vertical-align: top; font-size: 22px; font-weight: 700; line-height: 30px; padding: 0 2px ;min-width: 35px; text-align: center; margin-top: -11px; } .qty .plus, .qty .plus_child, .qty .plus_quartos { cursor: pointer; display: inline-block; vertical-align: top; color: white; width: 26px; height: 26px; font: 25px/1 Arial,sans-serif; text-align: center; border-radius: 50%; } .qty .minus, .qty .minus_child, .qty .minus_quartos { cursor: pointer; display: inline-block; vertical-align: top; color: white; width: 26px; height: 26px; font: 25px/1 Arial,sans-serif; text-align: center; border-radius: 50%; background-clip: padding-box; } .minus, .minus_child, .minus_quartos{ background-color: #aaa !important; } .plus, .plus_child, .plus_quartos{ background-color: #aaa !important; } .minus:hover, .minus_child:hover, .minus_quartos:hover{ background-color: #e8b90d !important; } .plus:hover, .plus_child:hover, .plus_quartos:hover{ background-color: #e8b90d !important; } /*Prevent text selection*/ span{ -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; } .input_number{ border: 0; width: 2%; } nput::-webkit-outer-spin-button, input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } input:disabled{ background-color:white; } .xpi__content__wrappergray { background: #f5f5f5; } .xpi__content__wrapper { background: #002f72; margin-bottom: 24px; border-bottom: 1px solid #e6e6e6; } .xpi__searchbox { padding: 44px 5px; position: relative; } .xpi__searchbox { max-width: 1110px; padding: 40px 5px 16px; margin: 0 auto; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .xpi__content__wrappergray .xpi__searchbox .sb-searchbox__title, .xpi__content__wrappergray .xpi__searchbox .sb-searchbox__subtitle-text { color: #333; } .xpi__searchbox .sb-searchbox__title { font-size: 24px; line-height: 32px; font-weight: 600; font-weight: 600; } .sb-searchbox__title { margin: 0; padding: 0; font-size: 26px; font-weight: normal; } .xpi__content__wrappergray .xpi__searchbox .sb-searchbox__title, .xpi__content__wrappergray .xpi__searchbox .sb-searchbox__subtitle-text { color: #333; } .xpi__searchbox .sb-searchbox__title { font-size: 24px; line-height: 32px; font-weight: 600; font-weight: 600; } .xpi__searchbox .sb-searchbox__subtitle-text { font-size: 14px; line-height: 20px; font-weight: 400; } .sb-searchbox--painted { font-size: 14px; line-height: 20px; font-weight: 400; background: 0; border-radius: 0; border: 0; padding: 0; } .xp__fieldset { color: #333; border: 0; display: table; background-color: #febb02; padding: 4px; border-radius: 4px; margin: 24px 0 16px; position: relative; width: 100%; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } @media(max-width: 320px){ .marginGallery{ margin: 0px 9px 0px -4px !important; } .imgWidth{ width: 160% !important; } .tituloHotel{ font-size: 1.5rem !important; margin-top: 16px!important; } .paddingRow{ padding: 0 15px 0 15px !important; } .fontSizeP{ font-size: 14px !important; } .fontSizePreco{ font-size: .805rem !important; } .paddingCelular{ padding-left: 4px !important;; } .colNomeCelular { margin: 0 -7px 0 -14px !important; } .col1Celular{ margin: 0 -9px 0 -14px !important; } .col2Celular{ margin: 0 9px 0 4px !important; } .borderCelular{ border-right: none !important; } } @media (min-width: 350px) and (max-width: 414px){ .imgWidth{ width: 130% !important; } .marginGallery { margin: 0px 8px 0px -4px !important; } .tituloHotel{ font-size: 1.5rem !important; margin-top: 16px!important; } .paddingRow{ padding: 0 15px 0 15px !important; } .fontSizeP{ font-size: .805rem !important; } .fontSizePreco{ font-size: .805rem !important; } .paddingCelular{ padding-left: 8px !important; } .colNomeCelular{ margin: 0 -4px 0 -5px !important; } } @media(min-width: 1650px){ .imgHotel{ width: 100% !important; height: 252px !important; } .imgWidth{ width: 130% !important; } } .marginGallery{ margin: 0px -3px 0px -4px; } .imgWidth{ width: 160%; } .tituloHotel{ font-size: 2rem; margin-top: 4px; } .paddingRow{ padding: 0; } .fontSizeP{ font-size: 14px; } .fontSizePreco{ font-size: 14px; } .borderCelular{ border-right: 1px solid #ddd; } .centerizar{ display: -webkit-flex !important; display: flex !important; -webkit-align-items: center !important; align-items: center !important; } .row { display: -ms-flexbox; display: flex; -ms-flex-wrap: wrap; flex-wrap: wrap; margin-right: -15px; margin-left: -15px; } .justify-content-center { -ms-flex-pack: center!important; justify-content: center!important; } </style> <div class="container-fluid"> <br><br> <div class="row justify-content-center font hotel" > <div class="col-md-10 col-lg-10"> <div class="row gallery0" style="background-color: #fff;box-shadow: 7px 14px 8px #ccc;border-radius: 8px;border: 1px solid #ccc;"> <div class="col-lg-4 centeri img-div-responsive" style=" text-align: center; padding: 0 0px 9px 15px; "> <a class="imggallery0 vai" href=""><img src="<?=$url?>" class="img-responsive img-fluid imgHotel" style="margin:11px;display: none"></a> <img src="<?=$url?>" class="img-responsive img-fluid imgHotel" style="margin-top: 11px;"> <br> </div> <div class="col-lg-4" style=""> <h3 class="tituloHotel" style="color: #0069a7!important;font-weight: 400;margin-bottom: 0;font-size: 28px;margin-top:6px"> <?=$title?> <br class="exibirCelular"></h3> <span><small style="font-size: 12px;color: #424242"><?=$localizacao?></small></span> <span class="exibirComputador" style="margin-right: 7px;margin-left: 7px;border-right: 1px solid #ccc;"></span> <br class="exibirCelular"> <hr style="margin-bottom: 5px;margin-top: 5px;"> <p style="line-height: 1.6;text-align: justify;"> <?=$description?> </p> <?php if (!empty($servicos)) { ?> <p style="font-weight: 700;font-size: 12px;margin-bottom: 0">SERVIÇOS DO HOTEL </p> <div class="row" style="margin-left: -1px;margin-bottom: 11px;"> <?=$servicos?> </div> <?php } ?> </div> <div class="col-lg-4 borderC" style="/* padding-top: 24px; */margin-top: 11px;"> <br class="exibirComputador"> <p class="exibirComputador" style="margin-bottom: 9px;"><br></p> <div class="row" style="margin-bottom: 5px;font-size: 13px;border-top: 1px solid #e5e5e5;padding-top: 6px;"> <div class="col-lg-1 col-1 paddingCelular" style="margin-right: -7px;"></div> <div class="col-lg-5 col-4 borderCelular col1Celular"><strong>Apto</strong></div> <div class="col-lg-2 col-2 borderCelular col2Celular"><strong>Tipo</strong></div> <div class="col-lg-1 col-2 borderCelular text-center"><strong>Pax</strong></div> <div class="col-lg-2 col-3" style="padding-right: 0;float: right;text-align: right;padding-left: 5px;"><strong>A partir de</strong></div> </div> <?php if (!empty($apartamentos)) { ?> <?php for ($i=0; $i < count($apartamentos); $i++) { ?> <div class="row" style="margin-bottom: 8px;padding-top: 4px;padding-bottom: 3px;background-color: #eee;"> <div class="col-lg-1 col-1 paddingCelular" style="margin-right: -7px;"> <p style="font-size: .875rem; margin-bottom: 0;"><input type="radio" name="nameHotel" id="nameHotel<?=$i?>" value="<?=str_replace(" ", "-", $apartamentos[$i]['acomodacao']);?>;<?=$apartamentos[$i]['id_produto'];?>;<?=$dados[2]?>" onchange="AtribuiValorHotel('<?=$i?>')"> </p> </div> <div class="col-lg-5 col-4 colNomeCelular" style="border-right: 1px solid #ddd;"> <p class="fontSizeP" style="margin-bottom: 0;"> <?=$apartamentos[$i]['acomodacao'];?> </p> </div> <div class="col-lg-2 col-3" style="border-right: 1px solid #ddd;"> <p class="fontSizeP" style="margin-bottom: 0;"> <?=$apartamentos[$i]['tipo'];?></p> </div> <div class="col-lg-1 col-1" style="border-right: 1px solid #ddd;"> <p class="fontSizeP" style="margin-bottom: 0;text-align: center"> <?=$apartamentos[$i]['pax'];?></p> </div> <div class="col-lg-2 col-3" style="padding-right: 0;float: right;text-align: right;padding-left: 5px;"> <p class="fontSizePreco" style="margin-bottom: 0;"><small style="font-size: 10px;"> </small><?=$apartamentos[$i]['valor'];?></p> </div> </div> <?php } ?> <?php } ?> <small>Valor da diária por apartamento.</small> <br> <br> <button class="btn btn-primary" style="float: right;width: 100%;font-size: 25px;text-transform: uppercase;margin-bottom: 14px;" onclick="enviarFormTodos();"><i class="fas fa-calendar-alt"></i> Reservar</button> <br><br> </div> </div> </div> </div> <br> </div> <br><br> </div> <input type="hidden" id="uri" name="" value="<?=$_SERVER['REQUEST_URI']?>"> <script type="text/javascript"> function show_div_count(){ jQuery(".dropdown").toggle(500); } jQuery(document).ready(function(){ jQuery('.count').prop('disabled', true); jQuery(document).on('click','.plus',function(){ var valor = parseInt(jQuery('.count').val()) + 1; jQuery('.count').val(valor); jQuery("#count_adultos").html("<strong>"+valor+" adultos</strong>"); }); jQuery(document).on('click','.minus',function(){ var valor = parseInt(jQuery('.count').val()) - 1; jQuery('.count').val(valor); jQuery("#count_adultos").html("<strong>"+valor+" adultos</strong>"); if (jQuery('.count').val() == 0 || jQuery('.count').val() == 1) { jQuery('.count').val(1); jQuery("#count_adultos").html("<strong>1 adulto</strong>"); } }); jQuery('.count_child').prop('disabled', true); jQuery(document).on('click','.plus_child',function(){ var valor = parseInt(jQuery('.count_child').val()) + 1; jQuery('.count_child').val(valor); jQuery("#count_criancas").html("<strong>"+valor+" crianças</strong>"); if (jQuery('.count_child').val() == 1) { jQuery('.count_child').val(1); jQuery("#count_criancas").html("<strong>1 criança</strong>"); } }); jQuery(document).on('click','.minus_child',function(){ var valor = parseInt(jQuery('.count_child').val()) - 1; jQuery('.count_child').val(valor); jQuery("#count_criancas").html("<strong>"+valor+" crianças</strong>"); if (jQuery('.count_child').val() == 0) { jQuery('.count_child').val(1); jQuery("#count_criancas").html("<strong>0 criança</strong>"); } if (jQuery('.count_child').val() == 1) { jQuery('.count_child').val(1); jQuery("#count_criancas").html("<strong>1 criança</strong>"); } }); jQuery('.count_quartos').prop('disabled', true); jQuery(document).on('click','.plus_quartos',function(){ var valor = parseInt(jQuery('.count_quartos').val()) + 1; jQuery('.count_quartos').val(valor); jQuery("#count_quartos").html("<strong>"+valor+" quartos</strong>"); }); jQuery(document).on('click','.minus_quartos',function(){ var valor = parseInt(jQuery('.count_quartos').val()) - 1; jQuery('.count_quartos').val(valor); jQuery("#count_quartos").html("<strong>"+valor+" quartos</strong>"); if (jQuery('.count_quartos').val() == 0 || jQuery('.count_quartos').val() == 1) { jQuery('.count_quartos').val(1); jQuery("#count_quartos").html("<strong>1 quarto</strong>"); } }); }); function AtribuiValorHotel(id){ var dados = jQuery("#nameHotel"+id).val(); var uri = jQuery("#uri").val(); dados = dados.split(";"); jQuery("#uri").val('/apto?param='+dados[0]+';'+dados[1]+';'+dados[2]); } function enviarFormTodos(){ var uri = jQuery("#uri").val(); window.location.href = uri; } </script> <!-- /Blog Section with Sidebar --> <?php get_footer(); ?>
a93886fef8e4188b682d6a7a21a830d5ff1ef46c
[ "JavaScript", "PHP" ]
18
PHP
TravelTec/integracao-hoteis
63cd80a2539f7b062a60ff8ef3e25257635410ed
a8a040b872feebeddad7d58cd10f2b05118ac344
refs/heads/master
<file_sep>#!/bin/bash python manage.py syncdb python manage.py loaddata debately/fixtures/debately_data.json python manage.py runserver <file_sep>import os from django.conf import settings from django.conf.urls.defaults import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), # Django authentication pages (r'^login/', 'django.contrib.auth.views.login', {'template_name': 'auth/login.html'}), (r'^logout/', 'django.contrib.auth.views.logout', {'template_name': 'auth/logout.html'}), # Debately urls (r'^', include('debately-site.debately.urls')), ) if settings.DEBUG: debately_static_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'static') debately_app_static_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'debately', 'static') urlpatterns += patterns('', # the following is for service static media in the development # environ. Should not be used in production # see http://docs.djangoproject.com/en/dev/howto/static-files/ # for details (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': debately_static_path}), (r'^debately/static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': debately_app_static_path}), )
84cc19a98a180f99691e2f1f1f21ab1623a7dd22
[ "Python", "Shell" ]
2
Shell
mikeheldar/debately-site
1fe488904c564490e0ad7a737b7aa01a77e2c492
d7883dba56eeafbba84522d4bc44f46e92fdd29d
refs/heads/master
<file_sep>package main; public class Exercitiul6 { public static void main(String[] args) { // TODO Auto-generated method stub int[] vector = new int[] {13, 25, 3, 93}; double doubleNumar= 23.5; for(int y=0; y<vector.length; y++) {vector[y] = vector[y] + (int)doubleNumar; } for(int x=0; x<vector.length; x++) { System.out.println(vector[x]); } } } <file_sep>package main; public class Exercitiul3 { public static void main(String[] args) { // TODO Auto-generated method stub int[] array = new int[] {5, 9, -3, 13 }; for(int i=0; i<array.length; i++) { if(array[i]<0) { System.out.println("Valoarea negativa se afla la indexul: " + i); } } } }
81adad58741191acd9b2dae411fdb760067ea70c
[ "Java" ]
2
Java
dragomirgeorge93/Curs-3---Tema
fce19f77b4b0567dd7a62ba207ac45f5302746ae
df10b5958429621db2bbbdf636ba8e6945d557cb
refs/heads/master
<repo_name>msavin/queue<file_sep>/queue.js Queue = {} Queue.config = {} Queue.pending = new Mongo.Collection("queuePending"); Queue.posted = new Mongo.Collection("queuePosted"); Queue.register = function (config) { keys = Object.keys(config); keys.forEach(function (key) { Queue.config[key] = config[key]; }); } Queue.add = function (name, data) { if (Queue.config[name]) { doc = { name: name, data: data, date: new Date() } if (Meteor.userId()) { doc.userId = Meteor.userId(); } Queue.collection.insert(doc); } else { console.log("Queue Error: '" + name + "' does not exist"); } } Queue.addToHistory = function (doc, action, extraData, result) { doc = { original: doc, action: action, extraData: extraData, result: result }; if (Meteor.userId) { userId: Meteor.userId(); } Queue.posted.insert(doc) } Queue.resolve = function (id, action, extraData) { // First, we get the document of the item in the queue doc = Queue.collection.findOne(id) if (doc) { // Then, we want to remove the document to minimize the risk of it being called twice remove = Queue.collection.remove(id); // Assume the remove returns 1, we can assume we are the only ones to touch it if (remove === 1) { try { result = Queue.config[doc.name][action](doc.data, extraData); // assuming the function above ran successfully, we add the item to history if (result) { Queue.addToHistory(doc, action, extraData, result) } return result; } catch (e) { // If the function failed for whatever reason, we put the item back in the queue Queue.collection.insert(doc); } } } else { console.log("Queue Error: item '" + id + "' was not found."); return false; } } Queue.resolveAll = function (id, action, extraData) { doc = Queue.collection.findOne(id) doc.data; docs.find({data: docData}).fetch().forEach(function (item) { Queue.resolve(item._id, action, extraData) }); } <file_sep>/README.md # Queue - a Moderation System Boilerplate for Meteor > Note: this package is not complete yet. I'm going to focus on getting the right feature set, then build the package. Feel free to open an issue or comment on the [forum thread](https://forums.meteor.com/t/queue-package-for-meteor-for-things-like-activity-moderation/37515/11) - your feedback will be super helpful to making sure this is done right! There are many moments when our application needs a moderation system to resolve complains or authorize certain tasks. For example, let's say we have an apartment listing website. We need to be able to receive reports of bad listings, and make the decision to pull them down or ignore the request. Or, we might want to have a process to approve or reject them before they can be seen publicly. Queue aims to help here by providing a boilerplate for managing these interactions. You start by creating a queue, and then defining what possible inputs and outputs it may have. Then, you can add items to it and resolve them as you wish. # Step 1: Creating the Queues To mirror our example above, lets say we want to create two queues: one to ensure that we have to approve every listing that goes on the website, and another to allow us to handle complaints. First, we need to register the queues and define the possible tasks. ```javascript Queue.register({ reportListingProblem: { remove: { report: function (data) { Apartments.remove(data.identifier) }, reporter: function (data, reporter) { MagicEmail.send({ userId: reporter.id, subject: "Thank you - your report has been addressed." message: data.message }) } }, ignore: { reporter: function (data, reporter) { MagicEmail.send({ userId: reporter.id, subject: "Thank you - your report has been declined." message: data.message }) } } } }) ``` This will make more sense after reading the rest of the article, but the idea is, Queue groups reported items to one document to prevent flooding and having to repeat actions. Therefore, you have two functions, one to deal with the report, and the other to provide some kind of feedback to the people who reported it. Both are optional. As for our MagicEmail function, its just to keep things simple - but you can think of it as something that will take the userId that Queue provides, finds the email addres sfor it, and sends it out along with a dynamic message. # Step 2: Adding Items and Resolving Them When we add items to our queue, there are a four kinds of data that we want to record. 1. Meta Data. Who is making these reports, at what time, and so on. Queue will track these things automatically when Meteor.user() is available. If it isn't, you can specify it yourself. 2. Priority Data. While we may prefer to track these items in chronological order, we may need to mark some items are higher priority than others. By default, every item will have a priority of 0, and you can add any number you wish 3. Identifier Data. When adding items to the Queue, we want to look if there is some commonality between them. For example, if the same apartment listing is reported 100 times, we might prefer to group these items into one report. 4. Supplementary Data. Each report might have a comment by a member or some other kind of indication. It's important that we can save and see all of them. ```javascript Meteor.call({ listingReport: function (complaint) { var complaintId = Queue.add( name: 'requestPostApproval', identifier: complaint.apartmentId, userId: Meteor.userId(), // optional & automatic priority: 1, // optional data: { reason: complaint.apartmentId, } }); return complaintId; } }) ``` In this example, we are adding an item to the Queue and identifying it with the _id of the listing. If other people complain about this listing, it will be grouped as one. We also pass in the userId of the person who filed the complaint through Meteor.userId(). This field is optional, because in this case, Queue would check for the variable and find it with-in the scope of the Method. # Step 3: Viewing the Issues To view problems, we have handy functions to help us see complaints. By default, we will get items sorted first by priority, then by how many times its been reported, then by oldest to latest. ``` Queue.get("reportListing", 10) // returns the top 10 items ``` This would let us interact with data easily through shell. Alternatively, if we want to build it into our admin panel, we can access the collections directly though `Queue.collection`. # Step 3: Solving Problems Next, let's say that someone trolled our website, and now we have five alerts about it thanks to our amazing members. We want to issue ```javascript Meteor.methods({ listingResolve: function (resolve) { if (!magicPermissionCheck()) return; Queue.resolve({ name: "requestPostApproval" identifier: resolve.apartmentId, resolverUserId: Meteor.userId, data: { publicMessage: resolve.public, privateMessage: resolve.private } }) } }) // ... Meteor.call("resolveComplaint", { name: "requestPostApproval", apartmentId: "Cb3rLq6FNZu7QtqKE", privateMessage: "Your listing has been removed from our website for not following the community guidelines.", publicMessage: "Thank you for reporting this problem so quickly! - you're all set, thanks for using our app!" }) ``` Then, the Queue would do its job. In our case, it would update the document of the apartment listing to be no longer visible, email the author about the decision, and email everyone else an update.
239c3c5c76a381f4566a6c63bc859953ecc0a398
[ "JavaScript", "Markdown" ]
2
JavaScript
msavin/queue
5fff9d228dea7175e139b192f4bd75fdfc5bcc4e
986b9b0e7d94bfcc3ce3893192a39d1ee0da3d65
refs/heads/main
<file_sep>task("deploy:PolygoonzFarm") .addParam("nft", "0x8<KEY>") .addParam("erc20", "0x1f44AF55E91f<KEY>fda580a905455c78") .addParam("dao", "0<KEY>") .addParam("reward", "520833333333333") .setAction(async function (taskArguments, { ethers }) { console.log("Task arguments: ", taskArguments); const PolygoonzFarmFactory = await ethers.getContractFactory( "PolygoonzFarm" ); const polygoonzFarm = await PolygoonzFarmFactory.deploy( taskArguments.nft, taskArguments.erc20, taskArguments.dao, taskArguments.reward ); await polygoonzFarm.deployed(); console.log("PolygoonzFarm deployed to: ", polygoonzFarm.address); }); // yarn hardhat deploy:PolygoonzFarm / // --nft 0x8<KEY> / // --erc20 0x1f<KEY> / // --dao 0<KEY> / // --reward 520833333333333 --network mumbai / <file_sep>require("dotenv").config(); const { NEXT_PUBLIC_API_URL: API_URL, NEXT_PUBLIC_PUBLIC_KEY: PUBLIC_KEY } = process.env; const { createAlchemyWeb3 } = require("@alch/alchemy-web3"); const web3 = createAlchemyWeb3(API_URL); const contract = require("../artifacts/contracts/Polygoonz.sol/Polygoonz.json"); const contractAddress = "0x8780bffc3aac7ebc40194bcd70d20b7d4e6a92b6"; const nftContract = new web3.eth.Contract(contract.abi, contractAddress); async function mintNFT(tokenURI) { const nonce = await web3.eth.getTransactionCount(PUBLIC_KEY, "latest"); //get latest nonce //the transaction const tx = { from: PUBLIC_KEY, to: contractAddress, nonce: nonce, gas: 500000, data: nftContract.methods.mintNFT(PUBLIC_KEY, tokenURI).encodeABI(), }; } <file_sep>require("@nomiclabs/hardhat-waffle"); require("./scripts/tasks/deployers"); const fs = require("fs"); const privateKey = fs.readFileSync(".secret").toString().trim() || "01234567890123456789"; /** * @type import('hardhat/config').HardhatUserConfig */ require("dotenv").config(); require("@nomiclabs/hardhat-ethers"); const { NEXT_PUBLIC_API_URL, PRIVATE_KEY } = process.env; module.exports = { defaultNetwork: "mumbai", networks: { hardhat: { chainId: 1337, }, mumbai: { url: NEXT_PUBLIC_API_URL, // url: "https://rpc-mumbai.matic.today", accounts: [privateKey], }, }, solidity: { version: "0.8.6", settings: { optimizer: { enabled: true, runs: 200, }, }, }, }; <file_sep>// 1. Import `extendTheme` import { extendTheme } from "@chakra-ui/react"; // 2. Call `extendTheme` and pass your custom values const theme = extendTheme({ colors: { brand: { 100: "#f7fafc", // ... 900: "#1a202c", }, }, }); export default theme;
e8eeb36cfe323e394f2ae489c9cc4f590d384646
[ "JavaScript", "TypeScript" ]
4
JavaScript
4ortytwo/polygoonz-marketplace
e5f2c0b88e33d98a013c74384ce0ec5fde0abe7c
6cd8ec795ab14b223989a79d590eb6e0e47d7870
refs/heads/master
<repo_name>kch5559/C<file_sep>/seedRandomNumber.c #include <stdio.h> #include <stdlib.h> /** * Chapter 20 * @topic Seed Random Number * @name Seed Random Number * @date 04062015 * @author <NAME> */ int main() { int seed, i; printf("enter the seed : "); scanf("%d",&seed); srand(seed); for( i = 0; i <5; i++) { printf("%d.Random Number : %d\n",i+1,rand()); } return 0; } <file_sep>/Chapter7-15.c #include <stdio.h> /** * Chapter 7 * @topic Loop * @name Loop * @date N/A * @author <NAME> */ int main() { int num1, num2; int sum; printf("input two numbers : "); scanf("%d %d",&num1,&num2); for( ;num1 <= num2 ; num1++) { sum += num1; } printf("sum : %d \n",sum); return 0; } <file_sep>/eleOddorEven.c #include <stdio.h> /** * Chapter 15 * @topic Challenge * @name ArrayEle even or odd * @date 03222015 * @author <NAME> */ void isEven (int element) { if(element % 2 == 0 ){ printf("%d ",element); } } void isOdd (int element) { if(element % 2 != 0 ){ printf("%d ",element); } } int main() { int arr[10]; int lengofarr = sizeof(arr)/sizeof(int); int i; for(i = 0; i < lengofarr; i ++ ){ printf("Enter the number : "); scanf("%d",&arr[i]); } printf("Even numbers : "); for(i = 0; i < lengofarr; i ++ ){ isEven(arr[i]); } printf("\nOdd numbers : "); for(i = 0; i < lengofarr; i ++ ) { isOdd(arr[i]); } printf("\n"); return 0; } <file_sep>/doubletosum.c #include <stdio.h> /** * Chapter 5 * @topic constant * @name double * @date N/A * @author <NAME> */ int main() { double n1, n2; printf("input two numbers: "); scanf("%lf %lf",&n1,&n2); printf("%f + %f = %f \n",n1,n2,n1+n2); printf("%f - %f = %f \n",n1,n2,n1-n2); printf("%f x %f = %f \n",n1,n2,n1*n2); return 0; } <file_sep>/comparisonoperator.c #include <stdio.h> /** * Chapter 3 * @topic Operator * @name comparison operator * @date N/A * @author <NAME> */ void trueorfalse (int num){ if(num == 0){ printf("No"); }else { printf("Yes"); } } int main(void) { int num1, num2; int result; printf("Enter two numbers : "); scanf("%d %d",&num1,&num2); num1 = (++num2) - 2; result = num1 > num2; num2 = (num1--) + 4; printf("num1 = %d \n", num1); printf("num2 = %d \n", num2); printf("%d + %d = %d \n", num1,num2,num1+num2); printf("is num1 bigger than num2 ? "); trueorfalse(result); return 0; } <file_sep>/ArgcArgv.c #include <stdio.h> /** * Chapter 19 * @topic Main fuction pointer * @name Main Fuction Pointer * @date 03282015 * @author <NAME> */ int main(int argc, char *argv[]) { int i = 0; printf("The legnth of the voca : %d \n",argc); for( i = 0; i < argc ; i ++) { printf("%d letter : %s \n",i+1, argv[i]); } return 0; } <file_sep>/asciiCharacter.c /* A program that the user types a vocaburary and finds the character having maximum ascii number. */ #include <stdio.h> /** * Chapter 11 * @topic Pointer and Array * @name Find max ascii character * @date n/a * @author <NAME> */ int main() { char voca[100]; int i = 0; int j; char max = '0'; printf("input letters: "); scanf("%s",voca); while(voca[i]!='\0') { i++; } printf("%d \n",i); for(j = 0; j < i; j++){ if(max<voca[j]) max=voca[j]; } printf("foo: %c \n",max); return 0; } <file_sep>/combination.c #include <stdio.h> /** * Chapter 11 * @topic Arrapy * @name combination * @date N/A * @author <NAME> */ int main() { int numbers[5] = {1, 2, 3, 4, 5}; int i,j; int lengthOfnumbers = sizeof(numbers)/sizeof(int); for(i = 0; i < lengthOfnumbers; i ++) { printf("%d ",numbers[i]); } printf("\nthe length of array is %d \n",lengthOfnumbers); for(i = 0; i < lengthOfnumbers ; i++) { for( j = i + 1; j < lengthOfnumbers; j++) { printf("%d",numbers[i]); printf("%d ",numbers[j]); } } return 0; } <file_sep>/reversearray.c #include <stdio.h> /** * Chapter 9 * @topic Array * @name reverse Array * @date 02182015 * @author <NAME> */ int main() { char voca[100]; char temp; int leng = 0; int i; printf("enter a voca : "); scanf("%s",voca); while(voca[leng] != '\0') { leng++; } printf("the length of the voca : %d \n",leng); for( i = 0 ; i<leng/2 ; i++) { temp = voca[i]; voca[i] = voca[(leng-i)-1]; voca[(leng-i)-1] = temp; } printf("%s \n",voca); return 0; } <file_sep>/oddgoesfirst.c #include <stdio.h> /** * Chapter 15 * @topic Challenge * @name oddgoesfirst * @date 03222015 * @author <NAME> */ int main() { int arr[10]; int front = 0, back = 9; int i, num; for( i = 0 ; i < 10 ; i ++) { printf("Enter the number : "); scanf("%d",&num); if(num % 2 == 0) { arr[back] = num; back--; }else{ arr[front] = num; front++; } } for( i = 0 ; i < 10 ; i ++){ printf("%d ",arr[i]); } return 0; } <file_sep>/twoTonine.c #include <stdio.h> /** * Chapter 7 * @topic Loop * @name twotoNine * @date N/A * @author <NAME> */ int main() { int num = 2, i = 1; do { i = 1; printf("%d단 \n",num); do { printf("%d X %d = %d \n",num,i,num*i); i++; }while(i<10); num++; }while(num<10); return 0; } <file_sep>/sumofnumbers.c #include <stdio.h> /** * Chapter 7 * @topic Loop * @name sum of the five numbers * @date 03152015 * @author <NAME> */ int main() { int num=0, i=1, sum=0; while(num<5) { while(i<=1) { printf("Enter the five integer bigger or eqaul to 1 (%d) : ", num+1); scanf("%d",&i); } sum+=i; i=1; num++; } printf("Sum of the numbers : %d \n",sum); return 0; } <file_sep>/subtraction.c // a program subtracting two numbers. #include <stdio.h> /** * Chapter 8 * @topic Conditinal Statement * @name practicing if-else * @date N/A * @author <NAME> */ int main() { int num1, num2; printf("two numbers : "); scanf("%d %d",&num1,&num2); if(num1 > num2){ printf("%d - %d = %d \n",num1,num2,num1-num2); }else if(num2 > num1){ printf("%d - %d = %d \n",num2,num1,num2-num1); } return 0; } <file_sep>/printMyname.c #include <stdio.h> /** * Chapter 1 * @topic Printf * @name Printf! * @date N/A * @author <NAME> */ int main(void) { //print my name woohoo printf("<NAME> \n"); return 0; } <file_sep>/maxmin.c #include <stdio.h> /** * Chapter 9 * @topic function * @name find Max and Min * @date N/A * @author <NAME> */ int FindMax (int n1, int n2, int n3) { if(n1>n2){ return (n1>n3)? n1 : n3; } else { return (n2>n3)? n2 : n3; } } int FindMin (int n1, int n2, int n3) { if(n1<n2) { return (n1<n3)? n1 : n3; } else { return(n2<n3)? n2 : n3; } } int main () { int n1, n2, n3; printf("input three number : "); scanf("%d %d %d",&n1,&n2,&n3); printf("Biggest number : %d \n",FindMax(n1, n2, n3)); printf("Smallest number : %d \n",FindMin(n1,n2,n3)); return 0; } <file_sep>/Bytestudy2.c #include <stdio.h> /** * Chapter 4 * @topic Byte * @name Study Byte * @date N/A * @author <NAME> */ int main() { int num1=40, num2=015, num3=0x34F; printf("40 의 10진수의 값 : %d \n", num1); printf("015 의 10진수의 값 : %d\n", num2); printf("0x34F의 10진수의 값 : %d \n", num3); printf("%d + %d = %d \n", num1, num2, num1+num2); printf("%d x %d = %d \n", num2, num3, num2*num3); printf("%d % %d = %d \n", num3, num1, num3/num1); return 0; } <file_sep>/multidimensionarray_1.c /** * Chapter 16 * @topic multidimension array * @name mulitple table in multidimension array * @date 03232015 * @author <NAME> */ #include <stdio.h> int main() { int arr[3][9]; int i,j; for( i = 0; i < 3; i ++) { for( j = 0; j < 9; j++) { arr[i][j] = (i + 2) * (j + 1); } } for( i = 0; i < 3; i ++) { for( j = 0; j < 9; j++) { printf("%d ",arr[i][j]); } printf("\n"); } return 0; } <file_sep>/HelloWorld.c #include <stdio.h> /** * Chapter 1 * @topic printf * @name HellowWorld * @date N/A * @author <NAME> */ int main(void) { printf("Hello World"); return 0; } <file_sep>/pointeroperator.c #include <stdio.h> /** * Chapter 13 * @topic Pointer and Array * @name pointer operator * @date 03212015 * @author <NAME> */ int main() { int arr[5] = {1, 2, 3, 4, 5}; int *ptr = arr; int i; /* ptr += 2; arr[0] += 2 ptr++; *arr[0+1] , *prt = arr[1] ptr += 2; arr[1] += 2 ptr++; *arr[1+1] , *prt = arr[2] ptr += 2; arr[2] += 2 ptr++; *arr[2+1], *prt = arr[3] ptr += 2; arr[3] += 2 ptr++; *arr[3+1], *prt = arr[4] ptr += 2; arr[4] += 2 */ for(i = 0; i < 5; i++ ){ *ptr += 2; printf("%d \n",arr[i]); ptr++; } return 0; } <file_sep>/byteoperator.c #include <stdio.h> /** * Chapter 2 * @topic Datatype * @name byte operator * @date 12232014 * @author <NAME> */ int main() { int num = 3; num = num << 3; num = num >> 2; printf("3 X 8 % 4 = %d \n", num); return 0; } <file_sep>/temporatureconvertor.c #include <stdio.h> /** * Chapter 9 * @topic function * @name convert * @date N/A * @author <NAME> */ double CelToFah (double n) { return 1.8*n+32; } double FahToCel (double n) { return (n-32)/1.8; } int main() { int opt; printf("Cel to Fah (1), Fah to Cel (2) : "); scanf("%d",&opt); if(opt==1) { double Cel; printf("input Cel: "); scanf("%lf",&Cel); printf("Cel to Fah: %f \n",CelToFah(Cel)); } if(opt==2) { double Fah; printf("input Fah: "); scanf("%lf",&Fah); printf("Fah to Cel: %f \n",FahToCel(Fah)); } return 0; } <file_sep>/askii.c #include <stdio.h> /** * Chapter 5 * @topic constant * @name stduy constant * @date N/A * @author <NAME> */ int main() { char cha; printf("input letter: "); scanf("%c",&cha); printf("%d \n",cha); return 0; } <file_sep>/reference_isPrime.c #include <stdio.h> //refernce int isPrime(int n); int main() { int p_count = 0; int i = 0; while(1) { i++; if (isPrime(i)) { printf("%d ", i); p_count++; } if (p_count == 100) { break; } } return 0; } int isPrime(int n) { if (n <= 1) { return 0; } if (n == 2) { return 1; } int i = n; while(--i > 1) { if (n % i == 0) { return 0; } } return 1; } <file_sep>/numberBaseBall.c /** * Chapter 20 * @topic Array and Fuction * @name Number Baseball Game * @date 04072015 * @author <NAME> */ #include <stdio.h> #include <stdlib.h> #include <time.h> /* * This is a game that the user has to guess what three random numbers that cpt makes. * The user has to guess not only the number, but also order of the numbers. If the user guess right number, but order * It is a ball and if the user guess right number and right order, it is a strike. * ex) cpt random number : 2, 0, 8 * 1. user guess : 1, 2, 8 ( 1 strike, 1 ball) * 2. user guess : 3, 0, 8 (2 strike, 1 ball) * 3. user guess : 2, 0 ,8 ( 3 strike, 0 ball) -> game ends. */ void RandomThreeNum(int *arr){ srand((int)time(NULL)); for(int i = 0; i < 3; i ++) { arr[i] = (rand() % 10); } } int Strike (int *user, int *cpt) { int cnt1 = 0; for(int i = 0; i < 3; i ++ ) { if(cpt[i] == user[i]) { cnt1++; } } return cnt1; } int Ball (int *user, int *cpt) { int cnt2 = 0; for(int i = 0; i < 3; i ++ ) { if(cpt[i] == user[i]) { continue; }else { for(int j = 0; j < 3; j++ ) { if(cpt[i] == user[j]) { cnt2++; } } } } return cnt2; } int main() { int randomN[3]; int *ptr1 = randomN; RandomThreeNum(ptr1); int strike, ball, cnt = 0; int userN[3]; printf("\nStart Game! \n"); do { printf("\nEnter three numbers: "); scanf("%d %d %d",&userN[0],&userN[1],&userN[2]); int *ptr2 = userN; strike = Strike(ptr1,ptr2); ball = Ball(ptr1,ptr2); printf("Result of your %d challenge : %d stirke and %d ball \n",cnt+1, strike,ball); cnt++; }while(strike < 3); printf("Game Over ! \n"); return 0; } <file_sep>/twoTonine2.c #include <stdio.h> /** * Chapter 7 * @topic Loop * @name two to nine 2 * @date N/A * @author <NAME> */ int main() { int i, num; for( num = 2 ; num<10 ; num++) { i = 1; while(i<10) { printf("%d X %d = %d \n",num,i,num*i); i++; } printf(" \n"); } return 0; } <file_sep>/double2.c #include <stdio.h> /** * Chapter * @topic datatype * @name double * @date N/A * @author <NAME> */ int main() { double dnum1, dnum2; double result1, result2; printf("Enter two decimal numbers : "); scanf("%lf %lf", &dnum1, &dnum2); result1 = dnum1*dnum2; result2 = dnum1/dnum2; printf(" dnum1 x dnum2 = %f \n", result1); printf(" dnum1 / dnum2 = %f \n", result2); return 0; } <file_sep>/Fibo.c #include <stdio.h> /** * Chapter 9 * @topic * @name fibonacci sequence * @date 03162015 * @author <NAME> */ void Fibo(int n) { int f1=0, f2=1, f3, i; if(n==1) printf("%d ",f1); else printf("%d %d ",f1,f2); for(i=1; i<n-1; i++) { f3 = f1 + f2; printf("%d ",f3); f1 = f2; f2 = f3; } } int main() { int opt; printf("input number: "); scanf("%d",&opt); Fibo(opt); return 0; } <file_sep>/practiceDoWhile.c #include <stdio.h> /** * Chapter 7 * @topic Loop * @name practicing do-while * @date N/A * @author <NAME> */ int main() { int total=0; int num=0; do{ printf("Enter the numbers to sum ( o to quit) : "); scanf("%d",&num); total += num; }while(num!=0); printf("Total of the input numbers : %d \n",total); return 0; } <file_sep>/compareabsolutevalue.c #include <stdio.h> /** * Chapter 8 * @topic fuction * @name comparation * @date 01152015 * @author <NAME> */ int AbsNumberCompare(int num1, int num2); int GetAbs(int num); int main() { int num1, num2; printf("input two numbers: "); scanf("%d %d",&num1,&num2); num1 = GetAbs(num1); num2 = GetAbs(num2); printf("Between %d and %d, the bigger aboulute value number is %d \n", num1,num2,AbsNumberCompare(num1,num2)); return 0; } int AbsNumberCompare(int num1, int num2) { if(GetAbs(num1)>GetAbs(num2)) return num1; else return num2; } int GetAbs(num) { if(num<0) return num*(-1); else return num; } <file_sep>/pointeroperator2.c #include <stdio.h> /** * Chapter 13 * @topic Pointer and Array * @name Pointer Operator * @date 03212015 * @author <NAME> */ int main() { int arr[5] = {1, 2, 3, 4, 5}; int *prt = arr; int i; for(i = 0; i < 5; i++ ){ printf("%d ",(*prt)+2); prt++; } return 0; } <file_sep>/timeSeedNum.c #include <stdio.h> #include <stdlib.h> #include <time.h> /** * Chapter 20 * @topic Time Seed Random Number * @name Time Seed Random Number * @date 04062015 * @author <NAME> */ int main() { int roll1, roll2; srand((int)time(NULL)); roll1 = RollDie(); roll2 = RollDie(); printf("roll1 : %d \nroll2 : %d\n",roll1,roll2); return 0; } int RollDie() { return rand() % 6 + 1; } <file_sep>/studybyte.c #include <stdio.h> /** * Chapter 4 * @topic Datatype * @name stduy byte * @date N/A * @author <NAME> */ int main() { int n = 3; int i = n << 3; int j = i >> 2; printf(" 3 X 8 = %d \n",i); printf(" 3 X 8 / 4 = %d \n",j); return 0; } <file_sep>/Const.c #include <stdio.h> /** * C practice * @topic const * @name const variable * @date N/A * @author <NAME> */ int main(){ const int MAX=100; const double PI=3.1415; printf(" MAX = %d \n",MAX); printf(" PI = %lf \n",PI); return 0; } <file_sep>/Chapter7-18.c // print a revers mutiplication table #include <stdio.h> /** * Chapter 7 * @topic Loop * @name Loop * @date N/A * @author <NAME> */ int main() { int n; int i = 9; printf("input the number : "); scanf("%d",&n); while(i!=0) { printf("%d x %d = %d \n",n,i,n*i); i--; } return 0; } <file_sep>/possiblenumber_2.c #include <stdio.h> /** * Chapter 8 * @topic Conditional Statement * @name Another way of finding all possible two digit numbers that sum is 99 * @date N/A * @author <NAME> */ int main() { int A,Z; int result; for(A = 1; A < 10; A++) { for(Z = 1; Z < 10; Z++) { if(A==Z) continue; result = (A*10+Z) + (Z*10+A); if(result==99) printf("%d%d + %d%d = %d \n",A,Z,Z,A,result); } } return 0; } <file_sep>/Bytestudy4.c #include <stdio.h> /** * Chapter 4 * @topic byte * @name study byte * @date N/A * @author <NAME> */ int main() { int num1 = 5; // 00000000 00000000 00000000 00000101 int num2 = 7; // 00000000 00000000 00000000 00000111 int num3 = num1^num2; // 00000000 00000000 00000000 00000010 printf("A result of XOR : %d \n", num3); return 0; } <file_sep>/Chapter7-17.c #include <stdio.h> /** * Chapter 7 * @topic Loop * @name Loop * @date N/A * @author <NAME> */ int main() { int c,n; int total; int i = 0; printf("How many numbers would you like to average? : "); scanf("%d",&c); while(c>0) { printf("Enter the number (%d): ",i+1); scanf("%d",&n); total+=n; c--; i++; } printf("%d \n",total); printf("average of the numbers : %f \n",(double)total/i); return 0; } <file_sep>/ArrayNameisPointer.c // A program to understand that relation between array and pointer #include <stdio.h> /** * Chapter 13 * @topic Pointer and Array * @name ArrayNameisPointer * @date N/A * @author <NAME> */ int main() { int arr[5] = {1, 2, 3, 4, 5}; int *ptr; ptr = &arr[0]; printf("%d %d \n",ptr[0],arr[0]); printf("%d %d \n",ptr[1],arr[1]); printf("%d %d \n",ptr[2],arr[2]); printf("%d %d \n",ptr[3],arr[3]); printf("%d %d \n",ptr[4],arr[4]); printf("%d %d \n",*ptr,*arr); *arr = 3; printf("%d %d \n",*ptr,*arr); printf("%d %d \n",ptr[0],arr[0]); return 0; } <file_sep>/acendingorder.c #include <stdio.h> /** * Chapter 15 * @topic Challenge * @name ascendingorder * @date 03232015 * @author <NAME> */ void ascending (int arr[], int leng) { int i,j; int temp; int min; for( i = 0; i < leng; i ++) { min = arr[i]; for(j = i + 1; j < leng; j ++ ){ if( min > arr[j]) { min = arr[j]; temp = arr[i]; arr[i] = min; arr[j] = temp; } } } } int main() { int arr[7]; int i; int lengthArr = sizeof(arr)/sizeof(int); printf("Enter the seven numbers : "); for(i = 0; i < lengthArr ; i ++ ){ scanf("%d", &arr[i]); } ascending(arr,lengthArr); for(i = 0; i < lengthArr ; i ++ ){ printf("%d ", arr[i]); } return 0; } <file_sep>/isnot2.c #include <stdio.h> /** * Chapter 2 * @topic Datatype * @name isnot2 * @date 12302014 * @author <NAME> */ int main() { int num1 = 15; int num2 = ~num1; printf("num1 = %d \nnum2 = %d \n", num1,num2); return 0; } <file_sep>/sizeOf.c #include <stdio.h> /** * C practice * @topic Datatypes * @name sizeOf * @date 01022015 * @author <NAME> */ int main() { printf("literal int size : %d \n", sizeof(7)); printf("literal double size : %d \n", sizeof(7.55)); printf("literal char size : %d \n", sizeof('A')); return 0; } <file_sep>/ascii.c #include <stdio.h> /** * Chapter 2 * @topic Datatype * @name Ascii * @date 12302014 * @author <NAME> */ int main() { char ch1 = 'A', ch2 = 65; int ch3 = 'B', ch4 = 66; printf(" %c %d \n",ch1 ,ch1); printf(" %c %d \n",ch2 ,ch2); printf(" %d %c \n",ch3 ,ch3); printf(" %c %d \n",ch4 ,ch4); return 0; } <file_sep>/practiceFor.c #include <stdio.h> /** * Chapter 7 * @topic Loop * @name Stop summing by using for loop * @date N/A * @author <NAME> */ int main() { int num1, num2; int total = 0; printf("num1 : "); //사용자 지정 num1 scanf("%d",&num1); printf("num2 : "); //사용자 지정 num2 scanf("%d",&num2); for( ; num1<=num2; num1++) //when num1 became bigger than num2. stop summing the numbers. { total+=num1; } printf(" 합 : %d \n", total); return 0; } <file_sep>/isPrime.c /* * A program that finds prime numbers and prints the numbers of prime numbers that the user enter. */ #include <stdio.h> /** * Practice * @topic Fuction * @name Find prime numbers * @date N/A * @author <NAME> */ int IsPrime(int num) { int i; int cnt = 0; if(num==2) { return 1; } for( i = 1 ; i<num-1; i++) { if(num%i==0) { cnt++; } } if(cnt==1) { return 1; } return 0; } int main() { int n, i; int cnt = 0; printf("Enter the number how many prime numbers you want : "); scanf("%d",&i); for(n = 1; cnt!=i; n++) { if(IsPrime(n)==1) { printf("%d ",n); cnt++; } } return 0; } <file_sep>/snailArray.c #include <stdio.h> /** * Chapter 20 * @topic Multiple Dimention Array * @name Snail Array * @date 04042015 * @author <NAME> */ int main() { int num; int i,j; int k = 1; int r = 0, c = -1, n = 0; printf("Enter the number : "); scanf("%d",&num); int arr[num][num]; int leng = num; while(1) { for( i = 0; i < leng ; i++ ){ n++; c = c + k; arr[r][c] = n; } leng--; if(n == num*num) { break; } for( i = 0; i < leng; i++) { n++; r = r + k; arr[r][c] = n; } k = k * ( - 1); } for(i = 0; i < num; i++ ) { for(j = 0; j < num; j++) { printf("%2d ",arr[i][j]); } printf("\n"); } return 0; } <file_sep>/ArrayParamAccess.c #include <stdio.h> /** * Chapter 14 * @topic Pointer and Fuction * @name ArrayParamAcces * @date 03222015 * @author <NAME> */ void ShowArrayElem(int *param, int length) { int i; for( i = 0; i < length ; i++ ){ printf("%d ",param[i]); } printf("\n"); } void AddArrayElem ( int *param, int length, int add) { int i; for(i = 0; i < length ; i ++) { param[i] += add; } } void multiplyArrayElem ( int *param, int length, int num) { int i; for(i = 0; i < length ; i ++ ){ param[i] *= num; } } int main() { int arr1[5] = {1, 2, 3, 4, 5}; int arr2[5] = {10, 20, 30, 40, 50}; int Arr1leng = sizeof(arr1)/sizeof(int); int Arr2leng = sizeof(arr2)/sizeof(int); ShowArrayElem(arr1, Arr1leng); AddArrayElem(arr1, Arr1leng, 2); ShowArrayElem(arr1, Arr1leng); multiplyArrayElem(arr1, Arr1leng, 20); ShowArrayElem(arr1, Arr1leng); ShowArrayElem(arr2, Arr2leng); AddArrayElem(arr2, Arr2leng, 10); ShowArrayElem(arr2, Arr2leng); multiplyArrayElem(arr2, Arr2leng, 2); ShowArrayElem(arr2, Arr2leng); return 0; } <file_sep>/divisibleby7or9.c #include <stdio.h> /** * Chapter 7 * @topic Loop * @name divisible * @date 01122015 * @author <NAME> */ int main() { int num; for(num=1; num<100; num++) { if(num%7==0 || num%9==0) { printf("%d is divisible by 7 or 9 \n",num); } } return 0; } <file_sep>/practicescanf.c #include <stdio.h> /** * Practice C * @topic Practice C * @name Practice * @date N/A * @author <NAME> */ int main() { int num1, num2; printf("num1= "); scanf("%d",&num1); printf("num2= "); scanf("%d",&num2); printf("%d 나누기 %d 의 몫은 %d 이고 나머지는 %d이다 \n",num2, num1, num2/num1, num2%num1); return 0; } <file_sep>/double.c #include <stdio.h> /** * Chapter 2 * @topic Datatype * @name double * @date 12302014 * @author <NAME> */ int main() { double rad; double area; printf("rad = "); scanf("%lf", &rad); area = rad*rad*3.1415; printf("area = %f \n",area); return 0; } <file_sep>/practiceprintf.c #include <stdio.h> /** * Practice C * @topic Practice C * @name Practice * @date N/A * @author <NAME> */ int main(void) { printf("%d %d %d \n", 1,2,3); printf("%d \n%d \n%d \n", 1,2,3); return 0; } <file_sep>/chart.c #include <stdio.h> /** * Practice C * @topic Practice C * @name Chart * @date N/A * @author <NAME> */ int main() { printf("%-10s %-8s %10s \n", "NAME", "SEX", "PHONE NUMBER"); printf("%-10s %-8s %10d \n", "Chohee", "Female", 1234567890); printf("%-10s %-8s %10ld \n", "Marin", "Male", 2345678901); printf("%-10s %-8s %10ld \n", "Rin", "Female", 3456789012); printf("%-10s %-8s %10ld \n", "Mike", "Male", 4567890123); printf("%-10s %-8s %10ld \n", "Joy", "Male", 5678901234); return 0; } <file_sep>/Bytestudy1.c #include <stdio.h> /** * Chapter 4 * @topic Byte * @name Study Byte * @date N/A * @author <NAME> */ int main(void) { int num1 = 0x3F, num2 = 015, num3 = 20; printf("0x3F의 10진수의 정수 값 : %d \n", num1); printf("015의 10진수의 정수 값 : %d \n", num2); printf("20의 10진수의 정수 값 : %d \n", num3); return 0; } <file_sep>/sizeof2.c #include <stdio.h> /** * Chapter 2 * @topic Datatype * @name size of other datetype * @date 12302014 * @author <NAME> */ int main() { char ch = 9; int inum = 1052; double dnum = 3.1354; printf(" Size of Ch : %d \n", sizeof(ch)); printf(" Size of Inum : %d \n", sizeof(inum)); printf(" Size of Dnum : %d \n", sizeof(dnum)); printf(" Size of Char : %d \n", sizeof(char)); printf(" Size of Int : %d \n", sizeof(int)); printf(" Size of Long : %d \n", sizeof(long)); printf(" Size of Float : %d \n", sizeof(float)); printf(" Size of Double : %d \n", sizeof(double)); return 0; } <file_sep>/studyoperator11.c #include <stdio.h> /** * Chapter 3 * @topic Operator * @name study operator * @date N/A * @author <NAME> */ int main(void){ int num1, num2; int result1, result2; printf("num1 : "); scanf("%d", &num1); printf("num2 : "); scanf("%d", &num2); result1 = num2 - num1; result2 = num1 * num2; printf("%d-%d=%d \n",num2,num1,result1); printf("%dx%d=%d \n", num1,num2,result2); return 0; } <file_sep>/pointer1.c #include <stdio.h> /** * Practice * @topic pointer * @name pointer practice * @date 02112015 * @author <NAME> */ int main() { int num1 = 10, num2 = 20; int *ptr1 = &num1; int *ptr2 = &num2; int *temp; *ptr1 = *ptr1<<1; *ptr2 = *ptr2>>1; temp = ptr1; ptr1 = ptr2; ptr2 = temp; printf("%d %d \n",*ptr1,*ptr2); return 0; } <file_sep>/descendingorder.c #include <stdio.h> /** * Chapter 15 * @topic Challenge * @name descendingorder * @date 03232015 * @author <NAME> */ void descending(int arr[], int leng) { int i,j; int temp; int max; for( i = 0; i < leng; i ++) { max = arr[i]; for( j = i + 1; j < leng; j ++) { if(max < arr[j]) { max = arr[j]; temp = arr[i]; arr[i] = max; arr[j] = temp; } } } } int main() { int arr[7]; int leng = sizeof(arr)/sizeof(int); int i; printf("Enter the seven numbers : "); for( i = 0; i < leng; i++) { scanf("%d", &arr[i]); } descending(arr, leng); for( i = 0; i < leng; i++) { printf("%d ", arr[i]); } return 0; } <file_sep>/isnot.c #include <stdio.h> /** * Chapter 2 * @topic Datatype * @name Ascii * @date 12302014 * @author <NAME> */ int main() { int num1=4, num2=9; printf(" A result of NOT = %d \n", ~num1+1); printf(" A result of NOT = %d \n", ~num2+1); return 0; } <file_sep>/hexadecimal.c #include <stdio.h> /** * Chapter 3 * @topic ????? * @name Hexadecimal * @date N/A * @author <NAME> */ int main () { int n; //the user enter the decimal number here printf("input the decimal number : "); scanf("%d",&n); //print as hexadecimal printf("hexadecimal of the number : %x \n",n); return 0; } <file_sep>/operatorstudy1.c #include <stdio.h> /** * Chapter 3 * @topic operator * @name diffrentoperator * @date N/A * @author <NAME> */ int main() { int num1=3, num2=6, num3=9; printf("%d + %d = %d \n", num1,num2,num1+num2); printf("%d - %d = %d \n", num3,num2,num3-num2); printf("%d x %d = %d \n", num1,num2,num1*num2); printf("%d 나누기 %d 의 몫은 %d이고, 나머지는 %d이다 \n", num3,num2,num3/num2,num3%num2); return 0; } <file_sep>/printmyinformation.c #include <stdio.h> /** * Chapter 2 * @topic printf * @name Print my name, address, and phone number * @date N/A * @author <NAME> */ int main(void) { printf("Name : <NAME> \n"); printf("Address : 601 William st. #520 Oakland, CA \n"); printf("P/N : 510-712-8533 \n"); return 0; } <file_sep>/googlejam3.c #include <stdio.h> /** * Google Code Jam * @topic Standing Ovation * @name 2015 Google Code Jam - C * @date 04112015 * @author <NAME> */ //I dunno............It is incorrect............... void fillArray(char repeat[], int arr[], int lengOfrep, int lengOfarr) { for(int i = 0, j = 0; i < lengOfarr; ) { if( j < lengOfrep) { arr[i] = repeat[j]; i++, j++; }else{ j = 0; continue; } } } void isI (int arr[], int length, int (*multi)[9], int NEWarr[], int *idx) { if(arr[*idx] == 105) { NEWarr[0] = arr[*idx]; *idx += 1; }else { for(; arr[*idx] != 105 && *idx < length; *idx+=1){ int row , col; for(int i = 0; i < 9; i ++) { if(arr[*idx] == multi[i][0]){ row = i; } } for(int j = 0; j < 9; j++) { if(arr[*idx+1] == multi[0][j]) { col = j; } } arr[*idx+1] = multi[row][col]; NEWarr[0] = multi[row][col]; if(NEWarr[0] == 105) { *idx += 2; break; } } } } void isJ (int arr[], int length, int (*multi)[9], int NEWarr[], int *idx) { if(arr[*idx] == 106) { NEWarr[1] = arr[*idx]; *idx += 1; }else { for(; arr[*idx] != 106 && *idx < length; *idx += 1){ int row , col; for(int i = 0; i < 9; i ++) { if(arr[*idx] == multi[i][0]){ row = i; } } for(int j = 0; j < 9; j++) { if(arr[*idx+1] == multi[0][j]) { col = j; } } arr[*idx+1] = multi[row][col]; NEWarr[1] = multi[row][col]; if(NEWarr[1] == 106) { *idx += 2; break; } } } } void isK (int arr[], int length, int (*multi)[9], int NEWarr[], int *idx) { if( *idx == length -1) { if(arr[*idx] == 107) { printf("%d \n",arr[*idx]); NEWarr[2] = 107; } }else { for(; *idx < length; *idx+=1){ int row , col; for(int i = 0; i < 9; i ++) { if(arr[*idx] == multi[i][0]){ row = i; } } for(int j = 0; j < 9; j++) { if(arr[*idx+1] == multi[0][j]) { col = j; } } arr[*idx+1] = multi[row][col]; NEWarr[2] = multi[row][col]; if(NEWarr[2] == 107) { break; } } } } int main() { int cpr[3]; int caseNum; int cnt = 0; int multi[9][9] = { {0,1,105,106,107,-1,-105,-106,-107}, {1,1,105,106,107,-1,-105,-106,-107}, {105,105,-1,107,-106,-105,1,-107,106}, {106,106,-107,-1,105,-106,107,1,-105}, {107,107,106,-105,-1,-107,-106,105,1}, {-1,-1,-105,-106,-107,1,105,106,107}, {-105,-105,1,-107,106,105,-1,107,-106}, {-106,-106,107,1,-105,106,-107,-1,105}, {-107,-107,-106,105,1,107,106,-105,-1}, }; scanf("%d",&caseNum); while(cnt < caseNum) { int L,X; char rpt[10000]; int arr[10000]; int i = 0; int *ptr = &i; scanf("%d %d",&L,&X); scanf("%s", rpt); printf("Case #%d: ",cnt+1); fillArray(rpt, arr, L , L * X); isI(arr, L*X, multi, cpr, ptr); isJ(arr, L*X, multi, cpr, ptr); isK(arr, L*X, multi, cpr, ptr); if(cpr[0] == 105 && cpr[1] == 106 && cpr[2] == 107) { printf("YES\n"); }else{ printf("NO\n"); } cnt++; } return 0; } <file_sep>/solvealgebra.c #include <stdio.h> /** * Chapter * @topic algebra * @name solve algebra * @date N/A * @author <NAME> */ int main() { int num1, num2, num3; int result; printf("Three numbers : "); scanf("%d %d %d", &num1,&num2,&num3); result = (num1-num2)*(num2+num3)*(num3%num1); printf("(%d-%d)x(%d+%d)x(%d/%d)=%d\n",num1,num2,num2,num3,num3,num1,result); return 0; } <file_sep>/secondMinuteHour.c #include <stdio.h> /** * Practice C * @topic Practice C * @name Practice * @date N/A * @author <NAME> */ const int H=60*60; const int M=60; void SecondToHMS(int sec); int main() { int sec; printf("input ( second ) : "); scanf("%d",&sec); SecondToHMS(sec); return 0; } void SecondToHMS(int sec) { int h,m,s; h=sec/H; sec=sec%H; m=sec/M; sec=sec%M; s=sec; printf("h : %d, m : %d, s : %d \n",h,m,s); } <file_sep>/timestable.c #include <stdio.h> /** * Chapter 7 * @topic loop_while * @name timestable * @date N/A * @author <NAME> */ int main() { int num=2; int i; while(num<10) { i=1; while(i<10) { printf("%d X %d = %d \n",num,i,num*i); i++; } num++; } return 0; } <file_sep>/90degree.c #include <stdio.h> /** * Chapter 20 * @topic Multiple Dimention Array * @name 90degree * @date 04032015 * @author <NAME> */ void RotateArr (int (*arr)[4]); void PrintArr (int (*arr)[4]); int main() { int arr[4][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} }; printf("*First rotation* \n"); RotateArr(arr); PrintArr(arr); printf("\n*Second rotation* \n"); RotateArr(arr); PrintArr(arr); printf("\n*Third rotation* \n"); RotateArr(arr); PrintArr(arr); return 0; } void RotateArr (int (*arr)[4]) { int temp[4][4]; int i,j; for(i = 0; i < 4; i++) { for(j = 0; j < 4; j++) { temp[j][3-i] = arr[i][j]; } } for(i = 0; i < 4; i++) { for(j = 0; j < 4; j++) { arr[i][j] = temp[i][j]; } } } void PrintArr (int (*arr)[4]) { int i,j; for(i = 0; i < 4; i++) { for(j = 0; j < 4; j++) { printf("%2d ",arr[i][j]); } printf("\n"); } } <file_sep>/nestedwhiles.c #include <stdio.h> /** * Chapter 7 * @topic loop * @name Practice Loop * @date N/A * @author <NAME> */ int main() { int i=0, j=0; while(i<6) { while(j<i) { printf("o"); j++; } printf("* \n"); i++; j=0; } return 0; } <file_sep>/TwoToNine.c #include <stdio.h> /** * Chapter 7 * @topic Loop * @name Two to Nine * @date N/A * @author <NAME> */ int main() { int num = 2, i = 1; while(num<10) { for( i = 1; i<10 ; i++) printf(" %d X %d = %d \n",num,i,num*i); printf(" \n"); num++; } return 0; } <file_sep>/IsPrimenumber2.c #include <stdio.h> /** * Practice * @topic using fuction * @name find prime numbers * @date N/A * @author <NAME> */ // a fuction to find the prime number int IsPrime(int n) { int i; int cnt = 0; if (n <= 1) { return 0; } if (n == 2) { return 1; } for(i = (n/2)+1; i>1; i--){ if(n%i==0) { cnt++; } } if(cnt==0) { return 1; } return 0; } int main() { int n; int cnt = -1; int i = 1; // the user enters how many prime numbers want to print. while(cnt<=0) { printf("input numbers(input positive number) : "); scanf("%d",&cnt); } //prints prime numbers. for(n = 1; i<=cnt ;n++) { if(IsPrime(n)==1) { printf("%d ",n); i++; } } return 0; } <file_sep>/idNumber.c #include <stdio.h> /** * Chapter 8 * @topic condtional statement * @name identifying the number * @date N/A * @author <NAME> */ int main() { int num; printf("Enter one integer : "); scanf("%d",&num); switch(num/10) { case 0: printf("bigger or equalt to 0 and smaller than 10\n"); break; case 1: printf("bigger or equalt to 10 and smaller than 20\n"); break; case 2: printf("bigger or equalt to 20 and smaller than 30\n"); break; default: printf("bigger than 3\n"); } return 0; } <file_sep>/MaxandMin.c #include <stdio.h> void MaxandMin (int leng, int *arr, int **maxP, int **minP) { int i; int *max = &arr[0]; int *min = &arr[0]; for( i = 0; i < leng; i++) { if(*max < arr[i]) { max = &arr[i]; } if(*min > arr[i]) { min = &arr[i]; } } *maxP = max; *minP = min; } int main() { int *maxPtr; int *minPtr; int arr[5]; int length = sizeof(arr)/sizeof(int); int i; for( i = 0; i < length; i ++) { scanf("%d",&arr[i]); } MaxandMin(length, arr, &maxPtr, &minPtr); printf("%d %d",*maxPtr, *minPtr); return 0; } <file_sep>/twopowerto.c #include <stdio.h> /** * Challenge * @topic fuction * @name twoPowerTo * @date N/A * @author <NAME> */ int PowerTo(int n){ if(n==0) return 1; return PowerTo(n-1)*2; } int main() { int n; printf("input a number: "); scanf("%d",&n); printf("%d \n",PowerTo(n)); return 0; } <file_sep>/palindrome.c #include <stdio.h> /** * Chapter 15 * @topic Challenge * @name Palindrome * @date 03222015 * @author <NAME> */ int main() { char voca[30]; int leng = 0; int i; int true = 1; printf("Enter the voca : "); scanf("%s",voca); for(leng = 0; voca[leng] != '\0'; leng++) { voca[leng]; } for( i = 0; i < leng/2; i++){ if(voca[i] == voca[(leng-1)-i]) { true = 1; }else { true = 0; break; } } if(true == 1) { printf("It is Palindrome ! \n"); }else { printf("It is not Palindrome ! \n"); } return 0; } <file_sep>/studyconstant.c #include <stdio.h> /** * Chapter 4 * @topic constant * @name stduy constant * @date N/A * @author <NAME> */ int main() { char num; printf("num = "); scanf("%c", &num); printf("%c \n",num); return 0; } <file_sep>/googlejam.c #include <stdio.h> /** * Google Code Jam * @topic Standing Ovation * @name 2015 Google Code Jam - A * @date 04112015 * @author <NAME> */ //A solution for 2015 googld code jam - A in small data. int tenPower (int max) { if(max==0){ return 1; }else { return 10 * tenPower(max-1); } } void dothis (int Max, int arr[], int length, int input) { int j = tenPower(Max); int i; if(input < j) { for(i = 0; input/j == 0; i++ ){ arr[i] = 0; j /= 10; } for(; i < Max+ 1 ; i++) { arr[i] = input/j; input = input % j; j /= 10; } }else { for(i = 0; i < Max+1; i++) { arr[i] = input / j; input = input % j; j /= 10; } } for(; i < length; i++ ){ arr[i] = 0; } } int main() { int mShy, input, cases; int arr[7]; int length = sizeof(arr)/sizeof(int); int caseN = 0; scanf("%d",&cases); while(caseN < cases) { int needed = 0; int ppl = arr[0]; scanf("%d %d",&mShy, &input); dothis(mShy,arr,length,input); for (int i = 1; i < mShy+1; i++) { if (arr[i] == 0) { continue; } if (ppl < i) { needed++; ppl++; i--; continue; } ppl += arr[i]; } if(mShy != 0) { if(arr[0] == 0) { needed++; arr[0] = needed; ppl = arr[0]; }else { ppl = arr[0]; } } printf("Case #%d : %d\n",caseN+1,needed); caseN++; } return 0; } <file_sep>/sizeof.c #include <stdio.h> /** * Chapter 2 * @topic Datatype * @name sizeof * @date 12302014 * @author <NAME> */ int main() { char num1 = 2, num2 = 4; short num3 = 300, num4 = 440; printf(" size of num1 and num2 = %d, %d \n", sizeof(num1), sizeof(num2)); printf(" size of num3 and num4 = %d, %d \n", sizeof(num3), sizeof(num4)); printf(" size of char add = %d \n", sizeof(num1+num2)); printf(" size of short add = %d \n", sizeof(num3+num2)); char result1 = num1+num2; short result2 = num3+num4; printf("size of result1 = %d \n", sizeof(result1)); printf("result1 = %d \n", result1); printf("size of result2 = %d \n", sizeof(result2)); printf("result1 = %d \n", result2); return 0; } <file_sep>/studydatatype.c #include <stdio.h> /** * Chapter 4 * @topic Datetype * @name stduy datatype * @date N/A * @author <NAME> */ int main() { int num1=10; int num2=0xD9, num3=0xA2; int num4=014, num5=034; printf("num1 = %d \n", num1); printf("num2 = %d, num3 = %d \n", num2,num3); printf("num4 = %d, num5 = %d \n", num4,num5); return 0; } <file_sep>/Ihave3500.c // A program to find how many bread, snack, and coke I can buy with $35. I have to buy at least one of each. #include <stdio.h> /** * Challenge * @topic loop * @name Ihave35 * @date N/A * @author <NAME> */ const int BREAD = 5; // $ 5.00 const int SNACK = 7; // $ 7.00 const int COKE = 4; // $ 4.00 int main() { int b, s, c; int result; for(b = 1; b<7 ; b++) { for(s = 1; s<5; s++) { for(c = 1; c<8; c++) { result = BREAD*b+SNACK*s+COKE*c; if(result==35) { printf("BREAD : %d \nSNACK : %d \nCOKE : %d\n",b,s,c); } } } printf("\n"); } return 0; } <file_sep>/pointeroperator4.c #include <stdio.h> /** * Chapter 13 * @topic Pointer and Array * @name Pointer Operator * @date 03212015 * @author <NAME> */ int main() { int arr[6] = {1, 2, 3, 4, 5, 6}; int *ptr1 = arr; int *ptr2 = &arr[5]; int i; for(i = 0; i < 3; i++ ){ int temp = *ptr1; *ptr1 = *ptr2; *ptr2 = temp; ptr1++; ptr2--; } for(i = 0; i < 6; i++) { printf("%d ",arr[i]); } return 0; } <file_sep>/powerto.c #include <stdio.h> /** * Practice C * @topic Practice C * @name Practice * @date N/A * @author <NAME> */ int main(void){ int num; int result; printf("num = "); scanf("%d", &num); result=num*num; printf("%d^2=%d",num,result); return 0; } <file_sep>/usefulFuctionPointer.c #include <stdio.h> /** * Chapter 19 * @topic fuction and pointer * @name usefulfuctionpointer * @date 03282015 * @author <NAME> */ int whoisorder (int age1, int age2, int (*ptr)(int, int)) { return ptr(age1, age2); } int isOrder (int age1, int age2) { if(age1 > age2) { return age1; }else{ return age2; } } int main() { int age1, age2; printf("Enter ages to compare : "); scanf("%d %d",&age1,&age2); printf("%d is order than the other. \n",whoisorder(age1,age2,isOrder)); return 0; } <file_sep>/rspgame.c #include <stdio.h> #include <stdlib.h> #include <time.h> int RSP(); int whoWin(int user, int cpt); int lost(int user, int cpt); void YouChose(int rsp); void CPTChose(int cptrsp); int main() { int user, cpt; int winning = 0, drawing = 0; srand((int)time(NULL)); while(1) { printf("Choose Rock (1), Scissors (2), Paper (3) : "); scanf("%d",&user); cpt = RSP(); printf("%d \n",cpt); YouChose(user); CPTChose(cpt); if(whoWin(user, cpt) == 1) { printf("Win! \n"); winning++; continue; }else if(whoWin(user, cpt) == 2) { printf("Draw! \n"); drawing++; continue; }else{ printf("You Lost. \n"); break; } } printf("you win %d times, and you draw %d times \n",winning,drawing); return 0; } int RSP() { return rand() % 3 + 1; } int whoWin(int user, int cpt) { switch(user) { case 1 : if(cpt==1) { return 2; }else if(cpt==2){ return 1; }else { return -1; } case 2 : if(cpt==2) { return 2; }else if(cpt==3){ return 1; }else { return -1; } case 3 : if(cpt==1) { return 1; }else if(cpt==3){ return 2; }else { return -1; } } } void YouChose(int rsp) { switch(rsp) { case 1 : printf("You Choose Rock. \n"); break; case 2 : printf("You Choose Scissors. \n"); break; case 3 : printf("You Choose Paper \n"); break; } } void CPTChose(int cptrsp) { switch(cptrsp) { case 1 : printf("Computer Choose Rock. \n"); break; case 2 : printf("Computer Choose Scissors. \n"); break; case 3 : printf("Computer Choose Paper \n"); break; } } <file_sep>/aaaa.c #include <stdio.h> int main(){ char x[2] = {'c','c'}; if(x[0] = 'c') { printf("!!!"); }else{ printf("????"); } return 0; } <file_sep>/possiblenumbers.c #include <stdio.h> /** * Chapter 8 * @topic Conditional Statement * @name Find all the possible two digit numbers that sum of those is 99 * @date N/A * @author <NAME> */ int main() { int A, Z; int result; for(A = 1; A<10; A++) { for(Z = 1; Z<10; Z++) { if(A==Z) continue; result = (A*10+Z)+(Z*10+A); if(result==99) printf("%d%d+%d%d = %d \n",A,Z,Z,A,result); } } return 0; } <file_sep>/2dArrParam.c #include <stdio.h> /** * Chapter 18 * @topic multidimension array & pointer * @name 2DArrParam * @date 03272015 * @author <NAME> */ void ShowArr( int (*arr)[4], int row) { int i, j; for(i = 0; i < row; i ++) { for( j = 0; j < 4; j++) { printf("%d ", arr[i][j]); } printf("\n"); } } int SumArr ( int (*arr)[4], int row) { int i, j; int sum = 0; for( i = 0; i < row; i ++) { for( j = 0; j < 4; j ++){ sum += arr[i][j]; } } return sum; } int main() { int arr1[2][4] = {1, 2, 3, 4, 5, 6, 7, 8}; int arr2[3][4] = {1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3}; ShowArr(arr1, sizeof(arr1)/sizeof(arr1[0])); printf("\n"); ShowArr(arr2, sizeof(arr2)/sizeof(arr2[0])); printf("\n"); printf("Sum of Arr1 = %d \n", SumArr(arr1, sizeof(arr1)/sizeof(arr1[0]))); printf("Sum of arr2 = %d \n", SumArr(arr2, sizeof(arr2)/sizeof(arr2[0]))); return 0; } <file_sep>/mutipletables.c /* * A program finding multiple tables of even numbers ( from 2 - 9 ) */ #include <stdio.h> /** * Chapter 8 * @topic Conditional Statement * @name Mutiple Tables * @date N/A * @author <NAME> */ int main() { int i,j; for(i=1; i<10; i++) { if(i%2!=0) continue; for(j=1; j<10; j++) { if(i<j) break; printf("%d X %d = %d \n",i,j,i*j); } printf("\n"); } return 0; } <file_sep>/decrecement.c #include <stdio.h> /** * Chapter 3 * @topic Operator * @name decrecement * @date N/A * @author <NAME> */ int main(){ int num1=5; int num2=9; num2=(--num1)+2; //num값을 1 먼저 감소시킨뒤 2를 더함환 num2가 6로 반환 //(num1--)+2를 적용시킬시 num2가 7로 반환 printf("num1=%d \n",num1); printf("num2=%d \n",num2); return 0; } <file_sep>/Hello_World.c #include <stdio.h> /** * Chapter 1 * @topic printf * @name Hello/nWorld/n * @date N/A * @author <NAME> */ int main(void) { printf("Hello \n World \n"); return 1; } <file_sep>/multidimensionarray_2.c /** * Chapter 16 * @topic multidimension array * @name use multidimension array * @date 03232015 * @author <NAME> */ #include <stdio.h> int main() { int arr1[2][4] = { {1, 2, 3, 4}, {5, 6, 7, 8} }; int arr2[4][2]; int i,j; for( i = 0; i < 4; i++) { for( j = 0; j < 2; j++){ arr2[i][j] = arr1[j][i]; } } for( i = 0; i < 4; i++) { for( j = 0; j < 2; j++){ printf("%d ",arr2[i][j]); } printf("\n"); } return 0; } <file_sep>/randomNumber.c #include <stdio.h> #include <stdlib.h> int rand(void); /** * Chapter 20 * @topic Random Number * @name Random Number * @date 04042015 * @author <NAME> */ int main() { printf("the range of the random number from 0 to 99 \n"); for(int i = 0; i < 5; i ++) { printf("Random number : %d \n",rand()%100); } return 0; } <file_sep>/positivenegative.c #include <stdio.h> /** * Chapter 3 * @topic Operator * @name positivenegative * @date N/A * @author <NAME> */ int main(void) { int num1= + 4 ; int num2= - 3 ; num1 = -num1; num2 = -num2; printf("%d \n", num1); printf("%d \n", num2); return 0; } <file_sep>/sumoperator.c #include <stdio.h> /** * Chapter 3 * @topic Operator * @name sum * @date N/A * @author <NAME> */ int main() { int num1, num2, num3; int result; printf("num1 = "); scanf("%d", &num1); printf("num2 = "); scanf("%d", &num2); printf("num3 = "); scanf("%d", &num3); num1 += 3; num2 = (--num3)+2; result = num1 + num2 + num3; printf("num1 = %d \nnum2 = %d \nnum3 = %d \n", num1,num2,num3); printf("%d + %d + %d = %d \n", num1,num2,num3,result); return 0; } <file_sep>/datatype.c #include <stdio.h> /** * Chapter 4 * @topic Datatype * @name stduy datatype * @date N/A * @author <NAME> */ int main() { int n; printf("input number: "); scanf("%d",&n); n = ~ n; printf("%d \n",n+1); return 0; } <file_sep>/twotothepowerK.c #include <stdio.h> /** * Chapter 10 * @topic Challenge * @name 2^k <= num * @date 03212015 * @author <NAME> */ int main() { int cnt = 0; int num, i; printf("Enter the integer : "); scanf("%d",&num); for(i = 1; i < num; i *= 2){ cnt++; } printf("2^%d <= %d \n",cnt,num); return 0; } <file_sep>/fuctionpointer.c #include <stdio.h> /** * Chapter 19 * @topic fuction and pointer * @name fuctionpointer * @date 03282015 * @author <NAME> */ int adder(int num1, int num2) { return num1 + num2; } void showstring (char *str) { printf("%s \n",str); } int main() { int num1 = 10, num2 = 20; char *str = "Hello World!"; int (*fptr1)(int,int) = adder; void (*fptr2)(char *) = showstring; printf("%d \n",fptr1(num1,num2)); fptr2(str); return 0; } <file_sep>/fizzbizz.c #include <stdio.h> /** * Practice C * @topic Practice C * @name fizzbizz * @date N/A * @author <NAME> */ int main() { int n; for(n=1 ; n<=100; n++) { if(n%3!=0 && n%5!=0) { printf("%d",n); } if(n%3==0){ printf("fizz"); } if(n%5==0){ printf("bizz"); } printf("\n"); } return 0; } <file_sep>/Chapter7-19.c #include <stdio.h> /** * Chapter 7 * @topic conditional statement * @name study while loop * @date N/A * @author <NAME> */ int main() { int n; int j = 1; printf("input number: "); scanf("%d",&n); while(j<=n) { printf("%d x %d = %d \n",n, j, n*j); j++; } return 0; } <file_sep>/morethanonefuction.c #include <stdio.h> /** * Chapter 8 * @topic fuction * @name morethanonefuction * @date 01152015 * @author <NAME> */ int Add(int num1, int num2) { return num1+num2; } void ShowAddResult(int num) { printf("The sum : %d \n",num); } int ReadNum(void) { int num; scanf("%d",&num); return num; } void HowToUseThisProg(void) { printf("the sum of entered numbers will display. \n"); printf("Enter two numbers : \n"); } int main() { int result, num1, num2; HowToUseThisProg(); num1 = ReadNum(); num2 = ReadNum(); result = Add(num1,num2); ShowAddResult(result); return 0; } <file_sep>/lengthofarray.c #include <stdio.h> /** * Chapter 8 * @topic Array * @name find length of arrays and a letter having biggest number as ascii * @date 12302014 * @author <NAME> */ int main() { char voca[100]; char max; int leng = 0; int i; printf("Enter a voca : "); scanf("%s",voca); while(voca[leng] != '\0' ) { leng++; } printf("length of the voca : %d \n",leng); max = voca[0]; for(i = 0; i < leng; i++) { if(max < voca[i]) { max = voca[i]; } } printf("%c \n", max); return 0; } <file_sep>/fibonaccisequence.c /* This is a program printing Fibonacci Sequence. It will print amount of numbers that the user enters. */ #include <stdio.h> /** * Practice * @topic function * @name Fibonacci Sequence. * @date n/a * @author <NAME> */ void FineSerises(int n) { int f1, f2, f3; int i; f1 = 0; f2 = 1; if(n==1) { printf("%d ",f1); } else { printf("%d %d ",f1,f2); } for(i=0 ; i<n-2; i++) { f3 = f1 + f2; printf("%d ",f3); f1=f2; f2=f3; } } int main(void) { int n; printf("input number : "); scanf("%d",&n); if(n<1) { printf("1 이상의 값을 입력하시오 \n"); return 0; } FineSerises(n); return 0; } <file_sep>/sizeofarray.c #include <stdio.h> /** * Chapter 9 * @topic Array * @name lengthofarrays * @date 02182015 * @author <NAME> */ int main() { char voca[100]; int leng; printf("Enter a voca: "); scanf("%s",voca); while(voca[leng] != '\0') { leng++; } printf("A length of the entered voca : %d \n",leng); return 0; } <file_sep>/ArrayParam.c #include <stdio.h> /** * Chapter 14 * @topic Pointer and Fuction * @name ArrayProgram * @date 03222015 * @author <NAME> */ void ShowArrayElem(int *ptr, int length) { int i; for( i = 0; i < length; i ++) { printf("%d ",ptr[i]); } printf("\n"); } int main() { int arr1[3] = { 1, 2, 3}; int arr2[5] = { 1, 2, 3, 4, 5}; ShowArrayElem(arr1, sizeof(arr1)/sizeof(int)); ShowArrayElem(arr2, sizeof(arr2)/sizeof(int)); return 0; } <file_sep>/repeatHelloWorld.c // A program that prints "Hello World" as many as the user wants to by entering number. #include <stdio.h> /** * Chapter 7 * @topic Loop * @name Practicing Loop * @date N/A * @author <NAME> */ int main() { int num; int i = 0; printf("Repeat Number : "); scanf("%d",&num); while(i<num) { printf("Hello World! %d \n",i); i++; } return 0; } <file_sep>/varietyoperator.c #include <stdio.h> /** * Chapter 3 * @topic Operator * @name varietiesoperator * @date N/A * @author <NAME> */ int main() { int num1=3, num2=5, num3=9; num1 += 3; num2 -= 2; num3 *= 2; printf("Result = %d, %d, %d \n", num1,num2,num3); return 0; } <file_sep>/AddTwoNumbers.c #include <stdio.h> /** * Chapter 3 * @topic Operator * @name Addtwonumbers * @date N/A * @author <NAME> */ int main() { int num1, num2; int result; printf("num1 : "); scanf("%d", &num1); printf("num2 : "); scanf("%d", &num2); result = num1+num2; printf("%d + %d = %d \n", num1,num2,result); return 0; } <file_sep>/comparetwonumbers.c #include <stdio.h> /** * Chapter 8 * @topic Fuction * @name Compare two numbers * @date 01152015 * @author <NAME> */ double NumberCompare(double num1, double num2); int main(){ double num1, num2; printf("Enter two numbers to compare: "); scanf("%lf %lf",&num1,&num2); printf("Between %f and %f, the bigger number is %f.\n",num1,num2,NumberCompare(num1,num2)); return 0; } double NumberCompare(double num1, double num2) { if(num1>num2) return num1; else return num2; } <file_sep>/practiceDoWhile2.c #include <stdio.h> /** * Chapter 7 * @topic Loop * @name practicing do-while 2 * @date N/A * @author <NAME> */ int main() { int num = 0, total = 0; do { total+=num; num=num+2; }while(num<=100); printf("Sum of even numbers that are less or equal to 100 : %d \n",total); return 0; } <file_sep>/Chapter7-20.c #include <stdio.h> /** * Chapter 7 * @topic conditional statement * @name study while loop * @date N/A * @author <NAME> */ int main() { int n; int i = 1; printf("input number: "); scanf("%d",&n); while(i<=n) { printf("Hello World! %d \n",i); i++; } return 0; } <file_sep>/fuctionwitharray.c #include <stdio.h> /** * Chapter 9 * @topic Array * @name find total, biggest number, and smallest number * @date N/A * @author <NAME> */ int main() { int arr[5]; int total,max,min; int i; for(i = 0; i<5; i++) { printf("input number: "); scanf("%d",&arr[i]); total+=arr[i]; } max=min=arr[0]; for(i = 0; i<5; i++) { if(max<arr[i]) max=arr[i]; if(min>arr[i]) min=arr[i]; } printf("%d \n",total); printf("%d \n",max); printf("%d \n",min); return 0; } <file_sep>/addandsubstract.c #include <stdio.h> /** * Chapter 8 * @topic fuction * @name addsubstract * @date 01152015 * @author <NAME> */ int Add(int num1, int num2) { return num1 + num2; } int Substract(int num1, int num2) { if(num1>num2) return num1 - num2; else return num2 - num1; } int main() { int num1, num2; int result; int input; printf("to add, enter 1 and to substract, enter 2 : "); scanf("%d",&input); if(input==1) { printf("Enter two numbers"); scanf("%d %d",&num1,&num2); result = Add(num1,num2); printf(" %d + %d = %d \n",num1,num2,result); } else { printf("Enter two numbers : "); scanf("%d %d",&num1,&num2); result = Substract(num1,num2); if(num1>num2) printf("%d - %d = %d \n",num1,num2,result); else printf("%d - %d = %d \n",num2,num1,result); } return 0; } <file_sep>/HMS.c // A program to print hours, minutes, and seconds when the user inputs seconds. #include <stdio.h> /** * Challenge * @topic N/A * @name findtime * @date N/A * @author <NAME> */ const int H=3600; const int M=60; int main() { int h,m,s; printf("input seconds : "); scanf("%d",&s); h=s/H; s=s%H; m=s/M; s=s%M; s=s; printf("H : %d \nM : %d\nS : %d \n",h,m,s); return 0; } <file_sep>/findGCD.c /* * A program that finds GCD of the numbers that the user input. */ #include <stdio.h> /** * Chapter 5 * @topic Challege * @name find GCD * @date N/A * @author <NAME> */ int GCD(int n1, int n2) { int i; if(n1<n2){ for(i = n1; i>0; i--){ if(n1%i==0 && n2%i==0){ return i; } } } } int main() { int n1, n2; printf("input two number : "); scanf("%d %d",&n1,&n2); if(n1<n2) { printf("GCD : %d \n",GCD(n1,n2)); } else { printf("GCD : %d \n",GCD(n2,n1)); } return 0; } <file_sep>/studyoperator7.c #include <stdio.h> /** * Chapter 3 * @topic Operator * @name * @date N/A * @author <NAME> */ int main() { int num1=5, num2=7; int result; result = (!(num1 > 7 || num2 == 7)); printf("result = %d \n", result); //0 is false, other numbers are true. return 0; } <file_sep>/10primenumbers.c #include <stdio.h> /** * Challenge * @topic fuction * @name 10primenumbers * @date N/A * @author <NAME> */ int IsPrime (int n) { int i; int cnt = 0; for(i = 1; i < n; i++){ if(n%i==0) { cnt++; } } if(cnt==1){ return 1; } } int main() { int cnt = 0; int n = 3; printf("2 "); while(cnt!=9) { if(IsPrime(n)==1) { printf("%d ",n); cnt++; } n++; } return 0; } <file_sep>/gradechart.c /** * Chapter 16 * @topic multidimension array * @name grade chart * @date 03232015 * @author <NAME> */ #include <stdio.h> int arr[5][5]; void Writerecord (void) { int i,j; int sum; int total; for(i = 0; i < 4; i ++) { sum = 0; switch(i) { case 0 : printf("Enter Jake's grade \n"); break; case 1 : printf("Enter Julie's grade \n"); break; case 2 : printf("Enter Lynn's grade \n"); break; case 3 : printf("Enter Micheal's grade \n"); break; } for(j = 0; j < 4; j++ ) { switch(j) { case 0 : printf("History : "); break; case 1 : printf("Mathematics : "); break; case 2 : printf("Literature : "); break; case 3 : printf("Science : "); break; } scanf("%d", &arr[i][j]); sum += arr[i][j]; } arr[i][4] = sum; total += sum; arr[4][4] = total; printf("\n"); } } void Sumofrecord (void) { int sum = 0; int i,j; for( i = 0; i < 4; i ++ ){ sum = 0; for( j = 0; j < 4; j ++) { sum += arr[j][i]; } arr[4][i] = sum; } } int main() { int i, j; Writerecord(); Sumofrecord(); printf("Name History Mathematics Literature Science Total\n"); for( i = 0; i < 5; i ++) { switch(i) { case 0 : printf("Jake"); break; case 1 : printf("Rick"); break; case 2 : printf("Lynn"); break; case 3 : printf("Mike"); break; default : printf(" "); } for(j = 0; j < 5; j++ ) { printf("%8d ",arr[i][j]); } printf("\n"); } return 0; } <file_sep>/twopowerto2.c #include <stdio.h> /** * Chapter 10 * @topic Challenge * @name recursive fuction * @date 03212015 * @author <NAME> */ int twopowerto (int num){ if(num == 0){ return 1; }else{ return 2 * twopowerto(num-1); } } int main() { int num; printf("Enter the number : "); scanf("%d",&num); printf("%d",twopowerto(num)); return 0; } <file_sep>/dividing.c #include <stdio.h> /** * C practice * @topic Datatypes * @name divide the two numbers * @date N/A * @author <NAME> */ int main() { int num1 = 5, num2 = 8; double divResult; divResult = (double)num1/num2; printf(" Result of dividing = %f \n", divResult); return 0; } <file_sep>/practiceSwitch.c #include <stdio.h> /** * Chapter 8 * @topic Conditional Statement * @name Swtich Practice * @date N/A * @author <NAME> */ int main() { int num; do{ printf("Enter the number ( 1 to 5 ) = "); scanf("%d",&num); }while(num < 1 && num > 5); //ask to enter the number from 1 to 5 unti the user enters the number in the range. switch(num) { case 1: printf("1 is ONE \n"); break; case 2: printf("2 is TWO \n"); break; case 3: printf("3 is THREE \n"); break; case 4: printf("4 is FOUR \n"); break; case 5: printf("5 is FIVE \n"); break; } return 0; } <file_sep>/Chapter7-16.c #include <stdio.h> /** * Chapter 7 * @topic Loop * @name Loop * @date N/A * @author <NAME> */ int main() { int num = 2; int sum = 0; do { sum += num; num = num+2; }while(num<=100); printf("total : %d \n",sum); return 0; } <file_sep>/findEvenOrOdd.c // a program identifying the ten numbers that given by the user are odd or even #include <stdio.h> /** * Pratice * @topic Array * @name findEvenNOdd * @date N/A * @author <NAME> */ int main() { int arr[10]; int i; printf("----Enter ten numbers---- \n"); for(i = 0; i<10; i++) { printf("%d : ",i+1); scanf("%d",&arr[i]); } printf("----------------------\neven number: "); for( i = 0; i<10; i++) { if(arr[i]%2==0) printf("%d ",arr[i]); } printf("\nodd number: "); for( i = 0; i<10; i++) { if(arr[i]%2!=0) printf("%d ",arr[i]); } return 0; } <file_sep>/staticFuction.c // A program that prints sum of three numbers given by the user. ( it is written to understand static fuction.) #include <stdio.h> /** * Chapter 9 * @topic Fuction * @name staticfunction * @date N/A * @author <NAME> */ int AddToTotal(int num) { static int total = 0; total += num; return total; } int main() { int num, i; int sum; printf("Enter three numbers to sum\n"); for(i=0 ;i<3 ; i++) { printf("%d : ", i+1); scanf("%d",&num); sum = AddToTotal(num); } printf("Total of the numbers : %d \n",sum); return 0; } <file_sep>/Tree.c #include <stdio.h> //make a Christmas tree /** * For Fun * @topic loop * @name A Christmas tree * @date 040915 * @author <NAME> */ int main() { int num, k = 0; int cnt = 0; char c = 'S'; printf("Enter number for levels of the tree : "); scanf("%d",&num); while(num > 0){ do { for( int i = 0; i < num - 1; i++) { printf(" "); } for(int j = 0; j < (cnt * 2) + 1; j++) { printf("%c", c); c = '*'; } printf("\n"); k++; }while(k < 2); cnt ++; num --; } return 0; } <file_sep>/studyoperator8.c #include <stdio.h> /** * Chapter 3 * @topic Operator * @name Study operator * @date N/A * @author <NAME> */ int main(void) { int num1 = 14, num2 = 8; int result1, result2; printf("num1 = %d, num2 = %d \n", num1,num2); num1 += (++num2); printf("num1 = %d, num2 = %d \n", num1,num2); result1= (num1 == 23 && num2 == 9); result2= ((num1 + 2 < 30) && (num2 -= (--num1) != -39)); printf("num1 = %d, num2 = %d \n", num1,num2); printf("result1 = %d \n", result1); printf("result2 = %d \n", result2); return 0; } <file_sep>/ArrayNameType.c // A program that prints a number of the array #include <stdio.h> /** * Chapter 13 * @topic Pointer and Array * @name Array Nume * @date N/A * @author <NAME> */ int main() { int arr[3] = { 1, 3, 3}; *arr = 2; printf("name of the arry : %p \n",arr); printf("%d \n",arr[0]); return 0; } <file_sep>/myworkoutchart.c /* WORKOUT WEEK 2 DATE : 12.23.14 */ #include <stdio.h> /** * Chapter 2 * @topic Datatype * @name my workout chart * @date 12232014 * @author <NAME> */ int main() { int num1 = 1, num2 = num1<<1, num3 = ++num2; printf("WORKOUT WEEK2 - Pushup & Squat Max \n"); printf("Day %d \n Pushup - 32 \n Squat - 137 \n", num1); printf("Day %d \n Pushup - 41 \n Squat - 148 \n", num2); printf("Day %d \n Pushup - 40 \n Squat - 150 \n", num3); return 0; } <file_sep>/factorial.c #include <stdio.h> /** * Chapter 7 * @topic Loop * @name factorial * @date N/A * @author <NAME> */ int main() { int num; int result=1; printf(" number : "); scanf("%d",&num); for( ; num!=0; num--){ result=result*num; } printf("factorial of the number : %d \n", result); return 0; } <file_sep>/differentdatatype.c #include <stdio.h> /** * Practice C * @topic Practice C * @name Practice * @date N/A * @author <NAME> */ int main() { double num1 = 245; int num2 = 2.45; int num3 = 245; char ch = num3; printf(" 정수 245를 실수로 : %f \n", num1); printf(" 실수 2.45를 정수로 : %d \n", num2); printf(" 큰 정수 129를 작은 정수로 : %d \n", ch); return 0; } <file_sep>/swtichWithChar.c #include <stdio.h> /** * Chapter 8 * @topic Conditional Statement * @name Practice Switch with characters * @date N/A * @author <NAME> */ int main() { char sel; printf("M is morning, A is afternoon, E is evening \n"); printf("Enter a letter (M ,A, or E) : "); scanf("%c",&sel); switch(sel) { case 'm': case 'M': printf("Morning \n"); break; case 'a': case 'A': printf("Afternoon \n"); break; case 'e': case 'E': printf("Evening \n"); break; default: printf("N/A \n"); } return 0; } <file_sep>/Bytestudy3.c #include <stdio.h> /** * Chapter 4 * @topic Byte * @name Study Byte * @date N/A * @author <NAME> */ int main() { int num1 = 14 ; //00000000 00000000 00000000 00001110 int num2 = 6 ; //00000000 00000000 00000000 00001010 int num3 = num1&num2 ; //00000000 00000000 0000000 00001010 printf(" result of AND : %d \n", num3); return 0; } <file_sep>/charArray.c #include <stdio.h> /** * Chapter 9 * @topic Array * @name Char Array * @date N/A * @author <NAME> */ int main() { char gt[]={'G','o','o','d',' ','t','i','m','e'}; int arrLen=sizeof(gt)/sizeof(char); int i; for(i = 0; i<arrLen; i++) printf("%c", gt[i]); return 0; } <file_sep>/manyHelloWorlds.c #include <stdio.h> /** * Chapter 1 * @topic printf * @name I love Hello World * @date N/A * @author <NAME> */ int main() { printf("I say Hello World \a \n"); printf("I say \" Hello World! \" \n"); printf("I say \b Hello Worldd\b You say Hello World \n"); printf("I say Hello \r Wolrd \n"); printf("I say \t Hello World \n"); printf("I say \' Hello World \' \n"); printf("Do I say Hello World \? \n"); printf("I say Hello World \\ \n"); return 0; } <file_sep>/Tobinary.c #include <stdio.h> /** * Chapter 15 * @topic Challenge * @name to binary * @date 03222015 * @author <NAME> */ //num / 2 = sth, sth / 2 = other int dividebytwo (int num) { if(num > 0){ dividebytwo(num/2); printf("num : %d \n",num); printf("%d \n",num%2); return 1; }else { return 0; } } int main() { int num ; printf("Enter the number : "); scanf("%d", &num); dividebytwo(num); return 0; }
dde511383c6cd1041bba2729eeb544a4d6df8cde
[ "C" ]
131
C
kch5559/C
18f4123ef1312b685093adcffbae69ccc86cd3aa
7de771a045e898df56a28408c9260d6a1ccc8b59
refs/heads/master
<file_sep>#include "DXUT.h" #include "Main.h" Main::Main() { } Main::~Main() { } void Main::Init() { mesh = LOADER->AddMesh("Gun",L"media\\cup.obj"); } void Main::Update() { } void Main::Render() { RENDER3D->Render(mesh,Vec3(0,0,0)); } void Main::Release() { } void Main::ResetDevice() { } void Main::LostDevice() { } <file_sep>#pragma once #include "singleton.h" struct Texture { public: LPDIRECT3DTEXTURE9 texturePtr; D3DXIMAGE_INFO info; public: Texture(LPDIRECT3DTEXTURE9 texturePtr, D3DXIMAGE_INFO info) :texturePtr(texturePtr), info(info) { } ~Texture() { } }; struct MultiTexture { public: list<Texture*> l_Texture; public: MultiTexture(Texture * texturePtr) { l_Texture.push_back(texturePtr); } ~MultiTexture() { } }; struct Mesh { public: LPD3DXMESH pMesh; vector<Material*> v_Matrial; public: Mesh() {} ~Mesh() { SAFE_DELETE(pMesh); v_Matrial.clear(); } }; class LoadManager :public singleton<LoadManager> { private: map <string, Texture*>m_Texture; map <string, MultiTexture*> m_MultiTexture; map <string,Mesh*> m_Mesh; public: LoadManager(); ~LoadManager(); public: Texture* AddImage(const string& key, const string& path); MultiTexture* AddImages(const string& key, const string& path, int count = 0); Texture* FindImage(const string& key); MultiTexture* FindImages(const string& key,int count = 0); Mesh* AddMesh(const string& key, const wstring& strFilename); Mesh* FindMesh(const string & key); }; #define LOADER LoadManager::GetInstance() <file_sep>#include "DXUT.h" #include "LoadManager.h" LoadManager::LoadManager() { } LoadManager::~LoadManager() { } Texture* LoadManager::AddImage(const string& key, const string& path) { auto find = m_Texture.find(key); if (find == m_Texture.end()) { D3DXIMAGE_INFO info; LPDIRECT3DTEXTURE9 texturePtr; if (D3DXCreateTextureFromFileExA(Device, path.c_str(), -2, -2, 0, 0, D3DFMT_UNKNOWN, D3DPOOL_DEFAULT, -1, -1, 0, &info, nullptr, &texturePtr) == S_OK) { Texture* text = new Texture(texturePtr, info); m_Texture[key] = text; return text; } return nullptr; } return find->second; } MultiTexture* LoadManager::AddImages(const string& key, const string& Folder, int count) { auto find = m_MultiTexture.find(key); if (find == m_MultiTexture.end()) { D3DXIMAGE_INFO info; LPDIRECT3DTEXTURE9 texturePtr; for (int i = 0; i > count; i++) { char a; sprintf(&a,"./Resouce/image/",Folder,"/",count,".png"); if (D3DXCreateTextureFromFileExA(Device, to_string(a).c_str(), -2, -2, 0, 0, D3DFMT_UNKNOWN, D3DPOOL_DEFAULT, -1, -1, 0, &info, nullptr, &texturePtr) == S_OK) { Texture* text = new Texture(texturePtr, info); MultiTexture* Multi = new MultiTexture(text); m_MultiTexture[key] = Multi; if (i == count) { return Multi; } } } return nullptr; } return find->second; } Texture* LoadManager::FindImage(const string& key) { auto find = m_Texture.find(key); if (find == m_Texture.end()) { return nullptr; } return find->second; } MultiTexture* LoadManager::FindImages(const string& key, int count) { auto find = m_MultiTexture.find(key); if (find == m_MultiTexture.end()) { return nullptr; } return find->second; } Mesh* LoadManager::AddMesh(const string& key, const wstring& strFilename) { auto find = m_Mesh.find(key); if (find != m_Mesh.end()) { return find->second; } CMeshLoader* pMeshLoader = new CMeshLoader(); pMeshLoader->Create(Device, strFilename); if (pMeshLoader->GetMesh() == nullptr) { SAFE_DELETE(pMeshLoader); return nullptr; } Mesh* mesh = new Mesh(); mesh->pMesh = pMeshLoader->GetMesh(); for (int i = 0; i < pMeshLoader->GetNumMaterials(); i++) { mesh->v_Matrial.push_back(pMeshLoader->GetMaterial(i)); } m_Mesh[key.c_str()] = mesh; SAFE_DELETE(pMeshLoader); return mesh; } Mesh* LoadManager::FindMesh(const string& key) { auto find = m_Mesh.find(key); if (find == m_Mesh.end()) { return nullptr; } return find->second; } <file_sep>#include "DXUT.h" #include "Render3DManager.h" Render3DManager::Render3DManager() { } Render3DManager::~Render3DManager() { } void Render3DManager::Render(Mesh* mesh, Vec3 pos, Vec3 rot, Vec3 size, D3DXCOLOR color) { D3DXMATRIX matP, matS, matR, matW,RotX,RotY,RotZ; D3DXMatrixTranslation(&matP, pos.x,pos.y,pos.z); D3DXMatrixScaling(&matS,size.x,size.y,size.z); D3DXMatrixRotationX(&RotX,rot.x); D3DXMatrixRotationY(&RotY,rot.y); D3DXMatrixRotationZ(&RotY, rot.z); matR = RotX * RotY * RotZ; matW = matR * matP * matS; Device->SetTransform(D3DTS_WORLD,&matW); int i = 0; for (auto iter : mesh->v_Matrial) { iter->material.Emissive = color; Device->SetTexture(0, iter->pTexture); Device->SetMaterial(&iter->material); mesh->pMesh->DrawSubset(i); i++; } D3DXMATRIX mat; D3DXMatrixIdentity(&mat); Device->SetTransform(D3DTS_WORLD,&mat); } <file_sep>#pragma once #include "singleton.h" class Render3DManager : public singleton<Render3DManager> { private: public: Render3DManager(); ~Render3DManager(); public: void Render(Mesh * mesh,Vec3 pos, Vec3 rot = Vec3(0, 0, 0),Vec3 size = Vec3(1,1,1) ,D3DXCOLOR color = D3DCOLOR_XRGB(255,255,255)); }; #define RENDER3D Render3DManager::GetInstance()<file_sep>#pragma once #include <iostream> #include <math.h> #include <algorithm> #include <list> #include <vector> #include <map> #include <istream> #include <ostream> #include <string> using namespace std; static float TimeScale = 1; #define Device DXUTGetD3D9Device() #define Vec2 D3DXVECTOR2 #define Vec3 D3DXVECTOR3 #define DTime DXUTGetElapsedTime() * TimeScale inline const int WINSIZEX = 1920; inline const int WINSIZEY = 1080; #include "MeshLoader.h" #include "LoadManager.h" #include "Render2DManager.h" #include "Render3DManager.h"
211ebf4008c3b8455e5cd5bdf8caac42f8236729
[ "C++" ]
6
C++
taewooo0513/taewooo7
a32152101fe122928101f6e3dfc45d084b333602
5b2b998a11db6004c642aaedcad136aafc381f29
refs/heads/master
<file_sep>var ping = require('ping'); var mysql = require('mysql'); const ckTerms = () => { var connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '<PASSWORD>', database: 'mander' }) var hosts = [ 'google.com', // internet is live '192.168.1.112', '192.168.1.113', '192.168.1.114', '192.168.1.115', '192.168.1.116', '192.168.1.117', '192.168.1.118', '192.168.1.119', '192.168.1.120', '192.168.1.121', '192.168.1.122', '192.168.1.123', '192.168.1.124', '192.168.1.125', '192.168.1.126', '192.168.1.127', '192.168.1.128', '192.168.1.129' ] connection.connect() connection.query('SELECT 1 + 1 AS solution', (error, results, fields) => { if (error) throw error console.log('The solution is: ', results[0].solution) }) hosts.forEach( (host) => { ping.sys.probe(host, (isAlive) => { var msg = isAlive ? 'host ' + host + ' is alive' : 'host ' + host + ' is dead' console.log(msg) }) }) connection.end() } setInterval(ckTerms, 500) <file_sep># pingTerms experimenting node (ping and mysql module) to monitor online devices with ping and log into MySQL
073b9eb3dc9c7b5c6b7e5aeff93bd72fed458c7c
[ "JavaScript", "Markdown" ]
2
JavaScript
andyj115/pingTerms
a5f6bc57579c10a65adf4f1cfc165c027978a2b4
e841da7e50f355cfb71d4f6f20120627c40167f9
refs/heads/master
<file_sep>$(document).ready(function () { //账号登录 $("#login").click(function () { window.location.href = "login.html"; }); //刷新验证码 $("#refresh_vcode").click(function () { $("#refresh_vcode").attr('src', "https://jkdev.cn/show_code.php"); }); });<file_sep># bootStrap响应式登录与注册界面 基于BootStrap 效果如下: <img src="./img.png"> <br> <img src="./img2.png">
54ec51da9f66ef25e31a2f98dce155f2a0a35957
[ "JavaScript", "Markdown" ]
2
JavaScript
Pillow520/HTML-BootStrap-Login
3596915903621282e2f90f7d8fe8979185cb093b
eabda9e6e8b1ad096b402fb1a46efa5221da73fd
refs/heads/master
<repo_name>Cyancey96/python_challenge<file_sep>/README.md # python_challenge How to run: Put any files you want the program to be able to save/load to in the Files folder. Run main.py using Python 3.7 Provided Files: TESTFILE_IPS.txt - Used by unit tests TESTFILE_LOAD.txt - Used by unit tests list_of_ips.txt - Text file containing 5000 IPs. Load IPs into the program with the "Get IPs" button. list_of_ips_RESULTS.txt - Text file containing responses for IPs in list_of_ips.txt. Load into the program using "Load Responses" to skip the IP Lookup process. small_list_of_ips.txt - Text file containing 100 IPs. I recommend using this file if you want to try out IP Lookup. Navigating the UI: Get IPs- Located at the top of the UI. Clicking this button will check the Files folder for a file with the same name in the box left to the button and populate the IP List with any IPs found in the file. IP Lookup- Located at the left of the UI. Clicking this button will look up Geo IP data for all IPs in the list. Progress can be checked from the terminal window. Results are populated in the Responses list. Save/Load Responses- 3 buttons located at the bottom of the UI. "Load Responses" will load a file from the Files folder into the Responses list. "Save Filtered Responses" will save a list of filtered responses to a file if a filter is applied. "Save Responses" will save all responses to to a file, including filtered responses. The file used by these buttons is specified using the textbox above them. Filter Responses- Located in the bottom-right of the UI. Clicking this will filter out responses from the Responses list using a Query provided in the textbox to the left of the button. These responses can be saved using the "Save Filtered Responses" button. See below for Query Language details. Clear Filter- Located in the bottom-right of the UI. Clicking this will remove a filter and display the original list of responses in the Responses window. Query Language: Grammar - <key><operator><value>:<key><operator><value> ':' is used to seperate statements. Operators: '='- Equals, can be used with strings and numbers '!='- Not equals, can be used with strings and numbers '<'- Less than, can be used with numbers '>'- Greater than, can be used with numbers '<='- Less than or equal, can be used with numbers '>=' Greater than or equal, can be used with numbers Query Language Examples: "ip=1.1.1.1"- Filters responses with an ip of "1.1.1.1" "country_code!=JP:latitude<0"- Filters responses with a latitude less than 0 if JP is not their country_code "country_code=US:zip_code=:longitude>=0" - Filters responses with a country_code of "US", a blank zip code, and a longitude greater than or equal to 0. Running Unit/Integration Tests: You can get pytest using "pip install pytest". You can run unit tests using "pytest unit_tests.py" and you can run integration tests using "pytest integration_tests.py". <file_sep>/functions.py import sys import re import json import urllib.error as er import urllib.request as req '''Parses IPs from a filename into a list of IPs''' def parse_file(filename): file = open(f"Files/{filename}") file_string = file.read() r = re.compile(r"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})") return r.findall(file_string) '''Populates Geo IP data into geo_list using IPs in ip_list''' def geo_lookup_ips(list_of_ips): geolist = [] error_list = [] base_url = "https://freegeoip.app" response_type = "json" counter = 0 # First run for ip in list_of_ips: counter += 1 try: res = json.loads(response(base_url, response_type, ip)) except er.HTTPError: print(f'{counter}/{len(list_of_ips)}: Error retrieving info for ip: {ip}', file=sys.stderr) error_list.append(ip) else: geolist.append(res) print(f'{counter}/{len(list_of_ips)}: Success retrieving info for ip: {ip}') # Retry getting info for ips that failed while len(error_list) > 0: counter = 0 original_error_list_len = len(error_list) for ip in error_list: counter += 1 try: res = json.loads(response(base_url, response_type, ip)) except er.HTTPError: print(f'{counter}/{original_error_list_len}: Error retrieving info for ip: {ip}', file=sys.stderr) else: error_list.remove(ip) geolist.append(res) print(f'{counter}/{original_error_list_len}: Success retrieving info for ip: {ip}') return geolist '''Returns response for an api call''' def response(base_url, response_type, ip_address): with req.urlopen(f'{base_url}/{response_type}/{ip_address}') as res: return res.read() '''Saves geodata to a file with the name in geo_filename_entry''' def save_geodata(filename, geo_data): file = open(f"Files/{filename}", 'w') json.dump(geo_data, file) '''Loads geodata from a file with the name in geo_filename_entry''' def load_geodata(filename): file = open(f"Files/{filename}", 'r') return json.load(file) '''Filters geo_list and stores results in filtered_geo_list and updates filtered results to GUI''' def filter_response(geo_data, query_string): return list(filter(lambda x: filter_query(x, query_string), geo_data)) '''Contains logic for filtering geo_data using a query stored in filter_entry''' def filter_query(geo_data, query_string): filter_bool = True queries = re.split(":", query_string) for query in queries: keyvals = re.split("(!=|<=|>=|<|>|=)", query) try: if keyvals[0] not in geo_data: filter_bool = False elif keyvals[1] == "<" and float(geo_data[keyvals[0]]) >= float(keyvals[2]): filter_bool = False elif keyvals[1] == ">" and float(geo_data[keyvals[0]]) <= float(keyvals[2]): filter_bool = False elif keyvals[1] == "<=" and float(geo_data[keyvals[0]]) > float(keyvals[2]): filter_bool = False elif keyvals[1] == ">=" and float(geo_data[keyvals[0]]) < float(keyvals[2]): filter_bool = False elif keyvals[1] == "!=" and float(geo_data[keyvals[0]]) == float(keyvals[2]): filter_bool = False elif keyvals[1] == "=" and float(geo_data[keyvals[0]]) != float(keyvals[2]): filter_bool = False except ValueError: try: if keyvals[1] == "!=" and geo_data[keyvals[0]] == keyvals[2]: filter_bool = False elif keyvals[1] == "=" and geo_data[keyvals[0]] != keyvals[2]: filter_bool = False except ValueError: print(f"ValueError: {geo_data[keyvals[0]]}", file=sys.stderr) filter_bool = False return filter_bool <file_sep>/integration_tests.py from functions import * def test_geo_lookup_ips(): ip_list = ['1.1.1.1', '2.2.2.2'] expected_geo_list = [{"ip": "1.1.1.1", "country_code": "AU", "country_name": "Australia", "region_code": "", "region_name": "", "city": "", "zip_code": "", "time_zone": "Australia/Sydney", "latitude": -33.494, "longitude": 143.2104, "metro_code": 0}, {"ip": "2.2.2.2", "country_code": "FR", "country_name": "France", "region_code": "", "region_name": "", "city": "", "zip_code": "", "time_zone": "Europe/Paris", "latitude": 48.8582, "longitude": 2.3387, "metro_code": 0}] actual_geo_list = geo_lookup_ips(ip_list) assert expected_geo_list == actual_geo_list <file_sep>/unit_tests.py import os from functions import * def test_parse_file(): expected_ip_list = ['244.36.171.60', '241.189.201.17', '172.16.58.3'] actual_ip_list = parse_file("TESTFILE_IPS.txt") assert actual_ip_list == expected_ip_list def test_save_geodata(): filename = "TESTFILE_SAVE.txt" geo_data = [{"ip": "244.36.171.60", "country_code": "", "country_name": "", "region_code": "", "region_name": "", "city": "", "zip_code": "", "time_zone": "", "latitude": 0, "longitude": 0, "metro_code": 0}, {"ip": "172.16.58.3", "country_code": "ES", "country_name": "Spain", "region_code": "AN", "region_name": "Andalusia", "city": "Villaverde del Rio", "zip_code": "41318", "time_zone": "Europe/Madrid", "latitude": 37.5892, "longitude": -5.8744, "metro_code": 0}, {"ip": "172.16.58.3", "country_code": "CH", "country_name": "Switzerland", "region_code": "ZH", "region_name": "Zurich", "city": "Zurich", "zip_code": "8002", "time_zone": "Europe/Zurich", "latitude": 47.3664, "longitude": 8.5546, "metro_code": 0}] save_geodata(filename, geo_data) file = open(f"Files/{filename}", 'r') assert json.load(file) == geo_data '''Clean Up''' file.close() os.remove(f"Files/{filename}") def test_load_geodata(): filename = "TESTFILE_LOAD.txt" expected_geo_data = [{"ip": "244.36.171.60", "country_code": "", "country_name": "", "region_code": "", "region_name": "", "city": "", "zip_code": "", "time_zone": "", "latitude": 0, "longitude": 0, "metro_code": 0}, {"ip": "172.16.58.3", "country_code": "ES", "country_name": "Spain", "region_code": "AN", "region_name": "Andalusia", "city": "Villaverde del Rio", "zip_code": "41318", "time_zone": "Europe/Madrid", "latitude": 37.5892, "longitude": -5.8744, "metro_code": 0}, {"ip": "172.16.58.3", "country_code": "CH", "country_name": "Switzerland", "region_code": "ZH", "region_name": "Zurich", "city": "Zurich", "zip_code": "8002", "time_zone": "Europe/Zurich", "latitude": 47.3664, "longitude": 8.5546, "metro_code": 0}] actual_geo_data = load_geodata(filename) assert actual_geo_data == expected_geo_data def test_filter_query_equal_string(): query = "country_name=Switzerland" geo_data = {"ip": "172.16.58.3", "country_code": "CH", "country_name": "Switzerland", "region_code": "ZH", "region_name": "Zurich", "city": "Zurich", "zip_code": "8002", "time_zone": "Europe/Zurich", "latitude": 47.3664, "longitude": 8.5546, "metro_code": 0} assert filter_query(geo_data, query) def test_filter_query_not_equal_string(): query = "country_name!=SWEETzerland" geo_data = {"ip": "172.16.58.3", "country_code": "CH", "country_name": "Switzerland", "region_code": "ZH", "region_name": "Zurich", "city": "Zurich", "zip_code": "8002", "time_zone": "Europe/Zurich", "latitude": 47.3664, "longitude": 8.5546, "metro_code": 0} assert filter_query(geo_data, query) def test_filter_query_equal_float(): query = "longitude=8.5546" geo_data = {"ip": "172.16.58.3", "country_code": "CH", "country_name": "Switzerland", "region_code": "ZH", "region_name": "Zurich", "city": "Zurich", "zip_code": "8002", "time_zone": "Europe/Zurich", "latitude": 47.3664, "longitude": 8.5546, "metro_code": 0} assert filter_query(geo_data, query) def test_filter_query_not_equal_float(): query = "longitude!=10.0" geo_data = {"ip": "172.16.58.3", "country_code": "CH", "country_name": "Switzerland", "region_code": "ZH", "region_name": "Zurich", "city": "Zurich", "zip_code": "8002", "time_zone": "Europe/Zurich", "latitude": 47.3664, "longitude": 8.5546, "metro_code": 0} assert filter_query(geo_data, query) def test_filter_query_less_than(): query = "longitude<10" geo_data = {"ip": "172.16.58.3", "country_code": "CH", "country_name": "Switzerland", "region_code": "ZH", "region_name": "Zurich", "city": "Zurich", "zip_code": "8002", "time_zone": "Europe/Zurich", "latitude": 47.3664, "longitude": 8.5546, "metro_code": 0} assert filter_query(geo_data, query) def test_filter_query_greater_than(): query = "latitude>10" geo_data = {"ip": "172.16.58.3", "country_code": "CH", "country_name": "Switzerland", "region_code": "ZH", "region_name": "Zurich", "city": "Zurich", "zip_code": "8002", "time_zone": "Europe/Zurich", "latitude": 47.3664, "longitude": 8.5546, "metro_code": 0} assert filter_query(geo_data, query) def test_filter_query_greater_than_or_equal(): query1 = "latitude>=10" query2 = "latitude>=47.3664" geo_data = {"ip": "172.16.58.3", "country_code": "CH", "country_name": "Switzerland", "region_code": "ZH", "region_name": "Zurich", "city": "Zurich", "zip_code": "8002", "time_zone": "Europe/Zurich", "latitude": 47.3664, "longitude": 8.5546, "metro_code": 0} assert filter_query(geo_data, query1) assert filter_query(geo_data, query2) def test_filter_query_less_than_or_equal(): query1 = "latitude<=100" query2 = "latitude<=47.3664" geo_data = {"ip": "172.16.58.3", "country_code": "CH", "country_name": "Switzerland", "region_code": "ZH", "region_name": "Zurich", "city": "Zurich", "zip_code": "8002", "time_zone": "Europe/Zurich", "latitude": 47.3664, "longitude": 8.5546, "metro_code": 0} assert filter_query(geo_data, query1) assert filter_query(geo_data, query2) def test_simple_filter_response(): query = "country_name!=Spain" geo_data = [{"ip": "244.36.171.60", "country_code": "", "country_name": "", "region_code": "", "region_name": "", "city": "", "zip_code": "", "time_zone": "", "latitude": 0, "longitude": 0, "metro_code": 0}, {"ip": "172.16.58.3", "country_code": "ES", "country_name": "Spain", "region_code": "AN", "region_name": "Andalusia", "city": "Villaverde del Rio", "zip_code": "41318", "time_zone": "Europe/Madrid", "latitude": 37.5892, "longitude": -5.8744, "metro_code": 0}, {"ip": "172.16.58.3", "country_code": "CH", "country_name": "Switzerland", "region_code": "ZH", "region_name": "Zurich", "city": "Zurich", "zip_code": "8002", "time_zone": "Europe/Zurich", "latitude": 47.3664, "longitude": 8.5546, "metro_code": 0}] expected_geo_data = [{"ip": "244.36.171.60", "country_code": "", "country_name": "", "region_code": "", "region_name": "", "city": "", "zip_code": "", "time_zone": "", "latitude": 0, "longitude": 0, "metro_code": 0}, {"ip": "172.16.58.3", "country_code": "CH", "country_name": "Switzerland", "region_code": "ZH", "region_name": "Zurich", "city": "Zurich", "zip_code": "8002", "time_zone": "Europe/Zurich", "latitude": 47.3664, "longitude": 8.5546, "metro_code": 0}] actual_geo_data = filter_response(geo_data, query) print(actual_geo_data) assert expected_geo_data == actual_geo_data def test_complex_filter_response(): query = "ip!=244.36.171.60:latitude<50:latitude<=47.3664:longitude>-6:longitude>=-5.8744:zip_code>8002" geo_data = [{"ip": "244.36.171.60", "country_code": "", "country_name": "", "region_code": "", "region_name": "", "city": "", "zip_code": "", "time_zone": "", "latitude": 0, "longitude": 0, "metro_code": 0}, {"ip": "172.16.58.3", "country_code": "ES", "country_name": "Spain", "region_code": "AN", "region_name": "Andalusia", "city": "Villaverde del Rio", "zip_code": "41318", "time_zone": "Europe/Madrid", "latitude": 37.5892, "longitude": -5.8744, "metro_code": 0}, {"ip": "172.16.58.3", "country_code": "CH", "country_name": "Switzerland", "region_code": "ZH", "region_name": "Zurich", "city": "Zurich", "zip_code": "8002", "time_zone": "Europe/Zurich", "latitude": 47.3664, "longitude": 8.5546, "metro_code": 0}] expected_geo_data = [{"ip": "172.16.58.3", "country_code": "ES", "country_name": "Spain", "region_code": "AN", "region_name": "Andalusia", "city": "Villaverde del Rio", "zip_code": "41318", "time_zone": "Europe/Madrid", "latitude": 37.5892, "longitude": -5.8744, "metro_code": 0}] actual_geo_data = filter_response(geo_data, query) print(actual_geo_data) assert expected_geo_data == actual_geo_data <file_sep>/main.py #!/usr/bin/env python from functions import * import tkinter as tk # GUI helper vars ip_list = [] geo_list = [] filtered_geo_list = [] def GUI_parse_file(): global filename_entry, ip_list, ip_list_lb ip_list = parse_file(filename_entry.get()) '''Update GUI''' ip_list_lb.delete(0, ip_list_lb.size()) for i, ip in enumerate(ip_list, 0): ip_list_lb.insert(i, ip) def GUI_geo_lookup_ips(): global ip_list, geo_list, geo_ip_results geo_list = geo_lookup_ips(ip_list) '''Update GUI''' for i, geo_data in enumerate(geo_list, 0): geo_ip_results.insert(i, geo_data) def GUI_save_geodata(): global geo_list, geo_filename_entry save_geodata(geo_filename_entry.get(), geo_list) def GUI_save_filtered_geodata(): global filtered_geo_list, geo_filename_entry save_geodata(geo_filename_entry.get(), filtered_geo_list) def GUI_load_geodata(): global geo_list, geo_ip_results, geo_filename_entry geo_list = load_geodata(geo_filename_entry.get()) '''Update GUI''' geo_ip_results.delete(0, geo_ip_results.size()) for i, geo_data in enumerate(geo_list, 0): geo_ip_results.insert(i, geo_data) def GUI_filter_response(): global geo_list, filtered_geo_list, geo_ip_results, filter_entry filtered_geo_list = filter_response(geo_list, filter_entry.get()) '''Update GUI''' geo_ip_results.delete(0, geo_ip_results.size()) for i, geo_data in enumerate(filtered_geo_list, 0): geo_ip_results.insert(i, geo_data) def GUI_clear_filter(): global geo_list, filtered_geo_list, geo_ip_results filtered_geo_list = [] '''Update GUI''' geo_ip_results.delete(0, geo_ip_results.size()) for i, geo_data in enumerate(geo_list, 0): geo_ip_results.insert(i, geo_data) top = tk.Tk() root = tk.Frame(top) root.pack(side=tk.TOP) file_label = tk.Label(root, text="File Name:") file_label.pack(side=tk.LEFT) filename_entry = tk.Entry(root, bd=5) filename_entry.pack(side=tk.LEFT) get_ip_button = tk.Button(root, text="Get IPs", command=GUI_parse_file) get_ip_button.pack(side=tk.LEFT) ip_frame = tk.Frame(top) ip_frame.pack(side=tk.LEFT) res_frame = tk.Frame(top) res_frame.pack(side=tk.LEFT) filter_frame = tk.Frame(top) filter_frame.pack(side=tk.BOTTOM) filter_label = tk.Label(filter_frame, text="Query:") filter_label.pack(side=tk.LEFT) filter_entry = tk.Entry(filter_frame, bd=5) filter_entry.pack(side=tk.LEFT) filter_button = tk.Button(filter_frame, text="Clear Filter", command=GUI_clear_filter) filter_button.pack(side=tk.BOTTOM) filter_button = tk.Button(filter_frame, text="Filter Responses", command=GUI_filter_response) filter_button.pack(side=tk.BOTTOM) load_button = tk.Button(res_frame, text="Load Responses", command=GUI_load_geodata) load_button.pack(side=tk.BOTTOM) save_button = tk.Button(res_frame, text="Save Responses", command=GUI_save_geodata) save_button.pack(side=tk.BOTTOM) save_filtered_button = tk.Button(res_frame, text="Save Filtered Responses", command=GUI_save_filtered_geodata) save_filtered_button.pack(side=tk.BOTTOM) geo_filename_entry = tk.Entry(res_frame, bd=5) geo_filename_entry.pack(side=tk.BOTTOM) file_label = tk.Label(res_frame, text="File Name:") file_label.pack(side=tk.BOTTOM) geo_ip_results = tk.Listbox(res_frame, height=20, width=100) geo_ip_results.pack(side=tk.BOTTOM) ips_label = tk.Label(ip_frame, text="IP List") ips_label.pack(side=tk.TOP) ips_label = tk.Label(res_frame, text="Responses") ips_label.pack(side=tk.TOP) ip_list_lb = tk.Listbox(ip_frame, height=20) ip_list_lb.pack(side=tk.TOP) geo_lookup_button = tk.Button(ip_frame, text="IP Lookup", command=GUI_geo_lookup_ips) geo_lookup_button.pack(side=tk.BOTTOM) top.mainloop()
59def75d8826a5ae9e3274b26834c8f8938ab164
[ "Markdown", "Python" ]
5
Markdown
Cyancey96/python_challenge
22291b500793118d7895dc110ebc672d758b1783
3b0ace2bb9ff5ac3e82f2deaeb008df799d11fc7
refs/heads/master
<file_sep>#include "../HW05/bst.h" #include <stdlib.h> #include <assert.h> #include <math.h> #include "../HW05/config.h" #include <stdio.h> #ifdef max #undef max #endif #define max(a, b) ((a) > (b) ? (a) : (b)) #define bst_LCHILD(x) ((2 * (x)) + 1) #define bst_RCHILD(x) ((2 * (x)) + 2) void bst_insert(bst_t* tree, int data) { #ifdef DEBUG printf("Inserting %d to tree...\n", data); #endif // DEBUG if (tree->nodes == 0) { if (tree->length < data) { bst_upscale(tree, data + 1); } tree->data[data] = 0; tree->nodes++; tree->root_index = data; #ifdef DEBUG printf("=> inserted to 0[%d] (first node)\n", data); #endif // DEBUG } else { bool set = FALSE; do { int idx = tree->root_index; if (tree->data[idx] == bst_EMPTY_NODE) { tree->data[data] = idx; tree->nodes++; set = TRUE; } else if (data > idx) { #ifdef DEBUG printf("\t\tData > stored (%d > %d) -> going to right subtree [%d]\n", data, idx, bst_RCHILD(idx)); #endif // DEBUG idx = bst_find_data(tree, bst_RCHILD(tree->data[data])); } } while (set == FALSE); } } int bst_find_data(bst_t* tree, int index) { int reti = bst_EMPTY_NODE; for (int i = 0; i < tree->length; i++) { if (tree->data[i] == index) { reti = i; break; } } return reti; }<file_sep>#pragma once #include "queue.h" #include "experiment.h" struct Laboratory { int days_available; int* days_used; int experiments_available_count; experiment_t** experiments_available; queue_t* experiment_unused; int maximal_income; int days_claimed; int total_income; }; typedef struct Laboratory laboratory_t; <file_sep>///<summary> /// File containing declaration of queue ///</summary> ///<remarks> /// Copyright 2019 <NAME> <<EMAIL>> /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http ://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissionsand /// limitations under the License. ///</remarks> #pragma once #include "simple_bool.h" #include "sorted.h" ///<summary> ///Definition of structure Queue ///</summary> struct Queue { ///<summary> /// Data stored in queue ///</summary> void** data; ///<summary> /// Index of first item in queue ///</summary> int head; ///<summary> ///Index of last item in queue ///</summary> int tail; ///<summary> ///Count of items in queue ///</summary> int count; ///<summary> ///Maximal length of queue ///</summary> int length; ///<summary> ///Index of data for "next" function ///</summary> int next_head; }; ///<summary> /// Definition of queue as new data type; ///</summary> typedef struct Queue queue_t; ///<summary> ///Creates static length queue ///</summary> queue_t* queue_create(); ///<summary> ///Adds data to queue ///</summary> ///<param name="queue">Queue where to add data</param> ///<param name="data"> Data to be added to queue</param> ///<returns>Returns <c>TRUE</c> if data was stored into queue, <c>FALSE</c> otherwise</returns> bool queue_push(queue_t* queue, void* data); ///<summary> ///Gets data from queue ///</summary> ///<param name="queue">Queue from which gets data</param> ///<returns>Data or <c>NULL</c> if queue is empty</returns> void* queue_pop(queue_t* queue); ///<summary> ///Checks if queue is empty ///</summary> ///<param name="queue">Queue which will be checked</param> ///<returns><c>TRUE</c> if queue is empty, <c>FALSE</c> otherwise</returns> bool queue_is_empty(queue_t* queue); ///<summary> ///Checks if queue is full ///</summary> ///<param name="queue">Queue which will be checked</param> ///<returns><c>TRUE</c> if queue is full, <c>FALSE</c> otherwise</returns> bool queue_is_full(queue_t* queue); ///<summary> ///Increases memory space for queue ///</summary> ///<param name="queue">Queue which memory space will be increased</param> void queue_upscale(queue_t* queue); ///<summary> ///Shrinks memory space for queue ///</summary> ///<param name="queue">Queue which memory space will be shrinked</param> void queue_shrink(queue_t* queue); ///<summary> ///Gets count of elements in queue ///</summary> ///<param name="queue"> Queue which will be checked</param> ///<returns>Count of elements stored in queue</returns> int queue_count(queue_t* queue); ///<summary> ///Gets element from queue at index ///</summary> ///<param name="queue">Queue from which will be data got</param> ///<param name="index">Index of data from which will be got</param> ///<returns>Selected data or <c>NULL</c> if there is nothing at index</returns> void* queue_at(queue_t* queue, int index); ///<summary> ///Checks, whether there is at least one element in queue ///</summary> ///<param name="queue">Queue which will be checked</param> ///<returns><c>TRUE</c> if there is any element, <c>FALSE</c> otherwise</returns> bool queue_is_not_empty(queue_t* queue); ///<summary> /// Gets data from queue without removing it ///</summary> ///<param name="queue">Queue with data</param> ///<returns>Selected data or <c>NULL</c></returns> void* queue_next(queue_t* queue); ///<summary> /// Checks, whether there is some data for "next" function ///</summary> ///<param name="queue">Queue which will be checked</param> ///<returns><c>TRUE</c> if there is at least one element, <c>FALSE</c> otherwise</returns> bool queue_next_not_empty(queue_t* queue); ///<summary> ///Resets index of "next" function ///</summary> ///<param name="queue">Queue which next index will be reseted</param> void queue_reset_next_index(queue_t* queue); ///<summary> ///Reverses data in queue ///</summary> ///<param name="queue">Queue, which data will be copied reversed</param> ///<returns>New queue with reversed data</returns> queue_t* queue_reverse_data(queue_t* queue); ///<summary> ///Deletes all data associated with queue ///</summary> ///<param name="queue">Queue which will be deleted</param> void queue_delete(queue_t* queue); ///<summary> ///Prints data stored in queue ///</summary> ///<param name="queue">Queue which data will be printed</param> void queue_print(queue_t* queue); ///<summary> ///Checks, whether queue contains element ///</summary> ///<param name="queue">Queue where will be element searched</param> ///<param name="element">Element, which will be searched</param> ///<param name="sort">Flag of sortation of data in queue</param> ///<param name="comparator"> ///Function wich returns 0 if items are same, /// number < 0 if first one is lower than second one, /// number > 0 if first one is greater than second one ///</param> ///<returns><c>TRUE</c> if queue contains element, <c>FALSE</c> otherwise</returns> bool queue_contains(queue_t* queue, void* element, sort_t sort, int(*comparator(void*, void*))); ///<summary> ///Checks, whether queue contains element using binar search ///</summary> ///<param name="queue">Queue where will be element searched</param> ///<param name="element">Element, which will be searched</param> ///<param name="sort">Flag of sortation of data in queue</param> ///<returns><c>TRUE</c> if queue contains element, <c>FALSE</c> otherwise</returns> bool queue_binary_search(queue_t* queue, void* element, sort_t sort, int(*comparator(void*, void*))); ///<summary> ///Recursive implementation of binary search ///</summary> ///<param name="queue">Queue with data</param> ///<param name="element">Searched element</param> ///<param name="sort">Flag of sortation of data in queue</param> ///<param name="start_index">Start of actually searched interval of indexes</param> ///<param name="end_index">End of actually searched interval of indexes</param> ///<returns><c>TRUE</c> if queue contains element, <c>FALSE</c> otherwise</returns> bool queue_binary_search_recursive(queue_t* queue, void* element, sort_t sort, int start_index, int end_index, int(*comparator(void*, void*))); ///<summary> /// Computes next index between indexes ///</summary> ///<param name="start_index">Starting index</param> ///<param name="end_index">Ending index</param> ///<param name="queue">Queue with data</param> ///<returns>Computed index between two indexes or <c>-1</c> if there is no such an index int queue_binary_search_next_index(int start_index, int end_index, queue_t* queue); ///<summary> ///Checks, whether there is index in queue data ///</summary> ///<param name="index">Index which will be checked</param> ///<param name="queue">Queue with data</param> ///<returns><c>TRUE</c> If there are data with index in queue, <c>FALSE</c> otherwise bool queue_index_in_queue(int index, queue_t* queue); <file_sep>///<summary> /// File containing main program of third homework ///</summary> ///<remarks> /// Copyright 2019 <NAME> <<EMAIL>> /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http ://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissionsand /// limitations under the License. ///</remarks> #include <stdio.h> #include <stdlib.h> #include <limits.h> #include "node.h" #include "plane.h" #include "hw03utils.h" #include "config.h" ///<summary> /// Stores count of planes stored in tree ///</summary> volatile static int COUNT = 0; ///<summary> ///Stores wight of one pilot figurine ///</summary> volatile static int WEIGHT = 0; ///<summary> ///Entry function of program ///</summary> ///<param name="argc">Count of arguments</param> ///<param name="argv">Arguments of program</param> ///<returns>0 if finished successfully, something different otherwise</returns> int main(int argc, char* argv[]) { int reti = EXIT_SUCCESS; scanf("%i %i", &COUNT, &WEIGHT); #ifdef DEBUG printf("Loaded data:: count: %d, weight of pilot: %d\n", COUNT, WEIGHT); #endif // DEBUG plane_t** planes = (plane_t**)malloc(COUNT * sizeof(plane_t*)); for (int i = 0; i < COUNT; i++) { int weight = -1; scanf("%i", &weight); planes[i] = plane_create(weight); #ifdef DEBUG printf("Loaded plane:: id: %d, weight: %d\n", plane_get_identifier(planes[i]), plane_get_weight(planes[i])); #endif // DEBUG } //Create tree from planes node_t* root = utils_create_tree(planes, 0, (COUNT - 1)); #ifdef DEBUG utils_print_tree(root); printf("Leaves: %d\n", node_count_leaves(root)); #endif // DEBUG int result = utils_count_whole_difference(root); #ifdef DEBUG printf("Sum of differences in tree: %d\n", result); #endif // DEBUG for (int i = 0; i < PILOTS; i++) { utils_place_pilot(root, WEIGHT); } #ifdef DEBUG utils_set_evaluator(root); node_print_tree_nodes_evaluation(root); #endif // DEBUG int result_pilot = utils_count_whole_difference(root); for (int i = 0; i < COUNT; i++) { plane_delete(planes[i]); } printf("%d %d\n", result, result_pilot); return reti; }<file_sep>#ifndef __HW05_UTILS_H__ #define __HW05_UTILS_H__ #include "node.h" #include "simple_bool.h" void utils_default_deleter(void* data); void utils_bst_insert(node_t* node, int data); node_t* utils_bst_find(node_t* node, int key); bool utils_consolidation_needed(node_t* root); node_t* utils_bst_delete(node_t* node, int key); node_t* utils_bst_get_min_value_node(node_t* node); void utils_bst_print_inorder(node_t* node); #endif // !__HW05_UTILS_H__ <file_sep>extern int OPERATIONS; extern int MAXIMAL_DEPTH; extern int NODES;<file_sep>#include <stdio.h> #include "structures.h" #include "config.h" //----------------------------------------------------------------------------------------------------------------------------------------------- void check_outside_situation(model_t* model, sticky_note_t* note, result_t* result) { #ifdef DEBUG printf("Checking new sticky note from outside\n"); #endif // DEBUG bool counted = FALSE; for (int i = note->distance_from_left; i < note->distance_from_left + note->width; i++) { if (model->situation_out[i] < note->height) { model->situation_out[i] = note->height; if (counted == FALSE) { queue_push(model->notes_out, note->id); counted = TRUE; result->visible_out++; } } } } //----------------------------------------------------------------------------------------------------------------------------------------------- void check_inside_situation(model_t* model, sticky_note_t* note, result_t* result) { #ifdef DEBUG printf("Checking new sticky note from inside\n"); #endif // DEBUG bool counted = FALSE; for (int i = note->distance_from_left; i < note->distance_from_left + note->width; i++) { if (model->situation_in[i] < note->height) { model->situation_in[i] = note->height; if (counted == FALSE) { queue_push(model->notes_in, note->id); counted = TRUE; result->visible_in++; } } } } //----------------------------------------------------------------------------------------------------------------------------------------------- void print_result(result_t* result) { #ifdef DEBUG printf("visible_out: %d\nvisible_in: %d\nvisible_both: %d\nvisibile_one:%d\nunvisible: %d\n", result->visible_out, result->visible_in, result->visible_both, result->visible_one, result->unvisible); #endif // DEBUG #ifndef DEBUG printf("%d %d %d\n", result->visible_both, result->visible_one, result->unvisible); #endif // !DEBUG } //----------------------------------------------------------------------------------------------------------------------------------------------- int check_visible_both(model_t* model) { int reti = 0; while (queue_next_not_empty(model->notes_in) == TRUE) { int element = queue_next(model->notes_in); if (queue_contains(model->notes_out, element, ASC) == TRUE) { reti++; } } return reti; } //----------------------------------------------------------------------------------------------------------------------------------------------- int check_visible_one(model_t* model) { int reti = 0; queue_t* data_union = queue_create_static((queue_count(model->notes_in) + queue_count(model->notes_out))); queue_t* difference = queue_create_static(queue_count(model->notes_out)); queue_reset_next_index(model->notes_in); #ifdef DEBUG printf("Checking visibility from one side only...\n"); #endif // DEBUG while (queue_next_not_empty(model->notes_in) == TRUE) { int element = queue_next(model->notes_in); queue_push(data_union, element); } queue_reset_next_index(model->notes_in); queue_reset_next_index(model->notes_out); while (queue_next_not_empty(model->notes_out) == TRUE) { int element = queue_next(model->notes_out); #ifdef DEBUG printf("___%d\n", element); #endif // DEBUG if (queue_contains(data_union, element, DESC) == FALSE) { queue_push(difference, element); } } queue_reset_next_index(model->notes_out); queue_reset_next_index(difference); while (queue_next_not_empty(difference) == TRUE) { queue_push(data_union, queue_next(difference)); } queue_reset_next_index(difference); queue_reset_next_index(data_union); #ifdef DEBUG printf("-----UNION-----\n"); printf("1st set:\n"); queue_print(model->notes_in); printf("\n2nd set:\n"); queue_print(model->notes_out); printf("\nUnion:\n"); queue_print(data_union); printf("\n---------------\n"); #endif // DEBUG reti = queue_count(data_union); queue_delete(data_union); queue_delete(difference); return reti; } <file_sep>#include <iostream> #include <cstdlib> #include "Globals.hpp" #include "Map.hpp" #include "config.h" using namespace std; int main(int argc, char* argv[]) { int reti = EXIT_SUCCESS; Globals* settings = Globals::getInstance(); //Load first line of input int number_of_villages, starting_village, ending_village, maximal_time = -1; cin >> number_of_villages; cin >> starting_village; cin >> ending_village; cin >> maximal_time; //Save it as globals variables settings->setValue("NUMBER OF VILLAGES", number_of_villages); settings->setValue("STARTING VILLAGE", starting_village); settings->setValue("FINAL VILLAGE", ending_village); settings->setValue("MAXIMAL TIME", maximal_time); #ifdef DEBUG cout << "--- Loaded data ---" << endl; printf("\tNUMBER OF VILLAGES: %d\n", settings->getValue("NUMBER OF VILLAGES")); printf("\tSTARTING VILLAGE: %d\n", settings->getValue("STARTING VILLAGE")); printf("\tENDING VILLAGE: %d\n", settings->getValue("FINAL VILLAGE")); printf("\tMAXIMAL TIME: %d\n", settings->getValue("MAXIMAL TIME")); #endif // DEBUG //Create map of villages Map villages = Map(settings->getValue("NUMBER OF VILLAGES")); //Load villages visit times #ifdef DEBUG cout << "--- Loading villages --- " << endl; #endif // DEBUG for (int i = 0; i < settings->getValue("NUMBER OF VILLAGES"); i++) { int time = 0; cin >> time; villages.addVillage(new Village(i, time)); #ifdef DEBUG cout << "\t" << "[" << i << "] (" << time << ")" << endl; #endif // DEBUG } //Load attractivenesses of villages #ifdef DEBUG cout << "--- Loading tourist indexes ---" << endl; #endif // DEBUG for (int i = 0; i < settings->getValue("NUMBER OF VILLAGES"); i++) { int tourist_index; cin >> tourist_index; villages.getVillage(i)->setAtractiveness(tourist_index); #ifdef DEBUG cout << "\t[" << i << "] >" << tourist_index << "<" << endl; #endif // DEBUG } //Load paths between villages #ifdef DEBUG cout << "--- Loading paths ---" << endl; #endif // DEBUG for (int i = 0; i < settings->getValue("NUMBER OF VILLAGES") - 1; i++) { int start, finish, cost; cin >> start; cin >> finish; cin >> cost; #ifdef DEBUG cout << "\t[" << start << "] -> [" << finish << "] @ " << cost << endl; #endif // DEBUG villages.makePath(villages.getVillage(start), villages.getVillage(finish), cost); } #ifdef DEBUG cout << "\t --- Available paths ---" << endl; for (int i = 0; i < settings->getValue("NUMBER OF VILLAGES"); i++) { try { Village* v = villages.getVillage(i); cout << "\t\t[" << v->getLabel() << "]: " << v->getPaths()->size() << endl; } catch (const std::exception& ex) { cout << endl << "[" << i << "]" << ex.what() << endl; } } #endif // DEBUG //Find shortest path from start to final village #ifdef DEBUG cout << "--- Finding shortest path ---" << endl; #endif // DEBUG settings->setValue("SHORTEST PATH", -1); villages.findPath(villages.getVillage(settings->getValue("STARTING VILLAGE")), villages.getVillage(settings->getValue("FINAL VILLAGE"))); return reti; }<file_sep>#pragma once #include "simple_bool.h" #include "laboratory_struct.h" #define DYN_QUEUE_UPSCALE 2 struct Dynamic_Queue { int count; int capacity; laboratory_t** data; int head; int tail; int next; }; typedef struct Dynamic_Queue dyn_queue_t; dyn_queue_t* dyn_queue_create(); bool dyn_queue_push(dyn_queue_t* queue, laboratory_t* item); laboratory_t* dyn_queue_pop(dyn_queue_t* queue); bool dyn_queue_is_empty(dyn_queue_t* queue); bool dyn_queue_upscale(dyn_queue_t* queue); void dyn_queue_delete(dyn_queue_t* queue); bool dyn_queue_has_next(dyn_queue_t* queue); laboratory_t* dyn_queue_next(dyn_queue_t* queue); void dyn_queue_reset_next_index(dyn_queue_t* queue); dyn_queue_t* dyn_queue_copy(dyn_queue_t* queue);<file_sep>///<summary> /// File containing declaration of planes used in third homework ///</summary> ///<remarks> /// Copyright 2019 <NAME> <<EMAIL>> /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http ://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissionsand /// limitations under the License. ///</remarks> #pragma once ///<summary> /// Definition of plane in third homework ///</summary> struct Plane { ///<summary> ///Unique identifier identifiing plane in system ///</summary> int id; ///<summary> ///Weight of plane ///</summary> int weight; ///<summary> ///Sets whether there is pilot in plane ///</summary> bool pl_has_pilot; }; ///<summary> /// Type definition of plane used in third homework ///</summary> typedef struct Plane plane_t; ///<summary> ///Stores last used identifier of plane ///</summary> static volatile int plane_LAST_ID = -1; ///<summary> ///Defines <c>NULL</c> plane ///</summary> #define plane_NULL ((plane_t*)NULL) ///<summary> ///Creates empty plane ///</summary> ///<returns>New empty plane or <c>NULL</c> if allocating space for plane failed</returns> plane_t* plane_create_empty(); ///<summary> ///Creates plane with defined weight ///</summary> ///<param name="weight">Weight of plane</param> ///<returns>New plane with defined weitgh or <c>NULL</c> if allocating space for plane failed</returns> plane_t* plane_create(int weight); ///<summary> ///Deletes plane and all data used by plane ///</summary> ///<param name="plane">Plane, which will be deleted</param> void plane_delete(plane_t* plane); ///<summary> ///Generally deletes plane and all data used by plane ///</summary> ///<param name="data">Pointer to where is plane stored</param> void plane_deleter(void* data); ///<summary> ///Checks, whether planes are same ///</summary> ///<param name="plane1">First plane to be compared</param> ///<param name="plane2">Second plane to be compared</param> ///<returns><c>TRUE</c> if they are same, <c>FALSE</c> otherwise</returns> bool plane_check_same(plane_t* plane1, plane_t* plane2); ///<summary> ///Gets weight of plane ///</summary> ///<param name="plane">Plane which weight will be returned</param> ///<returns>Weight of plane</returns> int plane_get_weight(plane_t* plane); ///<summary> ///Gets identifier of plane ///</summary> ///<param name="plane">Plane which identifier will be returned</param> ///<returns>Identifier of plane</returns> int plane_get_identifier(plane_t* plane); ///<summary> ///Sets pilot to plane ///</summary> ///<param name="plane">Plane to which will be pilot set</param> ///<param name="weight">Weight of pilot</param> void plane_set_pilot(plane_t* plane, int weight); ///<summary> ///Checks, whether there is a pilot in a plane ///</summary> ///<param name="plane">Plane to be checked</param> ///<returns><c>TRUE</c>if there is pilot, <c>FALSE</c> otherwise</returns> bool plane_get_has_pilot(plane_t* plane); ///<summary> ///Removes pilot from plane ///</summary> ///<param name="plane">Plane from which will be pilot removed</param> ///<param name="weight">Weight of pilot</param> void plane_unset_pilot(plane_t* plane, int weight); <file_sep>///<summary> /// File containing declarations of utility functions /// used in first homework for subject B4B33ALG - Algorithms ///</summary> ///<remarks> /// Copyright 2019 <NAME> <<EMAIL>> /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http ://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissionsand /// limitations under the License. ///</remarks> #pragma once #include "structures.h" #include "simple_bool.h" ///<summary> /// Function to check changes from outside after adding new sticky note ///</summary> ///<param name="model">Model describing actual situation of problem</param> ///<param name="note">Sticky note which will be added</param> ///<param name="result">Structure with results of solving actual problem</param> void check_outside_situation(model_t* model, sticky_note_t* note, result_t* result); ///<summary> /// Function to check changes from inside after adding new sticky note ///</summary> ///<param name="model">Model describing actual situation of problem</param> ///<param name="note">Sticky note which will be added</param> ///<param name="result">Structure with results of solving actual problem</param> void check_inside_situation(model_t* model, sticky_note_t* note, result_t* result); ///<summary> ///Prints information about results ///</summary> ///<param name="result">Result which data will be printed</param> void print_result(result_t* result); ///<summary> ///Checks, how many notes are visible from both sides ///</summary> ///<param name="model">Model describing final situation of problem</param> ///<returns>Count of notes visible from both sides</returns> int check_visible_both(model_t* model); ///<summary> ///Checks, how many notes are visible from at least one side ///</summary> ///<param name="model">Model describing final situation of problem</param> ///<returns>Count of notes visible from at least one side</returns> int check_visible_one(model_t* model); ///<summary> ///Defines maximum from two values ///</summary> ///<param name="a">First value in comparison</param> ///<param name="b">Second value in comparison</param> ///<returns>Maximum of two values</returns> #define MAX(a, b) (((a) > (b))? (a) : (b)) ///<summary> ///Defines minimum from two values ///</summary> ///<param name="a">First value in comparison</param> ///<param name="b">Second value in comparison</param> ///<returns>Minimum of two values</returns> #define MIN(a, b) (((a) < (b))? (a) : (b)) ///<summary> ///Prints model of situation ///</summary> ///<param name="model">Model of the situation //void print_model(model_t* model); !!!NOT IMPLEMENTED YET!!!<file_sep>#include <stdio.h> int ff(int x, int y) { if (y > 0) return (x * ff(x, y-1)); return 1; } void st_ff(int n) { if (n < 1) return; printf("1"); st_ff(n - 1); printf("22"); } void print_seq(int n, int c) { if (c > n) return; printf("%d ", c); print_seq(n, c++); printf("%d ", c); return; } int main() { printf("%d\n", ff(2, 5)); st_ff(3); printf("\n"); // print_seq(5, 1); printf("\n"); return 0; } <file_sep>using System; using System.Net; using System.Net.Sockets; using System.Text; using static NetConsole.Structures; namespace NetConsole { class Network { private UdpClient udpClient; private int port; private IPAddress ipAddress; private IPEndPoint ipEndPoint; private Logger logger; public Network(IPAddress address, int port, Logger logger) { this.ipAddress = address; this.port = port; this.logger = logger; this.init(); } public Network(string address, int port, Logger logger) { this.ipAddress = Dns.GetHostEntry(address).AddressList[0]; this.port = port; this.logger = logger; this.init(); } private void init() { this.udpClient = new UdpClient(this.port); this.ipEndPoint = new IPEndPoint(this.ipAddress, this.port); this.logger.LogTiny("Client started; listening on port " + this.port); } public void SendMessage(string message) { byte[] buffer = Encoding.ASCII.GetBytes(message); try { this.udpClient.Send(buffer, buffer.Length, this.ipEndPoint); this.logger.LogSuccess("Data sent"); } catch (NullReferenceException ex) { string[] log = { "Sending failed", ex.Message }; this.logger.LogMultiline(LogLevel.CRITICAL, log); } catch (Exception ex) { string[] log = { "Sending failed", ex.Message }; this.logger.LogMultiline(LogLevel.ERROR,log); } } public string ReceiveMessage() { string reti = null; //TODO: Repair receiving byte[] buffer = this.udpClient.Receive(ref this.ipEndPoint); reti = Encoding.ASCII.GetString(buffer); this.logger.LogTiny(reti); return reti; } public void LogMessage(string message) { if (message.Contains(",")) { string[] info = message.Split(','); if (info.Length == 2) { string[] available_levels = { "C", "E", "W", "I", "S", "B", "T" }; bool allowed_level = false; foreach (string level in available_levels) { if (info[0] == level) { allowed_level = true; break; } } if (allowed_level == true) { switch (info[0]) { case "C": this.logger.LogCritical(info[1]); break; case "E": this.logger.LogError(info[1]); break; case "W": this.logger.LogWarning(info[1]); break; case "I": this.logger.LogInfo(info[1]); break; case "S": this.logger.LogSuccess(info[1]); break; case "B": this.logger.LogBasic(info[1]); break; case "T": this.logger.LogTiny(info[1]); break; } } else { string[] log = { "Message parsing failed.", "Input: " + message, "Unknown log level!" }; this.logger.LogMultiline(LogLevel.WARNING, log); } } else { string[] log = { "Message parsing failed.", "Input: " + message, "Unknown format!" }; this.logger.LogMultiline(LogLevel.WARNING, log); } } else { string[] log = { "Message parsing failed.", "Input: " + message, "Not comma(,) found!" }; this.logger.LogMultiline(LogLevel.WARNING, log); } } } } <file_sep>#include "Map.hpp" #include "Exceptions.hpp" #include "Path.hpp" #include <iostream> #include <queue> #include "Globals.hpp" void Map::findShortestPath(std::queue<Village*>* villages, Village* actual, Village* final_village) { std::vector<Path<Village*>*>* neighbours = actual->getPaths(); Globals* settings = Globals::getInstance(); for (int i = 0; i < neighbours->size(); i++) { Village* final_node = neighbours->at(i)->getFinalNode(); if (final_node->getLabel() == final_village->getLabel()) { #ifdef DEBUG std::cout << "\tFinal village reached!" << std::endl; #endif // DEBUG settings->setValue("SHORTEST PATH", 1); while (villages->empty() == false) { villages->pop(); } break; } else { villages->push(neighbours->at(i)->getFinalNode()); } } } Map::Map(int villages) { this->villages_count = villages; this->villages = new Village*[this->villages_count]; } void Map::addVillage(Village* village) { int label = village->getLabel(); if (label >= this->villages_count) { throw VillageLabelOutOfBoundaryException(); } else { this->villages[label] = village; } } Village* Map::getVillage(int label) { if (this->villages[label]->getLabel() == label) { return this->villages[label]; } else { for (int i = 0; i < this->villages_count; i++) { if (this->villages[i]->getLabel() == label) { return this->villages[i]; } } } throw NotSuchAVillageWithLabelException(); } void Map::makePath(Village* villageA, Village* villageB, int cost) { villageA->addNeighbour(villageB, cost); } int Map::getCost(Village* villageA, Village* villageB) { int reti = -1; /* std::vector<Path<Village*>*>* neighbours = villageA->getPaths(); std::vector<Path<Village*>*>::iterator it = neighbours->begin(); while (it != neighbours->end()) { if (*(*it)->getFinalNode()->getLabel() == villageB->getLabel()) { reti = *(*it)->getCost(); break; } it++; } if (reti == -1) { throw NoPathBetweenVillagesException(); } */ return reti; } std::vector<Path<Village*>*>* Map::getPaths(Village* village) { return village->getPaths(); } std::vector<Village*>* Map::getNeighbours(Village* village) { std::vector<Path<Village*>*>* paths = this->getPaths(village); std::vector<Village*>* reti = new std::vector<Village*>(); std::vector<Path<Village*>*>::iterator it = paths->begin(); while ((it) != paths->end()) { reti->push_back(*(*it)->getFinalNode()); it++; } return reti; } std::vector<Village*>* Map::findPath(Village* start_village, Village* final_village) { std::vector<Village*>* reti = new std::vector<Village*>(); std::queue<Village*>* village_queue = new std::queue<Village*>(); village_queue->push(start_village); Globals* settings = Globals::getInstance(); while (village_queue->empty() == false && settings->getValue("SHORTEST PATH") == -1) { Village* actual = village_queue->front(); village_queue->pop(); this->findShortestPath(village_queue, actual, final_village); } return reti; } Map::~Map() { } <file_sep>///<summary> /// File containig implementation of functions and data types used for printing colors to console /// used in logging library ///</summary> ///<remarks> /// Copyright 2019 <NAME> <<EMAIL>> /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http ://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissionsand /// limitations under the License. ///</remarks> #include <stdio.h> #include <stdlib.h> #include "ConsoleColor.h" #include "ConsoleColor_utils.h" //============================================================================================================================= void console_color_set_foreground(console_color_t color) { console_color_foreground = color; char* code = console_color_get_color_code(&console_color_foreground, &console_color_background); printf("%s", code); (code); } //============================================================================================================================= void console_color_reset_colors() { printf("\033[0m"); } //============================================================================================================================= console_color_t console_color_get_from_rgb(int red, int green, int blue) { rgb_color_t rgb_color = { .red = red, .blue = blue, .green = green }; console_color_data_t data = { .rgb_color = rgb_color }; console_color_t reti = { .data = data, .type = RGB }; return reti; } //============================================================================================================================= console_color_t console_color_get_from_ansi(ansi_color_t color) { console_color_data_t data = { .ansi_color = color }; console_color_t reti = { .type = ANSI, .data = data }; return reti; } //============================================================================================================================= void console_color_set_background(console_color_t color) { console_color_background = color; char* code = console_color_get_color_code(&console_color_foreground, &console_color_background); printf("%s", code); //free(code); } <file_sep>CXX=g++ CFLAGS+=-Wall program: obj/hw06.o obj/globals.o obj/village.o obj/map.o $(CXX) $(CFLAGS) -o program obj/hw06.o obj/globals.o obj/village.o obj/map.o obj: mkdir obj obj/hw06.o: obj $(CXX) $(CFLAGS) -c -o obj/hw06.o hw06.cpp obj/globals.o: obj Globals.cpp Globals.hpp $(CXX) $(CFLAGS) -c -o obj/globals.o Globals.cpp obj/village.o: obj Village.cpp Village.hpp $(CXX) $(CFLAGS) -c -o obj/village.o Village.cpp obj/map.o: obj Map.cpp Map.hpp $(CXX) $(CFLAGS) -c -o obj/map.o Map.cpp clean: $(RM) program $(RM) -r obj <file_sep>#ifndef __QUEUE_H__ #define __QUEUE_H__ #include "simple_bool.h" volatile static int queue_node_identifier = 0; struct QueueNode { void* data; struct QueueNode* next; int id; }; typedef struct QueueNode queue_node_t; struct Queue { int count; queue_node_t* head; queue_node_t* tail; }; typedef struct Queue queue_t; queue_t* queue_create(); void queue_push(queue_t* queue, void* data); void* queue_pop(queue_t* queue); int queue_count(queue_t* queue); bool queue_is_empty(queue_t* queue); #endif // !__QUEUE_H__ <file_sep>///<summary> /// File containig definitions of all necessary structures and definitions /// used in first homework for subject B4B33ALG - Algorithms ///</summary> ///<remarks> /// Copyright 2019 <NAME> <<EMAIL>> /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http ://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissionsand /// limitations under the License. ///</remarks> #pragma once #include "queue.h" /* === STRUCTURES DEFINITIONS === */ ///<summary> /// Structure containing information about sticky note ///</summary> struct StickyNote { ///<summary> /// Defines unique identifier of sticky note in system ///</summary> int id; ///<summary> /// Width of sticky note ///</summary> int width; ///<summary> /// Height of sticky note ///</summary> int height; ///<summary> /// Distance of left side of sticky note from left side of area /// available for sticky notes ///</summary> int distance_from_left; }; ///<summary> /// Structures which holds final results of program ///</summary> struct Result { ///<summary> /// Number of sticky notes visible from outside ///</summary> int visible_out; ///<summary> /// Number of sticky notes visible from inside ///</summary> int visible_in; ///<summary> /// Number of sticky notes visible from both outside and inside ///</summary> int visible_both; ///<summary> /// Number of sticky notes visible from one side only ///</summary> int visible_one; ///<summary> /// Number of sticky notes which are not visible at all ///</summary> int unvisible; }; ///<summary> ///Structure whcich holds actual state of sticky note area ///</summary> struct Model { ///<summary> ///Describes situation from outside ///</summary> int* situation_out; ///<summary> ///Describes situation from inside ///</summary> int* situation_in; ///<summary> /// Width of model ///</summary> int width; ///<summary> ///Height of model ///</summary> int height; ///<summary> ///List of notes visible from outsied ///</summary> queue_t* notes_out; ///<summary> ///List of notes visible from inside ///</summary> queue_t* notes_in; }; /* === DATA TYPES DEFINITIONS === */ ///<summary> /// Defines structure <c>StickyNote</c> as new data type ///<seealso cref="StickyNote"/> ///</summary> typedef struct StickyNote sticky_note_t; ///<summary> ///Defines structure <c>Result</c> as new data type ///<seealso cref="Result"/> ///</summary> typedef struct Result result_t; ///<summary> ///Defines structure <c>Model</c> as new data type ///<seealso cref="Model"/> ///</summary> typedef struct Model model_t;<file_sep>CFLAGS+=-Wall COMPILER=clang program: hw03.o node.o plane.o hw03utils.o $(COMPILER) $(CFLAGS) -o program obj/hw03.o obj/node.o obj/plane.o obj/hw03utils.o hw03.o: obj hw03.c $(COMPILER) $(CFLAGS) -c -o obj/hw03.o hw03.c node.o: node.h node.c $(COMPILER) $(CFLAGS) -c -o obj/node.o node.c plane.o: plane.h plane.c $(COMPILER) $(CFLAGS) -c -o obj/plane.o plane.c hw03utils.o : hw03utils.h hw03utils.c $(COMPILER) $(CFLAGS) -c -o obj/hw03utils.o hw03utils.c obj: mkdir obj clean: $(RM) -r ./obj $(RM) ./program $(RM) ./hw03.tar.bz2 zip: hw03.tar.bz2 @echo "" hw03.tar.bz2: hw03.tar bzip2 hw03.tar hw03.tar: tar -cvf hw03.tar ./*.c ./*.h<file_sep>///<summary> /// File containig simple definition of bool used in this project ///</summary> ///<remarks> /// Copyright 2019 <NAME> <<EMAIL>> /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http ://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissionsand /// limitations under the License. ///</remarks> #pragma once ///<summary> ///Define <c>TRUE</c> as some non-zero value (here 1) ///</summary> #define TRUE 1 ///<summary> ///Define <c>FALSE</c> as zero value ///</summary> #define FALSE 0 ///<summary> ///Simple definition of something like a "boolean" ///</summary> typedef char bool;<file_sep>#include "hw04utils.h" #include "globals.h" #include <stdlib.h> #include <math.h> #include "ConsoleColor.h" #include "config.h" #include <stdio.h> bool utils_point_on_map(point_t point) { bool reti = FALSE; #ifdef DEBUG/* console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf("Checking point ["); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("%d", point.X); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf(";"); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("%d", point.Y); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf("] ("); console_color_set_foreground(console_color_get_from_ansi(YELLOW_BRIGHT)); printf("%d", point.X); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf(">="); console_color_set_foreground(console_color_get_from_ansi(YELLOW_BRIGHT)); printf("%d", 0); printf(":"); if (point.X >= 0) { console_color_set_foreground(console_color_get_from_ansi(GREEN_BRIGHT)); printf("T"); } else { console_color_set_foreground(console_color_get_from_ansi(RED_BRIGHT)); printf("F"); } console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf(","); console_color_set_foreground(console_color_get_from_ansi(YELLOW_BRIGHT)); printf("%d", point.X); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf("<"); console_color_set_foreground(console_color_get_from_ansi(YELLOW_BRIGHT)); printf("%d", COLS); printf(":"); if (point.X < COLS) { console_color_set_foreground(console_color_get_from_ansi(GREEN_BRIGHT)); printf("T"); } else { console_color_set_foreground(console_color_get_from_ansi(RED_BRIGHT)); printf("F"); } printf(","); console_color_set_foreground(console_color_get_from_ansi(YELLOW_BRIGHT)); printf("%d", point.Y); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf(">="); console_color_set_foreground(console_color_get_from_ansi(YELLOW_BRIGHT)); printf("%d", 0); printf(":"); if (point.Y >= 0) { console_color_set_foreground(console_color_get_from_ansi(GREEN_BRIGHT)); printf("T"); } else { console_color_set_foreground(console_color_get_from_ansi(RED_BRIGHT)); printf("F"); } printf(","); console_color_set_foreground(console_color_get_from_ansi(YELLOW_BRIGHT)); printf("%d", point.Y); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf("<"); console_color_set_foreground(console_color_get_from_ansi(YELLOW_BRIGHT)); printf("%d", ROWS); printf(":"); if (point.Y < ROWS) { console_color_set_foreground(console_color_get_from_ansi(GREEN_BRIGHT)); printf("T"); } else { console_color_set_foreground(console_color_get_from_ansi(RED_BRIGHT)); printf("F"); } console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf(") >> ");*/ #endif // DEBUG if ( point.X >= 0 && point.X < COLS && point.Y >= 0 && point.Y < ROWS ) { reti = TRUE; } #ifdef DEBUG/* if (reti == TRUE) { console_color_set_foreground(console_color_get_from_ansi(GREEN_BRIGHT)); printf("TRUE"); } else { console_color_set_foreground(console_color_get_from_ansi(RED_BRIGHT)); printf("FALSE"); } console_color_reset_colors(); printf("\n");*/ #endif // DEBUG return reti; } bool utils_can_go_left(point_t point) { return (utils_point_on_map((point_t) { .X = point.X - 1, .Y = point.Y })); } bool utils_can_go_right(point_t point) { return (utils_point_on_map((point_t) { .X = point.X + 1, .Y = point.Y })); } bool utils_can_go_up(point_t point) { return (utils_point_on_map((point_t) { .X = point.X, .Y = point.Y - 1 })); } bool utils_can_go_down(point_t point) { return (utils_point_on_map((point_t) { .X = point.X, .Y = point.Y + 1 })); } int utils_compute_motor_ionization(int E_initial, point_t start, point_t finish) { int reti = E_initial; if (MAP[start.Y][start.X] < MAP[finish.Y][finish.X]) { reti += D_mov; } else if (MAP[start.Y][start.X] == MAP[finish.Y][finish.X]) { reti = reti + 0; } else if (MAP[start.Y][start.X] > MAP[finish.Y][finish.X] && E_initial >= D_mov) { reti -= D_mov; } else if (MAP[start.Y][start.X] > MAP[finish.Y][finish.X] && E_initial < D_mov) { reti = 0; } return reti; } int utils_compute_environment_ionization(int E_eng, point_t start, point_t finish) { int reti = E_eng; if (E_eng >= (D_env + MAP[finish.Y][finish.X])) { reti -= D_env; } else if ((D_env + MAP[finish.Y][finish.X]) > E_eng&& E_eng > MAP[finish.Y][finish.X]) { reti = MAP[finish.Y][finish.X]; } else if (E_eng <= MAP[finish.Y][finish.X]) { reti = reti + 0; } return reti; } int utils_compute_ionization(int E_motor, point_t start, point_t finish) { int reti = utils_compute_motor_ionization(E_motor, start, finish); reti = utils_compute_environment_ionization(reti, start, finish); return reti; } point_t* utils_create_point(int X, int Y) { point_t* reti = (point_t*)malloc(sizeof(point_t)); #ifdef DEBUG if (reti == NULL) { console_color_set_background(console_color_get_from_ansi(RED)); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("Allocating space for new POINT FAILED!\n"); console_color_reset_colors(); console_color_set_background(console_color_get_from_ansi(BLACK)); } #endif // DEBUG reti->X = X; reti->Y = Y; return reti; } situation_t* utils_create_situation(point_t* point, int energy, int steps) { situation_t* reti = (situation_t*)malloc(sizeof(situation_t)); #ifdef DEBUG if (reti == NULL) { console_color_set_background(console_color_get_from_ansi(RED)); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("Allocating space for new SITUATION FAILED!\n"); console_color_reset_colors(); console_color_set_background(console_color_get_from_ansi(BLACK)); } #endif // DEBUG reti->energy = energy; reti->steps = steps; reti->point = point; #ifdef DEBUG console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf("Creating situation:: point: "); console_color_set_foreground(console_color_get_from_ansi(CYAN_BRIGHT)); printf("[%d; %d]", reti->point->X, reti->point->Y); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf(", energy: "); console_color_set_foreground(console_color_get_from_ansi(MAGENTA_BRIGHT)); printf("%d", energy); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf(", steps: "); console_color_set_foreground(console_color_get_from_ansi(BLUE_BRIGHT)); printf("%d", steps); console_color_reset_colors(); printf("\n"); #endif // DEBUG return reti; } void utils_check_position(situation_t* situation) { //if (utils_point_on_map(*situation->point) == TRUE) //{ #ifdef DEBUG console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf("Checking position ["); console_color_set_foreground(console_color_get_from_rgb(255, 255, 255)); printf("%d", situation->point->X); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf(";"); console_color_set_foreground(console_color_get_from_rgb(255, 255, 255)); printf("%d", situation->point->Y); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf("] Queue size: "); console_color_set_foreground(console_color_get_from_ansi(BLUE_BRIGHT)); printf("%d", queue_count(SITUATIONS)); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf(", Energy: "); console_color_set_foreground(console_color_get_from_ansi(MAGENTA_BRIGHT)); printf("%d", situation->energy); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf(", Steps: "); console_color_set_foreground(console_color_get_from_ansi(CYAN)); printf("%d", situation->steps); console_color_reset_colors(); printf("\n"); #endif // DEBUG if (situation->point->Y == FINISH->Y && situation->point->X == FINISH->X) { #ifdef DEBUG console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); console_color_set_background(console_color_get_from_ansi(GREEN)); printf("Drone reached destination."); console_color_reset_colors(); console_color_set_background(console_color_get_from_ansi(BLACK)); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf("["); console_color_set_foreground(console_color_get_from_rgb(255, 255, 255)); printf("%d", situation->point->X); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf(";"); console_color_set_foreground(console_color_get_from_rgb(255, 255, 255)); printf("%d", situation->point->Y); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf("]\n"); console_color_reset_colors(); #endif // DEBUG if (situation->steps < MIN_STEPS) { MIN_STEPS = situation->steps; #ifdef DEBUG console_color_set_foreground(console_color_get_from_ansi(GREEN_BRIGHT)); printf("Distance to destination: "); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("%d", situation->steps); console_color_set_foreground(console_color_get_from_ansi(GREEN_BRIGHT)); printf(" steps"); console_color_reset_colors(); printf("\n"); #endif // DEBUG return; } } else if (situation->steps >= MIN_STEPS) { console_color_set_background(console_color_get_from_ansi(YELLOW)); console_color_set_foreground(console_color_get_from_ansi(BLACK)); printf("Drone reached maximal steps without destination."); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); console_color_set_background(console_color_get_from_ansi(BLACK)); printf("["); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("%d", situation->point->X); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf(";"); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("%d", situation->point->Y); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf("]\n"); console_color_reset_colors(); return; } else if (situation->energy <= 0) { #ifdef DEBUG console_color_set_background(console_color_get_from_ansi(YELLOW_BRIGHT)); console_color_set_foreground(console_color_get_from_ansi(BLACK)); printf("Drone out of energy."); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); console_color_set_background(console_color_get_from_ansi(BLACK)); printf("["); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("%d", situation->point->X); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf(";"); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("%d", situation->point->Y); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf("]\n"); console_color_reset_colors(); #endif // DEBUG return; } if (VISITED[situation->point->Y][situation->point->X] == NULL) { #ifdef DEBUG #ifdef DEBUG console_color_set_background(console_color_get_from_ansi(CYAN)); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("Drone reached UNKNOWN position."); console_color_reset_colors(); console_color_set_background(console_color_get_from_ansi(BLACK)); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf("["); console_color_set_foreground(console_color_get_from_rgb(255, 255, 255)); printf("%d", situation->point->X); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf(";"); console_color_set_foreground(console_color_get_from_rgb(255, 255, 255)); printf("%d", situation->point->Y); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf("]\n"); console_color_reset_colors(); #endif // DEBUG #endif // DEBUG VISITED[situation->point->Y][situation->point->X] = situation; } else if (VISITED[situation->point->Y][situation->point->X]->energy > situation->energy) { #ifdef DEBUG console_color_set_background(console_color_get_from_ansi(BLUE)); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("Drone reached known position with "); console_color_set_foreground(console_color_get_from_ansi(RED_BRIGHT)); printf("lower"); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf(" energy."); console_color_reset_colors(); console_color_set_background(console_color_get_from_ansi(BLACK)); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf("["); console_color_set_foreground(console_color_get_from_rgb(255, 255, 255)); printf("%d", situation->point->X); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf(";"); console_color_set_foreground(console_color_get_from_rgb(255, 255, 255)); printf("%d", situation->point->Y); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf("]"); printf("(before: "); console_color_set_foreground(console_color_get_from_ansi(BLUE_BRIGHT)); printf("%d", VISITED[situation->point->Y][situation->point->X]->energy); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf(")"); console_color_reset_colors(); printf("\n"); #endif // DEBUG return; } else if (VISITED[situation->point->Y][situation->point->X]->energy < situation->energy) { #ifdef DEBUG console_color_set_background(console_color_get_from_ansi(BLUE)); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("Drone reached known position with "); console_color_set_foreground(console_color_get_from_ansi(GREEN_BRIGHT)); printf("higher"); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf(" energy."); console_color_reset_colors(); console_color_set_background(console_color_get_from_ansi(BLACK)); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf("["); console_color_set_foreground(console_color_get_from_rgb(255, 255, 255)); printf("%d", situation->point->X); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf(";"); console_color_set_foreground(console_color_get_from_rgb(255, 255, 255)); printf("%d", situation->point->Y); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf("]"); printf("(before: "); console_color_set_foreground(console_color_get_from_ansi(BLUE_BRIGHT)); printf("%d", VISITED[situation->point->Y][situation->point->X]->energy); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf(")"); console_color_reset_colors(); printf("\n"); #endif // DEBUG VISITED[situation->point->Y][situation->point->X] = situation; } else if (VISITED[situation->point->Y][situation->point->X]->energy == situation->energy) { if (VISITED[situation->point->Y][situation->point->X]->steps > situation->steps) { #ifdef DEBUG console_color_set_background(console_color_get_from_ansi(BLUE)); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("Drone reached known position with same energy and "); console_color_set_foreground(console_color_get_from_ansi(GREEN_BRIGHT)); printf("less"); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf(" steps."); console_color_reset_colors(); console_color_set_background(console_color_get_from_ansi(BLACK)); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf("["); console_color_set_foreground(console_color_get_from_rgb(255, 255, 255)); printf("%d", situation->point->X); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf(";"); console_color_set_foreground(console_color_get_from_rgb(255, 255, 255)); printf("%d", situation->point->Y); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf("]"); printf("(before: "); console_color_set_foreground(console_color_get_from_ansi(BLUE_BRIGHT)); printf("%d", VISITED[situation->point->Y][situation->point->X]->steps); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf(")"); console_color_reset_colors(); printf("\n"); #endif // DEBUG VISITED[situation->point->Y][situation->point->X] = situation; } else { #ifdef DEBUG console_color_set_background(console_color_get_from_ansi(BLUE)); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("Drone reached known position with same energy and "); console_color_set_foreground(console_color_get_from_ansi(RED_BRIGHT)); printf("more or same"); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf(" steps."); console_color_reset_colors(); console_color_set_background(console_color_get_from_ansi(BLACK)); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf("["); console_color_set_foreground(console_color_get_from_rgb(255, 255, 255)); printf("%d", situation->point->X); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf(";"); console_color_set_foreground(console_color_get_from_rgb(255, 255, 255)); printf("%d", situation->point->Y); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf("]"); printf("(before: "); console_color_set_foreground(console_color_get_from_ansi(BLUE_BRIGHT)); printf("%d", VISITED[situation->point->Y][situation->point->X]->steps); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf(")"); console_color_reset_colors(); printf("\n"); #endif // DEBUG return; } } if (utils_can_go_down(*situation->point) == TRUE) { point_t* next_point = utils_create_point(situation->point->X , situation->point->Y+1); int next_energy = utils_compute_ionization(situation->energy, *situation->point, *next_point); situation_t* next_situation = utils_create_situation(next_point, next_energy, situation->steps + 1); #ifdef DEBUG if (next_situation == NULL) { console_color_set_background(console_color_get_from_ansi(RED)); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("Allocating space for NEXT SITUATION FAILED!"); console_color_set_background(console_color_get_from_ansi(BLACK)); console_color_set_foreground(console_color_get_from_ansi(RED_BRIGHT)); printf("( going "); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("down"); console_color_set_foreground(console_color_get_from_ansi(RED_BRIGHT)); printf(" from ["); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("%d", situation->point->X); console_color_set_foreground(console_color_get_from_ansi(RED_BRIGHT)); printf(";"); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("%d", situation->point->Y); console_color_set_foreground(console_color_get_from_ansi(RED_BRIGHT)); printf("]"); console_color_reset_colors(); printf("\n"); } #endif // DEBUG queue_push(SITUATIONS, next_situation); } if (utils_can_go_right(*situation->point) == TRUE) { point_t* next_point = utils_create_point(situation->point->X + 1, situation->point->Y); int next_energy = utils_compute_ionization(situation->energy, *situation->point, *next_point); situation_t* next_situation = utils_create_situation(next_point, next_energy, situation->steps + 1); #ifdef DEBUG if (next_situation == NULL) { console_color_set_background(console_color_get_from_ansi(RED)); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("Allocating space for NEXT SITUATION FAILED!"); console_color_set_background(console_color_get_from_ansi(BLACK)); console_color_set_foreground(console_color_get_from_ansi(RED_BRIGHT)); printf("( going "); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("right"); console_color_set_foreground(console_color_get_from_ansi(RED_BRIGHT)); printf(" from ["); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("%d", situation->point->X); console_color_set_foreground(console_color_get_from_ansi(RED_BRIGHT)); printf(";"); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("%d", situation->point->Y); console_color_set_foreground(console_color_get_from_ansi(RED_BRIGHT)); printf("]"); console_color_reset_colors(); printf("\n"); } #endif // DEBUG queue_push(SITUATIONS, next_situation); } if (utils_can_go_up(*situation->point) == TRUE) { point_t* next_point = utils_create_point(situation->point->X, situation->point->Y - 1); int next_energy = utils_compute_ionization(situation->energy, *situation->point, *next_point); situation_t* next_situation = utils_create_situation(next_point, next_energy, situation->steps + 1); #ifdef DEBUG if (next_situation == NULL) { console_color_set_background(console_color_get_from_ansi(RED)); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("Allocating space for NEXT SITUATION FAILED!"); console_color_set_background(console_color_get_from_ansi(BLACK)); console_color_set_foreground(console_color_get_from_ansi(RED_BRIGHT)); printf("( going "); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("up"); console_color_set_foreground(console_color_get_from_ansi(RED_BRIGHT)); printf(" from ["); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("%d", situation->point->X); console_color_set_foreground(console_color_get_from_ansi(RED_BRIGHT)); printf(";"); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("%d", situation->point->Y); console_color_set_foreground(console_color_get_from_ansi(RED_BRIGHT)); printf("]"); console_color_reset_colors(); printf("\n"); } #endif // DEBUG queue_push(SITUATIONS, next_situation); } if (utils_can_go_left(*situation->point) == TRUE) { point_t* next_point = utils_create_point(situation->point->X - 1, situation->point->Y); int next_energy = utils_compute_ionization(situation->energy, *situation->point, *next_point); situation_t* next_situation = utils_create_situation(next_point, next_energy, situation->steps + 1); #ifdef DEBUG if (next_situation == NULL) { console_color_set_background(console_color_get_from_ansi(RED)); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("Allocating space for NEXT SITUATION FAILED!"); console_color_set_background(console_color_get_from_ansi(BLACK)); console_color_set_foreground(console_color_get_from_ansi(RED_BRIGHT)); printf("( going "); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("left"); console_color_set_foreground(console_color_get_from_ansi(RED_BRIGHT)); printf(" from ["); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("%d", situation->point->X); console_color_set_foreground(console_color_get_from_ansi(RED_BRIGHT)); printf(";"); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("%d", situation->point->Y); console_color_set_foreground(console_color_get_from_ansi(RED_BRIGHT)); printf("]"); console_color_reset_colors(); printf("\n"); } #endif // DEBUG queue_push(SITUATIONS, next_situation); } //} } int utils_situation_step_comparator(void* situationA, void* situationB) { situation_t* sA = (situation_t*)situationA; situation_t* sB = (situation_t*)situationB; int reti = -1; if ( sA->point->X == sB->point->X && sA->point->Y == sB->point->Y && sA->steps == sB->steps ) { reti = 0; } else { reti = sA->steps - sB->steps; } return reti; } int utils_situation_energy_comparator(void* situationA, void* situationB) { situation_t* sA = (situation_t*)situationA; situation_t* sB = (situation_t*)situationB; #ifdef DEBUG #endif // DEBUG int reti = -1; if ( sA->point->X == sB->point->X && sA->point->Y == sB->point->Y && sA->energy == sB->energy ) { reti = 0; } else { reti = sA->energy - sB->energy; } return reti; } int utils_situation_exact_comparator(void* situationA, void* situationB) { situation_t* sA = (situation_t*)situationA; situation_t* sB = (situation_t*)situationB; int reti = -1; if ( sA->point->X == sB->point->X && sA->point->Y == sB->point->Y && sA->energy == sB->energy && sA->steps == sB->steps ) { reti = 0; } else { point_t vector = { .X = sA->point->X - sB->point->X, .Y = sA->point->X - sB->point->X, }; reti = sqrt(pow(vector.X, 2) + pow(vector.Y, 2)); } return reti; } #ifdef SHOW_MAP void utils_display_map(point_t* point) { printf("\033[H"); for (int r = 0; r < ROWS; r++) { for (int c = 0; c < COLS; c++) { console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); console_color_t color = console_color_get_from_ansi(BLACK_BRIGHT); if (r == 0 && c == 0) { color = console_color_get_from_ansi(GREEN); } else if (r == FINISH->Y && c == FINISH->X) { color = console_color_get_from_ansi(RED); } else if (point->X == 0 && point->Y == 0) { //color = console_color_get_from_ansi(GREEN_BRIGHT); } else if (point->X == FINISH->X && point->Y == FINISH->Y) { //color = console_color_get_from_ansi(RED_BRIGHT); } else if (point->X == c && point->Y == r) { color = console_color_get_from_ansi(YELLOW_BRIGHT); } else if ( (point->X - 1 == c && point->Y == r)|| (point->X + 1 == c && point->Y == r)|| (point->Y - 1 == r && point->X == c)|| (point->Y + 1 == r && point->X == c) ) { color = console_color_get_from_ansi(WHITE_BRIGHT); } console_color_set_foreground(color); printf(" %2d ", MAP[r][c]); console_color_reset_colors(); } printf("\n"); } printf("\n"); console_color_set_foreground(console_color_get_from_ansi(WHITE)); printf("Actual steps: "); console_color_set_foreground(console_color_get_from_ansi(BLUE_BRIGHT)); printf("%d", STEPS); console_color_reset_colors(); printf("\n"); usleep(SHOW_DELAY); } #endif // SHOW_MAP <file_sep>COMPILER=clang CFLAGS+=-Wall program: hw04.o consolecolor.o consolecolorutils.o queue.o hw04utils.o $(COMPILER) $(CFLAGS) -lm -o program obj/hw04.o obj/consolecolor.o obj/consolecolorutils.o obj/queue.o obj/hw04utils.o hw04.o: obj hw04.c $(COMPILER) $(CFLAGS) -c -o obj/hw04.o hw04.c obj: mkdir obj consolecolor.o: obj ConsoleColor.c ConsoleColor.h $(COMPILER) $(CFLAGS) -c -o obj/consolecolor.o ConsoleColor.c consolecolorutils.o: obj ConsoleColor_utils.c ConsoleColor_utils.h $(COMPILER) $(CFLAGS) -c -o obj/consolecolorutils.o ConsoleColor_utils.c queue.o: obj queue.c queue.h $(COMPILER) $(CFLAGS) -c -o obj/queue.o queue.c hw04utils.o: obj hw04utils.c hw04utils.h $(COMPILER) $(CFLAGS) -c -o obj/hw04utils.o hw04utils.c clean: $(RM) -r obj $(RM) program $(RM) hw04.tar.bz2 zip: hw04.tar.bz2 @echo "Archive created" hw04.tar.bz2: hw04.tar bzip2 hw04.tar hw04.tar: $(RM) hw04.tar.bz2 tar -cvf hw04.tar *.c *.h <file_sep>///<summary> /// File containig implementation of functions and data types used for printing colors to console /// used in logging library ///</summary> ///<remarks> /// Copyright 2019 <NAME> <<EMAIL>> /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http ://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissionsand /// limitations under the License. ///</remarks> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "ConsoleColor.h" #include "ConsoleColor_utils.h" //============================================================================================================================= char* console_color_get_background_from_rgb(console_color_data_t color) { char* reti = malloc(32 * sizeof(char)); sprintf(reti, "\033[48;2;%i;%i;%im", color.rgb_color.red, color.rgb_color.green, color.rgb_color.blue); return reti; } //============================================================================================================================= char* console_color_get_foreground_from_rgb(console_color_data_t color) { char* reti = malloc(32 * sizeof(char)); sprintf(reti, "\033[38;2;%i;%i;%im", color.rgb_color.red, color.rgb_color.green, color.rgb_color.blue); return reti; } //============================================================================================================================= char* console_color_get_background_from_ansi(console_color_data_t color) { char* reti = malloc(32 * sizeof(char)); sprintf(reti, "\033[;%im", color.ansi_color + 10); return reti; } //============================================================================================================================= char* console_color_get_foreground_from_ansi(console_color_data_t color) { char* reti = malloc(32 * sizeof(char)); sprintf(reti, "\033[%im", color.ansi_color); return reti; } //============================================================================================================================= char* console_color_get_background(console_color_t* color) { switch (color->type) { case ANSI: return console_color_get_background_from_ansi(color->data); break; case RGB: return console_color_get_background_from_rgb(color->data); break; } } //============================================================================================================================= char* console_color_get_foreground(console_color_t* color) { switch (color->type) { case ANSI: return console_color_get_foreground_from_ansi(color->data); break; case RGB: return console_color_get_foreground_from_rgb(color->data); break; } } //============================================================================================================================= char* console_color_get_color_code(console_color_t* foreground, console_color_t* background) { char* reti = malloc(32 * sizeof(char)); if (foreground->type == ANSI && background->type == ANSI) //Both colors are defined by ANSI code { sprintf(reti, "\033[%i;%im", foreground->data.ansi_color, background->data.ansi_color + 10); } else if (foreground->type == ANSI && background->type == RGB) { sprintf(reti, "\033[%i;m", foreground->data.ansi_color); sprintf(reti + strlen(reti), "\033[48;2;%i;%i;%im", background->data.rgb_color.red, background->data.rgb_color.green, background->data.rgb_color.blue); } else if (foreground->type == RGB && background->type == ANSI) { sprintf(reti, "\033[%i;m", background->data.ansi_color); sprintf(reti + strlen(reti), "\033[38;2;%i;%i;%im", foreground->data.rgb_color.red, foreground->data.rgb_color.green, foreground->data.rgb_color.blue); } else if (foreground->type == RGB && background->type == RGB) { char* fg = console_color_get_foreground_from_rgb(foreground->data); char* bg = console_color_get_background_from_rgb(background->data); strcpy(reti, fg); strcpy(reti + strlen(reti), bg); //free(fg); //free(bg); } return reti; } //============================================================================================================================= <file_sep>COMPILER=clang CFLAGS+=-Wall all: program program: main.o experiment.o utils.o laboratory.o queue.o dynamic_queue.o $(COMPILER) $(CFLAGS) -lm ./obj/utils.o ./obj/queue.o ./obj/dynamic_queue.o ./obj/laboratory.o ./obj/experiment.o ./obj/main.o -o ./program obj: mkdir ./obj main.o: obj main.c $(COMPILER) $(CFLAGS) -c ./main.c -o ./obj/main.o experiment.o: obj experiment.c $(COMPILER) $(CFLAGS) -c ./experiment.c -o ./obj/experiment.o utils.o: obj utils.c $(COMPILER) $(CFLAGS) -c ./utils.c -o ./obj/utils.o laboratory.o: obj laboratory.c $(COMPILER) $(CFLAGS) -c -lm ./laboratory.c -o ./obj/laboratory.o queue.o: obj queue.c $(COMPILER) $(CFLAGS) -c ./queue.c -o ./obj/queue.o dynamic_queue.o: obj dynamic_queue.c $(COMPILER) $(CFLAGS) -c ./dynamic_queue.c -o ./obj/dynamic_queue.o clean: $(RM) -r ./obj $(RM) ./program<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NetworkSender { class Program { static void Main(string[] args) { int port = GetPortFromArgument(args) == -1 ? 1350 : GetPortFromArgument(args); Logger logger = new Logger(Structures.LogLevel.TINY, Structures.DateFormat.NONE, Structures.TimeFormat.NONE); logger.LogTiny("Logger started"); Network net = new Network(System.Net.IPAddress.Loopback, port, logger); string data = ""; do { Console.ForegroundColor = ConsoleColor.Gray; Console.Write("Enter data, "); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("--help"); Console.ForegroundColor = ConsoleColor.Gray; Console.Write(" for help or "); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("\\0"); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine(" for end:"); Console.ForegroundColor = ConsoleColor.White; data = Console.ReadLine(); if (data == "--help") { ShowHelp(); ConsoleKeyInfo key = Console.ReadKey(); ConsoleKey k = key.Key; while (k != ConsoleKey.Q && k != ConsoleKey.Escape) { key = Console.ReadKey(); k = key.Key; } Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.Gray; if (k == ConsoleKey.Q) { Console.Clear(); Console.CursorVisible = true; } else if (k == ConsoleKey.Escape) { return; } } else if (data != "\\0") { net.sendMessage(data); } } while (data != "\\0"); } public static int GetPortFromArgument(string[] args) { int reti = -1; foreach (string arg in args) { if (arg.ToLower().Contains("--port=")) { char[] separator = { '=' }; string[] argument = arg.Split(separator); string value = argument.Last(); try { reti = int.Parse(value); } catch { } } } return reti; } static void ShowHelp() { Console.Clear(); string header = "NETWORK SENDER"; int before = (Console.WindowWidth / 2) - (header.Length / 2); int after = Console.WindowWidth - before - header.Length; Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Black; for (int i = 0; i < before; i++) { Console.Write(" "); } Console.Write(header); for (int i = 0; i < after; i++) { Console.Write(" "); } Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Gray; Console.BackgroundColor = ConsoleColor.Black; Console.WriteLine(); Console.WriteLine(" Network sender is simple program to send text data (ASCII) over network using UDP."); Console.WriteLine(); Console.WriteLine(" USAGE"); Console.WriteLine(" It's simple to work with network sender. When program starts, there are three options"); Console.WriteLine(" what to type to console."); Console.Write(" - "); Console.ForegroundColor = ConsoleColor.White; Console.Write(" some text "); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine(); Console.WriteLine(" Some text to be sent over network"); Console.WriteLine(); Console.Write(" - "); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write(" --help"); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine(); Console.WriteLine(" Views this help page"); Console.WriteLine(); Console.Write(" - "); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write(" \\0"); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine(); Console.WriteLine(" Exits program"); Console.WriteLine(); Console.WriteLine(" PARAMETERS"); Console.WriteLine(" Program can run without parameters, but there is one parameter which can be set:"); Console.Write(" "); Console.ForegroundColor = ConsoleColor.Cyan; Console.Write("--port="); Console.ForegroundColor = ConsoleColor.Blue; Console.Write("<int>"); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine(); Console.Write(" Where "); Console.ForegroundColor = ConsoleColor.Blue; Console.Write("<int>"); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine(" can be any integer number from 0 to 65535 (recommended >= 1024)."); Console.WriteLine(" This parameter sets port number, to where will be all data sent to."); Console.WriteLine(); Console.WriteLine(" PURPOSE"); Console.Write(" This program was originally developed for testing functionality of program called "); Console.ForegroundColor = ConsoleColor.White; Console.Write("NetConsole"); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine("."); Console.WriteLine(" From this there comes main purpose of this program - testing network software."); Console.WriteLine(" Because of above, we show manual how to properly send data to NetConsole."); Console.WriteLine(" What to type to check NetConsole functionality? Basically it is CSV format:"); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write(" C"); Console.ForegroundColor = ConsoleColor.Gray; Console.Write(" | "); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("E"); Console.ForegroundColor = ConsoleColor.Gray; Console.Write(" | "); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("W"); Console.ForegroundColor = ConsoleColor.Gray; Console.Write(" | "); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("I"); Console.ForegroundColor = ConsoleColor.Gray; Console.Write(" | "); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("B"); Console.ForegroundColor = ConsoleColor.Gray; Console.Write(" | "); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("S"); Console.ForegroundColor = ConsoleColor.Gray; Console.Write(" | "); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("T,message"); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine(); Console.WriteLine(" Where first letter defines level of log:"); Console.Write(" - C for "); Console.ForegroundColor = ConsoleColor.Black; Console.BackgroundColor = ConsoleColor.Red; Console.WriteLine("[CRITICAL]"); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.Gray; Console.Write(" - E for "); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("[ ERROR ]"); Console.ForegroundColor = ConsoleColor.Gray; Console.Write(" - W for "); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("[WARNING ]"); Console.ForegroundColor = ConsoleColor.Gray; Console.Write(" - I for "); Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine("[ INFO ]"); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine(" - B for (basic)"); Console.Write(" - S for "); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("[SUCCESS ]"); Console.ForegroundColor = ConsoleColor.Gray; Console.Write(" - T for "); Console.ForegroundColor = ConsoleColor.DarkGray; Console.Write("( tiny )"); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine(); Console.WriteLine(" and message text to be logged."); Console.ForegroundColor = ConsoleColor.Black; Console.BackgroundColor = ConsoleColor.White; string footer = "Press <Q> for quit help, <ESC> for exit program"; Console.Write(footer); for (int i = 0; i < (Console.WindowWidth - footer.Length); i++) { Console.Write(" "); } Console.CursorVisible = false; } } } <file_sep>cat $1 | ./program<file_sep>CFLAGS+=-Wall OUTPUT=./program COMPILER=clang program: queue.o hw01utils.o hw01.o $(COMPILER) $(CFLAGS) -o $(OUTPUT) ./obj/hw01.o ./obj/hw01utils.o ./obj/queue.o hw01utils.o: hw01utils.h obj $(COMPILER) $(CFLAGS) -c -o ./obj/hw01utils.o hw01utils.c hw01.o: obj $(COMPILER) $(CFLAGS) -c -o ./obj/hw01.o hw01.c queue.o: obj $(COMPILER) $(CFLAGS) -c -o ./obj/queue.o queue.c obj: mkdir ./obj run: $(OUTPUT) clean: rm -r ./obj rm $(OUTPUT) zip: @echo "Not implemented yet"<file_sep>///<summary> /// File containig declarations of utility functions and data types used for printing colors to console /// used in logging library ///</summary> ///<remarks> /// Copyright 2019 <NAME> <<EMAIL>> /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http ://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissionsand /// limitations under the License. ///</remarks> #ifndef __CONSOLE_COLOR_UTILS_H__ #define __CONSOLE_COLOR_UTILS_H__ #include "ConsoleColor.h" ///<summary> ///Last used foreground color ///</summary> static console_color_t console_color_foreground; ///<summary> ///Last used background ///</summary> static console_color_t console_color_background; ///<summary> ///Gets printable ansi escape code for color as background ///</summary> ///<param name="color">Color which code will be got</param> char* console_color_get_background(console_color_t* color); ///<summary> ///Gets printable ansi escape code for color as foreground ///</summary> ///<param name="color">Color which code will be got</param> char* console_color_get_foreground(console_color_t* color); ///<summary> ///Gets printable ansi escape code for color as background ///</summary> ///<param name="color">Color in rgb model which code will be got</param> char* console_color_get_background_from_rgb(console_color_data_t color); ///<summary> ///Gets printable ansi escape code for color as foreground ///</summary> ///<param name="color">Color in rgb model which code will be got</param> char* console_color_get_foreground_from_rgb(console_color_data_t color); ///<summary> ///Gets printable ansi escape code for color as background ///</summary> ///<param name="color">Color as ansi escape code model which code will be got</param> char* console_color_get_background_from_ansi(console_color_data_t color); ///<summary> ///Gets printable ansi escape code for color as foreground ///</summary> ///<param name="color">Color as ansi escape code model which code will be got</param> char* console_color_get_foreground_from_rgb(console_color_data_t color); ///<summary> ///Gets printable ansi escape code for color for both foreground and background ///</summary> ///<param name="foreground">Color which will be foruground</param> ///<param name="background">Color which will be background</param> char* console_color_get_color_code(console_color_t* foreground, console_color_t* background); #endif // !__CONSOLE_COLOR_UTILS_H__ <file_sep>#include <stdio.h> #include <stdlib.h> #include "config.h" #include "utils.h" #include "experiment.h" #include "laboratory.h" static volatile int COUNT = 0; static volatile int DAYS = 0; int main(int argc, char* argv[]) { int reti = EXIT_SUCCESS; //Read basic attributes of quest scanf("%d %d", &COUNT, &DAYS); #ifdef DEBUG printf("Loaded:: count: %d, days: %d\n", COUNT, DAYS); #endif // DEBUG //Read all experiments experiment_t** experiments = malloc(COUNT * sizeof(experiment_t*)); for (int i = 0; i < COUNT; i++) { int days, income = 0; scanf("%d %d", &days, &income); experiment_t* experiment = experiment_create(i, days, income); for (int j = 0; j < experiment_get_days_count(experiment); j++) { int active_day = 0; scanf("%d", &active_day); experiment_set_active_day(experiment, j, active_day); } experiments[i] = experiment; #ifdef DEBUG printf("Loaded experiment::[%d] income:%d, days:%d (", experiments[i]->id, experiments[i]->income, experiments[i]->days_count); util_print_int_array(experiments[i]->days, experiments[i]->days_count); printf(")\n"); #endif // DEBUG } //Creates laboratory laboratory_t* default_lab = laboratory_create(DAYS, COUNT, experiments); //Sort experiments in laboratory laboratory_quicksort_experiments_by_length_desc(default_lab); #ifdef DEBUG printf("Sorted experiments:\n"); experiment_t** exs = laboratory_get_experiments(default_lab); int exs_count = laboratory_get_experiments_count(default_lab); for (int i = 0; i < exs_count; i++) { printf("[%d]:: id:%d, income: %d, days: %d (", i, exs[i]->id, exs[i]->income, exs[i]->days_count); util_print_int_array(exs[i]->days, exs[i]->days_count); printf(")\n"); } #endif // DEBUG //Make state tree //laboratory_recursive_scheduler(laboratory_copy(default_lab), -1); laboratory_scheduler(default_lab); return reti; }<file_sep>#include "config.h" #include "queue.h" #include "sorted.h" #include <stdio.h> #include <stdlib.h> //----------------------------------------------------------------------------------------------------------------------------------------------- queue_t* queue_create_static(int length) { queue_t* reti = malloc(1 * sizeof(queue_t)); #ifdef SAFE_MODE if (reti == NULL) { fprintf(stderr, "ERROR [queue.c/%d]: Allocation memory for queue failed!\n", __LINE__); exit(EXIT_FAILURE); } if (reti != NULL) { #endif // SAFE_MODE reti->length = length; reti->count = 0; reti->head = 0; reti->tail = 0; reti->next_head = 0; reti->data = malloc(reti->length * sizeof(int)); #ifdef SAFE_MODE if (reti->data == NULL) { fprintf(stderr, "ERROR [queue.c/%d]: Allocation memory for 'queue->data <int[%d]>' failed!\n", __LINE__, reti->length); exit(EXIT_FAILURE); } #endif // SAFE_MODE #ifdef SAFE_MODE } #endif // SAFE_MODE return reti; } //----------------------------------------------------------------------------------------------------------------------------------------------- bool queue_push(queue_t* queue, int data) { bool reti = FALSE; if (queue_is_full(queue) == FALSE) { reti = TRUE; queue->data[queue->tail] = data; queue->tail++; queue->count++; #ifdef DEBUG //printf("%d added to queue\n", data); #endif // DEBUG } return reti; } //----------------------------------------------------------------------------------------------------------------------------------------------- int queue_pop(queue_t* queue) { int reti = NULL; if (queue->count > 0) { reti = queue->data[queue->head]; queue->head++; queue->count--; #ifdef DEBUG printf("%d popped from queue (new length: %d)\n", reti, queue->count); #endif // DEBUG } return reti; } //----------------------------------------------------------------------------------------------------------------------------------------------- bool queue_is_empty(queue_t* queue) { return (queue->count == 0 ? TRUE : FALSE); } //----------------------------------------------------------------------------------------------------------------------------------------------- bool queue_is_full(queue_t* queue) { return (queue->tail == queue->length ? TRUE : FALSE); } //----------------------------------------------------------------------------------------------------------------------------------------------- int queue_count(queue_t* queue) { return queue->count; } //----------------------------------------------------------------------------------------------------------------------------------------------- int queue_at(queue_t* queue, int index) { int reti = NULL; if (queue->head <= index && queue->tail > index) { reti = queue->data[index]; } return reti; } //----------------------------------------------------------------------------------------------------------------------------------------------- bool queue_is_not_empty(queue_t* queue) { bool reti = (queue_count(queue) >= 1) ? TRUE : FALSE; return reti; } //----------------------------------------------------------------------------------------------------------------------------------------------- int queue_next(queue_t* queue) { int reti = NULL; if (queue_next_not_empty(queue) == TRUE) { reti = queue->data[queue->next_head]; queue->next_head++; } return reti; } //----------------------------------------------------------------------------------------------------------------------------------------------- bool queue_next_not_empty(queue_t* queue) { return (queue->next_head >= queue->tail) ? FALSE : TRUE; } //----------------------------------------------------------------------------------------------------------------------------------------------- void queue_reset_next_index(queue_t* queue) { queue->next_head = queue->head; } //----------------------------------------------------------------------------------------------------------------------------------------------- queue_t* queue_reverse_data(queue_t* queue) { queue_t* reti = queue_create_static(queue_count(queue)); for (int i = (queue->tail - 1); i >= queue->head; i--) { queue_push(reti, queue_at(queue, i)); } return reti; } //----------------------------------------------------------------------------------------------------------------------------------------------- void queue_delete(queue_t* queue) { free(queue->data); free(queue); } //----------------------------------------------------------------------------------------------------------------------------------------------- #ifdef DEBUG void queue_print(queue_t* queue) { for (int i = queue->head; i < queue->tail; i++) { printf("%d ", queue->data[i]); } printf("\n"); } #endif // DEBUG //----------------------------------------------------------------------------------------------------------------------------------------------- bool queue_contains(queue_t* queue, int element, sort_t sort) { bool reti = FALSE; if (sort == NONE) { for (int i = queue->head; i <= queue->tail; i++) { if (queue_at(queue, i) == element) { reti = TRUE; break; } } } else { reti = queue_binary_search(queue, element, sort); } return reti; } //----------------------------------------------------------------------------------------------------------------------------------------------- bool queue_binary_search(queue_t* queue, int element, sort_t sort) { return queue_binary_search_recursive(queue, element, sort, queue->head, queue->tail); } //----------------------------------------------------------------------------------------------------------------------------------------------- bool queue_binary_search_recursive(queue_t* queue, int element, sort_t sort, int start_index, int end_index) { int index = queue_binary_search_next_index(start_index, end_index, queue); int found = queue_at(queue, index); #ifdef DEBUG printf("( %d %d %d) f:%d, s:%d [%d %d %d]\n", start_index, index, end_index, found, element, queue_at(queue, start_index), queue_at(queue, index), queue_at(queue, end_index)); #endif // DEBUG if (found == element) { #ifdef DEBUG printf(">> TRUE\n"); #endif // DEBUG return TRUE; } else if ((start_index == index && queue_index_in_queue(start_index, queue)) || (end_index == index && queue_index_in_queue(end_index, queue))) { if ((queue_at(queue, start_index) == element && queue_index_in_queue(start_index, queue) == TRUE) || (queue_at(queue, end_index) == element && queue_index_in_queue(end_index, queue) == TRUE)) { #ifdef DEBUG printf(">> TRUE\n"); #endif // DEBUG return TRUE; } else { #ifdef DEBUG printf(">> FALSE\n"); #endif // DEBUG return FALSE; } } else if (index != -1) { if (sort == ASC) { if (found > element) { return queue_binary_search_recursive(queue, element, sort, start_index, index); } else if (found < element) { return queue_binary_search_recursive(queue, element, sort, index, end_index); } } else if (sort == DESC) { if (found > element) { return queue_binary_search_recursive(queue, element, sort, index, end_index); } else if (found < element) { return queue_binary_search_recursive(queue, element, sort, start_index, index); } } else { if ((queue_at(queue, start_index) == element && queue_index_in_queue(start_index, queue) == TRUE) || (queue_at(queue, end_index) == element && queue_index_in_queue(end_index, queue) == TRUE)) { #ifdef DEBUG printf(">> TRUE\n"); #endif // DEBUG return TRUE; } } } else if (index == -1) { if ((queue_at(queue, start_index) == element && queue_index_in_queue(start_index, queue) == TRUE) || (queue_at(queue, end_index) == element && queue_index_in_queue(end_index, queue))) { #ifdef DEBUG printf(">> TRUE\n"); #endif // DEBUG return TRUE; } } #ifdef DEBUG printf(">> FALSE\n"); #endif // DEBUG return FALSE; } //----------------------------------------------------------------------------------------------------------------------------------------------- int queue_binary_search_next_index(int start_index, int end_index, queue_t* queue) { int reti = -1; int computed = (start_index + end_index) / 2; if (queue_index_in_queue(computed, queue) == TRUE && start_index != end_index) { reti = computed; } return reti; } //----------------------------------------------------------------------------------------------------------------------------------------------- bool queue_index_in_queue(int index, queue_t* queue) { bool reti = FALSE; if (index >= queue->head && index < queue->tail) { reti = TRUE; } return reti; } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NetConsole { public static class Structures { public enum LogLevel { CRITICAL, ERROR, WARNING, SUCCESS, INFO, BASIC, TINY } public enum DateFormat { NONE, SHORT, LONG } public enum TimeFormat { NONE, HH, HH_MM, HH_MM_SS } public struct ConsoleColorScheme { public ConsoleColor header_background; public ConsoleColor header_foreground; public ConsoleColor body_background; public ConsoleColor body_foreground; public ConsoleColorScheme(ConsoleColor header_background, ConsoleColor header_foreground, ConsoleColor body_background, ConsoleColor body_foreground) { this.header_background = header_background; this.header_foreground = header_foreground; this.body_background = body_background; this.body_foreground = body_foreground; } } } } <file_sep>#include "queue.h" #include "config.h" #include "ConsoleColor.h" #include <stdlib.h> #include <stdio.h> queue_t* queue_create() { queue_t* reti = malloc(sizeof(queue_t)); if (reti != NULL) { reti->count = 0; reti->head = NULL; reti->tail = NULL; } #ifdef DEBUG if (reti == NULL) { console_color_set_background(console_color_get_from_ansi(RED)); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("Allocating space for QUEUE FAILED!\n"); console_color_reset_colors(); console_color_set_background(console_color_get_from_ansi(BLACK)); } #endif // DEBUG return reti; } void queue_push(queue_t* queue, void* data) { queue_node_t* node = (queue_node_t*)malloc(sizeof(queue_node_t)); #ifdef DEBUG if (node == NULL) { console_color_set_background(console_color_get_from_ansi(RED)); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("Allocating space for NODE FAILED!\n"); console_color_reset_colors(); console_color_set_background(console_color_get_from_ansi(BLACK)); } #endif // DEBUG node->data = data; node->next = NULL; node->id = queue_node_identifier; queue_node_identifier++; if (queue->head == NULL) { queue->head = node; } if (queue->tail == NULL) { queue->tail = node; } else { queue->tail->next = node; queue->tail = node; } queue->count++; #ifdef DEBUG console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf("Queue info:: head: "); if (queue->head == NULL) { console_color_set_foreground(console_color_get_from_ansi(RED_BRIGHT)); printf("NULL"); } else { console_color_set_foreground(console_color_get_from_ansi(MAGENTA_BRIGHT)); printf("%d", queue->head->id); } console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf("; tail:"); if (queue->tail == NULL) { console_color_set_foreground(console_color_get_from_ansi(RED_BRIGHT)); printf("NULL"); } else { console_color_set_foreground(console_color_get_from_ansi(MAGENTA_BRIGHT)); printf("%d", queue->tail->id); } console_color_reset_colors(); printf("\n"); #endif // DEBUG #ifdef DEBUG console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf("Pushed data "); if (data == NULL) { console_color_set_foreground(console_color_get_from_ansi(YELLOW_BRIGHT)); printf("NULL"); } else { console_color_set_foreground(console_color_get_from_ansi(GREEN)); printf("NOT NULL"); } console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf(" into queue["); console_color_set_foreground(console_color_get_from_ansi(CYAN_BRIGHT)); printf("%d", node->id); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf("]; size: "); console_color_set_foreground(console_color_get_from_ansi(BLUE_BRIGHT)); printf("%d", queue_count(queue)); console_color_reset_colors(); printf("\n"); #endif // DEBUG } void* queue_pop(queue_t* queue) { void* reti = NULL; #ifdef DEBUG int id = -1; #endif // DEBUG if (queue->head != NULL) { reti = queue->head->data; #ifdef DEBUG id = queue->head->id; #endif // DEBUG queue->head = queue->head->next; } queue->count--; #ifdef DEBUG console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf("Popped "); if (reti == NULL) { console_color_set_foreground(console_color_get_from_ansi(YELLOW_BRIGHT)); printf("NULL"); } else { console_color_set_foreground(console_color_get_from_ansi(GREEN)); printf("NOT NULL"); } console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf(" data from queue["); console_color_set_foreground(console_color_get_from_ansi(CYAN_BRIGHT)); printf("%d", id); console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf("]; size: "); console_color_set_foreground(console_color_get_from_ansi(BLUE_BRIGHT)); printf("%d", queue_count(queue)); console_color_reset_colors(); printf("\n"); #endif // DEBUG return reti; } int queue_count(queue_t* queue) { return queue->count; } bool queue_is_empty(queue_t* queue) { return (queue->count <= 0 ? TRUE : FALSE); }<file_sep>#pragma once #include "experiment.h" #include "simple_bool.h" #include "queue.h" #include "dynamic_queue.h" #include "laboratory_struct.h" laboratory_t* laboratory_create(int days_available, int experiments_count, experiment_t** experiments); laboratory_t* laboratory_copy(laboratory_t* laboratory); void laboratory_quicksort_experiments_by_length_asc(laboratory_t* laboratory); void laboratory_quicksort_experiments_by_length_asc_rec(laboratory_t* laboratory, int left_begin, int right_begin); void laboratory_quicksort_experiments_by_length_desc(laboratory_t* laboratory); experiment_t** laboratory_get_experiments(laboratory_t* laboratory); int laboratory_get_experiments_count(laboratory_t* laboratory); bool laboratory_schedule_experiment(laboratory_t* laboratory, experiment_t* experiment, int start_day); bool laboratory_can_schedule_experiment(laboratory_t* laboratory, experiment_t* experiment, int start_day); bool laboratory_is_not_scheduled_day(laboratory_t* laboratory, int day); dyn_queue_t* laboratory_experiment_scheduler(laboratory_t* laboratory, experiment_t* experiment, int start_day); void laboratory_recursive_scheduler(laboratory_t* laboratory, int last_used_day); void laboratory_scheduler(laboratory_t* laboratory);<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NetworkSender { public static class Format { public static Structures.ConsoleColorScheme TinyFormat = new Structures.ConsoleColorScheme ( ConsoleColor.Black, ConsoleColor.Gray, ConsoleColor.Black, ConsoleColor.DarkGray ); public static Structures.ConsoleColorScheme BasicFormat = new Structures.ConsoleColorScheme ( ConsoleColor.Black, ConsoleColor.White, ConsoleColor.Black, ConsoleColor.Gray ); public static Structures.ConsoleColorScheme SuccessFormat = new Structures.ConsoleColorScheme ( ConsoleColor.Black, ConsoleColor.DarkGreen, ConsoleColor.Black, ConsoleColor.Green ); public static Structures.ConsoleColorScheme InfoFormat = new Structures.ConsoleColorScheme ( ConsoleColor.Black, ConsoleColor.DarkBlue, ConsoleColor.Black, ConsoleColor.Blue ); public static Structures.ConsoleColorScheme WarningFormat = new Structures.ConsoleColorScheme ( ConsoleColor.Black, ConsoleColor.DarkYellow, ConsoleColor.Black, ConsoleColor.Yellow ); public static Structures.ConsoleColorScheme ErrorFormat = new Structures.ConsoleColorScheme ( ConsoleColor.Black, ConsoleColor.DarkRed, ConsoleColor.Black, ConsoleColor.Red ); public static Structures.ConsoleColorScheme CriticalFormat = new Structures.ConsoleColorScheme ( ConsoleColor.Black, ConsoleColor.Red, ConsoleColor.Red, ConsoleColor.Black ); } } <file_sep>#include <stdio.h> #include <stdlib.h> #include "config.h" #include "structures.h" #include "hw01utils.h" #include "queue.h" #include "simple_bool.h" static volatile int WIDTH = 0; static volatile int COUNT = 0; int main(int argc, char* argv[]) { int reti = EXIT_SUCCESS; result_t result = { 0, 0, 0, 0, 0 }; int* situation_out; #ifdef SAFE_MODE char line[INPUT_BUFFER_SIZE]; fgets(line, INPUT_BUFFER_SIZE, stdin); if (sscanf(line, "%d %d", &WIDTH, &COUNT) != 2) { reti = EXIT_FAILURE; fprintf(stderr, "ERROR [%d]: Parsing of first line failed!\n Expected: width<int> count<int>\n Get: %s", __LINE__, line); } #endif // SAFE_MODE #ifndef SAFE_MODE scanf("%d %d", &WIDTH, &COUNT); #endif // !SAFE_MODE #ifdef DEBUG printf("Loaded values:: maximal width: %d, count: %d\n", WIDTH, COUNT); #endif // DEBUG #ifdef SAFE_MODE if (reti == EXIT_SUCCESS) { #endif // SAFE_MODE model_t situation; situation.width = WIDTH; situation_out = (int*)calloc(WIDTH, sizeof(int)); situation.situation_out = situation_out; #ifdef SAFE_MODE if (situation.situation_out == NULL) { reti = EXIT_FAILURE; fprintf(stderr, "ERROR [%d]: Allocation memory for 'situation_out <int[%d]>' failed!", __LINE__, WIDTH); } #endif // SAFE_MODE int* situation_in = (int*)calloc(WIDTH, sizeof(int)); situation.situation_in = situation_in; #ifdef SAFE_MODE if (situation.situation_in == NULL) { reti = EXIT_FAILURE; fprintf(stderr, "ERROR [%d]: Allocation memory for 'situation_in <int[%d]>' failed!", __LINE__, WIDTH); } if (reti == EXIT_SUCCESS) { #endif // SAFE_MODE situation.notes_in = queue_create_static(COUNT); situation.notes_out = queue_create_static(COUNT); sticky_note_t* notes = (sticky_note_t*)malloc(COUNT * sizeof(sticky_note_t)); #ifdef SAFE_MODE if (situation.notes_in == NULL) { reti = EXIT_FAILURE; fprintf(stderr, "ERROR [%d]: Allocation for 'notes_in <queue_t>' failed!", __LINE__); } else if (situation.notes_out == NULL) { reti = EXIT_FAILURE; fprintf(stderr, "ERROR [%d]: Allocation for 'notes_out <queue_t>' failed!", __LINE__); } else if (notes == NULL) { reti = EXIT_FAILURE; fprintf(stderr, "ERROR [%d]: Allocation memory for 'notes <sticky_note_t[%d]>' failed!", __LINE__, COUNT); } if (reti == EXIT_SUCCESS) { #endif // SAFE_MODE //All memory spaces has been sucessfully allocated //Now its time for parse notes data from standart input for (int i = 0; i < COUNT; i++) { sticky_note_t sticky_note; #ifdef SAFE_MODE char data[INPUT_BUFFER_SIZE]; fgets(data, INPUT_BUFFER_SIZE, stdin); if (sscanf(data, "%d %d %d", &sticky_note.distance_from_left, &sticky_note.height, &sticky_note.width) != 3) { reti = EXIT_FAILURE; fprintf(stderr, "ERROR [%d]: Parsing line (%d) with sticky note data failed!\n Expected: distance_from_left<int> height<int> width<int>\n Get: %s\n", __LINE__, (i + 1), data); break; } if (sticky_note.width > WIDTH) { reti = EXIT_FAILURE; fprintf(stderr, "ERROR [%d]: Wrong input (%d)!\n Maximal allowed width: %d\n Get: %d\n", __LINE__, (i + 1), WIDTH, sticky_note.width); break; } #endif // SAFE_MODE #ifndef SAFE_MODE scanf("%d %d %d", &sticky_note.distance_from_left, &sticky_note.height, &sticky_note.width); #endif // !SAFE_MODE #ifdef DEBUG printf("Loaded sticky note[%d]:: distance from left: %d, width: %d, height: %d\n", (i + 1), sticky_note.distance_from_left, sticky_note.width, sticky_note.height); #endif // DEBUG sticky_note.id = i; if (reti == EXIT_SUCCESS) { notes[i] = sticky_note; check_outside_situation(&situation, &sticky_note, &result); } } for (int i = (COUNT - 1); i >= 0; i--) { check_inside_situation(&situation, &notes[i], &result); } result.visible_both = check_visible_both(&situation); result.visible_one = check_visible_one(&situation) - result.visible_both; result.unvisible = COUNT - result.visible_both - result.visible_one; #ifdef SAFE_MODE } #endif // SAFE_MODE free(notes); queue_delete(situation.notes_in); queue_delete(situation.notes_out); #ifdef SAFE_MODE } #endif // SAFE_MODE free(situation.situation_in); free(situation.situation_out); #ifdef SAFE_MODE } #endif // SAFE_MODE #ifdef SAFE_MODE if (reti == EXIT_SUCCESS) { #endif // SAFE_MODE print_result(&result); #ifdef SAFE_MODE } #endif // SAFE_MODE return reti; }<file_sep>#include "utils.h" #include <stdio.h> void util_print_int_array(int* array, int array_count) { for (int i = 0; i < array_count; i++) { printf("%2d", array[i]); if (i < (array_count - 1)) { printf(", "); } } } <file_sep>#pragma once #Script for testing 3rd homework cat "datapub/pub$1.in" | ./program echo "===" cat "datapub/pub$1.out" echo ""<file_sep>COMPILER=clang CFLAGS+=-Wall program: main.o consolecolor.o consolecolorutils.o $(COMPILER) $(CFLAGS) -o program ./main.o ./consolecolor.o ./consolecolorutils.o main.o: main.c $(COMPILER) $(CFLAGS) -c -o main.o main.c consolecolor.o: ConsoleColor.c ConsoleColor.h consolecolorutils.o $(COMPILER) $(CFLAGS) -c -o consolecolor.o ConsoleColor.c consolecolorutils.o: ConsoleColor_utils.h ConsoleColor_utils.c $(COMPILER) $(CFLAGS) -c -o consolecolorutils.o ConsoleColor_utils.c<file_sep>///<summary> /// File containig declarations of functions and data types used for printing colors to console /// used in logging library ///</summary> ///<remarks> /// Copyright 2019 <NAME> <<EMAIL>> /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http ://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissionsand /// limitations under the License. ///</remarks> #ifndef __CONSOLE_COLOR_H__ #define __CONSOLE_COLOR_H__ ///<summary> ///Defines colors by ANSI escape codes ///</summary> enum AnsiColor { ///<summary> ///Black color ///</summary> BLACK = 30, ///<summary> ///Red color ///</summary> RED, ///<summary> ///Green color ///</summary> GREEN, ///<summary> ///Yellow color ///</summary> YELLOW, ///<summary> ///Blue color ///</summary> BLUE, ///<summary> ///Magenta color ///</summary> MAGENTA, ///<summary> ///Cyan color ///</summary> CYAN, ///<summary> ///White color ///</summary> WHITE, ///<summary> ///Bright black color ///</summary> BLACK_BRIGHT = 90, ///<summary> ///Bright red color ///</summary> RED_BRIGHT, ///<summary> ///Bright green color ///</summary> GREEN_BRIGHT, ///<summary> ///Bright yellow color ///</summary> YELLOW_BRIGHT, ///<summary> ///Bright blue color ///</summary> BLUE_BRIGHT, ///<summary> ///Bright magenta color ///</summary> MAGENTA_BRIGHT, ///<summary> ///Bright cyan color ///</summary> CYAN_BRIGHT, ///<summary> ///Bright white color ///</summary> WHITE_BRIGHT }; ///<summary> ///Type definition of ansi escape codes for colors ///</summary> typedef enum AnsiColor ansi_color_t; ///<summary> ///Structure holding information about color in rgb ///</summary> struct RGBColor { ///<summary> ///Red part of color ///</summary> int red; ///<summary> ///Green part of color ///</summary> int green; ///<summary> ///Blue part of color ///</summary> int blue; }; ///<summary> ///Type definiton of color in RGB model ///</summary> typedef struct RGBColor rgb_color_t; ///<summary> ///Identifies type of color ///</summary> enum ColorType { ///<summary> ///Color defined by ANSI escape code ///</summary> ANSI, ///<summary> ///Color defined by RGB model ///</summary> RGB }; ///<summary> ///Type definition of identifier of type of color ///</summary> typedef enum ColorType color_type_t; ///<summary> ///Space for data defining color ///</summary> union ConsoleColorData { ///<summary> ///Space for color defined by ansi escape code ///</summary> ansi_color_t ansi_color; ///<summary> ///Space for color defined by rgb model ///</summary> rgb_color_t rgb_color; }; ///<summary> ///Type definition for space for data defining color ///</summary> typedef union ConsoleColorData console_color_data_t; ///<summary> ///Structure holding information about color usable in console ///</summary> struct ConsoleColor { ///<summary> ///Identifier of used type of color ///</summary> color_type_t type; ///<summary> ///Data defining color ///</summary> console_color_data_t data; }; ///<summary> ///Type definition of colors usable in console ///</summary> typedef struct ConsoleColor console_color_t; ///<summary> ///Function which sets background of standart output ///</summary> ///<param name="color">Color which will be set as background</param> void console_color_set_background(console_color_t color); ///<summary> ///Function which sets foreground of standart output ///</summary> ///<param name="color">Color which will be set as background</param> void console_color_set_foreground(console_color_t color); ///<summary> ///Function which sets default foreground and background ///</summary> void console_color_reset_colors(); ///<summary> ///Function which gets console color from parts of its RGB model ///</summary> ///<param name="red">Red part of color</param> ///<param name="green">Green part of color</param> ///<param name="blue">Blue part of color</param> console_color_t console_color_get_from_rgb(int red, int green, int blue); ///<summary> ///Gets color from its ANSI escape code ///</summary> ///<param name="color">ANSI escape code of color</param> console_color_t console_color_get_from_ansi(ansi_color_t color); #endif // !__CONSOLE_COLOR_H__<file_sep>#include "hw05_utils.h" #include "config.h" #include <stdio.h> #include <assert.h> void utils_default_deleter(void* data) {} void utils_bst_insert(node_t* node, int data) { void* actual_data = node_get_data(node); if (actual_data == NULL) { #ifdef DEBUG printf("=> inserted to node %d <%d>\n", node_get_identifier(node), node_get_depth(node)); #endif // DEBUG node_set_data(node, (void*)data, utils_default_deleter); return; } else { int int_data = (int)actual_data; if (data > int_data) { if (node_get_right_child(node) == node_NULL) { node_t* n = node_create(NULL, utils_default_deleter); node_set_right_child_F(node, n); } #ifdef DEBUG printf("\tinserting > stored (%d > %d) -> going to right subtree (%d <%d>)\n", data, int_data, node_get_identifier(node_get_right_child(node)), node_get_depth(node_get_right_child(node)) ); #endif // DEBUG #ifdef DEBUG if (node_check_null(node_get_right_child(node)) == TRUE) { printf("!!! RIGHT CHILD OF NODE %d <%d> IS NULL !!!\n", node_get_identifier(node), node_get_depth(node)); } #endif // DEBUG utils_bst_insert(node_get_right_child(node), data); return; } else if (data <= int_data) { if (node_get_left_child(node) == node_NULL) { node_t* n = node_create(NULL, utils_default_deleter); node_set_left_child_F(node, n); } #ifdef DEBUG printf("\tinserting <= stored (%d <= %d) -> going to left subtree (%d <%d>)\n", data, int_data, node_get_identifier(node_get_left_child(node)), node_get_depth(node_get_left_child(node)) ); #endif // DEBUG #ifdef DEBUG if (node_check_null(node_get_left_child(node)) == TRUE) { printf("!!! LEFT CHILD OF NODE %d <%d> IS NULL !!!\n", node_get_identifier(node), node_get_depth(node)); } #endif // DEBUG utils_bst_insert(node_get_left_child(node), data); return; } } } node_t* utils_bst_find(node_t* node, int key) { if (node == node_NULL) { return node_NULL; } else { if (node_get_data(node) == NULL) { return node_NULL; } else { int int_data = (int)node_get_data(node); if (int_data == key) { return node; } else if (key > int_data) { return (utils_bst_find(node_get_right_child(node), key)); } else if (key < int_data) { return (utils_bst_find(node_get_left_child(node), key)); } } } return node_NULL; } /* node_t* utils_bst_delete(node_t* root, int key) { node_t* node = utils_bst_find(root, key); node_t* reti = root; if (node != node_NULL) { #ifdef DEBUG printf("\tfound node containing key: %d <%d>\n", node_get_identifier(node), node_get_depth(node)); #endif // DEBUG if (node_get_left_child(node) == node_NULL && node_get_right_child(node) == node_NULL) //Is leafe { #ifdef DEBUG printf("=> is leafe -> removed from parent %d <%d>\n", node_get_identifier(node_get_parent(node)), node_get_depth(node_get_parent(node))); #endif // DEBUG node_child_t position = node_get_child_position(node); if (position != NONE) { node_set_child_F(node_get_parent(node), node_NULL, position); } return reti; } node_t* left_child = node_get_left_child(node); bool has_left = ((node_check_null(left_child) == TRUE || node_get_identifier(left_child) == -1 || left_child == node_NULL) ? FALSE : TRUE); node_t* right_child = node_get_right_child(node); bool has_right = ((node_check_null(right_child) == TRUE || node_get_identifier(right_child) == -1 || right_child == node_NULL) ? FALSE : TRUE); if (has_left == TRUE && has_right == FALSE) // Has only left child { #ifdef DEBUG printf("=> has only left child %d <%d> -> setting new child to parent %d <%d>\n", node_get_identifier(left_child), node_get_depth(left_child), node_get_identifier(node_get_parent(node)), node_get_depth(node_get_parent(node)) ); #endif // DEBUG node_set_child_F(node_get_parent(node), left_child, node_get_child_position(node)); return reti; } else if(has_right == TRUE && has_left == FALSE) // Has only right child { #ifdef DEBUG printf("=> has only right child %d <%d> -> setting new child to parent %d <%d>\n", node_get_identifier(right_child), node_get_depth(right_child), node_get_identifier(node_get_parent(node)), node_get_depth(node_get_parent(node)) ); #endif // DEBUG node_set_child_F(node_get_parent(node), right_child, node_get_child_position(node)); } } #ifdef DEBUG else { printf("\tkey is not in tree"); printf("=> nothing has been deleted\n"); } #endif // DEBUG return reti; } */ node_t* utils_bst_delete(node_t* root, int key) { if (root == node_NULL) { return root; } if (key < (int)node_get_data(root)) { node_set_left_child_F(root, utils_bst_delete(node_get_left_child(root), key)); } else if (key > (int)node_get_data(root)) { node_set_right_child_F(root, utils_bst_delete(node_get_right_child(root), key)); } else { if (node_get_left_child(root) == node_NULL) { node_t* temp = node_get_right_child(root); node_delete(temp); return temp; } else if (node_get_right_child(root) == node_NULL) { node_t* temp = node_get_left_child(root); node_delete(temp); return temp; } node_t* temp = utils_bst_get_min_value_node(node_get_right_child(root)); node_set_data(root, node_get_data(temp), utils_default_deleter); node_set_right_child_F(root, utils_bst_delete(node_get_right_child(root), key)); } return root; } node_t* utils_bst_get_min_value_node(node_t* node) { node_t* current = node; while (current != node_NULL && node_get_left_child(current) != node_NULL) { current = node_get_left_child(current); } #ifdef DEBUG printf("\t\t\t most left leafe: %d <%d>\n", node_get_identifier(current), node_get_depth(current)); #endif // DEBUG return current; } void utils_bst_print_inorder(node_t* node) { if (node == node_NULL) { return; } utils_bst_print_inorder(node_get_left_child(node)); printf(" %2d", (int)node_get_data(node)); utils_bst_print_inorder(node_get_right_child(node)); } <file_sep>#include<stdio.h> #include<stdlib.h> #include <math.h> #include "config.h" #include <vector> using namespace std; static int nodes_count = 0; static int consolidations = 0; //Sources: /* https://www.geeksforgeeks.org/binary-search-tree-set-1-search-and-insertion/ * https://www.geeksforgeeks.org/binary-search-tree-set-2-delete/ * https://www.geeksforgeeks.org/write-a-c-program-to-find-the-maximum-depth-or-height-of-a-tree/ * https://www.geeksforgeeks.org/convert-normal-bst-balanced-bst/ */ struct node { int key; struct node* left, * right; }; // A utility function to create a new BST node struct node* newNode(int item) { struct node* temp = (struct node*)malloc(sizeof(struct node)); temp->key = item; temp->left = temp->right = NULL; return temp; } // A utility function to do inorder traversal of BST void inorder(struct node* root) { if (root != NULL) { inorder(root->left); printf("%d ", root->key); inorder(root->right); } } /* A utility function to insert a new node with given key in BST */ struct node* insert(struct node* node, int key) { /* If the tree is empty, return a new node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key <= node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); nodes_count++; /* return the (unchanged) node pointer */ return node; } // C function to search a given key in a given BST struct node* search(struct node* root, int key) { // Base Cases: root is null or key is present at root if (root == NULL || root->key == key) return root; // Key is greater than root's key if (root->key < key) return search(root->right, key); // Key is smaller than root's key return search(root->left, key); } /* Given a non-empty binary search tree, return the node with minimum key value found in that tree. Note that the entire tree does not need to be searched. */ struct node* minValueNode(struct node* node) { struct node* current = node; /* loop down to find the leftmost leaf */ while (current && current->left != NULL) current = current->left; return current; } /* Given a binary search tree and a key, this function deletes the key and returns the new root */ struct node* deleteNode(struct node* root, int key) { // base case if (root == NULL) return root; // If the key to be deleted is smaller than the root's key, // then it lies in left subtree if (key < root->key) root->left = deleteNode(root->left, key); // If the key to be deleted is greater than the root's key, // then it lies in right subtree else if (key > root->key) root->right = deleteNode(root->right, key); // if key is same as root's key, then This is the node // to be deleted else { // node with only one child or no child if (root->left == NULL) { struct node* temp = root->right; free(root); return temp; } else if (root->right == NULL) { struct node* temp = root->left; free(root); return temp; } // node with two children: Get the inorder successor (smallest // in the right subtree) struct node* temp = minValueNode(root->right); // Copy the inorder successor's content to this node root->key = temp->key; // Delete the inorder successor root->right = deleteNode(root->right, temp->key); } nodes_count--; return root; } /* Compute the "maxDepth" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/ int maxDepth(struct node* node) { if (node == NULL) return 0; else { /* compute the depth of each subtree */ int lDepth = maxDepth(node->left); int rDepth = maxDepth(node->right); /* use the larger one */ if (lDepth > rDepth) return(lDepth + 1); else return(rDepth + 1); } } /* Function to do preorder traversal of tree */ void preOrder(struct node* node) { if (node == NULL) return; printf("%d ", node->key); preOrder(node->left); preOrder(node->right); } /* Checks, whether consolidation of binary search tree is needed*/ bool consolidation_needed(struct node* root, int count) { bool reti = true; if ((int)pow((double)2, (double)maxDepth(root) - (double)1) <= (int)2 * (int)count) { reti = false; } return reti; } /* This function traverse the skewed binary tree and stores its nodes pointers in vector nodes[] */ void storeBSTNodes(struct node* root, vector<struct node*>& nodes) { // Base case if (root == NULL) return; // Store nodes in Inorder (which is sorted // order for BST) storeBSTNodes(root->left, nodes); nodes.push_back(root); storeBSTNodes(root->right, nodes); } /* Recursive function to construct binary tree */ struct node* buildTreeUtil(vector<struct node*>& nodes, int start, int end) { // base case if (start > end) return NULL; /* Get the middle element and make it root */ int mid = (start + end) / 2; struct node* root = nodes[mid]; /* Using index in Inorder traversal, construct left and right subtress */ root->left = buildTreeUtil(nodes, start, mid - 1); root->right = buildTreeUtil(nodes, mid + 1, end); return root; } // This functions converts an unbalanced BST to // a balanced BST struct node* buildTree(struct node* root) { // Store nodes of given BST in sorted order vector<struct node*> nodes; storeBSTNodes(root, nodes); // Constucts BST from nodes[] int n = nodes.size(); return buildTreeUtil(nodes, 0, n - 1); } static node* root = NULL; /* Utility to count nodes inorder */ int countNodes(struct node* root) { unsigned int count = 1; if (root->left != NULL) { count += countNodes(root->left); } if (root->right != NULL) { count += countNodes(root->right); } return count; } /*Function to get largewr power of two than number */ int getLargerTwoPow(int number) { int reti = 0; while (pow(2, reti) < number) { reti++; } return reti; } /* Utiltiy to store tree as array*/ int AddToArray(struct node* node, int* arr, int i) { if (node == NULL) return i; if (node->left != NULL) i = AddToArray(node->left, arr, i); arr[i] = node->key; i++; if (node->right != NULL) i = AddToArray(node->right, arr, i); return i; } /* Computes middle index between two indexes */ int getMiddle(int start, int end) { return ceil(((end - start) / 2) + start); } /* Recursive function for tree consolidation */ void consolidate_recur(int* array, int start, int end, struct node* node, int count) { #ifdef DEBUG printf("\tConsolidating from: %d to: %d\n", start, end); #endif // DEBUG if (start == end ) { insert(node, array[start]); #ifdef DEBUG printf("\tInserted: %d [%d]\n", array[start], start); #endif // DEBUG return; } if (start > end) { return; } int idx = getMiddle(start, end); #ifdef DEBUG printf("\tInserted: %d [%d]\n", array[idx], idx); #endif // DEBUG insert(node, array[idx]); consolidate_recur(array, start, idx - 1, node, count); consolidate_recur(array, idx + 1, end, node, count); } /* Utility to consolidate tree*/ struct node* consolidate(struct node* root) { int* array = (int*)malloc(countNodes(root) * sizeof(int)); int last = AddToArray(root, array, 0); int maximal = pow((double)2, (double)getLargerTwoPow(countNodes(root))) - 1; int idx = getMiddle(0, maximal - 1); struct node* reti = newNode(array[idx]); consolidate_recur(array, 0, idx - 1, reti, countNodes(root)); consolidate_recur(array, idx + 1, last - 1, reti, countNodes(root)); return reti; } // Driver Program to test above functions int main() { int operations = 0; scanf("%d", &operations); for (int i = 0; i < operations; i++) { int value = 0; scanf("%d", &value); if (value > 0) { root = insert(root, value); #ifdef DEBUG printf(" --- INSERT %d ---\n", value); printf("I: "); inorder(root); printf("\n"); printf("P: "); preOrder(root); printf("\n\n"); #endif // DEBUG if (consolidation_needed(root, countNodes(root))) { root = consolidate(root); consolidations++; #ifdef DEBUG printf("=== CONSOLIDATING ===\n"); #endif // DEBUG } #ifdef DEBUG printf("I: "); inorder(root); printf("\n"); printf("P: "); preOrder(root); printf("\n\n"); #endif // DEBUG } else if (value < 0) { #ifdef DEBUG printf(" --- REMOVE %d ---\n", abs(value)); #endif // DEBUG root = deleteNode(root, abs(value)); #ifdef DEBUG printf("[%d] >%d>\n", countNodes(root), maxDepth(root) - 1); printf("I: "); inorder(root); printf("\n"); printf("P: "); preOrder(root); printf("\n\n"); #endif // DEBUG if (consolidation_needed(root, countNodes(root))) { root = consolidate(root); consolidations++; #ifdef DEBUG printf("===CONSOLIDAING===\n"); printf("[%d] >%d>\n", countNodes(root), maxDepth(root) - 1); printf("I: "); inorder(root); printf("\n"); printf("P: "); preOrder(root); printf("\n\n"); #endif // DEBUG } } } printf("%d %d\n", consolidations, maxDepth(root) - 1); return 0; } <file_sep>///<summary> /// File containing decalrations of utility functions used in third homework from algorithms ///</summary> ///<remarks> /// Copyright 2019 <NAME> <<EMAIL>> /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http ://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissionsand /// limitations under the License. ///</remarks> #ifndef __HW03_UTILS_H__ #define __HW03_UTILS_H__ #include "node.h" #include "plane.h" ///<summary> ///Structure with array of planes ///</summary> struct Plane_Array { ///<summary> ///Count of planes stored in array ///</summary> int count; ///<summary> ///Array with planes ///</summary> plane_t** data; }; ///<summary> ///Type definition of structure with array of planes ///</summary> typedef struct Plane_Array plane_array_t; ///<summary> ///Stores some information as return from function ///</summary> volatile static _RETI = 0; ///<summary> ///Structure with array of nodes ///</summary> struct Node_Array { ///<summary> ///Count of nodes stored in array ///</summary> int count; ///<summary> ///Array with nodes ///</summary> node_t** data; }; ///<summary> ///Type definition of structure with array of planes ///</summary> typedef struct Node_Array node_array_t; ///<summary> ///Function to compute difference between weights of subtrees ///</summary> ///<param name="node">Node of tree which will be accpeted as root of tree</param> ///<returns>Difference between weights of trees</returns> int utils_compute_difference(node_t* node); ///<summary> ///Function to compute weight of left subtree ///</summary> ///<param name="node">Node of tree which left subtree weight will be computed</param> int utils_compute_left_weight(node_t* node); ///<summary> ///Function to compute weight of right subtree ///</summary> ///<param name="node">Node of tree which right subtree weight will be computed </param> int utils_compute_right_weight(node_t* node); ///<summary> ///Function to compute weight of subtree ///</summary> ///<param name="node">Root of subtree which weight will be computed</param> ///<returns>Weight of subtree</returns> int utils_compute_subtree_weight(node_t* node); ///<summary> ///Function to create subtrees with lowes possible difference of weights ///</summary> ///<param name="array">Array with nodes</param> ///<param name="count">Count of nodes in array</param> ///<returns> ///Array of nodes which are roots of subtrees ///and in static variable _RETI count of elements ///</returns> node_t** utils_create_lowest_plane_subtrees(node_t** array, int count); ///<summary> ///Function to create array of planes ///</summary> ///<param name="count">Count of planes</param> ///<returns>Array of planes or <c>NULL</c></returns> plane_array_t* utils_create_plane_array(int count); ///<summary> ///Function to delete array of planes ///</summary> ///<param name="plane_arr">Array of planes which will be deleted</param> void utils_delete_plane_array(plane_array_t* plane_arr); ///<summary> ///Evaluator used in this homework ///</summary> ///<param name="node">Node which will be evaluated</param> ///<returns>Weight of tree</returns> int utils_node_evaluator(node_t* node); node_t* utils_create_tree(plane_t** planes, int start, int end); int utils_get_ideal_delimiter(plane_t** planes, int start, int end); int utils_sum_planes(plane_t** planes, int start, int end); void utils_int_deleter(void* int_ptr); void utils_print_tree(node_t* node); int utils_count_whole_difference(node_t* node); int utils_place_pilot(node_t* root, int weight); int utils_try_place_pilot(node_t* node, int weight); void utils_update_tree_differences(node_t* leafe); void utils_update_node(node_t* node); int utils_default_evaluator(node_t* node); void utils_set_evaluator(node_t* node); #endif // !__HW03_UTILS_H__ <file_sep>///<summary> /// File containing declaration of node in tree ///</summary> ///<remarks> /// Copyright 2019 <NAME> <<EMAIL>> /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http ://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissionsand /// limitations under the License. ///</remarks> #ifndef __NODE_H__ #define __NODE_H__ #include <stdlib.h> #include "simple_bool.h" ///<summary> ///Definiton of structure node in tree ///</summary> struct Node { ///<summary> ///Unique identifier of node ///</summary> int id; ///<summary> ///Left child of node ///</summary> struct Node* left_child; ///<summary> ///Right child of node ///</summary> struct Node* right_child; ///<summary> ///Parent of node int tree ///</summary> struct Node* parent; ///<summary> ///Data stored in node ///</summary> void* data; ///<summary> ///Function which can delete data from node ///</summary> void (*delete)(void*); ///<summary> ///Function which can get integer from node ///</summary> int (*evaluator)(struct Node*); ///<summary> ///Depth of node ///</summary> int depth; }; ///<summary> ///Type definition of node in tree ///</summary> typedef struct Node node_t; ///<summary> ///Enumeration defining position of child ///</summary> enum Node_Child { ///<summary> ///Defines left child ///</summary> LEFT, ///<summary> ///Defines right child ///</summary> RIGHT, ///<summary> ///Defines any child ///</summary> ANY, ///<summary> ///Defines none child ///</summary> NONE }; ///<summary> ///Type definition of enumeration defining position of child ///</summary> typedef enum Node_Child node_child_t; ///<summary> ///Stores last used identifier of node ///</summary> static volatile int node_LAST_ID = -1; ///<summary> ///Defines <c>NULL</c> node ///</summary> #define node_NULL ((node_t*)NULL) ///<summary> ///Creates empty node ///</summary> ///<returns>Empty node or <c>NULL</c> if allocation of memory failed</returns> node_t* node_create_empty(); ///<summary> ///Creates node with data ///</summary> ///<param name="data">Data which will be stored in node</param> ///<param name="delete">Function which can delete data stored in node</param> ///<returns>New node with data or <c>NULL</c> if allocation of memory failed</returns> node_t* node_create(void* data, void(*delete)(void*)); ///<summary> ///Deletes node and data stored in node ///</summary> ///<param name="node">Node which will be deleted</param> void node_delete(node_t* node); ///<summary> ///Default function used to delete data ///</summary> ///<param name="data">Data which will be deleted</param> void node_delete_empty_data(void* data); ///<summary> ///Checks, whether node is empty ///</summary> ///<returns><c>TRUE</c> if node is empty, <c>FALSE</c> otherwise</returns> bool node_is_empty(node_t* node); ///<summary> ///Sets parential node of node ///</summary> ///<param name="node">Node, which parent will be set</param> ///<param name="parent">Parential node</param> ///<param name="child">Sets, which child of parent will be this node</param> ///<returns><c>TRUE</c> if setting was successfull, <c>FALSE</c> otherwise</returns> bool node_set_parent(node_t* node, node_t* parent, node_child_t child); ///<summary> ///Sets parential node of node with overwriting current one ///</summary> ///<param name="node">Node, which parent will be set</param> ///<param name="parent">Parential node</param> ///<param name="child">Sets, which child of parent will be this node</param> void node_set_parent_F(node_t* node, node_t* parent, node_child_t child); ///<summary> ///Gets parent node of node ///</summary> ///<param name="node">Node which parent will be get</param> ///<returns>Pointer to parential node</returns> node_t* node_get_parent(node_t* node); ///<summary> ///Sets child of node ///</summary> ///<param name="node">Node, which child will be set</param> ///<param name="child">Node, which will be set as child</param> ///<param name="position">Position of child</param> ///<returns><c>TRUE</c> if child has been successfully set, <c>FALSE</c> otherwise</returns> bool node_set_child(node_t* node, node_t* child, node_child_t position); ///<summary> ///Sets child of node with overwritng current one ///</summary> ///<param name="node">Node, which child will be set</param> ///<param name="child">Node, which will be set as child</param> ///<param name="position">Position of child</param> void node_set_child_F(node_t* node, node_t* child, node_child_t position); ///<summary> ///Gets child of node ///</summary> ///<param name="node">Node, which child will be set</param> ///<param name="child">Node, which will be set as child</param> ///<param name="position">Position of child</param> ///<returns>Selected child of node or <c>NULL</c> </returns> node_t* node_get_child(node_t* node, node_child_t position); ///<summary> ///Sets left child of node ///</summary> ///<param name="node">Node, which left child will be set</param> ///<param name="left_child">Node which will be set as left child</param> ///<returns><c>TRUE</c> if child has been successfully set, <c>FALSE</c> otherwise</returns> bool node_set_left_child(node_t* node, node_t* left_child); ///<summary> ///Sets left child of node with overwriting current child ///</summary> ///<param name="node">Node, which left child will be set</param> ///<param name="left_child">Node which will be set as left child</param> void node_set_left_child_F(node_t* node, node_t* left_child); ///<summary> ///Gets left child of node ///</summary> ///<param name="node">Node, wchich left child will be get</param> ///<returns>Pointer to left child of node</returns> node_t* node_get_left_child(node_t* node); ///<summary> ///Sets right child of node ///</summary> ///<param name="node">Node, which right child will be set</param> ///<param name="right_child">Node which will be set as right child</param> ///<returns><c>TRUE</c> if child has been successfully set, <c>FALSE</c> otherwise</returns> bool node_set_right_child(node_t* node, node_t* right_child); ///<summary> ///Sets right child of node with overwriting current child ///</summary> ///<param name="node">Node, which right child will be set</param> ///<param name="right_child">Node which will be set as right child</param> void node_set_right_child_F(node_t* node, node_t* right_child); ///<summary> ///Gets right child of node ///</summary> ///<param name="node">Node, which right child will be get</param> ///<returns>Pointer to right child of node</returns> node_t* node_get_right_child(node_t* node); ///<summary> ///Gets unique identifier of node ///</summary> ///<param name="node">Node which identifier will be returned</param> ///<returns>Identifier of node or -1 for null node</returns> int node_get_identifier(node_t* node); ///<summary> ///Gets data stored in node ///</summary> ///<param name="node">Node, which data will be returned</param> ///<returns>Data stored in node or <c>NULL</c></returns> void* node_get_data(node_t* node); ///<summary> ///Sets data stored in node ///</summary> ///<param name="node">Node, which data will be stored</param> ///<param name="data">Data which will be stored in node</param> ///<param name="delete">Function, which can delete data</param> ///<returns><c>TRUE</c> if setting of data has been successfull, <c>FALSE</c> otherwise</returns> bool node_set_data(node_t* node, void* data, void(*delete)(void*)); ///<summary> ///Sets data stored in node with overwriting current one ///</summary> ///<param name="node">Node, which data will be stored</param> ///<param name="data">Data which will be stored in node</param> ///<param name="delete">Function, which can delete data</param> void node_set_data_force(node_t* node, void* data, void(*delete)(void*)); ///<summary> ///Checks, whether nodes are same ///</summary> ///<param name="node1">First node to be compared</param> ///<param name="node2">Second node to be compared</param> ///<returns><c>TRUE</c> if they are same, <c>FALSE</c> otherwise</returns> bool node_check_same(node_t* node1, node_t* node2); ///<summary> ///Checks, whether nodes and its subtrees are same ///</summary> ///<param name="node1">First node to be compared</param> ///<param name="node2">Second node to be compared</param> ///<returns><c>TRUE</c> if they and its subtrees are same, <c>FALSE</c> otherwise</returns> bool node_deep_check_same(node_t* node1, node_t* node2); ///<summary> ///Checks, whether node is null node ///</summary> ///<param name="node">Node which will be checked</param> ///<returns><c>TRUE</c> if node is null, <c>FALSE</c> otherwise</returns> bool node_check_null(node_t* node); ///<summary> ///Checks, whether node has left child ///</summary> ///<param name="node">Node which will be checked</param> ///<returns><c>TRUE</c> if node has left child, <c>FALSE</c> otherwise</returns> bool node_has_left_child(node_t* node); ///<summary> ///Checks, whether node has right child ///</summary> ///<param name="node">Node which will be checked</param> ///<returns><c>TRUE</c> if node has right child, <c>FALSE</c> otherwise</returns> bool node_has_right_child(node_t* node); ///<summary> ///Checks, whether node has child ///</summary> ///<param name="node">Node which will be checked</param> ///<returns><c>TRUE</c> if node has child, <c>FALSE</c> otherwise</returns> bool node_has_child(node_t* node); ///<summary> ///Checks, whether node has parent ///</summary> ///<param name="node"> Node, which will be checked</param> ///<returns><c>TRUE</c> if node has parent, <c>FALSE</c> otherwise</returns> bool node_has_parent(node_t* node); ///<summary> ///Checks, whether node is leaf of tree ///</summary> ///<param name="node">Node which will be checked</param> ///<returns><c>TRUE</c> if node is leaf of tree, <c>FALSE</c> otherwise</returns> bool node_is_leaf(node_t* node); ///<summary> ///Sets function which can return integer from node ///</summary> ///<param name="node">Node which function will be defined</param> ///<param name="evaluator">Function which can get integer from node</param> void node_set_evaluator(node_t* node, int(*evaluate)(node_t*)); ///<summary> ///Default node evaluator ///</summary> ///<param name="node">Node which will be evaluated</param> ///<returns>Identifier of node</returns> int node_default_evaluator(node_t* node); ///<summary> ///Gets integer from node ///</summary> ///<param name="node">Node which integer will be computed</param> ///<returns>Integer computed from node</returns> int node_evaluate(node_t* node); ///<summary> ///Deletes tree defined by node ///</summary> ///<param name="node">Node which is root of tree which will be deleted</param> void node_delete_tree(node_t* node); ///<summary> ///Counts leaves in tree ///</summary> ///<param name="node">Node which is root of tree which leavs will be counted</param> ///<returns>Count of leaves</returns> int node_count_leaves(node_t* node); ///<summary> ///Gets leaves from tree ///</summary> ///<param name="node">Node which is root of tree which leaves will be returned</param> ///<param name="result">Array, where will be stored results</param> void node_get_leaves(node_t* node, node_t** result); ///<summary> ///Recursive function to find leaves in tree ///!!!THIS FUNCTION SHOULDN'T BE CALLED ALONE!!! ///</summary> ///<param name="node">Node which is root of tree which leaves will be found</param> ///<param name="result">Array, where will be stored results</param> void node_find_leaves(node_t* node, node_t** result); ///<summary> ///Function to set depth of node ///</summary> ///<param name="node">Node which depth will be set</param> ///<param name="depth">Depth which will be set</param> void node_set_depth(node_t* node, int depth); ///<summary> ///Function to get depth of node ///</summary> ///<param name="node">Node which depth will be get</param> ///<returns>Depth of node</returns> int node_get_depth(node_t* node); ///<summary> ///Gets position of node to its parent ///</summary> ///<param name="node">Child of parent which position will be returned</param> ///<returns>Position of child to parent</returns> node_child_t node_get_child_position(node_t* node); #ifdef DEBUG ///<summary> ///Prints information about node ///</summary> ///<param name="node">Node which information will be printed</param> ///<param name="print">Function which can print data</param> void node_print(node_t* node, void(*print)(void*)); ///<summary> ///Prints nodes with its evaluation ///</summary> ///<param name="node">Node which evaluation will be printed</param> void node_print_tree_nodes_evaluation(node_t* node); #endif // DEBUG #endif // ! __NODE_H__<file_sep>#include <stdlib.h> #include <stdio.h> #include "globals.h" #include "config.h" #include "hw05_utils.h" #include "node.h" int OPERATIONS; int MAXIMAL_DEPTH = 0; int NODES = 0; int main(int argc, char* argv[]) { int reti = EXIT_SUCCESS; scanf("%d", &OPERATIONS); node_t* root = node_create_empty(); node_set_depth(root, 0); for (int i = 0; i < OPERATIONS; i++) { int value = 0; scanf("%d", &value); if (value > 0) //INSERT { #ifdef DEBUG printf("Inserting %d to tree...\n", value); #endif // DEBUG if (NODES == 0) //FIRST NODE { #ifdef DEBUG printf("=> inserted to node %d <%d> (root)\n", node_get_identifier(root), node_get_depth(root)); #endif // DEBUG node_set_data(root, value, utils_default_deleter); } else { utils_bst_insert(root, value); } NODES++; utils_bst_print_inorder(root); printf("\n"); } else { #ifdef DEBUG printf("Deleting %d from tree...\n", abs(value)); #endif // DEBUG root = utils_bst_delete(root, abs(value)); utils_bst_print_inorder(root); printf("\n"); } } #ifdef DEBUG printf("=== Depth of tree: %d ===\n", MAXIMAL_DEPTH); #endif // DEBUG utils_bst_print_inorder(root); printf("\n"); return reti; }<file_sep>#include "Village.hpp" #include <iostream> Village::Village() : label(-1), visit_time(1), tourist_index(-1) { this->paths = new std::vector<Path<Village*>*>(); } Village::Village(int label, int visit_time) : label(label), visit_time(visit_time), tourist_index(-1) { this->paths = new std::vector<Path<Village*>*>(); } int Village::getLabel() { return this->label; } int Village::getVisitTime() { return this->visit_time; } void Village::addNeighbour(Village* village, int cost) { Village** start = new Village * (this); Village** finish = &village; Path<Village*>* path = new Path<Village*> (start, finish, cost); this->paths->push_back(path); } std::vector<Path<Village*>*>* Village::getPaths() { return this->paths; } void Village::setAtractiveness(int tourist_index) { this->tourist_index = tourist_index; } int Village::getAtractiveness() { return this->tourist_index; } Village::~Village() { } <file_sep>#include "dynamic_queue.h" #include <stdlib.h> dyn_queue_t* dyn_queue_create() { dyn_queue_t* reti = malloc(sizeof(dyn_queue_t)); if (reti != NULL) { reti->capacity = 2; reti->count = 0; reti->data = malloc(reti->capacity * sizeof(laboratory_t*)); reti->head = 0; reti->tail = 0; reti->next = 0; } return reti; } bool dyn_queue_push(dyn_queue_t* queue, laboratory_t* item) { bool reti = TRUE; if (queue->capacity < queue->tail + 1) { reti = dyn_queue_upscale(queue); } if (reti == TRUE) { queue->data[queue->tail] = item; queue->tail++; queue->count++; } return reti; } laboratory_t* dyn_queue_pop(dyn_queue_t* queue) { laboratory_t* reti = NULL; if (dyn_queue_is_empty(queue) == FALSE) { reti = queue->data[queue->head]; queue->head++; queue->count--; } return reti; } bool dyn_queue_is_empty(dyn_queue_t* queue) { return (queue->count == 0 ? TRUE : FALSE); } bool dyn_queue_upscale(dyn_queue_t* queue) { bool reti = FALSE; laboratory_t** new_data = realloc(queue->data, queue->capacity * DYN_QUEUE_UPSCALE * sizeof(laboratory_t*)); if (new_data != NULL) { queue->data = new_data; reti = TRUE; queue->capacity = queue->capacity * DYN_QUEUE_UPSCALE; } return reti; } void dyn_queue_delete(dyn_queue_t* queue) { free(queue->data); free(queue); } bool dyn_queue_has_next(dyn_queue_t* queue) { return ((queue->next + 1) == queue->tail ? FALSE : TRUE); } laboratory_t* dyn_queue_next(dyn_queue_t* queue) { laboratory_t* reti = NULL; if (dyn_queue_has_next(queue) == TRUE) { reti = queue->data[queue->next]; queue->next++; } return reti; } void dyn_queue_reset_next_index(dyn_queue_t* queue) { queue->next = queue->head; } dyn_queue_t* dyn_queue_copy(dyn_queue_t* queue) { dyn_queue_t* reti = (dyn_queue_t*)malloc(sizeof(dyn_queue_t)); reti->capacity = queue->capacity; reti->count = queue->count; reti->head = queue->head; reti->next = queue->next; reti->tail = queue->tail; reti->data = (laboratory_t**)malloc(reti->capacity * sizeof(laboratory_t*)); for (int i = reti->head; i < reti->tail; i++) { reti->data[i] = queue->data[i]; } return reti; } <file_sep>///<summary> /// File containing declaration of sorted data type ///</summary> ///<remarks> /// Copyright 2019 <NAME> <<EMAIL>> /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http ://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissionsand /// limitations under the License. ///</remarks> #pragma once ///<summary> ///Defines way, in which are data sorted ///</summary> enum Sorted { ///<summary> ///Data are not sorted ///</summary> NONE, ///<summary> ///Data are sorted ascending ///</summary> ASC, ///<summary> ///Data are sorted descending ///</summary> DESC }; ///<summary> ///Definition of <c>enum</c> sorted as new data type ///</summary> typedef enum Sorted sort_t;<file_sep>program: main.cpp $(CXX) -Wall -lm -o program main.cpp clean: $(RM) program $(RM) hw05.tar.bz2 zip: $(RM) hw05.tar.bz2 tar -cvf hw05.tar main.cpp config.h bzip2 hw05.tar<file_sep>#ifndef __PATH_HPP__ #define __PATH_HPP__ template <class Node> ///<summary> ///Class representing path between two villages ///</summary> class Path { private: ///<summary> ///Starting node of path ///</summary> Node* starting_node; ///<summary> ///Final node of path ///</summary> Node* final_node; ///<summary> ///Cost of path ///</summary> int cost; public: ///<summary> ///Creates new path between villages ///</summary> ///<param name="starting_node">Starting node of path</param> ///<param name="final_node">Final node of path</param> ///<param name="cost">Cost of path</param> ///<returns>New instance of path</returns> Path(Node* starting_node, Node* final_node, int cost); ///<summary> ///Gets starting node of path ///</summary> ///<returns>Starting node of path</returns> Node getStartingNode(); ///<summary> ///Gets final node of path ///</summary> ///<returns>Final node of path</returns> Node getFinalNode(); ///<summary> ///Gets cost of path ///</summary> ///<returns>Cost of path</returns> int getCost(); ~Path(); }; template <class Node> Path<Node>::Path(Node* starting_node, Node* final_node, int cost) : starting_node(starting_node), final_node(final_node), cost(cost) { } template <class Node> Node Path<Node>::getStartingNode() { return this->starting_node; } template <class Node> Node Path<Node>::getFinalNode() { return this->final_node; } template <class Node> int Path<Node>::getCost() { return this->cost; } template<class Node> inline Path<Node>::~Path() { } #endif // !__PATH_HPP__ <file_sep>#ifndef __HW04_STRUCTS_H__ #define __HW04_STRUCTS_H__ struct Point { int X; int Y; }; typedef struct Point point_t; struct Situation { point_t* point; int energy; int steps; }; typedef struct Situation situation_t; #endif // !__HW04_STRUCTS_H__<file_sep>#ifndef __HW04_UTILS_H__ #define __HW04_UTILS_H__ #include "simple_bool.h" #include "hw04structs.h" bool utils_point_on_map(point_t); bool utils_can_go_left(point_t point); bool utils_can_go_right(point_t point); bool utils_can_go_up(point_t point); bool utils_can_go_down(point_t point); int utils_compute_motor_ionization(int E_initial, point_t start, point_t finish); int utils_compute_environment_ionization(int E_eng, point_t start, point_t finish); int utils_compute_ionization(int E_motor, point_t start, point_t finish); point_t* utils_create_point(int X, int Y); situation_t* utils_create_situation(point_t* point, int energy, int steps); void utils_check_position(situation_t* situation); int utils_situation_step_comparator(void* situationA, void* situationB); int utils_situation_energy_comparator(void* situationA, void* situationB); int utils_situation_exact_comparator(void* situationA, void* situationB); #ifdef SHOW_MAP void utils_display_map(point_t* point); #endif #endif // !__HW04_UTILS_H__<file_sep>#pragma once struct Experiment { int id; int income; int days_count; int* days; }; typedef struct Experiment experiment_t; experiment_t* experiment_create(int id, int days, int income); int experiment_get_days_count(experiment_t* experiment); void experiment_set_active_day(experiment_t* experiment, int index, int day); int experiment_sorter_by_length_asc(const void* element1, const void* element2); int experiment_sorter_by_length_desc(const void* element1, const void* element2); int experiment_sorter_by_income_asc(const void* element1, const void* element2); int experiment_sorter_by_income_desc(const void* element1, const void* element2);<file_sep>#include "experiment.h" #include "config.h" #include <stdio.h> #include <stdlib.h> experiment_t* experiment_create(int id, int days, int income) { experiment_t* reti = (experiment_t*)malloc(sizeof(experiment_t)); reti->id = id; reti->days_count = days; reti->income = income; reti->days = (int*)calloc(reti->days_count, sizeof(int)); return reti; } void experiment_set_active_day(experiment_t* experiment, int index, int day) { if (index < experiment->days_count) { experiment->days[index] = day; } } int experiment_get_days_count(experiment_t* experiment) { return experiment->days_count; } <file_sep> #include <stdlib.h> #include <stdio.h> #include "ConsoleColor.h" #include "config.h" #include "queue.h" #include "globals.h" #include "hw04utils.h" #include <limits.h> int ROWS, COLS, E_init, D_mov, D_env; int** MAP; situation_t*** VISITED; int MIN_STEPS; queue_t* SITUATIONS; point_t* FINISH; #ifdef SHOW_MAP int STEPS; #endif // SHOW_MAP int main(int argc, char* argv[]) { int reti = EXIT_SUCCESS; //Load first row with data scanf("%d %d %d %d %d", &ROWS, &COLS, &E_init, &D_mov, &D_env); #ifdef DEBUG printf("[%d x %d]\n", ROWS, COLS); #endif // DEBUG MAP = (int**)malloc(ROWS * sizeof(int*)); VISITED = (situation_t***)malloc(ROWS * sizeof(situation_t**)); #ifdef DEBUG if (VISITED == NULL) { console_color_set_background(console_color_get_from_ansi(RED)); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("Allocating space for VISITED FAILED!\n"); console_color_reset_colors(); console_color_set_background(console_color_get_from_ansi(BLACK)); } #endif // DEBUG #ifdef DEBUG if (MAP == NULL) { console_color_set_background(console_color_get_from_ansi(RED)); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("Allocating space for MAP FAILED!\n"); console_color_reset_colors(); console_color_set_background(console_color_get_from_ansi(BLACK)); } #endif // DEBUG SITUATIONS = queue_create(); MIN_STEPS = INT_MAX; FINISH = utils_create_point(COLS - 1, ROWS - 1); #ifdef DEBUG if (FINISH == NULL) { console_color_set_background(console_color_get_from_ansi(RED)); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("Allocating space for FINISH FAILED!\n"); console_color_reset_colors(); console_color_set_background(console_color_get_from_ansi(BLACK)); } console_color_set_background(console_color_get_from_ansi(WHITE_BRIGHT)); console_color_set_foreground(console_color_get_from_ansi(BLACK)); printf("Drone goal: go to ["); console_color_set_foreground(console_color_get_from_ansi(GREEN)); printf("%d", FINISH->X); console_color_set_foreground(console_color_get_from_ansi(BLACK)); printf("; "); console_color_set_foreground(console_color_get_from_ansi(GREEN)); printf("%d", FINISH->Y); console_color_set_foreground(console_color_get_from_ansi(BLACK)); printf("]"); console_color_set_background(console_color_get_from_ansi(BLACK)); console_color_reset_colors(); printf("\n"); #endif // DEBUG for (int r = 0; r < ROWS; r++) { MAP[r] = (int*)malloc(COLS * sizeof(int)); VISITED[r] = (situation_t**)malloc(COLS * sizeof(situation_t**)); #ifdef DEBUG if (VISITED[r] == NULL) { console_color_set_background(console_color_get_from_ansi(RED)); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("Allocating space for row %d FAILED!\n", r); console_color_reset_colors(); console_color_set_background(console_color_get_from_ansi(BLACK)); } #endif // DEBUG #ifdef DEBUG if (MAP[r] == NULL) { console_color_set_background(console_color_get_from_ansi(RED)); console_color_set_foreground(console_color_get_from_ansi(WHITE_BRIGHT)); printf("Allocating space for MAP[%d] FAILED!\n", r); console_color_reset_colors(); console_color_set_background(console_color_get_from_ansi(BLACK)); } #endif // DEBUG for (int c = 0; c < COLS; c++) { scanf("%d", &MAP[r][c]); #ifdef DEBUG console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf("%2d ", MAP[r][c]); console_color_reset_colors(); #endif // DEBUG } #ifdef DEBUG printf("\n"); #endif // DEBUG } //BFS situation_t* actual = utils_create_situation(utils_create_point(0, 0), E_init, 0); utils_check_position(actual); #ifdef SHOW_MAP printf("\033[2J"); utils_display_map(actual->point); #endif // SHOW_MAP while (queue_is_empty(SITUATIONS) == FALSE && MIN_STEPS == INT_MAX) { #ifdef DEBUG console_color_set_foreground(console_color_get_from_ansi(BLACK_BRIGHT)); printf("Popping new item...size before pop: "); console_color_set_foreground(console_color_get_from_ansi(YELLOW_BRIGHT)); printf("%d", queue_count(SITUATIONS)); console_color_reset_colors(); printf("\n"); #endif // DEBUG situation_t* s = queue_pop(SITUATIONS); utils_check_position(s); #ifdef SHOW_MAP STEPS = s->steps; utils_display_map(s->point); #endif // SHOW_MAP } printf("%d\n", MIN_STEPS); return reti; }<file_sep>#ifndef __VILLAGE_HPP__ #define __VILLAGE_HPP__ #include <vector> #include "Path.hpp" ///<summary> ///Class representing village in map ///</summary> class Village { private: ///<summary> ///Label of village ///</summary> int label; ///<summary> ///Time needed for visit village ///</summary> int visit_time; ///<summary> ///Paths from village ///</summary> std::vector<Path<Village*>*>* paths; ///<summary> ///Count of paths from village ///</summary> int paths_count = 0; ///<summary> ///Attractiveness of village for tourists ///</summary> int tourist_index; public: ///<summary> ///Creates new empty village ///</summary> ///<returns>Empty village</returns> Village(); ///<summary> ///Creates new village ///</summary> ///<param name="label">Label of village</param> ///<param name="visit_time">Time needed for visit village</param> ///<returns>New instance of village class</returns> Village(int label, int visit_time); ///<summary> ///Gets label of village ///</summary> ///<returns>Label of village</returns> int getLabel(); ///<summary> ///Gets time needed for visit village ///</summary> ///<returns>Time needed for visit village</returns> int getVisitTime(); ///<summary> ///Adds neihbour village to village ///</summary> ///<param name="village">Neighbour village</param> ///<param name="cost">Cost of the path to the neighbour village</param> void addNeighbour(Village* village, int cost); ///<summary> ///Gets path from village ///</summary> ///<returns>Paths leading from village</returns> std::vector<Path<Village*>*>* getPaths(); ///<summary> ///Sets attractiveness of village for tourist ///</summary> ///<param name="tourist_index">Value of attractiveness of village for tourist</param> void setAtractiveness(int tourist_index); ///<summary> ///Gets attractiveness of village ///</summary> ///<returns>Attractiveness of village</returns> int getAtractiveness(); ~Village(); }; #endif // __VILLAGE_HPP__ <file_sep>#ifndef __GLOBALS_HPP__ #define __GLOBALS_HPP__ #include <map> #include <string> ///<summary> ///Class conatining global variables ///</summary> class Globals { private: ///<summary> ///Values stored in globals ///</summary> std::map<std::string, int> values; ///<summary> ///Pointer to instance of globals ///</summary> static Globals* instance; ///<summary> ///Instances new globals ///</summary> Globals(); public: ///<summary> ///Gets instance of globals ///</summary> ///<returns>Instance of globals</returns> static Globals* getInstance(); ///<summary> ///Gets all values stored in globals ///</summary> ///<returns>All values stored in globals</returns> std::map<std::string, int> getValues(); ///<summary> ///Sets value of global variable ///</summary> ///<param name="key">Name of global variable</param> ///<param name="value">Data which will be set to global variable</param> void setValue(std::string key, int value); ///<summary> ///Gets value of global variable ///</summary> ///<param name="key">Name of global variable</param> ///<returns>Value of global variable</returns> int getValue(std::string key); }; #endif // !__GLOBALS_HPP__<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using static NetConsole.Structures; namespace NetConsole { class Logger { private LogLevel level; private DateFormat date; private TimeFormat time; private int header_len; public Logger(LogLevel level, DateFormat date, TimeFormat time) { this.level = level; this.date = date; this.time = time; this.header_len = this.GetHeader(LogLevel.CRITICAL).Length; } public void Log(LogLevel level, string message) { if (level <= this.level) { ConsoleColorScheme scheme = this.SelectColorScheme(level); this.FormatHeader(scheme); Console.Write(this.GetHeader(level)); this.FormatBody(scheme); Console.WriteLine(message); this.ResetFormat(); } } private string GetHeader(LogLevel level) { string reti = ""; DateTime now = DateTime.Now; if (date == DateFormat.LONG) { reti += now.ToLongDateString() + " "; } else if (date == DateFormat.SHORT) { reti += now.ToShortDateString() + " "; } if (time == TimeFormat.HH) { reti += now.ToString("hh") + " "; } else if (time == TimeFormat.HH_MM) { reti += now.ToString("hh:mm") + " "; } else if (time == TimeFormat.HH_MM_SS) { reti += now.ToString("hh:mm:ss") + " "; } if (level < LogLevel.BASIC) { reti += "["; } else { reti += " "; } switch (level) { case LogLevel.CRITICAL: reti += "CRITICAL]"; break; case LogLevel.ERROR: reti += " ERROR ]"; break; case LogLevel.WARNING: reti += "WARNING ]"; break; case LogLevel.SUCCESS: reti += "SUCCESS ]"; break; case LogLevel.INFO: reti += " INFO ]"; break; default: reti += " "; break; } reti += " "; return reti; } public void LogCritical(string message) { this.Log(LogLevel.CRITICAL, message); } public void LogError(string message) { this.Log(LogLevel.ERROR, message); } public void LogWarning(string message) { this.Log(LogLevel.WARNING, message); } public void LogInfo(string message) { this.Log(LogLevel.INFO, message); } public void LogBasic(string message) { this.Log(LogLevel.BASIC, message); } public void LogSuccess(string message) { this.Log(LogLevel.SUCCESS, message); } public void LogTiny(string message) { this.Log(LogLevel.TINY, message); } public void LogMultiline(LogLevel level, string[] message) { for (int i = 0; i < message.Length; i++) { if (i == 0) { this.Log(level, message[i]); } else { for (int j = 0; j <this.header_len; j++) { Console.Write(" "); } this.FormatBody(this.SelectColorScheme(level)); Console.WriteLine(message[i]); } } this.ResetFormat(); } private void FormatBody(ConsoleColorScheme colors) { Console.ForegroundColor = colors.body_foreground; Console.BackgroundColor = colors.body_background; } private void FormatHeader(ConsoleColorScheme colors) { Console.ForegroundColor = colors.header_foreground; Console.BackgroundColor = colors.header_background; } private ConsoleColorScheme SelectColorScheme(LogLevel level) { ConsoleColorScheme reti = Format.BasicFormat; switch(level) { case LogLevel.TINY: case LogLevel.BASIC: reti = Format.BasicFormat; break; case LogLevel.INFO: reti = Format.InfoFormat; break; case LogLevel.SUCCESS: reti = Format.SuccessFormat; break; case LogLevel.WARNING: reti = Format.WarningFormat; break; case LogLevel.ERROR: reti = Format.ErrorFormat; break; case LogLevel.CRITICAL: reti = Format.CriticalFormat; break; default: reti = Format.BasicFormat; break; } return reti; } private void ResetFormat() { Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.Gray; } } } <file_sep>#include <stdlib.h> #include <stdio.h> #include "ConsoleColor.h" int main(int argc, char* argv[]) { int reti = EXIT_SUCCESS; console_color_t color; console_color_data_t data; data.ansi_color = RED; color.type = ANSI; color.data = data; console_color_t white = console_color_get_from_rgb(255, 255, 255); console_color_set_foreground(white); console_color_set_background(white); printf("Test\n\n\n"); return reti; }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NetConsole { class Program { static void Main(string[] args) { int port = GetPortFromArgument(args) == -1 ? 1350 : GetPortFromArgument(args); Logger logger = new Logger(Structures.LogLevel.TINY, Structures.DateFormat.NONE, Structures.TimeFormat.NONE); logger.LogTiny("Logger started..."); Network provider = new Network(System.Net.IPAddress.Loopback, port, logger); while (true) { provider.LogMessage(provider.ReceiveMessage()); } Console.ReadKey(); } public static int GetPortFromArgument(string[] args) { int reti = -1; foreach (string arg in args) { if (arg.ToLower().Contains("--port=")) { char[] separator = { '=' }; string[] argument = arg.Split(separator); string value = argument.Last(); try { reti = int.Parse(value); } catch { } } } return reti; } } } <file_sep>#ifndef __EXCEPTIONS_HPP__ #define __EXCEPTIONS_HPP__ #include <exception> ///<summary> ///Exception thrown when try to add village to map but village ///label is greater than maximal village count ///</summary> class VillageLabelOutOfBoundaryException : public std::exception { virtual const char* what() const throw() { return "Cannot insert village into map! Village label is out of range for villages."; } }; ///<summary> ///Exception thrown when village with set label is not in map ///</summary> class NotSuchAVillageWithLabelException : public std::exception { virtual const char* what() const throw() { return "Cannot find village in map!"; } }; ///<summary> ///Exception thrown when there is no path between villages ///<summary> class NoPathBetweenVillagesException : public std::exception { virtual const char* what() const throw() { return "Cannot find path between villages in map!"; } }; #endif // !__EXCEPTIONS_HPP__ <file_sep>#include "hw03utils.h" #include "simple_bool.h" #include "plane.h" #include <stdlib.h> #include <math.h> #include <limits.h> #include <stdio.h> //------------------------------------------------------------------------------------------------------------------------------- int utils_compute_difference(node_t* node) { int reti = 0; reti = abs(utils_compute_left_weight(node) - utils_compute_right_weight(node)); return reti; } //------------------------------------------------------------------------------------------------------------------------------- int utils_compute_left_weight(node_t* node) { int reti = 0; if (node_check_null(node) == FALSE) { reti = utils_compute_subtree_weight(node_get_left_child(node)); } return reti; } //------------------------------------------------------------------------------------------------------------------------------- int utils_compute_right_weight(node_t* node) { int reti = 0; if (node_check_null(node) == FALSE) { reti = utils_compute_subtree_weight(node_get_right_child(node)); } return reti; } //------------------------------------------------------------------------------------------------------------------------------- int utils_compute_subtree_weight(node_t* node) { int reti = 0; if (node_is_leaf(node) == FALSE) { if (node_has_left_child(node) == TRUE) reti += utils_compute_subtree_weight(node_get_left_child(node)); if (node_has_right_child(node) == TRUE) reti += utils_compute_subtree_weight(node_get_right_child(node)); } else { reti = plane_get_weight(node_get_data(node)); } return reti; } //------------------------------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------------------------- plane_array_t* utils_create_plane_array(int count) { plane_array_t* reti = (plane_array_t*)malloc(sizeof(plane_array_t*)); if (reti != (plane_array_t*)NULL) { reti->count = count; reti->data = (plane_t**)malloc(sizeof(plane_t)); } return reti; } //------------------------------------------------------------------------------------------------------------------------------- void utils_delete_plane_array(plane_array_t* plane_arr) { free(plane_arr->data); free(plane_arr); } //------------------------------------------------------------------------------------------------------------------------------- int utils_node_evaluator(node_t* node) { int reti = 0; if (node_is_leaf(node) == TRUE) { reti = plane_get_weight(node_get_data(node)); } else { reti = utils_compute_subtree_weight(node); } } //------------------------------------------------------------------------------------------------------------------------------- node_t* utils_create_tree(plane_t** planes, int start, int end) { #ifdef DEBUG printf("Checking interval <%d;%d>\n", start, end); #endif // DEBUG node_t* reti = node_create_empty(); if (start == end) { node_set_data(reti, planes[start], plane_deleter); } else { int ideal = utils_get_ideal_delimiter(planes, start, end); node_set_left_child(reti, utils_create_tree(planes, start, ideal)); node_set_right_child(reti, utils_create_tree(planes, ideal + 1, end)); int* diff = (int*)malloc(sizeof(int)); *diff = utils_compute_difference(reti); node_set_data(reti, diff, utils_int_deleter); #ifdef DEBUG printf("Setting data to node:: [%d]: %d\n", node_get_identifier(reti), *diff); #endif // DEBUG } return reti; } //------------------------------------------------------------------------------------------------------------------------------- int utils_get_ideal_delimiter(plane_t** planes, int start, int end) { int min = INT_MAX; int reti = INT_MAX; for (int i = start; i <= end; i++) { int sum1 = utils_sum_planes(planes, 0, i); int sum2 = utils_sum_planes(planes, i + 1, end); if (abs(sum2 - sum1) < min) { min = abs(sum1 - sum2); reti = i; } } #ifdef DEBUG printf("Split at: %d [%d | %d]\n", reti, utils_sum_planes(planes, start, reti), utils_sum_planes(planes, (reti + 1), end)); #endif // DEBUG return reti; } //------------------------------------------------------------------------------------------------------------------------------- int utils_sum_planes(plane_t** planes, int start, int end) { int reti = 0; for (int i = start; i <= end; i++) { reti += plane_get_weight(planes[i]); } return reti; } //------------------------------------------------------------------------------------------------------------------------------- void utils_int_deleter(void* int_ptr) { free(int_ptr); } //------------------------------------------------------------------------------------------------------------------------------- void utils_print_tree(node_t* node) { printf("(%d)\n", node_get_identifier(node)); if (node_is_leaf(node) == TRUE) { return; } else { utils_print_tree(node_get_left_child(node)); utils_print_tree(node_get_right_child(node)); } } int utils_count_whole_difference(node_t* node) { int reti = 0; if (node_is_leaf(node) == FALSE) { reti += *(int*)node_get_data(node); if (node_is_leaf(node_get_left_child(node)) == FALSE) { reti += utils_count_whole_difference(node_get_left_child(node)); } if (node_is_leaf(node_get_right_child(node)) == FALSE) { reti += utils_count_whole_difference(node_get_right_child(node)); } } return reti; } int utils_place_pilot(node_t* root, int weight) { int min = INT_MAX; int leaves_count = node_count_leaves(root); node_t** leaves = (node_t**)malloc(leaves_count * sizeof(node_t*)); node_get_leaves(root, leaves); node_t* position = node_NULL; for (int i = 0; i < leaves_count; i++) { plane_t* plane = (plane_t*)node_get_data(leaves[i]); bool plane_has_pilot = plane_get_has_pilot(plane); if (plane_has_pilot == FALSE) { int res = utils_try_place_pilot(leaves[i], weight); if (res < min) { min = res; position = leaves[i]; } } } plane_set_pilot((plane_t*)node_get_data(position), weight); utils_update_node(position); #ifdef DEBUG printf(">>%d(%d)\n", node_get_identifier(position), plane_get_weight(node_get_data(position))); #endif // DEBUG free(leaves); //utils_update_tree_differences(position); return min; } int utils_try_place_pilot(node_t* node, int weight) { int reti = 0; plane_set_pilot((plane_t*)node_get_data(node), weight); utils_update_node(node); node_t* root = node; while (node_has_parent(root) == TRUE) { root = node_get_parent(root); break; } reti = utils_count_whole_difference(root); plane_unset_pilot((plane_t*)node_get_data(node), weight); utils_update_node(node); return reti; } void utils_update_tree_differences(node_t* leafe) { node_t* parent = leafe; node_t* child = node_NULL; int sum = plane_get_weight(node_get_data(leafe)); while (node_has_parent(parent)) { child = parent; parent = node_get_parent(parent); if (node_is_leaf(parent) == FALSE) { int* diff = node_get_data(parent); if (node_check_same(node_get_left_child(parent), child) == TRUE) { //Left child int right_weight = utils_compute_subtree_weight(node_get_right_child(parent)); *diff = abs(sum - right_weight); node_set_data(parent, diff, utils_int_deleter); sum += right_weight; } if (node_check_same(node_get_right_child(parent), child) == TRUE) { //Right child int left_weight = utils_compute_subtree_weight(node_get_left_child(parent)); *diff = abs(sum - left_weight); node_set_data(parent, diff, utils_int_deleter); sum += left_weight; } } } } void utils_update_node(node_t* node) { if (node_has_parent(node) == FALSE) { int left_weight = utils_compute_subtree_weight(node_get_left_child(node)); int right_weight = utils_compute_subtree_weight(node_get_right_child(node)); #ifdef DEBUG printf("[id: %d]: L:%d R:%d\n", node_get_identifier(node), left_weight, right_weight); #endif // DEBUG int* diff = node_get_data(node); *diff = abs(left_weight - right_weight); node_set_data_force(node, diff, utils_int_deleter); return; } if (node_is_leaf(node) == FALSE) { int left_weight = utils_compute_subtree_weight(node_get_left_child(node)); int right_weight = utils_compute_subtree_weight(node_get_right_child(node)); #ifdef DEBUG printf("[id: %d]: L:%d R:%d\n", node_get_identifier(node), left_weight, right_weight); #endif // DEBUG int* diff = node_get_data(node); *diff = abs(left_weight - right_weight); node_set_data_force(node, diff, utils_int_deleter); utils_update_node(node_get_parent(node)); } else { utils_update_node(node_get_parent(node)); } } int utils_default_evaluator(node_t* node) { if (node_is_leaf(node) == TRUE) { return plane_get_weight(node_get_data(node)); } else { int* reti = node_get_data(node); return *reti; } } void utils_set_evaluator(node_t* node) { node_set_evaluator(node, utils_default_evaluator); if (node_is_leaf(node) == FALSE) { if (node_has_left_child(node) == TRUE) { utils_set_evaluator(node_get_left_child(node)); } if (node_has_right_child(node) == TRUE) { utils_set_evaluator(node_get_right_child(node)); } } } <file_sep>#ifndef __MAP_HPP__ #define __MAP_HPP__ ///<summary> ///Default value of distance which sets two villages with no path between them ///</summary> #define VILLAGE_UNAVIALABLE -1 #include "Village.hpp" #include "config.h" #include <vector> #include <queue> ///<summary> ///Class representing map with villages ///</summary> class Map { private: ///<summary> ///Array with villages which are on map ///</summary> Village** villages; ///<summary> ///Count of villages on map ///</summary> int villages_count; ///<summary> ///Recursive function which finds shortes path between villages ///</summary> void findShortestPath(std::queue<Village*>* villages, Village* actual, Village* final_village); public: ///<summary> ///Creates new map with villages ///</summary> ///<param name="villages">Count of villages on map</param> ///<returns>New instance of map</returns> Map(int villages); ///<summary> ///Adds village to map ///</summary> ///<param name="village">Village which will be added to map</param> void addVillage(Village* village); ///<summary> ///Gets village by its label ///</summary> ///<param name="label">Label of village</param> ///<returns>Village with set label or <c>NULL</c></returns> Village* getVillage(int label); ///<summary> ///Makes path between two villages ///</summary> ///<param name="villageA">Starting village</param> ///<param name="villageB">Finishing village</param> ///<param name="cost">Cost of path between starting and finishing village</param> void makePath(Village* villageA, Village* villageB, int cost); ///<summary> ///Gets cost of path between villages ///</summary> ///<param name="villageA">Starting village</param> ///<param name="villageB">Finishing village</param> ///<returns>Cost of path between starting and finishing village</returns> int getCost(Village* villageA, Village* villageB); ///<summary> ///Gets paths leading from village ///</summary> ///<param name="village">Village which paths from will be returned</param> ///<returns>Paths leading from village</returns> std::vector<Path<Village*>*>* getPaths(Village* village); ///<summary> ///Gets neighbour villages available from one village ///</summary> ///<param name="village">Village which neighbours will be returned</param> ///<returns>Neighbour villages from set village</returns> std::vector<Village*>* getNeighbours(Village* village); ///<summary> ///Gets shortest path between two villages ///</summary> ///<param name="start_village">Starting village of shortest path finding</param> ///<param name="final_village">Final village of shortest path finind</param> ///<returns>Vector with villages visited during finding shortest path finindg</returns> std::vector<Village*>* findPath(Village* start_village, Village* final_village); ~Map(); }; #endif // ! __MAP_HPP__ <file_sep>using System; using System.Collections.Generic; using System.Text; using System.Net.Sockets; using System.Net; using NetworkSender; using static NetworkSender.Structures; namespace NetworkSender { class Network { private UdpClient udpClient; private int port; private IPAddress ipAddress; private IPEndPoint ipEndPoint; private Logger logger; public Network(IPAddress address, int port, Logger logger) { this.ipAddress = address; this.port = port; this.logger = logger; this.init(); } public Network(string address, int port, Logger logger) { this.ipAddress = Dns.GetHostEntry(address).AddressList[0]; this.port = port; this.logger = logger; this.init(); } private void init() { this.udpClient = new UdpClient(); this.ipEndPoint = new IPEndPoint(this.ipAddress, this.port); this.logger.LogSuccess("Client started; sedning via port " + this.port); } public void sendMessage(string message) { Byte[] buffer = Encoding.ASCII.GetBytes(message); try { this.udpClient.Send(buffer, buffer.Length, this.ipEndPoint); } catch (Exception ex) { string[] log = { "Sending failed", ex.Message }; this.logger.LogMultiline(LogLevel.ERROR,log); } this.logger.LogSuccess("Data sent"); } } } <file_sep>#pragma once void util_print_int_array(int* array, int array_count);<file_sep>#include "queue.h" #include <stdlib.h> queue_t* queue_create() { queue_t* reti = malloc(sizeof(queue_t)); if (reti != NULL) { reti->count = 0; reti->length = 2; reti->head = 0; reti->tail = 0; reti->next_head = 0; reti->data = (void**)malloc(reti->length * sizeof(void*)); } return reti; } bool queue_push(queue_t* queue, void* data) { if (queue->count + 1 <= queue->length) { queue_upscale(queue); } queue->data[queue->tail] = data; queue->tail++; queue->count++; return TRUE; } void* queue_pop(queue_t* queue) { void* reti = NULL; if (queue_is_empty(queue) == FALSE) { reti = queue->data[queue->head]; queue->head++; queue->count--; queue_shrink(queue); } return reti; } bool queue_is_empty(queue_t* queue) { return (queue->count == 0 ? TRUE : FALSE); } bool queue_is_full(queue_t* queue) { return (queue->count == queue->length ? TRUE : FALSE); } void queue_upscale(queue_t* queue) { queue->length = queue->length * 2; queue->data = realloc(queue->data, queue->length); } void queue_shrink(queue_t* queue) { if (queue->count == ((queue->length / 3) * 2)) { void** new_data = malloc(((queue->length / 3) * 2) * sizeof(void*)); int idx = 0; for (int i = queue->head; i < queue->tail; i++) { new_data[idx] = queue->data[i]; } free(queue->data); queue->data = new_data; int diff = queue->head; queue->head = 0; queue->tail = idx; queue->length = ((queue->length / 3) * 2); queue->next_head = queue->next_head - diff; } } int queue_count(queue_t* queue) { return queue->count; } void* queue_at(queue_t* queue, int index) { void* reti = NULL; if (queue_index_in_queue(index, queue)) { reti = queue->data[index]; } return reti; } bool queue_is_not_empty(queue_t* queue) { return (queue->count > 0 ? TRUE : FALSE); } void* queue_next(queue_t* queue) { void* reti = NULL; if (queue->next_head < queue->tail) { reti = queue_at(queue, queue->next_head); queue->next_head++; } return reti; } bool queue_next_not_empty(queue_t* queue) { bool reti = FALSE; if (queue->next_head + 1 < queue->tail) { reti = TRUE; } return reti; } void queue_reset_next_index(queue_t* queue) { queue->next_head = queue->head; } queue_t* queue_reverse_data(queue_t* queue) { queue_t* reti = queue_create(); for (int i = (queue->tail - 1); i >= queue->head; i--) { queue_push(reti, queue_at(queue, i)); } return reti; } void queue_delete(queue_t* queue) { free(queue->data); free(queue); } bool queue_contains(queue_t* queue, void* element, sort_t sort, int(*comparator(void*, void*))) { bool reti = FALSE; if (sort == NONE) { for (int i = queue->head; i <= queue->tail; i++) { if (comparator(queue_at(queue, i), element) == 0) { reti = TRUE; break; } } } else { reti = queue_binary_search(queue, element, sort, comparator); } return reti; } bool queue_binary_search(queue_t* queue, void* element, sort_t sort, int(*comparator(void*, void*))) { return queue_binary_search_recursive(queue, element, sort, queue->head, queue->tail, comparator); } bool queue_binary_search_recursive(queue_t* queue, void* element, sort_t sort, int start_index, int end_index, int(*comparator(void*, void*))) { int index = queue_binary_search_next_index(start_index, end_index, queue); void* found = queue_at(queue, index); if (comparator(found, element) == 0) { return TRUE; } else if ((start_index == index && queue_index_in_queue(start_index, queue)) || (end_index == index && queue_index_in_queue(end_index, queue))) { if ((comparator(queue_at(queue, start_index), element) == 0 && queue_index_in_queue(start_index, queue) == TRUE) || (comparator(queue_at(queue, end_index), element) == 0 && queue_index_in_queue(end_index, queue) == TRUE)) { return TRUE; } else { return FALSE; } } else if (index != -1) { if (sort == ASC) { if (comparator(found, element) > 0) { return queue_binary_search_recursive(queue, element, sort, start_index, index, comparator); } else if (comparator(found, element) < 0) { return queue_binary_search_recursive(queue, element, sort, index, end_index, comparator); } } else if (sort == DESC) { if ( comparator(found, element) > 0) { return queue_binary_search_recursive(queue, element, sort, index, end_index, comparator); } else if (comparator(found, element) < 0) { return queue_binary_search_recursive(queue, element, sort, start_index, index, comparator); } } else { if ((comparator(queue_at(queue, start_index), element) == 0 && queue_index_in_queue(start_index, queue) == TRUE) || (comparator(queue_at(queue, end_index), element) == 0 && queue_index_in_queue(end_index, queue) == TRUE)) { return TRUE; } } } else if (index == -1) { if ((comparator(queue_at(queue, start_index), element) == 0 && queue_index_in_queue(start_index, queue) == TRUE) || (comparator(queue_at(queue, end_index), element) == 0 && queue_index_in_queue(end_index, queue))) { return TRUE; } } return FALSE; } int queue_binary_search_next_index(int start_index, int end_index, queue_t* queue) { int reti = -1; int computed = (start_index + end_index) / 2; if (queue_index_in_queue(computed, queue) == TRUE && start_index != end_index) { reti = computed; } return reti; } bool queue_index_in_queue(int index, queue_t* queue) { bool reti = FALSE; if (index >= queue->head && index < queue->tail) { reti = TRUE; } return reti; }<file_sep>#include "queue.h" #include "hw04structs.h" #include "config.h" extern int ROWS, COLS, E_init, D_mov, D_env; extern int** MAP; extern situation_t*** VISITED; extern int MIN_STEPS; extern queue_t* SITUATIONS; extern point_t* FINISH; #ifdef SHOW_MAP extern int STEPS; #endif // SHOW_MAP <file_sep>#include "laboratory.h" #include <stdlib.h> #include <stdio.h> #include "config.h" #include "utils.h" #include <math.h> #define LAB_FREE -1 #define ACCEPT_RATIO 0.001 static volatile int MAX_INCOME = 0; static volatile int DAYS_CLAIMED = 0; laboratory_t* laboratory_create(int days_available, int experiments_count, experiment_t** experiments) { laboratory_t* reti = (laboratory_t*)malloc(sizeof(laboratory_t)); reti->days_available = days_available; reti->days_used = (int*)malloc(reti->days_available * sizeof(int)); for (int i = 0; i < reti->days_available; i++) { reti->days_used[i] = LAB_FREE; } reti->experiments_available = experiments; reti->experiments_available_count = experiments_count; reti->experiment_unused = queue_create_static(reti->experiments_available_count); reti->total_income = 0; reti->days_claimed = 0; reti->maximal_income = 0; for (int i = 0; i < reti->experiments_available_count; i++) { queue_push(reti->experiment_unused, experiments[i]); reti->maximal_income += experiments[i]->income; } return reti; } laboratory_t* laboratory_copy(laboratory_t* laboratory) { laboratory_t* reti = (laboratory_t*)malloc(sizeof(laboratory_t)); reti->days_available = laboratory->days_available; reti->days_used = (int*)malloc(reti->days_available * sizeof(int)); for (int i = 0; i < reti->days_available; i++) { reti->days_used[i] = laboratory->days_used[i]; } reti->experiments_available_count = laboratory->experiments_available_count; reti->experiments_available = laboratory->experiments_available; reti->total_income = laboratory->total_income; reti->days_claimed = laboratory->days_claimed; reti->maximal_income = laboratory->maximal_income; reti->experiment_unused = queue_create_static(queue_count(laboratory->experiment_unused)); while (queue_next_not_empty(laboratory->experiment_unused) == TRUE) { queue_push(reti->experiment_unused, queue_next(laboratory->experiment_unused)); } queue_reset_next_index(laboratory->experiment_unused); return reti; } void laboratory_quicksort_experiments_by_length_asc(laboratory_t* laboratory) { laboratory_quicksort_experiments_by_length_asc_rec(laboratory, 0, laboratory->experiments_available_count - 1); queue_delete(laboratory->experiment_unused); laboratory->experiment_unused = queue_create_static(laboratory->experiments_available_count); for (int i = 0; i < laboratory->experiments_available_count; i++) { queue_push(laboratory->experiment_unused, laboratory->experiments_available[i]); } #ifdef DEBUG printf(" queue count:%d\n", queue_count(laboratory->experiment_unused)); #endif // DEBUG } //Source: https://cs.wikipedia.org/wiki/Quicksort void laboratory_quicksort_experiments_by_length_asc_rec(laboratory_t* laboratory, int left_begin, int right_begin) { experiment_t* pivot = laboratory->experiments_available[(left_begin + right_begin) / 2]; int left_index, right_index; experiment_t* pom; left_index = left_begin; right_index = right_begin; do { while (laboratory->experiments_available[left_index]->days_count < pivot->days_count && left_index < right_begin) left_index++; while (laboratory->experiments_available[right_index]->days_count > pivot->days_count&& right_index > left_begin) right_index--; if (left_index <= right_index) { pom = laboratory->experiments_available[left_index]; laboratory->experiments_available[left_index++] = laboratory->experiments_available[right_index]; laboratory->experiments_available[right_index--] = pom; } } while (left_index < right_index); if (right_index > left_begin) laboratory_quicksort_experiments_by_length_asc_rec(laboratory, left_begin, right_index); if (left_index < right_begin) laboratory_quicksort_experiments_by_length_asc_rec(laboratory, left_index, right_begin); } void laboratory_quicksort_experiments_by_length_desc(laboratory_t* laboratory) { laboratory_quicksort_experiments_by_length_asc(laboratory); experiment_t** new_experiments = (experiment_t**)malloc(laboratory->experiments_available_count * sizeof(experiment_t*)); for (int i = 0; i < laboratory->experiments_available_count; i++) { new_experiments[laboratory->experiments_available_count - 1 - i] = laboratory->experiments_available[i]; } free(laboratory->experiments_available); laboratory->experiments_available = new_experiments; queue_t* new_unused = queue_reverse_data(laboratory->experiment_unused); free(laboratory->experiment_unused); laboratory->experiment_unused = new_unused; } experiment_t** laboratory_get_experiments(laboratory_t* laboratory) { return laboratory->experiments_available; } int laboratory_get_experiments_count(laboratory_t* laboratory) { return laboratory->experiments_available_count; } bool laboratory_schedule_experiment(laboratory_t* laboratory, experiment_t* experiment, int start_day) { bool reti = FALSE; if (laboratory_can_schedule_experiment(laboratory, experiment, start_day) == TRUE) { reti = TRUE; for (int i = 0; i < experiment->days_count; i++) { laboratory->days_used[experiment->days[i] + start_day] = experiment->id; } laboratory->total_income += experiment->income; laboratory->days_claimed += experiment->days_count; } return reti; } bool laboratory_can_schedule_experiment(laboratory_t* laboratory, experiment_t* experiment, int start_day) { bool reti = TRUE; for (int i = 0; i < experiment->days_count; i++) { if (start_day + experiment->days[i] > laboratory->days_available || laboratory_is_not_scheduled_day(laboratory, start_day + experiment->days[i]) == FALSE) { reti = FALSE; break; } } return reti; } bool laboratory_is_not_scheduled_day(laboratory_t* laboratory, int day) { return (laboratory->days_used[day] == LAB_FREE ? TRUE : FALSE); } laboratory_t* laboratory_recursive_experiment_scheduler(laboratory_t* laboratory, experiment_t* experiment, int last_used_day) { last_used_day++; if (last_used_day == laboratory->days_available) { return laboratory_copy(laboratory); } for (int i = last_used_day; i < laboratory->days_available; i++) { if (laboratory_can_schedule_experiment(laboratory, experiment, i)) { printf("day: %d, start at: %d\n", last_used_day, i); } laboratory_recursive_scheduler(laboratory, last_used_day); } #ifdef DEBUG //printf("Availablde schedule:: income: %d, experiments: ", laboratory->total_income); //util_print_int_array(laboratory->days_used, laboratory->days_available); //printf("\n"); #endif // DEBUG } void laboratory_recursive_scheduler(laboratory_t* laboratory, int last_used_day) { laboratory_recursive_experiment_scheduler(laboratory, laboratory->experiments_available[0], last_used_day); } dyn_queue_t* laboratory_experiment_scheduler(laboratory_t* laboratory, experiment_t* experiment, int start_day) { dyn_queue_t* reti = dyn_queue_create(); dyn_queue_push(reti, laboratory_copy(laboratory)); for (int i = start_day; i < laboratory->days_available; i++) { if (laboratory_can_schedule_experiment(laboratory, experiment, i) == TRUE) { laboratory_t* new_lab = laboratory_copy(laboratory); laboratory_schedule_experiment(new_lab, experiment, i); #ifdef DEBUG printf("start experiment: %d, at: %d ($%d)\n", experiment->id, i, experiment->income); #endif // DEBUG dyn_queue_push(reti, new_lab); } } return reti; } void laboratory_scheduler(laboratory_t* laboratory) { dyn_queue_t* all_states = dyn_queue_create(); dyn_queue_push(all_states, laboratory); while (queue_is_empty(laboratory->experiment_unused) == FALSE) { experiment_t* exp = queue_pop(laboratory->experiment_unused); dyn_queue_t* tmp_states = dyn_queue_copy(all_states); while (dyn_queue_is_empty(tmp_states) == FALSE) { laboratory_t* tmp_lab = dyn_queue_pop(tmp_states); dyn_queue_t* exp_scheduled = laboratory_experiment_scheduler(tmp_lab, exp, 0); while (dyn_queue_is_empty(exp_scheduled) == FALSE) { laboratory_t* res = dyn_queue_pop(exp_scheduled); #ifdef DEBUG printf("maximal income: %d, income: %d\n", res->maximal_income, res->total_income); #endif // DEBUG if (res->total_income > tmp_lab->total_income && res->total_income > MAX_INCOME * pow(((float)ACCEPT_RATIO),(float)((float)res->experiments_available_count - (float)res->experiment_unused->count))) { dyn_queue_push(all_states, res); if (res->total_income > MAX_INCOME) { MAX_INCOME = res->total_income; DAYS_CLAIMED = res->days_claimed; } } } dyn_queue_delete(exp_scheduled); } dyn_queue_delete(tmp_states); } #ifdef DEBUG printf("=== RESULTS (%d) ===\n", all_states->count); while (dyn_queue_is_empty(all_states) == FALSE) { laboratory_t* lab = dyn_queue_pop(all_states); printf("$%d, ", lab->total_income); util_print_int_array(lab->days_used, lab->days_available); printf("\n"); } dyn_queue_delete(all_states); #endif // DEBUG printf("%d %d\n", MAX_INCOME, DAYS_CLAIMED); } <file_sep>///<summary> /// File containing implementation of node functions ///</summary> ///<remarks> /// Copyright 2019 <NAME> <<EMAIL>> /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http ://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissionsand /// limitations under the License. ///</remarks> #include <stdlib.h> #include <stdio.h> #include "node.h" //------------------------------------------------------------------------------------------------------------------------------- node_t* node_create_empty() { node_t* reti = (node_t*)malloc(sizeof(node_t)); if (reti != node_NULL) { reti->data = NULL; reti->delete = node_delete_empty_data; node_LAST_ID++; reti->id = node_LAST_ID; reti->left_child = node_NULL; reti->right_child = node_NULL; reti->parent = node_NULL; reti->evaluator = node_default_evaluator; } return reti; } //------------------------------------------------------------------------------------------------------------------------------- node_t* node_create(void* data, void(*delete)(void*)) { node_t* reti = (node_t*)malloc(sizeof(node_t)); if (reti != NULL) { reti->data = data; reti->delete = delete; node_LAST_ID++; reti->id = node_LAST_ID; reti->left_child = node_NULL; reti->parent = node_NULL; reti->right_child = node_NULL; reti->evaluator = node_default_evaluator; } return reti; } //------------------------------------------------------------------------------------------------------------------------------- void node_delete(node_t* node) { node->delete(node->data); free(node); } //------------------------------------------------------------------------------------------------------------------------------- void node_delete_empty_data(void* data) { //pass } //------------------------------------------------------------------------------------------------------------------------------- bool node_is_empty(node_t* node) { bool reti = FALSE; if ( node_check_null(node) == TRUE || ( node->data == NULL && node_check_null(node_get_left_child(node)) == TRUE && node_check_null(node_get_right_child(node)) == TRUE ) ) { reti = TRUE; } return reti; } //------------------------------------------------------------------------------------------------------------------------------- bool node_set_parent(node_t* node, node_t* parent, node_child_t child) { bool reti = FALSE; bool set = FALSE; if (child == LEFT || child == ANY) { if (node_check_null(node_get_left_child(parent)) == TRUE) { node->parent = parent; node_set_left_child(node_get_parent(node), node); set = TRUE; reti = TRUE; } } if (child == RIGHT || (child == ANY && set == FALSE)) { if (node_check_null(node_get_right_child(parent)) == TRUE) { node->parent = parent; node_set_right_child(node_get_parent(node), node); reti = TRUE; set = TRUE; } } return reti; } //------------------------------------------------------------------------------------------------------------------------------- node_t* node_get_parent(node_t* node) { return node->parent; } //------------------------------------------------------------------------------------------------------------------------------- bool node_set_child(node_t* node, node_t* child, node_child_t position) { bool reti = FALSE; if (position == LEFT) { reti = node_set_left_child(node, child); } else if (position == RIGHT) { reti = node_set_right_child(node, child); } else if (position == ANY) { int rnd = rand() % 2; node_child_t first_position = (rnd == 0 ? LEFT : RIGHT); node_child_t second_position = (first_position == LEFT ? RIGHT : LEFT); reti = node_set_child(node, child, first_position); if (reti == FALSE) { reti = node_set_child(node, child, second_position); } } return reti; } //------------------------------------------------------------------------------------------------------------------------------- node_t* node_get_child(node_t* node, node_child_t position) { node_t* reti = node_NULL; if (position == LEFT) { reti = node_get_left_child(node); } else if (position == RIGHT) { reti = node_get_right_child(node); } else if (position == ANY) { int rnd = rand() % 2; node_child_t first_position = (rnd == 0 ? LEFT : RIGHT); node_child_t second_position = (first_position == LEFT ? RIGHT : LEFT); reti = node_get_child(node, first_position); if (node_check_null(reti) == TRUE) { reti = node_get_child(node, second_position); } } return reti; } //------------------------------------------------------------------------------------------------------------------------------- bool node_set_left_child(node_t* node, node_t* left_child) { bool reti = FALSE; if (node_check_null(node_get_left_child(node)) == TRUE) { reti = TRUE; node->left_child = left_child; node->left_child->parent = node; } return reti; } //------------------------------------------------------------------------------------------------------------------------------- node_t* node_get_left_child(node_t* node) { return node->left_child; } //------------------------------------------------------------------------------------------------------------------------------- bool node_set_right_child(node_t* node, node_t* right_child) { bool reti = FALSE; if (node_check_null(node_get_right_child(node)) == TRUE) { reti = TRUE; node->right_child = right_child; node->right_child->parent = node; } return reti; } //------------------------------------------------------------------------------------------------------------------------------- node_t* node_get_right_child(node_t* node) { return node->right_child; } //------------------------------------------------------------------------------------------------------------------------------- int node_get_identifier(node_t* node) { int reti = -1; if (node_check_null(node) == FALSE) { reti = node->id; } return reti; } //------------------------------------------------------------------------------------------------------------------------------- void* node_get_data(node_t* node) { return node->data; } //------------------------------------------------------------------------------------------------------------------------------- bool node_set_data(node_t* node, void* data, void(*delete)(void*)) { bool reti = FALSE; if (node->data == NULL) { node->data = data; node->delete = delete; } return reti; } //------------------------------------------------------------------------------------------------------------------------------- void node_set_data_force(node_t* node, void* data, void(*delete)(void*)) { node->data = data; node->delete = delete; } //------------------------------------------------------------------------------------------------------------------------------- bool node_check_same(node_t* node1, node_t* node2) { return (node_get_identifier(node1) == node_get_identifier(node2) ? TRUE : FALSE); } //------------------------------------------------------------------------------------------------------------------------------- bool node_deep_check_same(node_t* node1, node_t* node2) { bool reti = FALSE; if ( (node_check_null(node1) == TRUE && node_check_null(node2) == TRUE)|| ( node_check_null(node1) == FALSE && node_check_null(node2) == FALSE && node_get_identifier(node1) == node_get_identifier(node2) && node_deep_check_same(node_get_left_child(node1), node_get_left_child(node2)) == TRUE && node_deep_check_same(node_get_right_child(node1), node_get_right_child(node2)) == TRUE && node_get_data(node1) == node_get_data(node2) ) ) { reti = TRUE; } return reti; } //------------------------------------------------------------------------------------------------------------------------------- bool node_check_null(node_t* node) { return (node == node_NULL ? TRUE : FALSE); } //------------------------------------------------------------------------------------------------------------------------------- bool node_has_left_child(node_t* node) { return (node_check_null(node_get_left_child(node)) == TRUE ? FALSE : TRUE); } //------------------------------------------------------------------------------------------------------------------------------- bool node_has_right_child(node_t* node) { return (node_check_null(node_get_right_child(node)) == TRUE ? FALSE : TRUE); } //------------------------------------------------------------------------------------------------------------------------------- bool node_has_child(node_t* node) { return (node_has_left_child(node) == TRUE ? TRUE : node_has_right_child(node) ? TRUE : FALSE); } //------------------------------------------------------------------------------------------------------------------------------- bool node_has_parent(node_t* node) { return (node_check_null(node_get_parent(node)) == TRUE ? FALSE : TRUE); } //------------------------------------------------------------------------------------------------------------------------------- bool node_is_leaf(node_t* node) { return (node_check_null(node_get_left_child(node)) == TRUE && node_check_null(node_get_right_child(node)) == TRUE ? TRUE : FALSE); } //------------------------------------------------------------------------------------------------------------------------------- void node_set_evaluator(node_t* node, int(*evaluate)(node_t*)) { node->evaluator = evaluate; } //------------------------------------------------------------------------------------------------------------------------------- int node_evaluate(node_t* node) { return (node->evaluator(node)); } //------------------------------------------------------------------------------------------------------------------------------- int node_default_evaluator(node_t* node) { return node_get_identifier(node); } //------------------------------------------------------------------------------------------------------------------------------- void node_delete_tree(node_t* node) { if (node_is_leaf == TRUE) { node_delete(node); return; } else { node_delete_tree(node_get_right_child(node)); node_delete_tree(node_get_left_child(node)); } } //------------------------------------------------------------------------------------------------------------------------------- int node_count_leaves(node_t* node) { int reti = 0; if (node_is_leaf(node) == TRUE) { reti += 1; } else { reti += node_count_leaves(node_get_left_child(node)); reti += node_count_leaves(node_get_right_child(node)); } return reti; } //------------------------------------------------------------------------------------------------------------------------------- static int node_find_leaves_index = 0; void node_get_leaves(node_t* node, node_t** result) { int count = node_count_leaves(node); result = realloc(result, count * sizeof(node_t*)); node_find_leaves_index = 0; node_find_leaves(node, result); } //------------------------------------------------------------------------------------------------------------------------------- void node_find_leaves(node_t* node, node_t** result) { if (node_is_leaf(node) == TRUE) { result[node_find_leaves_index] = node; node_find_leaves_index++; #ifdef DEBUG printf("Node %d is leafe\n", node_get_identifier(node)); #endif // DEBUG return; } else { node_find_leaves(node_get_right_child(node), result); node_find_leaves(node_get_left_child(node), result); } } //------------------------------------------------------------------------------------------------------------------------------- #ifdef DEBUG void node_print(node_t* node, void(*print)(void*)) { printf("NODE\n"); printf(" - id: %d\n", node_get_identifier(node)); printf(" - parent: "); printf((node_has_parent(node)) == TRUE ? "%d" : "(null)", node_get_identifier(node_get_parent(node))); printf("\n"); printf(" - left child: "); printf((node_has_left_child(node)) == TRUE ? "%d" : "(null)", node_get_identifier(node_get_left_child(node))); printf("\n"); printf(" - right child: "); printf((node_has_right_child(node)) == TRUE ? "%d" : "(null)", node_get_identifier(node_get_right_child(node))); printf("\n"); printf(" - data:"); print(node_get_data(node)); printf("\n"); } void node_print_tree_nodes_evaluation(node_t* node) { printf("[%d]: %d\n", node_get_identifier(node), node_evaluate(node)); if (node_is_leaf(node)) { return; } else { if (node_has_left_child(node) == TRUE) { node_print_tree_nodes_evaluation(node_get_left_child(node)); } if (node_has_right_child(node) == TRUE) { node_print_tree_nodes_evaluation(node_get_right_child(node)); } } } #endif // DEBUG //-------------------------------------------------------------------------------------------------------------------------------
ac000c6c69cbbbd0599e3a9ca11cb1a230a93f80
[ "Makefile", "C#", "C", "C++", "Shell" ]
68
C
byte98/B4B33ALG
fad61e696c38d72c1461a2a716bfb415ce5d3355
3127d5f869294862b7afc295a14c8c8cb22f2f17
refs/heads/master
<file_sep>/* * procs.c * * Created on: Oct 12, 2018 * Author: NickB */ #include "kernelcalls.h" #include "procs.h" #include "MSGpasser.h" #include "kernel.h" #include "ISRs.h" #include <string.h> #include <stdio.h> #include <ctype.h> #include <stdlib.h> int nice_flag = 0; #define PKTSZE 5 void proc1() // During development this process acts primarily as a never ending process which prints 1s { int i = 0; // delay loop counter int SuccesfulBind; int SuccesfulSend; char * p1message = "12345"; // character pointer to a location this proesses stack mem containing the message SuccesfulBind = p_bind(1); // SuccesfulBind will be TRUE if succesful bind occured, FALSE if bind failed /*-----------------------------------------------------------------------------*/ /* The following is an outline of the four arguments being sent */ /* by this process to another process. The four arguments are as follows */ /* */ /* arg 1: destination of the message about to be sent */ /* arg 2: message source */ /* arg 3: a character pointer to somewhere in this processes stacks mem */ /* arg 4: the size of the message to be sent */ /* * note: the return value is TRUE if the data was succesfully * and FALSE if the data was not able to send the message */ /*------------------------------------------------------------------------------*/ if(SuccesfulBind){ while(1){ while(i < 1000000){ i++; } SuccesfulSend = p_send(2, 1, p1message, 5); // arg 1: destination of the message about to be sent i = 0; } } else p_terminate(); } void proc2() { int j = 0;// delay loop counter int k = 0; int incomingMsgSrc; // memory location on this processeses stack for incoming message source char incomingMsg[5]; // an a pointer to an array of 5 characters. memory location on this processeses stack for incoming message int row = ROW_ONE; int col = COL_ONE; int SuccesfulBind; //int SuccesfulRecv = FALSE; // not currently used SuccesfulBind = p_bind(2); if(SuccesfulBind){ while(1){ /*-----------------------------------------------------------------------------*/ /* The following is an outline of the four arguments being received */ /* by this process from its queue. The four arguments are as follows */ /* */ /* arg 1: the message queue from which to receive our message */ /* arg 2: pointer to the location for the message source to be stored */ /* arg 3: pointer to the location for the message to be stored */ /* arg 4: the size of the message to be recieved */ /* / * note: the return value is TRUE if the msg was succesfully recvd */ /* and FALSE if the msg was not succesfully recvd */ /*------------------------------------------------------------------------------*/ while(!(p_recv(2, &incomingMsgSrc, incomingMsg, 5))); // 5 because thats what the incoming message is uart_output_ch(row, col++, incomingMsg[0], 0); while(j < 100000){ j++; } j = 0; // resets delay loop counter uart_output_ch(row, col++, incomingMsg[1], 0); while(j < 100000){ j++; } j = 0; // resets delay loop counter uart_output_ch(row, col++, incomingMsg[2], 0); while(j < 100000){ j++; } j = 0; // resets delay loop counter uart_output_ch(row, col++, incomingMsg[3], 0); while(j < 100000){ j++; } j = 0; // resets delay loop counter uart_output_ch(row, col++, incomingMsg[4], 0); while(j < 100000){ j++; } j = 0; // resets delay loop counter if(col > 80){ // if our text reaches 80 characters, return the column to 1 and increment the row col = 1; row++; } } // while(1) close bracket } else p_terminate(); } void proc3() // currently is the get_id process { int myid; myid = p_get_id(); char strID [1]; sprintf(strID, "%d", myid); int i = 0; // delay loop counter // while(1){ while(i < 10000){ i++; } uart_output_ch(running[high_priority]->id, 1, strID[0], 0); i = 0; // resets delay loop counter // } p_terminate(); // the function which will make the kernel command call } void proc4() // During development this process acts primarily as a never ending process which prints 1s { int i = 0; // delay loop counter int SuccesfulBind; int SuccesfulSend; char * p1message = "abcde"; // character pointer to a location this proesses stack mem containing the message SuccesfulBind = p_bind(4); // SuccesfulBind will be TRUE if succesful bind occured, FALSE if bind failed /*-----------------------------------------------------------------------------*/ /* The following is an outline of the four arguments being sent */ /* by this process to another process. The four arguments are as follows */ /* */ /* arg 1: destination of the message about to be sent */ /* arg 2: message source */ /* arg 3: a character pointer to somewhere in this processes stacks mem */ /* arg 4: the size of the message to be sent */ /* * note: the return value is TRUE if the data was succesfully * and FALSE if the data was not able to send the message */ /*------------------------------------------------------------------------------*/ if(SuccesfulBind){ while(1){ while(i < 10000000){ i++; } SuccesfulSend = p_send(2, 4, p1message, 5); // arg 1: destination of the message about to be sent i = 0; } } else p_terminate(); } void proc5() // During development this process acts primarily as a never ending process which prints 1 through 9 on { int j = 0;// delay loop counter char exmpMsg1[1] = "a"; char exmpMsg2[1] = "1"; while(1){ while(j < 1000000){ j++; } j = 0; uart_output_ch(running[high_priority]->id, 1, exmpMsg1[0], 0); // 1 indicates the column number while(j < 1000000){ j++; } j = 0; uart_output_ch(running[high_priority]->id, 2, exmpMsg2[0], 0); // 2 indicates the column number } } void proc6() // During development this process acts primarily as a never ending process which prints 1s { int row = running[high_priority]->id; int col = 1; char ch[1] = "1"; int j = 0; // delay loop counter while(1){ while(j < 1000000){ j++; } j = 0; uart_output_ch(row, col++, ch[0]++, 0); if (col > 80) col = 1; if (ch[0] > '9') ch[0] = '1'; } } void proc7() // During development this process acts primarily as a never ending process which prints 1s { int row = running[high_priority]->id; int col = 1; char ch[1] = "1"; int j = 0; // delay loop counter while(1){ while(j < 1000000){ j++; } j = 0; uart_output_ch(row, col++, ch[0]++, 0); if (col > 80) col = 1; if (ch[0] > '9') ch[0] = '1'; } } void proc8() // During development this process acts primarily as a never ending process which prints 1s { int row = running[high_priority]->id; int col = 1; char ch[1] = "1"; int j = 0; // delay loop counter while(1){ while(j < 1000000){ j++; } j = 0; uart_output_ch(row, col++, ch[0]++, 0); if (col > 80) col = 1; if (ch[0] > '9') ch[0] = '1'; } } void proc9() // During development this process acts primarily as a never ending process which prints 1s { //proc 9 will now output a message to UART1 and then terminate. int row = running[high_priority]->id; int col = 1; char ch[PKTSZE] = {0x20, 0x30, 0x40, 0x50, 0x60}; int j = 0; // delay loop counter int i = 0; // process duration loop counter /* while(i < 10){ while(j < 1000000){ j++; } j = 0; uart_output_ch(row, col++, ch[0]++, 0); if (col > 80) col = 1; if (ch[0] > '9') ch[0] = '1'; i++; // increments the terminating loop counter } */ while(i < PKTSZE){ while(j < 1000000){ j++; } j = 0; uart_output_ch(row, col++, ch[i], 1); i++; // increments the terminating loop counter } p_terminate(); } void proc10() // During development this process acts primarily as a never ending process which prints 1s { int row = running[high_priority]->id; int col = 1; char ch[1] = "1"; int j = 0; // delay loop counter int i = 0; // process duration loop counter while(1){ while(i < 10){ while(j < 1000000){ j++; } j = 0; uart_output_ch(row, col++, ch[0]++, 0); if (col > 80) col = 1; if (ch[0] > '9') ch[0] = '1'; i++; // increments the terminating loop counter } p_nice(2); } } void time_server() // { } void monitor() // { //int k = 0;// output position increment counter loop counter int column = COL_ONE; int row = ROW_ONE; int incomingMsgSrc; // memory location on this processeses stack for incoming message source char incomingMsg[1]; // an a pointer to an array of 5 characters. memory location on this processeses stack for incoming message while(1){ /*-----------------------------------------------------------------------------*/ /* The following is an outline of the four arguments being received */ /* by this process from its queue. The four arguments are as follows */ /* */ /* arg 1: the message queue from which to receive our message */ /* arg 2: pointer to the location for the message source to be stored */ /* arg 3: pointer to the location for the message to be stored */ /* arg 4: the size of the message to be recieved */ /* / * note: the return value is TRUE if the msg was succesfully recvd */ /* and FALSE if the msg was not succesfully recvd */ /*------------------------------------------------------------------------------*/ while(!(p_recv(TO_MON, &incomingMsgSrc, incomingMsg, ONE_CHAR))); // we wait here until a message comes in from UART if(incomingMsg[0] == BACKSPACE){ uart_output_ch(row, column--, incomingMsg[0], 0); // delete the previously input character from the monitor } else uart_output_ch(row, column++, incomingMsg[0], 0); // outputs the input character to the monitor // uart_output_ch(row, column++, 'x'); // outputs the input character to the monitor if(column > 80){ // if our text reaches 80 characters, return the column to 1 and increment the row column = 1; row++; } } // end of while(1) container } void idle_proc() // currently is the get_id process { int i = 1; // loading bar count variable int j = 0; // delay loop counter while(1){ while(j < 100000){ j++; } if(i == 1){ uart_output_ch(ROW_ONE, 79, '\\', 0); } else if(i == 2){ uart_output_ch(ROW_ONE, 79, '|', 0); } else if(i == 3){ uart_output_ch(ROW_ONE, 79, '/', 0); } else if(i == 4){ uart_output_ch(ROW_ONE, 79, '-', 0); i = 0; // resets loading bar switch variable } i++; // increments loading symbol counter j = 0; // resets delay variable } } /* * * Process functions * */ /***************************************************************************************/ void pkcall(int code, void * structurePtr) { struct pkargs pka; pka.code = code; pka.ptr_to_structure = structurePtr; p_assignR7((unsigned long) &pka); SVC(); } int pkcall_with_return(int code, void * structurePtr) { struct pkargs pka; pka.code = code; pka.ptr_to_structure = structurePtr; p_assignR7((unsigned long) &pka); SVC(); return pka.rtnvalue; } /****************************************************************************************/ int p_get_id() { volatile int pkRtn; pkRtn = pkcall_with_return(GETID, NULL); // NULL because getid doesnt have any arguments in a structure or address to point at return pkRtn; } void p_terminate() { pkcall(TERMINATE, NULL); // NULL because terminate doesnt have any arguments in a structure or address to point at } void p_nice(int incr) { volatile int incrVal = incr; pkcall(NICE, &incrVal); } int p_bind(int index) // return value used as success or failure flag { volatile int pkRtn; volatile int indexVal = index; pkRtn = pkcall_with_return(BIND, &indexVal); return pkRtn; } int p_send(int to, int from, char * msg, int size){ volatile struct pkSend pk_send_args; /* Volatile to actually reserve space on stack*/ int pkRtn; // TRUE or FALSE depending on success (TRUE) or failure (FALSE) of send pk_send_args.to = to; // an integer value pk_send_args.from = from; // an integer value pk_send_args.msg = msg; // a character pointer to memory on the sending processes stack containing the message to send pk_send_args.size = size; // an integer value pkRtn = pkcall_with_return(SEND, &pk_send_args); // this function facilitates the sending and receiving of messages accross pkspace return pkRtn; // TRUE or FALSE depending on success (TRUE) or failure (FALSE) of send } int p_recv(int my_mailbox, int * from, char * msg, int sz){ volatile struct pkRecv pk_recv_args; /* Volatile to actually reserve space on stack*/ // send_msg('h', MONsrc, UARTq); int pkRtn; // TRUE or FALSE depending on success (TRUE) or failure (FALSE) of the receive call pk_recv_args.my_mailbox = my_mailbox; // an integer value pk_recv_args.from = from; // a character pointer to memory on the sending processes stack containing the message to send pk_recv_args.msg = msg; pk_recv_args.size = sz; pkRtn = pkcall_with_return(RECV, &pk_recv_args); return pkRtn; } int uart_output_ch(int row, int col, char ch, int xUARTnum) { /* Output a single character to specified screen position */ /* CUP (Cursor position) command plus character to display */ /* Assumes row and col are valid (1 through 24 and 1 through 80, respectively) */ struct CUPch uart_data; /* Since globals arenít permitted, this must be done each call */ uart_data . esc = ESC; uart_data . sqrbrkt = '['; uart_data . line[0] = '0' + row / 10; uart_data . line[1] = '0' + row % 10; uart_data . semicolon = ';'; uart_data . col[0] = '0' + col / 10; uart_data . col[1] = '0' + col % 10; uart_data . cmdchar = 'H'; uart_data . ch = ch; uart_data . UARTnum = xUARTnum; return pkcall_with_return(UART_OUT_CH, &uart_data); } void p_assignR7(volatile unsigned long data) { /* Assign 'data' to R7; since the first argument is R0, this is *simply a move from R0 to R7 */ __asm(" mov r7,r0"); } <file_sep>/* * MSGpasser.c * * Created on: Oct 12, 2018 * Author: NickB */ #include "MSGpasser.h" #include "ISRs.h" #include "menu.h" #include <string.h> struct message Queue[toMON_or_toUART][MAX_Q_SIZE]; // this matrix of structs is used in the message passer. first element indicates what Queue, seonds is the Queues size int front[NUM_OF_QUEUES] = {-1, -1}; // these are both arrays of two variables to indicae for which queue it is the front / rear. int rear[NUM_OF_QUEUES] = {-1, -1}; void send_msg(char msgData, int source, int outQueue) /* this is to put our message struct objects into the array of structs (our Queue)*/ { if(outQueue == UARTq && UartOutIdle == TRUE) // the uart is idle, send out the character! UART_sendChar(msgData); // forces the first character of our string out to the UART, thus passing control to the UART else{ // if it is busy, we will queue the data if( (front[outQueue] == rear[outQueue] + 1) || (front[outQueue] == 0 && rear[outQueue] == MAX_Q_SIZE-1)) // circular Q full conditional /* error handling q is full */; else{ if(front[outQueue] == -1) front[outQueue] = 0; rear[outQueue] = (rear[outQueue] + 1) % MAX_Q_SIZE; // circular q rear adjustment Queue[outQueue][rear[outQueue]].msg = msgData; // assign each individual component Queue[outQueue][rear[outQueue]].src = source; // ^^^^^^^^^^^^^^^^^^ } } } int rec_msg(char* d, int* s, int inQueue) { if(front[inQueue] == -1){ *d = 0; *s = EMPTY_FLAG; return FALSE; // this queue is empty } else{ *d = Queue[inQueue][front[inQueue]].msg; // extracting the data from the message *s = Queue[inQueue][front[inQueue]].src; if(front[inQueue] == rear[inQueue]){ front[inQueue] = -1; rear[inQueue] = -1; } // this is if that last message was the only message left in the queue, the queue gets reset to its empty state defaults else{ front[inQueue] = (front[inQueue] + 1) % MAX_Q_SIZE; // circular q front adjustment } return TRUE; // indicating we have a message -- enter the conditional and deal with it } } <file_sep>/* * kernelcalls.h * * Created on: Oct 20, 2018 * Author: NickB */ #ifndef KERNELCALLS_H_ #define KERNELCALLS_H_ typedef enum {GETID, NICE, TERMINATE, BIND, SEND, RECV, UART_OUT_CH} kernelcallcodes; /* * This structure is the shared memory between pspace and kspace */ struct pkargs { int code; unsigned int rtnvalue; void * ptr_to_structure; // this contains the message callers specific parameters (e.g. send has to from msg sz) }; /* * The following structure are pointed to by an sub data type within the above structure */ struct pkSend // a pointer to an element of this type exists within pkargs { int to; int from; char * msg; int size; }; struct pkRecv // a pointer to an element of this type exists within pkargs { int my_mailbox; int * from; char * msg; int size; }; struct CUPch { char esc; char sqrbrkt; char line[2]; /* 01 through 24 */ char semicolon; char col[2]; /* 01 through 80 */ char cmdchar; char ch; int UARTnum; }; #endif /* KERNELCALLS_H_ */ <file_sep>/* * SVC.c * * Created on: Oct 20, 2018 * Author: NickB */ #include <stdio.h> #include "kernel.h" #include "kernelcalls.h" #include "ISRs.h" #include "MSGpasser.h" //extern void systick_init(); void SVCall(void) { /* Supervisor call (trap) entry point * Using MSP - trapping process either MSP or PSP (specified in LR) * Source is specified in LR: F9 (MSP) or FD (PSP) * Save r4-r11 on trapping process stack (MSP or PSP) * Restore r4-r11 from trapping process stack to CPU * SVCHandler is called with r0 equal to MSP or PSP to access any arguments */ // send_msg('x', MONsrc, UARTq); // indicator that we are in the SVC call (debuging puerposes) /* Save LR for return via MSP or PSP */ __asm(" PUSH {LR}"); /* Trapping source: MSP or PSP? */ __asm(" TST LR,#4"); /* Bit #4 indicates MSP (0) or PSP (1) */ __asm(" BNE RtnViaPSP"); /* Trapping source is MSP - save r4-r11 on stack (default, so just push) */ __asm(" PUSH {r4-r11}"); __asm(" MRS r0,msp"); __asm(" BL SVCHandler"); /* r0 is MSP */ __asm(" POP {r4-r11}"); __asm(" POP {PC}"); /* Trapping source is PSP - save r4-r11 on psp stack (MSP is active stack) */ __asm("RtnViaPSP:"); __asm(" mrs r0,psp"); __asm(" stmdb r0!,{r4-r11}"); /* Store multiple, decrement before */ __asm(" msr psp,r0"); __asm(" BL SVCHandler"); /* r0 Is PSP */ /* Restore r4..r11 from trapping process stack */ __asm(" mrs r0,psp"); __asm(" ldmia r0!,{r4-r11}"); /* Load multiple, increment after */ __asm(" msr psp,r0"); __asm(" POP {PC}"); } void SVCHandler(struct stack_frame *argptr) { /* * Supervisor call handler * Handle startup of initial process * Handle all other SVCs such as getid, terminate, etc. * Assumes first call is from startup code * Argptr points to (i.e., has the value of) either: - the top of the MSP stack (startup initial process) - the top of the PSP stack (all subsequent calls) * Argptr points to the full stack consisting of both hardware and software register pushes (i.e., R0..xPSR and R4..R10); this is defined in type stack_frame * Argptr is actually R0 -- setup in SVCall(), above. * Since this has been called as a trap (Cortex exception), the code is in Handler mode and uses the MSP */ static int firstSVCcall = TRUE; struct pkargs *kcaptr; // points at our shared memory between p and k space struct pkSend *pkSptr; // points at the structure referred to in pkargs struct pkRecv *pkRptr; // points at the structure referred to in pkargs struct CUPch *pkUsend; // points at the structure referred to in pkargs if (firstSVCcall) { /* * Force a return using PSP * This will be the first process to run, so the eight "soft pulled" registers (R4..R11) must be ignored otherwise PSP will be pointing to the wrong location; the PSP should be pointing to the registers R0..xPSR, which will be "hard pulled"by the BX LR instruction. * To do this, it is necessary to ensure that the PSP points to (i.e., has) the address of R0; at this moment, it points to R4. * Since there are eight registers (R4..R11) to skip, the value of the sp should be increased by 8 * sizeof(unsigned int). * sp is increased because the stack runs from low to high memory. */ set_PSP((unsigned long)(running[high_priority] -> sp) + 8 * sizeof(unsigned int)); firstSVCcall = FALSE; /* Start SysTick */ /* Initialize SYSTICK */ SysTickPeriod(MAX_WAIT); SysTickIntEnable(); SysTickStart(); /* - Change the current LR to indicate return to Thread mode using the PSP - Assembler required to change LR to FFFF.FFFD (Thread/PSP) - BX LR loads PC from PSP stack (also, R0 through xPSR) - "hard pull" */ __asm(" movw LR,#0xFFFD"); /* Lower 16 [and clear top 16] */ __asm(" movt LR,#0xFFFF"); /* Upper 16 only */ __asm(" bx LR"); /* Force return to PSP */ } else /* Subsequent SVCs */ { /* * kcaptr points to the arguments associated with this kernel call * argptr is the value of the PSP (passed in R0 and pointing to the TOS) * the TOS is the complete stack_frame (R4-R10, R0-xPSR) * in this example, R7 contains the address of the structure supplied by the process - the structure is assumed to hold the arguments to the kernel function. * to get the address and store it in kcaptr, it is simply a matter of assigning the value of R7 (arptr -> r7) to kcaptr */ //#ifdef FOR_KERNEL_ARGS kcaptr = (struct pkargs *) argptr -> r7; switch(kcaptr -> code) { case GETID: kcaptr -> rtnvalue = running[high_priority]->id; break; case BIND: kcaptr -> rtnvalue = k_bind(*(int*)kcaptr -> ptr_to_structure); // this calls the bind function in kernel and returns TRUE for sucessful bind and FALSE for failed bind break; case NICE: k_nice(*(int*)kcaptr -> ptr_to_structure); break; case TERMINATE: k_terminater(); // this function will deallocate the stk and PCB break; case SEND: pkSptr = kcaptr -> ptr_to_structure; kcaptr -> rtnvalue = k_send(pkSptr->to, pkSptr->from, pkSptr->msg, pkSptr->size); // this function will facilitate the sending of messages; break; case RECV: pkRptr = kcaptr -> ptr_to_structure; kcaptr -> rtnvalue = k_recv(pkRptr->my_mailbox, pkRptr->from, pkRptr->msg, pkRptr->size); // this function will facilitate the receiving of messages break; case UART_OUT_CH: pkUsend = kcaptr -> ptr_to_structure; kcaptr -> rtnvalue = k_uart_organizer(pkUsend->ch, pkUsend->cmdchar, pkUsend->col[0], pkUsend->col[1], pkUsend->esc, pkUsend->line[0], pkUsend->line[1], pkUsend->semicolon, pkUsend->sqrbrkt, pkUsend->UARTnum); break; default: kcaptr -> rtnvalue = -1; } //#endif } } <file_sep>/* * MSGpasser.h * * Created on: Oct 12, 2018 * Author: NickB */ #ifndef MSGPASSER_H_ #define MSGPASSER_H_ #define MAX_Q_SIZE 4096 #define EMPTY_FLAG -1 #define MAX_ENTRIES 13 #define MONq 0 // these are used to indicate what Q to enter, or from where it has come #define UARTq 1 #define toMON_or_toUART 2 #define NUM_OF_QUEUES 2 /* this struct holds the message components, * including the source (UART or SYSCLCK) and the * data (char from user keystroke or time signal) */ struct message { char msg; /* letter/symbol or timing tick */ int src; /* UART or SYSTICK*/ }; void send_msg(char msgData, int source, int outQueue); int rec_msg(char* d, int* s, int inQueue); // this routine returns aa struct with the message information or 0 depending on if the //toMonitorQ (elevator Q) has a message or is empty #endif /* MSGPASSER_H_ */ <file_sep>/* * kernel.h * * Created on: Oct 12, 2018 * Author: NickB */ #ifndef KERNEL_H_ #define KERNEL_H_ void start(); #define TRUE 1 #define FALSE 0 #define PRIVATE static #define DISPLAYTBL_LEN1 63 #define DISPLAYTBL_LEN2 90 #define MAX_ENTRIES 13 // this is the number of different unique prcesses types in our table (proc1, proc2, proc3) #define MAX_MAILBOXES 16 // the max number of process mailboxes #define TO_TRAIN 13 // find a way to make this MAX_MAILBOXES - 3 rather than 7 #define TO_UART 14 // find a way to make this MAX_MAILBOXES - 2 rather than 8 #define TO_MON 15 // find a way to make this MAX_MAILBOXES - 1 rather than 9 #define ONE_CHAR 1 #define UART_SRC 0 #define PSTACKSZ 512 #define THUMBMODE 0x01000000 #define R0_OFFSET 8 #define PC_OFFSET 14 #define PSR_OFFSET 15 #define MAX_PRIORITIES 6 #define IDLE_PRIORITY 0 #define PRIORITY1 1 #define PRIORITY2 2 #define PRIORITY3 3 #define PRIORITY4 4 #define PRIORITY5 5 #define SVC() __asm(" SVC #0") #define disable() __asm(" cpsid i") #define enable() __asm(" cpsie i") #define MSP_RETURN 0xFFFFFFF9 //LR value: exception return using MSP as SP #define PSP_RETURN 0xFFFFFFFD //LR value: exception return using PSP as SP void set_LR(volatile unsigned long); unsigned long get_PSP(); void set_PSP(volatile unsigned long); unsigned long get_MSP(void); void set_MSP(volatile unsigned long); unsigned long get_SP(); void volatile save_registers(); void volatile restore_registers(); /* this struct holds the addresess of the function, the name of the function, and the number of chars in it's name */ struct fentry { void(*func)(); /* pointer to a function (process) */ // i think char * is ready for the argument char *name; /* text name associated with process */ int size; /* max number of chars in name*/ }; void reg_proc(char * prc, int pri, int pID); // prototype for function that calls the appropraite application process #define STACKSIZE 1024 /* Cortex default stack frame */ struct stack_frame { /* Registers saved by s/w (explicit) */ /* There is no actual need to reserve space for R4-R11, other than * for initialization purposes. Note that r0 is the h/w top-of-stack. */ unsigned long r4; unsigned long r5; unsigned long r6; unsigned long r7; unsigned long r8; unsigned long r9; unsigned long r10; unsigned long r11; /* Stacked by hardware (implicit)*/ unsigned long r0; unsigned long r1; unsigned long r2; unsigned long r3; unsigned long r12; unsigned long lr; unsigned long pc; unsigned long psr; }; /* Process control block */ struct pcb { /* Stack pointer - r13 (PSP) */ struct stack_frame *sp; /* Pointer to the original top of allocated stack (used when freeing memory)*/ unsigned long *top_of_stack; /* Processes ID */ int id; /* Links to adjacent PCBs */ struct pcb *next; struct pcb *prev; }; /* * * Message Passing Structures * * */ struct MQ_Item { char msg[256]; int * src; /* senders process id*/ int size; struct MQ_Item *next; }; struct MQ_List_Entry { struct MQ_Item *youngest; // indicates the last item in the message queue struct MQ_Item *oldest; // indicates the first item in the message queue int inUse; int owner; }; /* linked list stuff */ //actual linked list void createPCB(int whichPrc, int pr, int id); void addPCB(struct pcb*, int prio); void printList(void); //global variable extern struct pcb *running[MAX_PRIORITIES]; extern struct pcb *ll_head[MAX_PRIORITIES]; extern int high_priority; void k_terminater(); void k_nice(int new_priority); int k_bind(int indx); int k_send(int to_dst, int from, char * msg, int size); int k_recv(); int k_uart_organizer(char ch, char cmdchar, char col1, char col2, char esc, char line1, char line2, char semicolon, char sqrbrkt, int UARTnum); int k_uart_send(char output, int UARTnum); int k_uart_recv(char *d, int *s, int UARTnum); struct MQ_Item * MQmalloc(); void MQfree(struct MQ_Item * MQp); void createMQblocks(); // void init_MQ_list(); #endif /* KERNEL_H_ */ <file_sep>/* * menu.c * * Created on: Oct 12, 2018 * Author: NickB */ #include "menu.h" #include "MSGpasser.h" #include "ISRs.h" #include "kernel.h" #include "procs.h" #include <stdio.h> #include <math.h> #include <string.h> #include <ctype.h> #include <stdlib.h> void user_menu() { int i = 0; // indexes the string we're building to send to the parser int escapeCnt = 0; // used when ignoring escape keys send_msg('>', MONsrc, UARTq); int startFlag = FALSE; while(startFlag == FALSE){ // send_msg('.', MONsrc, UARTq); if (rec_msg(&data, &source, MONq)){ // this means 'if a message exists in the to monitor queue / the queue is not empty' b/c rec_msg returns a T/F flag send_msg(data, MONsrc, UARTq); // sends the users input key back to the screen via UART if(data == ESC || escapeCnt != 0 ){ // if an escape key is detected, the following two keys are ignored escapeCnt++; if(escapeCnt == 3) escapeCnt = 0; } else if(data == '\r'){ // if the enter key was pressed i=0; // resets our buffer string input = parser(str); // at this point the buffer command string is parsed if(strcmp(input.procName, "START") == 0) // checks to see if the user sent in the start command startFlag = TRUE; else if(strcmp(input.procName, "DISPLAY") == 0) // checks to see if the user sent in the start command show_reg_procs();// DISPLAY processes; else{ // reg_proc(input.procName, input.priority); // this function registers our requested processes // commented this out because 'too few arguments in fn call' send_msg('>', MONsrc, UARTq); } } else if(data == BACKSPACE){ // check for backspace str[--i] = '\0'; // if backspace detected, last entered character is removed from buffer string } else{ str[i++] = data; // places the new char in our buffer command string str[i] = '\0'; } } } } /* what will this functions * return value be fill in here */ /* this function parses through the incoming data separating it by delimiters (spaces) */ struct userinput parser(char Request[]){ char * procNum; // this is our users entered proccess name char * priorityVal; // this is the provided priority char * shouldntExist; // used in error cases char UPcmd[MAX_BUFFER_SIZE]; // uppercase command int i = 0; // used to convert entered commands to uppercase procNum = strtok(Request, " "); if(procNum != NULL){ priorityVal = strtok(NULL, " "); } if(priorityVal != NULL){ shouldntExist = strtok(NULL, " "); if(shouldntExist != NULL) ;// this is an error case, will probably have to send a '?' to the uart here ********************* } /* converts entered commands to upper case*/ while (i < strlen(procNum)){ UPcmd[i] = toupper(procNum[i]); i++; } i = 0; while(i < strlen(procNum)){ procNum[i] = UPcmd[i]; i++; } struct userinput UIrtrn = {procNum, priorityVal}; return UIrtrn; } void show_reg_procs(){ int i = 0; // facilitates sending the output string char displayStr[DISPLAYTBL_LEN1] = "\n\nProccess Name: ID: Allocated Stack Range:\n\n"; while(i < strlen(displayStr)){ send_msg(displayStr[i], MONsrc, UARTq); // sends message to the UART q from the MON src i++; } send_msg('>', MONsrc, UARTq); // gives out command promt symbol } <file_sep># Trainset ECED 4404 Assignment 3 <file_sep>/* * kernel.c * * Support kernel functions for process management * Remember: * - R0 is ARG1 * - R0 has function return value * Created on: Oct 12, 2018 * Author: NickB */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "procs.h" #include "kernel.h" #include "ISRs.h" #include "MSGpasser.h" /* * * * * * Globals * * * * * */ /* here is where the 3 different process table entries are built */ struct fentry flist[MAX_ENTRIES] = { {proc1, "P1", 8}, {proc2, "P2", 8}, {proc3, "P3", 8}, {proc4, "P4", 8}, {proc5, "P5", 8}, {proc6, "P6", 8}, {proc7, "P7", 8}, {proc8, "P8", 8}, {proc9, "P9", 8}, {proc10, "P10", 8},{time_server, "TS", 8}, {monitor, "MN", 8}, {idle_proc, "IDL", 8}}; //struct pcb *running = NULL; //struct pcb *ll_head = NULL; struct pcb *ll_head[MAX_PRIORITIES] = {NULL, NULL, NULL, NULL, NULL, NULL}; struct pcb *running[MAX_PRIORITIES] = {NULL, NULL, NULL, NULL, NULL, NULL}; int high_priority = 0; /* this is where the list of message queue information blocks (MQ_list_Entry) reside.All 'inUse' set = FALSE*/ //struct MQ_List_Entry MQ_list[MAX_MAILBOXES] = {{NULL, NULL, FALSE, -1}, {NULL, NULL, FALSE, -1}, {NULL, NULL, FALSE, -1}, {NULL, NULL, FALSE, -1}, {NULL, NULL, FALSE, -1}, {NULL, NULL, FALSE, -1}, {NULL, NULL, FALSE, -1}, {NULL, NULL, FALSE, -1}, {NULL, NULL, FALSE, -1}, {NULL, NULL, FALSE, -1},}; // this is our list of message queues. each queue can be bound to a specific process struct MQ_List_Entry MQ_list[MAX_MAILBOXES]; // instead of the above method, a function now initializes our values // by calling bind() struct MQ_Item * freeMQblock; // used in the meemory allocation of MQ message blocks int llCount = 0; // the number of items in our linked list (used for debugging purposes) /* * * reg_proc() and start() * * */ void reg_proc(char * prc, int pri, int pID){ // this is our argument) int j = 0; // used when searching unique processes table for matching name int i = 0; // used when outputting the matched process name char displayStr[23] = "\nProcess Registered..."; // sending in a '\n' here messes everything up with p1 int prcMatch = FALSE; // used as a flag to indicate if a correct process name was found while(j < MAX_ENTRIES){ if(strcmp(prc, flist[j].name) == 0){ prcMatch = TRUE; j = j + MAX_ENTRIES; // indicates to the while loop that we have found the right function and can leave } else j++; } j = j - MAX_ENTRIES; // returns j to the appropriate command table index // here we will either call the appropriate command, or output error '?' symbol if (prcMatch == FALSE){ ; } else { // at this point wehave a valid process name. this is where we will do reg proc stuff while(i < strlen(displayStr)){ // outputs "Process Registered..." // send_msg(displayStr[i], MONsrc, UARTq); // says yo we got it i++; } createPCB(j, pri, pID); // send in function pointer here } } void start(){ running[high_priority] = running[high_priority]->next; // shifts our running pcb to the right, meaning the first entered process is the first to run createMQblocks(); init_MQ_list(); // printList(); // here we will start the first process SVC(); } void createMQblocks(){ // allocates memory for the message blocks int i = 0; // loop counter // struct MQ_Item * freeMQblock; is defined as a global variable struct MQ_Item * prevMQblock; while(i < 256){ // we want to allocate memory for 256 message blocks freeMQblock = malloc(sizeof(struct MQ_List_Entry)); if(!i) // if the first memory allocation freeMQblock->next = NULL; // the end of the allocated memory blocks else freeMQblock->next = prevMQblock; // connecting the linked list prevMQblock = freeMQblock; i++; // increment while loop counter (so we have enough space for 256 messages stored at once) } } void init_MQ_list(){ int i = 0; // loop counter for initializing individual indexed list pointers while( i < (MAX_MAILBOXES - 3) ){ // minus 3 as the last two mailboxes will be reserved for the UART MQ_list[i].oldest = NULL; MQ_list[i].youngest = NULL; MQ_list[i].inUse = FALSE; MQ_list[i].owner = -1; // -1 is a default i++; } /* Initializing this to the Train output queue */ MQ_list[i].oldest = NULL; MQ_list[i].youngest = NULL; MQ_list[i].inUse = TRUE; MQ_list[i].owner = TO_TRAIN; /* Initializing the to monitor queue */ MQ_list[i].oldest = NULL; MQ_list[i].youngest = NULL; MQ_list[i].inUse = TRUE; MQ_list[i].owner = TO_UART; // reserved for sending messages to the monitor i++; // moving us to the last entry in MQ_list[i] MQ_list[i].oldest = NULL; MQ_list[i].youngest = NULL; MQ_list[i].inUse = TRUE; MQ_list[i].owner = TO_MON; // // reserved for sending messages to the monitor process from the UART } /* * * * * * * The following functions serve to create our PCBS and add them to our linked list * */ void createPCB(int whichPrc, int pr, int id) { unsigned long *stkTop; // points to the top of our new process stack struct stack_frame *newStk; // points to the top of our register and special reg stack frame in hi memory in our stack struct pcb *newPCB = (struct pcb *)malloc(sizeof(struct pcb)); // creates a pointer to out new PCB llCount++; stkTop = (unsigned long *)malloc(PSTACKSZ * sizeof(unsigned long)); // creates a pointer to the top of our new process stack of size PSTACKSZ // directs our new stack frame pointer (will be this PCBs PSP) to the appopriate spot in the code newStk = (struct stack_frame*)(stkTop + (PSTACKSZ - sizeof(struct stack_frame))); newStk->r0 = 0x00000000; // this needs to be initialized to zero newStk->pc = (unsigned long)flist[whichPrc].func; // assigns the entry point to the process newStk->psr = THUMBMODE; // indicates that the cortex is operating in thumb mode // newPCB->sp = (unsigned long)newStk; newPCB->sp = newStk; // now that sp is a pointer to stackframe, we don't need to cast newPCB->top_of_stack = stkTop; newPCB->id = id; newPCB->next = NULL; newPCB->prev = NULL; addPCB(newPCB, pr); } void addPCB(struct pcb *PCB, int prio) { if(prio > high_priority) high_priority = prio; //empty condition if (running[prio] == NULL) { running[prio] = PCB; running[prio]->next = running[prio] ->prev = running[prio]; ll_head[prio] = running[prio]; //printf("henlo\n"); } else { PCB->next = ll_head[prio]; PCB->prev = running[prio]; running[prio]->next = PCB; ll_head[prio]->prev = PCB; // running->prev= PCB; running[prio] = PCB; //printf("frenn\n"); } } /* * * * These are kernel functions that can be indirectly called within processes * see in SVCHandler for when they get called * */ void k_terminater() { // here we want to deallocate the stack and the pcb of the running process struct pcb *temp; if(running[high_priority]->next == running[high_priority]){ // check to see if this is the priorities last process being killed free(running[high_priority]->top_of_stack); free(running[high_priority]); running[high_priority] = NULL; } else{ // if its not the last priority, we'll need to fix the connection of the leftover adjacent nodes if(running[high_priority] != ll_head[high_priority]){ running[high_priority]->prev->next = running[high_priority]->next; running[high_priority]->next->prev = running[high_priority] ->prev; } else{ ll_head[high_priority]->prev->next = running[high_priority]->next; running[high_priority]->next->prev = ll_head[high_priority]->prev; ll_head[high_priority] = running[high_priority]->next; } free(running[high_priority]->top_of_stack); temp = running[high_priority]; running[high_priority] = temp->next; free(temp); } while(!running[high_priority]){ // if all processes at this priority have terminated, move down a priority until a non empty priority level is found high_priority--; } // we will set our new psp set_PSP((unsigned long)running[high_priority]->sp); // note: the registers are then restored in SVCall } void k_nice(int new_priority)// here is where we will remove the running PCB from the current priority linked list, and tack it onto the end of another list { int samePriority = 0; //trying to nice something to it's current priority - won't do anything if(high_priority == new_priority) samePriority = 1; struct pcb *temp; // used when fixing the connections of our linked lists if(!samePriority){ if(running[high_priority]->next == running[high_priority]){ //if last item //Reset the previously linked list contents and assign current running process the SP running[high_priority]-> next = running[high_priority]->prev = NULL; running[high_priority]->sp = (struct stack_frame*)get_PSP(); //Add the PCB to the new priority list addPCB(running[high_priority],new_priority); //list is empty - running points at NULL running[high_priority] = NULL; // we will then set our new psp while(!running[high_priority]) // if all processes at this priority have terminated, move down a priority until a non empty priority level is found high_priority--; set_PSP((unsigned long)running[high_priority]->sp); } else{ //Remove PCB from current priority queue if(running[high_priority] != ll_head[high_priority]){ // if its not the last element in this priority running[high_priority]->prev->next = running[high_priority]->next; running[high_priority]->next->prev = running[high_priority] ->prev; } else{ ll_head[high_priority]->prev->next = running[high_priority]->next; running[high_priority]->next->prev = ll_head[high_priority]->prev; ll_head[high_priority] = running[high_priority]->next; } if(high_priority >= new_priority) temp = running[high_priority] -> next; else temp = running[high_priority]; //Reset the previously linked list contents and assign current running process the SP running[high_priority]-> next = running[high_priority]->prev = NULL; running[high_priority]->sp = (struct stack_frame*)get_PSP(); //Add the PCB to the new priority list addPCB(running[high_priority],new_priority); //point to the next item - stored as temp running[high_priority] = temp; if(high_priority > new_priority) set_PSP((unsigned long)running[high_priority]->sp); free(temp); } } } int k_bind(int indx) { int succesfulBind; // succesful or unsucessful flag if(MQ_list[indx].inUse == FALSE){ // if the MQ_list MQ_list[indx].inUse = TRUE; MQ_list[indx].owner = running[high_priority]->id; succesfulBind = TRUE; // } else succesfulBind = FALSE;// we return an error (failed to bind flag) return succesfulBind; } /* * * * kernel-level message passing support routines * * */ int k_send(int to_dst, int from, char * msg, int size) { int succesfulSend; // dont actually initilize this to a value if(!MQ_list[to_dst].inUse){ // if the destination mailbox hasnt been binded to succesfulSend = FALSE; } else if(MQ_list[to_dst].owner != to_dst) // if the destination mailbox is owned by the wrong address // this is iffy reasoning figure it out succesfulSend = FALSE; else{ struct MQ_Item * MQ_Item_Ptr; // pointer to our new entry in the message queue char * k_msg_ptr; // points to the messsage in k_space char * p_msg_ptr; // points to the message in p_space int psz = size; // equal to the size sent in from p_space MQ_Item_Ptr = MQmalloc(); // null check MQ_Item_Ptr -> size = psz; // sets the size to the value sent from p_space p_msg_ptr = msg; k_msg_ptr = MQ_Item_Ptr -> msg; // now mem copy *pptr into *kptr memcpy(k_msg_ptr, p_msg_ptr, strlen(p_msg_ptr)); // SHOULD THIS STRLEN() BE PPTR OR KPTR //add MQ_Item_Ptr to list if(MQ_list[to_dst].youngest == NULL){ // if the list is empty MQ_Item_Ptr -> next = NULL; // our new youngests 'next pointer' will point to NULL //send_msg('h', MONsrc, UARTq); MQ_list[to_dst].youngest = MQ_Item_Ptr; MQ_list[to_dst].oldest = MQ_Item_Ptr; } else{ // if there are already waiting messages in the queue MQ_Item_Ptr -> next = NULL; // our new youngests 'next pointer' will point to NULL if(MQ_list[to_dst].youngest == MQ_list[to_dst].oldest){ // if there is only one message block in the list MQ_list[to_dst].oldest -> next = MQ_Item_Ptr; // our oldest 'next pointer' gets set to our new youngest message MQ_list[to_dst].youngest = MQ_Item_Ptr; // sets our new Item as the youngest } else{ // if there are at least 2 entries, the following linked list manipulation occurs MQ_list[to_dst].youngest -> next = MQ_Item_Ptr; // sets the old youngest next equal to our newest message block MQ_list[to_dst].youngest = MQ_Item_Ptr; // sets our new Item as the youngest } } } return succesfulSend; } int k_recv(int me, int * src, char * newMsg, int sz) { // UART_sendChar('u'); // char strA[10]; // char strB[10]; int succesfulRecv; // dont actually initilize this to a value if(MQ_list[me].owner == NULL){ succesfulRecv = FALSE;// if the calling processes mailbox hasnt been binded to } else if(MQ_list[me].owner != running[high_priority]->id && MQ_list[me].owner != TO_MON){ // the && MQ_list[me].owner != TO_MON is for the monitor case succesfulRecv = FALSE;// if the calling processes mailbox is improperly owned } else if(MQ_list[me].youngest == NULL){ // if the calling processes mailbox has no message waiting succesfulRecv = FALSE;// if the calling processes mailbox has no message waiting } else{ succesfulRecv = TRUE; char * k_msg_ptr; // points to the messsage in k_space char * p_msg_ptr; // points to the message in p_space int * k_msgSrc_ptr; int * p_msgSrc_ptr; struct MQ_Item * MQ_Item_Ptr; struct MQ_Item * temp; MQ_Item_Ptr = MQ_list[me].oldest; // our MQ_item_Ptr now points to the oldest message in the list -- which will be the message to be received by the caller p_msgSrc_ptr = src; // the pointer to the memory location in the callers stack where the source info will be stored k_msgSrc_ptr = MQ_Item_Ptr -> src; // the pointer to the memory location in the msp where the source of the received message is stored // now mem copy *p_msgSrc_ptr into *k_msgSrc_ptr // memcpy(p_msgSrc_ptr, k_msgSrc_ptr, strlen(k_msgSrc_ptr)); // SHOULD THIS STRLEN() BE PPTR OR KPTR // *p_msgSrc_ptr = *k_msgSrc_ptr; // not sure how to get this working p_msg_ptr = newMsg; k_msg_ptr = MQ_Item_Ptr -> msg; // now mem copy *p_msg_ptr into *k_msg_ptr memcpy(p_msg_ptr, k_msg_ptr, strlen(p_msg_ptr)); // SHOULD THIS STRLEN() BE PPTR OR KPTR //add MQ_Item_Ptr to list /* * * Have to set up for a case where the received message is the last message. (some queue stuff) * * */ if(MQ_list[me].oldest == MQ_list[me].youngest){ // if it is the last message in the queue MQfree(MQ_list[me].oldest); // free it MQ_list[me].oldest = NULL; // set the oldest/youngest pointers equal to NULL MQ_list[me].youngest = NULL; } else{ temp = MQ_list[me].oldest; MQ_list[me].oldest = MQ_list[me].oldest -> next; MQfree(temp); } } return succesfulRecv; } int k_uart_organizer(char ch, char cmdchar, char col1, char col2, char esc, char line1, char line2, char semicolon, char sqrbrkt, int UARTnum){ //int i = 0; // counter variable //char CUPandMSG[9] = {esc, sqrbrkt, line1, line2, semicolon, col1, col2, cmdchar, ch}; // creates a copy of our ch message locally (to be poined at) if(UARTnum == 0){ k_uart_send(esc,0); k_uart_send(sqrbrkt,0); k_uart_send(line1,0); k_uart_send(line2,0); k_uart_send(semicolon,0); k_uart_send(col1,0); k_uart_send(col2,0); k_uart_send(cmdchar,0); k_uart_send(ch,0); // ch } else if(UARTnum == 1){ k_uart_send(ch,1); // ch } /* while(i < 9){ k_uart_send(CUPandMSG[i]); i++; } i = 0; */ return 1; } int k_uart_send(char output, int UARTnum) { int i = 0; // counter variable int succesfulSend; // dont actually initilize this to a value char data = output; // if(UARTnum == 0){ if(UartOutIdle == TRUE){ // if the UART is not busy UART_sendChar(data); i++; succesfulSend = TRUE; } else{ // if the UART is busy, we will store the message and its poisitoin details in a linked list struct MQ_Item * MQ_Item_Ptr; // pointer to our new entry in the message queue char * k_msg_ptr; // points to the messsage in k_space char * p_msg_ptr; // points to the message in p_space // dont think we need this in this case as we have a copy of our ch int psz = ONE_CHAR; // equal to the size sent in from p_space MQ_Item_Ptr = MQmalloc(); // null check MQ_Item_Ptr -> size = psz; // sets the size to the value sent from p_space p_msg_ptr = &data; k_msg_ptr = MQ_Item_Ptr -> msg; // now mem copy *pptr into *kptr memcpy(k_msg_ptr, p_msg_ptr, strlen(p_msg_ptr)); // SHOULD THIS STRLEN() BE PPTR OR KPTR //add MQ_Item_Ptr to list if(MQ_list[TO_UART].youngest == NULL){ // if the list is empty MQ_Item_Ptr -> next = NULL; // our new youngests 'next pointer' will point to NULL //send_msg('h', MONsrc, UARTq); MQ_list[TO_UART].youngest = MQ_Item_Ptr; MQ_list[TO_UART].oldest = MQ_Item_Ptr; } else{ // if there are already waiting messages in the queue MQ_Item_Ptr -> next = NULL; // our new youngests 'next pointer' will point to NULL if(MQ_list[TO_UART].youngest == MQ_list[TO_UART].oldest){ // if there is only one message block in the list MQ_list[TO_UART].oldest -> next = MQ_Item_Ptr; // our oldest 'next pointer' gets set to our new youngest message MQ_list[TO_UART].youngest = MQ_Item_Ptr; // sets our new Item as the youngest } else{ // if there are at least 2 entries, the following linked list manipulation occurs MQ_list[TO_UART].youngest -> next = MQ_Item_Ptr; // sets the old youngest next equal to our newest message block MQ_list[TO_UART].youngest = MQ_Item_Ptr; // sets our new Item as the youngest } } } succesfulSend = TRUE; } else if(UARTnum == 1){ if(UartOutIdle == TRUE){ // if the UART is not busy UART_sendPacket(data); i++; succesfulSend = TRUE; } else{ // if the UART is busy, we will store the message and its poisitoin details in a linked list struct MQ_Item * MQ_Item_Ptr; // pointer to our new entry in the message queue char * k_msg_ptr; // points to the messsage in k_space char * p_msg_ptr; // points to the message in p_space // dont think we need this in this case as we have a copy of our ch int psz = ONE_CHAR; // equal to the size sent in from p_space MQ_Item_Ptr = MQmalloc(); // null check MQ_Item_Ptr -> size = psz; // sets the size to the value sent from p_space p_msg_ptr = &data; k_msg_ptr = MQ_Item_Ptr -> msg; // now mem copy *pptr into *kptr memcpy(k_msg_ptr, p_msg_ptr, strlen(p_msg_ptr)); // SHOULD THIS STRLEN() BE PPTR OR KPTR //add MQ_Item_Ptr to list if(MQ_list[TO_TRAIN].youngest == NULL){ // if the list is empty MQ_Item_Ptr -> next = NULL; // our new youngests 'next pointer' will point to NULL //send_msg('h', MONsrc, UARTq); MQ_list[TO_TRAIN].youngest = MQ_Item_Ptr; MQ_list[TO_TRAIN].oldest = MQ_Item_Ptr; } else{ // if there are already waiting messages in the queue MQ_Item_Ptr -> next = NULL; // our new youngests 'next pointer' will point to NULL if(MQ_list[TO_TRAIN].youngest == MQ_list[TO_TRAIN].oldest){ // if there is only one message block in the list MQ_list[TO_TRAIN].oldest -> next = MQ_Item_Ptr; // our oldest 'next pointer' gets set to our new youngest message MQ_list[TO_TRAIN].youngest = MQ_Item_Ptr; // sets our new Item as the youngest } else{ // if there are at least 2 entries, the following linked list manipulation occurs MQ_list[TO_TRAIN].youngest -> next = MQ_Item_Ptr; // sets the old youngest next equal to our newest message block MQ_list[TO_TRAIN].youngest = MQ_Item_Ptr; // sets our new Item as the youngest } } } } return succesfulSend; } int k_uart_recv(char* d, int* s, int UARTnum) { int succesfulRecv; // dont actually initilize this to a value if(UARTnum == 0) { if(MQ_list[TO_UART].youngest == NULL){ // if the calling processes mailbox has no message waiting succesfulRecv = FALSE;// if the calling processes mailbox has no message waiting } else{ succesfulRecv = TRUE; char * k_msg_ptr; // points to the messsage in k_space char * p_msg_ptr; // points to the message in p_space struct MQ_Item * MQ_Item_Ptr; struct MQ_Item * temp; MQ_Item_Ptr = MQ_list[TO_UART].oldest; // our MQ_item_Ptr now points to the oldest message in the list -- which will be the message to be received by the caller *d = *(MQ_Item_Ptr -> msg); // not sure how to get this working //add MQ_Item_Ptr to list /* * * Have to set up for a case where the received message is the last message. (some queue stuff) * * */ if(MQ_list[TO_UART].oldest == MQ_list[TO_UART].youngest){ // if it is the last message in the queue MQfree(MQ_list[TO_UART].oldest); // free it MQ_list[TO_UART].oldest = NULL; // set the oldest/youngest pointers equal to NULL MQ_list[TO_UART].youngest = NULL; } else{ // if there are more messages in the queue temp = MQ_list[TO_UART].oldest; MQ_list[TO_UART].oldest = MQ_list[TO_UART].oldest -> next; MQfree(temp); } } } else if(UARTnum == 1) { if(MQ_list[TO_TRAIN].youngest == NULL){ // if the calling processes mailbox has no message waiting succesfulRecv = FALSE;// if the calling processes mailbox has no message waiting } else{ succesfulRecv = TRUE; char * k_msg_ptr; // points to the messsage in k_space char * p_msg_ptr; // points to the message in p_space struct MQ_Item * MQ_Item_Ptr; struct MQ_Item * temp; MQ_Item_Ptr = MQ_list[TO_TRAIN].oldest; // our MQ_item_Ptr now points to the oldest message in the list -- which will be the message to be received by the caller *d = *(MQ_Item_Ptr -> msg); // not sure how to get this working //add MQ_Item_Ptr to list /* * * Have to set up for a case where the received message is the last message. (some queue stuff) * * */ if(MQ_list[TO_TRAIN].oldest == MQ_list[TO_TRAIN].youngest){ // if it is the last message in the queue MQfree(MQ_list[TO_TRAIN].oldest); // free it MQ_list[TO_TRAIN].oldest = NULL; // set the oldest/youngest pointers equal to NULL MQ_list[TO_TRAIN].youngest = NULL; } else{ // if there are more messages in the queue temp = MQ_list[TO_TRAIN].oldest; MQ_list[TO_TRAIN].oldest = MQ_list[TO_TRAIN].oldest -> next; MQfree(temp); } } } return succesfulRecv; } struct MQ_Item * MQmalloc(){ struct MQ_Item * MQp = freeMQblock; freeMQblock = freeMQblock->next; return MQp; } void MQfree(struct MQ_Item * MQp){ MQp->next = freeMQblock; freeMQblock = MQp; } /* * * * * The following functions are our processes context switching function * these were provided to us by * * * */ unsigned long get_PSP(void) { /* Returns contents of PSP (current process stack */ __asm(" mrs r0, psp"); __asm(" bx lr"); return 0; /***** Not executed -- shuts compiler up */ /***** If used, will clobber 'r0' */ } unsigned long get_MSP(void) { /* Returns contents of MSP (main stack) */ __asm(" mrs r0, msp"); __asm(" bx lr"); return 0; } void set_PSP(volatile unsigned long ProcessStack) { /* set PSP to ProcessStack */ __asm(" msr psp, r0"); } void set_MSP(volatile unsigned long MainStack) { /* Set MSP to MainStack */ __asm(" msr msp, r0"); } void volatile save_registers() { /* Save r4..r11 on process stack */ __asm(" mrs r0,psp"); /* Store multiple, decrement before; '!' - update R0 after each store */ __asm(" stmdb r0!,{r4-r11}"); __asm(" msr psp,r0"); } void volatile restore_registers() { /* Restore r4..r11 from stack to CPU */ __asm(" mrs r0,psp"); /* Load multiple, increment after; '!' - update R0 */ __asm(" ldmia r0!,{r4-r11}"); __asm(" msr psp,r0"); } unsigned long get_SP() { /**** Leading space required -- for label ****/ __asm(" mov r0,SP"); __asm(" bx lr"); return 0; } /* * * functions that are used for debugging purposes * */ void printList(void) // out of date, has not been update to handle priority list { /* int i = 0; // facilitates sending the output strings int k = 0; // facilitates moving to the next PCB char strA [300]; char strB [200]; while (k < llCount) { unsigned long r0_ptr = ((unsigned long)running->sp + (unsigned long)(R0_OFFSET * sizeof(unsigned long))); // this points to our r0 location in memory unsigned long pc_ptr = ((unsigned long)running->sp + (unsigned long)(PC_OFFSET * sizeof(unsigned long))); // this points to our pc location in memory unsigned long psr_ptr = ((unsigned long)running->sp + (unsigned long)(PSR_OFFSET * sizeof(unsigned long))); // this points to our psr location in memory struct stack_frame *spp = (running->sp); // this points to the running processes stack_fram struct sprintf(strA, "\n\n---------------------\n\nLinked List Entry: %d\nProcess ID: %d\n\nreg @ mem loc = value", k+1, running->id); sprintf(strB, "\n\nr0 @ %u = %u \npc @ %u = %u \npsr @ %u = %u", r0_ptr, (unsigned long)spp->r0, pc_ptr, (unsigned long)spp->pc, psr_ptr, (unsigned long)spp->psr ); while(i < strlen(strA)){ send_msg(strA[i], MONsrc, UARTq); // sends the process title string i++; } i = 0; while(i < strlen(strB)){ send_msg(strB[i], MONsrc, UARTq); // sends the registers and their values i++; } i = 0; running = running->next; // prints out our first one first k++; } */ } <file_sep> /** * main.c */ #define MAX_ENTRIES 13 #include <stdio.h> #include <string.h> #include "ISRs.h" #include "MSGpasser.h" #include "menu.h" #include "kernel.h" /* Software Functionality Use Cases. Uncomment demonstration to run */ //#define PRIORITY_NICE_DEMO 1 //#define MULTI_PROC_DEMO 2 //#define MSG_PASS_DEMO 3 //#define IO_DEMO 4 //#define IDLE_PROC_DEMO 5 #define TRAIN_PROC_DEMO 6 //#define CUP_DEMO 7 // global variable to count number of interrupts on PORTF0 (falling edge) volatile int count = 0; int main(void) { /* Initialize UART0 */ UART0_Init(); // Initialize UART0 InterruptEnable(INT_VEC_UART0); // Enable UART0 interrupts UART0_IntEnable(UART_INT_RX | UART_INT_TX); // Enable Receive and Transmit interrupts /* Initialize UART1 */ UART1_Init(); //Initialize UART1 InterruptEnable(INT_VEC_UART1); //Enable UART1 interrupts UART1_IntEnable(UART_INT_RX | UART_INT_TX); //Enable Receive and Transmit interrupts /*Systick Enable*/ SysTickPeriod(MAX_WAIT); SysTickIntEnable(); SysTickStart(); InterruptMasterEnable(); // Enable Master (CPU) Interrupts // user_menu(); // this is where the user can enter their processes in a menu. reg_proc() is contained in this function /* PRIORITY_NICE_DEMO */ #ifdef PRIORITY_NICE_DEMO reg_proc("P3", PRIORITY3, 3); // reg_proc("P6", PRIORITY2, 6); // reg_proc("P7", PRIORITY2, 7); // reg_proc("P10", PRIORITY4, 10); /* an ide process which prints out idle ... forever*/ reg_proc("IDL", IDLE_PRIORITY, 4); #endif /* MULTI_PROC_DEMO */ #ifdef MULTI_PROC_DEMO reg_proc("P6", PRIORITY1, 6); // reg_proc("P7", PRIORITY1, 7); // reg_proc("P8", PRIORITY1, 8); // /* an ide process which prints out idle ... forever*/ reg_proc("IDL", IDLE_PRIORITY, 4); #endif /* MSG_PASS_DEMO */ #ifdef MSG_PASS_DEMO reg_proc("P2", PRIORITY1, 2); // this is acting as a receiveing processes reg_proc("P1", PRIORITY1, 1); // this processes is sending reg_proc("P4", PRIORITY1, 4); // this processes is sending /* an ide process which prints out idle ... forever*/ reg_proc("IDL", IDLE_PRIORITY, 4); #endif /* IO_DEMO */ #ifdef IO_DEMO reg_proc("MN", PRIORITY1, 14); // this is acting as a receiveing processes ( 9 in the process id which matches the TO_UART index) /* an ide process which prints out idle ... forever*/ reg_proc("IDL", IDLE_PRIORITY, 4); #endif /* IDLE_PROC_DEMO */ #ifdef IDLE_PROC_DEMO reg_proc("P9", PRIORITY1, 9); // this is acting as a receiveing processes /* an ide process which prints out idle ... forever*/ reg_proc("IDL", IDLE_PRIORITY, 4); #endif /* TRAIN_PROC_DEMO */ #ifdef TRAIN_PROC_DEMO reg_proc("P9", PRIORITY1, 9); // this is acting as a receiveing processes /* an ide process which prints out idle ... forever*/ reg_proc("IDL", IDLE_PRIORITY, 4); #endif /* CUP_DEMO */ #ifdef CUP_DEMO reg_proc("P5", PRIORITY1, 5); // this is acting as a receiveing processes ( 9 in the process id which matches the TO_UART index) /* an ide process which prints out idle ... forever*/ reg_proc("IDL", IDLE_PRIORITY, 4); #endif start(); // this will start the processes and run them. the kernel is also where other stuff will happen return 0; } <file_sep>/* * menu.h * * Created on: Oct 12, 2018 * Author: NickB */ #ifndef MENU_H_ #define MENU_H_ #define EMPTY_FLAG -1 #define MAX_OUT_STR_LEN 17 #define MAX_BUFFER_SIZE 80 #define DISPLAYTBL_LEN1 63 #define TRUE 1 #define FALSE 0 #define NUL '\0' #define UARTsrc 1 #define CLOCKsrc 2 #define MONq 0 // these are used to indicate what Q to enter #define UARTq 1 #define MONsrc 3 //#define BACKSPACE 0x7f #define ESC 27 #define STARTFLAG -1 void user_menu(); char str[MAX_BUFFER_SIZE]; // this is the buffer string holding the incoming characters from the uart once offloaded from the queue char outStr[MAX_OUT_STR_LEN]; // this is the string that holds the output from the application layer // this struct holds the command and the argument of the users input struct userinput { char * procName; // this is our first command char * priority; // this is our argument }; char data; // memory locations sent to rec message by reference int source; struct userinput input; // this struct object is used in monitor. // the return value of parser is 'input', and input will be sent to command finder to call the appropriate processes /*this prototype is for the parse that tokenizes our command and argument, and attempts to identify it, the type is userinput*/ struct userinput parser(char Request[]); void reg_proc(char * prc, int pri, int prID); // prototype for function that calls the appropraite application process void show_reg_procs(); #endif /* MENU_H_ */ <file_sep>/* * ISRs.c * * Created on: Oct 12, 2018 * Author: NickB */ /* * ISRoutines.c * * Created on: Sep 11, 2018 * Author: NickB */ #include "ISRs.h" #include "MSGpasser.h" #include "kernel.h" #include <string.h> int UartOutIdle = TRUE; // memory location for Uart idle status void UART0_Init(void) { volatile int wait; /* Initialize UART0 */ SYSCTL_RCGCGPIO_R |= SYSCTL_RCGCUART_GPIOA; // Enable Clock Gating for UART0 SYSCTL_RCGCUART_R |= SYSCTL_RCGCGPIO_UART0; // Enable Clock Gating for PORTA wait = 0; // give time for the clocks to activate UART0_CTL_R &= ~UART_CTL_UARTEN; // Disable the UART wait = 0; // wait required before accessing the UART config regs // Setup the BAUD rate UART0_IBRD_R = 8; // IBRD = int(16,000,000 / (16 * 115,200)) = 8.680555555555556 UART0_FBRD_R = 44; // FBRD = int(.680555555555556 * 64 + 0.5) = 44.05555555555556 UART0_LCRH_R = (UART_LCRH_WLEN_8); // WLEN: 8, no parity, one stop bit, without FIFOs) GPIO_PORTA_AFSEL_R = 0x3; // Enable Receive and Transmit on PA1-0 GPIO_PORTA_PCTL_R = (0x01) | ((0x01) << 4); // Enable UART RX/TX pins on PA1-0 GPIO_PORTA_DEN_R = EN_DIG_PA0 | EN_DIG_PA1; // Enable Digital I/O on PA1-0 UART0_CTL_R = UART_CTL_UARTEN; // Enable the UART wait = 0; // wait; give UART time to enable itself. } void UART1_Init(void){ volatile int wait; /* Initialize UART0 */ SYSCTL_RCGCGPIO_R |= SYSCTL_RCGCUART_GPIOB; // Enable Clock Gating for UART0 SYSCTL_RCGCUART_R |= SYSCTL_RCGCGPIO_UART1; // Enable Clock Gating for PORTA wait = 0; // give time for the clocks to activate UART1_CTL_R &= ~UART_CTL_UARTEN; // Disable the UART1 wait = 0; // wait required before accessing the UART config regs // Setup the BAUD rate UART1_IBRD_R = 8; // IBRD = int(16,000,000 / (16 * 115,200)) = 8.680555555555556 UART1_FBRD_R = 44; // FBRD = int(.680555555555556 * 64 + 0.5) = 44.05555555555556 UART1_LCRH_R = (UART_LCRH_WLEN_8); // WLEN: 8, no parity, one stop bit, without FIFOs) GPIO_PORTB_AFSEL_R = 0x3; // Enable Receive and Transmit on PA1-0 GPIO_PORTB_PCTL_R = (0x01) | ((0x01) << 4); // Enable UART RX/TX pins on PA1-0 // GPIO_PORTB_DEN_R = EN_DIG_PB0 | EN_DIG_PB1; // Enable Digital I/O on PA1-0 UART1_CTL_R = UART_CTL_UARTEN; // Enable the UART wait = 0; // wait; give UART time to enable itself. } void InterruptEnable(unsigned long InterruptIndex) { /* Indicate to CPU which device is to interrupt */ if(InterruptIndex < 32) NVIC_EN0_R = 1 << InterruptIndex; // Enable the interrupt in the EN0 Register else NVIC_EN1_R = 1 << (InterruptIndex - 32); // Enable the interrupt in the EN1 Register } void UART0_IntEnable(unsigned long flags) { /* Set specified bits for interrupt */ UART0_IM_R |= flags; } void UART1_IntEnable(unsigned long flags) { /*Set specified bits for interrupt */ UART1_IM_R |= flags; } void UART0_IntHandler(void) { /* * Simplified UART ISR - handles receive and xmit interrupts * Application signalled when data received */ if (UART0_MIS_R & UART_INT_RX) { /* RECV done - clear interrupt and make char available to application */ UART0_ICR_R |= UART_INT_RX; Data = UART0_DR_R; data_ptr = &Data; // here we assign a ptr to our data value as our k_send function requires a char pointer as a parameter /* going to want to enqueue data into a FIFO queue */ /* this will be done by calling a function like 'send_msg()'*/ k_send(TO_MON, UART_SRC, data_ptr, ONE_CHAR); } if (UART0_MIS_R & UART_INT_TX) { /* XMIT done - clear interrupt */ UART0_ICR_R |= UART_INT_TX; /*-----------------------------------------------------------------------------*/ /* The following is an outline of the four arguments being received */ /* by this process from its queue. The four arguments are as follows */ /* */ /* arg 1: the message queue from which to receive our message */ /* arg 2: pointer to the location for the message source to be stored */ /* (not needed in this scope) */ /* arg 3: pointer to the location for the message to be stored */ /* arg 4: the size of the message to be recieved */ /* */ /* note: the return value is TRUE if the msg was succesfully recvd */ /* and FALSE if the msg was not succesfully recvd */ /*------------------------------------------------------------------------------*/ // this is the new way if(k_uart_recv(&dta, &src, 0)){ // this checks to see if there's anything waiting for us in the to UART queue /* this is where we will use all the information about position to output the character to the correct place on the screen*/ UART0_DR_R = dta; } else{ UartOutIdle = TRUE; } } } void UART1_IntHandler(void) { /* * Simplified UART1 ISR - handles receive and xmit interrupts * Application signalled when data received */ if (UART1_MIS_R & UART_INT_RX) { /* RECV done - clear interrupt and make char available to application */ UART1_ICR_R |= UART_INT_RX; Data = UART1_DR_R; data_ptr = &Data; // here we assign a ptr to our data value as our k_send function requires a char pointer as a parameter /* going to want to enqueue data into a FIFO queue */ /* this will be done by calling a function like 'send_msg()'*/ k_send(TO_MON, UART_SRC, data_ptr, ONE_CHAR); } if (UART1_MIS_R & UART_INT_TX) { /* XMIT done - clear interrupt */ UART1_ICR_R |= UART_INT_TX; /*-----------------------------------------------------------------------------*/ /* The following is an outline of the four arguments being received */ /* by this process from its queue. The four arguments are as follows */ /* */ /* arg 1: the message queue from which to receive our message */ /* arg 2: pointer to the location for the message source to be stored */ /* (not needed in this scope) */ /* arg 3: pointer to the location for the message to be stored */ /* arg 4: the size of the message to be recieved */ /* */ /* note: the return value is TRUE if the msg was succesfully recvd */ /* and FALSE if the msg was not succesfully recvd */ /*------------------------------------------------------------------------------*/ // this is the new way if(k_uart_recv(&dta, &src, 1)){ // this checks to see if there's anything waiting for us in the to UART queue /* this is where we will use all the information about position to output the character to the correct place on the screen*/ UART1_DR_R = dta; } else{ UartOutIdle = TRUE; } } } void UART_sendChar(char CharToUart) { UART0_DR_R = CharToUart; UartOutIdle = FALSE; } void UART_sendPacket(char CharToTrain) { UART1_DR_R = CharToTrain; UartOutIdle = FALSE; } void InterruptMasterEnable(void) { /* enable CPU interrupts */ __asm(" cpsie i"); } /* SYSTICK */ void SysTickStart(void) { // Set the clock source to internal and enable the counter to interrupt ST_CTRL_R |= ST_CTRL_CLK_SRC | ST_CTRL_ENABLE; } void SysTickStop(void) { // Clear the enable bit to stop the counter ST_CTRL_R &= ~(ST_CTRL_ENABLE); } void SysTickPeriod(unsigned long Period) { /* For an interrupt, must be between 2 and 16777216 (0x100.0000 or 2^24) */ ST_RELOAD_R = Period - 1; /* 1 to 0xff.ffff */ } void SysTickIntEnable(void) { // Set the interrupt bit in STCTRL ST_CTRL_R |= ST_CTRL_INTEN; } void SysTickIntDisable(void) { // Clear the interrupt bit in STCTRL ST_CTRL_R &= ~(ST_CTRL_INTEN); } void SysTickHandler(void) { // unsigned long *nextStkPtr; // points to the top of our new process stack //struct stack_frame *nextStk; // points to the top of our register and special reg stack frame in hi memory in our stack // first we need to save the register save_registers(); //next we will put our currently running process in the appchange our stack pointer running[high_priority]->sp = (struct stack_frame*)get_PSP(); //now moving the running pointer to the next PCB running[high_priority] = running[high_priority]->next; // we will set our new psp set_PSP((unsigned long)running[high_priority]->sp); //finally lets restore our registers restore_registers(); } <file_sep>/* * procs.h * * Created on: Oct 12, 2018 * Author: NickB */ #ifndef PROCS_H_ #define PROCS_H_ #define PROC1_DST 1 // these definitions are used when developing message passing #define PROC2_DST 2 #define PROC1_SRC 10 #define PROC2_SRC 20 #define ESC 27 #define COL_ONE 1 #define ROW_ONE 1 #define BACKSPACE 0x7f #define DEMO_MSG_SIZE 5 // process prototypes void proc1(); void proc2(); void proc3(); void proc4(); void proc5(); void proc6(); void proc7(); void proc8(); void proc9(); void proc10(); void time_server(); // void monitor(); // void idle_proc(); // functions void pkcall(int code, void * structurePtr); // used to handle pkcalls with no returns int pkcall_with_return(int code, void * structurePtr); // used to handle pkcalls with returns int p_get_id(); // return value is the id void p_terminate(); void p_nice(int incr); int p_bind(int index); // return value is TRUE for succesful bind and FALSE for unsuccesful bind int p_send(int to, int from, char * msg, int size); int p_recv(int my_mailbox, int * from, char * msg, int sz); int uart_output_ch(int row, int col, char ch, int UARTnum); void p_assignR7(volatile unsigned long data); #endif /* PROCS_H_ */ <file_sep>/* * ISRs.h * * Created on: Oct 12, 2018 * Author: NickB */ #ifndef ISRS_H_ #define ISRS_H_ /* UART */ void UART0_Init(void); void UART0_IntEnable(unsigned long flags); void UART0_IntHandler(void); void UART1_Init(void); void UART1_IntEnable(unsigned long flags); void UART1_IntHandler(void); void InterruptEnable(unsigned long InterruptIndex); void InterruptMasterEnable(void); void UART_sendChar(char CharToUart); // facilitates sending characters to the UART device // UART0 & PORTA Registers #define GPIO_PORTA_AFSEL_R (*((volatile unsigned long *)0x40058420)) // GPIOA Alternate Function Select Register #define GPIO_PORTA_DEN_R (*((volatile unsigned long *)0x4005851C)) // GPIOA Digital Enable Register #define GPIO_PORTA_PCTL_R (*((volatile unsigned long *)0x4005852C)) // GPIOA Port Control Register #define UART0_DR_R (*((volatile unsigned long *)0x4000C000)) // UART0 Data Register #define UART0_FR_R (*((volatile unsigned long *)0x4000C018)) // UART0 Flag Register #define UART0_IBRD_R (*((volatile unsigned long *)0x4000C024)) // UART0 Integer Baud-Rate Divisor Register #define UART0_FBRD_R (*((volatile unsigned long *)0x4000C028)) // UART0 Fractional Baud-Rate Divisor Register #define UART0_LCRH_R (*((volatile unsigned long *)0x4000C02C)) // UART0 Line Control Register #define UART0_CTL_R (*((volatile unsigned long *)0x4000C030)) // UART0 Control Register #define UART0_IFLS_R (*((volatile unsigned long *)0x4000C034)) // UART0 Interrupt FIFO Level Select Register #define UART0_IM_R (*((volatile unsigned long *)0x4000C038)) // UART0 Interrupt Mask Register #define UART0_MIS_R (*((volatile unsigned long *)0x4000C040)) // UART0 Masked Interrupt Status Register #define UART0_ICR_R (*((volatile unsigned long *)0x4000C044)) // UART0 Interrupt Clear Register #define UART0_CC_R (*((volatile unsigned long *)0x4000CFC8)) // UART0 Clock Control Register // UART1 & PORTB Registers #define GPIO_PORTB_AFSEL_R (*((volatile unsigned long *)0x40059420)) // GPIOB Alternate Function Select Register #define GPIO_PORTB_DEN_R (*((volatile unsigned long *)0x4005952C)) // GPIOB Digital Enable Register #define GPIO_PORTB_PCTL_R (*((volatile unsigned long *)0x4005951C)) // GPIOB Port Control Register #define UART1_DR_R (*((volatile unsigned long *)0x4000D000)) // UART1 Data Register #define UART1_FR_R (*((volatile unsigned long *)0x4000D018)) // UART1 Flag Register #define UART1_IBRD_R (*((volatile unsigned long *)0x4000D024)) // UART1 Integer Baud-Rate Divisor Register #define UART1_FBRD_R (*((volatile unsigned long *)0x4000D028)) // UART1 Fractional Baud-Rate Divisor Register #define UART1_LCRH_R (*((volatile unsigned long *)0x4000D02C)) // UART1 Line Control Register #define UART1_CTL_R (*((volatile unsigned long *)0x4000D030)) // UART1 Control Register #define UART1_IFLS_R (*((volatile unsigned long *)0x4000D034)) // UART1 Interrupt FIFO Level Select Register #define UART1_IM_R (*((volatile unsigned long *)0x4000D038)) // UART1 Interrupt Mask Register #define UART1_MIS_R (*((volatile unsigned long *)0x4000D040)) // UART1 Masked Interrupt Status Register #define UART1_ICR_R (*((volatile unsigned long *)0x4000D044)) // UART1 Interrupt Clear Register #define UART1_CC_R (*((volatile unsigned long *)0x4000DFC8)) // UART1 Clock Control Register #define INT_VEC_UART0 5 // UART0 Rx and Tx interrupt index (decimal) #define INT_VEC_UART1 6 // UART1 Rx and TX interrupt index (decimal) #define UART_FR_TXFF 0x00000020 // UART Transmit FIFO Full #define UART_FR_RXFE 0x00000010 // UART Receive FIFO Empty #define UART_RX_FIFO_ONE_EIGHT 0x00000038 // UART Receive FIFO Interrupt Level at >= 1/8 #define UART_TX_FIFO_SVN_EIGHT 0x00000007 // UART Transmit FIFO Interrupt Level at <= 7/8 #define UART_LCRH_WLEN_8 0x00000060 // 8 bit word length #define UART_LCRH_FEN 0x00000010 // UART Enable FIFOs #define UART_CTL_UARTEN 0x00000301 // UART RX/TX Enable #define UART_INT_TX 0x020 // Transmit Interrupt Mask #define UART_INT_RX 0x010 // Receive Interrupt Mask #define UART_INT_RT 0x040 // Receive Timeout Interrupt Mask #define UART_CTL_EOT 0x00000010 // UART End of Transmission Enable #define EN_RX_PA0 0x00000001 // Enable Receive Function on PA0 #define EN_TX_PA1 0x00000002 // Enable Transmit Function on PA1 #define EN_DIG_PA0 0x00000001 // Enable Digital I/O on PA0 #define EN_DIG_PA1 0x00000002 // Enable Digital I/O on PA1 // Clock Gating Registers #define SYSCTL_RCGCGPIO_R (*((volatile unsigned long *)0x400FE608)) #define SYSCTL_RCGCUART_R (*((volatile unsigned long *)0x400FE618)) //UART0 #define SYSCTL_RCGCGPIO_UART0 0x00000001 // UART0 Clock Gating Control #define SYSCTL_RCGCUART_GPIOA 0x00000001 // Port A Clock Gating Control //UART1 #define SYSCTL_RCGCGPIO_UART1 0x00000002 // UART1 Clock Gating Control #define SYSCTL_RCGCUART_GPIOB 0x00000002 // Port B Clock Gating Control // Clock Configuration Register #define SYSCTRL_RCC_R (*((volatile unsigned long *)0x400FE0B0)) #define CLEAR_USRSYSDIV 0xF83FFFFF // Clear USRSYSDIV Bits #define SET_BYPASS 0x00000800 // Set BYPASS Bit #define NVIC_EN0_R (*((volatile unsigned long *)0xE000E100)) // Interrupt 0-31 Set Enable Register #define NVIC_EN1_R (*((volatile unsigned long *)0xE000E104)) // Interrupt 32-54 Set Enable Register #define TRUE 1 #define FALSE 0 #define BLANK_MSG 0 // SysTick Registers // SysTick Control and Status Register (STCTRL) #define ST_CTRL_R (*((volatile unsigned long *)0xE000E010)) // Systick Reload Value Register (STRELOAD) #define ST_RELOAD_R (*((volatile unsigned long *)0xE000E014)) // SysTick defines #define ST_CTRL_COUNT 0x00010000 // Count Flag for STCTRL #define ST_CTRL_CLK_SRC 0x00000004 // Clock Source for STCTRL #define ST_CTRL_INTEN 0x00000002 // Interrupt Enable for STCTRL #define ST_CTRL_ENABLE 0x00000001 // Enable for STCTRL // Maximum period #define MAX_WAIT 0x186A00 /* 2^24 */ /* Global to signal SysTick interrupt */ volatile int elapsed; /* Globals */ char Data; /* Input data from UART receive */ char * data_ptr; extern int UartOutIdle; // memory location for Uart idle status #define MAX_MSG_SIZE 5 char dta; int src; int sourc; /* my defines */ #define MONq 0 // these are used to indicate what Q to enter or extract from #define UARTq 1 /*SYSTICK*/ /* - SysTick sample code - Originally written for the Stellaris (2013) - Will need to use debugger to "see" interrupts - Code uses bit-operations to access SysTick bits */ void SysTickStart(void); void SysTickStop(void); void SysTickPeriod(unsigned long Period); void SysTickIntEnable(void); void SysTickIntDisable(void); void SysTickHandler(void); #endif /* ISRS_H_ */
9973d0eff4f1e4ebf0e64bbfa7be1cc6b68f047a
[ "Markdown", "C" ]
14
C
EazyTeezy/Trainset
825d787b3594f7f07a5b09562810d6056d87516a
3efe161e256fa4a944f63a5a5f7d938d3e9a347f
refs/heads/master
<repo_name>mathwiz617/MagChamberSim<file_sep>/src/Player.cpp /* * Player.cpp * * Created on: Apr 26, 2016 * Author: matt */ #include "Player.h" Player::Player() { inventory = Inventory::Inventory(); mice = MiceStats::MiceStats(); gold = 0; points = 0; goldProfit = 0; goldGained = 0; goldLost = 0; embers = 0; embersGained = 0; meltedCheese = 0; cheeseMeltedAtOnce = 0; rubies = 0; sapphires = 0; emeralds = 0; scales = 0; rGained = 0; eGained = 0; saGained = 0; scGained = 0; charmsLooted = 0; rGainedTotal = 0; saGainedTotal = 0; eGainedTotal = 0; scGainedTotal = 0; embersGainedTotal = 0; charmsLootedTotal = 0; } string Player::BuildLootString(int embersGained, int rGained, int saGained, int eGained, int scGained, int charmsLooted){ string lootString; lootString += "You looted: "; if(embersGained > 0){ lootString += to_string(embersGained) + " embers "; } if(rGained > 0){ lootString += to_string(rGained) + " rubies "; } if(saGained > 0){ lootString += to_string(saGained) + " sapphires "; } if(eGained > 0){ lootString += to_string(eGained) + " emeralds "; } if(scGained > 0){ lootString += to_string(scGained) + " scales "; } if(charmsLooted > 0){ lootString += "You also looted " + to_string(charmsLooted) + " Ultimate charms! Lucky you!"; } return lootString; } Player::~Player() { // TODO Auto-generated destructor stub } <file_sep>/src/Mouse.cpp /* * Mouse.cpp * * Created on: Apr 25, 2016 * Author: matt */ #include "Mouse.h" #include "Loot.h" Mouse::Mouse() { mName = "None!"; mPower = 0; baitTier = 0; points = 0; gold = 0; odds = 0.0; caught = 0; missed = 0; lootPossible = GetLoot("None"); } Mouse::Mouse(string name, int power, int tier, int pointValue, int goldValue, double atrOdds){ mName = name; mPower = power; baitTier = tier; points = pointValue; gold = goldValue; odds = atrOdds; lootPossible = GetLoot(name); caught = 0; missed = 0; } vector<Loot> Mouse::GetLoot(string mouse){ Loot dropOne = Loot::Loot(); Loot dropTwo = Loot::Loot(); Loot dropThree = Loot::Loot(); int maxDroppedFirst; int maxDroppedSecond; int maxDroppedThird; string lootFirstName; string lootSecondName; string lootThirdName; vector<Loot> lootList; vector<double> chancesFirst; vector<double> chancesSecond; vector<double> chancesThird; lootList.clear(); chancesFirst.clear(); chancesSecond.clear(); chancesThird.clear(); if (mouse == "None"){ lootFirstName = "None"; chancesFirst.push_back(0); maxDroppedFirst = 0; dropOne.lName = lootFirstName; dropOne.numPossible = maxDroppedFirst; dropOne.chance = chancesFirst; lootList.push_back(dropOne); lootList.push_back(dropTwo); lootList.push_back(dropThree); } if (mouse == "Superheated"){ lootFirstName = "Ember"; chancesFirst.push_back(.5); maxDroppedFirst = 1; dropOne.lName = lootFirstName; dropOne.numPossible = maxDroppedFirst; dropOne.chance = chancesFirst; lootList.push_back(dropOne); lootList.push_back(dropTwo); lootList.push_back(dropThree); } if (mouse == "Magma"){ lootFirstName = "Ember"; chancesFirst.push_back(.4); maxDroppedFirst = 1; dropOne.lName = lootFirstName; dropOne.numPossible = maxDroppedFirst; dropOne.chance = chancesFirst; lootList.push_back(dropOne); lootList.push_back(dropTwo); lootList.push_back(dropThree); } if (mouse == "Green Dragon"){ lootFirstName = "Scale"; lootSecondName = "Emerald"; chancesFirst.push_back(.1); chancesSecond.push_back(1); maxDroppedFirst = 1; maxDroppedSecond = 1; dropOne.lName = lootFirstName; dropOne.numPossible = maxDroppedFirst; dropOne.chance = chancesFirst; dropTwo.lName = lootSecondName; dropTwo.numPossible = maxDroppedSecond; dropTwo.chance = chancesSecond; lootList.push_back(dropOne); lootList.push_back(dropTwo); lootList.push_back(dropThree); } if (mouse == "Blue Dragon"){ lootFirstName = "Scale"; lootSecondName = "Sapphire"; chancesFirst.push_back(.1); chancesSecond.push_back(1); maxDroppedFirst = 1; maxDroppedSecond = 1; dropOne.lName = lootFirstName; dropOne.numPossible = maxDroppedFirst; dropOne.chance = chancesFirst; dropTwo.lName = lootSecondName; dropTwo.numPossible = maxDroppedSecond; dropTwo.chance = chancesSecond; lootList.push_back(dropOne); lootList.push_back(dropTwo); lootList.push_back(dropThree); } if (mouse == "Red Dragon"){ lootFirstName = "Scale"; lootSecondName = "Ruby"; chancesFirst.push_back(.1); chancesSecond.push_back(1); maxDroppedFirst = 1; maxDroppedSecond = 1; dropOne.lName = lootFirstName; dropOne.numPossible = maxDroppedFirst; dropOne.chance = chancesFirst; dropTwo.lName = lootSecondName; dropTwo.numPossible = maxDroppedSecond; dropTwo.chance = chancesSecond; lootList.push_back(dropOne); lootList.push_back(dropTwo); lootList.push_back(dropThree); } if (mouse == "Black Dragon"){ lootFirstName = "Scale"; lootSecondName = "Ember"; chancesFirst.push_back(.25); chancesSecond.push_back(.66); chancesSecond.push_back(.66); chancesSecond.push_back(.66); maxDroppedFirst = 1; maxDroppedSecond = 3; dropOne.lName = lootFirstName; dropOne.numPossible = maxDroppedFirst; dropOne.chance = chancesFirst; dropTwo.lName = lootSecondName; dropTwo.numPossible = maxDroppedSecond; dropTwo.chance = chancesSecond; lootList.push_back(dropOne); lootList.push_back(dropTwo); lootList.push_back(dropThree); } if (mouse == "Broodmother"){ lootFirstName = "Scale"; lootSecondName = "Ember"; lootThirdName = "UC"; chancesFirst.push_back(1.0); chancesFirst.push_back(.8); chancesFirst.push_back(.6); chancesFirst.push_back(.4); chancesFirst.push_back(.2); chancesSecond.push_back(1.0); chancesSecond.push_back(.2); chancesSecond.push_back(.8); chancesSecond.push_back(.7); chancesSecond.push_back(.6); chancesSecond.push_back(.5); chancesSecond.push_back(.4); chancesSecond.push_back(.3); chancesSecond.push_back(.2); chancesSecond.push_back(.1); chancesThird.push_back(.01); maxDroppedFirst = 5; maxDroppedSecond = 10; maxDroppedThird = 1; dropOne.lName = lootFirstName; dropOne.numPossible = maxDroppedFirst; dropOne.chance = chancesFirst; dropTwo.lName = lootSecondName; dropTwo.numPossible = maxDroppedSecond; dropTwo.chance = chancesSecond; dropThree.lName = lootThirdName; dropThree.numPossible = maxDroppedThird; dropThree.chance = chancesThird; lootList.push_back(dropOne); lootList.push_back(dropTwo); lootList.push_back(dropThree); } return lootList; } Mouse::~Mouse() { } <file_sep>/src/Charm.cpp /* * Charm.cpp * * Created on: Apr 25, 2016 * Author: matt */ #include "Charm.h" Charm::Charm() { charmName = "none"; charmPower = 0; charmPowerBonus = 0; charmLuck = 0; amount = 0; charmAttractionBonus = 0; inSet = false; } Charm::Charm(string type, int pow, int powBonus, int lck, int owned, double atrBonus, bool set) { charmName = type; charmPower = pow; charmPowerBonus = powBonus; charmLuck = lck; amount = owned; charmAttractionBonus = atrBonus; inSet = set; } Charm::~Charm() { } <file_sep>/src/Charm.h /* * Charm.h * * Created on: Apr 25, 2016 * Author: matt */ #ifndef CHARM_H_ #define CHARM_H_ #include <iostream> using namespace std; class Charm { public: string charmName; //charm name int charmPower; //power int charmPowerBonus; //power bonus int charmLuck; //luck int amount; double charmAttractionBonus; //added to cheese attraction rate bool inSet; //Is it part of the Dragonslayer set? Charm(); Charm(string, int, int, int, int, double, bool); virtual ~Charm(); }; #endif /* CHARM_H_ */ <file_sep>/src/Loot.cpp /* * Loot.cpp * * Created on: Apr 25, 2016 * Author: matt */ #include "Loot.h" Loot::Loot() { lName = "None!"; numPossible = 1; chance.resize(1); chance.at(0) = 0; } Loot::Loot(string name, int numMax){ lName = name; numPossible = numMax; chance.resize(1); chance.at(0) = 0; } Loot::~Loot() { } <file_sep>/src/Base.cpp /* * Base.cpp * * Created on: Apr 25, 2016 * Author: matt */ #include "Base.h" Base::Base() { bName = "Disarmed!"; bPower = 0; bPowerBonus = 0; bLuck = 0; bAttractionBonus = 0; inInventory = false; inSet = false; } Base::Base(string type, int pow, int powBonus, int lck, double atrBonus, bool have, bool set) { bName = type; bPower = pow; bPowerBonus = powBonus; bLuck = lck; bAttractionBonus = atrBonus; inInventory = have; inSet = set; } Base::~Base() { } <file_sep>/src/Inventory.h /* * Inventory.h * * Created on: Apr 26, 2016 * Author: matt */ #ifndef INVENTORY_H_ #define INVENTORY_H_ #include "Base.h" #include "Charm.h" #include "Cheese.h" #include "Weapon.h" class Inventory { public: //declare weapons Weapon iceMaiden; Weapon powerTrap; Weapon luckTrap; Weapon bestTrap; Weapon invalidWeapon; Weapon weaponArmed; //declare bases Base rift; Base mino; Base basalt; Base invalidBase; Base baseArmed; //declare charms Charm otherCharm; Charm noCharm; Charm ultimate; Charm dragon; Charm charmArmed; //declare cheeses Cheese otherCheese; Cheese gouda; Cheese fieryFondue; Cheese moltenHavarti; Cheese treasureHavarti; Cheese cheeseArmed; int trapPower; //total power before bonus int trapLuck; //total luck, no bonuses double trapPowerTotal; //total power double powerBonus; //power bonus double attractionRateBonus; //bonus to cheese attraction rate double attractionRate; //total attraction rate bool shield; //Does your trap get +7 luck? Inventory(); virtual ~Inventory(); }; #endif /* INVENTORY_H_ */ <file_sep>/src/MiceStats.cpp /* * MiceStats.cpp * * Created on: Apr 26, 2016 * Author: matt */ #include "MiceStats.h" MiceStats::MiceStats() { //define mice here //("Name", power, bait tier, point value, gold value, attraction odds at the right tier) none = Mouse::Mouse("None", 0, 0, 0, 0, 0.0); heated = Mouse::Mouse("Superheated", 38000, 1, 50000, 10000, .4); magma = Mouse::Mouse("Magma", 35000, 1, 30000, 6000, .6); gDragon = Mouse::Mouse("Green Dragon", 80000, 2, 50000, 50000, .3); rDragon = Mouse::Mouse("Red Dragon", 80000, 2, 100000, 30000, .3); bDragon = Mouse::Mouse("Blue Dragon", 80000, 2, 30000, 100000, .3); blkDragon = Mouse::Mouse("Black Dragon", 150000, 2, 100000, 100000, .1); mother = Mouse::Mouse("Broodmother", 800000, 3, 500000, 500000, 1); attracted = Mouse::Mouse(); } MiceStats::~MiceStats() { // TODO Auto-generated destructor stub } <file_sep>/src/RedBox.cpp /* * RedBox.cpp * * Created on: Apr 25, 2016 * Author: matt */ #include "RedBox.h" RedBox::RedBox() { type = 1; amount = 0; } RedBox::RedBox(int drained, int value){ type = drained; amount = value; } RedBox::~RedBox() { // TODO Auto-generated destructor stub } <file_sep>/src/MagChamberSim.cpp /* * MagChamberSim.cpp * * Created on: Apr 25, 2016 * Author: matt */ #include "RedBox.h" #include "Player.h" #include <iostream> #include <ctime> using namespace std; const int EFF = 1; Weapon ChooseWeapon(string, Player); Base ChooseBase(string, Player); Charm ChooseCharm(string, Player); Cheese ChooseCheese(string, Player); Player ChooseMouse(Player); RedBox RedBoxValue(Player); Player Shop(Player); Player Craft(Player); Player SetTrap(Player); Player LootAdd(Player); Player Hunt(Player); bool Atr(double); bool CatchRoll(Player); bool RedBoxRoll(); void SeeMiceStats(Player, int); void SeeInventory(Player); int main() { Player hunter = Player::Player(); string weaponName; string baseName; string charmName; string cheeseName; string input; int cycles; int charmCount; int huntsInArea = 0; srand(time(NULL)); cout << "Enter starting options." << endl << "Defaulting to 20 Dragon Embers for testing." << endl; hunter.embers = 20; cout << "Defaulting to 12 million gold. " << endl; hunter.gold = 12000000; cout << "Defaulting to 1 billion points. " << endl; hunter.points = 1000000000; cout << "Defaulting to 1000 Gouda. " << endl; hunter.inventory.gouda.amount = 1000; cout << "Defaulting to 6 Ultimate charms. " << endl; charmCount = 6; hunter.inventory.ultimate.amount = charmCount; cout << "Defaulting to LGS active." << endl; hunter.inventory.shield = true; cout << endl; weaponName = "IceMaiden"; hunter.inventory.weaponArmed = ChooseWeapon(weaponName, hunter); baseName = "Rift"; hunter.inventory.baseArmed = ChooseBase(baseName, hunter); charmName = "None"; hunter.inventory.charmArmed = ChooseCharm(charmName, hunter); cheeseName ="Gouda"; hunter.inventory.cheeseArmed = ChooseCheese(cheeseName, hunter); hunter = SetTrap(hunter); cout << endl; do{ cout << endl << "What do you want to do?" << endl; cout << "Weapon = change weapon."<< endl; cout << "Base = change base."<< endl; cout << "Charm = change charm."<< endl; cout << "Cheese = change cheese."<< endl; cout << "LGS = toggle LGS." << endl; cout << "Hunt = hunt for mouse."<< endl; cout << "Trap = view trap."<< endl; cout << "Mice = view catch/miss stats for each mouse."<< endl; cout << "Shop = go shopping."<< endl; cout << "Craft = craft something."<< endl; cout << "Inventory = view inventory."<< endl; cout << "Done = end simulation." << endl; cin >> input; if (input == "Weapon"){ cout << "What do you want to change to? (Enter Ice Maiden, Power, Luck, or Best.)" << endl; cin >> weaponName; hunter.inventory.weaponArmed = ChooseWeapon(weaponName, hunter); hunter = SetTrap(hunter); } if (input == "Base"){ cout << "What do you want to change to? (NYFI, enter Rift, Mino, or Basalt.)" << endl; cin >> baseName; hunter.inventory.baseArmed = ChooseBase(baseName, hunter); hunter = SetTrap(hunter); } if (input == "Charm"){ cout << "What do you want to change to? (NYFI, enter None, Dragon, or Ultimate.)" << endl; cin >> charmName; hunter.inventory.charmArmed = ChooseCharm(charmName, hunter); hunter = SetTrap(hunter); } if (input == "Cheese"){ cout << "What do you want to change to?" <<endl; cout << "(Only Gouda is available for regular cheeses. Enter Gouda, FF, MH, or THH.)" << endl; cin >> cheeseName; hunter.inventory.cheeseArmed = ChooseCheese(cheeseName, hunter); hunter = SetTrap(hunter); } if (input == "LGS"){ if (hunter.inventory.shield == true){ hunter.inventory.shield = false; } else { hunter.inventory.shield = true; } } if (input == "Hunt"){ if(hunter.inventory.cheeseArmed.tier == 0){ cout << "No mice will be attracted! Arm a real cheese type!" << endl; } else{ cout << "How many times? "; cin >> cycles; hunter.goldProfit = 0; hunter.rGainedTotal = 0; hunter.saGainedTotal = 0; hunter.eGainedTotal = 0; hunter.scGainedTotal = 0; hunter.charmsLootedTotal = 0; hunter.embersGainedTotal = 0; hunter.cheeseMeltedAtOnce = 0; int i = 0; while(i < cycles && hunter.inventory.cheeseArmed.amount > 0){ huntsInArea++; hunter = Hunt(hunter); hunter.rGained = 0; hunter.saGained = 0; hunter.eGained = 0; hunter.scGained = 0; hunter.charmsLooted = 0; hunter.embersGained = 0; hunter = SetTrap(hunter); i++; if(hunter.inventory.cheeseArmed.amount < 1){ cout << "You ran out of cheese after " << i << " hunts. Go buy or craft more!" << endl; if ((hunter.inventory.cheeseArmed.cheeseName == "Gouda") && (hunter.inventory.cheeseArmed.amount < 0)){ hunter.inventory.gouda.amount = 0; hunter.inventory.cheeseArmed.amount = 0; } if ((hunter.inventory.cheeseArmed.cheeseName == "Fiery Fondue") && (hunter.inventory.cheeseArmed.amount < 0)){ hunter.inventory.fieryFondue.amount = 0; hunter.inventory.cheeseArmed.amount = 0; } if ((hunter.inventory.cheeseArmed.cheeseName == "Molten Havarti") && (hunter.inventory.cheeseArmed.amount < 0)){ hunter.inventory.moltenHavarti.amount = 0; hunter.inventory.cheeseArmed.amount = 0; } if ((hunter.inventory.cheeseArmed.cheeseName == "Treasure Hoard Havarti") && (hunter.inventory.cheeseArmed.amount < 0)){ hunter.inventory.treasureHavarti.amount = 0; hunter.inventory.cheeseArmed.amount = 0; } } if(hunter.inventory.charmArmed.amount < 1){ if (hunter.inventory.charmArmed.charmName != "none"){ cout << "You ran out of charms! Disarming charms." << endl; } if ((hunter.inventory.charmArmed.charmName == "Ultimate") && (hunter.inventory.charmArmed.amount < 0)){ hunter.inventory.ultimate.amount = 0; hunter.inventory.charmArmed.amount = 0; } if ((hunter.inventory.charmArmed.charmName == "Dragon") && (hunter.inventory.cheeseArmed.amount < 0)){ hunter.inventory.dragon.amount = 0; hunter.inventory.charmArmed.amount = 0; } hunter.inventory.charmArmed = hunter.inventory.noCharm; } } cout << "You have made an overall profit of: " << hunter.goldProfit << " gold this last round of hunting." << endl; cout << "You looted " << hunter.rGainedTotal << "/" << hunter.saGainedTotal << "/" << hunter.rGainedTotal << "/" << hunter.scGainedTotal << " rubies/sapphires/emeralds/scales." << endl; cout << "You looted " << hunter.embersGainedTotal << " embers and melted " << hunter.cheeseMeltedAtOnce << " pieces of cheese." << endl; cout << "You looted " << hunter.charmsLootedTotal << " Ultimate charms!" << endl; if(hunter.inventory.cheeseArmed.cheeseName == "Gouda"){ cout << "You have " << hunter.inventory.gouda.amount << " " << hunter.inventory.gouda.cheeseName << " remaining." << endl; } if(hunter.inventory.cheeseArmed.cheeseName == "FieryFondue"){ cout << "You have " << hunter.inventory.fieryFondue.amount << " " << hunter.inventory.fieryFondue.cheeseName << " remaining." << endl; } if(hunter.inventory.cheeseArmed.cheeseName == "MoltenHavarti"){ cout << "You have " << hunter.inventory.moltenHavarti.amount << " " << hunter.inventory.moltenHavarti.cheeseName << " remaining." << endl; } if(hunter.inventory.cheeseArmed.cheeseName == "TreasureHoardHavarti"){ cout << "You have " << hunter.inventory.treasureHavarti.amount << " " << hunter.inventory.treasureHavarti.cheeseName << " remaining." << endl; } } } if (input == "Trap"){ cout << hunter.inventory.weaponArmed.wName << "/" << hunter.inventory.baseArmed.bName << "/" << hunter.inventory.charmArmed.charmName << "(" << hunter.inventory.charmArmed.amount << ")/" << hunter.inventory.cheeseArmed.cheeseName << "(" << hunter.inventory.cheeseArmed.amount << ")" << endl; if (hunter.inventory.shield == true){ cout << "The LGS is active." << endl; } else{ cout << "The LGS is not active." << endl; } cout << "Power: " << hunter.inventory.trapPowerTotal << endl; cout << "Luck: " << hunter.inventory.trapLuck << endl; cout << "Attraction rate: " << hunter.inventory.attractionRate << endl; cout << "Hunting tier: " << hunter.inventory.cheeseArmed.tier << endl; } if (input == "Mice"){ SeeMiceStats(hunter, huntsInArea); } if (input == "Shop"){ hunter = Shop(hunter); hunter = SetTrap(hunter); } if (input == "Craft"){ hunter = Craft(hunter); hunter = SetTrap(hunter); } if (input == "Inventory"){ SeeInventory(hunter); } }while (input != "Done"); return 0; } //change weapon here Weapon ChooseWeapon(string weaponName, Player hunter){ Weapon weapon; if(weaponName == "IceMaiden"){ if (hunter.inventory.iceMaiden.inInventory == true){ weapon = hunter.inventory.iceMaiden; cout << "Ice Maiden armed." << endl; } else { cout << "You don't own that trap" << endl; } } else if((weaponName == "Power") && (hunter.points > 1000000)){ if (hunter.inventory.powerTrap.inInventory == true){ weapon = hunter.inventory.powerTrap; cout << "Power trap armed." << endl; } else { cout << "You don't own that trap" << endl; } } else if((weaponName == "Luck") && (hunter.points > 1000000)){ if (hunter.inventory.luckTrap.inInventory == true){ weapon = hunter.inventory.luckTrap; cout << "Luck trap armed." << endl; } else { cout << "You don't own that trap" << endl; } } else if(weaponName == "Best"){ if (hunter.inventory.bestTrap.inInventory == true){ weapon = hunter.inventory.bestTrap; cout << "Best trap armed." << endl; } else { cout << "You don't own that trap" << endl; } } else{ weapon = hunter.inventory.invalidWeapon; cout << "Current weapon is invalid." << endl; } return weapon; } //change base here Base ChooseBase(string baseName, Player hunter){ Base base; if(baseName == "Rift"){ base = hunter.inventory.rift; cout << "Rift Base armed." << endl; } else if(baseName == "Mino"){ base = hunter.inventory.mino; cout << "Minotaur Base armed." << endl; } else if(baseName == "Basalt"){ base = hunter.inventory.basalt; cout << "Basalt Base armed." << endl; } else{ base = hunter.inventory.invalidBase; cout << "Current base is invalid." << endl; } return base; } //change charm here Charm ChooseCharm(string charmName, Player hunter){ Charm charm; if(charmName == "None"){ charm = hunter.inventory.noCharm; cout << "No charm armed." << endl; } else if((charmName == "Ultimate") && (hunter.inventory.ultimate.amount > 0)){ charm = hunter.inventory.ultimate; cout << "Ultimate charm armed. Charm will be used up on each hunt." << endl << "Catch those mice!" << endl; } else if((charmName == "Dragon") && (hunter.inventory.dragon.amount > 0)){ charm = hunter.inventory.dragon; cout << "Dragon charm armed. Charm will be used up on each hunt." << endl; } else{ charm = hunter.inventory.otherCharm; cout << "This charm is NYI. Effectively none." << endl; } return charm; } //change cheese here Cheese ChooseCheese(string cheeseName, Player hunter){ Cheese cheese = Cheese::Cheese(); if((cheeseName == "Gouda") && (hunter.inventory.gouda.amount > 0)){ cheese = hunter.inventory.gouda; cout << "Gouda armed." << endl; cout << "Tier one mice will be attracted." << endl; cout << "Cheese will be used at a rate of two per hunt." << endl; } else if ((cheeseName == "FF") && (hunter.inventory.fieryFondue.amount > 0)){ cheese = hunter.inventory.fieryFondue; cout << "Fiery Fondue armed." << endl; cout << "Tier one mice will be attracted." << endl; } else if ((cheeseName == "MH") && (hunter.inventory.moltenHavarti.amount > 0)){ cheese = hunter.inventory.moltenHavarti; cout << "Molten Havarti armed." << endl; cout << "Tier two mice will be attracted." << endl; } else if ((cheeseName == "THH") && (hunter.inventory.treasureHavarti.amount > 0)){ cheese = hunter.inventory.treasureHavarti; cout << "Treasure Hoard Havarti armed." << endl; cout << "Tier three mice will be attracted." << endl; } else{ cheese = hunter.inventory.otherCheese; cout << "Invalid cheese." << endl; } return cheese; } //pick mouse here Player ChooseMouse( Player hunter){ double r = ((double) rand() / (RAND_MAX)); if (hunter.inventory.cheeseArmed.tier == 0){ hunter.mice.attracted = hunter.mice.none; } if (hunter.inventory.cheeseArmed.tier == 1){ if (r <= .4){ hunter.mice.attracted = hunter.mice.heated; } else{ hunter.mice.attracted = hunter.mice.magma; } } if (hunter.inventory.cheeseArmed.tier == 2){ if (r <= .3){ hunter.mice.attracted = hunter.mice.gDragon; } else if (r > .3 && r <= .6){ hunter.mice.attracted = hunter.mice.rDragon; } else if (r > .6 && r <= .9){ hunter.mice.attracted = hunter.mice.bDragon; } else{ hunter.mice.attracted = hunter.mice.blkDragon; } } if (hunter.inventory.cheeseArmed.tier == 3){ hunter.mice.attracted = hunter.mice.mother; } return hunter; } //Add loot from caught mouse to inventory Player LootAdd(Player hunter){ string drops; Loot loot; double r = ((double) rand() / (RAND_MAX)); loot.numPossible = 0; for(int i = 0; i < hunter.mice.attracted.lootPossible.size(); i++){ loot = hunter.mice.attracted.lootPossible.at(i); for (int j = 0; j < loot.numPossible; j++){ int numDropped = 0; if (r <= loot.chance.at(j)){ numDropped++; if(numDropped > loot.numPossible){ numDropped = loot.numPossible; } } if ((loot.lName == "Ember") && (numDropped > 0)){ hunter.embers += numDropped; hunter.embersGained += numDropped; hunter.embersGainedTotal += numDropped; } if ((loot.lName == "Scale") && (numDropped > 0)){ hunter.scales += numDropped; hunter.scGained += numDropped; hunter.scGainedTotal += numDropped; } if ((loot.lName == "Sapphire") && (numDropped > 0)){ hunter.sapphires += numDropped; hunter.saGained += numDropped; hunter.saGainedTotal += numDropped; } if ((loot.lName == "Ruby") && (numDropped > 0)){ hunter.rubies += numDropped; hunter.rGained += numDropped; hunter.rGainedTotal += numDropped; } if ((loot.lName == "Emerald") && (numDropped > 0)){ hunter.emeralds += numDropped; hunter.eGained += numDropped; hunter.eGainedTotal += numDropped; } if ((loot.lName == "UC") && (numDropped > 0)){ hunter.inventory.ultimate.amount += numDropped; hunter.charmsLooted += numDropped; hunter.charmsLootedTotal += numDropped; } } } if((hunter.embersGained > 0) || (hunter.rGained > 0) || (hunter.saGained > 0) || (hunter.eGained > 0) || (hunter.scGained > 0) ||(hunter.charmsLooted > 0)){ drops = hunter.BuildLootString(hunter.embersGained, hunter.rGained, hunter.saGained, hunter.eGained, hunter.scGained, hunter.charmsLooted); cout << drops << endl; } return hunter; } //does the cheese attract? bool Atr(double atrRate){ double r = ((double) rand() / (RAND_MAX)); if(r <= atrRate){ return true; } else { return false; } } //does the trap catch the mouse? bool CatchRoll(Player hunter){ double catchRate; double r = ((double) rand() / (RAND_MAX)); catchRate = ((EFF * hunter.inventory.trapPowerTotal) + ((3 - EFF) * (hunter.inventory.trapLuck * hunter.inventory.trapLuck))) / ((EFF * hunter.inventory.trapPowerTotal) + hunter.mice.attracted.mPower); if (r <= catchRate || hunter.inventory.charmArmed.charmName == "Ultimate"){ return true; } else{ return false; } } //if missed, is it a red box? bool RedBoxRoll(){ double r = ((double) rand() / (RAND_MAX)); if (r <= .5){ return true; } else{ return false; } } //how much, of what, does the red box take away? RedBox RedBoxValue(Player hunter){ RedBox value; double r = ((double) rand() / (RAND_MAX)); if (r <= .4 && hunter.inventory.cheeseArmed.storeCheese == true){ value.type = 1; //extra cheese if (hunter.inventory.cheeseArmed.cheeseName == "Gouda"){ value.amount = 10; } else{ value.amount = 1; } if (hunter.inventory.cheeseArmed.amount < 0){ hunter.inventory.cheeseArmed.amount = 0; } } else if (r > .4 && r <= .7){ value.type = 2; //drains points value.amount = 10000; } else if (r > .7 && hunter.gold > 999){ value.type = 3; //drains gold value.amount = 1000; } return value; } //The actual hunt, plus result output Player Hunt(Player hunter){ RedBox redBox; bool atrMouse = false; bool isMouseCaught = false; bool isRedBox = false; atrMouse = Atr(hunter.inventory.attractionRate); if (atrMouse == true){ hunter = ChooseMouse(hunter); isMouseCaught = CatchRoll(hunter); if (isMouseCaught == true){ if (hunter.inventory.charmArmed.charmName == "Ultimate"){ hunter.inventory.ultimate.amount -= 1; } if(hunter.mice.attracted.mName == "Superheated"){ hunter.mice.heated.caught++; } if(hunter.mice.attracted.mName == "Magma"){ hunter.mice.magma.caught++; } if(hunter.mice.attracted.mName == "Green Dragon"){ hunter.mice.gDragon.caught++; } if(hunter.mice.attracted.mName == "Red Dragon"){ hunter.mice.rDragon.caught++; } if(hunter.mice.attracted.mName == "Blue Dragon"){ hunter.mice.bDragon.caught++; } if(hunter.mice.attracted.mName == "Black Dragon"){ hunter.mice.blkDragon.caught++; } if(hunter.mice.attracted.mName == "Broodmother"){ hunter.mice.mother.caught++; } hunter.gold += hunter.mice.attracted.gold; hunter.goldGained += hunter.mice.attracted.gold; hunter.points += hunter.mice.attracted.points; if (hunter.inventory.cheeseArmed.cheeseName == "Gouda"){ hunter.inventory.gouda.amount -= 2; } if (hunter.inventory.cheeseArmed.cheeseName == "Fiery Fondue"){ hunter.inventory.fieryFondue.amount--; } if (hunter.inventory.cheeseArmed.cheeseName == "Molten Havarti"){ hunter.inventory.moltenHavarti.amount--; } if (hunter.inventory.cheeseArmed.cheeseName == "Treasure Hoard Havarti"){ hunter.inventory.treasureHavarti.amount--; } } else{ if(hunter.mice.attracted.mName == "Superheated"){ hunter.mice.heated.missed++; } if(hunter.mice.attracted.mName == "Magma"){ hunter.mice.magma.missed++; } if(hunter.mice.attracted.mName == "Green Dragon"){ hunter.mice.gDragon.missed++; } if(hunter.mice.attracted.mName == "Red Dragon"){ hunter.mice.rDragon.missed++; } if(hunter.mice.attracted.mName == "Blue Dragon"){ hunter.mice.bDragon.missed++; } if(hunter.mice.attracted.mName == "Black Dragon"){ hunter.mice.blkDragon.missed++; } if(hunter.mice.attracted.mName == "Broodmother"){ hunter.mice.mother.missed++; } isRedBox = RedBoxRoll(); if (hunter.inventory.cheeseArmed.cheeseName == "Gouda"){ hunter.inventory.gouda.amount -= 2; hunter.meltedCheese += 1; hunter.cheeseMeltedAtOnce += 1; } if (hunter.inventory.cheeseArmed.cheeseName == "Fiery Fondue"){ hunter.inventory.fieryFondue.amount--; } if (hunter.inventory.cheeseArmed.cheeseName == "Molten Havarti"){ hunter.inventory.moltenHavarti.amount--; } if (hunter.inventory.cheeseArmed.cheeseName == "Treasure Hoard Havarti"){ hunter.inventory.treasureHavarti.amount--; } if(isRedBox == true){ redBox = RedBoxValue(hunter); switch (redBox.type){ case 1: hunter.inventory.cheeseArmed.amount -= redBox.amount; if (hunter.inventory.cheeseArmed.cheeseName == "Gouda"){ hunter.inventory.gouda.amount -= redBox.amount; } if (hunter.inventory.cheeseArmed.cheeseName == "Fiery Fondue"){ hunter.inventory.fieryFondue.amount -= redBox.amount; } if (hunter.inventory.cheeseArmed.cheeseName == "<NAME>"){ hunter.inventory.moltenHavarti.amount -= redBox.amount; } if (hunter.inventory.cheeseArmed.cheeseName == "<NAME>"){ hunter.inventory.treasureHavarti.amount -= redBox.amount; } break; case 2: hunter.points -= redBox.amount; break; case 3: hunter.gold -= redBox.amount; hunter.goldLost += redBox.amount; break; } } } if(isMouseCaught == true){ hunter.goldProfit = hunter.goldGained - hunter.goldLost; cout << endl << "You caught a(n) " << hunter.mice.attracted.mName << " Mouse!" << endl; hunter = LootAdd(hunter); hunter.embersGained = 0; } else{ cout << endl << "You missed a(n) " << hunter.mice.attracted.mName << " Mouse!" << endl; if(isRedBox == true){ cout << "The mouse took "; switch (redBox.type){ case 1: cout << redBox.amount << " pieces of cheese!" << endl; break; case 2: cout << redBox.amount << " points!" << endl; break; case 3: cout << redBox.amount << " gold!" << endl; break; } } hunter.goldProfit = hunter.goldGained - hunter.goldLost; } } else{ if (hunter.inventory.cheeseArmed.cheeseName == "Gouda"){ hunter.inventory.gouda.amount -= 2; hunter.meltedCheese += 2; hunter.cheeseMeltedAtOnce += 2; } if (hunter.inventory.cheeseArmed.cheeseName == "Fiery Fondue"){ hunter.inventory.fieryFondue.amount--; hunter.meltedCheese += 1; hunter.cheeseMeltedAtOnce += 1; } if (hunter.inventory.cheeseArmed.cheeseName == "Molten Havarti"){ hunter.inventory.moltenHavarti.amount--; hunter.meltedCheese += 1; hunter.cheeseMeltedAtOnce += 1; } if (hunter.inventory.cheeseArmed.cheeseName == "Treasure Hoard Havarti"){ hunter.inventory.treasureHavarti.amount--; hunter.meltedCheese += 1; hunter.cheeseMeltedAtOnce += 1; } cout << endl << "No attraction!" << endl; } return hunter; } //self-described void SeeMiceStats(Player hunter, int hunts){ double rate = 0.0; cout << "Total hunts: " << hunts << endl; if((hunter.mice.heated.caught + hunter.mice.heated.missed) != 0){ rate = double(hunter.mice.heated.caught) / (hunter.mice.heated.caught + hunter.mice.heated.missed); cout << "Superheated: " << hunter.mice.heated.caught << "/" << hunter.mice.heated.missed << " " << (rate * 100) << "%" << endl; } if((hunter.mice.magma.caught + hunter.mice.magma.missed) != 0){ rate = double(hunter.mice.magma.caught) / (hunter.mice.magma.caught + hunter.mice.magma.missed); cout << "Magma: " << hunter.mice.magma.caught << "/" << hunter.mice.magma.missed << " " << (rate * 100) << "%" << endl; } if((hunter.mice.gDragon.caught + hunter.mice.gDragon.missed) != 0){ rate = double(hunter.mice.gDragon.caught) / (hunter.mice.gDragon.caught + hunter.mice.gDragon.missed); cout << "Green Dragon: " << hunter.mice.gDragon.caught << "/" << hunter.mice.gDragon.missed << " " << (rate * 100) << "%" << endl; } if((hunter.mice.rDragon.caught + hunter.mice.rDragon.missed) != 0){ rate = double(hunter.mice.rDragon.caught) / (hunter.mice.rDragon.caught + hunter.mice.rDragon.missed); cout << "Red Dragon: " << hunter.mice.rDragon.caught << "/" << hunter.mice.rDragon.missed << " " << (rate * 100) << "%" << endl; } if((hunter.mice.bDragon.caught + hunter.mice.bDragon.missed) != 0){ rate = double(hunter.mice.bDragon.caught) / (hunter.mice.bDragon.caught + hunter.mice.bDragon.missed); cout << "Blue Dragon: " << hunter.mice.bDragon.caught << "/" << hunter.mice.bDragon.missed << " " << (rate * 100) << "%" << endl; } if((hunter.mice.blkDragon.caught + hunter.mice.blkDragon.missed) != 0){ rate = double(hunter.mice.blkDragon.caught) / (hunter.mice.blkDragon.caught + hunter.mice.blkDragon.missed); cout << "Black Dragon: " << hunter.mice.blkDragon.caught << "/" << hunter.mice.blkDragon.missed << " " << (rate * 100) << "%" << endl; } if((hunter.mice.mother.caught + hunter.mice.mother.missed) != 0){ rate = double(hunter.mice.mother.caught) / (hunter.mice.mother.caught + hunter.mice.mother.missed); cout << "Broodmother: " << hunter.mice.mother.caught << "/" << hunter.mice.mother.missed << " " << (rate * 100) << "%" << endl; } return; } //spend your gold here! Player Shop(Player hunter){ string input; char correct = 'n'; char again = 'y'; do{ int goldCostPer = 0; int bought = 0; int totalGoldCost = 0; int emberCostPer = 0; int totalEmberCost = 0; cout << endl << "You own " << hunter.embers << " embers and " << hunter.gold << " gold." << endl; cout << "What would you like to buy?" << endl; cout << "Gouda = buy gouda, 600 gold per piece." << endl; cout << "MH = buy Molten Havarti. Spend 1 ember, 5,000 gold for pack of five pieces." << endl; cout << "Power = Power-based trap. Spend 100 embers, 5 million gold. Max of one." << endl; cout << "Luck = Luck-based trap. Spend 100 embers, 5 million gold. Max of one." << endl; cout << "None = leave shop." << endl; do{ cin >> input; if(input == "None"){ return hunter; } cout << endl << "How many would you like to buy?" << endl; cin >> bought; if (input == "Gouda"){ goldCostPer = 600; } else if (input == "MH"){ goldCostPer = 5000; emberCostPer = 1; } else if (input == "Power"){ if (hunter.inventory.powerTrap.inInventory == true){ cout << "You can't buy any more of those!" << endl; bought = 0; } else if (bought == 1){ goldCostPer = 5000000; emberCostPer = 100; } else{ cout << "You can only buy one of those!" << endl; bought = 1; goldCostPer = 5000000; emberCostPer = 100; } } else if(input == "Luck"){ if (hunter.inventory.luckTrap.inInventory == true){ cout << "You can't buy any more of those!" << endl; bought = 0; } else if (bought == 1){ goldCostPer = 5000000; emberCostPer = 100; } else{ cout << "You can only buy one of those!" << endl; bought = 1; goldCostPer = 5000000; emberCostPer = 100; } } else{ cout << "Invalid choice! Leaving shop." << endl; return hunter; } totalGoldCost = bought * goldCostPer; totalEmberCost = bought * emberCostPer; cout << "You want to buy " << bought << " " << input << " for " << totalGoldCost << " gold and " << totalEmberCost << " embers. Is this correct? Enter 'n' to choose again." << endl; cin >> correct; if(correct != 'n'){ if ((hunter.gold < totalGoldCost) || (hunter.embers < totalEmberCost)){ cout << "You can't afford that!" << endl; } else{ if(input == "Gouda"){ hunter.inventory.gouda.amount += bought; } if (input == "MH"){ hunter.inventory.moltenHavarti.amount += (bought * 5); } if (input == "Power" && bought == 1){ cout << "You bought the Power Trap!" << endl; hunter.inventory.powerTrap.inInventory = true; } if (input == "Luck" && bought == 1){ cout << "You bought the Luck Trap!" << endl; hunter.inventory.luckTrap.inInventory = true; } hunter.gold -= totalGoldCost; hunter.goldLost += totalGoldCost; hunter.embers -= totalEmberCost; } } }while (correct == 'n'); cout << "Do you want to buy anything else? Enter 'y' to buy again." << endl; cin >> again; }while(again == 'y'); return hunter; } //Turn old stuff into new stuff Player Craft(Player hunter){ string input; int sapphiresSpentPer = 0; int emeraldsSpentPer = 0; int rubiesSpentPer = 0; int scalesSpentPer = 0; int meltedCheesePer = 0; int goldCostPer = 0; int crafted = 0; int totalScaleCost = 0; int totalRubyCost = 0; int totalSapphireCost = 0; int totalEmeraldCost = 0; int meltedCheeseTotal = 0; int emberCostPer = 0; int totalEmberCost = 0; int totalGoldCost = 0; char correct = 'n'; char again = 'y'; do{ cout << "You own " << hunter.embers << " embers, " << hunter.meltedCheese << " melted cheese." << endl; cout << "You own " << hunter.rubies << "/" << hunter.sapphires << "/" << hunter.emeralds << "/" << hunter.scales << " rubies/sapphires/emeralds/scales." << endl; cout << "What would you like to craft?" << endl; cout << "Melt = Craft melted cheese, one ember per piece." << endl; cout << "FF = Craft Fiery Fondue. Spend 1 ember, 10 melted cheese for pack of ten pieces." << endl; cout << "THH3 = Craft 3 Treasure Hoard Havarti. Spend 10 embers, 3 Sapphires, 3 Rubies, 3 Emeralds, 30 Melted cheese." << endl; cout << "THH4 = Craft 4 Treasure Hoard Havarti. Spend 10 embers, 3 Sapphires, 3 Rubies, 3 Emeralds, 30 Melted cheese and 40,000 gold." << endl; cout << "Charm = Craft Dragon Charm. Spend 10 embers, 10 scales each." << endl; cout << "Trap = Craft Best trap. Spend 1000 embers, 50 scales, both Power and Luck traps. Max of one." << endl; cout << "Base = Craft Basalt base. Spend 500 embers, 50 scales. Max of one." << endl; cout << "None = stop crafting." << endl; do{ cin >> input; if(input == "None"){ return hunter; } cout << endl << "How many would you like to craft?" << endl; cin >> crafted; if (input == "Melt"){ emberCostPer = 1; } else if (input == "FF"){ meltedCheesePer = 10; emberCostPer = 1; } else if (input == "THH3"){ meltedCheesePer = 30; rubiesSpentPer = 3; sapphiresSpentPer = 3; emeraldsSpentPer = 3; emberCostPer = 10; } else if (input == "THH4"){ meltedCheesePer = 30; rubiesSpentPer = 3; sapphiresSpentPer = 3; emeraldsSpentPer = 3; emberCostPer = 10; goldCostPer = 40000; } else if(input == "Charm"){ emberCostPer = 10; totalScaleCost = 10; } else if(input == "Trap"){ if (hunter.inventory.bestTrap.inInventory){ cout << "You can't craft any more of those!" << endl; crafted = 0; } else if (crafted == 1){ emberCostPer = 1000; scalesSpentPer = 50; } else{ cout << "You can only craft one of those!" << endl; crafted = 1; scalesSpentPer = 50; emberCostPer = 1000; } } else if(input == "Base"){ if (hunter.inventory.basalt.inInventory){ cout << "You can't craft any more of those!" << endl; crafted = 0; } else if (crafted == 1){ emberCostPer = 500; scalesSpentPer = 50; } else{ cout << "You can only craft one of those!" << endl; crafted = 1; scalesSpentPer = 50; emberCostPer = 500; } } else{ cout << "Invalid choice! Leaving crafting menu." << endl; return hunter; } totalEmberCost = crafted * emberCostPer; totalScaleCost = crafted * scalesSpentPer; totalRubyCost = crafted * rubiesSpentPer; totalSapphireCost = crafted * sapphiresSpentPer; totalEmeraldCost = crafted * emeraldsSpentPer; meltedCheeseTotal = crafted * meltedCheesePer; totalGoldCost = crafted * goldCostPer; cout << "You are going to craft " << crafted << " " << input << "." << endl; cout << "This will require " << totalEmberCost << " embers, " << meltedCheeseTotal << " melted cheese, and " << totalRubyCost << "/" << totalSapphireCost << "/" << totalEmeraldCost << "/" << totalScaleCost << " rubies/sapphires/emeralds/scales." << endl; if (totalGoldCost != 0){ cout << "You will also spend " << totalGoldCost << " gold on SB+." << endl; } cout << "Is this correct? Enter 'n' to choose again." << endl; cin >> correct; if(correct != 'n'){ if (hunter.emeralds < totalEmeraldCost || hunter.rubies < totalRubyCost || hunter.sapphires < totalSapphireCost || hunter.embers < totalEmberCost || hunter.scales < totalScaleCost || hunter.meltedCheese < meltedCheeseTotal){ cout << "You can't afford that!" << endl; } else{ if(input == "Melt"){ hunter.meltedCheese += crafted; } if (input == "FF"){ hunter.inventory.fieryFondue.amount += (crafted * 10); } if (input == "THH3"){ hunter.inventory.treasureHavarti.amount += (crafted * 3); } if (input == "THH4"){ hunter.inventory.treasureHavarti.amount += (crafted * 4); } if (input == "Trap" && crafted == 1 && hunter.inventory.powerTrap.inInventory == true && hunter.inventory.luckTrap.inInventory == true){ cout << "You made the Best Trap!" << endl; hunter.inventory.powerTrap.inInventory = false; hunter.inventory.luckTrap.inInventory = false; hunter.inventory.bestTrap.inInventory = true; } if (input == "Base"){ cout << "You made the Basalt Base!" << endl; hunter.inventory.basalt.inInventory = true; } hunter.embers -= totalEmberCost; hunter.emeralds -= totalEmeraldCost; hunter.rubies -= totalRubyCost; hunter.sapphires -= totalSapphireCost; hunter.scales -= totalScaleCost; hunter.meltedCheese -= meltedCheeseTotal; } } }while (correct == 'n'); cout << "Do you want to craft anything else? Enter 'y' to buy again." << endl; cin >> again; }while(again == 'y'); return hunter; } //set the trap, called after initial setup, changing parts, and after each hunt Player SetTrap(Player hunter){ Cheese cheese; Charm charm; int setPieces = 0; int setPowerBonus = 0; int setLuckBonus = 0; if (hunter.inventory.cheeseArmed.cheeseName == "Gouda"){ cheese = hunter.inventory.gouda; } if (hunter.inventory.cheeseArmed.cheeseName == "Fiery Fondue"){ cheese = hunter.inventory.fieryFondue; } if (hunter.inventory.cheeseArmed.cheeseName == "Molten Havarti"){ cheese = hunter.inventory.moltenHavarti; } if (hunter.inventory.cheeseArmed.cheeseName == "<NAME>"){ cheese = hunter.inventory.treasureHavarti; } hunter.inventory.cheeseArmed = cheese; if(hunter.inventory.charmArmed.charmName == "Ultimate"){ charm = hunter.inventory.ultimate; } if(hunter.inventory.charmArmed.charmName == "Dragon"){ charm = hunter.inventory.dragon; } if(hunter.inventory.charmArmed.charmName == "none"){ charm = hunter.inventory.noCharm; } hunter.inventory.charmArmed = charm; if(hunter.inventory.weaponArmed.inSet == true){ setPieces++; } if(hunter.inventory.baseArmed.inSet == true){ setPieces++; } if(hunter.inventory.charmArmed.inSet == true){ setPieces++; } if(setPieces > 1){ setPowerBonus = 10000; } if(setPieces == 3){ setLuckBonus = 30; } hunter.inventory.powerBonus = (hunter.inventory.weaponArmed.wPowerBonus + hunter.inventory.baseArmed.bPowerBonus + hunter.inventory.charmArmed.charmPowerBonus) / 100.0; hunter.inventory.trapPower = hunter.inventory.weaponArmed.wPower + hunter.inventory.baseArmed.bPower + hunter.inventory.charmArmed.charmPower + setPowerBonus; hunter.inventory.trapPowerTotal = hunter.inventory.trapPower + (hunter.inventory.trapPower * hunter.inventory.powerBonus); if(hunter.inventory.shield == true){ hunter.inventory.trapLuck = hunter.inventory.weaponArmed.wLuck + hunter.inventory.baseArmed.bLuck + hunter.inventory.charmArmed.charmLuck + 7 + setLuckBonus; } else{ hunter.inventory.trapLuck = hunter.inventory.weaponArmed.wLuck + hunter.inventory.baseArmed.bLuck + hunter.inventory.charmArmed.charmLuck + setLuckBonus; } hunter.inventory.attractionRateBonus = (1 - hunter.inventory.cheeseArmed.cheeseAttractionRate) * (hunter.inventory.weaponArmed.wAttractionBonus + hunter.inventory.baseArmed.bAttractionBonus + hunter.inventory.charmArmed.charmAttractionBonus); hunter.inventory.attractionRate = hunter.inventory.cheeseArmed.cheeseAttractionRate + hunter.inventory.attractionRateBonus; return hunter; } //self-described void SeeInventory(Player hunter){ cout << endl << "You have " << hunter.gold << " gold and " << hunter.points << " points." << endl; cout << "You own " << hunter.embers << " embers, " << hunter.meltedCheese << " melted cheese." << endl; cout << "You own " << hunter.rubies << "/" << hunter.sapphires << "/" << hunter.emeralds << "/" << hunter.scales << " rubies/sapphires/emeralds/scales." << endl; if(hunter.inventory.iceMaiden.inInventory == true){ cout << "You own the Ice Maiden." << endl; } if(hunter.inventory.powerTrap.inInventory == true){ cout << "You own the Power trap." << endl; } if(hunter.inventory.luckTrap.inInventory == true){ cout << "You own the Luck trap." << endl; } if(hunter.inventory.bestTrap.inInventory == true){ cout << "You own the Best trap." << endl; } if(hunter.inventory.rift.inInventory == true){ cout << "You own the Rift base." << endl; } if(hunter.inventory.mino.inInventory == true){ cout << "You own the Minotaur Base."<< endl; } if(hunter.inventory.basalt.inInventory == true){ cout << "You own the Basalt Base."<< endl; } cout << "You own " << hunter.inventory.ultimate.amount << " Ultimate Charms." << endl; cout << "You own " << hunter.inventory.dragon.amount << " Dragon Charms." << endl; cout << "You own " << hunter.inventory.gouda.amount << " gouda." << endl; cout << "You own " << hunter.inventory.fieryFondue.amount << " Fiery Fondue." << endl; cout << "You own " << hunter.inventory.moltenHavarti.amount << " Molten Havarti." << endl; cout << "You own " << hunter.inventory.treasureHavarti.amount << " Treasure Hoard Havarti." << endl; return; } <file_sep>/README.md # MagChamberSim A simulator for a Mousehunt area idea. Yeah, I know I ignored a bunch of coding standards. Bite me, this isn't professionally done. Notes: To add trap components, declare them in "Inventory.h", and define them in "Inventory.cpp". Make sure to add a way to get them, and add them to SeeInventory, SetTrap, and the relevant Choose function. If you add cheese or a charm, make sure to subtract them appropriately after each hunt. To change mouse power or add new mice, change "MiceStats.cpp" and "Mouse.h". Make sure to add loot in Mouse.cpp and SeeMiceStats. Catch rate is determined through the community-determined 3-eff model. Effectiveness multiplier is a constant, set globally. To add loot, change "Inventory.cpp" and "Inventory.h". Make sure to add it to Mouse::GetLoot and SeeInventory, and give it a purpose. <file_sep>/src/Loot.h /* * Loot.h * * Created on: Apr 25, 2016 * Author: matt */ #ifndef LOOT_H_ #define LOOT_H_ #include <iostream> #include <vector> using namespace std; class Loot { public: string lName; //loot type int numPossible; //max dropped vector<double> chance; //chances of each successive drop Loot(); Loot(string, int); virtual ~Loot(); }; #endif /* LOOT_H_ */ <file_sep>/src/Weapon.h /* * Weapon.h * * Created on: Apr 25, 2016 * Author: matt */ #ifndef WEAPON_H_ #define WEAPON_H_ #include <iostream> using namespace std; class Weapon { public: string wName; //name int wPower; //power int wPowerBonus; //power bonus int wLuck; //luck double wAttractionBonus; //added to cheese attraction rate bool inInventory; //do you have it? bool inSet; //Is it part of the Dragonslayer set? Weapon(); Weapon(string, int, int, int, double, bool, bool); virtual ~Weapon(); }; #endif /* WEAPON_H_ */ <file_sep>/src/Cheese.h /* * Cheese.h * * Created on: Apr 25, 2016 * Author: matt */ #ifndef CHEESE_H_ #define CHEESE_H_ #include <iostream> using namespace std; class Cheese { public: string cheeseName; //type of cheese int tier; //bait tier int amount; //amount left double cheeseAttractionRate; //base AR bool storeCheese; //Can it be stolen in a red box? Cheese(); Cheese(string, int, int, double, bool); virtual ~Cheese(); }; #endif /* CHEESE_H_ */ <file_sep>/src/Base.h /* * Base.h * * Created on: Apr 25, 2016 * Author: matt */ #ifndef BASE_H_ #define BASE_H_ #include <iostream> using namespace std; class Base { public: string bName; //base name int bPower; //power int bPowerBonus; //power bonus int bLuck; //luck double bAttractionBonus; //added to cheese attraction rate bool inInventory; //do you have it? bool inSet; //Is it part of the Dragonslayer set? Base(); Base(string, int, int, int, double, bool, bool); virtual ~Base(); }; #endif /* BASE_H_ */ <file_sep>/src/Player.h /* * Player.h * * Created on: Apr 26, 2016 * Author: matt */ #ifndef PLAYER_H_ #define PLAYER_H_ #include "MiceStats.h" #include "Inventory.h" class Player { public: Inventory inventory; MiceStats mice; long long gold; long long points; int goldProfit; int goldGained; int goldLost; int embers; int embersGained; int meltedCheese; int cheeseMeltedAtOnce; int rubies, sapphires, emeralds, scales; int rGained; int saGained; int eGained; int scGained; int charmsLooted; int rGainedTotal; int saGainedTotal; int eGainedTotal; int scGainedTotal; int embersGainedTotal; int charmsLootedTotal; Player(); string BuildLootString(int, int, int, int, int, int); virtual ~Player(); }; #endif /* PLAYER_H_ */ <file_sep>/src/Inventory.cpp /* * Inventory.cpp * * Created on: Apr 26, 2016 * Author: matt */ #include "Inventory.h" Inventory::Inventory() { //define pieces of trap here //define weapons //("Name", power, power bonus, luck, attraction bonus, owned) iceMaiden = Weapon::Weapon("Ice Maiden", 5200, 12, 8, 0.0, true, false); powerTrap = Weapon::Weapon("Power", 20000, 50, 50, 0.0, false, false); luckTrap = Weapon::Weapon("Luck", 15000, 30, 90, 0.0, false, false); bestTrap = Weapon::Weapon("Best", 40000, 60, 90, 0.0, true, false); invalidWeapon = Weapon::Weapon(); weaponArmed = Weapon::Weapon(); //define bases //("Name", power, power bonus, luck, attraction bonus, owned) rift = Base::Base("Rift Base", 250, 12, 11, 0.0, true, false); mino = Base::Base("Minotaur Base", 1000, 20, 15, 10.0, true, false); basalt = Base::Base("Basalt Base", 3000, 40, 30, 0.0, true, false); invalidBase = Base::Base(); baseArmed = Base::Base(); //define charms //("Name", power, power bonus, luck, number owned, attraction bonus) otherCharm = Charm::Charm("NYI", 0, 0, 0, 0, 0.0, false); ultimate = Charm::Charm("Ultimate", 0, 0, 0, 0, 0.0, false); dragon = Charm::Charm("Dragon", 10000, 40, 30, 0, 0.0, true); noCharm = Charm::Charm(); charmArmed = noCharm; //define cheeses //("Name", bait tier, owned, attraction, store-bought, regular) otherCheese = Cheese::Cheese("NYI", 0, 0, 0, false); gouda = Cheese::Cheese("Gouda", 1, 0, .85, true); fieryFondue = Cheese::Cheese("Fiery Fondue", 1, 0, .9, false); moltenHavarti = Cheese::Cheese("Molten Havarti", 2, 0, .99, true); treasureHavarti = Cheese::Cheese("Treasure Hoard Havarti", 3, 0, 1, false); cheeseArmed = Cheese::Cheese(); //other variables defined here shield = false; powerBonus = 0.0; trapPower = 0; trapPowerTotal = 0.0; trapLuck = 0; attractionRateBonus = 0; attractionRate = 0; } Inventory::~Inventory() { // TODO Auto-generated destructor stub } <file_sep>/src/Mouse.h /* * Mouse.h * * Created on: Apr 25, 2016 * Author: matt */ #ifndef MOUSE_H_ #define MOUSE_H_ #include <iostream> #include <vector> #include "Loot.h" using namespace std; class Mouse { public: string mName; //mouse breed name int mPower; //mouse power int baitTier; //bait tier needed to attract this mouse int caught; //number caught int missed; //number missed int points; //points given for catch int gold; //gold given for catch double odds; //odds of this mouse appearing per attraction on this tier vector<Loot> lootPossible; //possible drops Mouse(); Mouse(string, int, int, int, int, double); vector<Loot> GetLoot(string); virtual ~Mouse(); }; #endif /* MOUSE_H_ */ <file_sep>/src/Weapon.cpp /* * Weapon.cpp * * Created on: Apr 25, 2016 * Author: matt */ #include "Weapon.h" Weapon::Weapon() { wName = "Disarmed!"; wPower = 0; wPowerBonus = 0; wLuck = 0; wAttractionBonus = 0; inInventory = false; inSet = false; } Weapon::Weapon(string type, int pow, int powBonus, int lck, double atrBonus, bool have, bool set) { wName = type; wPower = pow; wPowerBonus = powBonus; wLuck = lck; wAttractionBonus = atrBonus; inInventory = have; inSet = set; } Weapon::~Weapon() { } <file_sep>/src/RedBox.h /* * RedBox.h * * Created on: Apr 25, 2016 * Author: matt */ #ifndef REDBOX_H_ #define REDBOX_H_ class RedBox { public: int type; int amount; RedBox(); RedBox(int, int); virtual ~RedBox(); }; #endif /* REDBOX_H_ */ <file_sep>/src/MiceStats.h /* * MiceStats.h * * Created on: Apr 26, 2016 * Author: matt */ #ifndef MICESTATS_H_ #define MICESTATS_H_ #include "Mouse.h" class MiceStats { public: //declare mice here Mouse none; Mouse heated; Mouse magma; Mouse gDragon; Mouse rDragon; Mouse bDragon; Mouse blkDragon; Mouse mother; Mouse attracted; MiceStats(); virtual ~MiceStats(); }; #endif /* MICESTATS_H_ */ <file_sep>/src/Cheese.cpp /* * Cheese.cpp * * Created on: Apr 25, 2016 * Author: matt */ #include "Cheese.h" Cheese::Cheese(){ cheeseName = "Disarmed!"; tier = 0; amount = 0; cheeseAttractionRate = 0; storeCheese = false; } Cheese::Cheese(string type, int baitTier, int stash, double atr, bool isStoreCheese) { cheeseName = type; tier = baitTier; amount = stash; cheeseAttractionRate = atr; storeCheese = isStoreCheese; } Cheese::~Cheese(){ }
f3d9473df8221a6b857e438e78ef9570a33afdf0
[ "Markdown", "C++" ]
22
C++
mathwiz617/MagChamberSim
b3a8acba6f79b8ccc43fe9be66a8b35482a26a1c
2996da6db50903757594fead4f3934fe9f0f6c14
refs/heads/master
<file_sep># -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-09-08 14:28 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('recipes', '0014_recipe_url'), ] operations = [ migrations.AlterField( model_name='ingredient', name='name', field=models.CharField(max_length=128, unique=True), ), ] <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-09-08 14:00 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('recipes', '0012_auto_20160907_1645'), ] operations = [ migrations.AlterModelOptions( name='ingredient', options={'verbose_name': 'Ingredient', 'verbose_name_plural': '1. Ingredienten'}, ), migrations.AlterModelOptions( name='recipe', options={'verbose_name': 'Recept', 'verbose_name_plural': '2. Recepten'}, ), migrations.AlterModelOptions( name='recipelist', options={'verbose_name': 'Receptenlijst', 'verbose_name_plural': '3. Receptenlijsten'}, ), migrations.AlterModelOptions( name='shoppinglist', options={'verbose_name': 'Boodschappenlijst', 'verbose_name_plural': '4. Boodschappenlijsten'}, ), migrations.AlterField( model_name='recipecame_from', name='name', field=models.CharField(max_length=128, verbose_name='Origin'), ), migrations.AlterField( model_name='recipecategory', name='name', field=models.CharField(max_length=128, verbose_name='Category'), ), ] <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-09-10 08:48 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('recipes', '0016_recipelist_dateadded'), ] operations = [ migrations.AlterModelOptions( name='ingredient', options={'ordering': ['category', 'name'], 'verbose_name': 'Ingredient', 'verbose_name_plural': '1. Ingredienten'}, ), migrations.AlterModelOptions( name='recipe', options={'ordering': ['name'], 'verbose_name': 'Recept', 'verbose_name_plural': '2. Recepten'}, ), migrations.AlterField( model_name='ingredient', name='amount', field=models.DecimalField(decimal_places=2, default=1, max_digits=6), ), ] <file_sep>from django.conf.urls import url from . import views urlpatterns = [ # ex: /polls/ #url(r'^$', views.index, name='index'), url(r'^list$', views.shoppinglist, name = 'shoppinglist'), url(r'^tst$', views.tst, name = 'tst') ] <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-09-07 14:45 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('recipes', '0011_auto_20160907_1640'), ] operations = [ migrations.AlterField( model_name='recipe', name='came_from', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='recipes.RecipeCame_From', verbose_name='Came from'), ), ] <file_sep>from django.shortcuts import render # Create your views here. from django.http import HttpResponse from .models import Recipelist, RecipeIngredient, Shoppinglist, ShoppinglistIngredient, Recipe, Ingredient, RecipeRecipelist from django.db.models import F, FloatField, Sum from math import ceil def shoppinglist(request): SL = ShoppinglistIngredient.objects.filter(shoppinglist__name = 'Shopping List').order_by('ingredient__store', 'ingredient__category') output='<html><table>' Store = '' Cat = '' for i in SL: if i.ingredient.store <> Store: Store = i.ingredient.store output+='<tr><td><h1>%s</h1></td></tr>' % Store if i.ingredient.category.name <> Cat: Cat = i.ingredient.category.name output+='<tr><td><h2>%s</h2></td></tr>' % Cat output+='<tr><td>%s</td><td>%s</td></tr>' % (str(i.ingredient.name), i.amount_to_buy) output+='</table></html>' return HttpResponse(output) def tst(request): recept = Recipe.objects.get(name = 'd') ingredient = Ingredient.objects.get(name = '1') t = RecipeIngredient.objects.filter(recipe = recept, ingredient = ingredient).values('ingredient').annotate(score = Sum('amount')) output = str(t.get(ingredient = ingredient)['score']) for i in t: output += str(i) return HttpResponse(output) ''' output = '' #sl = Shoppinglist.objects.get(name = 'New list2') s = ShoppinglistIngredient.objects.filter(shoppinglist__name = 'MyShoppingList').values( 'ingredient__name').annotate(score = Sum('amount')) for ingredient in s: output += ingredient['ingredient__name'] output += str(ceil(ingredient['score'])) output += str('<br>') return HttpResponse(output) def index(request): r = Recipe.objects.get(name = 'Andere curry') for i in r: output += str(i) return output ''' <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-09-07 07:51 from __future__ import unicode_literals from django.db import migrations, models import recipes.models class Migration(migrations.Migration): dependencies = [ ('recipes', '0005_auto_20160907_0849'), ] operations = [ migrations.AlterField( model_name='recipe', name='time', field=models.IntegerField(default=15, validators=[recipes.models.validate_mod_five]), ), ] <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-09-08 14:35 from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('recipes', '0015_auto_20160908_1628'), ] operations = [ migrations.AddField( model_name='recipelist', name='dateadded', field=models.DateTimeField(blank=True, default=django.utils.timezone.now), ), ] <file_sep>from __future__ import unicode_literals from django.db import models from django.utils.timezone import now from imagekit.models import ImageSpecField from imagekit.processors import ResizeToFill, ResizeToFit from django.core.exceptions import ValidationError from math import ceil # Create your models here. class IngredientCategory(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Meta: ordering = ['name'] class Ingredient(models.Model): name = models.CharField(max_length=128, unique = True) amount = models.DecimalField(default=1, max_digits=6, decimal_places=2) store_choices = (('AH', 'Albert Heijn'), ('SL', 'Sligro')) store = models.CharField(max_length = 2, choices = store_choices, default = 'SL') category = models.ForeignKey(IngredientCategory, on_delete=models.CASCADE) description_of_amount = models.CharField(max_length=128, default = 'Per stuk') price = models.DecimalField(default=1, max_digits=6, decimal_places=2) def __str__(self): # __unicode__ on Python 2 return "%s | %s (%s)" % (self.category, self.name, self.description_of_amount) class Meta: ordering = ['category', 'name'] verbose_name = 'Ingredient' verbose_name_plural = '1. Ingredienten' def validate_mod_five(value): if value % 5 != 0: raise ValidationError( ('Only use time in steps of 5 (0, 5, 10, 15 etc.) - %(value)s does not fall in that category'), params={'value': value}, ) class RecipeCategory(models.Model): name = models.CharField(verbose_name="Category", max_length=128) def __str__(self): return self.name class Meta: ordering = ['name'] class RecipeCame_From(models.Model): name = models.CharField(verbose_name="Origin", max_length=128) def __str__(self): return self.name class Meta: ordering = ['name'] class Recipe(models.Model): name = models.CharField(max_length=128) method=models.TextField(blank=True) dateadded = models.DateTimeField(default=now, blank=True) category = models.ForeignKey(RecipeCategory, on_delete=models.CASCADE) came_from = models.ForeignKey(RecipeCame_From, verbose_name="Came from", on_delete=models.CASCADE) ingredient = models.ManyToManyField(Ingredient, through='RecipeIngredient') time = models.IntegerField(default=15, validators=[validate_mod_five]) url = models.URLField(blank=True) image = models.ImageField(upload_to = 'recipes', blank=True) image_thumbnail = ImageSpecField(source='image', processors=[ResizeToFit(100, 50)], format='JPEG', options={'quality': 90}) image_large = ImageSpecField(source='image', processors=[ResizeToFit(1280, 720)], format='JPEG', options={'quality': 90}) class Meta: verbose_name = 'Recept' verbose_name_plural = '2. Recepten' ordering = ['name'] def _time_category(self): return str(int(10 * ceil(self.time / 10.0))) time_category = property(_time_category) def _get_price(self): price = 0 t = RecipeIngredient.objects.select_related('ingredient').filter(recipe = self) for i in t: price += i.amount / i.ingredient.amount * i.ingredient.price return round(price,2) price = property(_get_price) def __str__(self): # __unicode__ on Python 2 return self.name def get_ingredients(self): t = RecipeIngredient.objects.filter(recipe = self) out = '' for i in t: out+=i.ingredient.name out+='\t' out+=str(i.amount) out+='\t' out+=str(i.ingredient.price) out+='\t' out+=str(i.ingredient.amount) out+='\n' return out #"\n".join([str(i.amount) for i in t]) ingredients = property(get_ingredients) class RecipeIngredient(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) amount = models.DecimalField(default=1, max_digits=10, decimal_places=2) class Recipelist(models.Model): name = models.CharField(max_length=128) recipe = models.ManyToManyField(Recipe, through='RecipeRecipelist') dateadded = models.DateTimeField(default=now, blank=True) def __str__(self): return self.name def _recipes(self): out = '' #"\n".join([str(i.amount) for i in t]) return ', '.join([str(i.recipe.name) for i in RecipeRecipelist.objects.select_related('recipe').filter(recipelist = self)]) #for i in RecipeRecipelist.objects.filter(recipelist = self): #out+=i.recipe.name #return out recipes = property(_recipes) class Meta: verbose_name = 'Receptenlijst' verbose_name_plural = '3. Receptenlijsten' class RecipeRecipelist(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) recipelist = models.ForeignKey(Recipelist, on_delete=models.CASCADE) class Shoppinglist(models.Model): ingredient = models.ManyToManyField(Ingredient, through='ShoppinglistIngredient') name = models.CharField(max_length=128, default = 'Shoppinglist') dateadded = models.DateTimeField(default=now, blank=True) class Meta: verbose_name = 'Boodschappenlijst' verbose_name_plural = '4. Boodschappenlijsten' class ShoppinglistIngredient(models.Model): ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) shoppinglist = models.ForeignKey(Shoppinglist, on_delete=models.CASCADE) amount = models.DecimalField(default=1, max_digits=10, decimal_places=2) def __str__(self): return '%s - %s' % (self.ingredient.name, self.amount) def _amount_to_buy(self): return int(ceil(self.amount)) amount_to_buy = property (_amount_to_buy) <file_sep>from django.contrib import admin from imagekit.admin import AdminThumbnail from django.conf.urls import url from django import forms # Register your models here. from .models import Recipe, Ingredient, RecipeIngredient, Recipelist, RecipeRecipelist, Shoppinglist, ShoppinglistIngredient, IngredientCategory, RecipeCategory, RecipeCame_From from django.db.models import Sum import os.path #admin.site.register(Recipe) #admin.site.register(Ingredient) #admin.site.register(RecipeIngredient) class IngredientAdmin(admin.ModelAdmin): list_display = ('name', 'category', 'amount', 'store', 'description_of_amount', 'price' ) list_filter = ('store', 'category__name') admin.site.register(Ingredient, IngredientAdmin) class IngredientInline(admin.TabularInline): #model=Recipe#.ingredient.through model = RecipeIngredient extra = 1 def add_name_to_button(button_nm = 'Edit...'): """ An edit button, ah... it looks so nice (it does!). """ def edit_button(self, obj): on_click = "window.location='%d';" % obj.id return '<input type="button" onclick="%s" value="%s" />' % (on_click, button_nm) return edit_button class RecipeAdmin(admin.ModelAdmin): list_display = ('name', 'get_recipe_rating', 'link_image', 'time', 'get_category', 'get_came_from', 'price',) edit_button = add_name_to_button('Edit') edit_button.allow_tags = True edit_button.short_description = 'edit' def link_image(self, obj): output = '' try: picture = obj.image.path if os.path.isfile(picture): output = '<a href = "%s"><img src = "%s"</a>' % (obj.image_large.url, obj.image_thumbnail.url) else: output = 'Fout: bestand niet beschikbaar' except: output = 'Nog geen foto' return output def get_recipe_rating(self, obj): ''' gets the rating based on previous usage ''' #SL = ShoppinglistIngredient.objects.filter(shoppinglist__name = 'All ingredients (not aggregated)').values('ingredient').annotate(score = Sum('amount')) rl = Recipelist.objects.filter(name = 'Recipe lists history', recipe = obj).count() return rl link_image.allow_tags = True link_image.short_description = '' def get_category(self, obj): return obj.category.name get_category.short_description = 'Category' def get_came_from(self, obj): return obj.came_from.name get_came_from.short_description = 'Came from' image_display = AdminThumbnail(image_field = 'image_thumbnail') image_display.short_description = '' def method__custom_rendering(self, obj): return "<pre>%s</pre>" % (obj.method,) method__custom_rendering.allow_tags = True method__custom_rendering.short_description = 'Method' readonly_fields = ('dateadded', ) search_fields = ['name'] list_filter = ('time', 'category__name', 'came_from__name') inlines = (IngredientInline,) actions = ['populate_recipelist', 'start_new_week', ] def populate_recipelist(modeladmin, request, queryset): s, created = Recipelist.objects.get_or_create(name = 'Recipe List') #s.save() for recept in queryset.all(): t = RecipeRecipelist.objects.create(recipe = recept, recipelist = s) populate_recipelist.short_description = "Add items to recipe list" def start_new_week(modeladmin, request, queryset): ''' add the recipes that are on the current list to the historical list and delete the recipes and ingredients from the shopping list ''' rl = 'Recipe List' sl1 = 'Shopping List' sl2 = 'All ingredients (not aggregated)' rlo = Recipelist.objects.get(name = rl) s, created = Recipelist.objects.get_or_create(name = 'Recipe lists history') for i in RecipeRecipelist.objects.select_related('recipe').filter(recipelist = rlo): t = RecipeRecipelist.objects.create(recipe = i.recipe, recipelist = s) Recipelist.objects.filter(name = rl).delete() Shoppinglist.objects.filter(name = sl1).delete() Shoppinglist.objects.filter(name = sl2).delete() start_new_week.short_description = "Start a new week and clear all recipes and shopping lists" admin.site.register(Recipe, RecipeAdmin) # The recipelist class RecipeInline(admin.TabularInline): #fieldsets = ('name',) model = RecipeRecipelist extra = 1 class RecipelistAdmin(admin.ModelAdmin): list_display = ('name', 'dateadded', 'recipes', ) readonly_fields = ('name', 'dateadded', ) inlines = (RecipeInline,) actions = ['populate_ingredient_shopping_list'] def populate_ingredient_shopping_list(modeladmin, request, queryset): #Shoppinglist.objects.filter(name = 'MyTempList').delete() s, created = Shoppinglist.objects.get_or_create(name = 'All ingredients (not aggregated)') #s.save() for lijst in queryset.all(): for recept in lijst.recipe.all(): for ingredient in recept.ingredient.all(): t = RecipeIngredient.objects.filter(recipe = recept, ingredient = ingredient).values('ingredient').annotate(score = Sum('amount')) si = ShoppinglistIngredient.objects.create(ingredient = ingredient, shoppinglist = s, amount = t.get(ingredient = ingredient)['score'] / ingredient.amount) Shoppinglist.objects.filter(name = 'Shopping List').delete() SL = ShoppinglistIngredient.objects.filter(shoppinglist__name = 'All ingredients (not aggregated)').values('ingredient').annotate(score = Sum('amount')) s, created = Shoppinglist.objects.get_or_create(name = 'Shopping List') for i in SL: ShoppinglistIngredient.objects.create(ingredient = Ingredient.objects.get(id=i['ingredient']), shoppinglist = s, amount = i['score']) populate_ingredient_shopping_list.short_description = "Create shopping list for selected items" admin.site.register(Recipelist, RecipelistAdmin) class IngredientInline2(admin.TabularInline): list_display = ('amount', 'amount_to_buy') model = ShoppinglistIngredient extra = 1 class ShoppinglistAdmin(admin.ModelAdmin): list_display = ('name', 'dateadded') inlines = (IngredientInline2,) readonly_fields = ('name', 'dateadded') admin.site.register(Shoppinglist, ShoppinglistAdmin) admin.site.register(IngredientCategory) admin.site.register(RecipeCategory) admin.site.register(RecipeCame_From) <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-09-07 10:09 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('recipes', '0007_ingredientcategory'), ] operations = [ migrations.RemoveField( model_name='ingredientcategory', name='ingredient', ), migrations.AddField( model_name='ingredient', name='category', field=models.ForeignKey(default=0, on_delete=django.db.models.deletion.CASCADE, to='recipes.IngredientCategory'), preserve_default=False, ), ] <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-08-12 18:05 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Ingredient', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=128)), ('amount', models.DecimalField(decimal_places=2, default=1, max_digits=5)), ('store', models.CharField(choices=[('AH', 'Albert Heijn'), ('SL', 'Sligro')], default='SL', max_length=2)), ('description_of_amount', models.CharField(max_length=128)), ('price', models.DecimalField(decimal_places=2, default=1, max_digits=5)), ], ), migrations.CreateModel( name='Recipe', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=128)), ('method', models.TextField()), ('time', models.IntegerField(default=15)), ], ), migrations.CreateModel( name='RecipeIngredient', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('amount', models.DecimalField(decimal_places=2, default=1, max_digits=5)), ('ingredient', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='recipes.Ingredient')), ('recipe', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='recipes.Recipe')), ], ), migrations.CreateModel( name='Recipelist', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=128)), ], ), migrations.CreateModel( name='RecipeRecipelist', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('recipe', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='recipes.Recipe')), ('recipelist', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='recipes.Recipelist')), ], ), migrations.CreateModel( name='Shoppinglist', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(default='Shoppinglist', max_length=128)), ('dateadded', models.DateTimeField(blank=True, default=django.utils.timezone.now)), ], ), migrations.CreateModel( name='ShoppinglistIngredient', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('amount', models.DecimalField(decimal_places=2, default=1, max_digits=5)), ('ingredient', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='recipes.Ingredient')), ('shoppinglist', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='recipes.Shoppinglist')), ], ), migrations.AddField( model_name='shoppinglist', name='ingredient', field=models.ManyToManyField(through='recipes.ShoppinglistIngredient', to='recipes.Ingredient'), ), migrations.AddField( model_name='recipelist', name='recipe', field=models.ManyToManyField(through='recipes.RecipeRecipelist', to='recipes.Recipe'), ), migrations.AddField( model_name='recipe', name='ingredient', field=models.ManyToManyField(through='recipes.RecipeIngredient', to='recipes.Ingredient'), ), ]
2c85902430aa6a8841bb205f6b70114dd002267c
[ "Python" ]
12
Python
namrehkok/cookbook
b32c0b8221e77fc68c9dce0f32589126e1c022df
7dee4ebab30ced666894733d3e04dff0d29b9e61
refs/heads/master
<file_sep>import sys import os from smartasic import BasicModule,Port from DynamicGenerator import DynamicGenerator from pathlib import Path """ if isDemux = 1 then this module for Multiplexor and isDemux= 0 then Demultiplexor """ class Multiplexor(BasicModule): def Create_dic_of_variable(self): self.variable_dict['NumClients']=self.NumClients self.variable_dict['PortWidth']=self.PortWidth self.variable_dict['isDemux']=self.isDemux self.variable_dict['isBinary']=self.isBinary def get_body(self): dynamicgenerator=DynamicGenerator(self.variable_dict,self.multiplexor_body) self.body+=dynamicgenerator.parse_body() self.body=self.body.replace("name",self.name) dynamicgenerator.silentremove() return self.body def get_verilog(self): return self.get_body() def main(self): self.write_to_file(self.get_verilog()) return self.get_verilog() def __init__(self, portwidth, numclients, isdemux, isbinary): self.PortWidth = portwidth self.NumClients = numclients self.isDemux = isdemux self.isBinary = isbinary self.body="" self.variable_dict={} self.Create_dic_of_variable() if self.isDemux==1: self.name="AH_Multiplexor"+"_"+str(portwidth)+"_"+str(numclients) else: self.name="AH_Demultiplexor"+"_"+str(portwidth)+"_"+str(numclients) self.multiplexor_body=""" module name ( /f_f/ if isDemux == 1: code = "\\n".join(["in_data"+str(i)+"," for i in range(NumClients)]) code += "\\nout_data,\\n mux_select );" else: code = "\\n".join(["out_data" + str(i) + "," for i in range(NumClients)]) code += "\\n in_data,\\n demux_select );" /f_f/ /f_f/ if isDemux == 1: code = "\\n".join([" input ["+str(PortWidth-1)+":0] in_data"+str(i)+";" for i in range(NumClients)]) code += "\\n output ["+str(PortWidth-1)+":0] out_data;\\n input ["+(str(NumClients-1) if isBinary ==1 else str(int(ceil(log2(NumClients-1)))))+":0] mux_select;" else: code = "\\n".join([" output [" + str(PortWidth - 1) + ":0] out_data" + str(i) + ";" for i in range(NumClients)]) code += "\\n input ["+str(PortWidth-1)+":0] in_data;\\n input ["+(str(NumClients-1) if isBinary == 1 else str(int(ceil(log2(NumClients-1)))))+":0] demux_select;" /f_f/ /f_f/ if isDemux == 1: code = " wire assign out_data = "+str(PortWidth)+"'d0 |" + " |\\n ".join(["(mux_select"+("["+str(i)+"]" if isBinary == 1 else "= "+str(int(ceil(log2(self.NumClients))))+"'d"+str(i)+"") +"? in_data"+str(i)+" : "+str(PortWidth)+"'d0)" for i in range(NumClients)]) else: code = "\\n".join(["wire assign out_data"+str(i)+" = demux_select"+("["+str(i)+"]" if isBinary ==1 else "=="+str(int(ceil(log2(NumClients))))+"'d"+str(i))+"? in_data : 25'd0;" for i in range(NumClients)]) /f_f/ end module """ mux=Multiplexor(int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4])) mux.main()<file_sep>from templates import pipe_body_template import argparse parser = argparse.ArgumentParser() parser.add_argument("-isb", help="input skid buffer", action="store_true") parser.add_argument("-wid", help="width of data", type=int) args = parser.parse_args() class Pipe: def __init__(self): self.Width = args.wid self.body = None def pipe(self): register = "reg rd_valid;\nreg ["+str(self.Width-1)+":0] rd_data;\nwire wr_ready;" code = "assign wr_ready = rd_ready || !rd_valid;\n" \ "always @(posedge clk or negedge rst) begin\n\tif (!rst) begin\n\t\t" \ "rd_valid <= 1'b0;\n\tend else begin\n\t\t" \ "if (wr_ready) begin\n\t\t\t" \ "rd_valid <= wr_valid;\n\t\t" \ "end\n\t" \ "end\nend\n" code += "always @(posedge clk) begin\n\tif (wr_ready && wr_valid) begin" \ "\n\t\trd_data["+str(self.Width-1)+":0] <= wr_data["+str(self.Width-1)+":0];" \ "\n\tend\nend" self.body = self.body.replace("//PIPE", code) def skid(self): register = "reg wr_ready;\nreg skid_flop_wr_ready;\nreg skid_flop_wr_valid;\nreg ["+str(self.Width-1)+":0] skid_flop_wr_data;" code = "always @(posedge clk or negedge rst) begin\n\tif (!rst) begin" \ "\n\n\twr_ready <= 1'b1;\n\t\tskid_flop_wr_ready <= 1'b1;" \ "\n\tend else begin" \ "\n\t\twr_ready <= rd_ready;\n\t\tskid_flop_wr_ready <= rd_ready;" \ "\n\tend\nend\n" code += "always @(posedge clk or negedge rst) begin\n\t" \ "if (!rst) begin\n\t\tskid_flop_wr_valid <= 1'b0;" \ "\n\tend else begin\n\t\tif (skid_flop_wr_ready) begin" \ "\n\t\t\tskid_flop_wr_valid <= wr_valid;\n\t\tend\n\tend" \ "\nend\nassign rd_valid = (skid_flop_wr_ready) ? wr_valid : skid_flop_wr_valid;\n" code += "always @(posedge clk) begin\n\t" \ "if (skid_flop_wr_ready & wr_valid) begin\n\t\tskid_flop_wr_data["+str(self.Width-1)+":0] <= wr_data["+str(self.Width-1)+":0];" \ "\n\tend\nend\nassign rd_data["+str(self.Width-1)+":0] = (skid_flop_wr_ready) ? wr_data["+str(self.Width-1)+":0] : skid_flop_wr_data["+str(self.Width-1)+":0];\n" self.body = self.body.replace("//SKID", code) self.body = self.body.replace("SKID_REGISTERS", register) def get_body(self): self.body = pipe_body_template self.body = self.body.replace("WIDEWIDTH - 1", str(self.Width -1)) self.pipe() if args.isb: self.skid() def __str__(self): self.get_body() return self.body print(Pipe()) <file_sep>from enum import Enum A = None if A: print(A)<file_sep>import copy import yaml from AH_RoundRobinArbiter import RoundRobinArbiter from AH_SnoopableFIFO import SnoopableFIFO from AH_Multiplexor import Multiplexor from AH_Decoder import Decoder from smartasic import BasicModule from BusParser import BusParser import sys print(sys.path) class OrderedSwitch(BasicModule): def Create_dic_of_variable(self): self.variable_dict = self.__dict__ def get_body(self): object_dict = {} #============================================================================= # First we create the snoopable FIFO basic object with connection rules # and we update the dict spf1 = SnoopableFIFO(self.dsPktSize, self.SnoopDepth, self.upResponseDecodableFieldWidth) spf1.smart_connectionop("astob", "wr_","egress0_dspkt_") spf1.smart_connectionop("astob", "rd_", "egress0_dspkt_") spf1.smart_connectionop("astob", "snoop_", "egress0_dspkt_") spf1.add_connection_flat("svalid","{ingress_decoded[1], ingress_decoded[2], ingress_decoded[3]}") #print(spf1.dict) object_dict.update({"u_egress0_snoopablefifo_"+str(self.dsPktSize)+"_"+str(self.SnoopDepth)+"_"+str(self.upResponseDecodableFieldWidth) : spf1}) #============================================================================= #============================================================================= #A deep copy of each new snoopableFIFO object is created from first massaged # object. The object_dict.update is called each time. for i in range(1, self.NumberOfEgress): curr_obj = copy.deepcopy(spf1) curr_obj.smart_connectionop("astob", "egress0" , "egress"+str(i)) # print(curr_obj.get_object_declaration_str("hello")) object_dict.update({"u_egress"+str(i)+"_snoopablefifo_" + str(self.dsPktSize) + "_" + str(self.SnoopDepth) + "_" + str(self.upResponseDecodableFieldWidth): curr_obj}) #============================================================================= #Now two mux objects are created and necessary changes in cnames are done. c = 1 #============================================================================= mux1 = Multiplexor(self.NumberOfEgress, self.dsPktSize,1,1) mux1.smart_connectionop("demux", "egr[0-9]{1,10}" , "uspkt") mux2 = Multiplexor(self.NumberOfEgress, self.dsPktSize,1,0) mux2.smart_connectionop("demux","egr[0-9]{1,10}", "dspkt") #============================================================================= #decoder is instantiated # ============================================================================= decoder = Decoder(self.NumberOfEgress, self.upPktSize) #============================================================================ #arbiter is instantiated. # ============================================================================= arbiter = RoundRobinArbiter(self.NumberOfEgress) ar_req_code = "{"+"\n".join(["egress"+str(i)+"_us_pkt_valid," for i in range(self.NumberOfEgress)])+"}" arbiter.add_connection_flat("req",ar_req_code) arbiter.add_connection_flat("grant","egress_arbed["+str(self.NumberOfEgress-1)+":0]") #print(arbiter.get_object_declaration_str("hh")) #============================================================================ snoop_dec = "" for k,v in object_dict.items(): snoop_dec += v.get_object_declaration_str(k) # ============================================================================= #String replacements in order body # ============================================================================= self.body = self.body.replace("//snoop_decs", snoop_dec) self.body = self.body.replace("//arbiter_dec" , arbiter.get_object_declaration_str("u_arbiter_4")) self.body = self.body.replace("//decoder_dec", decoder.get_object_declaration_str("u_decoder_"+ str(self.NumberOfEgress) + "_" + str(self.dsDecodableFieldWidth))) self.body = self.body.replace("//demux_dec1", mux1.get_object_declaration_str("u_demux_"+ str(self.NumberOfEgress) + "_" + str(self.dsPktSize))) self.body = self.body.replace("//demux_dec2", mux1.get_object_declaration_str("u_demux_"+ str(self.NumberOfEgress) + "_" + str(self.dsPktSize))) #============================================================================= #Everyting is added to obj_list #============================================================================= obj_list = list(object_dict.values()) obj_list.append(mux1) obj_list.append(mux2) obj_list.append(decoder) self.dict , self.wire_dict = self.populate_wire_and_ports(obj_list) def add_ports_from_bus(self): self.get_all_key_value_pairs(self.dict) def __init__(self, number_of_egress,ds_packet_size, ups_packet_size, ds_decodable_field_width, ups_response_decodable_field_width, snoopdepth): self.NumberOfEgress = number_of_egress self.dsPktSize = ds_packet_size self.SnoopDepth = snoopdepth self.upPktSize = ups_packet_size self.dsDecodableFieldWidth = ds_decodable_field_width self.upResponseDecodableFieldWidth = ups_response_decodable_field_width self.name = "AH_"+self.__class__.__name__+"_"+str(number_of_egress)+"_"+str(ds_packet_size)+"_"+str(ups_packet_size)+"_"+str(ds_decodable_field_width)+"_"+str(ups_response_decodable_field_width) self.dict = {} self.wire_dict = {} BasicModule.__init__(self, self.name) self.body = """ // 4 --> number of egress. // 25 -> ds packet size // 20 -> upstream packet size. // 10 -> address or downstream decodable field width. // 12 -> id or ordering and upstream-response decodable field width. // These numbers are unique - if you look into decoder instnce and demux instance - you will find them onlye // =========================================================================================== // =========================================================================================== // ================================================ // ============================================================================================================================ // Identify the ADDR field or similar downstream field which can help decide // the direction of transaction // 4 --> decode arm, 13 --> decode-field (typically address) ID. //TODO:Here we are assuming that upper most field contains address. //It might not be so in most cases. So the ordered-switch does need to have //that passed as a parameter. We need to decide whether ordered switch //reflects the name there. //TODO: Again each address aperture will be different and there's no way we //can pass this as argument. Even if we do, somewhere we need to provide it. //In current approach, the apertures will be built inside decoder. //Now ap_00001 can be a nomenclature on full Ahant's library. // 4 --> number of egress. // 25 -> ds packet size // 20 -> upstream packet size. // 10 -> address or downstream decodable field width. // 12 -> id or ordering and upstream-response decodable field width. // These numbers are unique - if you look into decoder instnce and demux instance - you will find them onlye AH_decoder_4_10 u_decoder_4_10_ap_00001 ( .ingress_pkt_field (ingress_ds_pkt[24:24-9]), .decoded_binary (ingress_decoded[3:0]) .dec_err () //decoder_obj //u_demux_4_25 = AH_demux(4, 25) //u_demux.port_connect() 1. Instance the class of Python and create an object - pass the parms required 2. Access the port dict - add stuffs to it may be so that it reprensts the connectivity picture 3. call class_instance.port_connect method - it prints the ports in veirlog syntax and updates on calling class the wire dictionary, and it's own port dictionary may be. // 4 --> number of egress. // 25 -> ds packet size // 20 -> upstream packet size. // 10 -> address or downstream decodable field width. // 12 -> id or ordering and upstream-response decodable field width. //demux_dec1 // 25 --> width of fifo // 32 --> depth of FIFO - TODO: Again another parameter. It's not possible // to reflect all of them in module name. It's better to probably keep a param // list inside and create a .h fle for the same also. //=================================================================================== //snoop_decs wire assign egress3_ds_pkt_valid = ingress_decode[0] & !block_egress3_ds_pkt & egress3_ds_pkt_valid_pre; wire assign egress2_ds_pkt_valid = ingress_decode[0] & !block_egress2_ds_pkt & egress2_ds_pkt_valid_pre; wire assign egress1_ds_pkt_valid = ingress_decode[0] & !block_egress1_ds_pkt & egress1_ds_pkt_valid_pre; wire assign egress0_ds_pkt_valid = ingress_decode[0] & !block_egress0_ds_pkt & egress0_ds_pkt_valid_pre; // TODO: Downstream path is complete more or less. // Upstream path needs to be done. //=================================================================================== //arbiter_dec =================================================================================== // 4 --> number of egress. // 25 -> ds packet size // 20 -> upstream packet size. // 10 -> address or downstream decodable field width. // 12 -> id or ordering and upstream-response decodable field width. //demux_dec2 //=================================================================================== // While sending upstream response valid - // For each egress channel- // if we find the guy has won grant and carries an entry with same trackable field(ID) // as the one stored in FIFO, we let it go. wire assign snoopfifo_rd_legal = 1'b0 | (egress_arbed[0] & egress0_snoopfifo_rd_valid & (egress0_snoopfifo_rd[11:0] = ingress_us_pkt[11:0]) ) | (egress_arbed[1] & egress1_snoopfifo_rd_valid & (egress1_snoopfifo_rd[11:0] = ingress_us_pkt[11:0]) ) | (egress_arbed[2] & egress2_snoopfifo_rd_valid & (egress2_snoopfifo_rd[11:0] = ingress_us_pkt[11:0]) ) | (egress_arbed[3] & egress3_snoopfifo_rd_valid & (egress3_snoopfifo_rd[11:0] = ingress_us_pkt[11:0]) ) | ); /f_f/ code = "\\n"+"\\n".join(["(egress_arbed[0] & egress0_snoopfifo_rd_valid & (egress0_snoopfifo_rd[upResponseDecodableFieldWidth - 1:0] = ingress_us_pkt[:0]) )" for i in range(NumberOfEgress)]) /f_f/ wire assign ingress_us_pkt_valid = arbed_out_valid & snoop_fifo_rd_legal; wire assign arbed_out_ready = ingress_us_pkt_ready & snoop_fifo_rd_legal; //TODO: watch out for timing in this area and think about simplifying the logic. wire assign egress0_snoopfifo_rd_ready = snoopfifo_rd_legal; wire assign egress1_snoopfifo_rd_ready = snoopfifo_rd_legal; wire assign egress2_snoopfifo_rd_ready = snoopfifo_rd_legal; wire assign egress3_snoopfifo_rd_ready = snoopfifo_rd_legal; endmodule // 25 --> width of fifo // 32 --> depth of FIFO - TODO: Again another parameter. It's not possible // to reflect all of them in module name. It's better to probably keep a param // list inside and create a .h fle for the same also. //Identify the ID or trackable field from downstream packet.Create snoop valid //and match signals from downstream request valid. // Instantiate the snoop FIFO - which can create a snoop match logic. Connect // the snoop match to decoder/demux output there. The decoder will have only // legal requests to egress arms forwarded downstream. // Instantiaate upstream decoder (based on trackable field as ID) // // Instantiate the upstream arbiter. """ t = OrderedSwitch(int(sys.argv[1]), int(sys.argv[2]),int(sys.argv[3]) ,int(sys.argv[4]), int(sys.argv[5]), int(sys.argv[6])) t.main() #with open('../order_port.yaml','w') as f: # f.write(yaml.dump(t.dict)) #print(yaml.dump(t.dict)) #print("1"*500) t.add_ports_from_bus() #print(yaml.dump(t.wire_dict)) p , q = t.get_port_str() #print(p) ##print(q)i <file_sep>import sys import os from smartasic import BasicModule,Port from DynamicGenerator import DynamicGenerator from BusParser import BusParser from pathlib import Path class LruArbiter(BasicModule,BusParser): #========================================================================= # Overwrite the add_ports_from_bus method here. # Create the instance of busparser class. # Then use the widop method to change the port width req, gnt, gnt_busy signals. #========================================================================= ###### creating dictonary of variable def Create_dic_of_variable(self): self.variable_dict['Num_Clients']=self.Num_Clients def add_ports_from_bus(self): BasicModule.add_ports_from_bus(self) self.widop_flat("req",self.Num_Clients) self.widop_flat("gnt",self.Num_Clients) self.widop_flat("gnt_busy",self.Num_Clients) self.get_all_key_value_pairs(self.dict) def get_body(self): dynamicgenerator=DynamicGenerator(self.variable_dict,self.body) self.body+=dynamicgenerator.parse_body() self.body = self.body.replace("NUMCLIENTS - 1", str(self.Num_Clients -1)) dynamicgenerator.silentremove() #def get_verilog(self): # modulecode=self.get_header() # self.get_body() # modulecode=modulecode.replace("BODY",self.body) # return modulecode #def main(self): # self.write_to_file(self.get_verilog()) # return self.get_verilog() def __init__(self,num_clients,path_of_yaml=None,bus_name=None): self.bus_name=bus_name self.Num_Clients=num_clients if path_of_yaml is None: path_of_yaml = "../../../smartasic2/refbuses/arbiter.yaml" bus_name = "arbiter" self.name="AH_"+self.__class__.__name__+"_"+str(num_clients) BasicModule.__init__(self, self.name) BusParser.__init__(self,self.load_dict(path_of_yaml),bus_name) #self.Create_dic_of_variable() #self.add_ports_from_bus(path_of_yaml,bus_name) self.body = """ /f_f/ code = "\\n"+"\\n".join(["req ["+str(Num_Clients-1)+":0] req"+str(i)+"_used_status;" for i in range(Num_Clients)]) /f_f/ always @(posedge clk, negedge rstn) begin if(~rstn) begin /f_f/ code="" for i in range(Num_Clients): code+="\\n\treq"+str(i)+"_used_status <= "+str(Num_Clients)+"'d"+str(Num_Clients-i)+";" /f_f/ end else begin /f_f/ code="\\n\tgnt_pre["+str(Num_Clients-1)+":0] = "+str(Num_Clients)+"'d0\\n\treq_int["+str(Num_Clients-1)+":0]= req["+str(Num_Clients)+":0] & {"+str(Num_Clients)+"{gnt_busy}};" for i in range(Num_Clients): code+="\\n\tif(req["+str(i)+"]) begin" code+="\\n\t\tgnt_pre["+str(i)+"] = (req"+str(i)+"_used_status=="+str(Num_Clients)+") ? 1'b1 |\\n" for j in range(Num_Clients): if i==j: continue else: code+="\\n\t((req"+str(j)+" & (req"+str(j)+"_used_status > req"+str(i)+"_used_status)) ?1'b0 |" code+="\\n\t\t1'b1;\\n\tend" /f_f/ always @(req, gnt_busy) begin /f_f/ code="\\n\tgnt_pre["+str(Num_Clients-1)+":0] = "+str(Num_Clients)+"'d0\\n\treq_int["+str(Num_Clients-1)+":0]= req["+str(Num_Clients)+":0] & {"+str(Num_Clients)+"{gnt_busy}};" for i in range(Num_Clients): code+="\\n\tif(req["+str(i)+"]) begin" code+="\\n\t\tgnt_pre["+str(i)+"] = (req"+str(i)+"_used_status=="+str(Num_Clients)+") ? 1'b1 |\\n" for j in range(Num_Clients): if i==j: continue else: code+="\\n\t((req"+str(j)+" & (req"+str(j)+"_used_status > req"+str(i)+"_used_status)) ?1'b0 |" code+="\\n\t\t1'b1;\\n\tend" /f_f/ assign gnt[NUMCLIENTS - 1:0] = gnt_pre[NUMCLIENTS - 1:0]; """ lb=LruArbiter(int(sys.argv[1]),sys.argv[2],sys.argv[3]) lb.main() <file_sep># ===================================================================================================================================== # Port class SW architecture # ===================================================================================================================================== class BusParser: # ===================================================================================================================================== # Initialize the Bus class # bus_name loaded from yaml. # prefix is added to define the bus, # # cpu2usb_controller_uart_uartn_txd (this is a port or signal name on the verilog module) # cpu2usb_controller_uart_uartn_rxd (this is a port or signal name on the verilog module) # cpu2usb_controller_uart_uartn_cts (this is a port or signal name on the verilog module) # cpu2usb_controller_uart_uartn_rts (this is a port or signal name on the verilog module) # prefix --> cpu2usb_controller # # bus --> uart # any hierarchy after that is missing here but it might come for AXI kind of other buses # # # normally the master2slave_* format is used. # During object init, world_view string is loaded to both prefix and prefloat keys (btw, these keys are not there in original yaml, so required to created.) # ===================================================================================================================================== def __init__ (self, bus_name, world_view): pass # ===================================================================================================================================== # prints the loaded bus object hash at any point of time. This method can be used during debug. def print (self, bus_name): # ===================================================================================================================================== # dumps the bus back in yaml format. This method should be part of all the module classes that uses buses (all most all of them.) # The dumped buses can be used by senior architects and designers to figure out the state of affairs. def dyaml(self, bus_name): # ===================================================================================================================================== # This just flips the entire bus # expression is signal name written in bus_name.hier_1_ch.hier_2_ch....signal_1_name mode. def flip(self, expression): # ===================================================================================================================================== # change width of particular signal. # TODO: We need to put some formulae here so that associated signals can change width together # For e.g., data and strobe are related and they should be able to change together. # similarly, read and write port width is similar and they should be able to be changed together. # # Here expression is the signal in hierarchical way. And we should be able to search the signal directly. # def widop(self, expression, width_new): # ===================================================================================================================================== # Bus connectivity architecture # connects the bus to a prefloat value - the prefloat value is the name with which the wire is floated. # Ultimately when a bunch of objects are modules are instantiated in a class, the prefloat value wires will be used to dump all the wires def prefixop(self, expression, prefix): pass def prefloatop(self, expression, prefloat): pass # ===================================================================================================================================== # port-map opertor -- <file_sep>from BusParser import BusParser import copy trial = BusParser("arbiter.yaml" ,"arbiter") trial.dyaml("loaded_arbiter.yaml") trial.remove_sub_dict("astob.snoop") trial.add_super_node("astob.wr","ingress") trial.add_super_node("astob.rd","ingress") trial.flip_op("astob.ingress") trial.copy("astob.ingress" , "egress0") trial.copy("astob.egress0" , "egress1") trial.copy("astob.egress0" , "egress2") trial.copy("astob.egress0" , "egress3") trial.dyaml("trial.yaml") trial.remove_sub_dict("astob.egress0") trial.remove_sub_dict("astob.egress1") trial.remove_sub_dict("astob.egress2") trial.remove_sub_dict("astob.egress3") #trial.dyaml("trial1.yaml") trial.remove_node("astob.ingress") trial.dyaml("trial1.yaml") trial.add_sub_dict("astob.snoop",temp) trial.flip_op("astob.snoop") trial.flip_op("astob") trial.dyaml("**astob.yaml") <file_sep>Arbiter.py: def shift_request(self): Arbiter.py: def shift_grant(self): Arbiter.py: def grant_signal(self): Arbiter.py: def rotate(self): Arbiter.py: def declare_weight_inputs(self): Arbiter.py: def declare_weight_vectors(self): Arbiter.py: def declare_weight_registers(self): Arbiter.py: def get_body(self): Arbiter.py: def update_weight_code(self): Arbiter.py: def __str__(self): CAM.py: def get_body(self): CAM.py: def request_declaration(self): CAM.py: def cam_locations(self): CAM.py: def cam_write(self): CAM.py: def assign_snoop(self): CAM.py: def snoop_cam(self): CAM.py: def assign_freeup(self): CAM.py: def __str__(self): Encoder.py: def __init__(self): Encoder.py: def binary2gray(self): Encoder.py: def gray2binary(self): Encoder.py: def onehot2binary(self): Encoder.py: def get_body(self): Encoder.py: def __str__(self): Multiplexor.py: def get_body(self): Multiplexor.py: def declare_ports(self): Multiplexor.py: def declare_vectors(self): Multiplexor.py: def assign_data(self): Multiplexor.py: def __str__(self): OrderingPoint.py: def module_declaration(self): OrderingPoint.py: def io_declaration(self): OrderingPoint.py: def assign_wires(self): OrderingPoint.py: def get_body(self): OrderingPoint.py: def __str__(self): PacketConverter.py: def get_body(self): PacketConverter.py: def declaration(self): PacketConverter.py: def add_collated(self): PacketConverter.py: def assign_data(self): PacketConverter.py: def __str__(self): Pipe.py: def __init__(self): Pipe.py: def pipe(self): Pipe.py: def skid(self): Pipe.py: def get_body(self): Pipe.py: def __str__(self): smartasic.py: def get_declaration(self): smartasic.py: def __str__(self): smartasic.py: def get_port_str(self): smartasic.py: def get_header(self): smartasic.py: def update(self): smartasic.py: def get_body(self): smartasic.py: def get_fifo_v(self): smartasic.py: def __str__(self): Snoopable_FIFO.py: def get_body(self): Snoopable_FIFO.py: def declare_register(self): Snoopable_FIFO.py: def assign_loc(self): Snoopable_FIFO.py: def write_loc(self): Snoopable_FIFO.py: def assign_read(self): Snoopable_FIFO.py: def assign_snoop_match(self): Snoopable_FIFO.py: def __str__(self): <file_sep>from templates import ordering_point_template import sys class OrderingPoint: def __init__(self, numclients): self.NumClients = numclients self.body = None def module_declaration(self): code = "\n".join(["decoded_req"+str(i)+"," for i in range(self.NumClients)]) code += "\n"+"\n".join(["snoop_match" + str(i) + "," for i in range(self.NumClients)]) code += "\n"+"\n".join(["legal_decoded_req" + str(i) + "," for i in range(self.NumClients)]) self.body = self.body.replace("//MODULE_DEC", code) def io_declaration(self): code = "\n".join(["input decoded_req"+str(i)+";" for i in range(self.NumClients)]) code += "\n" + "\n".join(["input snoop_match" + str(i) + ";" for i in range(self.NumClients)]) code += "\n" + "\n".join(["output legal_decoded_req" + str(i) + ";" for i in range(self.NumClients)]) self.body = self.body.replace("//I/O_DEC", code) def assign_wires(self): code = "\n" for i in range(self.NumClients): code += "wire assign legal_decoded_req"+str(i)+" =(\n"+"|\n".join(["snoop_match"+str((i+j)%self.NumClients) for j in range(self.NumClients)])+") ? 1'b0 : 1'b1;\n\n" self.body = self.body.replace("//WIRE_ASSIGN", code) def get_body(self): self.body = ordering_point_template self.body = self.body.replace("NUMCLIENTS", str(self.NumClients)) self.module_declaration() self.io_declaration() self.assign_wires() def __str__(self): self.get_body() return self.body print(OrderingPoint(int(sys.argv[1]))) <file_sep>from templates import mux_body_template from math import ceil, log2 import sys class Multiplexor: def __init__(self, portwidth, numclients, isdemux, isbinary): self.PortWidth = portwidth self.NumClients = numclients self.isDemux = isdemux self.body = None self.isBinary = isbinary def get_body(self): self.body = mux_body_template self.body = self.body.replace("NAME", "mux" if self.isDemux is None else "demux") self.body = self.body.replace("MUXPORTWIDTH", str(self.PortWidth)) self.body = self.body.replace("MUXNUMCLIENTS", str(self.NumClients)) self.declare_ports() self.declare_vectors() self.assign_data() def declare_ports(self): if not self.isDemux: code = "\n".join(["in_data"+str(i)+"," for i in range(self.NumClients)]) code += "\nout_data,\nmux_select" else: code = "\n".join(["out_data" + str(i) + "," for i in range(self.NumClients)]) code += "\nin_data,\ndemux_select" self.body = self.body.replace("//PORT_DECLARATION", code) def declare_vectors(self): if not self.isDemux: code = "\n".join(["input ["+str(self.PortWidth-1)+":0] in_data"+str(i)+";" for i in range(self.NumClients)]) code += "\noutput ["+str(self.PortWidth-1)+":0] out_data;\ninput ["+(str(self.NumClients-1) if not self.isBinary else str(int(ceil(log2(self.NumClients-1)))))+":0] mux_select;" else: code = "\n".join(["output [" + str(self.PortWidth - 1) + ":0] out_data" + str(i) + ";" for i in range(self.NumClients)]) code += "\ninput ["+str(self.PortWidth-1)+":0] in_data;\ninput ["+(str(self.NumClients-1) if not self.isBinary else str(int(ceil(log2(self.NumClients-1)))))+":0] demux_select;" self.body = self.body.replace("//VECTOR_DECLARATION", code) def assign_data(self): if not self.isDemux: code = "wire assign out_data = "+str(self.PortWidth)+"'d0 |" + " |\n ".join(["(mux_select"+("["+str(i)+"]" if not self.isBinary else "= "+str(int(ceil(log2(self.NumClients))))+"'d"+str(i)+"") +"? in_data"+str(i)+" : "+str(self.PortWidth)+"'d0)" for i in range(self.NumClients)]) else: code = "\n".join(["wire assign out_data"+str(i)+" = demux_select"+("["+str(i)+"]" if not self.isBinary else "=="+str(int(ceil(log2(self.NumClients))))+"'d"+str(i))+"? in_data : 25'd0;" for i in range(self.NumClients)]) self.body = self.body.replace("//ASSIGN_DATA", code) def __str__(self): self.get_body() return self.body print(Multiplexor(int(sys.argv[1]), int(sys.argv[2]), sys.argv[3], sys.argv[4])) <file_sep>#============================================================================================= # Class Dynamic Generator - The chief functionality of this class to be able to take a piece # of code as string and able to run it as any other python code and return the output string # We achieve this today by writing into py file and getting another output file and write # back to main file. # TODO: In future, find out a better way to achieve this. #============================================================================================= import os from datetime import datetime #### import datatime class DynamicGenerator: """ body_data -> actual template means if we go for LruArbiter module, we are passing body template of LruArbiter module. dic -> dictonary of variable we are using in Module, it is used when we are creating temporary python file. """ def __init__(self,dic,body_data): self.body_data=body_data self.dic=dic self.temp_py_file="" self.temp_txt_file="" def parse_body(self): main_body="" split_body=self.body_data.split("/f_f/") # /f_f/ is an expression, based on this we are splitinng the body into a list. for b in range(len(split_body)): """ if the index is odd then we process odd position code, dumped into pyhton code then process into text file. otherwise just concat as string handleing """ if b%2==0: main_body+=split_body[b] else: main_body+=self.temporary_pyfile(self.dic,split_body[b]) return main_body def temporary_pyfile(self,dic,body_data): time_current=datetime.now().strftime('%H_%M_%S') code="" for x,y in dic.items(): code+=x+"="+str(y)+"\n" ## here we process variable to temp python code+="\n"+body_data+"\nprint(code)" self.temp_py_file="temp_"+time_current+".py" # creting temporay pyhton based on time to handle mutithreading with open(self.temp_py_file,'w') as f: #Add package calls at top of the file. #f.write("import yaml") f.write(code) f.close() self.temp_txt_file="output_"+time_current+".txt" # creating temporary text file from where we retrive output and processed to verilog file. cmd="python "+self.temp_py_file os.system(cmd+'>'+self.temp_txt_file) # running python file using os.system return self.temporary_txtfile() """ method for retrive output from temporary text file, and copy into body """ def temporary_txtfile(self): lines="" fp=open(self.temp_txt_file,'r') for p in fp: lines+=p return lines """ after processing all operation removing all temporary file """ def silentremove(self): try: # os.remove(self.temp_py_file) # os.remove(self.temp_txt_file) os.system("rm temp_*") os.system("rm output_*") except: raise Exception("file not found") <file_sep><<<<<<< HEAD import os from enum import Enum from math import log2 from templates2 import module_template from templates2 import fifo_body_template from BusParser import BusParser from pathlib import Path class Port: class Direction(Enum): INPUT = "input" OUTPUT = "output" INOUT = "inout" def __init__(self, name, direction, width): """ if not isinstance(direction, Port.Direction): raise TypeError('direction must be an instance of Port.Direction') """ if width < 1: raise TypeError('width should be > 0') self.name = name self.direction = direction self.width = width def get_declaration(self): if self.width == 1: return "{0} {1};".format(self.direction, self.name) else: return "{0} [{1}:0] {2};".format(self.direction, self.width - 1, self.name) def __str__(self): return self.get_declaration() class BasicModule: def __init__(self, name): self.name = name self.Ports = [] self.add_port("clk", "input", 1) self.add_port("rstn", "input", 1) def add_port(self, name, direction, width): self.Ports.append(Port(name, direction, width)) def get_port_str(self): # port_objs = [self.__dict__[name] for name in self.__dict__ if isinstance(self.__dict__[name], Port)] # port_decl_str = "" # port_name_str = "" # for port in port_objs: # port_decl_str += str(port) # port_decl_str += "\n" # port_name_str += port.name # port_name_str += ", " # port_name_str = port_name_str.strip().strip(",") # print(port) # return port_name_str, port_decl_str port_decl_str = "\n".join([str(port) for port in self.Ports]) port_name_str = "\n,".join([port.name for port in self.Ports]) return port_name_str, port_decl_str #==================================================================================================================================================== # IMPORTANT - This base class method instantiates a busparser class aj object and will contain the port as dictionary object within busparser object. # # This method should be overwirren in subclasses whenever necessary. Use case of overwritting is as follows - # # While writing a new class for a new Verilog Module, we should always look inside refbuses folder and see if there's an existing yaml # that matches the dictionary closely or somewhat closely. # Then we should use available busparser method to operate on the dictionary and reach the desired dictionary for the target vlass. # Ultimately a list is extracted from the dictionary object and used to create ports for each leaf. In get header method it reflects the output # in Verilog world. # # Finally, the rationale behind keeping this as dictionary is that it's a systematic data-structure and can be used through multiple hierarchies # systematically. #==================================================================================================================================================== def add_ports_from_bus(self, filepath, bus_name): parser = BusParser(filepath, bus_name) ports = parser.port_names(parser.dict, []) i=0 for port in ports: i +=1 print(port) port_name = list(port.keys())[0] print(port_name) self.add_port(port_name, port[port_name]['direction'], port[port_name]['width']) def get_header(self): mytemplate = module_template mytemplate = mytemplate.replace("MODULENAME", self.name) portlist, portdecl = self.get_port_str() mytemplate = mytemplate.replace("PORTLIST", portlist) mytemplate = mytemplate.replace("PORTDECLARATION", portdecl) return mytemplate #==================================================================================================================================================== # IMPORTANT :- These base class methods downstream are useful building blocks for many verilog code - they offer stuffs including. # looping for wr, rd, snoop, snoop-invalidate, register declaration, wire declaration etc many things. # The idea is to use these methods as much as possible and if required create a new method on similar lines and push to base class. # # Method name should be kept generic and arguments used judiciously so that it can be maintained cleanly as the framework grows. #==================================================================================================================================================== def get_reg_str(self, type, delimiter, width, module_name, iterations): return "\n"+delimiter.join(["{2} [{0}:0] {1}".format(width, module_name, type)+str(i)+";" for i in range(iterations)]) def snoop_match_noinv(self, module_name, snoop, SnoopWidth, iterations, delimiter): return "\n"+delimiter.join(["(({0}[{2}:0] == {1}) ? 1'b1 : 1'b0)".format(module_name,snoop,SnoopWidth-1) for i in range(iterations)]) def snoop_inv(self, delimiter, snoopwidth, snoop, module_name, camdepth, camwidth): return "\n" + delimiter.join(["( ({0} == {1}".format(snoop,module_name)+str(i)+"["+str(snoopwidth-1)+":0]) ? {0}".format(module_name)+str(i)+" : "+str(camwidth)+"'d0 )" for i in range(camdepth)]) def snoop_get_wr_ptr(self,delimiter,module_name,snoop,snoopwidth,encodeddepth,camdepth): return delimiter.join(["( ({0} == {1}".format(snoop,module_name) + str(i) + "[" + str(snoopwidth - 1) + ":0]) ?"+module_name + str(i) + " : " + str(encodeddepth) + "'d" + str(i) + " )" for i in range(camdepth)]) def read_loc(self, encodeddepth, module_name, fifowidth, fifodepth, delimiter): return "\n"+delimiter.join(["( (rd_pointer["+str(encodeddepth)+":0] == "+str(encodeddepth+1)+"'d" ""+str(i)+") ? "+module_name+str(i)+" : "+str(fifowidth)+"'d0)" for i in range(fifodepth)]) def write_loc(self, delimiter, module_name, encodeddepth, fifodepth): return "\n\t"+delimiter.join([module_name+str(i)+" <= (wr_pointer["+str(encodeddepth-2)+":0] == "+str(encodeddepth)+"'d"+str(i)+") ? wr_data : "+module_name+str(i)+";" for i in range(fifodepth)]) def write_loc_rstn(self, delimiter, module_name, fifowidth, fifodepth): return "\n\t"+delimiter.join([module_name+str(i)+" <= "+str(fifowidth)+"'d0;" for i in range (fifodepth)]) def cam_write(self,delimiter,module_name,camdepth,encodeddepth): return "\n\t" + delimiter.join([module_name + str(i) + " <= (internal_wr_en & (internal_wr_ptr == " + str(encodeddepth) + "" "'d" + str(i) + ") ) ? wr_data : "+module_name + str(i) + ";" for i in range(camdepth)]) def write_to_file(self, verilog): with open(str(Path.home())+"/Documents/smartasic2/dumpverilog/"+self.name+".v","w") as f: f.write(verilog) def remove_port(self, port_name): for port in self.Ports: if port.name == port_name: self.Ports.remove(port) return class FIFO(BasicModule): class ClockType(Enum): SYNC = "sync" ASYNC = "async" RSYNC = "rsync" class FlowControl(Enum): VALID_READY = "valid_ready" VALID_BUSY = "valid_busy" VALID_CREDIT = "valid_credit" def __init__(self, name, width, depth, clk_type, flow_ctrl): if not isinstance(clk_type, FIFO.ClockType): raise TypeError('clk_type must be an instance of FIFO.ClockType') if not isinstance(flow_ctrl, FIFO.FlowControl): raise TypeError('flow_ctrl must be an instance of FIFO.FlowControl') super(FIFO, self).__init__(name) self.width = width self.depth = depth self.clk_type = clk_type self.flow_ctrl = flow_ctrl self.wr_valid = Port("wr_valid", Port.Direction.INPUT, 1) self.wr_ready = Port("wr_ready", Port.Direction.OUTPUT, 1) self.wr_data = Port("wr_data", Port.Direction.INPUT, self.width) self.rd_valid = Port("rd_valid", Port.Direction.OUTPUT, 1) self.rd_ready = Port("rd_ready", Port.Direction.INPUT, 1) self.rd_data = Port("rd_data", Port.Direction.OUTPUT, self.width) def update(self): self.__init__(self.name, self.width, self.depth, self.clk_type, self.flow_ctrl) def update_width(self, width): self.__init__(self.name, width, self.depth, self.clk_type, self.flow_ctrl) def update_height(self, height): self.__init__(self.name, self.width, height, self.clk_type, self.flow_ctrl) def get_body(self): encoded_depth = int(log2(self.depth)) mytemplate = fifo_body_template mytemplate = mytemplate.replace("ENCODEDDEPTH", str(encoded_depth)) mytemplate = mytemplate.replace("FIFOWIDTH", str(self.width)) mytemplate = mytemplate.replace("FIFODEPTH", str(self.depth)) return mytemplate def get_fifo_v(self): modulecode = self.get_header() modulecode = modulecode.replace("BODY", self.get_body()) return modulecode def __str__(self): return self.get_fifo_v() ======= import os from enum import Enum from math import log2 from templates2 import module_template from templates2 import fifo_body_template from BusParser import BusParser from pathlib import Path class Port: class Direction(Enum): INPUT = "input" OUTPUT = "output" INOUT = "inout" def __init__(self, name, direction, width): """ if not isinstance(direction, Port.Direction): raise TypeError('direction must be an instance of Port.Direction') """ if width < 1: raise TypeError('width should be > 0') self.name = name self.direction = direction self.width = width def get_declaration(self): if self.width == 1: return "{0} {1};".format(self.direction, self.name) else: return "{0} [{1}:0] {2};".format(self.direction, self.width - 1, self.name) def __str__(self): return self.get_declaration() class BasicModule: def __init__(self, name): self.name = name self.Ports = [] self.add_port("clk", "input", 1) self.add_port("rstn", "input", 1) def add_port(self, name, direction, width): self.Ports.append(Port(name, direction, width)) def get_port_str(self): # port_objs = [self.__dict__[name] for name in self.__dict__ if isinstance(self.__dict__[name], Port)] # port_decl_str = "" # port_name_str = "" # for port in port_objs: # port_decl_str += str(port) # port_decl_str += "\n" # port_name_str += port.name # port_name_str += ", " # port_name_str = port_name_str.strip().strip(",") # print(port) # return port_name_str, port_decl_str port_decl_str = "\n".join([str(port) for port in self.Ports]) port_name_str = "\n,".join([port.name for port in self.Ports]) return port_name_str, port_decl_str #==================================================================================================================================================== # IMPORTANT - This base class method instantiates a busparser class aj object and will contain the port as dictionary object within busparser object. # # This method should be overwirren in subclasses whenever necessary. Use case of overwritting is as follows - # # While writing a new class for a new Verilog Module, we should always look inside refbuses folder and see if there's an existing yaml # that matches the dictionary closely or somewhat closely. # Then we should use available busparser method to operate on the dictionary and reach the desired dictionary for the target vlass. # Ultimately a list is extracted from the dictionary object and used to create ports for each leaf. In get header method it reflects the output # in Verilog world. # # Finally, the rationale behind keeping this as dictionary is that it's a systematic data-structure and can be used through multiple hierarchies # systematically. #==================================================================================================================================================== def add_ports_from_bus(self, filepath, bus_name): parser = BusParser(filepath, bus_name) ports = parser.port_names(parser.dict, []) i=0 for port in ports: i +=1 print(port) port_name = list(port.keys())[0] print(port_name) self.add_port(port_name, port[port_name]['direction'], port[port_name]['width']) def get_header(self): mytemplate = module_template mytemplate = mytemplate.replace("MODULENAME", self.name) portlist, portdecl = self.get_port_str() mytemplate = mytemplate.replace("PORTLIST", portlist) mytemplate = mytemplate.replace("PORTDECLARATION", portdecl) return mytemplate #==================================================================================================================================================== # IMPORTANT :- These base class methods downstream are useful building blocks for many verilog code - they offer stuffs including. # looping for wr, rd, snoop, snoop-invalidate, register declaration, wire declaration etc many things. # The idea is to use these methods as much as possible and if required create a new method on similar lines and push to base class. # # Method name should be kept generic and arguments used judiciously so that it can be maintained cleanly as the framework grows. #==================================================================================================================================================== def get_reg_str(self, type, delimiter, width, module_name, iterations): return "\n"+delimiter.join(["{2} [{0}:0] {1}".format(width, module_name, type)+str(i)+";" for i in range(iterations)]) def snoop_match_noinv(self, module_name, snoop, SnoopWidth, iterations, delimiter): return "\n"+delimiter.join(["(({0}[{2}:0] == {1}) ? 1'b1 : 1'b0)".format(module_name,snoop,SnoopWidth-1) for i in range(iterations)]) def snoop_inv(self, delimiter, snoopwidth, snoop, module_name, camdepth, camwidth): return "\n" + delimiter.join(["( ({0} == {1}".format(snoop,module_name)+str(i)+"["+str(snoopwidth-1)+":0]) ? {0}".format(module_name)+str(i)+" : "+str(camwidth)+"'d0 )" for i in range(camdepth)]) def snoop_get_wr_ptr(self,delimiter,module_name,snoop,snoopwidth,encodeddepth,camdepth): return delimiter.join(["( ({0} == {1}".format(snoop,module_name) + str(i) + "[" + str(snoopwidth - 1) + ":0]) ?"+module_name + str(i) + " : " + str(encodeddepth) + "'d" + str(i) + " )" for i in range(camdepth)]) def read_loc(self, encodeddepth, module_name, fifowidth, fifodepth, delimiter): return "\n"+delimiter.join(["( (rd_pointer["+str(encodeddepth)+":0] == "+str(encodeddepth+1)+"'d" ""+str(i)+") ? "+module_name+str(i)+" : "+str(fifowidth)+"'d0)" for i in range(fifodepth)]) def write_loc(self, delimiter, module_name, encodeddepth, fifodepth): return "\n\t"+delimiter.join([module_name+str(i)+" <= (wr_pointer["+str(encodeddepth-2)+":0] == "+str(encodeddepth)+"'d"+str(i)+") ? wr_data : "+module_name+str(i)+";" for i in range(fifodepth)]) def write_loc_rstn(self, delimiter, module_name, fifowidth, fifodepth): return "\n\t"+delimiter.join([module_name+str(i)+" <= "+str(fifowidth)+"'d0;" for i in range (fifodepth)]) def cam_write(self,delimiter,module_name,camdepth,encodeddepth): return "\n\t" + delimiter.join([module_name + str(i) + " <= (internal_wr_en & (internal_wr_ptr == " + str(encodeddepth) + "" "'d" + str(i) + ") ) ? wr_data : "+module_name + str(i) + ";" for i in range(camdepth)]) def write_to_file(self, verilog): with open(str(Path.home())+"/Documents/smartasic2/dumpverilog/"+self.name+".v","w") as f: f.write(verilog) def remove_port(self, port_name): for port in self.Ports: if port.name == port_name: self.Ports.remove(port) return class FIFO(BasicModule): class ClockType(Enum): SYNC = "sync" ASYNC = "async" RSYNC = "rsync" class FlowControl(Enum): VALID_READY = "valid_ready" VALID_BUSY = "valid_busy" VALID_CREDIT = "valid_credit" def __init__(self, name, width, depth, clk_type, flow_ctrl): if not isinstance(clk_type, FIFO.ClockType): raise TypeError('clk_type must be an instance of FIFO.ClockType') if not isinstance(flow_ctrl, FIFO.FlowControl): raise TypeError('flow_ctrl must be an instance of FIFO.FlowControl') super(FIFO, self).__init__(name) self.width = width self.depth = depth self.clk_type = clk_type self.flow_ctrl = flow_ctrl self.wr_valid = Port("wr_valid", Port.Direction.INPUT, 1) self.wr_ready = Port("wr_ready", Port.Direction.OUTPUT, 1) self.wr_data = Port("wr_data", Port.Direction.INPUT, self.width) self.rd_valid = Port("rd_valid", Port.Direction.OUTPUT, 1) self.rd_ready = Port("rd_ready", Port.Direction.INPUT, 1) self.rd_data = Port("rd_data", Port.Direction.OUTPUT, self.width) def update(self): self.__init__(self.name, self.width, self.depth, self.clk_type, self.flow_ctrl) def update_width(self, width): self.__init__(self.name, width, self.depth, self.clk_type, self.flow_ctrl) def update_height(self, height): self.__init__(self.name, self.width, height, self.clk_type, self.flow_ctrl) def get_body(self): encoded_depth = int(log2(self.depth)) mytemplate = fifo_body_template mytemplate = mytemplate.replace("ENCODEDDEPTH", str(encoded_depth)) mytemplate = mytemplate.replace("FIFOWIDTH", str(self.width)) mytemplate = mytemplate.replace("FIFODEPTH", str(self.depth)) return mytemplate def get_fifo_v(self): modulecode = self.get_header() modulecode = modulecode.replace("BODY", self.get_body()) return modulecode def __str__(self): return self.get_fifo_v() <file_sep>import os from smartasic import BasicModule,Port from DynamicGenerator import DynamicGenerator from BusParser import BusParser from pathlib import Path from math import log2, ceil import sys class CAM(BasicModule,BusParser): #======================================================================================================= # #======================================================================================================= def add_ports_from_bus(self): self.add_sub_dict_flat("snoop" , {"sin" : {"direction" : "input" , "type" : "fluid" , "width" : self.SnoopWidth}}) self.widop_flat("wdata",self.CamWidth) self.widop_flat("sin",self.SnoopWidth) self.widop_flat("sdata",self.CamWidth) self.remove_sub_dict_flat("rd") #self.init_connections(self.dict) self.get_all_key_value_pairs(self.dict) def Create_dic_of_variable(self): self.variable_dict['CamWidth']=self.CamWidth self.variable_dict['SnoopWidth']=self.SnoopWidth self.variable_dict['CamDepth']= self.CamDepth self.variable_dict['EncodedDepth']=self.EncodedDepth def get_body(self): dynamicgenerator=DynamicGenerator(self.variable_dict,self.cambody) self.body+=dynamicgenerator.parse_body() self.body = self.body.replace("ENCODEDDEPTH - 1", str(self.EncodedDepth-1)) self.body = self.body.replace("ENCODEDDEPTH", str(self.EncodedDepth)) self.body = self.body.replace("CAMWIDTH - 1", str(self.CamWidth - 1)) self.body = self.body.replace("CAMWIDTH", str(self.CamWidth)) self.body = self.body.replace("SNOOPWIDTH - 1", str(self.SnoopWidth - 1)) self.body = self.body.replace("SNOOPWIDTH", str(self.SnoopWidth)) dynamicgenerator.silentremove() def get_verilog(self): modulecode=self.get_header() self.get_body() modulecode=modulecode.replace("BODY",self.body) return modulecode def main(self): self.write_to_file(self.get_verilog()) return self.get_verilog() def __init__(self, camdepth, camwidth, snoopwidth, path_of_yaml=None,bus_name=None): self.CamDepth = camdepth self.EncodedDepth = ceil(log2(int(camdepth))) self.SnoopWidth = snoopwidth self.CamWidth = camwidth if path_of_yaml is None: path_of_yaml = "../../../smartasic2/refbuses/astob_for_order_switch.yaml" bus_name = "astob" self.name = "AH_" + self.__class__.__name__ + "_" + str(camdepth) + "_" + str(camwidth) + "_" + str(snoopwidth) BasicModule.__init__(self,self.name) self.body = "" BusParser.__init__(self, self.load_dict(path_of_yaml), bus_name) self.variable_dict={} self.Create_dic_of_variable() self.add_ports_from_bus() self.cambody=""" wire [ENCODEDDEPTH - 1:0] internal_wr_ptr; req [ENCODEDDEPTH:0] wr_loc_counter; /f_f/ code = "\\n".join(["req ["+str(CamWidth-1)+":0] cam_loc"+str(i)+";" for i in range(CamDepth)]) /f_f/ always @ (posedge clk or negedge rst_an) begin if (!rst_an) begin wr_loc_counter <= ENCODEDDEPTH+1'd0; // log2(CAMDEPTH) +1 end else begin wr_loc_counter <= wr_location_counter[ENCODEDDEPTH] ? wr_location_counter : wr_location_counter + 1'b1; end end AH_srvfifo_ENCODEDDEPTH_CAMDEPTH u_wrloc_recirfifo ( .wr_valid(freeup_loc) ,.wr_ready(freedup_loc_valid) ,.wr_data(freedup_loc_ready) ,.rd_valid(recir_loc_valid) ,.rd_ready(recir_loc_ready) ,.rd_data(recir_loc) ); assign internal_wr_en = wr_valid & (recir_loc_valid | ~wr_location_counter[ENCODEDDEPTH]); assign internal_wr_ptr = ~wr_location_counter[ENCODEDDEPTH + 1] ? ~wr_location_counter[ENCODEDDEPTH - 1:0] : recir_loc; assign wr_ready = ~wr_location_counter[ENCODEDDEPTH + 1] ? 1'b1 : recir_loc_valid; assign recir_loc_ready = ~wr_location_counter[ENCODEDDEPTH + 1] ? 1'b0 : wr_valid; always @ (posedge clk or negedge rst_an) if (!rst_an) begin /f_f/ code = "\\n\t"+"\\n\t".join(["cam_loc"+str(i)+" <= "+str(CamWidth)+"'d0;" for i in range(CamDepth)]) /f_f/ end else begin /f_f/ code = "\\n\t"+"\\n\t".join(["cam_loc"+str(i)+" <= (internal_wr_en & (internal_wr_ptr == "+str(EncodedDepth)+"" "'d"+str(i)+") ) ? wr_data : cam_loc"+str(i)+";" for i in range(CamDepth)]) /f_f/ end wire assign snoop_match = freedup_loc_ready) & ( /f_f/ code = " |\\n ".join(["(snoop_in == cam_loc"+str(i)+"["+str(SnoopWidth-1)+":0])" for i in range(CamDepth)]) /f_f/ ); wire assign snoop_data = CAMWIDTH'd0 | /f_f/ code = " |\\n ".join(["( (snoop_in == cam_loc"+str(i)+"["+str(SnoopWidth-1)+":0]) ? cam_loc"+str(i)+" : "+str(CamWidth)+"'d0 )" for i in range(CamDepth)]) /f_f/ ; wire assign freeup_loc = ENCODEDDEPTH'd0 | /f_f/ code = " |\\n ".join(["( (snoop_in == cam_loc"+str(i)+"["+str(SnoopWidth-1)+":0]) ? cam_loc"+str(i)+" : "+str(EncodedDepth)+"'d"+str(i)+" )" for i in range(CamDepth)]) /f_f/ ; wire assign freedup_loc_valid = snoop_match; """ cam=CAM(int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]),sys.argv[4],sys.argv[5]) cam.main() <file_sep>from math import log2, ceil import argparse parser = argparse.ArgumentParser() parser.add_argument("-b2g", help="binary2gray", action="store_true") parser.add_argument("-g2b", help="gray2binary", action="store_true") parser.add_argument("-oh2b", help="onehot2binary", action="store_true") parser.add_argument("-cw", help="width of data", type = int) args = parser.parse_args() class Encoder: def __init__(self): self.body = None self.CodeWidth = None self.get_body() def binary2gray(self): self.CodeWidth = args.cw module_dec = "module AH_binary2gray (\nbinary,\ngray,\n);" vector_dec = "input ["+str(self.CodeWidth-1)+":0] binary;\n" \ "output ["+str(self.CodeWidth-1)+":0] gray;\n" code = "\n".join(["wire assign gray["+str(i)+"] = binary["+str(i+1)+"] ^ binary["+str(i)+"];" for i in range(self.CodeWidth-1)]) code += "\nwire assign gray["+str(self.CodeWidth-1)+"] = binary[0];\nendmodule" self.body = "\n".join([module_dec, vector_dec, code]) def gray2binary(self): self.CodeWidth = args.cw module_dec = "module AH_gray2binary (\nbinary,\ngray,\n);" vector_dec = "input [" + str(self.CodeWidth - 1) + ":0] gray;\n" \ "output [" + str(self.CodeWidth - 1) + ":0] binary;\n" code = "\n".join( ["wire assign binary[" + str(i) + "] = gray[" + str(i + 1) + "] ^ gray[" + str(i) + "];" for i in range(self.CodeWidth - 1)]) code += "\nwire assign gray[" + str(self.CodeWidth - 1) + "] = binary[0];\nendmodule" self.body = "\n".join([module_dec, vector_dec, code]) def onehot2binary(self): self.CodeWidth = args.cw module_dec = "module AH_onehot2binary (\nbinary,\nonehot,\n);" vector_dec = "input [" + str(pow(2,self.CodeWidth)-1) + ":0] onehot;\n" \ "output [" + str(self.CodeWidth - 1) + ":0] binary;\n" \ "wire binary;\n" code = "always @(*)\nbegin\n\tcase(onehot)\n\t\t" code = "\n\t\t".join([str(pow(2,self.CodeWidth))+"'d"+str(pow(2,i))+" : binary = "+str(self.CodeWidth)+"'d"+str(i)+";" for i in range(pow(2,self.CodeWidth))]) code += "\n\t\t//translate off\n\t\tdefault : binary = "+str(self.CodeWidth)+"'dx" \ "\n\t\ttranslate on\n\tendcase\nend" self.body = "\n".join([module_dec, vector_dec, code]) def get_body(self): if args.b2g: self.binary2gray() elif args.g2b: self.gray2binary() elif args.oh2b: self.onehot2binary() def __str__(self): return self.body print(Encoder())<file_sep>AH_2OrderedSwitch.py: def main(self): AH_2OrderedSwitch.py- self.get_body() AH_2OrderedSwitch.py- AH_2OrderedSwitch.py- def __init__(self, number_of_egress,ds_packet_size, ups_packet_size, ds_decodable_field_width, ups_response_decodable_field_width, snoopdepth): AH_2OrderedSwitch.py- self.name = "AH_"+self.__class__.__name__+"_"+str(number_of_egress)+"_"+str(ds_packet_size)+"_"+str(ups_packet_size)+"_"+str(ds_decodable_field_width)+"_"+str(ups_response_decodable_field_width) AH_2OrderedSwitch.py- BasicModule.__init__(self, self.name) AH_2OrderedSwitch.py- self.NumberOfEgress = number_of_egress AH_2OrderedSwitch.py- self.DsPktSize = ds_packet_size AH_2OrderedSwitch.py- self.SnoopDepth = snoopdepth AH_2OrderedSwitch.py- self.upPktSize = ups_packet_size AH_2OrderedSwitch.py- self.dsDecodableFieldWidth = ds_decodable_field_width AH_2OrderedSwitch.py- self.upResponseDecodableFieldWidth = ups_response_decodable_field_width AH_2OrderedSwitch.py- self.port_dict = {} -- AH_CAM.py: def main(self): AH_CAM.py- self.write_to_file(self.get_verilog()) AH_CAM.py- return self.get_verilog() AH_CAM.py- AH_CAM.py- AH_CAM.py- def __init__(self, camdepth, camwidth, snoopwidth, path_of_yaml=None,bus_name=None): AH_CAM.py- self.CamDepth = camdepth AH_CAM.py- self.EncodedDepth = ceil(log2(int(camdepth))) AH_CAM.py- self.SnoopWidth = snoopwidth AH_CAM.py- self.CamWidth = camwidth AH_CAM.py- if path_of_yaml is None: AH_CAM.py- path_of_yaml = "../../../smartasic2/refbuses/astob_for_order_switch.yaml" AH_CAM.py- bus_name = "astob" -- AH_Decoder.py: def main(self): AH_Decoder.py- print("I am about to write a verilog file now") AH_Decoder.py- self.write_to_file(self.get_verilog()) AH_Decoder.py- print (self.get_verilog()) AH_Decoder.py- return self.get_verilog() AH_Decoder.py- AH_Decoder.py- def __init__(self, portwidth, numclients, path_of_yaml=None, bus_name=None, apertures_yaml=None): AH_Decoder.py- if path_of_yaml is None: AH_Decoder.py- path_of_yaml = "../../../smartasic2/refbuses/decoder.yaml" AH_Decoder.py- bus_name = "decoder" AH_Decoder.py- apertures_yaml = "decode_apertures.yaml" AH_Decoder.py- AH_Decoder.py- self.AperturesYaml = apertures_yaml -- AH_DivPipelined.py: def main(self): AH_DivPipelined.py- self.write_to_file(self.get_verilog()) AH_DivPipelined.py- return self.get_verilog() AH_DivPipelined.py- AH_DivPipelined.py- def __init__(self,bits,stages,path_of_yaml=None,bus_name=None): AH_DivPipelined.py- self.bits=bits AH_DivPipelined.py- self.stages=stages AH_DivPipelined.py- self.body="" AH_DivPipelined.py- self.name="AH_"+self.__class__.__name__+"_"+str(bits)+"_"+str(stages) AH_DivPipelined.py- BasicModule.__init__(self , self.name) AH_DivPipelined.py- self.variable_dict={} AH_DivPipelined.py- BusParser.__init__(self,self.load_dict(path_of_yaml),bus_name) AH_DivPipelined.py- self.Create_dic_of_variable() -- AH_LruArbiter.py: def main(self): AH_LruArbiter.py- self.write_to_file(self.get_verilog()) AH_LruArbiter.py- return self.get_verilog() AH_LruArbiter.py- AH_LruArbiter.py- def __init__(self,num_clients,path_of_yaml=None,bus_name=None): AH_LruArbiter.py- self.bus_name=bus_name AH_LruArbiter.py- self.Num_Clients=num_clients AH_LruArbiter.py- self.variable_dict={} AH_LruArbiter.py- self.name="AH_"+self.__class__.__name__+"_"+str(num_clients) AH_LruArbiter.py- BasicModule.__init__(self, self.name) AH_LruArbiter.py- BusParser.__init__(self,self.load_dict(path_of_yaml),bus_name) AH_LruArbiter.py- self.body="" AH_LruArbiter.py- self.Create_dic_of_variable() -- AH_Multiplexor.py: def main(self): AH_Multiplexor.py- print("I am about to write a verilog file now") AH_Multiplexor.py- self.write_to_file(self.get_verilog()) AH_Multiplexor.py- print (self.get_verilog()) AH_Multiplexor.py- return self.get_verilog() AH_Multiplexor.py- AH_Multiplexor.py- def __init__(self, portwidth, numclients, isdemux, isbinary, path_of_yaml=None, bus_name=None): AH_Multiplexor.py- self.PortWidth = portwidth AH_Multiplexor.py- self.NumClients = numclients AH_Multiplexor.py- self.IsDemux = isdemux AH_Multiplexor.py- self.body = None AH_Multiplexor.py- self.IsBinary = isbinary AH_Multiplexor.py- -- AH_Mutiplexor.py: def main(self): AH_Mutiplexor.py- self.write_to_file(self.get_verilog()) AH_Mutiplexor.py- return self.get_verilog() AH_Mutiplexor.py- AH_Mutiplexor.py- AH_Mutiplexor.py- def __init__(self, portwidth, numclients, isdemux, isbinary): AH_Mutiplexor.py- self.PortWidth = portwidth AH_Mutiplexor.py- self.NumClients = numclients AH_Mutiplexor.py- self.isDemux = isdemux AH_Mutiplexor.py- self.isBinary = isbinary AH_Mutiplexor.py- self.body="" AH_Mutiplexor.py- self.variable_dict={} AH_Mutiplexor.py- self.Create_dic_of_variable() -- AH_OrderedSwitch.py: def main(self): AH_OrderedSwitch.py- self.get_body() AH_OrderedSwitch.py- AH_OrderedSwitch.py- def __init__(self, number_of_egress,ds_packet_size, ups_packet_size, ds_decodable_field_width, ups_response_decodable_field_width, snoopdepth): AH_OrderedSwitch.py- self.name = "AH_"+self.__class__.__name__+"_"+str(number_of_egress)+"_"+str(ds_packet_size)+"_"+str(ups_packet_size)+"_"+str(ds_decodable_field_width)+"_"+str(ups_response_decodable_field_width) AH_OrderedSwitch.py- BasicModule.__init__(self, self.name) AH_OrderedSwitch.py- self.NumberOfEgress = number_of_egress AH_OrderedSwitch.py- self.dsPktSize = ds_packet_size AH_OrderedSwitch.py- self.SnoopDepth = snoopdepth AH_OrderedSwitch.py- self.upPktSize = ups_packet_size AH_OrderedSwitch.py- self.dsDecodableFieldWidth = ds_decodable_field_width AH_OrderedSwitch.py- self.upResponseDecodableFieldWidth = ups_response_decodable_field_width AH_OrderedSwitch.py- self.dict = {} -- AH_PacketConverter.py: def main(self): AH_PacketConverter.py- self.write_to_file(self.get_verilog()) AH_PacketConverter.py- return self.get_verilog() AH_PacketConverter.py- AH_PacketConverter.py- AH_PacketConverter.py- AH_PacketConverter.py- def __init__(self, width1, width2, isW2N,path_of_yaml=None,bus_name=None): AH_PacketConverter.py- self.WideWidth = max(width1, width2) AH_PacketConverter.py- self.NarrowWidth = min(width1, width2) AH_PacketConverter.py- self.isW2N = isW2N AH_PacketConverter.py- self.ratio = (self.WideWidth // self.NarrowWidth) AH_PacketConverter.py- self.VecWidth = int(log2(self.WideWidth/self.NarrowWidth)) AH_PacketConverter.py- if self.isW2N == "True": -- AH_RoundRobinArbiter.py: def main(self): AH_RoundRobinArbiter.py- self.write_to_file(self.get_verilog()) AH_RoundRobinArbiter.py- return self.get_verilog() AH_RoundRobinArbiter.py- AH_RoundRobinArbiter.py- AH_RoundRobinArbiter.py- def __init__(self,num_clients,path_of_yaml=None,bus_name=None,weight=None): AH_RoundRobinArbiter.py- self.bus_name=bus_name AH_RoundRobinArbiter.py- self.Num_Clients=num_clients AH_RoundRobinArbiter.py- self.weight = weight AH_RoundRobinArbiter.py- if weight==None: AH_RoundRobinArbiter.py- self.name="AH_"+self.__class__.__name__+"_"+str(num_clients) AH_RoundRobinArbiter.py- else: AH_RoundRobinArbiter.py- self.name="AH_"+self.__class__.__name__+"_"+str(num_clients)+"_"+str(weight) -- AH_SnoopableFIFO.py: def main(self): AH_SnoopableFIFO.py- self.write_to_file(self.get_verilog()) AH_SnoopableFIFO.py- return self.get_verilog() AH_SnoopableFIFO.py- AH_SnoopableFIFO.py- def __init__(self, fifowidth, fifodepth, snoopwidth, path_of_yaml = None, bus_name = None): AH_SnoopableFIFO.py- AH_SnoopableFIFO.py- self.FifoWidth = fifowidth AH_SnoopableFIFO.py- self.FifoDepth = fifodepth AH_SnoopableFIFO.py- self.SnoopWidth = snoopwidth AH_SnoopableFIFO.py- if path_of_yaml is None: AH_SnoopableFIFO.py- path_of_yaml = "../../../smartasic2/refbuses/astob.yaml" AH_SnoopableFIFO.py- bus_name = "astob" AH_SnoopableFIFO.py- -- smartasic.py: def main(self): smartasic.py- self.write_to_file(self.get_verilog()) smartasic.py- return self.get_verilog() smartasic.py- smartasic.py- smartasic.py- <file_sep> # TODO: Move this template strings to Jinja templates. module_template = """ module MODULENAME (PORTLIST); PORTDECLARATION BODY endmodule """ fifo_body_template = """ // ***************************************************************************** // Body of Module // ***************************************************************************** reg [ENCODEDDEPTH:0] wr_ptr, rd_ptr; always @(posedge clk,negedge rstn) begin if(!rstn) wr_ptr <= 0; else if(wr_valid & !wr_busy) wr_ptr <= (rd_valid & !rd_busy)? wr_ptr : wr_ptr+1; else if(rd_valid & !rd_busy) wr_ptr <= wr_ptr -1 ; end assign wr_busy = (wr_ptr == $fifo_depth) assign rd_valid = (wr_ptr != 0); reg [ENCODEDDEPTH - 1 :0] addr; reg [ENCODEDDEPTH - 1 :0] rd_addr; always @(posedge clk, negedge rstn) begin if(!rstn) addr <= 0; else if(wr_valid & !wr_busy) addr <= addr+1; end wire [FIFOWIDTH-1:0] mem_data[FIFODEPTH - 1 :0]; assign mem_data[addr][FIFOWIDTH-1:0] = wr_data[FIFOWIDTH-1:0] always @(posedge clk, negedge rstn) begin if(!rstn) rd_addr <=0; else if (rd_valid & !rd_busy) rd_addr <= rd_addr +1; end assign rd_data = mem_data[rd_addr]; // ***************************************************************************** """ arbiter_body_template = """ //Rotate -> Priority -> Rotate module round_robin_arbiter_NUMCLIENTS ( rst_n, clk, req, grant //CFG_DECLARATIONS ); input rst_n; input clk; input [NUMCLIENTS - 1:0] req; output [NUMCLIENTS - 1:0] grant; //INPUT_WEIGHT_VECTORS reg [ENCODEDNUMCLIENTS - 1:0] rotate_ptr; reg [NUMCLIENTS - 1:0] shift_req; reg [NUMCLIENTS - 1:0] shift_grant; reg [NUMCLIENTS - 1:0] grant_comb; reg [NUMCLIENTS - 1:0] grant; //WEIGHT_REGISTERS // shift req to round robin the current priority always @ (*) begin //SHIFT_REQUEST endcase end // simple priority arbiter always @ (*) begin //SHIFT_GRANT end // generate grant signal always @ (*) begin //GRANT_SIGNAL endcase end always @ (posedge clk or negedge rst_n) begin if (!rst_n) grant[NUMCLIENTS - 1:0] <= NUMCLIENTS'b0; else grant[NUMCLIENTS - 1:0] <= grant_comb[NUMCLIENTS - 1:0] & ~grant[NUMCLIENTS - 1:0]; end // update the rotate pointer // rotate pointer will move to the one after the current granted always @ (posedge clk or negedge rst_n) begin if (!rst_n) rotate_ptr[ENCODEDNUMCLIENTS - 1:0] <= ENCODEDNUMCLIENTS'b0; else case (1'b1) // synthesis parallel_case //ROTATION endcase end """ weight_update_template = """ always @ (posedge clk or negedge rst_an) begin if (!rst_an) begin //WEIGHT_BIT end else begin //WEIGHT_NEGATION end end assign refresh_weights = //REFRESH_WEIGHT //ASSIGN_WEIGHT """ cam_body_template = """ module AH_cam_CAMDEPTH_CAMWIDTH_SNOOPWIDTH ( rst_an, clk, wr_data, wr_valid, wr_ready, snoop_in, snoop_valid, snoop_match, snoop_data ); // ============================================================================ // Below are the main parameters which are used for CAM functionality. // // CAMWIDTH --> width of storage - similar to FIFO storage // CAMDEPTH --> Number of rows the CAM can fit // ENCODEDDEPTH --> log2 of the CAM depth, the write/read pointers and snoop // marker all have this width. // // SNOOPWIDTH --> width of snoop-in port. This is always lte CAMWIDTH // ============================================================================ input rst_an; input clk; input [CAMWIDTH - 1:0] wr_data; //POINT --> CAMWIDTH output wr_valid; output wr_ready; // ============================================================================ //snoop happens at the LSBs. It is expected that for snoop to happen // in upper bits, write will be swizzled into LSB locations. input [SNOOPWIDTH - 1:0] snoop_in; // SNOOPWIDTH lte CAMWIDTH input snoop_valid; output snoop_match; output [CAMWIDTH - 1:0] snoop_data; // CAMWIDTH here wire [ENCODEDDEPTH - 1:0] internal_wr_ptr; // asume CAMDEPTH = 64, then wr-ptr-width is log2(CAMDEPTH). req [ENCODEDDEPTH:0] wr_loc_counter; // It's log2(CAMDEPTH) +1 from the above //REQUEST_DECLARATION // ============================================================================ // CAM working principle -- // 1. Initially all the entries are in pool of free locations. // 2. These are stored in a FIFO - at reset there's a counter which runs // and freely increments to keep feeding these locations to write logic. Once initial // 32/64/256 locations are used, the FIFO takes over. This helps to start the CAM right // right at the begining without any issues. // // 3. Once a snoop comes and if a snoop match happens, the location is invalidated and // correspnding location is written back into FIFO to be reused. // the problem with this scheme is that it immediately a reused location isn't available for // writing. // // If we apply a combo based logic, then that's possible - but then the resulting combo can be // very difficult to meet timing creating pipelining and having delays anyways. // In general for smaller CAMs, combo based wr-location search might be a good thing. // ============================================================================ // ============================================================================ // The counter always @ (posedge clk or negedge rst_an) begin if (!rst_an) begin wr_loc_counter <= ENCODEDDEPTH+1'd0; // log2(CAMDEPTH) +1 end else begin wr_loc_counter <= wr_location_counter[ENCODEDDEPTH] ? wr_location_counter : wr_location_counter + 1'b1; end end // ============================================================================ // Instance the reuse FIFO // Number 6 below is same as ENCODEDDEPTH or log2(CAMDEPTH). Number 64 below is same as CAMDEPTH. AH_srvfifo_ENCODEDDEPTH_CAMDEPTH u_wrloc_recirfifo ( .wr_valid(freeup_loc) ,.wr_ready(freedup_loc_valid) ,.wr_data(freedup_loc_ready) ,.rd_valid(recir_loc_valid) ,.rd_ready(recir_loc_ready) ,.rd_data(recir_loc) ); // ============================================================================ // Take the location from recir_loc or from wr_loc_counter and prepare to write an incoming data // Use the counter for initial phase only - so the MSB of counter when reached to 1, this method // of using counter shouldn't be used anymore // These are for CAM locations assign internal_wr_en = wr_valid & (recir_loc_valid | ~wr_location_counter[ENCODEDDEPTH]); assign internal_wr_ptr = ~wr_location_counter[ENCODEDDEPTH + 1] ? ~wr_location_counter[ENCODEDDEPTH - 1:0] : recir_loc; // Handshake with external wr-port assign wr_ready = ~wr_location_counter[ENCODEDDEPTH + 1] ? 1'b1 : recir_loc_valid; // Handshake with recirculation FIFO pop-port assign recir_loc_ready = ~wr_location_counter[ENCODEDDEPTH + 1] ? 1'b0 : wr_valid; // ============================================================================ // Now actual CAM locations // NOTE:- only 3 locations are shown - it should continue for 64 locations. always @ (posedge clk or negedge rst_an) if (!rst_an) begin //CAM_LOCATIONS end else begin //CAM_WRITE end // ============================================================================ // Handle the snoop part here. wire assign snoop_match = freedup_loc_ready) & ( //SNOOP_CAM ); wire assign snoop_data = CAMWIDTH'd0 | //ASSIGN_SNOOP ; wire assign freeup_loc = ENCODEDDEPTH'd0 | //ASSIGN_FREEUP ; wire assign freedup_loc_valid = snoop_match; endmodule """ mux_body_template = """ module NAME_MUXPORTWIDTH_MUXNUMCLIENTS ( //PORT_DECLARATION ); //VECTOR_DECLARATION //ASSIGN_DATA endmodule """ snoopable_fifo_template = """ // 20 - FIFOWIDTH // 32 - FIFODEPTH // 10 - SNOOPWIDTH // FIFONAME carries these 3 string. It can carry // other stuffs as srv (sync/ready-valid) module FIFO_FIFOWIDTH_FIFODEPTH_SNOOPWIDTH_snoopable ( clk, rstn, wr_valid, wr_ready, wr_data, rd_valid, rd_ready, rd_data, snoop_data, snoop_valid, snoop_match ); input rstn, intput clk, input [FIFOWIDTH - 1:0] wr_data; //FIFOWIDTH input wr_valid; input wr_ready; out [FIFOWIDTH - 1:0] rd_data; //FIFOWIDTH input rd_valid; input rd_ready; input [SNOOPWIDTH - 1:0] snoop_data; // SNOOPWIDTH input snoop_valid; input snoop_match; reg [ENCODEDDEPTH:0] wr_pointer; // ENCODEDDEPTH + 1 = log2(32) + 1 reg [ENCODEDDEPTH:0] rd_pointer; // ENCODEDDEPTH + 1 //REG_DECLARATIONS always @ (posedge clk or negedge rstn) begin if(rstn) begin wr_pointer <= ENCODEDDEPTH + 1'd0; end else begin wr_pointer <= ( (wr_pointer[ENCODEDDEPTH] ^ rd_pointer[ENCODEDDEPTH]) && (wr_pointer[ENCODEDDEPTH - 1:0] == rd_pointer[ENCODEDDEPTH - 1:0]) ) ? wr_pointer : wr_valid ? ( wr_pointer + 1'b1) : wr_pointer; end end always @ (posedge clk or negedge rstn) begin if(rstn) begin rd_pointer <= ENCODEDDEPTH + 1'd0; end else begin rd_pointer <= (rd_pointer[ENCODEDDEPTH:0] == rd_pointer[ENCODEDDEPTH:0]) ? rd_pointer : rd_ready ? (rd_pointer + 1'b1) : rd_pointer; end end always @ (posedge clk or negedge rstn) begin if(!rstn) begin //ASSIGN_LOC end else begin //LOC_WRITE end end wr_ready = ! ( (wr_pointer[ENCODEDDEPTH] ^ rd_pointer[ENCODEDDEPTH]) && (wr_pointer[ENCODEDDEPTH - 1:0] == rd_pointer[ENCODEDDEPTH - 1:0]) ); rd_valid = !(rd_pointer[ENCODEDDEPTH:0] == rd_pointer[ENCODEDDEPTH:0]); assign rd_data = FIFOWIDTH'd0 | //ASSIGN_READ assing snoop_match = 1'b0 | //ASSIGN_SNOOP_MATCH // snoop_match isn't used now - it can be in future. endmodule """ packet_converter_template = """ module AH_NAME ( clk, rstn, in_data, in_valid, in_ready, out_data, out_valid, out_ready ); input in_valid; output in_ready; output out_valid; input out_ready; //DECLARATIONS //============================================================ // wide to narrow ratio should be an integer. // TODO:// As an extension of this module, in future we should // support rational numbers - or M/N. reg [VECWIDTH - 1:0] packet_lane; // Vec width log2(WIDEWIDTH/NARROWWIDTH) wire [VECWIDTH - 1:0] npacket_lane; always(@posedge clk or negedge rstn) begin if (!rstn) begin packet_lane <= VECWIDTH'd0; // log2(WIDEWIDTH/NARROWWIDTH) //COLLATED end else begin packet_lane <= npacket_lane; //NCOLLATED end end // 3 is basically (WIDEWIDTH/NARROWWIDTH) -1 // //ASSIGN_DATA endmodule """ pipe_body_template = """ module_pipe_WIDTH( wr_data, wr_valid, wr_ready, rd_data, rd_valid, rd_ready, clk, rstn ); //di -> wr_data/ vi --> wr_valid / ro ---> wr_ready/ //do --> rd_data/vo --> rd_valid/ ri ---> rd_ready / input clk; input rst; input wr_valid; output wr_ready; input [WIDEWIDTH - 1:0] wr_data; output rd_valid; input rd_ready; output [WIDEWIDTH - 1:0] rd_data; reg rd_valid //SKID_REGISTERS //PIPE //SKID // PIPE OUTPUT assign wr_ready = rd_ready; assign rd_valid = wr_valid; assign rd_data = wr_data; endmodule """ ordering_point_template =""" module AH_ordering_point_NUMCLIENTS ( //MODULE_DEC ); //I/O_DEC //WIRE_ASSIGN """ lruArbiter_body = """ module lru_arbiter ( clk, rstn, req, gnt_busy, gnt ); input clk, rstn input [NUMCLIENTS - 1:0] req; input [NUMCLIENTS - 1:0] gnt_busy; output [NUMCLIENTS - 1:0] gnt; ##reg [NUMCLIENTS - 1:0] req0_used_status; ##reg [NUMCLIENTS - 1:0] req1_used_status; ##reg [NUMCLIENTS - 1:0] req2_used_status; ##reg [NUMCLIENTS - 1:0] req3_used_status; //REG_STATUS always @(posedge clk, negedge rstn) begin if(~rstn) begin req0_used_status <= 4'd4; req1_used_status <= 4'd3; req2_used_status <= 4'd2; req3_used_status <= 4'd1; end //STATUS_USED else begin if(gnt[0]& !gnt_busy) begin ##req0_used_status <= 4'b1; ##req1_used_status <= req1_used_status<req0_used_status ? req1_used_status + 1'b1 : req1_used_status; ##req2_used_status <= req2_used_status<req0_used_status ? req2_used_status + 1'b1 : req2_used_status ; ##req3_used_status <= req3_used_status<req0_used_status ? req3_used_status + 1'b1 : req3_used_status ; end if(gnt[1] & !gnt_busy) begin ## req1_used_status <= 4'b1; ## req0_used_status <= req0_used_status<req1_used_status ? req0_used_status + 1'b1 : req0_used_status; ##req2_used_status <= req2_used_status<req1_used_status ? req2_used_status + 1'b1 : req2_used_status ; ##req3_used_status <= req3_used_status<req1_used_status ? req3_used_status + 1'b1 : req3_used_status ; end if(gnt[2]& !gnt_busy) begin ##req2_used_status <= 4'b1; # # req0_used_status <= req0_used_status<req0_used_status ? req0_used_status + 1'b1 : req0_used_status; ##req1_used_status <= req1_used_status<req0_used_status ? req1_used_status + 1'b1 : req1_used_status ; ##req3_used_status <= req3_used_status<req0_used_status ? req3_used_status + 1'b1 : req3_used_status ; end if(gnt[3] & !gnt_busy) begin ##req3_used_status <= 4'b1; ##req0_used_status <= req0_used_status<req0_used_status ? req0_used_status + 1'b1 : req0_used_status; ##req1_used_status <= req1_used_status<req1_used_status ? req1_used_status + 1'b1 : req1_used_status ; ##req2_used_status <= req2_used_status<req2_used_status ? req2_used_status + 1'b1 : req2_used_status ; end end //GNT_STATUS end always @(req, gnt_busy) begin gnt_pre[3:0] = 4'd0; req_int [3:0]= req[3:0] & {4{gnt_busy}}; if(req[0]) begin gnt_pre[0] = (req0_used_status==4) ? 1'b1 : ((req1 & (req1_used_status > req0_used_status)) ? 1'b0 : ((req2 & (req2_used_status > req0_used_status)) ? 1'b0 : ((req3 & (req3_used_status > req0_used_status)) ? 1'b0 : 1'b1; end if(req[1]) begin gnt_pre[1] = (req1_used_status==4) ? 1'b1 : ((req0 & (req0_used_status > req1_used_status)) ? 1'b0 : ((req2 & (req2_used_status > req1_used_status)) ? 1'b0 : ((req3 & (req3_used_status > req1_used_status)) ? 1'b0 : 1'b1; end if(req[2]) begin gnt_pre[2] = (req2_used_status==4) ? 1'b1 : ((req1 & (req1_used_status > req2_used_status)) ? 1'b0 : ((req0 & (req0_used_status > req2_used_status)) ? 1'b0 : ((req3 & (req3_used_status > req2_used_status)) ? 1'b0 : 1'b1; end if(req[3]) begin gnt_pre[3] = (req3_used_status==4) ? 1'b1 : ((req0 & (req0_used_status > req3_used_status)) ? 1'b0 : ((req2 & (req2_used_status > req3_used_status)) ? 1'b0 : ((req1 & (req1_used_status > req3_used_status)) ? 1'b0 : 1'b1; end end //GNT_REQUEST assign gnt[NUMCLIENTS - 1:0] = gnt_pre[NUMCLIENTS - 1:0]; <<<<<<< HEAD """ ======= endmodule """ >>>>>>> 4006e27d0108573ad2367bef47ea28d7408e5b8e <file_sep>from math import log2,ceil from templates import arbiter_body_template,weight_update_template import sys class Arbiter: def __init__(self, numclients, weight=None): self.NumClients = numclients self.EncodedNumClients = int(ceil(log2(numclients))) self.arbiter_body = None self.weight = weight def shift_request(self): shift_request_code = "case (rotate_ptr["+str(self.EncodedNumClients - 1)+":0])\n\t\t\t" \ + str(self.EncodedNumClients)+"'b"+"0"*self.EncodedNumClients + ": shift_req["+str(self.NumClients-1)+":0] = " \ "req["+str(self.NumClients-1)+":0];\n\t\t\t" + \ str(self.EncodedNumClients)+"'b"+"0"*(self.EncodedNumClients-1)+"1: shift_req[" + str(self.NumClients-1)+":0] = " \ "{req[0],req["+str(self.NumClients-1)+":1]};\n\t\t\t" for i in range(2, self.NumClients-1): shift_request_code += str(self.EncodedNumClients)+"'b"+"0"*(self.EncodedNumClients-len(bin(i)[2:]))+bin(i)[2:]+":" \ " shift_req["+str(self.NumClients-1)+":0] = {req["+str(i-1)+":0],req["+str(self.NumClients-1)+":" \ + str(i)+"]};\n\t\t\t" shift_request_code += str(self.EncodedNumClients)+"'b"+bin(self.NumClients-1)[2:]+": shift_req["+str(self.NumClients-1)+":0] = " \ "{req["+str(self.NumClients-2)+":0],req["+str(self.NumClients-1)+"]};" self.arbiter_body = self.arbiter_body.replace("//SHIFT_REQUEST",shift_request_code) def shift_grant(self): shift_grant_code = "shift_grant["+str(self.NumClients-1)+":0] = " +str(self.NumClients)+"" \ "'b0;\n\t\t\tif (shift_req[0]) shift_grant[0] = 1'b1;\n\t\t\t" for i in range(1,self.NumClients): shift_grant_code += "else if (shift_req["+str(i)+"]) shift_grant["+str(i)+"] = 1'b1;\n\t\t\t" self.arbiter_body = self.arbiter_body.replace("//SHIFT_GRANT",shift_grant_code) def grant_signal(self): grant_signal_code = "case (rotate_ptr["+str(self.EncodedNumClients - 1)+":0])\n\t\t\t" \ + str(self.EncodedNumClients)+"'b"+"0"*self.EncodedNumClients + ": grant_comb["+str(self.NumClients-1)+":0] = " \ "shift_grant["+str(self.NumClients-1)+":0];\n\t\t\t" + \ str(self.EncodedNumClients)+"'b"+"0"*(self.EncodedNumClients-1)+"1: grant_comb[" + str(self.NumClients-1)+":0] = " \ "{shift_grant["+str(self.NumClients-2)+":0]," \ "shift_grant["+str(self.NumClients-1)+"]};\n\t\t\t" for i in range(self.NumClients-3, 0, -1): grant_signal_code += str(self.EncodedNumClients)+"'b"+"0"*(self.EncodedNumClients-len(bin(self.NumClients-i-1)[2:]))+bin(self.NumClients-i-1)[2:]+":" \ " grant_comb["+str(self.NumClients-1)+":0] = {shift_grant["+str(i)+":0],shift_grant["+str(self.NumClients-1)+":" \ + str(i+1)+"]};\n\t\t\t" grant_signal_code += str(self.EncodedNumClients)+"'b"+bin(self.NumClients-1)[2:]+":" \ " grant_comb["+str(self.NumClients-1)+":0] = {shift_grant[0],shift_grant["+str(self.NumClients-1)+":1]};\n" self.arbiter_body = self.arbiter_body.replace("//GRANT_SIGNAL",grant_signal_code) def rotate(self): rotate_code = "" for i in range(self.NumClients): rotate_code += "grant["+str(i)+"]: rotate_ptr["+str(self.EncodedNumClients-1)+":0] <= " \ + ("| nweight"+str(i)+" ? : rotate_ptr :" if self.weight is not None else "")+str(self.EncodedNumClients)+"'d"+str((i+1) % self.NumClients)+";\n\t\t\t" self.arbiter_body = self.arbiter_body.replace("//ROTATION",rotate_code) def declare_weight_inputs(self): declaration = "\n".join(["cfg_weight" + str(i) + "," for i in range(self.NumClients)]) self.arbiter_body = self.arbiter_body.replace("//CFG_DECLARATIONS", ","+declaration) def declare_weight_vectors(self): declaration = "\n".join(["input ["+str(self.weight)+":0] cfg_weight"+str(i)+";" for i in range(self.NumClients)]) self.arbiter_body = self.arbiter_body.replace("//INPUT_WEIGHT_VECTORS", declaration) def declare_weight_registers(self): declaration = "\n".join(["reg ["+str(self.weight)+":0] weight" + str(i) + ";" for i in range(self.NumClients)]) self.arbiter_body = self.arbiter_body.replace("//WEIGHT_REGISTERS", declaration) def get_body(self): self.arbiter_body = arbiter_body_template self.arbiter_body = self.arbiter_body.replace("ENCODEDNUMCLIENTS - 1", str(self.EncodedNumClients - 1)) self.arbiter_body = self.arbiter_body.replace("ENCODEDNUMCLIENTS", str(self.EncodedNumClients)) self.arbiter_body = self.arbiter_body.replace("NUMCLIENTS - 1", str(self.NumClients - 1)) self.arbiter_body = self.arbiter_body.replace("NUMCLIENTS", str(self.NumClients)) self.shift_request() self.shift_grant() self.grant_signal() self.rotate() if self.weight is not None: self.declare_weight_inputs() self.declare_weight_registers() self.declare_weight_vectors() self.arbiter_body = self.arbiter_body +"\n"+ self.update_weight_code() def update_weight_code(self): update_weight_code = weight_update_template update_weight_code = update_weight_code.replace("//WEIGHT_BIT", "\n".join(["weight" + str(i) + " <= "+str(self.weight+1)+"'d0;" for i in range(self.NumClients)])) update_weight_code = update_weight_code.replace("//WEIGHT_NEGATION", "\n".join(["weight" + str(i) + " <= " + "nweight" + str(i) + ";" for i in range(self.NumClients)])) update_weight_code = update_weight_code.replace("//REFRESH_WEIGHT", " & ".join(["(~|weight" + str(i)+")" for i in range(self.NumClients)]) + ";") assign_weight = "" for i in range(self.NumClients): assign_weight += "assign nweight"+str(i)+" = refresh_weights ? cfg_weight"+str(i)+" : (req["+str(i)+"] & gnt["+str(i)+"]) ? " \ "weight"+str(i)+" - 1'b1 : weight"+str(i)+";\n" update_weight_code = update_weight_code.replace("//ASSIGN_WEIGHT",assign_weight) return update_weight_code def __str__(self): return self.arbiter_body + "endmodule" if len(sys.argv) > 2: trial = Arbiter(int(sys.argv[1]), int(sys.argv[2])) else: trial = Arbiter(int(sys.argv[1])) trial.get_body() print(trial) <file_sep>#================================================================================================== # This is a pipelined divisor Module. It can have number of pipes which are mentioned by stages # variable. Also the bit width of divisor is available. # TODO: A final touch is pending on this block to transform the code into multiple inheritence # dictionary at class level. # TODO: The body of the code where main verilog and intermittant Python is written can be # further moved to bottom side. We need to think through this more. #================================================================================================== import sys import os from smartasic import BasicModule,Port from DynamicGenerator import DynamicGenerator from BusParser import BusParser from pathlib import Path class DivPipelined(BasicModule, BusParser): def add_ports_from_bus(self, filepath, bus_name): # parser = BusParser(filepath, bus_name) self.widop_flat('dividend',self.bits) self.widop_flat('divisor',self.bits) self.get_all_key_value_pairs(self.dict) def Create_dic_of_variable(self): self.variable_dict['bits']=self.bits self.variable_dict['stages']=self.stages def get_body(self): dynamicgenerator=DynamicGenerator(self.variable_dict,self.DivPipelinedBody) self.body+=dynamicgenerator.parse_body() self.body=self.body.replace("BITS*2*(STAGES-1)-1",str(self.bits*2*self.stages-1-1)) self.body=self.body.replace("BITS*2*(STAGES-2)-2",str(self.bits*2*self.stages-2-2)) self.body=self.body.replace("BITS*2*(STAGES-2)+1",str(self.bits*2*self.stages-2+1)) self.body=self.body.replace("BITS*2*(STAGES-2)-1",str(self.bits*2*self.stages-2-1)) self.body=self.body.replace("BITS*2*(STAGES-2)",str(self.bits*2*self.stages-2)) self.body=self.body.replace("BITS*2*(STAGES-3)",str(self.bits*2*self.stages-3)) self.body=self.body.replace("BITS*2*2-1",str(self.bits*2*2-1)) self.body=self.body.replace("BITS*2-1",str(self.bits*2-1)) self.body=self.body.replace("BITS-2",str(self.bits-2)) self.body=self.body.replace("BITS*2",str(self.bits*2)) self.body=self.body.replace("STAGES-2",str(self.stages-2)) self.body=self.body.replace("STAGES-1",str(self.stages-1)) self.body=self.body.replace("STAGES-3",str(self.stages-3)) self.body=self.body.replace("BITS-1",str(self.bits-1)) dynamicgenerator.silentremove() def get_verilog(self): modulecode=self.get_header() self.get_body() modulecode=modulecode.replace("BODY",self.body) return modulecode def main(self): self.write_to_file(self.get_verilog()) return self.get_verilog() def __init__(self,bits,stages,path_of_yaml=None,bus_name=None): self.bits=bits self.stages=stages self.body="" self.name="AH_"+self.__class__.__name__+"_"+str(bits)+"_"+str(stages) BasicModule.__init__(self , self.name) self.variable_dict={} BusParser.__init__(self,self.load_dict(path_of_yaml),bus_name) self.Create_dic_of_variable() self.add_ports_from_bus(path_of_yaml,bus_name) self.DivPipelinedBody= """ //======================================================================================================================================================= `timescale 1ns / 1ps reg data_valid; reg div_by_zero; reg [STAGES-1:0] start_gen, negative_quotient_gen, div_by_zero_gen; reg [BITS*2*(STAGES-1)-1:0] dividend_gen, divisor_gen, quotient_gen; wire [BITS-1:0] pad_dividend; wire [BITS-2:0] pad_divisor; assign pad_dividend = 0; assign pad_divisor = 0; always @ (posedge clk or negedge rst_n) begin if (!rst_n) begin div_by_zero_gen[0] <= 0; start_gen[0] <= 0; negative_quotient_gen[0] <= 0; dividend_gen[BITS*2-1:0] <= 0; divisor_gen[BITS*2-1:0] <= 0; end else begin div_by_zero_gen[0] <= (divisor == 0); start_gen[0] <= start; negative_quotient_gen[0] <= dividend[BITS-1] ^ divisor[BITS-1]; dividend_gen[BITS*2-1:0] <= (dividend[BITS-1]) ? ~{dividend,pad_dividend} + 1 : {dividend,pad_dividend}; divisor_gen[BITS*2-1:0] <= (divisor [BITS-1]) ? ~{1'b1,divisor, pad_divisor} + 1 : {1'b0,divisor, pad_divisor}; end end always @ (posedge clk or negedge rst_n) begin if (!rst_n) begin div_by_zero_gen[1] <= 0; start_gen[1] <= 0; negative_quotient_gen[1] <= 0; divisor_gen[BITS*2*2-1:BITS*2] <= 0; quotient_gen[BITS*2-1:0] <= 0; dividend_gen[BITS*2*2-1:BITS*2] <= 0; end else begin div_by_zero_gen[1] <= div_by_zero_gen[0]; start_gen[1] <= start_gen[0]; negative_quotient_gen[1] <= negative_quotient_gen[0]; divisor_gen[BITS*2*2-1:BITS*2] <= divisor_gen[BITS*2-1:0] >> 1; if ( dividend_gen[BITS*2-1:0] <= divisor_gen[BITS*2-1:0]) begin quotient_gen[BITS*2-1:0] <= 1 << STAGES - 2; dividend_gen[BITS*2*2-1:BITS*2] <= dividend_gen[BITS*2-1:0] - divisor_gen[BITS*2-1:0]; end else begin quotient_gen[BITS*2-1:0] <= 0; dividend_gen[BITS*2*2-1:BITS*2] <= dividend_gen[BITS*2-1:0]; end end // else: !if(!rst_n) end // always @ (posedge clk) /f_f/ code="" for i in range(1,stages-2): code+="\\nalways @ (posedge clk or negedge rst_n) begin" code+="\\n\tif (!rst_n) begin" code+="\\n\t\tdiv_by_zero_gen["+str(i+1)+"]\t\t<= 0;" code+="\\n\t\tstart_gen["+str(i+1)+"]\t\t\t<= 0;" code+="\\n\t\tnegative_quotient_gen["+str(i+1)+"]\t<= 0;" code+="\\n\t\tdivisor_gen["+str(bits*2*(i+2)-1)+":"+str(bits*2*(i+1))+"]\t\t<= 0;" code+="\\n\t\tquotient_gen["+str(bits*2*(i+1)-1)+":"+str(bits*2*i)+"]\t\t<= 0;" code+="\\n\t\tdividend_gen["+str(bits*2*(i*2)-1)+":"+str(bits*2*(i+1))+"]\t\t<= 0;" code+="\\n\tend else begin" code+="\\n\t\tdiv_by_zero_gen["+str(i+1)+"]\t\t<=div_by_zero_gen["+str(i)+"];" code+="\\n\t\tstart_gen["+str(i+1)+"]\t\t\t<=strat_gen["+str(i)+"];" code+="\\n\t\tnegative_quotient_gen["+str(i+1)+"]\t<=negative_quotient_gen["+str(i)+"];" code+="\\n\t\tdivisor_gen["+str(bits*2*(i+2)-1)+":"+str(bits*2*(i+1))+"]\t\t<=divisor_gen["+str(bits*2*(i+1)-1)+":"+str(bits*2*i)+"] >> 1;" code+="\\n\t\tif (dividend_gen["+str(bits*2*i+1-1)+":"+str(bits*2*i)+"]\t\t<=divisor_gen["+str(bits*2*i+1-1)+":"+str(bits*2*i)+"] begin" code+="\\n\t\tquotient_gen["+str(bits*2*(i+1)-1)+":"+str(bits*2*i)+"]\t\t<=quotient_gen["+str(bits*2*i-1)+":"+str(bits*2*(i-1))+"] | (1 << "+str(stages-2-i)+")" code+="\\n\t\tdividend_gen["+str(bits*2*(i+2)-1)+":"+str(bits*2*(i+1))+"]\t\t<= dividend_gen["+str(bits*2*(i+1)-1)+":"+str(bits*2*i)+"] - divisor_gen["+str(bits*2*(i+1)-1)+":"+str(bits*2*i)+"];\\n\tend else begin" code+="\\n\t\tquotient_gen["+str(bits*2*(i+1)-1)+":"+str(bits*2*i)+"]\t\t<= quotient_gen["+str(bits*2*i-1)+":"+str(bits*2*(i-1))+"];" code+="\\n\t\tdividend_gen["+str(bits*2*(i+2)-1)+":"+str(bits*2*(i+1))+"]\t\t<= dividend_gen["+str(bits*2*(i+1)-1)+":"+str(bits*2*i)+"];\\n\t\tend \\n\tend \\nend \\n" /f_f/ /f_f/ code="" code+="always @ (posedge clk or negedge rst_n) begin" code+="\\n\tdiv_by_zero_gen["+str(stages-1)+"]\t<= 0;" code+="\\n\tnegative_quotient_gen["+str(stages-1)+"]\t<= 0;" code+= "\\n\tquotient_gen["+str(bits*2*(stages-1)-1)+":"+str(bits*2*(stages-2))+"] <= 0; end else begin" code+="\\n\tdiv_by_zero_gen["+str(stages-1)+"]\t<= div_by_zero_gen["+str(stages-2)+"];" code+="\\n\tstart_gen["+str(stages-1)+"]\t<= start_gen["+str(stages-2)+"];" code+="\\n\tnegative_quotient_gen["+str(stages-1)+"]\t<= negative_quotient_gen["+str(stages-2)+"];" code+="\\n\tif ( dividend_gen["+str(bits*2-1)+":0]\t<= divisor_gen["+str(bits*2-1)+":0]) begin" code+="\\n\tquotient_gen["+str(bits*2-1)+":0] \t<= 1 << "+str(stages - 2)+";" code+="\\n\tif ( dividend_gen["+str(bits*2*(stages-1)-1)+":"+str(bits*2*(stages-2))+"] \t<= divisor_gen["+ str(bits*2*(stages-1)-1)+":"+str(bits*2*(stages-2))+"] )" code+="\\n\tquotient_gen["+str(bits*2*(stages-1)-1)+":"+str(bits*2*(stages-2))+"] \t<= quotient_gen["+str(bits*2*(stages-2)-1)+":"+str(bits*2*(stages-3))+"] | 1;\\n\telse" code+="\\n\tquotient_gen["+str(bits*2*(stages-1)-1)+":"+str(bits*2*(stages-2))+"] \t<= quotient_gen["+str(bits*2*(stages-2)-1)+":"+str(bits*2*(stages-3))+"];\\n\t\tend\\n\tend" /f_f/ always @ (posedge clk or negedge rst_n) begin if (!rst_n) begin div_by_zero_gen[STAGES-1]<= 0; start_gen[STAGES-1]<= 0; negative_quotient_gen[STAGES-1]<= 0; quotient_gen[BITS*2*(STAGES-1)-1:BITS*2*(STAGES-2)]<= 0; end else begin div_by_zero_gen[STAGES-1]<= div_by_zero_gen[STAGES-2]; start_gen[STAGES-1]<= start_gen[STAGES-2]; negative_quotient_gen[STAGES-1]<= negative_quotient_gen[STAGES-2]; if ( dividend_gen[BITS*2*(STAGES-1)-1:BITS*2*(STAGES-2)] <= divisor_gen[BITS*2*(STAGES-1)-1:BITS*2*(STAGES-2)] ) quotient_gen[BITS*2*(STAGES-1)-1:BITS*2*(STAGES-2)] <= quotient_gen[BITS*2*(STAGES-2)-1:BITS*2*(STAGES-3)] | 1; else quotient_gen[BITS*2*(STAGES-1)-1:BITS*2*(STAGES-2)] <= quotient_gen[BITS*2*(STAGES-2)-1:BITS*2*(STAGES-3)]; end // else: !if(!rst_n) end // always @ (posedge clk) always @ (posedge clk or negedge rst_n) begin if (!rst_n) begin div_by_zero <= 0; data_valid <= 0; quotient <= 0; end else begin div_by_zero <= div_by_zero_gen[STAGES-1]; data_valid <= start_gen[STAGES-1]; quotient <= (negative_quotient_gen[STAGES-1]) ? ~quotient_gen[BITS*2*(STAGES-1)-1:BITS*2*(STAGES-2)+1]: quotient_gen[BITS*2*(STAGES-1)-1:BITS*2*(STAGES-2)]; end end //======================================================================================================================================================= """ dp=DivPipelined(int(sys.argv[1]), int(sys.argv[2]), sys.argv[3], sys.argv[4]) dp.main() <file_sep>import sys import os from smartasic import BasicModule,Port from math import log2,ceil from DynamicGenerator import DynamicGenerator from BusParser import BusParser from pathlib import Path class PacketConverter(BasicModule,BusParser): def Create_dic_of_variable(self): self.variable_dict['WideWidth']=self.WideWidth self.variable_dict['NarrowWidth']=self.NarrowWidth self.variable_dict['isW2N']=self.isW2N self.variable_dict['ratio']=self.ratio self.variable_dict['VecWidth']=self.VecWidth def add_ports_from_bus(self, filepath, bus_name): # parser = BusParser(filepath, bus_name) self.remove_sub_dict_flat("snoop") self.rename_flat("wcredit","wready") self.rename_flat("rcredit","rready") self.widop_flat('rdata',self.WideWidth) self.widop_flat("wdata",self.NarrowWidth) self.flipop_flat("wr") self.flipop_flat("rd") self.get_all_key_value_pairs(self.dict) def get_body(self): dynamicgenerator=DynamicGenerator(self.variable_dict,self.packetconverter) self.body+=dynamicgenerator.parse_body() self.body = self.body.replace("WIDEWIDTH - 1", str(self.WideWidth - 1)) self.body = self.body.replace("VECWIDTH - 1", str(self.VecWidth - 1)) self.body = self.body.replace("NARROWWIDTH - 1", str(self.NarrowWidth - 1)) self.body = self.body.replace("WIDEWIDTH", str(self.WideWidth)) self.body = self.body.replace("VECWIDTH", str(self.VecWidth)) dynamicgenerator.silentremove() def get_verilog(self): modulecode=self.get_header() self.get_body() modulecode=modulecode.replace("BODY",self.body) return modulecode def main(self): self.write_to_file(self.get_verilog()) return self.get_verilog() def __init__(self, width1, width2, isW2N,path_of_yaml=None,bus_name=None): self.WideWidth = max(width1, width2) self.NarrowWidth = min(width1, width2) self.isW2N = isW2N self.ratio = (self.WideWidth // self.NarrowWidth) self.VecWidth = int(log2(self.WideWidth/self.NarrowWidth)) if self.isW2N == "True": self.name = "AH_"+self.__class__.__name__+"_w2n_"+str(self.NarrowWidth)+"_"+str(self.WideWidth) else: self.name = "AH_"+self.__class__.__name__+"_n2w_"+str(self.NarrowWidth)+"_"+str(self.WideWidth) BasicModule.__init__(self, self.name) self.body="" BusParser.__init__(self,self.load_dict(path_of_yaml),bus_name) self.variable_dict={} self.Create_dic_of_variable() self.add_ports_from_bus(path_of_yaml,bus_name) self.packetconverter=""" /f_f/ code="" if isW2N == "True": code +="reg ["+str(WideWidth)+":0] collated_packet;" /f_f/ reg [VECWIDTH - 1:0] packet_lane; wire [VECWIDTH - 1:0] npacket_lane; always(@posedge clk or negedge rstn) begin if (!rstn) begin packet_lane <= VECWIDTH'd0; /f_f/ code="\tcollated_packet <="+str(WideWidth)+"'d0;" /f_f/ end else begin packet_lane <= npacket_lane; /f_f/ code="\tcollated_packet <= ncollated_packet;" /f_f/ end end /f_f/ if isW2N == "True": code = "assign npacket_lane = (rd_valid & wr_ready) ? packet_lane +1'b1 :\\npacket_lane;" code += "assign wr_valid = rd_valid;\\n" \ "assign wr_data = rd_data >> ("+str(NarrowWidth)+"* packet_lane); \\n" \ "assign rd_ready = wr_ready & (packet_lane == "+str(VecWidth)+"'d"+str(ratio-1)+")" else: code = "assign npacket_lane = !rd_valid ? packet_lane:\\n\t" \ "(packet_lane != "+str(VecWidth)+"'d"+str(ratio-1)+") ? packet_lane + 1'b1:\\n\t" \ "wr_ready ? packet_lane + 1'b1 :packet_lane;" code += "\\nwire assign ncollated_packet = ( (packet_lane == "+str(VecWidth)+"'d"+str(ratio)+") " \ "&& rd_valid && wr_ready ) ? "+str(WideWidth)+"'d0 : " \ "? {collated_packet, rd_data} : " \ "collated_packet;" code += "\\nassign wr_valid = rd_valid && (packet_lane == "+str(VecWidth)+"'d"+str(ratio)+");\\n" \ "assign rd_ready = (packet_lane == "+str(VecWidth)+"'d"+str(ratio)+") ? wr_ready ? 1'b1;\\n" \ "assign wr_data = ncollated_packet;" /f_f/ """ packetconverter=PacketConverter(int(sys.argv[1]), int(sys.argv[2]), sys.argv[3],sys.argv[4], sys.argv[5]) packetconverter.main() <file_sep>from templates import lruArbiter_body import sys class LruArbiter: def ___init__(self, num_clients): self.Num_Clients=num_clients self.body = None def get_body(self): self.body =lruArbiter_body self.body = self.body.replace("NUMCLIENTS - 1", str(self.Num_Clients -1)) def reg_status(self): code = "\n"+"\n".join(["req ["+str(self.Num_Clients-1)+":0] req"+str(i)+"_used_status;" for i in range(self.Num_Clients)]) self.body = self.body.replace("//REG_STATUS", code) def status_used(self): code="\n"+"\n".join(["req"+str(i)+"_used_status <= "+str(self.Num_clients)+"'d"+str(self.Num_Clients-i)+";" for i in range(self.Num_Clients)]) self.body=self.body.replace("//STATUS_USED",code) def gnt(self): code="\n"+"\t".join(["req"+str(i)+"_used_status <= "+str(self.Num_Clients)+"'b1;" if i==j else "req"+str(j)+"_used_status <= req"+str(j)+"_used_status<req"+str(i)+"_used_status ? req"+str(j)+"_used_status + 1'b1 : req"+str(j)_"used_status;" for i in range(self.Num_Clients) for j in range(self.Num_Clients)]) self.body=self.body.repalce("//GNT_STATS",code) def gnt_request(self): code="\n"+"\t".join(["(req"+str(i)+"_used_status=="+str(self.Num_Clients)+") ? 1'b1 :" if j==j else "((req"+str(j)+" & (req"+str(j)+"_used_status > req"+str(i)+"_used_status)) ? 1'b0:" for i in range(self.Num_Clients) for j in range(self.Num_Clients)])+"\n\t1'b1;" self.body=self.body.repalce("//GNT_REQUEST",code) def __str__(self): self.get_body() return self.body print(LruArbiter(int(sys.argv[1]))) <file_sep>from math import ceil, log2 from templates import cam_body_template import sys from smartasic import BasicModule from BusParser import BusParser class CAM(BusParser, BasicModule): def __init__(self, camdepth, camwidth, snoopwidth, bus_name, path_of_yaml): self.CamDepth = camdepth self.EncodedDepth = ceil(log2(int(camdepth))) self.SnoopWidth = snoopwidth self.CamWidth = camwidth self.name = "AH_" + self.__class__.__name__ + "_" + str(camdepth) + "_" + str(camwidth) + "_" + str(snoopwidth) BasicModule.__init__(self,self.name) self.body = None BusParser.__init__(self, path_of_yaml, bus_name) self.add_ports_from_bus() #======================================================= # overwrite the add_ports_from_bus method here. # Create the instance of busparser class. # Then use the wid_op method to change the port width req, gnt, gnt_busy signals. #======================================================= def add_ports_from_bus(self): #1. assuming that we are loading arbiter.yaml #2. parser.wid_op (num_clientm , a.b.c.d format pass the signal name) #3. Do this for all the signals that are required. #print(parser.dict) BasicModule.add_ports_from_bus(self) self.widop_flat("wdata",self.CamWidth) self.widop_flat("rdata",self.CamWidth) self.widop_flat("sdata",self.CamWidth) self.add_sub_dict_flat("snoop" , {"sin" : {"direction" : "input" , "type" : "fluid" , "width" : self.SnoopWidth}}) self.get_all_key_value_pairs(self.dict) def get_body(self): self.body = cam_body_template self.body = self.body.replace("ENCODEDDEPTH - 1", str(self.EncodedDepth-1)) self.body = self.body.replace("ENCODEDDEPTH", str(self.EncodedDepth)) self.body = self.body.replace("CAMWIDTH - 1", str(self.CamWidth - 1)) self.body = self.body.replace("CAMWIDTH", str(self.CamWidth)) self.body = self.body.replace("SNOOPWIDTH - 1", str(self.SnoopWidth - 1)) self.body = self.body.replace("SNOOPWIDTH", str(self.SnoopWidth)) self.body = self.body.replace("//REG_DECLARATION" , self.get_reg_str("reg","\n",self.CamWidth,"cam_loc",self.CamDepth)) self.body = self.body.replace("//CAM_LOCATIONS" , self.write_loc_rstn("\n\t", "cam_loc", self.CamWidth, self.CamDepth)) self.body = self.body.replace("//ASSIGN_SNOOP", self.snoop_inv("\n", self.SnoopWidth,"snoop_in", "cam_loc",self.CamDepth,self.CamWidth)) self.body = self.body.replace("//CAM_WRITE",self.cam_write("\n\t","cam_loc",self.CamDepth,self.EncodedDepth)) self.body = self.body.replace("//ASSIGN_FREEUP", self.snoop_get_wr_ptr("|\n","cam_loc","snoop_in",self.SnoopWidth,self.EncodedDepth,self.CamDepth)) self.body = self.body.replace("//SNOOP_MATCH",self.snoop_match_noinv("cam_loc","snoop_in",self.SnoopWidth,self.CamDepth,"|\n")) def get_verilog(self): modulecode = self.get_header() self.get_body() modulecode = modulecode.replace("BODY", self.body) return modulecode def __str__(self): self.write_to_file(self.get_verilog()) return self.get_verilog() #print(CAM(int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]),sys.argv[4],sys.argv[5])) <file_sep>#ACTION ITEMS :- # 1. Adding all the rules for the connection forcedout - or smartout method # 2. Provide a default yaml in the init of class, but keep option open to take that as argument. # 3. regular expression - whatever gets stored through regular expression, retrieve them from default variables. #****** # 4. Remove the "None" arg from smartconnectionop. # 5. Once above 4 is done, create a replica of AH_2Ordered_switch.v ---> that will be put in smartasicUp.sh # 6. Add a looping support of objects in DynamicGenerator - not now. More thought process is required. **** obj1.smart_connport("astob", "cl_", "egress0_ds_pkt_") obj2.smart_conn("astob", "wr_", "egress0_ds_pkt_") obj3.smart_conn("astob", "rd_", "egress0_ds_pkt_") obj4.smart_conn("astob", "sn_", "egress0_ds_pkt_") u_demux_4_25.smart_connectionop("astob", None,"egres(.)_dspkt_valid","egress${1}_dspkt_valid_pre") u_demux_4_25.smart_connectionop("astob", None,"egres(.)_(dspkt)_(valid)","${3}_${2}_egress${1}") "egress(0)_dspkt_valid/egress{1}_dspkt_valid_pre" "{0} a good {1}".format("have","day") mo.group(1) /1\ import copy import yaml from AH_SnoopableFIFO import SnoopableFIFO from smartasic import BasicModule from BusParser import BusParser import sys print(sys.path) class OrderedSwitch(BasicModule): def get_body(self): object_dict = {} spf1 = SnoopableFIFO(self.DsPktSize, self.SnoopDepth, self.upResponseDecodableFieldWidth , "/home/mayukhs/Documents/smartasic2/refbuses/astob_for_order_switch.yaml", "astob") object_dict.update({"u_egress0_snoopablefifo_"+str(self.DsPktSize)+"_"+str(self.SnoopDepth)+"_"+str(self.upResponseDecodableFieldWidth) : spf1}) spf1.smart_connectionop("astob", None,"wr_","egress0_dspkt_") spf1.smart_connectionop("astob", None, "rd_", "egress0_dspkt_") spf1.smart_connectionop("astob", None, "snoop_", "egress0_dspkt_") spf1.add_connection_flat("svalid","{ingress_decoded[1], ingress_decoded[2], ingress_decoded[3]}") #print(spf1.dict) object_dict.update({"u_egress0_snoopablefifo_"+str(self.DsPktSize)+"_"+str(self.SnoopDepth)+"_"+str(self.upResponseDecodableFieldWidth) : spf1}) for i in range(1, self.NumberOfEgress): curr_obj = copy.deepcopy(spf1) curr_obj.smart_connectionop("astob", None, "egress0" , "egress"+str(i)) self.port_dict , self.wire_dict = self.populate_wire_and_ports(object_dict.values()) def main(self): self.get_body() def __init__(self, number_of_egress,ds_packet_size, ups_packet_size, ds_decodable_field_width, ups_response_decodable_field_width, snoopdepth): self.name = "AH_"+self.__class__.__name__+"_"+str(number_of_egress)+"_"+str(ds_packet_size)+"_"+str(ups_packet_size)+"_"+str(ds_decodable_field_width)+"_"+str(ups_response_decodable_field_width) BasicModule.__init__(self, self.name) self.NumberOfEgress = number_of_egress self.DsPktSize = ds_packet_size self.SnoopDepth = snoopdepth self.upPktSize = ups_packet_size self.dsDecodableFieldWidth = ds_decodable_field_width self.upResponseDecodableFieldWidth = ups_response_decodable_field_width self.port_dict = {} self.wire_dict = {} self.order_body = """ // 4 --> number of egress. // 25 -> ds packet size // 20 -> upstream packet size. // 10 -> address or downstream decodable field width. // 12 -> id or ordering and upstream-response decodable field width. // ====================================================== // ====================================================== // This is commented out code. Generated verilog will // Take care of it. // ====================================================== // ====================================================== // === module AH_ordered_switch_4_25_20_10_12 ( // === clk, // === rstn, // === // === // ================================================ // === ingress_ds_pkt, // === ingress_ds_pkt_valid, // === ingress_ds_pkt_ready, // === // === ingress_us_pkt, // === ingress_us_pkt_valid, // === ingress_us_pkt_ready, // === // === // ================================================ // === egress0_ds_pkt, // === egress0_ds_pkt_valid, // === egress0_ds_pkt_ready, // === // === egress0_us_pkt, // === egress0_us_pkt_valid, // === egress0_us_pkt_ready, // === // === // ================================================ // === egress1_us_pkt, // === egress1_us_pkt_valid, // === egress1_us_pkt_ready, // === // === egress1_ds_pkt, // === egress1_ds_pkt_valid, // === egress1_ds_pkt_ready, // === // === // =============================================== // === egress2_ds_pkt, // === egress2_ds_pkt_valid, // === egress2_ds_pkt_ready, // === // === egress2_us_pkt, // === egress2_us_pkt_valid, // === egress2_us_pkt_ready, // === // === // =============================================== // === egress3_ds_pkt, // === egress3_ds_pkt_valid, // === egress3_ds_pkt_ready, // === // === egress3_us_pkt, // === egress3_us_pkt_valid, // === egress3_us_pkt_ready, // === // === ); // === // === // // === =========================================================================================== // === // // === =========================================================================================== // === // === input clk; // === input rstn; // === // === // ================================================ // === input [24:0] ingress_ds_pkt_data; // === input ingress_ds_pkt_valid; // === output ingress_ds_pkt_ready; // === // === output [19:0] ingress_us_pkt_data; // === output ingress_us_pkt_valid; // === input ingress_us_pkt_ready; // === // === // ================================================ // === output [24:0] egress0_ds_pkt; // === output egress0_ds_pkt_valid; // === input egress0_ds_pkt_ready; // === // === input [19:0] egress0_us_pkt; // === input egress0_us_pkt_valid; // === output egress0_us_pkt_ready; // === // === // ================================================ // === output [24:0] egress1_ds_pkt; // === output egress1_ds_pkt_valid; // === input egress1_ds_pkt_ready; // === // === input [19:0] egress1_us_pkt; // === input egress1_us_pkt_valid; // === output egress1_us_pkt_ready; // === // === // ================================================ // === output [24:0] egress2_ds_pkt; // === output egress2_ds_pkt_valid; // === input egress2_ds_pkt_ready; // === // === input [19:0] egress2_us_pkt; // === input egress2_us_pkt_valid; // === output egress2_us_pkt_ready; // === // === // ================================================ // === output [24:0] egress3_ds_pkt; // === output egress3_ds_pkt_valid; // === input egress3_ds_pkt_ready; // === // === output [19:0] egress3_us_pkt; // === output egress3_us_pkt_valid; // === input egress3_us_pkt_ready; // === // ================================================ // === // === // ============================================================================================================================ // === // Identify the ADDR field or similar downstream field which can help decide // === // the direction of transaction // === // === // 4 --> decode arm, 13 --> decode-field (typically address) ID. // === // === //TODO:Here we are assuming that upper most field contains address. // === //It might not be so in most cases. So the ordered-switch does need to have // === //that passed as a parameter. We need to decide whether ordered switch // === //reflects the name there. // === // === //TODO: Again each address aperture will be different and there's no way we // === //can pass this as argument. Even if we do, somewhere we need to provide it. // === //In current approach, the apertures will be built inside decoder. // === //Now ap_00001 can be a nomenclature on full Ahant's library. // === // ================================================ // === // ================================================ // === // ================================================ // === // spf1 = SnoopableFIFO(self.DsPktSize, self.SnoopDepth, self.upResponseDecodableFieldWidth , "/home/mayukhs/Documents/smartasic2/refbuses/astob_for_order_switch.yaml", "astob") // === // object_dict.update({"u_egress0_snoopablefifo_"+str(self.DsPktSize)+"_"+str(self.SnoopDepth)+"_"+str(self.upResponseDecodableFieldWidth) : spf1}) // === // spf1.smart_connectionop("astob", None,"wr_","egress0_dspkt_") // === // spf1.smart_connectionop("astob", None, "rd_", "egress0_dspkt_") // === // spf1.smart_connectionop("astob", None, "snoop_", "egress0_dspkt_") // === // // === // AH_decoder_4_10 u_decoder_4_10_ap_00001 ( // === // .decode_field (ingress_ds_pkt[24:24-9]), // === // .decode_output (ingress_decoded[3:0]) // === // ); /f_f/ # I am creating instance of the object here. # TODO: First important thing is - the default yaml file will be embedded # inside the class so that we can minimize coding. # VALID -> TODO: Secondly, the smart-connect needn't be called if the cname doesn't need any # change which is the case for demux here. # TODO: The regular expression based call on smart_connectionop. It can save lots of lines # of code. What is the internal variables for storage from regular expressions. u_demux_4_25 = AH_demux(self.NumEgress, self.DsPktSize, ../../../smartasic2/refbuses/demux_mux.yaml, demux_mux) u_demux_4_25 = AH_demux(self.NumEgress, self.DsPktSize) u_demux_4_25.add_connectionop("astob", None, "select", "") u_demux_4_25.smart_connectionop("astob", None,"egres(.)_dspkt_valid","egress${1}_dspkt_valid_pre") u_demux_4_25.get_object_declaration_str('u_demux_4_25') /f_f/ // === // ================================================ // === // ================================================ // === // ================================================ // === // // === // //AH_demux_4_25 u_demux_4_25 ( // .select (ingress_decoded[3:0]) // .ing_data (ingress_ds_pkt), // .ing_valid (ingress_ds_pkt_valid), // .ing_ready (ingress_ds_pkt_ready), // // .egr0_data (egress0_ds_pkt), //.egr0_valid (egress0_ds_pkt_valid_pre), // .egr0_ready (egress0_ds_pkt_ready), // .egr1_data (egress1_ds_pkt), // .egr1_valid (egress1_ds_pkt_valid_pre), // .egr1_ready (egress1_ds_pkt_ready), .egr2_data (egress2_ds_pkt), .egr2_valid (egress2_ds_pkt_valid_pre), .egr2_ready (egress2_ds_pkt_ready), .egr3_data (egress3_ds_pkt), .egr3_valid (egress3_ds_pkt_valid_pre), .egr3_ready (egress3_ds_pkt_ready), ); // === // // === // // 25 --> width of fifo // === // // 32 --> depth of FIFO - TODO: Again another parameter. It's not possible // === // // to reflect all of them in module name. It's better to probably keep a param // === // // list inside and create a .h fle for the same also. // === // u r t // === // //=================================================================================== // === // AH_snoopfifo_10_32_10 u_egress0_snoopfifo_25_32_12 ( // === // .clk (clk), // === // .rstn (rstn), // === // // === // .wr_data (egress0_ds_pkt), // === // .wr_valid (egress0_ds_pkt_valid), // === // .wr_ready (egress0_ds_pkt_ready), // === // // === // .rd_data (egress0_snoopfifo_rd), // === // .rd_valid (egress0_snoopfifo_rd_valid), // === // .rd_ready (egress0_snoopfifo_rd_ready), // === // // === // .snoop_data (egress0_ds_pkt), // === // .snoop_valid ({ingress_decoded[1], ingress_decoded[2], ingress_decoded[3]}), // === // .snoop_match (block_egress0_ds_pkt), // === // // === // ); /f_f/ for i in range(self.NumEgress): "u_egress"+str(i)+"_snoopfifo_10_32_12 = AH_snoopfifo(self.IdWidth, self.DsPktSize, self.AddrWidth)" "u_egress"+str(i)+"_snoopfifo_10_32_12.smart_connectionop("astob", None,"wr_","egress"+str(i)+"_dspkt_valid")" "u_egress"+str(i)+"_snoopfifo_10_32_12.smart_connectionop("astob", None,"wr_","egress"+str(i)+"_dspkt_valid")" "u_egress"+str(i)+"_snoopfifo_10_32_12.add_connectionop("astob", None,"snoop_data","egress"+str(i)+"dspkt")" "u_egress"+str(i)+"_snoopfifo_10_32_12.add_connectionop("astob", None,"snoop_valid","{ingress_decoded[1],ingress_decoded[2],ingress_decoded[3]}")" "u_egress"+str(i)+"_snoopfifo_10_32_12.add_connectionop("astob", None,"snoop_match","block_egress0_ds_pkt")" for i in range(self.NumEgress): "wire assign egress"+str(i)+"_ds_pkt_valid = ingress_decode[0] & !block_egress"+str(i)+"_ds_pkt & egress"+str(i)+"_ds_pkt_valid_pre;" wire assign egress1_ds_pkt_valid = ingress_decode[0] & !block_egress1_ds_pkt & egress1_ds_pkt_valid_pre; wire assign egress2_ds_pkt_valid = ingress_decode[0] & !block_egress2_ds_pkt & egress2_ds_pkt_valid_pre; wire assign egress3_ds_pkt_valid = ingress_decode[0] & !block_egress3_ds_pkt & egress3_ds_pkt_valid_pre; wire assign egress0_ds_pkt_valid = ingress_decode[0] & !block_egress0_ds_pkt & egress0_ds_pkt_valid_pre; /f_f/ // === // // === // //=================================================================================== // === // AH_snoopfifo_10_32_10 u_egress1_snoopablefifo_25_32_12 ( // === // .clk (clk), // === // .rstn (rstn), // === // // === // .wr_data (egress1_ds_pkt), // === // .wr_valid (egress1_ds_pkt_valid), // === // .wr_ready (egress1_ds_pkt_ready), // === // // === // .rd_data (egress1_snoopfifo_rd), // === // .rd_valid (egress1_snoopfifo_rd_valid), // === // .rd_ready (egress1_snoopfifo_rd_ready), // === // // === // .snoop_data (egress1_ds_pkt), // === // .snoop_valid ({ingress_decoded[2], ingress_decoded[3], ingress_decoded[0]}), // === // .snoop_match (block_egress1_ds_pkt), // === // // === // ); // === // // === // // === // //=================================================================================== // === // AH_snoopfifo_10_32_10 u_egress2_snoopablefifo_25_32_12 ( // === // .clk (clk), // === // .rstn (rstn), // === // // === // .wr_data (egress2_ds_pkt), // === // .wr_valid (egress2_ds_pkt_valid), // === // .wr_ready (egress2_ds_pkt_ready), // === // // === // .rd_data (egress2_snoopfifo_rd), // === // .rd_valid (egress2_snoopfifo_rd_valid), // === // .rd_ready (egress2_snoopfifo_rd_ready), // === // // === // .snoop_data (egress2_ds_pkt), // === // .snoop_valid ({ingress_decoded[3], ingress_decoded[0], ingress_decoded[1]}), // === // .snoop_match (block_egress2_ds_pkt), // === // // === // ); // === // // === // // === // //=================================================================================== // === // AH_snoopfifo_10_32_10 u_egress3_snoopablefifo_25_32_12 ( // === // .clk (clk), // === // .rstn (rstn), // === // // === // .wr_data (egress3_ds_pkt), // === // .wr_valid (egress3_ds_pkt_valid), // === // .wr_ready (egress3_ds_pkt_ready), // === // // === // .rd_data (egress3_snoopfifo_rd), // === // .rd_valid (egress3_snoopfifo_rd_valid), // === // .rd_ready (egress3_snoopfifo_rd_ready), // === // // === // .snoop_data (egress3_ds_pkt), // === // .snoop_valid ({ingress_decoded[0], ingress_decoded[1], ingress_decoded[2]}), // === // .snoop_match (block_egress3_ds_pkt), // === // // === // ); // === // // === // // TODO: Downstream path is complete more or less. // === // // Upstream path needs to be done. //=================================================================================== AH_arbrr_4 u_arbrr_4 ( .clk(clk), .rstn(rstn), //TODO: Choose one of the implementation .req ({ egress0_us_pkt_valid , egress1_us_pkt_valid , egress2_us_pkt_valid , egress3_us_pkt_valid }), //TODO: we need width-learning or something similar here. .grant (egress_arbed[3:0] ), ); /f_f/ #TODO: How to incorporate the string 4 into object name - tht's something to be seen. # Or leave it from the proposal altogether. #TODO: Again figure out how we can move this entire thing in loop. #TODO: string manipulation around smart_connect/add_connect becomes a big issue. #We need to address it effectively. u_arbrr_4 = AH_snoopfifo(self.NumEgress) u_arbrr_4.smart_connectionop("astob", None,"req","{egress0_uspkt_valid, egress1_us_pkt_valid, egress2_uspkt_valid, egress3_us_pkt_valid}") u_arbrr_4.add_connectionop("astob", None, "grant", "egress_arbed[3:0]") u_decoder_4_20 = AH_decoder(self.NumEgress, self.IdWidth) u_decder_4_20.add_connectionop("astob", None, "select", "egress_arbed") u_decder_4_20.smart_connectionop("astob", None, "egress_pkt", "arbed_out") u_decder_4_20.add_connectionop("astob", None, "egress_pkt_data", "ingress_uspkt_data") for i in range(self.NumEgress): u_decder_4_20.add_connectionop("astob", None, "ingress(.)_pkt", "egress[1]_uspkt") /f_f/ //=================================================================================== AH_decoder_4_20 u_decoder_4_20 ( .select (egress_arbed[3:0]), .egress_pkt_data (ingress_us_pkt_data), .eegress_pkt_valid (arbed_out_valid), .degress_pkt_ready (arbed_out_ready), .ingress0_pkt_data (egress0_us_pkt_data), .ingress0_pkt_valid (egress0_us_pkt_valid), .ingress0_pkt_ready (egress0_us_pkt_ready), .ingress1_pkt_data (egress1_us_pkt_data), .ingress1_pkt_valid (egress1_us_pkt_valid), .ingress1_pkt_ready (egress1_us_pkt_ready), .ingress2_pkt_data (egress2_us_pkt_data), .ingress2_pkt_valid (egress2_us_pkt_valid), .ingress2_pkt_ready (egress2_us_pkt_ready), .ingress3_pkt_data (egress3_us_pkt_data), .ingress3_pkt_valid (egress3_us_pkt_valid), .ingress3_pkt_ready (egress3_us_pkt_ready), ); //=================================================================================== // While sending upstream response valid - // For each egress channel- // if we find the guy has won grant and carries an entry with same trackable field(ID) // as the one stored in FIFO, we let it go. wire assign snoopfifo_rd_legal = 1'b0 | (egress_arbed[0] & egress0_snoopfifo_rd_valid & (egress0_snoopfifo_rd[11:0] = ingress_us_pkt[11:0]) ) | (egress_arbed[1] & egress1_snoopfifo_rd_valid & (egress1_snoopfifo_rd[11:0] = ingress_us_pkt[11:0]) ) | (egress_arbed[2] & egress2_snoopfifo_rd_valid & (egress2_snoopfifo_rd[11:0] = ingress_us_pkt[11:0]) ) | (egress_arbed[3] & egress3_snoopfifo_rd_valid & (egress3_snoopfifo_rd[11:0] = ingress_us_pkt[11:0]) ) | ); /f_f/ code = "\\n"+"\\n".join(["(egress_arbed[0] & egress0_snoopfifo_rd_valid & (egress0_snoopfifo_rd[upResponseDecodableFieldWidth - 1:0] = ingress_us_pkt[:0]) )" for i in range(NumberOfEgress)]) /f_f/ wire assign ingress_us_pkt_valid = arbed_out_valid & snoop_fifo_rd_legal; wire assign arbed_out_ready = ingress_us_pkt_ready & snoop_fifo_rd_legal; //TODO: watch out for timing in this area and think about simplifying the logic. wire assign egress0_snoopfifo_rd_ready = snoopfifo_rd_legal; wire assign egress1_snoopfifo_rd_ready = snoopfifo_rd_legal; wire assign egress2_snoopfifo_rd_ready = snoopfifo_rd_legal; wire assign egress3_snoopfifo_rd_ready = snoopfifo_rd_legal; endmodule // 25 --> width of fifo // 32 --> depth of FIFO - TODO: Again another parameter. It's not possible // to reflect all of them in module name. It's better to probably keep a param // list inside and create a .h fle for the same also. //Identify the ID or trackable field from downstream packet.Create snoop valid //and match signals from downstream request valid. // Instantiate the snoop FIFO - which can create a snoop match logic. Connect // the snoop match to decoder/demux output there. The decoder will have only // legal requests to egress arms forwarded downstream. // Instantiaate upstream decoder (based on trackable field as ID) // // Instantiate the upstream arbiter. """ t = OrderedSwitch(10, 20, 30, 40, 50) t.main() with open('/home/mayukhs/Documents/smartasic2/refbuses/order_port.yaml','w') as f: f.write(yaml.dump(t.port_dict)) print(t.port_dict) print("1"*50) #print(yaml.dump(t.wire_dict)) <file_sep> # TODO: Move this template strings to Jinja templates. module_template = """ module MODULENAME (PORTLIST); PORTDECLARATION BODY endmodule """ fifo_body_template = """ // ***************************************************************************** // Body of Module // ***************************************************************************** reg [ENCODEDDEPTH:0] wr_ptr, rd_ptr; always @(posedge clk,negedge rstn) begin if(!rstn) wr_ptr <= 0; else if(wr_valid & !wr_busy) wr_ptr <= (rd_valid & !rd_busy)? wr_ptr : wr_ptr+1; else if(rd_valid & !rd_busy) wr_ptr <= wr_ptr -1 ; end assign wr_busy = (wr_ptr == $fifo_depth) assign rd_valid = (wr_ptr != 0); reg [ENCODEDDEPTH - 1 :0] addr; reg [ENCODEDDEPTH - 1 :0] rd_addr; always @(posedge clk, negedge rstn) begin if(!rstn) addr <= 0; else if(wr_valid & !wr_busy) addr <= addr+1; end wire [FIFOWIDTH-1:0] mem_data[FIFODEPTH - 1 :0]; assign mem_data[addr][FIFOWIDTH-1:0] = wr_data[FIFOWIDTH-1:0] always @(posedge clk, negedge rstn) begin if(!rstn) rd_addr <=0; else if (rd_valid & !rd_busy) rd_addr <= rd_addr +1; end assign rd_data = mem_data[rd_addr]; // ***************************************************************************** """ ArbiterBody = """ //Rotate -> Priority -> Rotate //INPUT_WEIGHT_VECTORS reg [ENCODEDNUMCLIENTS - 1:0] rotate_ptr; reg [NUMCLIENTS - 1:0] shift_req; reg [NUMCLIENTS - 1:0] shift_grant; reg [NUMCLIENTS - 1:0] grant_comb; reg [NUMCLIENTS - 1:0] grant; //WEIGHT_REGISTERS // shift req to round robin the current priority always @ (*) begin //SHIFT_REQUEST endcase end // simple priority arbiter always @ (*) begin //SHIFT_GRANT end // generate grant signal always @ (*) begin //GRANT_SIGNAL endcase end always @ (posedge clk or negedge rst_n) begin if (!rst_n) grant[NUMCLIENTS - 1:0] <= NUMCLIENTS'b0; else grant[NUMCLIENTS - 1:0] <= grant_comb[NUMCLIENTS - 1:0] & ~grant[NUMCLIENTS - 1:0]; end // update the rotate pointer // rotate pointer will move to the one after the current granted always @ (posedge clk or negedge rst_n) begin if (!rst_n) rotate_ptr[ENCODEDNUMCLIENTS - 1:0] <= ENCODEDNUMCLIENTS'b0; else case (1'b1) // synthesis parallel_case //ROTATION endcase end """ weight_update_template = """ always @ (posedge clk or negedge rst_an) begin if (!rst_an) begin //WEIGHT_BIT end else begin //WEIGHT_NEGATION end end assign refresh_weights = //REFRESH_WEIGHT //ASSIGN_WEIGHT """ cam_body_template = """ module AH_cam_CAMDEPTH_CAMWIDTH_SNOOPWIDTH ( rst_an, clk, wr_data, wr_valid, wr_ready, snoop_in, snoop_valid, snoop_match, snoop_data ); // ============================================================================ // Below are the main parameters which are used for CAM functionality. // // CAMWIDTH --> width of storage - similar to FIFO storage // CAMDEPTH --> Number of rows the CAM can fit // ENCODEDDEPTH --> log2 of the CAM depth, the write/read pointers and snoop // marker all have this width. // // SNOOPWIDTH --> width of snoop-in port. This is always lte CAMWIDTH // ============================================================================ input rst_an; input clk; input [CAMWIDTH - 1:0] wr_data; //POINT --> CAMWIDTH output wr_valid; output wr_ready; // ============================================================================ //snoop happens at the LSBs. It is expected that for snoop to happen // in upper bits, write will be swizzled into LSB locations. input [SNOOPWIDTH - 1:0] snoop_in; // SNOOPWIDTH lte CAMWIDTH input snoop_valid; output snoop_match; output [CAMWIDTH - 1:0] snoop_data; // CAMWIDTH here wire [ENCODEDDEPTH - 1:0] internal_wr_ptr; // asume CAMDEPTH = 64, then wr-ptr-width is log2(CAMDEPTH). req [ENCODEDDEPTH:0] wr_loc_counter; // It's log2(CAMDEPTH) +1 from the above //REQUEST_DECLARATION // ============================================================================ // CAM working principle -- // 1. Initially all the entries are in pool of free locations. // 2. These are stored in a FIFO - at reset there's a counter which runs // and freely increments to keep feeding these locations to write logic. Once initial // 32/64/256 locations are used, the FIFO takes over. This helps to start the CAM right // right at the begining without any issues. // // 3. Once a snoop comes and if a snoop match happens, the location is invalidated and // correspnding location is written back into FIFO to be reused. // the problem with this scheme is that it immediately a reused location isn't available for // writing. // // If we apply a combo based logic, then that's possible - but then the resulting combo can be // very difficult to meet timing creating pipelining and having delays anyways. // In general for smaller CAMs, combo based wr-location search might be a good thing. // ============================================================================ // ============================================================================ // The counter always @ (posedge clk or negedge rst_an) begin if (!rst_an) begin wr_loc_counter <= ENCODEDDEPTH+1'd0; // log2(CAMDEPTH) +1 end else begin wr_loc_counter <= wr_location_counter[ENCODEDDEPTH] ? wr_location_counter : wr_location_counter + 1'b1; end end // ============================================================================ // Instance the reuse FIFO // Number 6 below is same as ENCODEDDEPTH or log2(CAMDEPTH). Number 64 below is same as CAMDEPTH. AH_srvfifo_ENCODEDDEPTH_CAMDEPTH u_wrloc_recirfifo ( .wr_valid(freeup_loc) ,.wr_ready(freedup_loc_valid) ,.wr_data(freedup_loc_ready) ,.rd_valid(recir_loc_valid) ,.rd_ready(recir_loc_ready) ,.rd_data(recir_loc) ); // ============================================================================ // Take the location from recir_loc or from wr_loc_counter and prepare to write an incoming data // Use the counter for initial phase only - so the MSB of counter when reached to 1, this method // of using counter shouldn't be used anymore // These are for CAM locations assign internal_wr_en = wr_valid & (recir_loc_valid | ~wr_location_counter[ENCODEDDEPTH]); assign internal_wr_ptr = ~wr_location_counter[ENCODEDDEPTH + 1] ? ~wr_location_counter[ENCODEDDEPTH - 1:0] : recir_loc; // Handshake with external wr-port assign wr_ready = ~wr_location_counter[ENCODEDDEPTH + 1] ? 1'b1 : recir_loc_valid; // Handshake with recirculation FIFO pop-port assign recir_loc_ready = ~wr_location_counter[ENCODEDDEPTH + 1] ? 1'b0 : wr_valid; // ============================================================================ // Now actual CAM locations // NOTE:- only 3 locations are shown - it should continue for 64 locations. always @ (posedge clk or negedge rst_an) if (!rst_an) begin //CAM_LOCATIONS end else begin //CAM_WRITE end // ============================================================================ // Handle the snoop part here. wire assign snoop_match = freedup_loc_ready) & ( //SNOOP_CAM ); wire assign snoop_data = CAMWIDTH'd0 | //ASSIGN_SNOOP ; wire assign freeup_loc = ENCODEDDEPTH'd0 | //ASSIGN_FREEUP ; wire assign freedup_loc_valid = snoop_match; endmodule """ mux_body_template = """ module NAME_MUXPORTWIDTH_MUXNUMCLIENTS ( //PORT_DECLARATION ); //VECTOR_DECLARATION //ASSIGN_DATA endmodule """ snoopable_fifo_template = """ // 20 - FIFOWIDTH // 32 - FIFODEPTH // 10 - SNOOPWIDTH // FIFONAME carries these 3 string. It can carry // other stuffs as srv (sync/ready-valid) module FIFO_FIFOWIDTH_FIFODEPTH_SNOOPWIDTH_snoopable ( clk, rstn, wr_valid, wr_ready, wr_data, rd_valid, rd_ready, rd_data, snoop_data, snoop_valid, snoop_match ); input rstn, intput clk, input [FIFOWIDTH - 1:0] wr_data; //FIFOWIDTH input wr_valid; input wr_ready; out [FIFOWIDTH - 1:0] rd_data; //FIFOWIDTH input rd_valid; input rd_ready; input [SNOOPWIDTH - 1:0] snoop_data; // SNOOPWIDTH input snoop_valid; input snoop_match; reg [ENCODEDDEPTH:0] wr_pointer; // ENCODEDDEPTH + 1 = log2(32) + 1 reg [ENCODEDDEPTH:0] rd_pointer; // ENCODEDDEPTH + 1 //REG_DECLARATIONS always @ (posedge clk or negedge rstn) begin if(rstn) begin wr_pointer <= ENCODEDDEPTH + 1'd0; end else begin wr_pointer <= ( (wr_pointer[ENCODEDDEPTH] ^ rd_pointer[ENCODEDDEPTH]) && (wr_pointer[ENCODEDDEPTH - 1:0] == rd_pointer[ENCODEDDEPTH - 1:0]) ) ? wr_pointer : wr_valid ? ( wr_pointer + 1'b1) : wr_pointer; end end always @ (posedge clk or negedge rstn) begin if(rstn) begin rd_pointer <= ENCODEDDEPTH + 1'd0; end else begin rd_pointer <= (rd_pointer[ENCODEDDEPTH:0] == rd_pointer[ENCODEDDEPTH:0]) ? rd_pointer : rd_ready ? (rd_pointer + 1'b1) : rd_pointer; end end always @ (posedge clk or negedge rstn) begin if(!rstn) begin //ASSIGN_LOC end else begin //LOC_WRITE end end wr_ready = ! ( (wr_pointer[ENCODEDDEPTH] ^ rd_pointer[ENCODEDDEPTH]) && (wr_pointer[ENCODEDDEPTH - 1:0] == rd_pointer[ENCODEDDEPTH - 1:0]) ); rd_valid = !(rd_pointer[ENCODEDDEPTH:0] == rd_pointer[ENCODEDDEPTH:0]); assign rd_data = FIFOWIDTH'd0 | //ASSIGN_READ assing snoop_match = 1'b0 | //ASSIGN_SNOOP_MATCH // snoop_match isn't used now - it can be in future. endmodule """ packet_converter_template = """ //DECLARATIONS reg [VECWIDTH - 1:0] packet_lane; wire [VECWIDTH - 1:0] npacket_lane; always(@posedge clk or negedge rstn) begin if (!rstn) begin packet_lane <= VECWIDTH'd0; //COLLATED end else begin packet_lane <= npacket_lane; //NCOLLATED end end //ASSIGN_DATA endmodule """ pipe_body_template = """ module_pipe_WIDTH( wr_data, wr_valid, wr_ready, rd_data, rd_valid, rd_ready, clk, rstn ); //di -> wr_data/ vi --> wr_valid / ro ---> wr_ready/ //do --> rd_data/vo --> rd_valid/ ri ---> rd_ready / input clk; input rst; input wr_valid; output wr_ready; input [WIDEWIDTH - 1:0] wr_data; output rd_valid; input rd_ready; output [WIDEWIDTH - 1:0] rd_data; reg rd_valid //SKID_REGISTERS //PIPE //SKID // PIPE OUTPUT assign wr_ready = rd_ready; assign rd_valid = wr_valid; assign rd_data = wr_data; endmodule """ ordering_point_template =""" module AH_ordering_point_NUMCLIENTS ( //MODULE_DEC ); //I/O_DEC //WIRE_ASSIGN """ LruArbiterBody = """ //REG_STATUS always @(posedge clk, negedge rstn) begin if(~rstn) begin //STATUS_USED end else begin //GNT_STATUS always @(req, gnt_busy) begin //GNT_REQUEST assign gnt[NUMCLIENTS - 1:0] = gnt_pre[NUMCLIENTS - 1:0]; """ DivPipelinedBody= """ `timescale 1ns / 1ps reg data_valid; reg div_by_zero; reg [STAGES-1:0] start_gen, negative_quotient_gen, div_by_zero_gen; reg [BITS*2*(STAGES-1)-1:0] dividend_gen, divisor_gen, quotient_gen; wire [BITS-1:0] pad_dividend; wire [BITS-2:0] pad_divisor; assign pad_dividend = 0; assign pad_divisor = 0; always @ (posedge clk or negedge rst_n) begin if (!rst_n) begin div_by_zero_gen[0] <= 0; start_gen[0] <= 0; negative_quotient_gen[0] <= 0; dividend_gen[BITS*2-1:0] <= 0; divisor_gen[BITS*2-1:0] <= 0; end else begin div_by_zero_gen[0] <= (divisor == 0); start_gen[0] <= start; negative_quotient_gen[0] <= dividend[BITS-1] ^ divisor[BITS-1]; dividend_gen[BITS*2-1:0] <= (dividend[BITS-1]) ? ~{dividend,pad_dividend} + 1 : {dividend,pad_dividend}; divisor_gen[BITS*2-1:0] <= (divisor [BITS-1]) ? ~{1'b1,divisor, pad_divisor} + 1 : {1'b0,divisor, pad_divisor}; end end always @ (posedge clk or negedge rst_n) begin if (!rst_n) begin div_by_zero_gen[1] <= 0; start_gen[1] <= 0; negative_quotient_gen[1] <= 0; divisor_gen[BITS*2*2-1:BITS*2] <= 0; quotient_gen[BITS*2-1:0] <= 0; dividend_gen[BITS*2*2-1:BITS*2] <= 0; end else begin div_by_zero_gen[1] <= div_by_zero_gen[0]; start_gen[1] <= start_gen[0]; negative_quotient_gen[1] <= negative_quotient_gen[0]; divisor_gen[BITS*2*2-1:BITS*2] <= divisor_gen[BITS*2-1:0] >> 1; if ( dividend_gen[BITS*2-1:0] <= divisor_gen[BITS*2-1:0]) begin quotient_gen[BITS*2-1:0] <= 1 << STAGES - 2; dividend_gen[BITS*2*2-1:BITS*2] <= dividend_gen[BITS*2-1:0] - divisor_gen[BITS*2-1:0]; end else begin quotient_gen[BITS*2-1:0] <= 0; dividend_gen[BITS*2*2-1:BITS*2] <= dividend_gen[BITS*2-1:0]; end end // else: !if(!rst_n) end // always @ (posedge clk) //LOOP_FOR_DIV_PIPELINE //last_computation_stage always @ (posedge clk or negedge rst_n) begin if (!rst_n) begin div_by_zero_gen[STAGES-1]<= 0; start_gen[STAGES-1]<= 0; negative_quotient_gen[STAGES-1]<= 0; quotient_gen[BITS*2*(STAGES-1)-1:BITS*2*(STAGES-2)]<= 0; end else begin div_by_zero_gen[STAGES-1]<= div_by_zero_gen[STAGES-2]; start_gen[STAGES-1]<= start_gen[STAGES-2]; negative_quotient_gen[STAGES-1]<= negative_quotient_gen[STAGES-2]; if ( dividend_gen[BITS*2*(STAGES-1)-1:BITS*2*(STAGES-2)] <= divisor_gen[BITS*2*(STAGES-1)-1:BITS*2*(STAGES-2)] ) quotient_gen[BITS*2*(STAGES-1)-1:BITS*2*(STAGES-2)] <= quotient_gen[BITS*2*(STAGES-2)-1:BITS*2*(STAGES-3)] | 1; else quotient_gen[BITS*2*(STAGES-1)-1:BITS*2*(STAGES-2)] <= quotient_gen[BITS*2*(STAGES-2)-1:BITS*2*(STAGES-3)]; end // else: !if(!rst_n) end // always @ (posedge clk) always @ (posedge clk or negedge rst_n) begin if (!rst_n) begin div_by_zero <= 0; data_valid <= 0; quotient <= 0; end else begin div_by_zero <= div_by_zero_gen[STAGES-1]; data_valid <= start_gen[STAGES-1]; quotient <= (negative_quotient_gen[STAGES-1]) ? ~quotient_gen[BITS*2*(STAGES-1)-1:BITS*2*(STAGES-2)+1]: quotient_gen[BITS*2*(STAGES-1)-1:BITS*2*(STAGES-2)]; end end """ ################################## CARRY LOOK AHEAD ADDER ###################################### CarryLookAheadAdderBody=""" wire [WIDTH-1:0] g, p, c; wire [(2 * WIDTH * WIDTH + WIDTH-1):0] e; wire cin; //loop_call xor #(2) (sum[0],p[0],cin); xor #(2) x[WIDTH-1:1](sum[WIDTH-1:1],p[WIDTH-1:1],c[WIDTH-2:0]); buf #(1) (cout, c[WIDTH-1]); PGGen pggen[WIDTH-1:0](g[WIDTH-1:0],p[WIDTH-1:0],a[WIDTH-1:0],b[WIDTH-1 :0]); """ ###################################### KOGGE STONE ADDER ###################################### KoggeStoneAdderBody=""" wire cin = 1'b0; wire [WIDTH-1:0] c; wire [WIDTH-1:0] g, p; Square sq[WIDTH-1:0](g, p, a, b); //loop_for_circle_triangle buf #(1) (cout, c[WIDTH-1]); """ ############################# CARRY RIPPLE ADDER ################################### CarryRippleAdderBody=""" module CarryRippleAdder(output [WIDTH-1:0] sum, output cout, input [WIDTH-1:0] a, b, input cin); wire [WIDTH-1:1] c; FA fa0(sum[0], c[1], a[0], b[0], cin); FA fa[2:1](sum[WIDTH-2:1], c[WIDTH-1:2], a[WIDTH-2:1], b[WIDTH-2:1], c[WIDTH-2:1]); FA fa3(sum[WIDTH-1], cout, a[WIDTH-1], b[WIDTH-1], c[WIDTH-1]); """ ############################### CARRY SELECT ADDER ################################## CarrySelectAdderBody=""" //sla_8_others" """ ####################### CARRY SKIP ADDER #################################### CarrySkipAdderBody=""" //carry_skip_Adder """ ########################### Hybrid Adder ###################### HybridAdderBody=""" CarryLookAheadAdder cla(sum[WIDTH/2-1:0], cout_1, a[WIDTH/2-1:0], b[WIDTH/2-1:0], 1'b0); KoggeStoneAdder ksa(sum[WIDTH-1:WIDTH], cout, a[WIDTH-1:WIDTH], b[WIDTH-1:WIDTH], cout_1); """ <file_sep>import os from enum import Enum from math import log2 from templates import module_template from templates import fifo_body_template from pathlib import Path from BusParser import BusParser import re import yaml from DynamicGenerator import DynamicGenerator class Port: class Direction(Enum): INPUT = "input" OUTPUT = "output" INOUT = "inout" def __init__(self, name, direction, type, width, heiarchy, cname): """ if not isinstance(direction, Port.Direction): raise TypeError('direction must be an instance of Port.Direction') """ if width < 1: raise TypeError('width should be > 0') self.name = name self.type = type self.direction = direction self.width = width self.heiarchy = heiarchy self.cname = cname def get_declaration(self): if self.width == 1: return "{0} {1};".format(self.direction, self.name) else: return "{0} [{1}:0] {2};".format(self.direction, self.width - 1, self.name) def __str__(self): return self.get_declaration() class BasicModule: def __init__(self, name): self.name = name self.Ports = [] self.results = [] self.port_list = [] self.body = "" self.variable_dict={} self.Create_dic_of_variable() self.add_ports_from_bus() def add_port(self, name, direction, type, width, heiarchy, cname): self.Ports.append(Port(name, direction, type, width, heiarchy, cname)) def get_port_str(self): """port_objs = [self.__dict__[name] for name in self.__dict__ if isinstance(self.__dict__[name], Port)] port_decl_str = "" port_name_str = "" for port in port_objs: port_decl_str += str( port_decl_str += str(port) port_decl_str += "\n" port_name_str += port.name port_name_str += ", " port_name_str = port_name_str.strip().strip(",") return port_name_str, port_decl_str """ port_decl_str = "\n".join([str(port) for port in self.Ports]) port_name_str = "\n,".join([port.name for port in self.Ports]) return port_name_str, port_decl_str #==================================================================================================================================================== # IMPORTANT - This base class method instantiates a busparser class aj object and will contain the port as dictionary object within busparser object. # # This method should be overwirren in subclasses whenever necessary. Use case of overwritting is as follows - # # While writing a new class for a new Verilog Module, we should always look inside refbuses folder and see if there's an existing yaml # that matches the dictionary closely or somewhat closely. # Then we should use available busparser method to operate on the dictionary and reach the desired dictionary for the target vlass. # Ultimately a list is extracted from the dictionary object and used to create ports for each leaf. In get header method it reflects the output # in Verilog world. # # Finally, the rationale behind keeping this as dictionary is that it's a systematic data-structure and can be used through multiple hierarchies # systematically. #==================================================================================================================================================== def get_all_key_value_pairs(self, data): self.Ports.clear() def inner(data): if isinstance(data, dict): # print("I found a dictionary") for k, v in data.items(): if (isinstance(v, dict) or isinstance(v, list) or isinstance(v, tuple) ): # print("I am going to dive one level recursion here.") if 'direction' in v.keys(): # TODO: I need to find the values of 'width', 'direction' and of course # 'signal' here. If I can print them, I can just call self.add_port method # here with them. # print("I am going see what name and cname values I pass to port-class\n") # print(str(v['name'])+"_|_|_|_|_"+str(v['cname'])) self.add_port(v['name'], v['direction'], v['type'], v['width'], v['heiarchy'], v['cname']) # print("I have found direction, must be at a signal.") self.port_list.append(k) inner(v) else: self.results.append((k, v)) elif isinstance(data, list) or isinstance(data, tuple): for item in data: inner(item) inner(data) return self.results def add_ports_from_bus(self): pass # print("\n I am checking whether this BasicModule add_ports_from_bus gets executed anywhere..\n\n") # self.Ports.clear() #Some are combo modules alone - clock and reset aren't required. #TODO: Is there a graceful way to not having clock-reset in every .yaml file. # But at the same time combo modules are spared from adding. # We need to work on this down the line. #self.add_port("clk", "input", "nonfluid",1,"clk", "clk") #self.add_port("rstn", "input","nonfluid",1,"rstn", "rstn") def get_object_declaration_str(self, obj_name): """ Prints the object declaration in verilog. """ self.get_all_key_value_pairs(self.dict) code = "\n".join(["."+ports.name + "\t\t\t\t" + "("+ports.cname+")" for ports in self.Ports]) return self.name + " " + obj_name + "(\n"+code+"\n)" def populate_wire_and_ports(self, args): """ Poplulates wire and port dictionary of the class which instantiates the smaller modules. """ wire_dict = {} port_dict = {} args = list(args) #print(args) set_of_ports = set() for i in range(len(args)): args[i].Ports.clear() args[i].get_all_key_value_pairs(args[i].dict) for i in range(len(args)): curr_obj = args[i] for curr_port in curr_obj.Ports: is_connected = None # print("PORTS : "+str(port.__dict__)) if curr_port.direction == 'output' and curr_port.cname not in set_of_ports: is_input_there = False for j in range(len(args)): if any([i!=j and other_port.direction == 'output' and other_port.cname == curr_port.cname for other_port in args[j].Ports]): raise Exception("Problem in " + str(curr_port.__dict__)) if any([i!=j and other_port.direction == 'input' and other_port.cname == curr_port.cname for other_port in args[j].Ports]): is_input_there = True is_connected = True and is_input_there set_of_ports.add(curr_port.cname) elif curr_port.direction == 'input' and curr_port.cname not in set_of_ports: cout = True for j in range(len(args)): if any([i!=j and other_port.direction == 'output' and curr_port.cname == other_port.cname for other_port in args[j].Ports]): cout = False if not cout: is_connected = False set_of_ports.add(curr_port.cname) if is_connected == True and curr_port.name != 'clk' and curr_port.name != 'rstn': self.create_dict_branch("astob_"+curr_port.cname, wire_dict, curr_port) elif is_connected == False or (is_connected == None and curr_port.cname not in set_of_ports) and curr_port.name!='clk' and curr_port.name !='rstn': self.create_dict_branch("astob_"+curr_port.cname, port_dict, curr_port) # print("AFTER : "+ str(port_dict)) return port_dict , wire_dict def create_dict_branch(self, exp, dictionary, signal): """Creates a branch in a dictionary""" signal.__dict__['name'] = signal.__dict__['cname'] signal.__dict__['heiarchy'] = exp heiarchy = exp.split("_") j = 0 for j in range(len(heiarchy)): if list(dictionary.keys()).count(heiarchy[j]) > 0: dictionary = dictionary[heiarchy[j]] else: break # print("J : "+str(j)) for i in range(j, len(heiarchy) - 1): dictionary[heiarchy[i]] = {heiarchy[i+1]: None} dictionary = dictionary[heiarchy[i]] dictionary[heiarchy[len(heiarchy) - 1]] = signal.__dict__ # print("AFTER : "+ str(dictionary)) def find_and_replace(self, data, pattern, replacement): """Finds and replaces regex in signal cnames""" parser = BusParser(data, list(data.keys())[0]) def inner(data): if isinstance(data, dict): for k, v in data.items(): if isinstance(v, dict) or isinstance(v, list) or isinstance(v, tuple): if 'direction' in v.keys(): if re.match(pattern, v['cname']): matches = [group for group in re.match(pattern , v['cname']).groups()][1:] v['cname'] = replacement.format([*matches]) inner(v) elif isinstance(data, list) or isinstance(data, tuple): for item in data: inner(item) inner(data) def connport(self, data, pattern, port_dict): """Forcefully changes wires to ports""" parser = BusParser(data, list(data.keys())[0]) def inner(data): if isinstance(data, dict): for k, v in data.items(): if isinstance(v, dict) or isinstance(v, list) or isinstance(v, tuple): if 'direction' in v.keys(): if re.match(pattern, v['cname']): self.create_dict_branch(v['heiarchy'], port_dict, v) parser.remove_sub_dict(v['heiarchy']) inner(v) elif isinstance(data, list) or isinstance(data, tuple): for item in data: inner(item) inner(data) def load_dict(self, filepath): """returns dictionary from a yaml file""" return yaml.load(open(filepath).read()) def get_header(self): self.get_all_key_value_pairs(self.dict) mytemplate = module_template mytemplate = mytemplate.replace("MODULENAME", self.name) portlist, portdecl = self.get_port_str() mytemplate = mytemplate.replace("PORTLIST", portlist) mytemplate = mytemplate.replace("PORTDECLARATION", portdecl) return mytemplate #==================================================================================================================================================== # IMPORTANT :- These base class methods downstream are useful building blocks for many verilog code - they offer stuffs including. # looping for wr, rd, snoop, snoop-invalidate, register declaration, wire declaration etc many things. # The idea is to use these methods as much as possible and if required create a new method on similar lines and push to base class. # # Method name should be kept generic and arguments used judiciously so that it can be maintained cleanly as the framework grows. #==================================================================================================================================================== def get_reg_str(self, type, delimiter, width, module_name, iterations): return "\n"+delimiter.join(["{2} [{0}:0] {1}".format(width, module_name, type)+str(i)+";" for i in range(iterations)]) def snoop_match_noinv(self, module_name, snoop, SnoopWidth, iterations, delimiter): return "\n"+delimiter.join(["(({0}{3}[{2}:0] == {1}) ? 1'b1 : 1'b0)".format(module_name,snoop,SnoopWidth-1,i) for i in range(iterations)]) def snoop_inv(self, delimiter, snoopwidth, snoop, module_name, camdepth, camwidth): return "\n" + delimiter.join(["( ({0} == {1}".format(snoop,module_name)+str(i)+"["+str(snoopwidth-1)+":0]) ? {0}".format(module_name)+str(i)+" : "+str(camwidth)+"'d0 )" for i in range(camdepth)]) def snoop_get_wr_ptr(self,delimiter,module_name,snoop,snoopwidth,encodeddepth,camdepth): return delimiter.join(["( ({0} == {1}".format(snoop,module_name) + str(i) + "[" + str(snoopwidth - 1) + ":0]) ?"+module_name + str(i) + " : " + str(encodeddepth) + "'d" + str(i) + " )" for i in range(camdepth)]) def read_loc(self, encodeddepth, module_name, fifowidth, fifodepth, delimiter): return "\n"+delimiter.join(["( (rd_pointer["+str(encodeddepth)+":0] == "+str(encodeddepth+1)+"'d" ""+str(i)+") ? "+module_name+str(i)+" : "+str(fifowidth)+"'d0)" for i in range(fifodepth)]) def write_loc(self, delimiter, module_name, encodeddepth, fifodepth): return "\n\t"+delimiter.join([module_name+str(i)+" <= (wr_pointer["+str(encodeddepth-2)+":0] == "+str(encodeddepth)+"'d"+str(i)+") ? wr_data : "+module_name+str(i)+";" for i in range(fifodepth)]) def write_loc_rstn(self, delimiter, module_name, fifowidth, fifodepth): return "\n\t"+delimiter.join([module_name+str(i)+" <= "+str(fifowidth)+"'d0;" for i in range (fifodepth)]) def cam_write(self,delimiter,module_name,camdepth,encodeddepth): return "\n\t" + delimiter.join([module_name + str(i) + " <= (internal_wr_en & (internal_wr_ptr == " + str(encodeddepth) + "" "'d" + str(i) + ") ) ? wr_data : "+module_name + str(i) + ";" for i in range(camdepth)]) def write_to_file(self, verilog): #print(str(Path.home()) with open(str(Path.home())+"/Documents/smartasic2/Modules/golden/AH_genverilog/"+self.name+".v","w") as f: f.write(verilog) def remove_port(self, port_name): for port in self.Ports: if port.name == port_name: self.Ports.remove(port) return #============================================================================ # Below portion is for migrating the methods that can remain in base-class. # Continuing this will keep code size in all classes under check. #============================================================================ def main(self): self.write_to_file(self.get_verilog()) return self.get_verilog() def get_verilog(self): modulecode=self.get_header() self.get_body() modulecode=modulecode.replace("BODY",self.body) return modulecode def get_body(self): dynamicgenerator = DynamicGenerator(self.variable_dict, self.body) # passing dictonary and snoopbody to split the body self.body += dynamicgenerator.parse_body() class FIFO(BasicModule): class ClockType(Enum): SYNC = "sync" ASYNC = "async" RSYNC = "rsync" class FlowControl(Enum): VALID_READY = "valid_ready" VALID_BUSY = "valid_busy" VALID_CREDIT = "valid_credit" def __init__(self, name, width, depth, clk_type, flow_ctrl): if not isinstance(clk_type, FIFO.ClockType): raise TypeError('clk_type must be an instance of FIFO.ClockType') if not isinstance(flow_ctrl, FIFO.FlowControl): raise TypeError('flow_ctrl must be an instance of FIFO.FlowControl') super(FIFO, self).__init__(name) self.width = width self.depth = depth self.clk_type = clk_type self.flow_ctrl = flow_ctrl self.wr_valid = Port("wr_valid", Port.Direction.INPUT, 1) self.wr_ready = Port("wr_ready", Port.Direction.OUTPUT, 1) self.wr_data = Port("wr_data", Port.Direction.INPUT, self.width) self.rd_valid = Port("rd_valid", Port.Direction.OUTPUT, 1) self.rd_ready = Port("rd_ready", Port.Direction.INPUT, 1) self.rd_data = Port("rd_data", Port.Direction.OUTPUT, self.width) def update(self): self.__init__(self.name, self.width, self.depth, self.clk_type, self.flow_ctrl) def update_width(self, width): self.__init__(self.name, width, self.depth, self.clk_type, self.flow_ctrl) def update_height(self, height): self.__init__(self.name, self.width, height, self.clk_type, self.flow_ctrl) def get_body(self): encoded_depth = int(log2(self.depth)) mytemplate = fifo_body_template mytemplate = mytemplate.replace("ENCODEDDEPTH", str(encoded_depth)) mytemplate = mytemplate.replace("FIFOWIDTH", str(self.width)) mytemplate = mytemplate.replace("FIFODEPTH", str(self.depth)) return mytemplate def get_fifo_v(self): modulecode = self.get_header() modulecode = modulecode.replace("BODY", self.get_body()) return modulecode def __str__(self): return self.get_fifo_v() <file_sep>import os #from templates import mux_body_template from smartasic import BasicModule,Port from DynamicGenerator import DynamicGenerator from BusParser import BusParser from pathlib import Path from math import log2, ceil import sys class Multiplexor(BasicModule,BusParser): ## creating dictonary of variable def Create_dic_of_variable(self): self.variable_dict['PortWidth']=self.PortWidth self.variable_dict['NumClients']=self.NumClients self.variable_dict['IsDemux']=self.IsDemux self.variable_dict['IsBinary']=self.IsBinary self.variable_dict['EncodedDepth']=self.EncodedDepth #It's assumed that the original mux-demux yaml file will have 2 egress ports at least. The rest has to be added. # Then the yaml is demux - so ingress and egress keys swap name if we need to provide a mux def add_ports_from_bus(self): #print(self.dict) self.dyaml("1.yaml") BasicModule.add_ports_from_bus(self) print("I am going to operate on this dict now") if(self.NumClients > 2): for i in range(2, self.NumClients): self.copy_flat("egress1", "egress"+str(i)) self.rename("demux.egress"+str(i)+".egr1_data" , "egr"+str(i)+"_data" ) self.rename("demux.egress"+str(i)+".egr1_valid", "egr"+str(i)+"_valid") self.rename("demux.egress"+str(i)+".egr1_ready", "egr"+str(i)+"_ready") self.widop_flat("ing_data",self.PortWidth) for i in range(0, self.NumClients): self.widop_flat("egr"+str(i)+"_data",self.PortWidth) #print(self.dict) print("I am going to operate on this dict again") self.dyaml("2.yaml") #print("This is the self.IsDemux value --"+self.IsDemux) if self.IsDemux is False: for i in range (self.NumClients): self.rename_flat("egress"+str(i), "ingress"+str(i)) self.rename("demux.ingress"+str(i)+".egr"+str(i)+"_data" , "ing"+str(i)+"_data" ) self.rename("demux.ingress"+str(i)+".egr"+str(i)+"_valid", "ing"+str(i)+"_valid") self.rename("demux.ingress"+str(i)+".egr"+str(i)+"_ready", "ing"+str(i)+"_ready") #print(self.dict) print("I am going to operate on this dict again(2)") self.dyaml("3.yaml") if not self.IsDemux: self.rename_flat("ingress", "egress") #print(self.dict) print("I am going to operate on this dict again(3)") self.dyaml("3_3.yaml") self.rename("demux.egress.ing_data" , "egr_data" ) self.rename("demux.egress.ing_valid", "egr_valid") self.rename("demux.egress.ing_ready", "egr_ready") self.rename_flat("demux", "mux") # print(self.dict) self.dyaml("4.yaml") print("I am done with this dict which is final.") self.init_connections(self.dict) self.get_all_key_value_pairs(self.dict) def get_body(self): dynamicgenerator=DynamicGenerator(self.variable_dict,self.muxdemuxbody) # passing dictonary and snoopbody to split the body self.body+=dynamicgenerator.parse_body() self.body = self.body.replace("NAME", "mux" if self.IsDemux is None else "demux") self.body = self.body.replace("MUXPORTWIDTH", str(self.PortWidth)) self.body = self.body.replace("MUXNUMCLIENTS", str(self.NumClients)) dynamicgenerator.silentremove() def get_verilog(self): modulecode=self.get_header() self.get_body() modulecode=modulecode.replace("BODY",self.body) return modulecode def main(self): print("I am about to write a verilog file now") self.write_to_file(self.get_verilog()) print (self.get_verilog()) return self.get_verilog() def __init__(self,numclients,portwidth, isdemux, isbinary, path_of_yaml=None, bus_name=None): self.PortWidth = portwidth self.NumClients = numclients self.IsDemux = isdemux self.body = None self.IsBinary = isbinary if path_of_yaml is None: path_of_yaml = "../../../smartasic2/refbuses/mux_demux.yaml" bus_name = "demux" self.curName = "mux" if self.IsDemux is None else "demux" self.name = "AH_"+self.curName+"_"+str(self.PortWidth)+"_"+str(self.NumClients)+"_"+str(self.IsBinary) print("Just checking what is the file name..") print (self.name) #BasicModule.__init__(self, self.name) self.body = "" self.EncodedDepth = int(ceil(log2(numclients))) self.variable_dict={} self.Create_dic_of_variable() BusParser.__init__(self, self.load_dict(path_of_yaml), bus_name) BasicModule.__init__(self, self.name) #self.add_ports_from_bus() self.muxdemuxbody = """ // Ingress and Egress are short circuited based on condition /f_f/ code = "" if IsDemux: for i in range(NumClients): code += "\\nwire assign egress"+str(i)+"_ds_pkt = (demux_select== "+str(EncodedDepth)+"'d"+str(i)+") ? ingress_ds_pkt : "+str(EncodedDepth)+"'d0;" for i in range(NumClients) : code += "\\nwire assign egress"+str(i)+"_ds_pkt_valid = (demux_select== "+str(EncodedDepth)+"'d"+str(i)+") ? ingress_ds_pkt_valid : "+str(EncodedDepth)+"'d0;" code += "\\n" code += "\\nwire assign ingress_ds_pkt_ready =" for i in range(NumClients): code += "\\n ((demux_select== "+str(EncodedDepth)+"'d"+str(i)+") ? egress1_ds_pkt_ready ? 1'b0) | " code += "\\n 1'b0;" else: code += "\\nwire assign egress_ds_pkt =" #code += "\\n ((mux_select== "+str(EncodedDepth)+"'d"+str(i)+") ? ingress"+str(i)+"_ds_pkt : "+str(EncodedDepth)+"'d0 ) |" for i in range(NumClients) #code += "\\n "+str(EncodedDepth)+"'d0;" #code += "\\n" #code += "\\nwire assign egress_ds_pkt_valid =" #code += " ((mux_select== "+str(EncodedDepth)+"'d"+str(i)+") ? ingress"+str(i)+"_ds_pkt : "+str(EncodedDepth)+"'d0 ) |" for i in range(NumClients) #code += "\\n "+str(EncodedDepth)+"'d0;" #code += "\\n" #code += "\\nwire assign ingress"+str(EncodedDepth)+"_ds_pkt_ready = (mux_select== "+str(EncodedDepth)+"'d"+str(i)+") ? egress_ds_pkt_ready : 1'b0;" for i in range(NumClients) #code += "\\n" /f_f/ """ if __name__ == "__main__": if len(sys.argv) > 5: muxdemux=Multiplexor(int(sys.argv[1]), int(sys.argv[2]), sys.argv[3], sys.argv[4], sys.argv[5], sys.argv[6]) else: muxdemux=Multiplexor(int(sys.argv[1]), int(sys.argv[2]), sys.argv[3], sys.argv[4]) muxdemux.main() ####def get_body(self): #### self.body = mux_body_template #### self.declare_ports() #### self.declare_vectors() #### self.assign_data() ####def declare_ports(self): #### if not self.IsDemux: #### code = "\n".join(["in_data"+str(i)+"," for i in range(self.NumClients)]) #### code += "\nout_data,\nmux_select" #### else: #### code = "\n".join(["out_data" + str(i) + "," for i in range(self.NumClients)]) #### code += "\nin_data,\ndemux_select" #### self.body = self.body.replace("//PORT_DECLARATION", code) ####def declare_vectors(self): #### if not self.IsDemux: #### code = "\n".join(["input ["+str(self.PortWidth-1)+":0] in_data"+str(i)+";" for i in range(self.NumClients)]) #### code += "\noutput ["+str(self.PortWidth-1)+":0] out_data;\ninput ["+(str(self.NumClients-1) if not self.IsBinary else str(int(ceil(log2(self.NumClients-1)))))+":0] mux_select;" #### else: #### code = "\n".join(["output [" + str(self.PortWidth - 1) + ":0] out_data" + str(i) + ";" for i in range(self.NumClients)]) #### code += "\ninput ["+str(self.PortWidth-1)+":0] in_data;\ninput ["+(str(self.NumClients-1) if not self.IsBinary else str(int(ceil(log2(self.NumClients-1)))))+":0] demux_select;" #### self.body = self.body.replace("//VECTOR_DECLARATION", code) ####def assign_data(self): #### if not self.IsDemux: #### code = "wire assign out_data = "+str(self.PortWidth)+"'d0 |" + " |\n ".join(["(mux_select"+("["+str(i)+"]" if not self.IsBinary else "= "+str(int(ceil(log2(self.NumClients))))+"'d"+str(i)+"") +"? in_data"+str(i)+" : "+str(self.PortWidth)+"'d0)" for i in range(self.NumClients)]) #### else: #### code = "\n".join(["wire assign out_data"+str(i)+" = demux_select"+("["+str(i)+"]" if not self.IsBinary else "=="+str(int(ceil(log2(self.NumClients))))+"'d"+str(i))+"? in_data : 25'd0;" for i in range(self.NumClients)]) #### self.body = self.body.replace("//ASSIGN_DATA", code) ####def __str__(self): #### self.get_body() #### return self.body ####def __init__(self, fifowidth, fifodepth, snoopwidth, path_of_yaml, bus_name): #### self.FifoWidth = fifowidth #### self.FifoDepth = fifodepth #### self.SnoopWidth = snoopwidth #### self.name = "AH_"+self.__class__.__name__+"_"+str(fifowidth)+"_"+str(fifodepth)+"_"+str(snoopwidth) #### BasicModule.__init__(self, self.name) #### self.body = "" #### self.EncodedDepth = int(ceil(log2(fifodepth))) #### self.variable_dict={} #### self.Create_dic_of_variable() #### BusParser.__init__(self, path_of_yaml, bus_name) #### self.add_ports_from_bus() <file_sep># Modules Modules for Ahant <file_sep>import sys import os from smartasic import BasicModule,Port from math import log2,ceil from DynamicGenerator import DynamicGenerator from BusParser import BusParser from pathlib import Path class RoundRobinArbiter(BasicModule,BusParser): def Create_dic_of_variable(self): self.variable_dict['Num_Clients']=self.Num_Clients self.variable_dict['EncodedNum_Clients']=self.EncodedNum_Clients self.variable_dict['weight']=self.weight def add_ports_from_bus(self): BasicModule.add_ports_from_bus(self) self.widop_flat("req",self.Num_Clients) self.rename_flat('gnt',"grant") self.widop_flat("grant",self.Num_Clients) self.remove_sub_dict_flat("gnt_busy") self.get_all_key_value_pairs(self.dict) def get_body(self): dynamicgenerator=DynamicGenerator(self.variable_dict,self.body) self.body+=dynamicgenerator.parse_body() #BasicModule.get_body self.body= self.body.replace("ENCODEDNUMCLIENTS - 1", str(self.EncodedNum_Clients - 1)) self.body= self.body.replace("ENCODEDNUMCLIENTS", str(self.EncodedNum_Clients)) self.body = self.body.replace("NUMCLIENTS - 1", str(self.Num_Clients - 1)) self.body = self.body.replace("NUMCLIENTS", str(self.Num_Clients)) dynamicgenerator.silentremove() ##def get_verilog(self): ## modulecode=self.get_header() ## self.get_body() ## modulecode=modulecode.replace("BODY",self.body) ## return modulecode ##def main(self): ## self.write_to_file(self.get_verilog()) ## return self.get_verilog() def __init__(self,num_clients,path_of_yaml=None,bus_name=None,weight=None): self.bus_name=bus_name self.Num_Clients=num_clients self.weight = weight self.EncodedNum_Clients = int(ceil(log2(self.Num_Clients))) if path_of_yaml == None: path_of_yaml = "../../../smartasic2/refbuses/arbiter.yaml" bus_name = "arbiter" if weight==None: self.name="AH_"+self.__class__.__name__+"_"+str(num_clients) else: self.name="AH_"+self.__class__.__name__+"_"+str(num_clients)+"_"+str(weight) BusParser.__init__(self,self.load_dict(path_of_yaml),bus_name) BasicModule.__init__(self ,self.name) #self.variable_dict={} #self.Create_dic_of_variable() #self.body="" #self.add_ports_from_bus() #self.add_ports_from_bus(path_of_yaml,bus_name) self.body=""" /f_f/ if(weight != None): code="\\n".join(["input ["+str(weight)+":0] cfg_weight"+str(i)+";" for i in range(Num_Clients)]) else: code="" /f_f/ reg [ENCODEDNUMCLIENTS - 1:0] rotate_ptr; reg [NUMCLIENTS - 1:0] shift_req; reg [NUMCLIENTS - 1:0] shift_grant; reg [NUMCLIENTS - 1:0] grant_comb; reg [NUMCLIENTS - 1:0] grant; /f_f/ if(weight != None): code="\\n".join(["input ["+str(weight)+":0] cfg_weight"+str(i)+";" for i in range(Num_Clients)]) else: code="" /f_f/ always @ (*) begin /f_f/ code="case (rotate_ptr["+str(EncodedNum_Clients - 1)+":0])\\n\t\t\t" \ + str(EncodedNum_Clients)+"'b"+"0"*EncodedNum_Clients + ": shift_req["+str(Num_Clients-1)+":0] = " \ "req["+str(Num_Clients-1)+":0];\\n\t\t\t" + \ str(EncodedNum_Clients)+"'b"+"0"*(EncodedNum_Clients-1)+"1: shift_req[" + str(Num_Clients-1)+":0] = " \ "{req[0],req["+str(Num_Clients-1)+":1]};\\n\t\t\t" for i in range(2, Num_Clients-1): code+=str(EncodedNum_Clients)+"'b"+"0"*(EncodedNum_Clients-len(bin(i)[2:]))+bin(i)[2:]+":" \ " shift_req["+str(Num_Clients-1)+":0] = {req["+str(i-1)+":0],req["+str(Num_Clients-1)+":" \ + str(i)+"]};\\n\t\t\t" code+=str(EncodedNum_Clients)+"'b"+bin(Num_Clients-1)[2:]+": shift_req["+str(Num_Clients-1)+":0] = " \ "{req["+str(Num_Clients-2)+":0],req["+str(Num_Clients-1)+"]};" /f_f/ endcase end always @ (*) begin /f_f/ code="shift_grant["+str(Num_Clients-1)+":0] = " +str(Num_Clients)+"" \ "'b0;\\n\t\t\tif (shift_req[0]) shift_grant[0] = 1'b1;\\n\t\t\t" for i in range(1,Num_Clients): code += "else if (shift_req["+str(i)+"]) shift_grant["+str(i)+"] = 1'b1;\\n\t\t\t" /f_f/ endcase end always @ (*) begin /f_f/ code="case (rotate_ptr["+str(EncodedNum_Clients - 1)+":0])\\n\t\t\t" \ + str(EncodedNum_Clients)+"'b"+"0"*EncodedNum_Clients + ": grant_comb["+str(Num_Clients-1)+":0] = " \ "shift_grant["+str(Num_Clients-1)+":0];\\n\t\t\t" + \ str(EncodedNum_Clients)+"'b"+"0"*(EncodedNum_Clients-1)+"1: grant_comb[" + str(Num_Clients-1)+":0] = " \ "{shift_grant["+str(Num_Clients-2)+":0]," \ "shift_grant["+str(Num_Clients-1)+"]};\\n\t\t\t" for i in range(Num_Clients-3, 0, -1): code += str(EncodedNum_Clients)+"'b"+"0"*(EncodedNum_Clients-len(bin(Num_Clients-i-1)[2:]))+bin(Num_Clients-i-1)[2:]+":" \ " grant_comb["+str(Num_Clients-1)+":0] = {shift_grant["+str(i)+":0],shift_grant["+str(Num_Clients-1)+":" \ + str(i+1)+"]};\\n\t\t\t" code += str(EncodedNum_Clients)+"'b"+bin(Num_Clients-1)[2:]+":" \ " grant_comb["+str(Num_Clients-1)+":0] = {shift_grant[0],shift_grant["+str(Num_Clients-1)+":1]};\\n" /f_f/ endcase end always @ (posedge clk or negedge rst_n) begin if (!rst_n) grant[NUMCLIENTS - 1:0] <= NUMCLIENTS'b0; else grant[NUMCLIENTS - 1:0] <= grant_comb[NUMCLIENTS - 1:0] & ~grant[NUMCLIENTS - 1:0]; end always @ (posedge clk or negedge rst_n) begin if (!rst_n) rotate_ptr[ENCODEDNUMCLIENTS - 1:0] <= ENCODEDNUMCLIENTS'b0; else case (1'b1) // synthesis parallel_case /f_f/ code="" for i in range(Num_Clients): code += "grant["+str(i)+"]: rotate_ptr["+str(EncodedNum_Clients-1)+":0] <= " \ + ("| nweight"+str(i)+" ? : rotate_ptr :" if weight is not None else "")+str(EncodedNum_Clients)+"'d"+str((i+1) % Num_Clients)+";"+"\\n\t\t\t" /f_f/ endcase end /f_f/ code="" if(weight!=None): code+="\\nalways @ (posedge clk or negedge rst_an) \\n\tbegin \\n if (!rst_an) begin " code+="\\n".join(["weight" + str(i) + " <= "+str(weight+1)+"'d0;" for i in range(Num_Clients)]) code+="\\nend else begin" code+="\\n".join(["weight" + str(i) + " <= " + "nweight" + str(i) + ";" for i in range(Num_Clients)]) code+="\\n\t\tend\\n\tend\\nassign refresh_weights = " code+= " & ".join(["(~|weight" + str(i)+")" for i in range(Num_Clients)]) + ";" /f_f/ /f_f/ code="" if(weight!=None): for i in range(Num_Clients): code += "assign nweight"+str(i)+" = refresh_weights ? cfg_weight"+str(i)+" : (req["+str(i)+"] & gnt["+str(i)+"]) ? weight"+str(i)+" - 1'b1 : weight"+str(i)+";\\n" /f_f/ """ if __name__ == "__main__": if len(sys.argv) > 4: #print(RoundRobinArbiter(int(sys.argv[1]),sys.argv[2], sys.argv[3],int(sys.argv[4]))) roundrobinarbiter=RoundRobinArbiter(int(sys.argv[1]),sys.argv[2], sys.argv[3],int(sys.argv[4])) else: #print(RoundRobinArbiter(int(sys.argv[1]), sys.argv[2], sys.argv[3])) roundrobinarbiter=RoundRobinArbiter(int(sys.argv[1])) roundrobinarbiter.main() <file_sep>from BusParser import BusParser import copy trial = BusParser("/home/mayukhs/Documents/smartasic2/refbuses/astob_heavy.yaml","astob") temp = copy.deepcopy(trial.dict["astob"]["hier1"]) trial.dyaml("loaded.yaml") trial.widop_flat("wdata", 10) trial.widop_flat("rdata",10) trial.remove_node_flat("hier1") trial.add_sub_dict_flat("snoop", {"hello" :{"direction": "input"}}) trial.remove_sub_dict_flat("sdata") trial.flipop_flat("snoop") trial.flipop_flat("wvalid") trial.rename_flat("smatch" , "snoopmatch") trial.rename_flat("rdata" , "readmatch") trial.copy_flat("snoop" , "snoop_test") trial.dyaml("transit.yaml") #################################### trial.widop_flat("wdata", 18) trial.widop_flat("readmatch", 18) trial.add_super_node_flat("rd" , "hier1") trial.remove_sub_dict_flat("hello") trial.add_sub_dict_flat("snoop" , {"sdata" : {"direction" : "output" , "type" : "fluid" , "width" : 18}}) trial.rename_flat("snoopmatch","smatch") trial.rename_flat("readmatch" , "rdata") trial.flipop_flat("wvalid") trial.flipop_flat("snoop") trial.remove_sub_dict_flat("snoop_test") trial.dyaml("Sync.yaml") <file_sep>from templates import packet_converter_template from math import ceil, log2 import sys class PacketConverter: def __init__(self, width1, width2, isW2N): self.WideWidth = max(width1, width2) self.NarrowWidth = min(width1, width2) self.isW2N = isW2N self.ratio = (self.WideWidth // self.NarrowWidth) self.VecWidth = int(log2(self.WideWidth/self.NarrowWidth)) self.body = None def get_body(self): name = None if self.isW2N == "True": name = "w2n_"+str(self.WideWidth)+"_"+str(self.NarrowWidth) else: name = "n2w_"+str(self.NarrowWidth)+"_"+str(self.WideWidth) self.body = packet_converter_template self.body = self.body.replace("NAME", name) self.body = self.body.replace("WIDEWIDTH - 1", str(self.WideWidth - 1)) self.body = self.body.replace("VECWIDTH - 1", str(self.VecWidth - 1)) self.body = self.body.replace("NARROWWIDTH - 1", str(self.NarrowWidth - 1)) self.body = self.body.replace("WIDEWIDTH", str(self.WideWidth)) self.body = self.body.replace("VECWIDTH", str(self.VecWidth)) self.declaration() self.add_collated() self.assign_data() def declaration(self): if self.isW2N: code = "input ["+str(self.WideWidth-1)+":0]in_data;\noutput ["+str(self.NarrowWidth-1)+":0] out_data;" else: code = "input ["+str(self.WideWidth-1)+":0]in_data;\noutput ["+str(self.WideWidth-1)+":0] out_data;\n" \ "reg ["+str(self.WideWidth)+":0] collated_packet;" self.body = self.body.replace("//DECLARATIONS", code) def add_collated(self): self.body = self.body.replace("//COLLATED", "\tcollated_packet <="+str(self.WideWidth)+"'d0;") self.body = self.body.replace("//NCOLLATED", "\tcollated_packet <= ncollated_packet;") def assign_data(self): if self.isW2N: code = "assign npacket_lane = (in_valid & out_ready) ? packet_lane +1'b1 :\npacket_lane;" code += "assign out_valid = in_valid;\n" \ "assign out_data = in_data >> ("+str(self.NarrowWidth)+"* packet_lane); // LINT WARNING - take care.\n" \ "assign in_ready = out_ready & (packet_lane == "+str(self.VecWidth)+"'d"+str(self.ratio-1)+")" else: code = "assign npacket_lane = !in_valid ? packet_lane:\n\t" \ "(packet_lane != "+str(self.VecWidth)+"'d"+str(self.ratio-1)+") ? packet_lane + 1'b1:\n\t" \ "out_ready ? packet_lane + 1'b1 :packet_lane;" code += "wire assign ncollated_packet = ( (packet_lane == "+str(self.VecWidth)+"'d"+str(self.ratio)+") " \ "&& in_valid && out_ready ) ? "+str(self.WideWidth)+"'d0 : // delivery cyclein_valid\n " \ "? {collated_packet, in_data} : // Lint warning needs to be clean here\n" \ "collated_packet;" code += "assign out_valid = in_valid && (packet_lane == "+str(self.VecWidth)+"'d"+str(self.ratio)+");\n" \ "assign in_ready = (packet_lane == "+str(self.VecWidth)+"'d"+str(self.ratio)+") ? out_ready ? 1'b1;\n" \ "assign out_data = ncollated_packet;" self.body = self.body.replace("//ASSIGN_DATA", code) def __str__(self): self.get_body() return self.body print(PacketConverter(int(sys.argv[1]), int(sys.argv[2]), sys.argv[3])) <file_sep>import os from smartasic import BasicModule,Port from DynamicGenerator import DynamicGenerator from BusParser import BusParser from pathlib import Path from math import log2, ceil import sys class SnoopableFIFO(BasicModule,BusParser): ## creating dictonary of variable def Create_dic_of_variable(self): self.variable_dict['FifoWidth']=self.FifoWidth self.variable_dict['FifoDepth']=self.FifoDepth self.variable_dict['SnoopWidth']=self.SnoopWidth self.variable_dict['EncodedDepth']=self.EncodedDepth def add_ports_from_bus(self): BasicModule.add_ports_from_bus(self) self.widop_flat("wdata", self.FifoWidth) self.widop_flat("rdata", self.FifoWidth) self.widop_flat("sdata", self.FifoWidth) # self.init_connections(self.dict) self.get_all_key_value_pairs(self.dict) def get_body(self): dynamicgenerator = DynamicGenerator(self.variable_dict, self.bpdy) # passing dictonary and bpdy to split the body self.body += dynamicgenerator.parse_body() self.body = self.body.replace("SNOOPWIDTH - 1", str(self.SnoopWidth -1)) self.body = self.body.replace("ENCODEDDEPTH - 1", str(self.EncodedDepth - 1)) self.body = self.body.replace("FIFOWIDTH - 1", str(self.FifoWidth - 1)) self.body = self.body.replace("ENCODEDDEPTH + 1", str(self.EncodedDepth + 1)) self.body = self.body.replace("ENCODEDDEPTH", str(self.EncodedDepth)) self.body = self.body.replace("FIFOWIDTH", str(self.FifoWidth)) self.body = self.body.replace("FIFODEPTH", str(self.FifoDepth)) self.body = self.body.replace("SNOOPWIDTH", str(self.SnoopWidth)) dynamicgenerator.silentremove() def __init__(self, fifowidth, fifodepth, snoopwidth, path_of_yaml = None, bus_name = None): self.FifoWidth = fifowidth self.FifoDepth = fifodepth self.SnoopWidth = snoopwidth self.EncodedDepth = int(ceil(log2(fifodepth))) if path_of_yaml is None: path_of_yaml = "../../../smartasic2/refbuses/astob.yaml" bus_name = "astob" self.name = "AH_"+self.__class__.__name__+"_"+str(fifowidth)+"_"+str(fifodepth)+"_"+str(snoopwidth) BusParser.__init__(self, self.load_dict(path_of_yaml), bus_name) BasicModule.__init__(self, self.name) self.bpdy=""" reg [ENCODEDDEPTH:0] wr_pointer; // ENCODEDDEPTH + 1 = log2(32) + 1 reg [ENCODEDDEPTH:0] rd_pointer; // ENCODEDDEPTH + 1 /f_f/ code = "\\n"+"\\n".join(["reg ["+str(FifoWidth-1)+":0] fifo_loc"+str(i)+";" for i in range(FifoDepth)]) /f_f/ always @ (posedge clk or negedge rstn) begin if(rstn) begin wr_pointer <= ENCODEDDEPTH + 1'd0; end else begin wr_pointer <= ( (wr_pointer[ENCODEDDEPTH] ^ rd_pointer[ENCODEDDEPTH]) && (wr_pointer[ENCODEDDEPTH - 1:0] == rd_pointer[ENCODEDDEPTH - 1:0]) ) ? wr_pointer : wr_valid ? ( wr_pointer + 1'b1) : wr_pointer; end end always @ (posedge clk or negedge rstn) begin if(rstn) begin rd_pointer <= ENCODEDDEPTH + 1'd0; end else begin rd_pointer <= (rd_pointer[ENCODEDDEPTH:0] == rd_pointer[ENCODEDDEPTH:0]) ? rd_pointer : rd_ready ? (rd_pointer + 1'b1) : rd_pointer; end end always @ (posedge clk or negedge rstn) begin if(!rstn) begin /f_f/ code = "\\n\t"+"\\n\t".join(["fifo_loc"+str(i)+" <= "+str(FifoWidth)+"'d0;" for i in range (FifoDepth)]) /f_f/ end else begin /f_f/ code = "\\n\t"+"\\n\t".join(["fifo_loc"+str(i)+" <= (wr_pointer["+str(EncodedDepth-2)+":0] == "+str(EncodedDepth)+"'d"+str(i)+") ? wr_data : fifo_loc"+str(i)+";" for i in range(FifoDepth)]) /f_f/ end end wr_ready = ! ( (wr_pointer[ENCODEDDEPTH] ^ rd_pointer[ENCODEDDEPTH]) && (wr_pointer[ENCODEDDEPTH - 1:0] == rd_pointer[ENCODEDDEPTH - 1:0]) ); rd_valid = !(rd_pointer[ENCODEDDEPTH:0] == rd_pointer[ENCODEDDEPTH:0]); assign rd_data = FIFOWIDTH'd0 | /f_f/ code = "\\n"+" |\\n ".join(["( (rd_pointer["+str(EncodedDepth)+":0] == "+str(EncodedDepth+1)+"'d))"]) /f_f/ assing snoop_match = 1'b0 | /f_f/ code = "\\n"+"|\\n ".join(["((fifo_loc["+str(SnoopWidth-1)+":0] == snoop_data) ? 1'b1 : 1'b0)" for i in range(FifoDepth)]) /f_f/ """ if __name__ == "__main__": if len(sys.argv) > 3: snoopablefifo=SnoopableFIFO(int(sys.argv[1]),int(sys.argv[2]),int(sys.argv[3]),sys.argv[4],sys.argv[5]) else: snoopablefifo=SnoopableFIFO(int(sys.argv[1]),int(sys.argv[2]),int(sys.argv[3])) snoopablefifo.main() <file_sep>import yaml import collections import copy import queue import re class BusParser: def __init__(self, filepath, bus_name): self.dict = yaml.load(open(filepath).read()) self.BusName = bus_name self.init_connections(self.dict) #============================================================================================================================================= # Used to craate an useful net name for each signal for example cpu_2_peripheral0_* bus. It overloads the prefix and prefloat directly # #============================================================================================================================================= def widop_flat(self, key, width): """Wrapper function for non heiarchical operations""" self.widop(self.get_path(key),width) def flipop_flat(self, key): """Wrapper function for non heiarchical operations""" self.flipop(self.get_path(key)) def prefixop_flat(self, key, prefix): """Wrapper function for non heiarchical operations""" self.prefixop(self.get_path(key), prefix) def prefloatop_flat(self, key, prefloat): """Wrapper function for non heiarchical operations""" self.prefloatop(self.get_path(key),prefloat) def remove_sub_dict_flat(self, key): """Wrapper function for non heiarchical operations""" self.remove_sub_dict(self.get_path(key)) def add_super_node_flat(self, key, node): """Wrapper function for non heiarchical operations""" self.add_super_node(self.get_path(key), node) def rename_flat(self, key, new_name): """Wrapper function for non heiarchical operations""" self.rename(self.get_path(key),new_name) def copy_flat(self, key, new_name): """Wrapper function for non heiarchical operations""" self.copy(self.get_path(key), new_name) def remove_node_flat(self, key): """Wrapper function for non heiarchical operations""" self.remove_node(self.get_path(key)) def add_sub_dict_flat(self, key, sub_dict): """Wrapper function for non heiarchical operations""" self.add_sub_dict(self.get_path(key),sub_dict) def get_subdict_flat(self, key, u): """Wrapper function for non heiarchical operations""" self.get_subdict(self.get_path(key),u) def add_world_view(self, world_view): """Adds world view like usb2cpu to the ports""" self.prefixop(self.BusName, world_view) self.prefloatop(self.BusName, world_view) def add_connection_flat(self, key, new_cname): self.add_connection(self.get_path(key), new_cname) def smart_connection_flat(self, key, linked_to, pattern_in_cname, replacement): self.smart_connectionop(self.get_path(key), linked_to, pattern_in_cname, replacement) def widop(self, exp, width): """Changes width of a fluid port""" heiarchy = exp.split(".") temp = self.dict.copy() for levels in heiarchy: temp = temp[levels] if temp['type'] == 'nonfluid': raise Exception("The width of this signal cannot be changed") else: temp['width'] = width def flipop(self, exp): """Flips all the ports of a subtdict provided by heiarchy""" heiarchy = exp.split(".") temp = self.dict.copy() for levels in heiarchy: temp = temp[levels] #print(heiarchy[len(heiarchy)-1]) self.flip(temp) def flip(self, u): """ Used by flipop :param u: :return: flipped subdict """ for k, v in u.items(): if isinstance(v, collections.Mapping): u[k] = self.flip(u.get(k)) else: u['direction'] = 'output' if u['direction'] == 'input' else 'input' return u def print(self): """ Prints the current dictionary :return: None """ print(self.dict) def dyaml(self, filename): """ Dumps the current dict to a yaml. :param filename: File path to which the dyaml will be dumped :return: None """ noalias_dumper = yaml.dumper.SafeDumper noalias_dumper.ignore_aliases = lambda self , data : True with open(filename,"w") as f: f.write(yaml.dump(self.dict,default_flow_style = False,Dumper = noalias_dumper,indent =4,width = 25)) f.close() def prefixop(self, exp, prefix): """ Adds prefix to the :param exp: The heiarchy of the node to whose subdict the prefix is added. Eg: "astob.wr" :param prefix: Eg: usb2cpu :return: None """ heiarchy = exp.split(".") temp = self.dict.copy() for levels in heiarchy: temp = temp[levels] self.change_prefix(temp,prefix) def prefloatop(self, exp, prefloat): """ Adds prefix to the :param exp: The heiarchy of the node to whose subdict the prefix is added. Eg: "astob.wr" :param prefloat: Eg: usb2cpu :return: None """ heiarchy = exp.split(".") temp = self.dict.copy() for levels in heiarchy: temp = temp[levels] self.change_prefloat(temp,prefloat) def change_prefix(self, u, pf): """ :param u: the subdict to which prefix is to be added. :param pf: the prefix :return: returns changed subdict """ for k in list(u.keys()): if isinstance(u.get(k), collections.Mapping): u[k] = self.change_prefix(u.get(k), pf) else: u['prefix'] = pf return u def change_prefloat(self, u, pf): """ :param u: the subdict whose prefloat is to be changed. :param pf: the prefloat. :return: the changed subdict. """ for k in list(u.keys()): if isinstance(u.get(k), collections.Mapping): u[k] = self.change_prefloat(u.get(k), pf) else: u['prefloat'] = pf return u """ def port_names(self, u, names) for k in list(u.keys()): if list(u[k].keys())[0] != "direction": u[k] = self.port_names(u.get(k), names) else: if not any([u == i for i in names]): names.append(u) return names """ def remove_sub_dict(self, exp): """ :param exp: Heiarchy of the node whose subdict is to be removed for eg: "astob.rd" :return: None """ heiarchy = exp.split(".") temp = self.dict.copy() for i in range(len(heiarchy)-1): # print(temp) temp = temp[heiarchy[i]] del temp[heiarchy[len(heiarchy)-1]] def add_super_node(self,exp,node): """ :param exp: Heiarchy of the node which becomes child of the super node to be added. :param node: super node's name :return: None """ heiarchy = exp.split(".") temp = self.dict.copy() for i in range(len(heiarchy) - 1): temp = temp[heiarchy[i]] sub_dict = copy.deepcopy(temp[heiarchy[len(heiarchy)-1]]) del temp[heiarchy[len(heiarchy) - 1]] temp = self.dict.copy() for i in range(len(heiarchy)-2): temp = temp [heiarchy[i]] #print(temp) if not node in list(temp[heiarchy[len(heiarchy)-2]].keys()): temp[heiarchy[len(heiarchy)-2]][node] = {heiarchy[len(heiarchy)-1]:sub_dict} else: #print("1"*52) temp[heiarchy[len(heiarchy)-2]][node].update({heiarchy[len(heiarchy)-1]:sub_dict}) def rename(self,exp,new_name): """ :param exp: Heiarchy of the node to be renamed. :param new_name: New name of the node. :return: None """ heiarchy = exp.split(".") temp = self.dict.copy() for i in range(len(heiarchy) - 1): temp = temp[heiarchy[i]] sub_dict = copy.deepcopy(temp[heiarchy[len(heiarchy) - 1]]) del temp[heiarchy[len(heiarchy) - 1]] temp = self.dict.copy() for i in range(len(heiarchy) - 1): temp = temp[heiarchy[i]] temp[new_name] = sub_dict def copy(self,exp,new_name): """ :param exp: Heiarchy of the subdict to be copied. :param new_name: Node to which its copied on the same Level. :return: None """ heiarchy = exp.split(".") temp = self.dict.copy() for i in range(len(heiarchy) - 1): temp = temp[heiarchy[i]] sub_dict = copy.deepcopy(temp[heiarchy[len(heiarchy)-1]]) temp.update({new_name: sub_dict}) def remove_node(self, exp): """ :param exp: Heiarchy of the node to be removed :return: None """ heiarchy = exp.split(".") temp = self.dict.copy() for i in range(len(heiarchy) - 1): temp = temp[heiarchy[i]] #del temp[heiarchy[len(heiarchy)-1]] sub_dict = copy.deepcopy(temp[heiarchy[len(heiarchy) - 1]]) del temp[heiarchy[len(heiarchy)-1]] temp.update(sub_dict) def add_sub_dict(self,exp,sub_dict): """ :param exp: Heiarchy of the node to which subdict will be added. :param sub_dict: subdict to add :return: None """ heiarchy = exp.split(".") temp = self.dict.copy() for i in range(len(heiarchy)): temp = temp[heiarchy[i]] temp.update(sub_dict) def get_path(self, key): """ Returns heiarchical path of a key :param key: a unique key of the dictionary. :return: Returns a string which denotes the heiarchical path of the key. """ qu = queue.Queue(maxsize=1000) qu.put(self.BusName) while not qu.empty(): path = qu.get() temp_dict = self.get_subdict(path, self.dict) if isinstance(temp_dict, collections.Mapping): for k in temp_dict.keys(): if k == key: return path + "." + k # print(path + "." + k) qu.put(path + "." + k) def get_subdict(self,exp,u): """ :param exp: Heiarchy of the subdict to be fetched :param u: original dictionary :return: None """ heiarchy = exp.split(".") temp = u.copy() for levels in heiarchy: temp = temp[levels] return temp def smart_connectionop(self, exp, linked_to, pattern_in_cname, replacement): """ :param exp: The heiarchy of the node to which connection is to be made. :param linked_to: The class object to which the invoking object will be connected :param connection_name: The name of the created connection :return: None """ heiarchy = exp.split(".") temp = self.dict.copy() for levels in heiarchy: temp = temp[levels] self.smart_connection(temp, linked_to, pattern_in_cname, replacement) def smart_connection(self, u, linked_to, pattern_in_cname, replacement): for k in list(u.keys()): if isinstance(u.get(k), collections.Mapping): u[k] = self.smart_connection(u.get(k), linked_to, pattern_in_cname, replacement) else: u.update({"linked_to": linked_to.name if linked_to is not None else None, "cname": re.sub(pattern_in_cname, replacement, u['cname'])}) return u def init_connections(self, data): def inner(data): if isinstance(data, dict): for k, v in data.items(): if isinstance(v, dict) or isinstance(v, list) or isinstance(v, tuple): if 'direction' in v.keys(): v.update({"cname": "_".join(self.get_path(k).split(".")[1:])}) v.update({"heiarchy": "_".join(self.get_path(k).split(".")[1:])}) v.update({"linked_to": None}) v.update({"name": "_".join(self.get_path(k).split(".")[len(self.get_path(k).split(".")) - 1:])}) inner(v) elif isinstance(data, list) or isinstance(data, tuple): for item in data: inner(item) inner(data) def add_connection(self, exp, connection_name): heiarchy = exp.split(".") temp = self.dict.copy() for levels in heiarchy: temp = temp[levels] temp.update({"cname": connection_name}) <file_sep>import os #from templates import mux_body_template from smartasic import BasicModule,Port from DynamicGenerator import DynamicGenerator from BusParser import BusParser from pathlib import Path from math import log2, ceil import sys class Decoder(BasicModule,BusParser): ## creating dictonary of variable def Create_dic_of_variable(self): self.variable_dict['PortWidth']=self.PortWidth self.variable_dict['NumClients']=self.NumClients self.variable_dict['EncodedNumClients']=self.EncodedNumClients #self.variable_dict['AperturesYaml']=self.AperturesYaml def add_ports_from_bus(self): BasicModule.add_ports_from_bus(self) #print(self.dict) self.dyaml("1.yaml") print("I am going to operate on this dict now") self.widop_flat("ingress_pkt_field", self.PortWidth) self.widop_flat("decoded_binary", self.EncodedNumClients) # print(self.dict) self.dyaml("4.yaml") print("I am done with this dict") #self.init_connections(self.dict) self.get_all_key_value_pairs(self.dict) def get_body(self): dynamicgenerator=DynamicGenerator(self.variable_dict,self.decoderbody) # passing dictonary and snoopbody to split the body self.body+=dynamicgenerator.parse_body() self.body = self.body.replace("ENCODEDNUMCLIENTS - 1", str(self.EncodedNumClients -1)) self.body = self.body.replace("ENCODEDNUMCLIENTS", str(self.EncodedNumClients)) #self.body = self.body.replace("NAME", "mux" if self.IsDemux is None else "demux") #self.body = self.body.replace("MUXNUMCLIENTS", str(self.NumClients)) dynamicgenerator.silentremove() def get_verilog(self): modulecode=self.get_header() self.get_body() modulecode=modulecode.replace("BODY",self.body) return modulecode def main(self): print("I am about to write a verilog file now") self.write_to_file(self.get_verilog()) print (self.get_verilog()) return self.get_verilog() def __init__(self, portwidth, numclients, path_of_yaml=None, bus_name=None, apertures_yaml=None): if path_of_yaml is None: path_of_yaml = "../../../smartasic2/refbuses/decoder.yaml" bus_name = "decoder" apertures_yaml = "decode_apertures.yaml" self.AperturesYaml = apertures_yaml self.PortWidth = portwidth self.NumClients = numclients self.EncodedNumClients = int(ceil(log2(numclients))) self.name = "AH_decoder_"+str(self.PortWidth)+"_"+str(self.NumClients) print("Just checking what is the file name..") # print (self.name) # BasicModule.__init__(self, self.name) self.body = "" self.variable_dict={} self.Create_dic_of_variable() self.decode_apertures_dict = self.load_dict(apertures_yaml) BusParser.__init__(self, self.load_dict(path_of_yaml), bus_name) BasicModule.__init__(self, self.name) #self.add_ports_from_bus() self.decoderbody = """ // Ingress and Egress are short circuited based on condition wire [ENCODEDNUMCLIENTS - 1:0] decoded_binary; wire dec_err; /f_f/ import yaml ap_dict = yaml.load(open("decode_apertures.yaml").read()) code = "" for (k,v) in ap_dict['decode_apertures'].items(): #print ("I am inside dictionary with K and V as ") #print("K is "+str(k)) #print("V is "+str(v)) code += "\\n\t"+"wire assign decode_range_"+str(k)+"_tom ="+str(v['tom']) code += "\\n\t"+"wire assign decode_range_"+str(k)+"_bom ="+str(v['bom']) /f_f/ /f_f/ code = "" for i in range(NumClients): code += "\\n\t"+"assign decoded_binary["+str(i)+"] = ( (ingress_pkt_field) >= decode_range_client"+str(i)+"_bom) && (ingress_pkt_field) <= decode_range_client"+str(i)+"_tom" /f_f/ assign dec_err = ~ (|decoded_binary); """ if __name__ == "__main__": if len(sys.argv) > 3: decoder=Decoder(int(sys.argv[1]), int(sys.argv[2]), sys.argv[3], sys.argv[4], sys.argv[5]) else: decoder=Decoder(int(sys.argv[1]), int(sys.argv[2])) decoder.main() <file_sep>from templates import snoopable_fifo_template from math import log2, ceil import sys from smartasic import BasicModule from BusParser import BusParser class SnoopableFIFO(BasicModule, BusParser): def __init__(self, fifowidth, fifodepth, snoopwidth, bus_name, path_of_yaml): self.FifoWidth = fifowidth self.FifoDepth = fifodepth self.SnoopWidth = snoopwidth self.name = "AH_"+self.__class__.__name__+"_"+str(fifowidth)+"_"+str(fifodepth)+"_"+str(snoopwidth) BasicModule.__init__(self,self.name) self.body = None self.EncodedDepth = int(ceil(log2(fifodepth))) BusParser.__init__(self, path_of_yaml, bus_name) self.add_ports_from_bus() #======================================================= # overwrite the add_ports_from_bus method here. # Create the instance of busparser class. # Then use the wid_op method to change the port width req, gnt, gnt_busy signals. #======================================================= def add_ports_from_bus(self): #1. assuming that we are loading arbiter.yaml #2. parser.wid_op (num_clientm , a.b.c.d format pass the signal name) #3. Do this for all the signals that are required. #print(parser.dict) BasicModule.add_ports_from_bus(self) self.widop_flat("wdata",self.FifoWidth) self.widop_flat("rdata",self.FifoWidth) self.widop_flat("sdata",self.FifoWidth) self.get_all_key_value_pairs(self.dict) def get_body(self): self.body = snoopable_fifo_template self.body = self.body.replace("SNOOPWIDTH - 1", str(self.SnoopWidth -1)) self.body = self.body.replace("ENCODEDDEPTH - 1", str(self.EncodedDepth - 1)) self.body = self.body.replace("FIFOWIDTH - 1", str(self.FifoWidth - 1)) self.body = self.body.replace("ENCODEDDEPTH + 1", str(self.EncodedDepth + 1)) self.body = self.body.replace("ENCODEDDEPTH", str(self.EncodedDepth)) self.body = self.body.replace("FIFOWIDTH", str(self.FifoWidth)) self.body = self.body.replace("FIFODEPTH", str(self.FifoDepth)) self.body = self.body.replace("SNOOPWIDTH", str(self.SnoopWidth)) self.body = self.body.replace("//REG_DECLARATIONS", self.get_reg_str("reg", "\n", self.FifoWidth, "fifo_loc", self.FifoDepth)) self.body = self.body.replace("//ASSIGN_LOC", self.write_loc_rstn("\n\t", "fifo_loc", self.FifoWidth, self.FifoDepth)) self.body = self.body.replace("//LOC_WRITE", self.write_loc("\n\t", "fifo_loc",self.EncodedDepth,self.FifoDepth)) self.body = self.body.replace("//ASSIGN_READ",self.read_loc(self.EncodedDepth,"fifo_loc",self.FifoWidth,self.FifoDepth,"|\n")) self.body = self.body.replace("//ASSIGN_SNOOP_MATCH", self.snoop_match_noinv("fifo_loc","snoop_data",self.SnoopWidth,self.FifoDepth,"|\n")) def get_verilog(self): modulecode = self.get_header() self.get_body() modulecode = modulecode.replace("BODY", self.body) return modulecode def __str__(self): self.write_to_file(self.get_verilog()) return self.get_verilog() #print(SnoopableFIFO(int(sys.argv[1]),int(sys.argv[2]),int(sys.argv[3]),sys.argv[4],sys.argv[5]))
b35d2dc4a52a8351a6fa239c79735ba0bfc77277
[ "Markdown", "Python" ]
33
Python
mayukh45/Modules
5d367df25af319ffed3d3d95de356c22c8672d00
f4269df572985e596aa80f1f38e74186976bda87
refs/heads/master
<file_sep>import { Provider } from './src/Providers'; export default Provider; <file_sep>import 'react-native-gesture-handler'; import { NavigationContainer } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; import React, { useContext, useEffect, useState } from 'react'; import { ActivityIndicator, Button, Text } from 'react-native'; import { Center } from './Center'; import AsyncStorage from '@react-native-async-storage/async-storage'; import { AuthContext } from './AuthProvider'; const Stack = createStackNavigator(); // Screens function Login({ navigation }) { const { login } = useContext(AuthContext); return ( <Center> <Text>I am a login screen</Text> <Button title="log me in" onPress={() => { login(); }} /> <Button title="Go to register" onPress={() => { navigation.navigate('Register'); }} /> </Center> ); } function Register({ navigation, route }) { return ( <Center> <Text>Route Name: {route.name}</Text> <Text>I am a register screen</Text> <Button title="go to login" onPress={() => { navigation.navigate('Login'); // navigation.goBack(); }} /> </Center> ); } export const Routes = () => { const { user, login } = useContext(AuthContext); const [loading, setLoading] = useState(true); useEffect(() => { // check if the user is logged in or not AsyncStorage.getItem('user') .then(userString => { if (userString) { // decode it login(); } else { setLoading(false); } }) .catch(err => { console.error(err); setLoading(false); }); }); if (loading) { return ( <Center> <ActivityIndicator size="large" color="black" /> </Center> ); } return ( <NavigationContainer> {user ? ( <Center> <Text>you exist</Text> </Center> ) : ( <Stack.Navigator // for all the screens // screenOptions={{ // header: () => null, // }} initialRouteName="Login"> <Stack.Screen name="Login" options={{ headerTitle: 'Sign In', }} component={Login} /> <Stack.Screen name="Register" options={{ // for individual screens headerTitle: 'Sign Up', }} component={Register} /> </Stack.Navigator> )} </NavigationContainer> ); }; <file_sep># SETUP You can follow any of the following links for setup: - [React Native V2 by <NAME>](https://kadikraman.github.io/react-native-v2/navigation-rn) - [React Navigation docs](https://reactnavigation.org/docs/getting-started) Add the stack, bottom-tabs or drawer navigation as per your requirements: ### Stack Navigation ```bash npm i @react-navigation/stack ``` ### Bottom Tabs Navigation ```bash npm i @react-navigation/bottom-tabs ``` ### Drawer Navigation ```bash npm i @react-navigation/drawer ```
6f282271d55080eba2206fe02a9be15cea074c36
[ "JavaScript", "Markdown" ]
3
JavaScript
hassanrehman01398/Exploring-React-Navigation-V5
0a6caa459f281a3b95a6efb3e05c2ee8b770756b
44800ccb86a4f08f62d05ff868162430cb27ec89
refs/heads/main
<repo_name>waldoomaet/Cuanto_Apotamo<file_sep>/Cuanto Apotamo/Cuanto Apotamo/Dummy services/LogInApiService.cs using Cuanto_Apotamo.Models; using Cuanto_Apotamo.Services; using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Text.Json; using System.Threading.Tasks; namespace Cuanto_Apotamo.Dummy_services { class LogInApiService : ILogInApiService { public async Task<LogInApiResponse> Authenticate(Credentials userCredentials) { if (string.IsNullOrEmpty(userCredentials.UserName)) { return new LogInApiResponse() { Status = "fail", ErrorMessage = "User field missing" }; } else if (string.IsNullOrEmpty(userCredentials.Password)) { return new LogInApiResponse() { Status = "fail", ErrorMessage = "User password missing" }; } else if(userCredentials.UserName == "true" && userCredentials.Password == "<PASSWORD>") { var foundUser = new User() { FullName = "<NAME>", Username = "wruiz", IdentificationDocument = "abc1234", Email = "<EMAIL>", CreditCardNumber = 1234567812345678, CVV = 123, CreditCardExpirationDate = DateTime.Now, Balance = 100.23f }; return new LogInApiResponse() { Status = "success", Data = foundUser, ErrorMessage = "" }; } else { return new LogInApiResponse() { Status = "fail", ErrorMessage = "User or password missing" }; } } } } <file_sep>/Cuanto Apotamo/Cuanto Apotamo/ViewModels/RootViewModel.cs using Cuanto_Apotamo.Models; using Cuanto_Apotamo.Services; using Prism.Commands; using Prism.Navigation; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using System.Windows.Input; namespace Cuanto_Apotamo.ViewModels { public class RootViewModel : BaseViewModel, INavigatedAware { private User _user { get; set; } public ObservableCollection<FlyoutOption> FlyoutOptions { get; set; } public ObservableCollection<FlyoutOption> FavoriteFlyoutOptions { get; set; } public FlyoutOption SelectedFavoriteFlyoutOption { get; set; } public FlyoutOption SelectedFlyoutOption { get; set; } public ICommand NavigateCommand { get; set; } public ICommand StarCommand { get; set; } public bool HasFavorites { get; set; } // This probably should be the balance in user object public string Money { get; set; } public RootViewModel(INavigationService navigationService) : base(navigationService) { // TODO: This must be an API call that brings all the favorite categories of the user FavoriteFlyoutOptions = new ObservableCollection<FlyoutOption>(); HasFavorites = FavoriteFlyoutOptions.Count > 0; // TODO: This must be an API call that brings all the categories of the Flyout FlyoutOptions = new ObservableCollection<FlyoutOption>() { new FlyoutOption("Politica"), new FlyoutOption("Musica"), new FlyoutOption("Arte") }; StarCommand = new DelegateCommand<FlyoutOption>(OnStartClicked); NavigateCommand = new DelegateCommand<string>(async (string path) => { await NavigationService.NavigateAsync($"{Constants.Navigation.NavigationPage}/{path}", _user.ToNavigationParameters()); }); } public void OnStartClicked(FlyoutOption option) { option.IsStarted = !option.IsStarted; if (!option.IsStarted) { FavoriteFlyoutOptions.Remove(option); FlyoutOptions.Add(option); } else { FlyoutOptions.Remove(option); FavoriteFlyoutOptions.Add(option); } HasFavorites = FavoriteFlyoutOptions.Count > 0; } public void OnNavigatedTo(INavigationParameters parameters) { _user = new User(parameters); Money = $"${_user.Balance}"; } public void OnNavigatedFrom(INavigationParameters parameters) { } } }<file_sep>/Cuanto Apotamo/Cuanto Apotamo/Dummy services/SignUpApiService.cs using Cuanto_Apotamo.Models; using Cuanto_Apotamo.Services; using System; using System.Collections.Generic; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Cuanto_Apotamo.Dummy_services { class SignUpApiService : ISignUpApiService { public async Task<SignUpApiResponse> Create(User newUser) { if (newUser.Password != newUser.ReEnteredPassword) { Dictionary<string, string> responseData = new Dictionary<string, string>() { {"password", "Both passwords must be equal!"} }; return new SignUpApiResponse() { Status = "fail", Data = responseData, ErrorMessage = "" }; } // Basic validation to assure that any property is null foreach (PropertyInfo prop in newUser.GetType().GetProperties()) { if (prop.GetValue(newUser) is null) { Dictionary<string, string> responseData = new Dictionary<string, string>() { {prop.Name, $"{prop.Name} is required! {prop.GetValue(newUser)} was passed."} }; return new SignUpApiResponse() { Status = "fail", Data = responseData, ErrorMessage = "" }; } } return new SignUpApiResponse() { Status = "success", Data = newUser, ErrorMessage = "" }; } public async Task<string> Test() { return "Hello world!"; } } } <file_sep>/Cuanto Apotamo/Cuanto Apotamo/ViewModels/LogInViewModel.cs using Cuanto_Apotamo.Models; using Cuanto_Apotamo.Services; using Prism.Commands; using Prism.Navigation; using Prism.Services; using System; using System.Collections.Generic; using System.Text; using System.Windows.Input; using Xamarin.Essentials; namespace Cuanto_Apotamo.ViewModels { class LogInViewModel : BaseViewModel { public Credentials Credentials { get; set; } private IPageDialogService _alertService; private ILogInApiService _logInService; public ICommand LogInCommand { get; set; } public ICommand CreateAccountCommand { get; set; } public LogInViewModel(INavigationService navigationService, ILogInApiService LogInApiService, IPageDialogService dialogService) : base(navigationService) { Credentials = new Credentials(); LogInCommand = new DelegateCommand(OnLogIn); CreateAccountCommand = new DelegateCommand(async () => { await NavigationService.NavigateAsync($"{Constants.Navigation.SignUp}"); }); _alertService = dialogService; _logInService = LogInApiService; } private async void OnLogIn() { if (Connectivity.NetworkAccess == NetworkAccess.Internet) { var response = await _logInService.Authenticate(Credentials); if (response.Status == "success") { await _alertService.DisplayAlertAsync("Success!", $"Tu usuario fue autenticado satisfactoriamente!", "Ok"); // Have to change next line User returnedUser = (User)response.Data; var nav = new NavigationParameters(); // Tengo que poner returnedUser aqui await NavigationService.NavigateAsync($"/{Constants.Navigation.Root}/Navigation/tabbed", nav); } else if (response.Status == "fail") { await _alertService.DisplayAlertAsync("Error", $"Usuario o Contraseña Incorrectos", "Ok"); } else { await _alertService.DisplayAlertAsync("Error", $"Algo ocurrio: {response.ErrorMessage}", "Ok"); } } else { await _alertService.DisplayAlertAsync("Error", "Compruebe su conexion a Internet", "Ok"); } } } } <file_sep>/WebAPI/Data/Configuration/BalanceTransactionEntityTypeConfiguration.cs using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WebAPI.Domain; namespace WebAPI.Data.Configuration { public class BalanceTransactionEntityTypeConfiguration : IEntityTypeConfiguration<BalanceTransaction> { public void Configure(EntityTypeBuilder<BalanceTransaction> builder) { builder.HasKey(f => f.Id); builder.HasOne(f => f.User) .WithMany(a => a.BalanceTransactions) .HasForeignKey(a => a.UserID) /*.OnDelete(DeleteBehavior.Cascade)*/; builder.Property(f => f.Balance) .IsRequired(); builder.Property(f => f.RegistrationDate) .HasDefaultValue(DateTime.Now); } } } <file_sep>/WebAPI/Migrations/20211015043009_initial.cs using System; using Microsoft.EntityFrameworkCore.Migrations; namespace WebAPI.Migrations { public partial class initial : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Bets", columns: table => new { Id = table.Column<int>(type: "INTEGER", nullable: false) .Annotation("Sqlite:Autoincrement", true), Title = table.Column<string>(type: "TEXT", nullable: false), Description = table.Column<string>(type: "TEXT", nullable: false), TotalBets = table.Column<float>(type: "REAL", nullable: false), TotalPlayers = table.Column<int>(type: "INTEGER", nullable: false), Status = table.Column<int>(type: "INTEGER", nullable: false), RegistrationDate = table.Column<DateTime>(type: "TEXT", nullable: false, defaultValue: new DateTime(2021, 10, 15, 0, 30, 8, 930, DateTimeKind.Local).AddTicks(3499)) }, constraints: table => { table.PrimaryKey("PK_Bets", x => x.Id); }); migrationBuilder.CreateTable( name: "Users", columns: table => new { Id = table.Column<int>(type: "INTEGER", nullable: false) .Annotation("Sqlite:Autoincrement", true), FullName = table.Column<string>(type: "TEXT", nullable: false), Username = table.Column<string>(type: "TEXT", nullable: false), IdentificationDocument = table.Column<string>(type: "TEXT", nullable: false), Email = table.Column<string>(type: "TEXT", nullable: false), CreditCardNumber = table.Column<string>(type: "TEXT", nullable: false), CVV = table.Column<int>(type: "INTEGER", nullable: false), CreditCardExpirationDate = table.Column<DateTime>(type: "TEXT", nullable: false), Password = table.Column<string>(type: "TEXT", nullable: false), Balance = table.Column<float>(type: "REAL", nullable: false), RegistrationDate = table.Column<DateTime>(type: "TEXT", nullable: false, defaultValue: new DateTime(2021, 10, 15, 0, 30, 8, 938, DateTimeKind.Local).AddTicks(2610)) }, constraints: table => { table.PrimaryKey("PK_Users", x => x.Id); }); migrationBuilder.CreateTable( name: "BetOptions", columns: table => new { Id = table.Column<int>(type: "INTEGER", nullable: false) .Annotation("Sqlite:Autoincrement", true), BetId = table.Column<int>(type: "INTEGER", nullable: false), Title = table.Column<string>(type: "TEXT", nullable: false), TotalBets = table.Column<float>(type: "REAL", nullable: false), TotalPlayers = table.Column<int>(type: "INTEGER", nullable: false), Stake = table.Column<float>(type: "REAL", nullable: false), DidWin = table.Column<bool>(type: "INTEGER", nullable: false), RegistrationDate = table.Column<DateTime>(type: "TEXT", nullable: false, defaultValue: new DateTime(2021, 10, 15, 0, 30, 8, 934, DateTimeKind.Local).AddTicks(7608)) }, constraints: table => { table.PrimaryKey("PK_BetOptions", x => x.Id); table.ForeignKey( name: "FK_BetOptions_Bets_BetId", column: x => x.BetId, principalTable: "Bets", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "BalanceTransactions", columns: table => new { Id = table.Column<int>(type: "INTEGER", nullable: false) .Annotation("Sqlite:Autoincrement", true), UserID = table.Column<int>(type: "INTEGER", nullable: false), Balance = table.Column<float>(type: "REAL", nullable: false), RegistrationDate = table.Column<DateTime>(type: "TEXT", nullable: false, defaultValue: new DateTime(2021, 10, 15, 0, 30, 8, 915, DateTimeKind.Local).AddTicks(1539)) }, constraints: table => { table.PrimaryKey("PK_BalanceTransactions", x => x.Id); table.ForeignKey( name: "FK_BalanceTransactions_Users_UserID", column: x => x.UserID, principalTable: "Users", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "UserBets", columns: table => new { Id = table.Column<int>(type: "INTEGER", nullable: false) .Annotation("Sqlite:Autoincrement", true), UserId = table.Column<int>(type: "INTEGER", nullable: false), BetOptionId = table.Column<int>(type: "INTEGER", nullable: false), Amount = table.Column<float>(type: "REAL", nullable: false), RegistrationDate = table.Column<DateTime>(type: "TEXT", nullable: false, defaultValue: new DateTime(2021, 10, 15, 0, 30, 8, 932, DateTimeKind.Local).AddTicks(6536)) }, constraints: table => { table.PrimaryKey("PK_UserBets", x => x.Id); table.ForeignKey( name: "FK_UserBets_BetOptions_BetOptionId", column: x => x.BetOptionId, principalTable: "BetOptions", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_UserBets_Users_UserId", column: x => x.UserId, principalTable: "Users", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_BalanceTransactions_UserID", table: "BalanceTransactions", column: "UserID"); migrationBuilder.CreateIndex( name: "IX_BetOptions_BetId", table: "BetOptions", column: "BetId"); migrationBuilder.CreateIndex( name: "IX_UserBets_BetOptionId", table: "UserBets", column: "BetOptionId"); migrationBuilder.CreateIndex( name: "IX_UserBets_UserId", table: "UserBets", column: "UserId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "BalanceTransactions"); migrationBuilder.DropTable( name: "UserBets"); migrationBuilder.DropTable( name: "BetOptions"); migrationBuilder.DropTable( name: "Users"); migrationBuilder.DropTable( name: "Bets"); } } } <file_sep>/WebAPI/Data/Configuration/BetEntityTypeConfiguration.cs using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WebAPI.Domain; namespace WebAPI.Data.Configuration { public class BetEntityTypeConfiguration : IEntityTypeConfiguration<Bet> { public void Configure(EntityTypeBuilder<Bet> builder) { builder.HasKey(f => f.Id); builder.Property(f => f.Title) .IsRequired(); builder.Property(f => f.Description) .IsRequired(); builder.Property(f => f.TotalBets) .IsRequired(); builder.Property(f => f.TotalPlayers) .IsRequired(); builder.Property(f => f.Status) .IsRequired(); builder.HasMany(s => s.BetOptions) .WithOne(sp => sp.Bet) .HasForeignKey(sp => sp.BetId); builder.Property(f => f.RegistrationDate) .HasDefaultValue(DateTime.Now); } } } <file_sep>/Cuanto Apotamo/Cuanto Apotamo/ViewModels/TempViewModel.cs using Cuanto_Apotamo.Models; using Prism.Navigation; using System; using System.Collections.Generic; using System.Text; namespace Cuanto_Apotamo.ViewModels { class TempViewModel : BaseViewModel { public Bet Bet { get; set; } = new Bet("titulo", 1000, "te la entierro", "donde hay tierra", 25); public TempViewModel(INavigationService navigationService) : base(navigationService) { } } } <file_sep>/Cuanto Apotamo/Cuanto Apotamo/Services/LogInApiService.cs using Cuanto_Apotamo.Models; using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Text.Json; using System.Threading.Tasks; namespace Cuanto_Apotamo.Services { class LogInApiService : ILogInApiService { private static HttpClient _client = new HttpClient(); public LogInApiService() { _client.BaseAddress = new Uri(Constants.Url.Api); } public async Task<LogInApiResponse> Authenticate(Credentials userCredentials) { var response = await _client.PostAsync("LogIn/Authenticate", new StringContent(JsonSerializer.Serialize(userCredentials), Encoding.UTF8, "application/json")); var responseString = await response.Content.ReadAsStringAsync(); return JsonSerializer.Deserialize<LogInApiResponse>(responseString); } } } <file_sep>/WebAPI/Domain/BetOption.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebAPI.Domain { public class BetOption { public int Id { get; set; } public int BetId { get; set; } public Bet Bet { get; set; } public string Title { get; set; } public float TotalBets { get; set; } public int TotalPlayers { get; set; } public float Stake { get; set; } public bool DidWin { get; set; } public DateTime RegistrationDate { get; set; } public ICollection<UserBet> UserBets { get; set; } } } <file_sep>/Cuanto Apotamo/Cuanto Apotamo/Models/BetOption.cs using System; using System.Collections.Generic; using System.Text; namespace Cuanto_Apotamo.Models { class BetOption { public string Title { get; set; } public int Players { get; set; } public float Fund { get; set; } public string stake { get; set; } } } <file_sep>/Cuanto Apotamo/Cuanto Apotamo/ViewModels/SignUpViewModel.cs using Cuanto_Apotamo.Models; using Cuanto_Apotamo.Services; using Prism.Commands; using Prism.Navigation; using Prism.Services; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.Json; using System.Windows.Input; using Xamarin.Essentials; namespace Cuanto_Apotamo.ViewModels { class SignUpViewModel : BaseViewModel { public User User { get; set; } public string Test { get; set; } = "Prueba"; private IPageDialogService _alertService; private ISignUpApiService _signUpService; public ICommand SignUpCommand { get; set; } public SignUpViewModel(INavigationService navigationService, ISignUpApiService signUpApiService, IPageDialogService dialogService) : base(navigationService) { User = new User(); SignUpCommand = new DelegateCommand(OnSignUp); _alertService = dialogService; _signUpService = signUpApiService; } private async void OnSignUp() { if (Connectivity.NetworkAccess == NetworkAccess.Internet) { var response = await _signUpService.Create(User); if (response.Status == "success") { User returnedUser = JsonSerializer.Deserialize<User>(JsonSerializer.Serialize(response.Data)); await _alertService.DisplayAlertAsync("Success!", $"{returnedUser.FullName} tu usuario fue creado satisfactoriamente!", "Ok"); var navigationParams = new NavigationParameters { }; await NavigationService.NavigateAsync($"/{Constants.Navigation.NavigationPage}/{Constants.Navigation.Root}/{Constants.Navigation.MainPage}"); } else if (response.Status == "fail") { var returnedData = JsonSerializer.Deserialize<Dictionary<string, string>>(JsonSerializer.Serialize(response.Data)); await _alertService.DisplayAlertAsync("Error", $"{returnedData.First().Value}", "Ok"); } else { await _alertService.DisplayAlertAsync("Error", $"Algo ocurrio: {response.ErrorMessage}", "Ok"); } } else { await _alertService.DisplayAlertAsync("Error", "Sin conexión a Internet", "Ok"); } } } } <file_sep>/Cuanto Apotamo/Cuanto Apotamo/Services/SignUpApiService.cs using Cuanto_Apotamo.Models; using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Text.Json; using System.Threading.Tasks; namespace Cuanto_Apotamo.Services { class SignUpApiService : ISignUpApiService { private static HttpClient _client = new HttpClient(); public SignUpApiService() { _client.BaseAddress = new Uri(Constants.Url.Api); } public async Task<SignUpApiResponse> Create(User newUser) { var response = await _client.PostAsync("api/SignUp/Create", new StringContent(JsonSerializer.Serialize(newUser), Encoding.UTF8, "application/json")); var responseString = await response.Content.ReadAsStringAsync(); return JsonSerializer.Deserialize<SignUpApiResponse>(responseString); } public async Task<string> Test() { try { var response = await _client.GetAsync("api/SignUp/Test"); return await response.Content.ReadAsStringAsync(); } catch (Exception err) { throw err; } } } }<file_sep>/Cuanto Apotamo/Cuanto Apotamo/ViewModels/MainViewModel.cs using Prism.Navigation; using System; using System.Collections.Generic; using System.Text; namespace Cuanto_Apotamo.ViewModels { class MainViewModel : BaseViewModel { public string Text => "Hello world"; public MainViewModel(INavigationService navigationService) : base(navigationService) { } } } <file_sep>/Cuanto Apotamo/Cuanto Apotamo/Models/User.cs using Prism.Navigation; using System; using System.Collections.Generic; using System.Text; using System.Text.Json.Serialization; namespace Cuanto_Apotamo.Models { class User : NavigationParameterManager { public User() { } public User(INavigationParameters navigationParameters) : base(navigationParameters) { } [JsonPropertyName("fullName")] public string FullName { get; set; } [JsonPropertyName("username")] public string Username { get; set; } [JsonPropertyName("identificationDocument")] public string IdentificationDocument { get; set; } [JsonPropertyName("email")] public string Email { get; set; } [JsonPropertyName("creditCardNumber")] public Int64? CreditCardNumber { get; set; } [JsonPropertyName("cvv")] public int? CVV { get; set; } [JsonPropertyName("creditCardExpirationDate")] public DateTime? CreditCardExpirationDate { get; set; } = DateTime.Now; [JsonPropertyName("password")] public string Password { get; set; } [JsonPropertyName("reEnteredPassword")] public string ReEnteredPassword { get; set; } [JsonPropertyName("balance")] public float Balance { get; set; } } } <file_sep>/readme.md Final Project **IMPORTANT: The API was 'home-brewed', so to make it work with the Xamarin Form project is mandatory to change the IP address of the base URI according to the one your router has assigned you,and to install an extension called 'Conveyor' by Keyoti https://marketplace.visualstudio.com/items?itemName=vs-publisher-1448185.ConveyorbyKeyoti.** # Screenshots ## Main page <img src="SS\main.png"> ## Flyout menu <img src="SS\flyout.png"> ## Sign Up page <img src="SS\sign_up.png"> ## Sign Up page full <img src="SS\sign_up_full.png"> ## Alert popup <img src="SS\alert.png"> <img src="SS\1.jfif"> <img src="SS\2.jfif"> <img src="SS\3.jfif"> <img src="SS\4.jfif"> <img src="SS\5.jfif"> <file_sep>/Cuanto Apotamo/Cuanto Apotamo/Constants.cs using System; using System.Collections.Generic; using System.Text; namespace Cuanto_Apotamo.Services { public static class Constants { public static class Navigation { public const string MainPage = "Main"; public const string NavigationPage = "Navigation"; public const string Root = "Root"; public const string SignUp = "SignUp"; public const string LogIn = "LogIn"; public const string Temp = "Temp"; } public static class Url { public const string Api = "http://192.168.68.139:45457/"; } } } <file_sep>/WebAPI/Domain/User.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebAPI.Domain { public class User { public int Id { get; set; } public string FullName { get; set; } public string Username { get; set; } public string IdentificationDocument { get; set; } public string Email { get; set; } public string CreditCardNumber { get; set; } public int? CVV { get; set; } public DateTime? CreditCardExpirationDate { get; set; } public string Password { get; set; } public float? Balance { get; set; } public DateTime RegistrationDate { get; set; } public ICollection<BalanceTransaction> BalanceTransactions { get; set; } public ICollection<UserBet> UserBets { get; set; } } } <file_sep>/WebAPI/Domain/UserBet.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebAPI.Domain { public class UserBet { public int Id { get; set; } public int UserId { get; set; } public User User { get; set; } public int BetOptionId { get; set; } public BetOption BetOption { get; set; } public float Amount { get; set; } public DateTime RegistrationDate { get; set; } } } <file_sep>/Cuanto Apotamo/Cuanto Apotamo/ViewModels/RootTabbedViewModel.cs using Cuanto_Apotamo.Models; using Prism.Navigation; using System; using System.Collections.Generic; using System.Text; namespace Cuanto_Apotamo.ViewModels { class RootTabbedViewModel : BaseViewModel, INavigatedAware { public User User { get; set; } public string Test { get; set; } public RootTabbedViewModel(INavigationService navigationService) : base(navigationService) { Test = "test"; } public void OnNavigatedTo(INavigationParameters parameters) { User = new User(parameters); Test = User.FullName; } public void OnNavigatedFrom(INavigationParameters parameters) { } } } <file_sep>/WebAPI/Data/DataContext.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; using Microsoft.Extensions.Configuration; using WebAPI.Data.Configuration; using WebAPI.Domain; namespace WebAPI.Data { public class DataContext : DbContext { public DataContext(DbContextOptions<DataContext> options) : base(options) { } public DbSet<Bet> Bets { get; set; } public DbSet<User> Users { get; set; } public DbSet<BalanceTransaction> BalanceTransactions { get; set; } public DbSet<BetOption> BetOptions { get; set; } public DbSet<UserBet> UserBets { get; set; } public IConfiguration Configuration { get; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.ApplyConfiguration(new BalanceTransactionEntityTypeConfiguration()); modelBuilder.ApplyConfiguration(new BetEntityTypeConfiguration()); modelBuilder.ApplyConfiguration(new UserBetEntityTypeConfiguration()); modelBuilder.ApplyConfiguration(new BetOptionEntityTypeConfiguration()); modelBuilder.ApplyConfiguration(new UserEntityTypeConfiguration()); } } } <file_sep>/WebAPI/Domain/BalanceTransaction.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebAPI.Domain { public class BalanceTransaction { public int Id { get; set; } public int UserID { get; set; } public User User { get; set; } public float Balance { get; set; } public DateTime RegistrationDate { get; set; } } } <file_sep>/WebAPI/Data/Configuration/UserBetEntityTypeConfiguration.cs using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WebAPI.Domain; namespace WebAPI.Data.Configuration { public class UserBetEntityTypeConfiguration : IEntityTypeConfiguration<UserBet> { public void Configure(EntityTypeBuilder<UserBet> builder) { builder.HasKey(f => f.Id); builder.HasOne(f => f.User) .WithMany(a => a.UserBets) .HasForeignKey(a => a.UserId); builder.HasOne(f => f.BetOption) .WithMany(a => a.UserBets) .HasForeignKey(a => a.BetOptionId); builder.Property(f => f.Amount) .IsRequired(); builder.Property(f => f.RegistrationDate) .HasDefaultValue(DateTime.Now); } } } <file_sep>/Cuanto Apotamo/Cuanto Apotamo/Models/NavigationParameterManager.cs using Prism.Navigation; using System; using System.Collections.Generic; using System.Reflection; using System.Text; namespace Cuanto_Apotamo.Models { class NavigationParameterManager { public NavigationParameterManager() { } public NavigationParameterManager(INavigationParameters navegationParameters) { this.ToObject(navegationParameters); } private void ToObject(INavigationParameters navegationParameters) { foreach(var pair in navegationParameters) { PropertyInfo prop = this.GetType().GetProperty(pair.Key); var type = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType; if(type == typeof(DateTime)) { prop.SetValue(this, DateTime.Parse(navegationParameters.GetValue<string>(pair.Key))); } else if(type == typeof(float)) { prop.SetValue(this, float.Parse(navegationParameters.GetValue<string>(pair.Key))); } else { prop.SetValue(this, pair.Value); } } } public INavigationParameters ToNavigationParameters() { var navParameters = new NavigationParameters(); foreach (PropertyInfo prop in this.GetType().GetProperties()) { navParameters.Add(prop.Name, prop.GetValue(this)); } return navParameters; } } } <file_sep>/Cuanto Apotamo/Cuanto Apotamo/Models/FlyoutOption.cs using System; using System.Collections.Generic; using System.Text; namespace Cuanto_Apotamo.Models { public class FlyoutOption { public string Title { get; set; } public bool IsStarted { get; set; } = false; public bool IsNotStarted { set { IsNotStarted = !IsStarted; } } public FlyoutOption(string title) { Title = title; } } } <file_sep>/Cuanto Apotamo/Cuanto Apotamo/App.xaml.cs using Prism; using Prism.Ioc; using Prism.Unity; using System; using Xamarin.Forms; using Xamarin.Forms.Xaml; using Cuanto_Apotamo.Views; using Cuanto_Apotamo.ViewModels; using Cuanto_Apotamo.Services; namespace Cuanto_Apotamo { public partial class App : PrismApplication { public App(IPlatformInitializer platformInitializer) : base(platformInitializer) { } protected override void OnInitialized() { InitializeComponent(); NavigationService.NavigateAsync($"{Constants.Navigation.NavigationPage}/{Constants.Navigation.LogIn}"); } protected override void RegisterTypes(IContainerRegistry containerRegistry) { containerRegistry.RegisterForNavigation<RootTabbedPage, RootTabbedViewModel>("tabbed"); containerRegistry.RegisterForNavigation<BalancePage, BalancePageViewModel>("balance"); containerRegistry.RegisterForNavigation<SearchPage>("search"); containerRegistry.RegisterForNavigation<NavigationPage>(Constants.Navigation.NavigationPage); containerRegistry.RegisterForNavigation<MainPage, MainViewModel>(Constants.Navigation.MainPage); containerRegistry.RegisterForNavigation<Root, RootViewModel>(Constants.Navigation.Root); // This one also need a ViewModel name change containerRegistry.RegisterForNavigation<SignUpPage, SignUpViewModel>(Constants.Navigation.SignUp); containerRegistry.RegisterForNavigation<LogInPage, LogInViewModel>(Constants.Navigation.LogIn); containerRegistry.RegisterForNavigation<TempPage, TempViewModel>(Constants.Navigation.Temp); containerRegistry.Register<ISignUpApiService, Dummy_services.SignUpApiService>(); containerRegistry.Register<ILogInApiService, Dummy_services.LogInApiService>(); } } } <file_sep>/Cuanto Apotamo/Cuanto Apotamo/ViewModels/BalancePageViewModel.cs using Cuanto_Apotamo.Models; using Prism.Navigation; using System; using System.Collections.Generic; using System.Text; namespace Cuanto_Apotamo.ViewModels { class BalancePageViewModel : BaseViewModel, INavigatedAware { public User User { get; set; } public BalancePageViewModel(INavigationService navigationService) : base(navigationService) { } public void OnNavigatedFrom(INavigationParameters parameters) { } public void OnNavigatedTo(INavigationParameters parameters) { User = new User(parameters); } } } <file_sep>/WebAPI/Data/Configuration/BetOptionEntityTypeConfiguration.cs using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WebAPI.Domain; namespace WebAPI.Data.Configuration { public class BetOptionEntityTypeConfiguration : IEntityTypeConfiguration<BetOption> { public void Configure(EntityTypeBuilder<BetOption> builder) { builder.HasKey(f => f.Id); builder.HasOne(f => f.Bet) .WithMany(a => a.BetOptions) .HasForeignKey(a => a.BetId); builder.Property(f => f.Title) .IsRequired(); builder.Property(f => f.TotalBets) .IsRequired(); builder.Property(f => f.Stake) .IsRequired(); builder.Property(f => f.TotalPlayers) .IsRequired(); builder.Property(f => f.DidWin) .IsRequired(); builder.Property(f => f.RegistrationDate) .HasDefaultValue(DateTime.Now); } } } <file_sep>/Cuanto Apotamo/Cuanto Apotamo/Services/ILogInApiService.cs using Cuanto_Apotamo.Models; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Cuanto_Apotamo.Services { interface ILogInApiService { Task<LogInApiResponse> Authenticate(Credentials userCredentials); } } <file_sep>/WebAPI/Data/Configuration/UserEntityTypeConfiguration.cs using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WebAPI.Domain; namespace WebAPI.Data.Configuration { public class UserEntityTypeConfiguration : IEntityTypeConfiguration<User> { public void Configure(EntityTypeBuilder<User> builder) { builder.HasKey(f => f.Id); builder.Property(f => f.FullName) .IsRequired(); builder.Property(f => f.Username) .IsRequired(); builder.Property(f => f.IdentificationDocument) .IsRequired(); builder.Property(f => f.Email) .IsRequired(); builder.Property(f => f.CreditCardNumber) .IsRequired(); builder.Property(f => f.CVV) .IsRequired(); builder.Property(f => f.CreditCardExpirationDate) .IsRequired(); builder.Property(f => f.Password) .IsRequired(); builder.Property(f => f.Balance) .IsRequired(); builder.HasMany(s => s.UserBets) .WithOne(sp => sp.User) .HasForeignKey(sp => sp.UserId); builder.HasMany(s => s.BalanceTransactions) .WithOne(sp => sp.User) .HasForeignKey(sp => sp.UserID); builder.Property(f => f.RegistrationDate) .HasDefaultValue(DateTime.Now); } } } <file_sep>/WebAPI/Domain/Bet.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebAPI.Domain { public enum BetStatus { Open =1, Close=2, Complete=3 } public class Bet { public int Id { get; set; } public string Title { get; set; } public string Description { get; set; } public float TotalBets { get; set; } public int TotalPlayers { get; set; } public BetStatus Status { get; set; } public DateTime RegistrationDate { get; set; } public ICollection<BetOption> BetOptions { get; set; } } } <file_sep>/Cuanto Apotamo/Cuanto Apotamo/Models/Bet.cs using System; using System.Collections.Generic; using System.Text; namespace Cuanto_Apotamo.Models { class Bet { public Bet(string title, float totalBet, string deal, string betClose, int totalPlayers) { Title = title; TotalBet = totalBet; Deal = deal; BetClose = betClose; TotalPlayers = totalPlayers; } public string Title { get; set; } public float TotalBet { get; set; } public string Deal { get; set; } public string BetClose { get; set; } public int TotalPlayers { get; set; } List<BetOption> Options { get; set; } } }
e24d587f4cb2f381dedfe4ee9964e8575a57f63f
[ "Markdown", "C#" ]
32
C#
waldoomaet/Cuanto_Apotamo
c310c34c5207d923bfbf7c765e31e68bfab451f8
322ea4ab424a73bfd403bf900339c1baa20f3177
refs/heads/master
<repo_name>rock3tz/Snapchat<file_sep>/Snapchat/SelectUserViewController.swift // // SelectUserViewController.swift // Snapchat // // Created by <NAME> on 04/02/2017. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit import FirebaseAuth import FirebaseDatabase import FirebaseStorage class SelectUserViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableview: UITableView! var users : [User] = [] var imageUrl = "" var descripionText = "" var uuid = "" override func viewDidLoad() { super.viewDidLoad() tableview.delegate = self tableview.dataSource = self FIRDatabase.database().reference().child("users").observe(FIRDataEventType.childAdded, with: { (snaphot) in print(snaphot.value ?? "") let user = User() user.email = snaphot.childSnapshot(forPath: "email").value as! String user.uid = snaphot.key self.users.append(user) self.tableview.reloadData() }) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return users.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.textLabel?.text = users[indexPath.row].email return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let user = users[indexPath.row] let snap = ["from" : FIRAuth.auth()?.currentUser?.email, "description" : descripionText, "imageURL" : imageUrl, "uuid" : uuid] FIRDatabase.database().reference().child("users").child(user.uid).child("snaps").childByAutoId() .setValue(snap) _ = navigationController?.popToRootViewController(animated: true) } } <file_sep>/Snapchat/User.swift // // User.swift // Snapchat // // Created by <NAME> on 04/02/2017. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit class User { var email = "" var uid = "" } <file_sep>/Snapchat/SnapsViewController.swift // // SnapsViewController.swift // Snapchat // // Created by <NAME> on 04/02/2017. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit import FirebaseDatabase import FirebaseAuth class SnapsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableview: UITableView! var snaps : [Snap] = [] override func viewDidLoad() { super.viewDidLoad() tableview.dataSource = self tableview.delegate = self // Do any additional setup after loading the view. FIRDatabase.database().reference().child("users").child((FIRAuth.auth()?.currentUser?.uid)!) .child("snaps").observe(FIRDataEventType.childAdded, with: { (snaphot) in print(snaphot.value ?? "") let snap = Snap() snap.from = snaphot.childSnapshot(forPath: "from").value as! String snap.description = snaphot.childSnapshot(forPath: "description").value as! String snap.imageUrl = snaphot.childSnapshot(forPath: "imageURL").value as! String snap.uuid = snaphot.childSnapshot(forPath: "uuid").value as! String snap.key = snaphot.key self.snaps.append(snap) self.tableview.reloadData() }) FIRDatabase.database().reference().child("users").child((FIRAuth.auth()?.currentUser?.uid)!) .child("snaps").observe(FIRDataEventType.childRemoved, with: { (snaphot) in print(snaphot.value ?? "") var index = 0; for snap in self.snaps { if snap.key == snaphot.key { self.snaps.remove(at: index) } index += 1 } self.tableview.reloadData() }) } @IBAction func logoutTapped(_ sender: Any) { navigationController?.dismiss(animated: true, completion: nil) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if snaps.count == 0 { return 1 } return snaps.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() if snaps.count == 0 { cell.textLabel?.text = "You have no snaps 😞" } else { cell.textLabel?.text = snaps[indexPath.row].from } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let snap = snaps[indexPath.row] performSegue(withIdentifier: "showSegue", sender: snap) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showSegue" { let nextVC = segue.destination as! ViewSnapViewController nextVC.snap = sender as! Snap } } } <file_sep>/Snapchat/ViewSnapViewController.swift // // ViewSnapViewController.swift // Snapchat // // Created by <NAME> on 04/02/2017. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit import SDWebImage import FirebaseAuth import FirebaseDatabase import FirebaseStorage class ViewSnapViewController: UIViewController { @IBOutlet weak var imageview: UIImageView! @IBOutlet weak var label: UILabel! var snap = Snap() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. label.text = snap.description imageview.sd_setImage(with: URL(string: snap.imageUrl)) } override func viewWillDisappear(_ animated: Bool) { FIRDatabase.database().reference().child("users").child((FIRAuth.auth()?.currentUser?.uid)!).child("snaps").child(snap.key).removeValue() FIRStorage.storage().reference().child("images").child("\(snap.uuid).jpg").delete(completion: { (error2) in print("We deleted the pic") }) } }
e01c3ff83765854ee30a8ade58348d5dadb3d60d
[ "Swift" ]
4
Swift
rock3tz/Snapchat
ec75dab2fe8b5675a6c1be00f936ae5e177acdd0
e0c4c76431503077549fe68133f5149327c01d4f
refs/heads/main
<file_sep>from django.contrib import admin from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.index,name="homePage"), path('contact-us/', views.contactus,name="contactus"), path('register/', views.register,name="registerPage"), path('login/', views.logins,name="loginPage"), path('logout/', views.logout_view,name="logout"), path('profile/', views.profile,name="profile"), path('update_profile/', views.updateProfile, name="update_profile"), path('blog/', views.blog,name="blog"), path('addblog/', views.addblog, name="addblog"), path('delete_blog/<int:id>', views.deleteblog, name="deleteblog"), path('update_blog/<int:id>', views.updateblog, name="updateblog"), path('search/',views.search,name="search"), path('photo_upload/',views.uploadImages,name="uploadimage"), path('gallery_upload/',views.uploadGallery,name="uploadGallery"), path('view_profile/<str:username>',views.view_profile,name="view_profile"), path('profile/gallery/',views.profile_gallery,name="profile_gallery"), path('settings/',views.profile_settings,name="profile_settings"), path('delete_user/',views.delete_user,name="delete_user"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) <file_sep># Generated by Django 3.2.3 on 2021-06-25 10:02 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('register', '0028_alter_blog_blog_user'), ] operations = [ migrations.AlterField( model_name='blog', name='blog_user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), ] <file_sep># Generated by Django 3.2.3 on 2021-05-22 04:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('register', '0005_alter_blog_blogtime'), ] operations = [ migrations.AlterField( model_name='blog', name='blogtime', field=models.DateField(auto_now=True), ), ] <file_sep># Generated by Django 3.2.3 on 2021-05-29 15:49 from django.conf import settings import django.contrib.auth.models from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('register', '0008_alter_blog_blog_author'), ] operations = [ migrations.AlterField( model_name='blog', name='blog_author', field=models.CharField(default=django.contrib.auth.models.User, max_length=60), ), migrations.CreateModel( name='UserProfile', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('userProfile', models.ImageField(upload_to='images')), ('bio', models.CharField(blank=True, max_length=150, null=True)), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ] <file_sep> from django.http import request from django.shortcuts import redirect def restrictPages(func_view): def wrapper(request,*args,**kwargs): if request.user.is_authenticated: return redirect('/') else: return func_view(request,*args,**kwargs) return wrapper <file_sep># Generated by Django 3.2.3 on 2021-06-04 08:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('register', '0021_alter_userprofile_userimage'), ] operations = [ migrations.AddField( model_name='userprofile', name='profileGallery', field=models.ImageField(blank=True, null=True, upload_to='images/profile'), ), migrations.AlterField( model_name='userprofile', name='userImage', field=models.ImageField(blank=True, default='default_profile.jpg', null=True, upload_to='images/'), ), ] <file_sep>from django.contrib.auth import decorators from django.shortcuts import render,redirect from django.contrib.auth.models import User from django.contrib import messages from django.contrib.auth import authenticate,login,logout from .models import Blog, UserProfile,ProfileGallery from django.contrib.auth.decorators import login_required from .decorators import restrictPages from .forms import * from django.contrib.auth.hashers import check_password from django.core.paginator import Paginator # Create your views here. def index(request): # blogs = Blog.objects.all().order_by('-blogtime') blogs = Blog.date_objects.all() user = User.objects.all() dict= { 'blog':blogs, 'users': user, } return render(request,'index.html', dict) def contactus(request): if request.method == 'POST': form = ContactForm() if form.is_valid(): form.save() # messages.info(request,"Thank You for Contacting Us.") return redirect('/') else: # messages.info(request,"Something Went Wrong. Please Try Again.") return redirect('/contact-us') else: form = ContactForm() return render(request,'contactus.html',{'form':form}) @login_required(login_url='/login') def search(request): query = request.GET['search_user'] filterUser = User.objects.filter(username__icontains=query) posting = {'filterUser':filterUser, 'query':query } return render(request,'search.html',posting) # ModelForm Register View @restrictPages def register(request): form = UserForm() if request.method == 'POST': form = UserForm(request.POST) print(form) if form.is_valid(): form.save() messages.info(request,'Registration Complete. Please Log in.') return redirect('/login') return render(request,'register.html',{'userForm':form}) @restrictPages def logins(request): if request.method == 'POST': usernames = request.POST['login_username'] passwords = request.POST['login_password'] user = authenticate(username=usernames.lower(), password=<PASSWORD>) print(user) if user is not None: login(request,user) messages.add_message(request, messages.SUCCESS, 'Successfully Log in.') return redirect('/') else: messages.add_message(request, messages.WARNING, 'Sorry, Invalid Credentials. Please Log in Again.') return redirect('/login') else: return render(request,'login.html') def logout_view(request): logout(request) messages.success(request,"Logout Successfully.") return redirect('/') @login_required(login_url='/login') def updateProfile(request): users = request.user form = UserUpdateForm(instance = request.user) profileform = ProfileForm(instance = request.user.userprofile) if request.method == 'POST': form = UserUpdateForm(request.POST, instance = request.user) profileform = ProfileForm(request.POST,instance=request.user.userprofile) if form.is_valid() and profileform.is_valid(): form.save() profileform.save() return redirect('/profile') dict={ 'user':users, 'form':form, 'profileForm':profileform } return render(request, 'updateProfile.html',dict) @login_required(login_url='/login') def blog(request): author_name = request.user.first_name + " " + request.user.last_name if request.method == 'POST': form = BlogForm(request.POST) form.instance.blog_user = request.user form.instance.blog_author = author_name if form.is_valid(): form.save() return redirect('/blog') form = BlogForm() user = request.user userblog = user.blog_set.all().order_by('-blogtime') dict= { 'blog':userblog, 'form':form } return render(request,'blog.html',dict) @login_required(login_url='/login') def addblog(request): author_name = request.user.first_name + " " + request.user.last_name if request.method == 'POST': form = BlogForm(request.POST) form.instance.blog_user = request.user form.instance.blog_author = author_name if form.is_valid(): form.save() return redirect('/blog') else: form = BlogForm() context = {'form':form} return render(request,'addblog.html',context) @login_required(login_url='/login') def deleteblog(request,id): try: user = request.user print("request.user",user) blogInfo = Blog.objects.get(id=id) userInformation = blogInfo.blog_user print("user",userInformation) if user == userInformation: blogInfo.delete() messages.info(request,"Blog has been deleted Successfully.") return redirect("/blog/") else: messages.info(request,"Sorry, Error Occured. You don't have access.") return redirect('/') except: messages.info(request," Sorry Error Occured.") return redirect("/blog/") @login_required(login_url='/login') def updateblog(request,id): try: user = request.user.id bloginfo = Blog.objects.get(id=id) userInformation = bloginfo.blog_user.id if user == userInformation: dict ={ 'blog':bloginfo } if request.method =='POST': posting = request.POST post = posting['blogpost'] title = posting['title'] bloginfo.blogpost = post bloginfo.blogtitle = title bloginfo.save() messages.info(request,"Your blog has been updated.") return redirect("/blog/") else: return render(request, "updateblog.html",dict) else: messages.info(request,"Sorry, You don't have access.") return redirect("/") except: return redirect("/") @login_required(login_url='/login') def profile(request): user = request.user blog = user.blog_set.all() content = { 'blog':blog } return render(request, 'profile.html', content) @login_required(login_url='/login') def uploadImages(request): user = request.user try: if request.method =="POST": imagefile = request.FILES['uploadImage'] user.userprofile.userImage = imagefile user.userprofile.save() messages.info(request,"Profile has been updated successfully.") return redirect('/profile') except: return redirect('/') @login_required(login_url='/login') def uploadGallery(request): user = request.user if request.method =="POST": imagefile = request.FILES['galleryImage'] c = user.profilegallery_set.create(userGallery=imagefile,userInfo=user) c.save() messages.info(request,"Image is added to Gallery.") return redirect('/profile/gallery') @login_required(login_url='/login') def delete_user(request): user = request.user # Checking password for deleting account if request.method == "POST": checkPassword = request.POST['check_password'] check_Password = user.check_password(checkPassword) if checkPassword == '': messages.info(request,"Please Enter Password to Continue.") return redirect('/settings') if check_Password == True: user.delete() messages.info(request," User has been deleted. Thank you for Joining Us.") return redirect('/') else: messages.info(request," Invalid Password.") return redirect('/settings') def view_profile(request,username): user = User.objects.get(username=username) imageGallery = user.profilegallery_set.all() return render(request,'view_profile.html',{'user':user,'gallery':imageGallery}) def profile_gallery(request): user = request.user gallery = user.profilegallery_set.all() profileGallery = user.userprofile.userImage content = { 'gallery':gallery, 'profile':profileGallery } return render(request,'profile_html/profile_gallery.html',content) def profile_settings(request): return render(request,'profile_html/profile_settings.html')<file_sep>from django.contrib.auth.models import User from django.db import models import datetime from django.db.models.fields.related import OneToOneField from django.db.models.signals import post_save # Create your models here. class BlogOrderManager(models.Manager): def get_queryset(self): return super().get_queryset().order_by('-blogtime') class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,blank=True) userImage = models.ImageField(upload_to="images/",null=True,blank=True,default="default_profile.jpg") bio = models.CharField(max_length=150, null=True,blank=True) def __str__(self): return self.user.username class ProfileGallery(models.Model): userInfo = models.ForeignKey(User, on_delete=models.CASCADE) userGallery = models.ImageField(upload_to="profile/",blank=True,null=True) def __str__(self): return self.userInfo.username class Blog(models.Model): blogtitle = models.CharField(max_length=60) blogpost = models.TextField() blogtime = models.DateTimeField(auto_now_add=True) blog_user = models.ForeignKey(User, on_delete=models.CASCADE) blog_author = models.CharField(max_length=60,default=User) objects = models.Manager() date_objects = BlogOrderManager() def __str__(self): return self.blogtitle + " " + self.blog_author class Contact(models.Model): first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) email = models.EmailField() subject = models.CharField(max_length=120) messages = models.TextField() def __str__(self): return self.first_name + " " + self.last_name def create_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) post_save.connect(create_profile, sender=User) def update_profile(sender, instance, created, **kwargs): if created == False: instance.userprofile.save() post_save.connect(create_profile, sender=User) <file_sep># Generated by Django 3.2.3 on 2021-06-07 15:29 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('register', '0026_rename_contactform_contact'), ] operations = [ migrations.AlterField( model_name='contact', name='first_name', field=models.CharField(max_length=40), ), migrations.AlterField( model_name='contact', name='last_name', field=models.CharField(max_length=40), ), migrations.AlterField( model_name='contact', name='subject', field=models.CharField(max_length=120), ), ] <file_sep># Generated by Django 3.2.3 on 2021-05-22 03:29 from django.db import migrations, models import django.db.models.manager class Migration(migrations.Migration): dependencies = [ ('register', '0002_blog_blogtitle'), ] operations = [ migrations.AlterModelManagers( name='blog', managers=[ ('filtertime', django.db.models.manager.Manager()), ], ), migrations.AlterField( model_name='blog', name='blogtime', field=models.DateField(auto_now=True), ), ] <file_sep>from django import forms from django.forms import widgets from .models import * from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class ContactForm(forms.ModelForm): class Meta: model = Contact fields = '__all__' widgets = { 'messages': forms.Textarea(attrs={'cols':60,'rows':5}), } # Registering User class UserForm(UserCreationForm): class Meta: model = User fields = ['username','first_name','last_name','email'] def clean_username(self): data = self.cleaned_data['username'] lower_case = data.lower() return lower_case # Updating User information class UserUpdateForm(forms.ModelForm): class Meta: model = User fields = ('username','first_name','last_name','email') def clean_username(self): data = self.cleaned_data['username'] lower_case = data.lower() return lower_case # Updating or Adding User Bio class ProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ['bio'] class BlogForm(forms.ModelForm): class Meta: model = Blog fields = ['blogtitle','blogpost'] <file_sep># Generated by Django 3.2.3 on 2021-05-31 04:57 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('register', '0017_alter_userprofile_userimage'), ] operations = [ migrations.AlterField( model_name='userprofile', name='userImage', field=models.ImageField(blank=True, default='media/default_profile.jpg', null=True, upload_to='images/'), ), ] <file_sep>from django.contrib import admin from .models import Blog, UserProfile,ProfileGallery,Contact # Register your models here. admin.site.register((Blog,UserProfile,ProfileGallery,Contact))<file_sep># Generated by Django 3.2.3 on 2021-05-29 13:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('register', '0007_alter_blog_blog_author'), ] operations = [ migrations.AlterField( model_name='blog', name='blog_author', field=models.CharField(max_length=60), ), ] <file_sep># Generated by Django 3.2.3 on 2021-05-30 04:53 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('register', '0010_alter_userprofile_userprofile'), ] operations = [ migrations.RemoveField( model_name='userprofile', name='userProfile', ), migrations.AddField( model_name='userprofile', name='userImage', field=models.ImageField(blank=True, null=True, upload_to='images/'), ), ] <file_sep># Generated by Django 3.2.3 on 2021-06-25 11:27 from django.db import migrations import django.db.models.manager class Migration(migrations.Migration): dependencies = [ ('register', '0029_alter_blog_blog_user'), ] operations = [ migrations.AlterModelManagers( name='blog', managers=[ ('date_objects', django.db.models.manager.Manager()), ], ), ] <file_sep># Generated by Django 3.2.3 on 2021-05-22 03:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('register', '0004_alter_blog_managers'), ] operations = [ migrations.AlterField( model_name='blog', name='blogtime', field=models.TimeField(auto_now=True), ), ] <file_sep># Generated by Django 3.2.3 on 2021-06-04 08:55 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('register', '0020_alter_userprofile_user'), ] operations = [ migrations.AlterField( model_name='userprofile', name='userImage', field=models.ImageField(blank=True, null=True, upload_to='images/profile'), ), ] <file_sep># Generated by Django 3.2.3 on 2021-05-30 05:30 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('register', '0011_auto_20210530_1038'), ] operations = [ migrations.AlterField( model_name='userprofile', name='bio', field=models.CharField(blank=True, default='', max_length=150, null=True), ), ] <file_sep># Generated by Django 3.2.3 on 2021-05-29 13:44 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('register', '0006_alter_blog_blogtime'), ] operations = [ migrations.AlterField( model_name='blog', name='blog_author', field=models.CharField(default=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), max_length=60), ), ]
fb9a13b74022041b40ad302248c94e80e542577a
[ "Python" ]
20
Python
shadowEyee/normal-social-site
e2a9f1247d4efef757680f429eb27c8f425542ac
77beef63d2210ef246c591ae8f1d3d285acb6807
refs/heads/master
<file_sep> const fs = require("fs"); const savedNote = require("../db/db.json"); module.exports = function(app){ function writeToDBase(notes){ notes = JSON.stringify(notes); console.log (notes); fs.writeFileSync("./db/db.json", notes, function(err){ if (err) { return console.log(err); } }); } app.get("/api/notes", function(req, res){ res.json(savedNote); }); app.post("/api/notes", function(req, res){ if (savedNote.length == 0){ req.body.id = "0"; } else{ req.body.id = JSON.stringify(JSON.parse(savedNote[savedNote.length - 1].id) + 1); } console.log("req.body.id: " + req.body.id); savedNote.push(req.body); console.log(savedNote); res.json(req.body); }); app.delete("/api/notes/:id", function(req, res){ let id = req.params.id.toString(); for (i=0; i < savedNote.length; i++){ if (savedNote[i].id == id){ console.log("Note Deleted!"); res.send(savedNote[i]); savedNote.splice(i,1); break; } } writeToDBase(savedNote); }); };<file_sep> # NOTE-TAKER ![License: MIT](https://img.shields.io/badge/License-MIT-brightgreen) ## Description: This aplication is a server side application using Express.js. With this application the client can write, save, and delete notes. the information is saved and retrieved from a JSON file. ## Table of Content: * [Installation](#installation) * [Usage](#usage) * [License](#license) ## Installation: npm install ## Usage: Live Demo: https://note-taker-14482.herokuapp.com/ ![](demo.gif)
68ad3d0cc154c57a89e096db0e91e1b5ccbb8dd9
[ "JavaScript", "Markdown" ]
2
JavaScript
cheryld433/Note-Taker
0df030ad1eb9c436f1cdbcad74627d58181c1290
63b1ddc5c0a2325c2385bf8e365a1b158abe9fd5
refs/heads/master
<repo_name>thinkful-ei-leopard/noteful-api-jose<file_sep>/src/notes/notes-service.js const NoteService = { getAllNotes(knexInstance) { return knexInstance .select('*') .from('notes') }, getById(knexInstance, id) { return knexInstance .from('notes') .select('*') .where('id', id) .first() }, insertNote(knexInstance, newNote) { return knexInstance .insert(newNote) .into('notes') .returning('*') .then( rows => { return rows[0] }) }, deleteNote(knexInstance, id) { return knexInstance('notes') .where({ id }) .delete() }, patchNote(knexInstance, id, newNoteFields) { return knexInstance('notes') .where({ id }) .update(newNoteFields) } } module.exports = NoteService<file_sep>/src/folders/folders-router.js const path = require('path') const express = require('express') const xss = require('xss') const FolderService = require('./folders-service') const folderRouter = express.Router() const jsonParser = express.json() folderRouter .route('/') .get((req, res, next) => { const knexInstance = req.app.get('knexInstance') FolderService.getAllFolders(knexInstance) .then(folders => { res.json(folders) }) .catch(next) }) .post(jsonParser, (req, res, next) => { const newFolder = { name: req.body.name } FolderService.insertFolder(req.app.get('knexInstance'), newFolder) .then(folder => { res.status(201).location(path.posix.join(req.originalUrl + `/${folder.id}`)).json(folder) }) .catch(next) }) folderRouter .route('/:id') .all((req, res, next) => { FolderService.getById(req.app.get('knexInstance'), req.params.id) .then(folder => { if(!folder) { return res.status(404).json({ error: { message: `folder doesn't exist`} }) } res.folder = folder next() }) .catch(next) }) .get((req, res, next) => { res.json({ id: res.folder.id, name: xss(res.folder.name), date_created: res.folder.date_created }) }) .delete((req, res, next) => { const knexInstance = req.app.get('knexInstance') FolderService.deleteFolder(knexInstance, req.params.id) .then(folder => { if(!folder) { return res.status(404).json({ error: { message: `folder doesn't exist` } }) } res.status(204).end() }) .catch(next) }) .patch(jsonParser, (req, res, next) => { const folderToUpdate = {name: req.body.name} FolderService.updateFolder( req.app.get('knexInstance'), req.params.id, folderToUpdate ) .then(numRowsAffected => { res.status(204).end() }) .catch(next) }) module.exports = folderRouter<file_sep>/seeds/seed.notes_table.sql INSERT INTO notes (name, content, folderId) VALUES ('test note 1', 'this is a test post', 1), ('test note 2', 'this is a test post 2', 2), ('test note 3', 'this is a test post 3', 2)<file_sep>/src/notes/notes-router.js const path = require('path') const express = require('express') const xss = require('xss') const NoteService = require('./notes-service') const noteRouter = express.Router() const jsonParser = express.json() const serializeNote = note => ({ id: note.id, name: xss(note.name), modified: note.modified, content: xss(note.content), date_created: note.date_created, folderid: note.folderid }) noteRouter .route('/') .get((req, res, next) => { const knexInstance = req.app.get('knexInstance') NoteService.getAllNotes(knexInstance) .then(notes => { res.json(notes.map(serializeNote)) }) .catch(next) }) .post(jsonParser, (req, res, next) => { const knexInstance = req.app.get('knexInstance') const newNote = { name: req.body.name, content: req.body.content, folderid: req.body.folderid } NoteService.insertNote(knexInstance, newNote) .then(note => { res.status(201).location(path.posix.join(req.originalUrl + `/${note.id}`)).json(serializeNote(note)) }) .catch(next) }) noteRouter .route('/:id') .all((req, res, next) => { NoteService.getById( req.app.get('knexInstance'), req.params.id ) .then(note => { if(!note) { return res.status(404).json({ error: { message: `note does not exist` } }) } res.note = note next() }) .catch(next) }) .get((req, res, next) => { res.json(serializeNote(res.note)) }) .delete((req, res, next) => { NoteService.deleteNote( req.app.get('knexInstance'), req.params.id ) .then(numRowsAffected => { res.status(204).end() }) .catch(next) }) .patch(jsonParser, (req, res, next) => { const noteToUpdate = { name: req.body.name, content: req.body.content} NoteService.patchNote( req.app.get('knexInstance'), req.params.id, noteToUpdate ) .then(numRowsAffected => { res.status(204).end() }) .catch(next) }) module.exports = noteRouter
51e07808897cea5dc135386d76c60d4cc1d6426e
[ "JavaScript", "SQL" ]
4
JavaScript
thinkful-ei-leopard/noteful-api-jose
1df0d89b061f680b2a04dc546fb46aae4bd424e7
85d6251ce56650da2d7c607ef2568f3cee3b9be8
refs/heads/master
<repo_name>DanilAbr/1001661-guess-melody-5<file_sep>/src/game.js const isArtistAnswerCorrect = (question, userAnswer) => { return userAnswer.artist === question.song.artist; }; const isGenreAnswerCorrect = (question, userAnswer) => { return userAnswer.every((item, index) => { return item === (question.answers[index].genre === question.genre); }); }; export { isArtistAnswerCorrect, isGenreAnswerCorrect, }; <file_sep>/src/components/private-route/selectors.js const getAuthorizationStatus = (state) => state.USER.authorizationStatus; export {getAuthorizationStatus};
3fcad9192d5a92e2bbcf80e710029708fcd372f0
[ "JavaScript" ]
2
JavaScript
DanilAbr/1001661-guess-melody-5
f4eda1f31fb1ee9fcd31ea7cbd801131054d14ad
21dec484d78c0590a74c70c06ba056584e84c7e0
refs/heads/master
<repo_name>curre001/ProgrammingAssignment2<file_sep>/cachematrix.R ## Write a short comment describing this function ## This function pretty much creates the storage container for the inverse matrix ## in the cacheSolve function it needs to look somewhere to see if its been computed. ## We do that here. makeCacheMatrix <- function(x = matrix()) { xinv <- NULL set <- function(y) { x <<- y xinv <<- NULL } get <- function() x setInv <- function(inv) xinv <<- inv getInv <- function() xinv list(set = set, get = get, setInv = setInv, getInv = getInv) } ## Write a short comment describing this function ## This functions uses some conditional logic to see if the inverse has ## been computed, and if so, fetches the value from the cache. If not, then it ## computes the inverse and returns it. cacheSolve <- function(x, ...) { m <- x$getInv() if(!is.null(m)) { message("getting cached data") return(m) } data <- x$get() m <- solve(data) x$setInv(m) m }
1d6326e4e7cfc12404394007a4e370808d260f7b
[ "R" ]
1
R
curre001/ProgrammingAssignment2
deee3662b6d42900ea01dba1524a2477e8de810c
a2fdeb970b933b964a76edd3e99301fca438d90c
refs/heads/master
<repo_name>WuDecki/Turing-machine-project<file_sep>/src/main/java/gui/components/TuringGrid.java package gui.components; import javafx.scene.layout.GridPane; import javafx.scene.text.FontWeight; import model.Operation; import model.State; import model.StateType; import model.TuringMachineProgram; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class TuringGrid extends GridPane { private static final int STATE_TYPE_FONT_SIZE = 22; private static final String HIGHLIGHT_STATE_CLASS = "highlight-state"; private static final String HIGHLIGHT_CHARACTER_CLASS = "highlight-character"; private static final String HIGHLIGHT_CELL_CLASS = "highlight-cell"; private TuringMachineProgram program; private TuringGridCell[][] cells; public TuringGrid() { super(); } public void initialize(final TuringMachineProgram program) { this.program = program; getChildren().clear(); setGridLinesVisible(true); initializeCells(program); for (int i = 0; i < program.getStates().size() + 1; i++) { addColumn(i, cells[i]); } getChildren().stream() .map(TuringGridCell.class::cast) .forEach(cell -> cell.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE)); } private void initializeCells(final TuringMachineProgram program) { List<State> states = program.getStates(); List<Character> symbols = program.getSymbols(); cells = new TuringGridCell[states.size() + 1][symbols.size() + 1]; // Corner empty cell cells[0][0] = new TuringGridCell(""); // Columns headers for (int i = 1; i < states.size() + 1; i++) { cells[i][0] = new TuringGridCell(states.get(i - 1).getIdn(), null, FontWeight.BOLD); } // Row headers for (int i = 1; i < symbols.size() + 1; i++) { cells[0][i] = new TuringGridCell(symbols.get(i - 1).toString(), null, FontWeight.BOLD); } // Cells State state; Operation operation; for (int i = 1; i < states.size() + 1; i++) { state = states.get(i - 1); for (int j = 1; j < symbols.size() + 1; j++) { operation = state.getOperation(symbols.get(j - 1)); if (state.getType().equals(StateType.NORMAL)) { cells[i][j] = new TuringGridCell(operation.toString(), operation); cells[i][j].initOperationEditor(program); } else { cells[i][j] = new TuringGridCell(state.getType().name().substring(0, 1), null, FontWeight.BOLD, STATE_TYPE_FONT_SIZE); } cells[i][j].setState(state); } } } synchronized public void addCellHighlight(TuringGridCell cell) { cell.getStyleClass().add(HIGHLIGHT_CELL_CLASS); } synchronized public void removeCellHighlight(TuringGridCell cell) { cell.getStyleClass().remove(HIGHLIGHT_CELL_CLASS); } synchronized public TuringGridCell getCell(State wantedState, Character character) { for (int i = 0; i < cells[0].length; i++) { if (cells[0][i].getText().equals(character.toString())) { for (TuringGridCell[] cell : cells) { State state = cell[i].getState(); if (state != null && state.equals(wantedState)) { return cell[i]; } } break; } } return null; } synchronized public void addStateHighlight(final List<TuringGridCell> cells) { addHighlight(cells, HIGHLIGHT_STATE_CLASS); } synchronized public void removeStateHighlight(final List<TuringGridCell> cells) { removeHighlight(cells, HIGHLIGHT_STATE_CLASS); } synchronized public void addCharacterHighlight(final List<TuringGridCell> cells) { addHighlight(cells, HIGHLIGHT_CHARACTER_CLASS); } synchronized public void removeCharacterHighlight(final List<TuringGridCell> cells) { removeHighlight(cells, HIGHLIGHT_CHARACTER_CLASS); } synchronized private void addHighlight(final List<TuringGridCell> cells, String styleClass) { cells.stream() .map(TuringGridCell::getStyleClass) .filter(strings -> !strings.contains(styleClass)) .forEach(styles -> styles.add(styleClass)); } synchronized private void removeHighlight(final List<TuringGridCell> cells, String styleClass) { cells.stream() .map(TuringGridCell::getStyleClass) .filter(strings -> strings.contains(styleClass)) .forEach(styles -> styles.remove(styleClass)); } synchronized public List<TuringGridCell> getStateColumn(final State state) { final ArrayList<TuringGridCell> stateColumn = new ArrayList<>(); TuringGridCell[][] cells = this.cells; for (int i = 1; i < cells.length; i++) { TuringGridCell[] column = cells[i]; if (column[0].getText().equals(state.getIdn())) { stateColumn.addAll(Arrays.asList(column)); break; } } return stateColumn; } synchronized public List<TuringGridCell> getCharacterRow(final Character character) { final ArrayList<TuringGridCell> row = new ArrayList<>(); TuringGridCell[][] cells = this.cells; for (int i = 0; i < cells[0].length; i++) { TuringGridCell cell = cells[0][i]; if (cell.getText().equals(character.toString())) { for (TuringGridCell[] turingGridCells : cells) { row.add(turingGridCells[i]); } break; } } return row; } synchronized public void clearHighlights() { for (TuringGridCell[] column : cells) { for (TuringGridCell cell : column) { cell.getStyleClass().removeAll(HIGHLIGHT_CELL_CLASS, HIGHLIGHT_CHARACTER_CLASS, HIGHLIGHT_STATE_CLASS); } } } } <file_sep>/src/main/java/gui/builders/TuringMachineProgramBuilder.java package gui.builders; import model.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class TuringMachineProgramBuilder { private static final char EMPTY_CHARACTER = '$'; private TuringMachineProgramBuilder() { } public static TuringMachineProgram getDefaultProgram() { final List<Character> symbols = new ArrayList<>(); symbols.add(EMPTY_CHARACTER); final State acceptable = new State("S1", StateType.ACCEPTABLE); final State rejectable = new State("S2", StateType.REJECTABLE); final List<State> states = new ArrayList<>(Arrays.asList( acceptable, rejectable )); return new TuringMachineProgram(symbols, EMPTY_CHARACTER, states, states.get(0), PommelStartPosition.BEGINNING); } public static void addSymbol(final TuringMachineProgram program, final Character symbol) { final State lastState = program.getStates().get(program.getStates().size() - 1); program.getSymbols().add(symbol); program.getStates().stream() .filter(state -> state.getType().equals(StateType.NORMAL)) .forEach(state -> state.getOperations().put(symbol, new Operation(EMPTY_CHARACTER, PommelMovement.NONE, lastState))); } public static void removeSymbol(final TuringMachineProgram program, final Character symbol) { program.getStates().stream() .filter(state -> state.getType().equals(StateType.NORMAL)) .forEach(state -> { state.getOperations().remove(symbol); state.getOperations().forEach((character, operation) -> { if (operation.getNewChar() == symbol) { operation.setNewChar(EMPTY_CHARACTER); } }); }); program.getSymbols().remove(symbol); } public static void addNewState(final TuringMachineProgram program) { final List<State> states = program.getStates(); final State lastState = states.get(states.size() - 1); final State newState = new State(String.format("S%d", states.size() - 2), StateType.NORMAL); program.getSymbols().forEach(character -> newState.addOperation(character, new Operation(EMPTY_CHARACTER, PommelMovement.NONE, lastState))); states.add(states.size() - 2, newState); for (int i = states.size() - 2; i < states.size(); i++) { states.get(i).setIdn("S" + (i)); } program.setFirstState(program.getStates().get(0)); } public static void removeState(final TuringMachineProgram program, final State toRemove) { final List<State> states = program.getStates(); final State lastState = states.get(states.size() - 1); states.remove(toRemove); states.forEach(state -> state.getOperations().forEach((character, operation) -> { if (operation.getNextState().equals(toRemove)) { operation.setNextState(lastState); } })); } public static Character[] convertToTapeCharacters(final String text) { final List<Character> characters = new ArrayList<>(); for (final char character : text.toCharArray()) { characters.add(character); } return characters.toArray(new Character[0]); } } <file_sep>/src/main/java/model/Operation.java package model; public class Operation { private Character newChar; private Character conditionalChar; private PommelMovement movement; private State nextState; public Operation(final Character newChar, final PommelMovement movement, final State nextState) { this.newChar = newChar; this.movement = movement; this.nextState = nextState; } public Character getNewChar() { return newChar; } public PommelMovement getMovement() { return movement; } public State getNextState() { return nextState; } public void setNewChar(final Character newChar) { this.newChar = newChar; } public void setMovement(final PommelMovement movement) { this.movement = movement; } public void setNextState(final State nextState) { this.nextState = nextState; } public Character getConditionalChar() { return conditionalChar; } public void setConditionalChar(Character conditionalChar) { this.conditionalChar = conditionalChar; } @Override public String toString() { return String.format("%s\n%c %c", getNextState().getIdn(), getNewChar(), getMovement().equals(PommelMovement.NONE) ? '-' : getMovement().name().charAt(0)); } } <file_sep>/src/main/java/model/TuringMachine.java package model; import model.controllers.TuringMachineController; public class TuringMachine { private TuringMachineController controller; private Pommel pommel; private Ribbon ribbon; private TuringMachineProgram program; private State actualState; public TuringMachine(TuringMachineController controller) { this.controller = controller; } public void loadProgram(TuringMachineProgram program) { this.program = program; this.actualState = null; } public TuringMachineResponse startProgram(Character[] tape) throws TuringMachineException, InterruptedException { checkTapeSymbols(tape); ribbon = new Ribbon(tape); configurePommel(); actualState = program.getFirstState(); return executeActualState(); } private void checkTapeSymbols(Character[] tape) throws TuringMachineException { TapeValidator tapeValidator = new TapeValidator(program, tape); if (!tapeValidator.isValid()) throw new TuringMachineException("A tape includes incorrect symbols for loaded program"); } private void configurePommel() throws TuringMachineException { Integer pommelStartPosition = calculatePommelStartPosition(); if (pommelStartPosition == -1) throw new TuringMachineException("A pommel has invalid position"); pommel = new Pommel(pommelStartPosition); } private Integer calculatePommelStartPosition() { PommelStartPosition startPosition = program.getStartPosition(); switch (startPosition) { case BEGINNING: { return 0; } case END: { return ribbon.getInputCharactersLength() -1; } } return -1; } private TuringMachineResponse executeActualState() throws TuringMachineException, InterruptedException { StateType actualStateType = getActualStateType(); if (actualStateType == StateType.ACCEPTABLE) { return TuringMachineResponse.ACCEPT; } else if (actualStateType == StateType.REJECTABLE) { return TuringMachineResponse.REJECT; } else { Character actualCharacter = pommel.readCharacter(ribbon); controller.onMakeDecision(actualState, actualCharacter); Operation operation = actualState.getOperation(actualCharacter); final State previousState = actualState; actualState = processOperation(operation); controller.onChangeState(previousState, actualCharacter, operation.getNextState()); return executeActualState(); } } private StateType getActualStateType() { return actualState.getType(); } private State processOperation(Operation operation) throws InterruptedException { pommel.writeCharacter(ribbon, operation.getNewChar()); pommel.move(operation.getMovement()); controller.onProcessOperation(operation); return operation.getNextState(); } public Character[] getRibbonTape() { return ribbon.getTape(); } } <file_sep>/src/main/java/gui/controllers/ToolsAndOptionsController.java package gui.controllers; import gui.StaticContext; import gui.builders.TuringMachineProgramBuilder; import javafx.collections.FXCollections; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.ChoiceBox; import javafx.scene.control.ComboBox; import javafx.scene.control.TextField; import javafx.scene.control.TextInputDialog; import javafx.scene.layout.HBox; import javafx.stage.FileChooser; import model.PommelStartPosition; import model.State; import model.TuringMachineProgram; import model.conversion.JsonFileManager; import model.conversion.JsonToProgramConverter; import model.conversion.ProgramToJsonConverter; import org.json.JSONObject; import java.io.File; import java.net.URL; import java.util.ResourceBundle; public class ToolsAndOptionsController extends AbstractController implements Initializable { public HBox toolsAndOptions; public ComboBox<State> removeStateInput; public TextField addSymbolInput; public ComboBox<Character> removeSymbolInput; public ChoiceBox<PommelStartPosition> pommelStartingPositionChoiceBox; private MainController mainController; @Override public void initialize(URL location, ResourceBundle resources) { pommelStartingPositionChoiceBox.setItems( FXCollections.observableArrayList(PommelStartPosition.BEGINNING, PommelStartPosition.END) ); pommelStartingPositionChoiceBox.setValue(PommelStartPosition.BEGINNING); pommelStartingPositionChoiceBox.setOnAction(event -> onPommelStartingPositionChange()); } private void onPommelStartingPositionChange() { final PommelStartPosition position = pommelStartingPositionChoiceBox.getValue(); mainController.pommel.setPosition( mainController.ribbon, position ); mainController.getProgram().setStartPosition(position); } @FXML public void addState() { final TuringMachineProgram program = mainController.getProgram(); TuringMachineProgramBuilder.addNewState(program); mainController.initializeTuringProgramGrid(program); } @FXML public void removeState() { final State toRemove = removeStateInput.getValue(); if (toRemove == null) { showError("State need to be chosen!"); return; } try { final TuringMachineProgram program = mainController.getProgram(); TuringMachineProgramBuilder.removeState(program, toRemove); mainController.initializeTuringProgramGrid(program); } catch (final Exception ignored) { showError("Sorry, state could not be removed!"); } } @FXML public void addSymbol() { final String input = addSymbolInput.getText(); if (input == null || input.length() != 1) { showError("Symbol need to be a single character!"); return; } if (!input.matches("[a-zA-Z]")) { showError("Symbol need to be an alphabetical english character!"); return; } final TuringMachineProgram program = mainController.getProgram(); if (program.getSymbols().contains(input.charAt(0))) { showError("Alphabet already contains that character!"); return; } TuringMachineProgramBuilder.addSymbol(program, input.charAt(0)); mainController.initializeTuringProgramGrid(program); addSymbolInput.clear(); } @FXML public void removeSymbol() { final Character symbol = removeSymbolInput.getValue(); if (symbol == null) { showError("Symbol need to be chosen!"); return; } try { final TuringMachineProgram program = mainController.getProgram(); TuringMachineProgramBuilder.removeSymbol(program, symbol); mainController.initializeTuringProgramGrid(program); } catch (final Exception ignored) { showError("Sorry, symbol could not be removed!"); } } @FXML public void clearProgram() { final TuringMachineProgram defaultProgram = TuringMachineProgramBuilder.getDefaultProgram(); mainController.initializeTuringProgramGrid(defaultProgram); mainController.restartProgram(); } @FXML public void initializeTape() { final TextInputDialog dialog = new TextInputDialog(); dialog.setTitle("Tape Input Dialog"); dialog.setHeaderText("Provide tape characters"); dialog.showAndWait() .ifPresent(characters -> { if (!characters.matches("[a-zA-Z$]*")) { showError("Symbol need to be an alphabetical english character! (Character \"$\" is acceptable)"); return; } if (characters.isEmpty()) { showError("Tape can't be empty!"); return; } final Character[] tapeCharacters = TuringMachineProgramBuilder.convertToTapeCharacters(characters); mainController.initializeRibbonAndPommel(tapeCharacters); }); } @FXML public void importTuringProgram() { final FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Open Turing Machine Program File"); final File file = fileChooser.showOpenDialog(StaticContext.STAGE); try { if (file != null) { final JSONObject jsonProgram = JsonFileManager.readJsonObject(file.getAbsolutePath()); final TuringMachineProgram program = new JsonToProgramConverter(jsonProgram).convert(); mainController.initializeTuringProgramGrid(program); showSuccess("Program successfully imported!"); } } catch (Exception e) { showError("Error during Turing machine program import!"); } } @FXML public void exportTuringProgram() { final FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Open Turing Machine Program File"); FileChooser.ExtensionFilter fileExtensions = new FileChooser.ExtensionFilter("JSON", "*.json"); fileChooser.getExtensionFilters().add(fileExtensions); final File file = fileChooser.showSaveDialog(StaticContext.STAGE); try { if (file != null) { JsonFileManager.writeJsonObject(file.getAbsolutePath(), new ProgramToJsonConverter(mainController.getProgram()).convert()); showSuccess("Program successfully saved!"); } } catch (Exception e) { showError("Error during Turing machine program export!"); } } public PommelStartPosition getPommelStartingPosition() { return pommelStartingPositionChoiceBox.getValue(); } public void setMainController(MainController mainController) { this.mainController = mainController; } } <file_sep>/src/main/java/model/controllers/TuringMachineController.java package model.controllers; import model.Operation; import model.State; public interface TuringMachineController { void onMakeDecision(State actualState, Character actualCharacter) throws InterruptedException; void onChangeState(State actualState, Character actualCharacter, State nextState) throws InterruptedException; void onProcessOperation(Operation operation) throws InterruptedException; } <file_sep>/src/main/java/model/Pommel.java package model; public class Pommel { private Integer actualPosition; public Pommel(Integer pommelPosition) { this.actualPosition = pommelPosition; } public Character readCharacter(Ribbon ribbon) throws TuringMachineException { return ribbon.getCharacterAtPosition(actualPosition); } public void writeCharacter(Ribbon ribbon, Character character) { ribbon.setCharacterAtPosition(character, actualPosition); } public void move(PommelMovement movement) { actualPosition += movement.getIndexChange(); } } <file_sep>/src/main/java/model/TuringMachineResponse.java package model; public enum TuringMachineResponse { ACCEPT, REJECT } <file_sep>/src/main/java/model/conversion/TuringMachineDefinition.java package model.conversion; import model.PommelStartPosition; import model.State; import java.util.List; class TuringMachineDefinition { private List<Character> symbols; private Character movementCharacter; private List<State> states; private State firstState; private PommelStartPosition pommelStartPosition; public List<Character> getSymbols() { return symbols; } public void setSymbols(List<Character> symbols) { this.symbols = symbols; } public Character getMovementCharacter() { return movementCharacter; } public void setMovementCharacter(Character movementCharacter) { this.movementCharacter = movementCharacter; } public List<State> getStates() { return states; } public void setStates(List<State> states) { this.states = states; } public State getFirstState() { return firstState; } public void setFirstState(State firstState) { this.firstState = firstState; } public PommelStartPosition getPommelStartPosition() { return pommelStartPosition; } public void setPommelStartPosition(PommelStartPosition pommelStartPosition) { this.pommelStartPosition = pommelStartPosition; } public State getStateByIdn(String idn) { for (State state: states) { if (state.getIdn().equals(idn)) return state; } return null; } } <file_sep>/src/main/java/gui/controllers/MainController.java package gui.controllers; import gui.StaticContext; import gui.animations.TuringAnimation; import gui.builders.TuringMachineProgramBuilder; import gui.components.Pommel; import gui.components.Ribbon; import gui.components.TuringGrid; import javafx.application.Platform; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.collections.FXCollections; import javafx.concurrent.Task; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.layout.HBox; import model.StateType; import model.TuringMachineProgram; import model.TuringMachineResponse; import java.net.URL; import java.util.ResourceBundle; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; public class MainController extends AbstractController { @FXML private ToolsAndOptionsController toolsAndOptionsController; @FXML public TuringGrid grid; @FXML public Button startProgramButton; @FXML public CheckBox stepByStepCheckBox; @FXML public HBox toolsAndOptions; @FXML public Button restartProgramButton; @FXML public Pommel pommel; @FXML public Ribbon ribbon; private TuringMachineProgram program; private Character[] tape; private BooleanProperty isProgramRunning = new SimpleBooleanProperty(false); private Thread turingAnimationThread; private Task<TuringMachineResponse> turingAnimationTask; private TuringAnimation turingAnimation; @Override public void initialize(final URL location, final ResourceBundle resources) { initToolsAndOptions(); initDefaults(); initializeDisablingOnProgramRun(); initializeRibbonAndPommel(TuringMachineProgramBuilder.convertToTapeCharacters("$$$$$")); StaticContext.STAGE.setOnCloseRequest(event -> { if (turingAnimationTask != null && turingAnimationThread.isAlive()) { turingAnimation.getController().setRestart(true); turingAnimationTask.cancel(true); } }); } private void initToolsAndOptions() { toolsAndOptionsController.setMainController(this); } private void initDefaults() { initializeTuringProgramGrid(TuringMachineProgramBuilder.getDefaultProgram()); } private void initializeDisablingOnProgramRun() { stepByStepCheckBox.disableProperty().bind(isProgramRunning); grid.disableProperty().bind(isProgramRunning); toolsAndOptions.disableProperty().bind(isProgramRunning); } public void initializeTuringProgramGrid(final TuringMachineProgram program) { this.program = program; toolsAndOptionsController.removeSymbolInput.setItems( FXCollections.observableList( program.getSymbols().stream() .filter(character -> character != '$') .collect(Collectors.toList()) ) ); if (program.getSymbols().size() > 1) { toolsAndOptionsController.removeSymbolInput.setValue(program.getSymbols().get(1)); } toolsAndOptionsController.removeStateInput.setItems( FXCollections.observableList( program.getStates().stream() .filter(state -> state.getType().equals(StateType.NORMAL)) .collect(Collectors.toList()) ) ); if (program.getStates().size() > 2) { toolsAndOptionsController.removeStateInput.setValue(program.getStates().get(0)); } grid.initialize(program); toolsAndOptionsController.pommelStartingPositionChoiceBox.setValue(program.getStartPosition()); } @FXML public void startProgram() { if (tape == null || tape.length == 0) { showError("Please initialize tape!"); return; } if (program.getStates().size() < 3) { showError("Turing machine program needs more than 3 states to be executed!"); return; } if (program.getSymbols().size() < 2) { showError("Turing machine program needs more than 2 symbols to be executed!"); return; } grid.clearHighlights(); long sleep = 1000; boolean isStepByStep = false; if (stepByStepCheckBox.isSelected()) { startProgramButton.setText("Next step"); startProgramButton.setOnAction(event -> { startProgramButton.setDisable(true); this.startProgramNextStep(); CompletableFuture.runAsync(() -> { try { TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException ignored) { } finally { startProgramButton.setDisable(false); } }); }); sleep = 360000; isStepByStep = true; } else { startProgramButton.setDisable(true); } isProgramRunning.setValue(true); pommel.setPosition(ribbon, program.getStartPosition()); turingAnimation = TuringAnimation.getInstance(program, tape, grid, pommel, ribbon, sleep, isStepByStep); turingAnimationTask = turingAnimation.getTuringAnimationTask(); turingAnimationTask.setOnSucceeded(event -> { showSuccess(String.format("The results of the program ended with an %s state!", turingAnimationTask.getValue())); enableButtons(); }); turingAnimationTask.setOnFailed(event -> { if (!(turingAnimationTask.getException() instanceof InterruptedException)) { showError(turingAnimationTask.getException().getMessage()); } enableButtons(); restartProgram(); }); turingAnimationThread = new Thread(turingAnimationTask); turingAnimationThread.start(); } private void enableButtons() { Platform.runLater(() -> { startProgramButton.setText("Start program"); startProgramButton.setOnAction(event -> this.startProgram()); startProgramButton.setDisable(false); restartProgramButton.setDisable(false); isProgramRunning.setValue(false); }); } public void initializeRibbonAndPommel(Character[] tape) { this.tape = tape; ribbon.init(tape); pommel.setPosition(ribbon, program.getStartPosition()); } private void startProgramNextStep() { turingAnimationThread.interrupt(); } @FXML public void restartProgram() { restartProgramButton.setDisable(true); CompletableFuture.runAsync(() -> { if (turingAnimationTask != null && turingAnimationThread.isAlive()) { turingAnimation.getController().setRestart(true); turingAnimationTask.cancel(true); } grid.clearHighlights(); pommel.setPosition(ribbon, program.getStartPosition()); }).thenRun(this::enableButtons); } public TuringMachineProgram getProgram() { return program; } } <file_sep>/src/main/java/model/conversion/JsonFileManager.java package model.conversion; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class JsonFileManager { public static JSONObject readJsonObject(String filePath) throws IOException, JSONException { String json = new String(Files.readAllBytes(Paths.get(filePath))); return new JSONObject(json); } public static void writeJsonObject(String filePath, JSONObject jsonObject) throws IOException { Files.write(Paths.get(filePath), jsonObject.toString().getBytes()); } } <file_sep>/src/main/java/gui/components/TuringGridCell.java package gui.components; import javafx.geometry.Insets; import javafx.scene.control.Label; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import javafx.scene.text.TextAlignment; import model.Operation; import model.State; import model.TuringMachineProgram; import org.controlsfx.control.PopOver; public class TuringGridCell extends Label { private static final String STYLE_CLASS_TURING_GRID_CELL_EDITOR_ENABLED = "turing-grid-cell-editor-enabled"; private static final Insets DEFAULT_CELL_PADDING = new Insets(0, 0, 0, 0); private final Operation operation; private State state; public TuringGridCell(final String text, final Operation operation, final FontWeight fontWeight, final double fontSize, final Insets padding) { super(text); setFont(Font.font(Font.getDefault().getFamily(), fontWeight, fontSize)); setTextAlignment(TextAlignment.CENTER); setPadding(padding); this.operation = operation; state = null; } public TuringGridCell(final String text, final Operation operation, final FontWeight fontWeight, final double fontSize) { this(text, operation, fontWeight, fontSize, DEFAULT_CELL_PADDING); } public TuringGridCell(final String text, final Operation operation, final FontWeight fontWeight) { this(text, operation, fontWeight, 16, DEFAULT_CELL_PADDING); } public TuringGridCell(final String text, final Operation operation) { this(text, operation, FontWeight.NORMAL, 16, DEFAULT_CELL_PADDING); } public TuringGridCell(final String text) { this(text, null, FontWeight.NORMAL, 16, DEFAULT_CELL_PADDING); } public void initOperationEditor(final TuringMachineProgram program) { final PopOver popOver = new PopOver(); final TuringGridCellEditor editor = new TuringGridCellEditor(program, operation); editor.saveButton.setOnAction(event -> popOver.hide()); popOver.setContentNode(editor); popOver.setHeaderAlwaysVisible(true); popOver.setTitle("Edit"); popOver.setOnHiding(event -> { operation.setNewChar(editor.characterComboBox.getValue()); operation.setMovement(editor.pommelMovementComboBox.getValue()); operation.setNextState(editor.nextStateComboBox.getValue()); setText(operation.toString()); toggleEditorEnabled(); }); setOnMouseClicked(event -> { popOver.show(this); toggleEditorEnabled(); }); } private void toggleEditorEnabled() { if (getStyleClass().contains(STYLE_CLASS_TURING_GRID_CELL_EDITOR_ENABLED)) { getStyleClass().remove(STYLE_CLASS_TURING_GRID_CELL_EDITOR_ENABLED); } else { getStyleClass().add(STYLE_CLASS_TURING_GRID_CELL_EDITOR_ENABLED); } } public Operation getOperation() { return operation; } public State getState() { return state; } public void setState(final State state) { this.state = state; } } <file_sep>/src/main/java/model/conversion/JsonToProgramConverter.java package model.conversion; import model.*; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class JsonToProgramConverter { private JSONObject jsonObject; private TuringMachineDefinition definition; public JsonToProgramConverter(JSONObject jsonObject) { this.jsonObject = jsonObject; } public TuringMachineProgram convert() throws JSONException, InvalidConversionException { definition = new TuringMachineDefinition(); convertSymbols(); convertStates(); convertFirstState(); convertMovementSymbol(); convertPommelStartPosition(); return prepareTuringMachineProgram(); } private void convertSymbols() throws JSONException { List<String> rawSymbols = extractList(jsonObject.getJSONArray("symbols")); List<Character> symbols = new ArrayList<>(); for(String rawSymbol: rawSymbols) { symbols.add(rawSymbol.toCharArray()[0]); } definition.setSymbols(symbols); } private void convertStates() throws JSONException, InvalidConversionException { List<String> statesIdn = extractList(jsonObject.getJSONArray("states")); JSONObject program = jsonObject.getJSONObject("program"); definition.setStates(createStates(statesIdn, program)); for(String stateIdn: statesIdn) { Object rawState = program.get(stateIdn); State state = definition.getStateByIdn(stateIdn); prepareOperations(state, rawState); } } private List<State> createStates(List<String> statesIdn, JSONObject program) throws JSONException { List<State> states = new ArrayList<>(); for(String stateIdn: statesIdn) { Object rawState = program.get(stateIdn); StateType stateType = chooseStateType(rawState); states.add(new State(stateIdn, stateType)); } return states; } private void prepareOperations(State state, Object rawState) throws JSONException, InvalidConversionException { if (!state.getType().equals(StateType.NORMAL)) return; for (Character symbol: definition.getSymbols()) { JSONArray array = ((JSONObject)rawState).getJSONArray(symbol.toString()); Character newCharacter = array.getString(0).charAt(0); PommelMovement movement = getPommelMovement(array.getString(1)); String nextStateIdn = array.getString(2); State nextState = definition.getStateByIdn(nextStateIdn); Operation operation = new Operation(newCharacter, movement, nextState); state.addOperation(symbol, operation); } } private PommelMovement getPommelMovement(String movementSymbol) throws InvalidConversionException { switch (movementSymbol) { case "P": { return PommelMovement.RIGHT; } case "L": { return PommelMovement.LEFT; } case "-": { return PommelMovement.NONE; } default: throw new InvalidConversionException("Invalid pommel movement symbol"); } } private StateType chooseStateType(Object rawState) { if (rawState instanceof String) { String stateType = (String)rawState; if (stateType.equals("SA")) { return StateType.ACCEPTABLE; } else { return StateType.REJECTABLE; } } else{ return StateType.NORMAL; } } private static List<String> extractList(JSONArray jsonArray) throws JSONException { List<String> list = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { list.add(jsonArray.getString(i)); } return list; } private void convertFirstState() throws JSONException { String firstStateIdn = jsonObject.getString("firstState"); State firstState = definition.getStateByIdn(firstStateIdn); definition.setFirstState(firstState); } private void convertMovementSymbol() throws JSONException { String movementSymbol = jsonObject.getString("movementSymbol"); definition.setMovementCharacter(movementSymbol.charAt(0)); } private void convertPommelStartPosition() throws JSONException, InvalidConversionException { String pommelStartPosition = jsonObject.getString("pommelStartPosition"); definition.setPommelStartPosition(choosePommelStartPosition(pommelStartPosition)); } private PommelStartPosition choosePommelStartPosition(String pommelStartPosition) throws InvalidConversionException { switch (pommelStartPosition) { case "P": return PommelStartPosition.BEGINNING; case "K": return PommelStartPosition.END; default: throw new InvalidConversionException("Invalid pommel start position symbol"); } } private TuringMachineProgram prepareTuringMachineProgram() { return new TuringMachineProgram(definition.getSymbols(), definition.getMovementCharacter(), definition.getStates(), definition.getFirstState(), definition.getPommelStartPosition()); } } <file_sep>/src/main/java/model/TapeValidator.java package model; import java.util.List; public class TapeValidator { TuringMachineProgram program; Character[] tape; public TapeValidator(TuringMachineProgram program, Character[] tape) { this.program = program; this.tape = tape; } public boolean isValid() { return symbolsAreCorrect(); } private boolean symbolsAreCorrect() { List<Character> symbols = program.getSymbols(); for (Character character: tape) { if (!symbolIsCorrect(symbols, character)) { return false; } } return true; } private boolean symbolIsCorrect(List<Character> symbols, Character character) { for (Character symbol: symbols) { if (symbol.equals(character)) { return true; } } return false; } } <file_sep>/src/main/java/model/StateType.java package model; public enum StateType { NORMAL, ACCEPTABLE, REJECTABLE } <file_sep>/src/main/java/gui/components/TuringGridCellEditor.java package gui.components; import gui.configuration.Config; import javafx.collections.FXCollections; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.layout.VBox; import model.Operation; import model.PommelMovement; import model.State; import model.TuringMachineProgram; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; public class TuringGridCellEditor extends VBox implements Initializable { private final TuringMachineProgram program; private final Operation operation; @FXML public ComboBox<Character> characterComboBox; @FXML public ComboBox<PommelMovement> pommelMovementComboBox; @FXML public ComboBox<State> nextStateComboBox; @FXML public Button saveButton; public TuringGridCellEditor(final TuringMachineProgram program, final Operation operation) { this.program = program; this.operation = operation; final FXMLLoader fxmlLoader = new FXMLLoader(TuringGridCellEditor.class.getResource(Config.Nodes.TURING_GRID_CELL_EDITOR)); fxmlLoader.setRoot(this); fxmlLoader.setController(this); try { fxmlLoader.load(); } catch (final IOException e) { e.printStackTrace(); } } @Override public void initialize(final URL location, final ResourceBundle resources) { characterComboBox.setItems(FXCollections.observableList(program.getSymbols())); pommelMovementComboBox.setItems(FXCollections.observableArrayList(PommelMovement.values())); nextStateComboBox.setItems(FXCollections.observableList(program.getStates())); characterComboBox.setValue(operation.getNewChar()); pommelMovementComboBox.setValue(operation.getMovement()); nextStateComboBox.setValue(operation.getNextState()); } } <file_sep>/src/main/java/model/TuringMachineProgram.java package model; import java.util.List; public class TuringMachineProgram { private final List<Character> symbols; private final Character movementCharacter; private List<State> states; private State firstState; private PommelStartPosition startPosition; public TuringMachineProgram(final List<Character> symbols, final Character movementCharacter, final List<State> states, final State firstState, final PommelStartPosition startPosition) { this.symbols = symbols; this.movementCharacter = movementCharacter; this.states = states; this.firstState = firstState; this.startPosition = startPosition; } public List<Character> getSymbols() { return symbols; } public Character getMovementCharacter() { return movementCharacter; } public List<State> getStates() { return states; } public void setStates(final List<State> states) { this.states = states; } public State getFirstState() { return firstState; } public void setFirstState(State firstState) { this.firstState = firstState; } public PommelStartPosition getStartPosition() { return startPosition; } public void setStartPosition(PommelStartPosition startPosition) { this.startPosition = startPosition; } } <file_sep>/settings.gradle rootProject.name = 'turing-machine' <file_sep>/src/main/java/model/PommelMovement.java package model; public enum PommelMovement { LEFT(-1), RIGHT(1), NONE(0); Integer indexChange; PommelMovement(Integer indexChange) { this.indexChange = indexChange; } public Integer getIndexChange() { return indexChange; } }
f90c3fd4f4d576c1d661cc58b12fc80d393de52b
[ "Java", "Gradle" ]
19
Java
WuDecki/Turing-machine-project
4b4a92d192ddeec265355f45525c8f222f80079e
45dc95d5b53c8789532b64f03f923edafc0c59ae
refs/heads/master
<repo_name>NPU-CPE/scoreboard<file_sep>/app.js /* global require console process Promise module */ 'use strict'; var $ = require("jquery"); const express = require('express'), app = express(); function getRandomInt(max) { return Math.floor(Math.random() * Math.floor(max)); } var fs = require('fs'); var usersJSON = JSON.parse(fs.readFileSync('name.json', 'utf8')); var current_data = { data: [] }; function getTail() { let c = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' ]; return `N${getRandomInt(9999)}${c[getRandomInt(c.length - 1)]}`; } function getFlight() { return getRandomInt(2000); } function getHeading() { return getRandomInt(359) .toString() .padStart(3, '0'); } function getGate() { const t = ['A', 'B', 'C'][getRandomInt(2)]; const g = getRandomInt(30); return `${t}${g}${g}`; } function getContestant(userID){ const users= [ 'b613110310018', 'b613110310042', 'b613110310083', 'b623110310017', 'b623110310025', 'b623110310033', 'b623110310041', 'b623110310058', 'b623110310066', 'b623110310074', 'b623110310082', 'b623110310090', 'b623110310108', 'b623110310124', 'b623110310132', 'b623110310140', 'b623110310157', 'b623110310165', 'b623110310173', 'b623110310181', 'b623110310199', 'b623110310215', 'b623110310223', 'b624110310023', 'b624110310031', 'b624110310049', 'b603110310019', 'b603110310027', 'b603110310035', 'b603110310043', 'b603110310050', 'b603110310076', 'b603110310084', 'b603110310092', 'b603110310100', 'b603110310118', 'b603110310126', 'b603110310134', 'b603110310142', 'b603110310159', 'b603110310167', 'b603110310175', 'b593030710011', 'b593030710028', 'b593030710036', 'b593030710044', 'b593030710051', 'b593030710085', 'b593030710127', 'sk', 'songrit' ]; //var userID=users[getRandomInt(users.length)]; for(var i = 0; i < users.length; i++) { if(usersJSON[i].ID == userID) { return [[usersJSON[i].FirstName+"."+usersJSON[i].SurName.charAt(0)], [usersJSON[i].Years], YearNum([usersJSON[i].Years]), ]; } } // console.log(i +":"+usersJSON[i].ID+":"+userID); return "No match"; } function YearNum(year){ if (year==2562) return("Y1"); if (year==2561) return("Y2"); if (year==2560) return("Y3"); if (year==2559) return("Y4"); else return("YX"); } function YearName(year){ switch(year){ case 2562: return("Freshie");break; case 2561: return("Sophomore");break; case 2560: return("Senior");break; case 2559: return("Super Senior");break; default: return("Super Senior"); } return(-1); } function getWPM() { let sec = getRandomInt(59) .toString() .padStart(2, '0'); let mins = getRandomInt(59) .toString() .padStart(2, '0'); return `${mins}${sec}`; } function myFunction(x) { alert("Row index is: " + x.rowIndex); } function getTime() { let hrs = getRandomInt(23) .toString() .padStart(2, '0'); let mins = getRandomInt(59) .toString() .padStart(2, '0'); return `${hrs}${mins}`; } // ======================================================================== // API app.use('/api/arrivals', (req, res) => { let r = { data: [] }; var dataJSON = JSON.parse(fs.readFileSync('data.json', 'utf8')); for (let i = 0; i < dataJSON.length; i++) { // Create the data for a row. var contest=getContestant(dataJSON[i].users); let data = { ranking: dataJSON.length-i, exam: dataJSON[i].exam.charAt(7)+dataJSON[i].exam.charAt(8)+dataJSON[i].exam.charAt(9), name: contest[0], grade: contest[2], wpm: dataJSON[i].adj_wpm }; // Let's add an occasional delayed exam. data.status = getRandomInt(10) > 7 ? 'B' : 'A'; if (data.status === 'B') { data.remarks = `Delayed ${getRandomInt(50)}M`; } // Add the row the the response. console.log(data); r.data.push(data); } current_data=r.data; res.json(r); }); // ======================================================================== // STATIC FILES app.use('/', express.static('public')); // ======================================================================== // WEB SERVER const port = process.env.PORT || 8080; app.listen(port); console.log('split flap started on port ' + port);
e06134e2cacc9977b55aca3622b1fa1a1801d1a3
[ "JavaScript" ]
1
JavaScript
NPU-CPE/scoreboard
be997b1869c993331ae1f0b7a75ba435f6ae7fe3
95712edc27bd8329ad34e50a7a1573beafd42ee9
refs/heads/master
<repo_name>Suor/dvc-test<file_sep>/docker/fedora/26/Dockerfile FROM fedora:26 RUN dnf update -y && \ dnf install -y python-pip wget libffi-devel python-devel gcc git && \ pip install --upgrade pip <file_sep>/requirements.txt nose wget requests distro gitpython <file_sep>/docker/ubuntu/18.04/Dockerfile FROM ubuntu:18.04 RUN apt-get update && \ apt-get install -y python-pip wget libffi-dev git && \ pip install --upgrade pip <file_sep>/tests/main.py import os import platform from subprocess import check_call try: from pip import main as pipmain except: from pip._internal import main as pipmain URL = 'https://updater.dvc.org' TIMEOUT = 10 RETRIES = 3 def latest_version(platform, pkg): import requests r = requests.get(URL, timeout=TIMEOUT) j = r.json() return j['packages'][platform][pkg] def install_latest_version(platform, cmd, pkg): import wget import posixpath latest = latest_version(platform, pkg) fname = posixpath.basename(latest) if not os.path.exists(fname): wget.download(latest, out=fname) ret = os.system("{} {}".format(cmd, fname)) assert ret == 0 def install_pip(): retries = RETRIES while retries > 0: ret = pipmain(['install', 'dvc']) if ret == 0: break retries -= 1 assert ret == 0 def install_deb(): import distro assert platform.system() == "Linux" dist = distro.linux_distribution(full_distribution_name=False)[0] assert dist == "ubuntu" install_latest_version('linux', 'dpkg -i', 'deb') def install_rpm(): import distro assert platform.system() == "Linux" dist = distro.linux_distribution(full_distribution_name=False)[0] assert dist == "fedora" install_latest_version('linux', 'rpm -ivh', 'rpm') def install_pkg(): assert platform.system() == "Darwin" install_latest_version('osx', 'sudo installer -target / -pkg', 'pkg') def install_formula(): assert platform.system() == "Darwin" ret = os.system("brew install iterative/homebrew-dvc/dvc") assert ret == 0 def install_cask(): assert platform.system() == "Darwin" ret = os.system("brew cask install iterative/homebrew-dvc/dvc") assert ret == 0 def install_exe(): assert platform.system() == "Windows" raise NotImplementedError def install(): pkg = os.getenv("DVC_TEST_PKG", None) if pkg is None: raise Exception("Use DVC_TEST_PKG to specify test package") elif pkg == "pip": install_pip() elif pkg == "deb": install_deb() elif pkg == "rpm": install_rpm() elif pkg == "pkg": install_pkg() elif pkg == "formula": install_formula() elif pkg == "cask": install_cask() elif pkg == "exe": install_exe() else: raise Exception("Unsupported pkg {}".format(pkg)) def main(argv=None): ret = os.system("pip install -r requirements.txt") assert ret == 0 system = os.getenv("DVC_TEST_SYSTEM", None) if system is None: raise Exception("Use DVC_TEST_SYSTEM to specify test system") elif system in ["linux", "osx", "windows"]: install() else: raise Exception("Unsupported test system {}".format(system)) check_call("nosetests -v --processes=-1 --process-timeout=200", shell=True)
b1aac1b1e90f7e1ba9bafe06fb523009ab6471db
[ "Python", "Text", "Dockerfile" ]
4
Dockerfile
Suor/dvc-test
db79d7c79b42fee3ee6fdd3697db5a4160e505a7
e21acd9a0be0aa82920e0369380a894ff8d53506
refs/heads/master
<repo_name>kevinyxlu/cs32lab03<file_sep>/parse.cpp #include <algorithm> #include <memory> /* helper routines to read out csv data */ #include "parse.h" /* 1 "County", 2 "State", 3 "Age.Percent 65 and Older", 4 "Age.Percent Under 18 Years", 5 "Age.Percent Under 5 Years", 6 "Education.Bachelor's Degree or Higher", "Education.High School or Higher", "Employment.Nonemployer Establishments", "Employment.Private Non-farm Employment", 10 "Employment.Private Non-farm Employment Percent Change", "Employment.Private Non-farm Establishments", "Ethnicities.American Indian and Alaska Native Alone", "Ethnicities.Asian Alone","Ethnicities.Black Alone", "Ethnicities.Hispanic or Latino", 15 "Ethnicities.Native Hawaiian and Other Pacific Islander Alone", "Ethnicities.Two or More Races", "Ethnicities.White Alone", "Ethnicities.White Alone, not Hispanic or Latino", "Housing.Homeownership Rate", 20 "Housing.Households", "Housing.Housing Units", "Housing.Median Value of Owner-Occupied Units", "Housing.Persons per Household", "Housing.Units in Multi-Unit Structures", 25 "Income.Median Houseold Income", "Income.Per Capita Income", 27 "Income.Persons Below Poverty Level", "Miscellaneous.Building Permits", "Miscellaneous.Foreign Born", 30 "Miscellaneous.Land Area", "Miscellaneous.Language Other than English at Home", "Miscellaneous.Living in Same House +1 Years", "Miscellaneous.Manufacturers Shipments", "Miscellaneous.Mean Travel Time to Work", 35 "Miscellaneous.Percent Female", 36 "Miscellaneous.Veterans", 37 "Population.2010 Population", 38 "Population.2014 Population", 39 "Population.Population Percent Change", 40 "Population.Population per Square Mile", "Sales.Accommodation and Food Services Sales", "Sales.Merchant Wholesaler Sales", "Sales.Retail Sales", "Sales.Retail Sales per Capita", 45 "Employment.Firms.American Indian-Owned", "Employment.Firms.Asian-Owned", "Employment.Firms.Black-Owned", "Employment.Firms.Hispanic-Owned", "Employment.Firms.Native Hawaiian and Other Pacific Islander-Owned", 50 "Employment.Firms.Total", "Employment.Firms.Women-Owned" */ /* helper to strip out quotes from a string */ string stripQuotes(std::string temp) { temp.erase( remove(temp.begin(), temp.end(), '\"' ), temp.end()); return temp; } /* helper: get field from string stream */ /* assume field has quotes for CORGIS */ string getField(std::stringstream &ss) { string data, junk; //ignore the first quotes std::getline(ss, junk, '\"'); //read the data (not to comma as some data includes comma (Hospital names)) std::getline(ss, data, '\"'); //read to comma final comma (to consume and prep for next) std::getline(ss, junk, ','); //data includes final quote (see note line 18) return stripQuotes(data); } /* helper: read out column names for CSV file */ void consumeColumnNames(std::ifstream &myFile) { std::string line; std::string colname; // Extract the first line in the file std::getline(myFile, line); // Create a stringstream from line std::stringstream ss(line); // Read the column names (for debugging) // Extract each column name for debugging while(std::getline(ss, colname, ',')) { //std::cout << colname << std::endl; } } /* Read one line from a CSV file for county demographic data specifically TODO: for lab01 you will be asked to add fields here - think about type */ shared_ptr<demogData> readCSVLineDemog(std::string theLine) { std::stringstream ss(theLine); string name = getField(ss); string state = getField(ss); double popOver65 = stod(getField(ss)); double popUnder18 = stod(getField(ss)); double popUnder5 = stod(getField(ss)); // first 5 fields double popBachelorEduPlus = stod(getField(ss)); double popHighSchoolEduPlus = stod(getField(ss)); //first 7 fields //skipping to the total 2014 population (which is in field 38) LMAOOOO AHHAAHHAA //now skip over some data for (int i=0; i < 31; i++) { getField(ss); } int totalPop2014 = stoi(getField(ss)); return make_shared<demogData>(name, state, popOver65, popUnder18, popUnder5, popBachelorEduPlus, popHighSchoolEduPlus, totalPop2014); } shared_ptr<demogData> readCSVLineDemogCounty(std::string theLine) { std::stringstream ss(theLine); string countyName = getField(ss); string state = getField(ss); double percentOver65 = stod(getField(ss)); double percentUnder18 = stod(getField(ss)); double percentUnder5 = stod(getField(ss)); // first 5 fields double percentBachelorEduPlus = stod(getField(ss)); double percentHighSchoolEduPlus = stod(getField(ss)); //first 7 fields //skip to to (field 27) in order to get poverty percentage for (int i=0; i<20; i++) { getField(ss); } double percentInPoverty = stod(getField(ss)); // field 27 //skipping to the total 2014 population (which is in field 38) LMAOOOO AHHAAHHAA //now skip over some data for (int i=0; i < 10; i++) { getField(ss); } int totalPop2014 = stoi(getField(ss)); // field 38 int countOver65 = (percentOver65 / 100) * totalPop2014; int countUnder18 = (percentUnder18 / 100) * totalPop2014; int countUnder5 = (percentUnder5 / 100) * totalPop2014; int countBachelorEduPlus = (percentBachelorEduPlus / 100) * totalPop2014; int countHighSchoolEduPlus = (percentHighSchoolEduPlus / 100) * totalPop2014; int countPoverty = (percentInPoverty / 100) * totalPop2014; return make_shared<demogData>(countyName, state, percentOver65, percentUnder18, percentUnder5, percentBachelorEduPlus, percentHighSchoolEduPlus, percentInPoverty, totalPop2014); } //read from a CSV file (for a given data type) return a vector of the data // DO NOT modify for lab01 std::vector<shared_ptr<demogData> > read_csv(std::string filename, typeFlag fileType) { //the actual data std::vector<shared_ptr<demogData> > theData; // Create an input filestream std::ifstream myFile(filename); // Make sure the file is open if(!myFile.is_open()) { throw std::runtime_error("Could not open file"); } if(myFile.good()) { consumeColumnNames(myFile); // Helper vars std::string line; // Now read data, line by line and create demographic dataobject while(std::getline(myFile, line)) { if (fileType == DEMOG) { //theData.push_back(readCSVLineDemog(line)); theData.push_back(readCSVLineDemogCounty(line)); } else { cout << "ERROR - unknown file type" << endl; exit(0); } } // Close file myFile.close(); } return theData; } <file_sep>/dataAQ.h #ifndef DATAAQ_H #define DATAAQ_H #include <string> #include <iostream> #include <vector> #include <map> #include "demogState.h" /* data aggregator and query for testing */ class dataAQ { public: dataAQ(); /* necessary function to aggregate the data - this CAN and SHOULD vary per student - depends on how they map, etc. */ void createStateData(std::vector<shared_ptr<demogData>> theData); //return the name of the state with the largest population under age 5 string youngestPop(); //return the name of the state with the largest population under age 18 string teenPop(); //return the name of the state with the largest population over age 65 string wisePop(); //return the name of the state with the largest population who did not finish high school string underServeHS(); //return the name of the state with the largest population who completed college string collegeGrads(); //return the name of the state with the largest population below the poverty line string belowPoverty(); //getter given a state name return a pointer to demogState data shared_ptr<demogState> getStateData(string stateName) { /*fix this*/ return theStates[stateName]; } //must implement output per aggregate data friend std::ostream& operator<<(std::ostream &out, const dataAQ &allStateData); //core data private for dataAQ private: //Decide how to aggregate the data into a map ADD here map<std::string, shared_ptr<demogState>> theStates; }; #endif <file_sep>/dataAQ.cpp /* aggregate data */ #include "dataAQ.h" #include "demogData.h" #include <iostream> #include <algorithm> dataAQ::dataAQ() {} /* necessary function to aggregate the data - this CAN and SHOULD vary per student - depends on how they map, etc. */ void dataAQ::createStateData(std::vector<shared_ptr<demogData>> theData) { //FILL in std::string currentState = theData[0]->getState(); std::vector<shared_ptr<demogData>> stateCounties; for (auto entry : theData) { if (entry->getState() != currentState) { theStates.insert(std::make_pair(currentState, std::make_shared<demogState>(currentState, stateCounties))); // std::cout << "New map entry for state: " << currentState << "\n"; //deboog stateCounties.clear(); currentState = entry->getState(); } stateCounties.push_back(entry); } if (stateCounties.size()) { theStates.insert(std::make_pair(currentState, std::make_shared<demogState>(currentState, stateCounties))); //std::cout << "New map entry for (final) state: " << currentState << "\n"; //deboog stateCounties.clear(); } //std::cout << theStates.size() << "\n"; //deboog } //return the name of the state with the largest population under age 5 string dataAQ::youngestPop() { //FILL in double record = 0; string usurper = ""; for (auto state : theStates) { if (state.second->getpopUnder5() > record) { usurper = state.first; record = state.second->getpopUnder5(); } } return usurper; } //return the name of the state with the largest population under age 18 string dataAQ::teenPop() { double record = 0; string usurper = ""; for (auto state : theStates) { //std::cout << state.first << ": " << state.second->getpopUnder18() << " vs " << record << "\n"; if (state.second->getpopUnder18() > record) { usurper = state.first; record = state.second->getpopUnder18(); } } return usurper; } //return the name of the state with the largest population over age 65 string dataAQ::wisePop() { double record = 0; string usurper = ""; for (auto state : theStates) { if (state.second->getpopOver65() > record) { usurper = state.first; record = state.second->getpopOver65(); } } return usurper; } //return the name of the state with the largest population who did not receive high school diploma string dataAQ::underServeHS() { //FILL in double record = 0; string usurper = ""; for (auto state : theStates) { if ((100.0 - state.second->getHSup()) > record) { usurper = state.first; record = 100.0 - state.second->getHSup(); } } return usurper; } //return the name of the state with the largest population who did receive bachelors degree and up string dataAQ::collegeGrads() { double record = 0; string usurper = ""; for (auto state : theStates) { if ((state.second->getBAup()) > record) { usurper = state.first; record = state.second->getBAup(); } } return usurper; } //return the name of the state with the largest population below the poverty line string dataAQ::belowPoverty() { double record = 0; string usurper = ""; for (auto state : theStates) { if (state.second->getPoverty() > record) { usurper = state.first; record = state.second->getPoverty(); } } return usurper; } <file_sep>/main.cpp // Spring 2021 CS32 lab03 // Created by: <NAME> and <NAME> // Created on: 04/25/2021 #include <iostream> #include <string> #include <fstream> #include <vector> #include "demogData.h" #include "parse.h" #include "dataAQ.h" using namespace std; int main() { dataAQ theAnswers; //read in a csv file and create a vector of objects representing each counties data std::vector<shared_ptr<demogData>> theData = read_csv( "county_demographics.csv", DEMOG); //debug print out - uncomment if you want to double check your data /* for (const auto &obj : theData) { std::cout << *obj << std::endl; } */ theAnswers.createStateData(theData); //one example of how to print required - ADD OTHERS cout << "*** the state that needs the most pre-schools**" << endl; string needPK = theAnswers.youngestPop(); cout << "Name of state: " << needPK << endl; if (theAnswers.getStateData(needPK) != nullptr){ cout << *(theAnswers.getStateData(needPK)) << endl; } else{ cout << "Did you read the lab instructions?" << endl; } //NOW fill in these too cout << "*** the state that needs the most high schools**" << endl; needPK = theAnswers.teenPop(); cout << "Name of state: " << needPK << endl; if (theAnswers.getStateData(needPK) != nullptr){ cout << *(theAnswers.getStateData(needPK)) << endl; } else{ cout << "state ptr getter failed" << endl; } cout << "*** the state that needs the most vaccines**" << endl; needPK = theAnswers.wisePop(); cout << "Name of state: " << needPK << endl; if (theAnswers.getStateData(needPK) != nullptr){ cout << *(theAnswers.getStateData(needPK)) << endl; } else{ cout << "state ptr getter failed" << endl; } cout << "*** the state that needs the most help with education**" << endl; needPK = theAnswers.underServeHS(); cout << "Name of state: " << needPK << endl; if (theAnswers.getStateData(needPK) != nullptr){ cout << *(theAnswers.getStateData(needPK)) << endl; } else{ cout << "state ptr getter failed" << endl; } cout << "*** the state with most college grads**" << endl; needPK = theAnswers.collegeGrads(); cout << "Name of state: " << needPK << endl; if (theAnswers.getStateData(needPK) != nullptr){ cout << *(theAnswers.getStateData(needPK)) << endl; } else{ cout << "state ptr getter failed" << endl; } cout << "*** the state with largest percent of the population below the poverty line**" << endl; needPK = theAnswers.belowPoverty(); cout << "Name of state: " << needPK << endl; if (theAnswers.getStateData(needPK) != nullptr){ cout << *(theAnswers.getStateData(needPK)) << endl; } else{ cout << "state ptr getter failed" << endl; } return 0; } <file_sep>/demogData.h #ifndef DEMOG_H #define DEMOG_H #include <string> #include<iostream> using namespace std; /* class to represent county demographic data from CORGIS */ class demogData { public: demogData(string inN, string inS, double in65, double in18, double in5, int totPop14) : name(inN), state(inS), popOver65(in65), popUnder18(in18), popUnder5(in5), popBachelorEduPlus(-1), popHighSchoolEduPlus(-1), totalPopulation2014(totPop14){} demogData(string inN, string inS, double in65, double in18, double in5, double inBach, double inHigh, int totPop14) : name(inN), state(inS), popOver65(in65), popUnder18(in18), popUnder5(in5), popBachelorEduPlus(inBach), popHighSchoolEduPlus(inHigh), totalPopulation2014(totPop14) {} demogData(string inN, string inS, double in65, double in18, double in5, double inBach, double inHigh, double inPov, int totPop14) : name(inN), state(inS), popOver65(in65), popUnder18(in18), popUnder5(in5), popBachelorEduPlus(inBach), popHighSchoolEduPlus(inHigh), popInPoverty(inPov), totalPopulation2014(totPop14) {} string getName() const { return name; } string getState() const { return state; } double getpopOver65() const { return popOver65; } double getpopUnder18() const { return popUnder18; } double getpopUnder5() const { return popUnder5; } int getPop() const { return totalPopulation2014; } double getBAup() const { return popBachelorEduPlus; } double getHSup() const { return popHighSchoolEduPlus; } double getPoverty() const { return popInPoverty; } int getpopOver65Count() const; int getpopUnder18Count() const; int getpopUnder5Count() const; int getBAupCount() const; int getHSupCount() const; int getPovertyCount() const; friend std::ostream& operator<<(std::ostream &out, const demogData &DD); //the friend in front means this function can access private vars even though //its not a member function private: const string name; const string state; const double popOver65; const double popUnder18; const double popUnder5; const int totalPopulation2014; const double popBachelorEduPlus; const double popHighSchoolEduPlus; const double popInPoverty = -1; }; #endif <file_sep>/demogState.h #ifndef STATE_H #define STATE_H #include <memory> #include <string> #include <iostream> #include <vector> #include "demogData.h" /* class to represent state data - fairly redundent at this point but will use inheritence later - FILL IN */ class demogState { public: //FILL IN // constructor with no arguments puts -1 for all values as stud values demogState() {} //constructor with two arguments: the abbreviation of the state and a vector demogState(string state, vector<shared_ptr<demogData>> countyData); string getState() const { return stateName; } double getpopOver65() const { return percentOver65; } double getpopUnder18() const { return percentUnder18; } double getpopUnder5() const { return percentUnder5; } double getBAup() const { return percentBachelorPlus; } double getHSup() const { return percentHSPlus; } double getPoverty() const { return percentPoverty; } /* int getpopOver65Count() const { return countOver65; } int getpopUnder18Count() const { return countUnder18; } int getpopUnder5Count() const { return countUnder5; } int getBAupCount() const { return countBachelorPlus; } int getPop() const { return totalPopulation; } int getHSupCount() const { return countHSPlus; } int getPovertyCount() const { return countPoverty; }*/ friend std::ostream& operator<<(std::ostream &out, const demogState &SD); private: // state information string stateName = "TOUPDATE"; // name of the state int totalPopulation = -1; // the population of the state int numCounties = -1; // number of counties imn the state // percentage data double percentOver65 = -1; // age above 65 double percentUnder18 = -1; // age under 18 double percentUnder5 = -1; // age under 5 double percentBachelorPlus = -1; // bachelor degree or more double percentHSPlus = -1; // high school educated or more double percentPoverty = -1; // below poverty // count data int countOver65 = -1; // age above 65 int countUnder18 = -1; // age under 18 int countUnder5 = -1; // age under 5 int countBachelorPlus = -1; // bachelor degree or more int countHSPlus = -1; // high school educated or more int countPoverty = -1; // below poverty //DATA here }; #endif <file_sep>/demogState.cpp #include "demogState.h" #include "demogData.h" #include <sstream> #include <string> #include <assert.h> #include <iomanip> using namespace std; //add member functions here /* print state data - as aggregate of all the county data */ std::ostream& operator<<(std::ostream &out, const demogState&SD) { // outputs the data in the form: // State Info: UT // Number of Counties: 29 // Population Info: // (over 65): 10.03% and total: 295146 // (under 18): 30.71% and total: 903830 // (under 5): 8.58% and total: 252378 // Education info: // (Bachelor or more): 30.54% and total: 898886 // (high school or more): 91.01% and total: 2678412 // persons below poverty: 12.67% and total: 372832 // Total population: 2942902 cout << fixed; cout.precision(2); out << "State Info: " << SD.stateName << endl; // State Info: UT out << "Number of Counties: " << SD.numCounties << endl; // Number of Counties: 29 out << "Population Info:\n"; // Population Info: out << "(over 65): " << SD.percentOver65 << "% and total: " << SD.countOver65 << endl; // (over 65): 10.03% and total: 295146 out << "(under 18): " << SD.percentUnder18 << "% and total: " << SD.countUnder18 << endl; // (under 18): 30.71% and total: 903830 out << "(under 5): " << SD.percentUnder5 << "% and total: " << SD.countUnder5 << endl; // (under 5): 8.58% and total: 252378 out << "Education info:\n"; // Education info: out << "(Bachelor or more): " << SD.percentBachelorPlus << "% and total: " << SD.countBachelorPlus << endl; // (Bachelor or more): 30.54% and total: 898886 out << "(high school or more): " << SD.percentHSPlus << "% and total: " << SD.countHSPlus << endl; // (high school or more): 91.01% and total: 2678412 out << "persons below poverty: " << SD.percentPoverty << "% and total: " << SD.countPoverty << endl;// persons below poverty: 12.67% and total: 372832 out << "Total population: " << SD.totalPopulation << endl; // Total population: 2942902 return out; } demogState::demogState(string state, vector<shared_ptr<demogData>> countyData) { stateName = state; // set name of the state numCounties = countyData.size(); // size of the vector should be the number of counties // set all the counts to 0 to prepare to iterate through vector totalPopulation = 0; countOver65 = 0; countUnder18 = 0; countUnder5 = 0; countBachelorPlus = 0; countHSPlus = 0; countPoverty = 0; for(int i = 0; i < countyData.size(); i++) // iterate through all counties in the state to get all counts for the state { // aggregate the data counts for the states totalPopulation = totalPopulation + countyData[i]->getPop(); // aggregate population countOver65 = countOver65 + countyData[i]->getpopOver65Count(); // aggregate countOver65 countUnder18 = countUnder18 + countyData[i]->getpopUnder18Count(); // aggregate countUnder18 countUnder5 = countUnder5 + countyData[i]->getpopUnder5Count(); countBachelorPlus = countBachelorPlus + countyData[i]->getBAupCount(); countHSPlus = countHSPlus + countyData[i]->getHSupCount(); countPoverty = countPoverty + countyData[i]->getPovertyCount(); } percentOver65 = (countOver65 / double(totalPopulation)) * 100; // calculate the percent age above 65 percentUnder18 = (countUnder18 / double(totalPopulation)) * 100; // calculate the percent age under 18 percentUnder5 = (countUnder5 / double(totalPopulation)) * 100; // calculate the percent age under 5 percentBachelorPlus = (countBachelorPlus / double(totalPopulation)) * 100; // calculate the percent bachelor degree or more percentHSPlus = (countHSPlus / double(totalPopulation)) * 100; // calculate the percent high school educated or more percentPoverty = (countPoverty / double(totalPopulation)) * 100; // calculate the percent below poverty }
4823cd7350f6d3612291eb7558247da9ba6606cc
[ "C++" ]
7
C++
kevinyxlu/cs32lab03
582c42181d8e7891a6f34a3ef5f524c915e963a1
44e643093a0caa4b74b177bd1fe0c34a2537585f
refs/heads/master
<file_sep>import fetch from 'node-fetch'; import ZeroPaper from '.'; describe('Complete Flow', () => { let zeropaper = null; const credentials = { username: '<EMAIL>', password: '<PASSWORD>', }; beforeEach(async () => { fetch.mock.reset(); zeropaper = new ZeroPaper(credentials); }); test('logs in the user successfully', async () => { await zeropaper.login(); expect(zeropaper.loginToken).not.toBeNull(); expect(fetch.mock.calls()).toHaveLength(1); expect(fetch.mock.calls()[0]).toMatchObject({ method: 'POST', url: 'https://accounts.zeropaper.com.br/access_client/sign_in', body: JSON.stringify(credentials), }); }); test('Recovers transactions', async () => { await zeropaper.login(); const transactions = await zeropaper.getTransactions({ companyId: '123', start: '2018-01-01', end: '2018-01-31', }); expect(fetch.mock.calls()).toHaveLength(2); expect(fetch.mock.calls()[1]).toMatchObject({ method: 'GET', url: 'https://api.zeropaper.com.br/v2/transactions?company_id=123&filter%5Bstart_date%5D=2018-01-01&filter%5Bend_date%5D=2018-01-31', }); expect(transactions).toEqual([ { id: 111111111, category_id: 3, description: 'IOF', paydate: '2018-01-31', paid: true, value: 16.81, payment_plan: 'one_time', frequency_main_id: null, frequency_type: null, frequency_total: null, frequency_number: null, comment: '', duedate: '2018-01-31', document_number: null, split: false, has_nf: false, has_boleto: false, has_attachment: false, relationships: { contact: { id: 1, name: '<NAME>', }, transaction_subcategory: { id: 2, name: 'Imposto', }, bank_account: { id: 3, name: '<NAME>', }, expense_center: { id: null, name: null, }, bank_account_origin: { id: null, name: null, }, bank_account_destination: { id: null, name: null, }, boleto: { id: null, status: null, url: null, due_date: null, total_amount: null, contact: { id: null, name: null, work_email: null, home_email: null, address: { id: null, cep: null, }, }, item: { id: null, description: null, }, }, splits: [], }, }, { id: 222222222, category_id: 1, description: 'Cliente X - Pagamento Y', paydate: '2018-01-20', paid: true, value: 20000, payment_plan: 'instalment', frequency_main_id: 407908855, frequency_type: 'M', frequency_total: 5, frequency_number: 5, comment: '', duedate: '2018-01-30', document_number: '', split: false, has_nf: false, has_boleto: false, has_attachment: false, relationships: { contact: { id: 1, name: '<NAME>', }, transaction_subcategory: { id: 2, name: '<NAME>', }, bank_account: { id: 3, name: 'Conta Corrente BB', }, expense_center: { id: null, name: null, }, bank_account_origin: { id: null, name: null, }, bank_account_destination: { id: null, name: null, }, boleto: { id: null, status: null, url: null, due_date: null, total_amount: null, contact: { id: null, name: null, work_email: null, home_email: null, address: { id: null, cep: null, }, }, item: { id: null, description: null, }, }, splits: [], }, }, ]); }); test('Updates transaction', async () => { await zeropaper.login(); const body = { company_id: '111111', force_update: 'N', reference_date: '2018-01-30', tags: [], }; expect(zeropaper.updateTransaction(1, body)).resolves.toBeTruthy(); expect(fetch.mock.calls()).toHaveLength(2); expect(fetch.mock.calls()[1]).toMatchObject({ method: 'PATCH', url: 'https://api.zeropaper.com.br/v1/transactions/1', body: JSON.stringify(body), }); }); }); <file_sep>export default { meta: { code: 200, }, notifications: [], response: [ { id: 111111111, category_id: 3, description: 'IOF', paydate: '2018-01-31', paid: true, value: 16.81, payment_plan: 'one_time', frequency_main_id: null, frequency_type: null, frequency_total: null, frequency_number: null, comment: '', duedate: '2018-01-31', document_number: null, split: false, has_nf: false, has_boleto: false, has_attachment: false, relationships: { contact: { id: 1, name: 'Banco do Brasil', }, transaction_subcategory: { id: 2, name: 'Imposto', }, bank_account: { id: 3, name: '<NAME>', }, expense_center: { id: null, name: null, }, bank_account_origin: { id: null, name: null, }, bank_account_destination: { id: null, name: null, }, boleto: { id: null, status: null, url: null, due_date: null, total_amount: null, contact: { id: null, name: null, work_email: null, home_email: null, address: { id: null, cep: null, }, }, item: { id: null, description: null, }, }, splits: [], }, }, { id: 222222222, category_id: 1, description: 'Cliente X - Pagamento Y', paydate: '2018-01-20', paid: true, value: 20000, payment_plan: 'instalment', frequency_main_id: 407908855, frequency_type: 'M', frequency_total: 5, frequency_number: 5, comment: '', duedate: '2018-01-30', document_number: '', split: false, has_nf: false, has_boleto: false, has_attachment: false, relationships: { contact: { id: 1, name: '<NAME>', }, transaction_subcategory: { id: 2, name: '<NAME>', }, bank_account: { id: 3, name: '<NAME>', }, expense_center: { id: null, name: null, }, bank_account_origin: { id: null, name: null, }, bank_account_destination: { id: null, name: null, }, boleto: { id: null, status: null, url: null, due_date: null, total_amount: null, contact: { id: null, name: null, work_email: null, home_email: null, address: { id: null, cep: null, }, }, item: { id: null, description: null, }, }, splits: [], }, }, ], }; <file_sep>export default { iamTicket: { ticket: 'V1-111-asdpks978s9d24d4asfp89', userId: '111111111111111', userIdPseudonym: '<PASSWORD>', agentId: '111111111111111', realmId: null, userContextRealmId: null, authenticationLevel: '25', identityAssuranceLevel: '-1', namespaceId: '50000001', role: [], access: null, scoped: false, authTime: '1544831100241', createTime: '1544831100439', sessionId: 'as4d654d89as7ad98as4d65a4dasad46s-1544831100241', identityProvider: null, compliance: [], context: null, mergedIds: null, }, action: 'PASS', riskLevel: 'LOW', challenge: [], longLivedToken: null, authContextId: null, passwordResetRequired: false, }; <file_sep>import loginResponse from './api/login'; import transactionsResponse from './api/transactions'; function delayResponse(data) { return new Promise(resolve => setTimeout(() => resolve(data)), 10); } export default (function fetchMock() { let calls = []; const fetch = (url, { method = 'GET', body = null, headers }) => { calls.push({ url, method, body, headers }); const defaultResponse = { ok: true, status: 200, statusText: 'OK', json: () => delayResponse({}), }; let response = {}; if (/accounts.zeropaper.com.br\/access_client\/sign_in/.test(url)) { response = { json: () => delayResponse(loginResponse) }; } else if (/api.zeropaper.com.br\/v2\/transactions/.test(url)) { response = { json: () => delayResponse(transactionsResponse) }; } return delayResponse({ ...defaultResponse, ...response }); }; fetch.mock = { calls: () => calls, reset: () => { calls = []; }, }; return fetch; })(); <file_sep>import fetch from 'node-fetch'; import querystring from 'querystring'; export default class ZeroPaper { credentials = null; loginToken = null; constructor({ username, password }) { this.credentials = { username, password }; } async login() { const url = 'https://accounts.zeropaper.com.br/access_client/sign_in'; const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': ' application/json', intuit_sessionid: 'ACBDC15C8FE44B5AA8482812CB6541CA', }, body: JSON.stringify(this.credentials), }); const json = await response.json(); this.isLoggedIn = true; this.loginToken = json.iamTicket.ticket; } async getTransactions({ companyId, start, end }) { const query = querystring.stringify({ company_id: companyId, 'filter[start_date]': start, 'filter[end_date]': end, }); const url = `https://api.zeropaper.com.br/v2/transactions?${query}`; const response = await fetch(url, { headers: { 'X-Application-Uid': '73d4a5202a0101df4ccd770fd645f9b53e2d1efd3108748a122ff5bafe10a6ab', Authorization: `Intuit_IAM_Authentication intuit_userid=193514544004679,intuit_token=${ this.loginToken },intuit_realmid=193514586571929`, }, }); const json = await response.json(); return json.response; } async updateTransaction(id, body) { const url = `https://api.zeropaper.com.br/v1/transactions/${id}`; const response = await fetch(url, { method: 'PATCH', body: JSON.stringify(body), headers: { 'Content-Type': 'application/json', 'X-Application-Uid': '73d4a5202a0101df4ccd770fd645f9b53e2d1efd3108748a122ff5bafe10a6ab', Authorization: `Intuit_IAM_Authentication intuit_userid=193514544004679,intuit_token=${ this.loginToken },intuit_realmid=193514586571929`, }, }); return response.ok; } }
123f6e96845de573d2414608bdd18acc57db578f
[ "JavaScript" ]
5
JavaScript
arthurnobrega/zeropaper-api
248a36e41930e7cd526a264b0022e3626769f19a
3bcf2aafa181fec5d9b0119b5e7af69eeb4c541f
refs/heads/master
<file_sep>class Organization < ActiveRecord::Base belongs_to :user has_many :events has_many :organization_issues has_many :issues, through: :organization_issues validates_presence_of :name end <file_sep>class CreateOrganizations < ActiveRecord::Migration[5.0] def change create_table :organizations do |t| t.string :name t.boolean :brooklyn t.boolean :bronx t.boolean :manhattan t.boolean :queens t.boolean :staten_island t.string :location t.string :fax t.string :phone t.string :website t.string :description t.string :associated_faith t.integer :user_id t.timestamps null: false end end end <file_sep>class UsersController < ApplicationController get '/signup' do if !logged_in? erb :'users/create_user' else redirect '/' end end post '/signup' do if !logged_in? user = User.new(username: params[:username], email: params[:email], password: params[:password]) session[:user_id] = user.id if user.save end redirect '/' end get '/login' do if !logged_in? erb :'users/login' else redirect '/' end end post '/login' do if !logged_in? user = User.find_by(username: params[:username]) if user && user.authenticate(params[:password]) session[:user_id] = user.id redirect '/' else erb :'users/failure' end else redirect '/' # do I need this redirect, or could I simply have the controller ignore POST '/login' requests from logged in users? end end get '/logout' do session.clear if logged_in? redirect '/' end get '/users' do if logged_in? @users = User.all.sort_by{|u| u.username.downcase} erb :'users/users' else redirect '/login' end end get '/users/:id' do if logged_in? @user = User.find_by(id: params[:id]) if @user @events = @user.events.sort_by{|e| e.datetime} @organizations = @user.organizations.sort_by{|o| o.name.downcase} erb :'users/show_user' else redirect '/unknown/user' end else redirect '/login' end end end <file_sep># Help Out NYC ## Summary Simple Sinatra app to help NYC residents track local volunteer opportunities. ## Setting up the local web server * Clone this GitHub repository down to your local machine * Run `bundle install` * Run `rackup` * Navigate to [localhost:9292](http://localhost:9292/) in your browser (preferably Chrome) ## Usage You will be unable to access any pages except [/signup](http://localhost:9292/signup) and [/login](http://localhost:9292/login) until you log in. Once logged in, you can: * Create new: * [organizations](http://localhost:9292/organizations/new) * [events](http://localhost:9292/events/new) * Edit existing: * [organizations](http://localhost:9292/organizations/1/edit) *that you created* * [events](http://localhost:9292/events/1/edit) *that you created* * View lists of: * [organizations](http://localhost:9292/organizations) * [issues](http://localhost:9292/issues) * [events](http://localhost:9292/events) * [users](http://localhost:9292/users) * View individual: * [organizations](http://localhost:9292/organizations/1) * [issues](http://localhost:9292/issues/1) * [events](http://localhost:9292/events/1) * [users](http://localhost:9292/users/1) * Sign up for events that haven't yet met their volunteer goal. * Remove yourself from the volunteer list for events for which you previously signed up. * Log out. ## Notes * The [db/development.sqlite](https://github.com/gj/help-out-sinatra/blob/master/db/development.sqlite) database contains the following data generated by [db/seeds.rb](https://github.com/gj/help-out-sinatra/blob/master/db/seeds.rb): * 970 real NYC organizations scraped from [the NYC Women's Resource Network Database](https://data.cityofnewyork.us/Social-Services/NYC-Women-s-Resource-Network-Database/pqg4-dm6b) * 22 real issues scraped from the same database * 5000 fake events generated randomly * 200 fake users generated from [the U.S. Social Security Administration's list of "the 100 most popular given names for male and female babies born during the last 100 years, 1916-2015"](https://www.ssa.gov/OACT/babynames/decades/century.html) ## Contributing Bug reports and pull requests are welcome on [GitHub](https://github.com/gj/help-out-sinatra). ## License This Sinatra app is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT). <file_sep>class Event < ActiveRecord::Base belongs_to :organization has_many :user_events has_many :users, through: :user_events validates_presence_of :name, :organization_id, :datetime, :description, :volunteers_wanted end <file_sep>class User < ActiveRecord::Base has_secure_password has_many :organizations has_many :user_events has_many :events, through: :user_events validates_presence_of :username, :email, :password end <file_sep>class ApplicationController < Sinatra::Base configure do set :public_folder, 'public' set :views, 'app/views' enable :sessions set :session_secret, "super_duper_secret_phrase" end get '/' do erb :index end get '/unknown/:type' do @type = params[:type] erb :unknown end post '/:type/:id/edit' do if logged_in? redirect "/#{params[:type]}/#{params[:id]}/edit" else redirect '/login' end end delete '/:type/:id' do if logged_in? case params[:type] when "events" event = Event.find(params[:id]) event.destroy if event.organizer == current_user.id redirect '/events' when "organizations" organization = Organization.find(params[:id]) organization.destroy if organization.user == current_user redirect '/organizations' when "users" user = User.find(params[:id]) if user == current_user Event.where(organizer: user.id).each do |e| e.organizer = nil e.save end user.destroy session.clear redirect '/' end else redirect '/' end else redirect '/login' end end helpers do def logged_in? !!current_user end def current_user @current_user ||= User.find_by(id: session[:user_id]) end end end <file_sep>class OrganizationsController < ApplicationController get '/organizations' do if logged_in? @organizations = Organization.all.sort_by{|o| o.name.downcase} erb :'organizations/organizations' else redirect '/login' end end get '/organizations/new' do if logged_in? @issues = Issue.all.sort_by{|i| i.name.downcase} @organizations = Organization.all erb :'organizations/create_organization' else redirect '/login' end end post '/organizations' do if logged_in? organization = Organization.find_by(name: params[:organization][:name]) if organization redirect "/organizations/#{organization.id}" else organization = Organization.create(params[:organization]) params[:issue_ids].each{|id| organization.issues << Issue.find_by(id: id)} if params.has_key?("issue_ids") # is there a better way to do this? organization.user = @current_user organization.save # if I save one of the objects in an AR relationship pairing, does the other (User, in this case) automatically save as well? redirect "/organizations/#{organization.id}" end else redirect '/login' end end get '/organizations/:id' do if logged_in? @organization = Organization.find_by(id: params[:id]) if @organization @events = @organization.events.sort_by{|o| o.datetime} erb :'organizations/show_organization' else redirect '/unknown/organization' end else redirect '/login' end end get '/organizations/:id/edit' do if logged_in? @organization = Organization.find_by(id: params[:id]) if @organization if @organization.user && @organization.user == @current_user @organizations = Organization.all @issues = Issue.all erb :'organizations/edit_organization' else erb :'organizations/failure' end else redirect '/unknown/organization' end else redirect '/login' end end patch '/organizations/:id' do if logged_in? organization = Organization.find_by(id: params[:id]) if organization if organization.name != params[:organization][:name] && Organization.find_by(name: params[:organization][:name]) redirect "/organizations/#{Organization.find_by(name: params[:organization][:name]).id}" else if organization.user == @current_user # reset the multi-option params organization.brooklyn = nil organization.bronx = nil organization.manhattan = nil organization.queens = nil organization.staten_island = nil organization.issues.clear # fill in the new values organization.update(params[:organization]) params[:issue_ids].each{|id| organization.issues << Issue.find_by(id: id)} if params.has_key?("issue_ids") organization.save redirect "/organizations/#{organization.id}" else erb :'organizations/failure' end end else redirect '/unknown/organization' end else redirect '/login' end end end <file_sep>class Issue < ActiveRecord::Base has_many :organization_issues has_many :organizations, through: :organization_issues validates_presence_of :name end <file_sep>class OrganizationIssue < ActiveRecord::Base belongs_to :organization belongs_to :issue end <file_sep>class IssuesController < ApplicationController get '/issues' do if logged_in? @issues = Issue.all.sort_by{|i| i.name.downcase} @organizations = Organization.all erb :'issues/issues' else redirect '/login' end end get '/issues/:id' do if logged_in? @issue = Issue.find_by(id: params[:id]) if @issue @organizations = @issue.organizations.sort_by{|o| o.name.downcase} erb :'issues/show_issue' else redirect '/unknown/issue' end else redirect '/login' end end end <file_sep>class EventsController < ApplicationController get '/events' do if logged_in? # limit to 100 random events to ease SQL query strain @events = Event.all.sample(100).sort_by{|e| e.datetime} erb :'events/events' else redirect '/login' end end get '/events/new' do if logged_in? @organizations = Organization.all.sort_by{|o| o.name.downcase} erb :'events/create_event' else redirect '/login' end end post '/events' do if logged_in? event = Event.find_by(name: params[:event][:name], datetime: params[:event][:datetime]) if event redirect "/events/#{event.id}" else event = Event.create(params[:event]) event.organizer = @current_user.id @current_user.events << event event.save @current_user.save redirect "/events/#{event.id}" end else redirect '/login' end end get '/events/:id' do if logged_in? @event = Event.find_by(id: params[:id]) if @event @organizer = User.find_by(id: @event.organizer) @attendees = @event.users.sort_by{|u| u.username} erb :'events/show_event' else redirect '/unknown/event' end else redirect '/login' end end get '/events/:id/edit' do if logged_in? @event = Event.find_by(id: params[:id]) if @event if @event.organizer == @current_user.id @organizations = Organization.all.sort_by{|o| o.name.downcase} erb :'events/edit_event' else erb :'events/failure' end else redirect '/unknown/event' end else redirect '/login' end end patch '/events/:id' do if logged_in? event = Event.find_by(id: params[:id]) if event if event.organizer == @current_user.id # If the user tries to change the event's name to an existing event's name, redirect them to the existing event's page. If they are the creator of the existing event (and thereby have edit privs), they may edit the existing event. if (event.name != params[:event][:name] || event.datetime != params[:event][:datetime]) && Event.find_by(name: params[:event][:name], datetime: params[:event][:datetime]) redirect "/events/#{Event.find_by(name: params[:event][:name], datetime: params[:event][:datetime]).id}" else event.update(params[:event]) event.save redirect "/events/#{event.id}" end end else redirect '/unknown/event' end else redirect '/login' end end post '/events/:id/signup' do if logged_in? event = Event.find_by(id: params[:id]) if event @current_user.events.include?(event) ? @current_user.events.delete(event) : @current_user.events << event redirect "/events/#{event.id}" else redirect '/unknown/event' end else redirect '/login' end end end
fd40ae22c5c412a8b6a8833e9ca886238af70395
[ "Markdown", "Ruby" ]
12
Ruby
gj/help-out-sinatra
689e19d54b4edce4ca0b4b915cae6c4d87760a66
8d2da82ab8268fb377469dda11995df3788ed70e
refs/heads/master
<file_sep>// // DetailEquipeController.swift // iosProject // // Created by <NAME> on 19/04/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import SDWebImage import Alamofire class DetailEquipeController: UIViewController, UITableViewDelegate, UITableViewDataSource { var image = String() var nameEq = "" var nbPoint = "" var win = "" var continent = "" var draw = "" var butMarq = "" var butRecu = "" var idEquipe = String() var id_equipe = Int() @IBOutlet weak var JoueurTable: UITableView! @IBOutlet weak var equipeNamelbl: UILabel! @IBOutlet weak var continentlbl: UILabel! @IBOutlet weak var imageview: UIImageView! @IBOutlet weak var butreculbl: UILabel! @IBOutlet weak var butmarqlbl: UILabel! @IBOutlet weak var defaitelbl: UILabel! @IBOutlet weak var ptslbl: UILabel! @IBOutlet weak var victoirelbl: UILabel! var joueursListe = [AnyObject]() let URL_USER_LOGIN = String(AppDelegate.adresseIP)+"AndroidBD/joueurs.php" @IBAction func backToDetail(_ sender: UIButton) { dismiss(animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() id_equipe = Int(idEquipe)! JoueurTable.delegate = self JoueurTable.dataSource = self let parameters: Parameters=["id": id_equipe] Alamofire.request(URL_USER_LOGIN, method: .post, parameters: parameters).responseJSON { response in //printing response print(response) //getting the json value from the server let result = response.result //getting the user from response if let groups = result.value as? Dictionary<String,AnyObject>{ if let inner=groups["joueurs"]{ self.joueursListe = inner as! [AnyObject] self.JoueurTable.reloadData() } } } imageview.sd_setImage(with: URL(string: (image)), placeholderImage: UIImage(named: "coupedumonde")) equipeNamelbl.text! = nameEq continentlbl.text! = continent ptslbl.text! = nbPoint victoirelbl.text! = win defaitelbl.text! = draw butmarqlbl.text! = butMarq butreculbl.text! = butRecu } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = JoueurTable.dequeueReusableCell(withIdentifier: "joueurCell") as! JoueurViewCell cell.joueurName.text = joueursListe[indexPath.row]["nom_joueur"] as? String cell.posteJoueur.text = joueursListe[indexPath.row]["poste"] as? String return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return joueursListe.count } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let desVC = UIStoryboard.init(name : "Main", bundle : nil).instantiateViewController(withIdentifier: "JoueurDetailController") as! JoueurDetailController desVC.nomJ = (joueursListe[indexPath.row]["nom_joueur"] as? String)! desVC.nationaliteJ = (joueursListe[indexPath.row]["nationalite"] as? String)! desVC.imgUrl = (joueursListe[indexPath.row]["photo_joueur"] as? String)! desVC.ageJ = (joueursListe[indexPath.row]["age"] as? String)! desVC.butJ = (joueursListe[indexPath.row]["nb_but"] as? String)! desVC.clubJ = (joueursListe[indexPath.row]["Club"] as? String)! desVC.posteJ = (joueursListe[indexPath.row]["poste"] as? String)! desVC.id_joueur = (joueursListe[indexPath.row]["id_joueur"] as? String)! desVC.id_equip = (joueursListe[indexPath.row]["id_equipe"] as? String)! self.present(desVC, animated: true, completion: nil) } } <file_sep> import UIKit import SDWebImage import Alamofire class JoueurDetailController: UIViewController { var nomJ = "" var nationaliteJ = "" var ageJ = "" var posteJ = "" var butJ = "" var clubJ = "" var imgUrl = "" var id_joueur = "" var id = Int() var id_equip = String() @IBOutlet weak var imagePlayer: UIImageView! @IBOutlet weak var joueurName: UILabel! @IBOutlet weak var joueurNationalite: UILabel! @IBOutlet weak var joueurAge: UILabel! @IBOutlet weak var joueurPoste: UILabel! @IBOutlet weak var joueurNbBut: UILabel! @IBOutlet weak var joueurClub: UILabel! @IBOutlet weak var lblRating: UILabel! var ratingValue = Int() @IBOutlet weak var submitRating: UIButton! @IBAction func AlerteRating(_ sender: UIButton) { var msg = "Are you sure to rate " msg += nomJ msg += " "+String(ratingValue) msg += "/10" RatePlayer() let alerteController = UIAlertController( title : "Rating", message : msg, preferredStyle : .alert ) let imageAlerte = UIImage(named : "review") alerteController.addImage(image : imageAlerte!) let okAction = UIAlertAction(title: "Confirm", style: UIAlertActionStyle.default) { UIAlertAction in let desVC = UIStoryboard.init(name : "Main", bundle : nil).instantiateViewController(withIdentifier: "tabbar") as! UITabBarController self.present(desVC, animated: true, completion: nil) } alerteController.addAction(okAction) // alerteController.addAction(UIAlertAction(title : "Submit", style : .default, handler: nil)) self.present(alerteController, animated: true, completion: nil) } @IBAction func sliderRating(_ sender: UISlider) { lblRating.text = String(Int(sender.value)) ratingValue = Int(sender.value) } @IBAction func submitRating(_ sender: UIButton) { RatePlayer() } @IBAction func toDetailEq(_ sender: UIButton) { dismiss(animated: true, completion: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "toPlayer"{ let alert = UIAlertController(title: "Rating", message: "Success", preferredStyle: UIAlertControllerStyle.alert) // add an action (button) // alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { UIAlertAction in let desVC = UIStoryboard.init(name : "Main", bundle : nil).instantiateViewController(withIdentifier: "tabbar") as! UITabBarController self.present(desVC, animated: true, completion: nil) } alert.addAction(okAction) // show the alert self.present(alert, animated: true, completion: nil) } } override func viewDidLoad() { super.viewDidLoad() LoadingOverlay.shared.showProgressView(view) let delay = max(0.0, 1.0) DispatchQueue.main.asyncAfter(deadline: .now() + delay) { LoadingOverlay.shared.hideProgressView() } id = Int(id_joueur)! imagePlayer.sd_setImage(with: URL(string: (imgUrl)), placeholderImage: UIImage(named: "coupedumonde")) //equipeNamelbl.text! = nameEq joueurName.text! = nomJ joueurNationalite.text! = nationaliteJ joueurAge.text! = ageJ joueurPoste.text! = posteJ joueurNbBut.text! = butJ+" Goals" joueurClub.text! = clubJ } func RatePlayer(){ let parameters: Parameters = [ "id_joueur": id, "note": ratingValue ] let URL_USER_LOGIN = String(AppDelegate.adresseIP)+"AndroidBD/ratePlayer.php" Alamofire.request(URL_USER_LOGIN, method: .post, parameters: parameters).responseJSON{ response in //printing response print(response) //getting the json value from the server if let result = response.result.value { let jsonData = result as! NSDictionary if(!(jsonData.value(forKey: "error") as! Bool)){ }else{ let alert = UIAlertController(title: "My Title", message: "failed", preferredStyle: UIAlertControllerStyle.alert) // add an action (button) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) // show the alert self.present(alert, animated: true, completion: nil) } } } } } <file_sep>// // FavouritePartiesViewController.swift // iosProject // // Created by <NAME> on 16/04/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import CoreData class FavouritePartiesViewController: UITableViewController { @IBOutlet weak var favoriteTableView: UITableView! var partieArray :[String] = [] var partieArray2 :[String] = [] var partieArray3 :[String] = [] var partieArray4 :[String] = [] var partieArray5 :[String] = [] override func viewDidLoad() { super.viewDidLoad() let refreshControl = UIRefreshControl() refreshControl.tintColor = UIColor(red:0.25, green:0.72, blue:0.85, alpha:1.0) refreshControl.attributedTitle = NSAttributedString(string: "Fetching Favourites matchs ...") refreshControl.addTarget(self, action: #selector(sortArray), for: UIControlEvents.valueChanged) self.refreshControl = refreshControl tableView.addSubview(refreshControl) let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext let request = NSFetchRequest<NSFetchRequestResult>(entityName: "MyParties") //request.predicate = NSPredicate(format: "age = %@", "12") request.returnsObjectsAsFaults = false do { let result = try context.fetch(request) for data in result as! [NSManagedObject] { partieArray.append(data.value(forKey: "dateMatch") as! String) // print("aaaa\(data.value(forKey: "heureMatch"))") partieArray2.append(data.value(forKey: "heureMatch") as! String) partieArray3.append(data.value(forKey: "equipe") as! String) partieArray4.append(data.value(forKey: "equipeA") as! String) // partieArray5.append(data.value(forKey: "image") as! String) } } catch { print("Failed") } tableView.tableFooterView = UIView() } @objc private func sortArray(_ sender: Any) { //let request = NSFetchRequest<NSFetchRequestResult>(entityName: "MyParties") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows if partieArray.count == 0 { let emptyLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: self.view.bounds.size.height)) emptyLabel.text = "No Data" emptyLabel.textAlignment = NSTextAlignment.center self.tableView.backgroundView = emptyLabel // self.tableView.separatorStyle = UITableViewCellSeparatorStyle.none return 0 } else { return partieArray.count } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "PartieCell") let partieLbl = cell?.viewWithTag(97) as? UILabel let partieLbl1 = cell?.viewWithTag(94) as? UILabel let partieLbl2 = cell?.viewWithTag(95) as? UILabel let partieLbl3 = cell?.viewWithTag(96) as? UILabel // let partieLbl4 = cell?.viewWithTag(100) as? UIImageView partieLbl?.text = partieArray[indexPath.row] partieLbl1?.text = partieArray2[indexPath.row] partieLbl2?.text = partieArray3[indexPath.row] partieLbl3?.text = partieArray4[indexPath.row] // partieLbl4?.image = UIImage(named: partieArray5[indexPath.row]) return cell! } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete{ var myData: Array<AnyObject> = [] let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext let request = NSFetchRequest<NSFetchRequestResult>(entityName: "MyParties") //request.predicate = NSPredicate(format: "age = %@", "12") request.returnsObjectsAsFaults = false do { let result = try context.fetch(request) for data in result as! [NSManagedObject] { myData.append(data) } } catch { print("Failed") } context.delete(myData[indexPath.row] as! NSManagedObject ) myData.remove(at: indexPath.row) do { try context.save() } catch _ { } partieArray.remove(at: indexPath.row) tableView.reloadData() } } } <file_sep>// // DetailControllerViewController.swift // iosProject // // Created by <NAME> on 04/05/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import SDWebImage import CoreData import UserNotifications class DetailControllerViewController: UIViewController { var favArray : [String] = [] var image = String() var imageEquipe = String() var labelDate = String() var labelHeure = String() var labelEq1 = String() var labelEq2 = String() var labelStade = String() let now = Date() let start = "2018-05-14 02:43:20" let dateFormatter = DateFormatter() @IBOutlet weak var lbl6: UILabel! @IBOutlet weak var lbl4: UILabel! @IBOutlet weak var lbl3: UILabel! @IBOutlet weak var lbl1: UILabel! @IBOutlet weak var menuView: UIView! @IBOutlet weak var favouriteView: UIViewX! @IBOutlet weak var lbl2: UILabel! @IBOutlet weak var imgEq: UIImageView! @IBOutlet weak var img: UIImageView! @IBOutlet weak var addFavorisButton: UIButton! @IBOutlet weak var favButton: UIButtonX! override func viewDidLoad() { super.viewDidLoad() UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (success, error) in if error != nil { print("Authorization Unsuccessful") } else { print("Authorization Successful" ) } } favButton.alpha = 0 img.sd_setImage(with: URL(string: (image))) // img.image = UIImage(named: image) // imgEq.image = UIImage(named: imageEquipe) // imgEq.sd_setImage(with: URL(string: (imageEquipe))) imgEq.sd_setImage(with: URL(string: (imageEquipe))) lbl1.text = labelDate lbl2.text = labelHeure lbl3.text = labelEq1 lbl4.text = labelEq2 lbl6.text = labelStade loadFav() } @IBAction func addButton(_ sender: UIButton) { if favouriteView.transform == .identity{ UIView.animate(withDuration: 1, animations: { self.favouriteView.transform = CGAffineTransform(scaleX: 11, y: 11) self.menuView.transform = CGAffineTransform(translationX: 0, y: -11) self.addFavorisButton.transform = CGAffineTransform(rotationAngle: self.radians(degrees: 180)) }) { (true) in UIView.animate(withDuration: 0.5, animations: { self.toggleSharedButton() }) } } else { UIView.animate(withDuration: 1, animations: { self.favouriteView.transform = .identity self.menuView.transform = .identity self.addFavorisButton.transform = .identity self.toggleSharedButton() }) } } func toggleSharedButton(){ let alpha = CGFloat(favButton.alpha == 0 ? 1 : 0) favButton.alpha = alpha } func radians(degrees: Double) -> CGFloat { return CGFloat(degrees * .pi / degrees) } @IBAction func favActionButton(_ sender: UIButtonX) { timedNotifications(inSeconds: 5) { (success) in if success { print("Successfully Notified") } } if !favArray.contains(labelDate) && !favArray.contains(labelEq1) { let appDelegate = UIApplication.shared.delegate as! AppDelegate let managedContext = appDelegate.persistentContainer.viewContext let entity = NSEntityDescription.entity(forEntityName: "MyParties", in: managedContext) let partie = NSManagedObject(entity: entity!, insertInto: managedContext) print(labelHeure,"fefe") partie.setValue(labelDate, forKey: "dateMatch") partie.setValue(labelHeure, forKey: "heureMatch") partie.setValue(labelEq1, forKey: "equipe") partie.setValue(labelEq2, forKey: "equipeA") // partie.setValue(imageEquipe, forKey: "image") do { try managedContext.save() let alert = UIAlertController(title: "Success", message: "Partie Added", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) loadFav() print("ok") } catch { print("failed =(") } } else { let alert = UIAlertController(title: "Warning", message: "Partie Already Exists", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.destructive, handler: nil)) self.present(alert, animated: true, completion: nil) } } func loadFav(){ favArray.removeAll() let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext let request = NSFetchRequest<NSFetchRequestResult>(entityName: "MyParties") //request.predicate = NSPredicate(format: "age = %@", "12") request.returnsObjectsAsFaults = false do { let result = try context.fetch(request) for data in result as! [NSManagedObject] { favArray.append((data.value(forKey: "dateMatch") as! String)) // favArray.append((data.value(forKey: "equipe") as! String)) } } catch { print("Failed") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func backButton(_ sender: Any) { dismiss(animated: true, completion: nil) } func timedNotifications(inSeconds: TimeInterval, completion: @escaping (_ Success: Bool) -> ()) { let trigger = UNTimeIntervalNotificationTrigger(timeInterval: inSeconds, repeats: false) let content = UNMutableNotificationContent() content.title = labelDate content.subtitle = labelHeure content.body = labelEq1+" "+"VS"+" "+labelEq2 content.sound = UNNotificationSound.default() if let path = Bundle.main.path(forResource: "messi", ofType: "png") { let url = URL(fileURLWithPath: path) do { let attachment = try UNNotificationAttachment(identifier: "messi", url: url, options: nil) content.attachments = [attachment] } catch { print("The attachment was not loaded.") } } let request = UNNotificationRequest(identifier: "customNotification", content: content, trigger: trigger) UNUserNotificationCenter.current().add(request) { (error) in if error != nil { completion(false) } else { completion(true) } } } } <file_sep>// // DetailsActualityController.swift // iosProject // // Created by <NAME> on 26/03/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import SDWebImage class DetailsActualityController: UIViewController { var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView() @IBOutlet weak var imageActuality: UIImageView! @IBOutlet weak var titleActuality: UILabel! @IBOutlet weak var authorActuality: UILabel! @IBOutlet weak var descriptionActuality: UILabel! var image = String() var titleAc = "" var descAc = "" var author = "" override func viewDidLoad() { super.viewDidLoad() LoadingOverlay.shared.showProgressView(view) let delay = max(0.0, 1.0) DispatchQueue.main.asyncAfter(deadline: .now() + delay) { LoadingOverlay.shared.hideProgressView() } imageActuality.sd_setImage(with: URL(string: (image)), placeholderImage: UIImage(named: "coupedumonde")) titleActuality.text! = titleAc descriptionActuality.text! = descAc } } <file_sep>// // ViewController.swift // iosProject // // Created by <NAME> on 25/03/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import Alamofire import SDWebImage class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var actualityTable: UITableView! var articles: [Actuality] = [] let actualityArray = ["bresil", "tunisie", "argentine", "marroc"] // let URL_USER_LOGIN = "http://172.16.58.3/AndroidBD/actualities.php" var actualityListe = [AnyObject]() override func viewDidLoad() { super.viewDidLoad() actualityTable.dataSource = self actualityTable.delegate = self super.viewDidLoad() fetchActualities() } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = actualityTable.dequeueReusableCell(withIdentifier: "actualityCell") as! ActualityCell // cell.layer.cornerRadius = 50 //cell.imageCell.image = UIImage(named: (actualityListe[indexPath.row]["image"] as? String)!) //cell.imageCell.sd_setImage(with: URL(string: (actualityListe[indexPath.row]["image"] as? String)!), placeholderImage: UIImage(named: "tunisie")) // cell.titleCell.text = actualityArray[indexPath.row].capitalized // cell.titleCell.text = actualityListe[indexPath.row]["nom"] as? String cell.titleCell.text = articles[indexPath.item].title //cell.imageCell.sd_setImage(with: URL(string: (articles[indexPath.row].urlImg)!), placeholderImage: UIImage(named: "tunisie")) if self.articles[indexPath.item].urlImg == nil { cell.imageCell.image = UIImage(named : "coupedumonde") } else { cell.imageCell.downloadImage(from: self.articles[indexPath.item].urlImg!) } return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return articles.count } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { LoadingOverlay.shared.showProgressView(view) let mainStoryBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let desVC = mainStoryBoard.instantiateViewController(withIdentifier: "DetailsActualityController") as! DetailsActualityController //desVC.image = UIImage(named: actualityListe[indexPath.row])! desVC.image = (articles[indexPath.item].urlImg)! desVC.titleAc = articles[indexPath.item].title! desVC.descAc = articles[indexPath.item].desc! self.navigationController?.pushViewController(desVC, animated: true) } func fetchActualities(){ let urlRequest = URLRequest(url: URL(string : "https://newsapi.org/v2/top-headlines?sources=football-italia&apiKey=373fd1b74aeb471cadc2e0354d2ae79d")!) LoadingOverlay.shared.showProgressView(view) let task = URLSession.shared.dataTask(with: urlRequest){ (data,response,error) in if error != nil { print(error!) } self.articles = [Actuality]() do { let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject] if let actualitiesFromJson = json["articles"] as? [[String : AnyObject]] { for actualityFromJson in actualitiesFromJson { let actuality = Actuality() if let title = actualityFromJson["title"] as? String, let desc = actualityFromJson["description"] as? String, let url = actualityFromJson["url"] as? String, let urlImage = actualityFromJson["urlToImage"] as? String { actuality.title = title actuality.desc = desc actuality.url = url actuality.urlImg = urlImage } self.articles.append(actuality) } } DispatchQueue.main.sync { LoadingOverlay.shared.hideProgressView() self.actualityTable.reloadData() } } catch let error{ print(error) } } task.resume() } } extension UIImageView { func downloadImage(from url : String){ let urlRequest = URLRequest(url : URL(string : url)!) let task = URLSession.shared.dataTask(with: urlRequest){ (data,response,error) in if error != nil { print(error!) return } DispatchQueue.main.async { self.image = UIImage(data: data!) } } task.resume() } } <file_sep>// // PoolsController.swift // iosProject // // Created by <NAME> on 25/03/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import SDWebImage import Alamofire class PoolsController: UIViewController, UITableViewDataSource, UITableViewDelegate { var selectedSegment = 1 let array1 = ["Tunisie","Cameroun","Bresil","Belgique"] let array2 = ["Arabie Saoudite","Angleterre","Egypte","Panama"] let URL_USER_LOGIN = String(AppDelegate.adresseIP)+"AndroidBD/groupe1.php" var G1Liste = [AnyObject]() override func viewDidLoad() { super.viewDidLoad() groupTableView.delegate = self groupTableView.dataSource = self Alamofire.request(URL_USER_LOGIN, method: .post, parameters: nil).responseJSON { response in //printing response print(response) //getting the json value from the server let result = response.result //getting the user from response if let groups = result.value as? Dictionary<String,AnyObject>{ if let inner=groups["groupe1"]{ self.G1Liste = inner as! [AnyObject] self.groupTableView.reloadData() } } } // Do any additional setup after loading the view. } @IBAction func groupsControl(_ sender: UISegmentedControl) { if sender.selectedSegmentIndex == 0 { selectedSegment = 1 selectPool(id: selectedSegment) } else if sender.selectedSegmentIndex == 1{ selectedSegment = 2 selectPool(id: selectedSegment) } else if sender.selectedSegmentIndex == 2{ selectedSegment = 3 selectPool(id: selectedSegment) } else if sender.selectedSegmentIndex == 3{ selectedSegment = 4 selectPool(id: selectedSegment) } else if sender.selectedSegmentIndex == 4{ selectedSegment = 5 selectPool(id: selectedSegment) } else if sender.selectedSegmentIndex == 5{ selectedSegment = 6 selectPool(id: selectedSegment) } else if sender.selectedSegmentIndex == 6{ selectedSegment = 7 selectPool(id: selectedSegment) } else if sender.selectedSegmentIndex == 7{ selectedSegment = 8 selectPool(id: selectedSegment) } self.groupTableView.reloadData() } @IBOutlet weak var groupTableView: UITableView! func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = groupTableView.dequeueReusableCell(withIdentifier: "teamCell") as! PoolsCell cell.EquipeImg.sd_setImage(with: URL(string: (G1Liste[indexPath.row]["drapeau_equipe"] as? String)!), placeholderImage: UIImage(named: "coupedumonde")) // cell.EquipeImg.layer.cornerRadius = cell.EquipeImg.frame.height / 2 // cell.EquipeImg.layer.cornerRadius = 50 cell.EquipeName.text = G1Liste[indexPath.row]["nom_equipe"] as? String cell.EquipPts.text = G1Liste[indexPath.row]["nb_point"] as? String return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return G1Liste.count } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let desVC = UIStoryboard.init(name : "Main", bundle : nil).instantiateViewController(withIdentifier: "DetailEquipeController") as! DetailEquipeController desVC.idEquipe = (G1Liste[indexPath.row]["id_equipe"] as? String)! desVC.continent = (G1Liste[indexPath.row]["continent"] as? String)! desVC.image = (G1Liste[indexPath.row]["drapeau_equipe"] as? String)! desVC.nameEq = (G1Liste[indexPath.row]["nom_equipe"] as? String)! desVC.nbPoint = (G1Liste[indexPath.row]["nb_point"] as? String)! desVC.butMarq = (G1Liste[indexPath.row]["but_marque"] as? String)! desVC.butRecu = (G1Liste[indexPath.row]["but_recu"] as? String)! desVC.win = (G1Liste[indexPath.row]["nb_victoire"] as? String)! desVC.draw = (G1Liste[indexPath.row]["nb_defaite"] as? String)! self.present(desVC, animated: true, completion: nil) } func selectPool(id : Int){ let URL_USER_LOGIN = String(AppDelegate.adresseIP)+"AndroidBD/pools.php" let parameters: Parameters=["id": id] Alamofire.request(URL_USER_LOGIN, method: .post, parameters: parameters).responseJSON { response in //printing response print(response) //getting the json value from the server let result = response.result //getting the user from response if let groups = result.value as? Dictionary<String,AnyObject>{ if let inner=groups["groupe1"]{ self.G1Liste = inner as! [AnyObject] self.groupTableView.reloadData() } } } } } <file_sep>// // PoolsCell.swift // iosProject // // Created by <NAME> on 09/04/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class PoolsCell: UITableViewCell { @IBOutlet weak var EquipeWinDraw: UILabel! @IBOutlet weak var EquipeImg: UIImageView! @IBOutlet weak var EquipPts: UILabel! @IBOutlet weak var EquipeName: UILabel! } <file_sep>// // Team.swift // iosProject // // Created by <NAME> on 15/04/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class Team { var name:String? var coupeNumb:String? var image:String? init(name:String,coupeNumb:String,image:String) { self.name=name self.coupeNumb=coupeNumb self.image=image } } <file_sep>// // MapsViewController.swift // iosProject // // Created by <NAME> on 11/04/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import MapKit class MapsViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var mapView: MKMapView! var longitude = Int() var latitude = Int() var nameStadium = String() var nameCountry = String() var locationManager: CLLocationManager! var names:[String]! var images:[UIImage]! var descriptions:[String]! var coordinates:[Any]! var currentRestaurantIndex: Int = 0 override func viewDidLoad() { super.viewDidLoad() // Some restaurants in London names = ["lekaterinbourg Arena", "Kazan Arena", "Otkrytie Arena", "Loujniki stadium", "Saint Petersbourg Arena", "Spartak Arena", "Fisht stadium", "Volgograd Arena","Nijni Novgorod","Rostov Arena","Samara Arena","Mordovia Arena","Baltika Arena"] // Restaurants' images to show in the pin callout images = [UIImage(named: "s1")!, UIImage(named: "s2")!, UIImage(named: "s3")!, UIImage(named: "s4")!, UIImage(named: "s5")!, UIImage(named: "s6")!, UIImage(named: "s7")!, UIImage(named: "s8")!,UIImage(named: "s9")!,UIImage(named: "s10")!,UIImage(named: "s11")!,UIImage(named: "s12")!,UIImage(named: "s13")!] // Latitudes, Longitudes coordinates = [ [56.00, 60.00], [55.00 , 49.00], [55.00 , 37.00], [55.00 , 37.00], [60.00 , 30.00], [55.00 , 37.00], [43.00 , 40.00], [49.00 , 44.00], [56.00 , 44.00], [47.00 , 39.00], [53.00 , 50.00], [54.00 , 45.00], [54.00 , 20.00] ] currentRestaurantIndex = 0 // Ask for user permission to access location infos locationManager = CLLocationManager() locationManager.requestWhenInUseAuthorization() // Show the user current location mapView.showsUserLocation = true mapView.delegate = self } //MARK: MKMapViewDelegate func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) { let region = MKCoordinateRegion(center: self.mapView.userLocation.coordinate, span: MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)) mapView.setRegion(region, animated: true) } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { // If annotation is not of type RestaurantAnnotation (MKUserLocation types for instance), return nil if !(annotation is StadiumAnnotation){ return nil } var annotationView = self.mapView.dequeueReusableAnnotationView(withIdentifier: "Pin") if annotationView == nil{ annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "Pin") annotationView?.canShowCallout = true }else{ annotationView?.annotation = annotation } let restaurantAnnotation = annotation as! StadiumAnnotation annotationView?.detailCalloutAccessoryView = UIImageView(image: restaurantAnnotation.image) // Left Accessory let leftAccessory = UILabel(frame: CGRect(x: 0,y: 0,width: 50,height: 30)) leftAccessory.text = restaurantAnnotation.eta leftAccessory.font = UIFont(name: "Verdana", size: 14) annotationView?.leftCalloutAccessoryView = leftAccessory // Right accessory view let image = UIImage(named: "bus.png") let button = UIButton(type: .custom) button.frame = CGRect(x: 0, y: 0, width: 30, height: 30) button.setImage(image, for: UIControlState()) annotationView?.rightCalloutAccessoryView = button return annotationView } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { let placemark = MKPlacemark(coordinate: view.annotation!.coordinate, addressDictionary: nil) // The map item is the restaurant location let mapItem = MKMapItem(placemark: placemark) let launchOptions = [MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeTransit] mapItem.openInMaps(launchOptions: launchOptions) } //SHowing all stadiums @IBAction func nextStadium(_ sender: Any) { // 1 if currentRestaurantIndex > names.count - 1{ currentRestaurantIndex = 0 } // 2 let coordinate = coordinates[currentRestaurantIndex] as! [Double] let latitude: Double = coordinate[0] let longitude: Double = coordinate[1] let locationCoordinates = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) var point = StadiumAnnotation(coordinate: locationCoordinates) point.title = names[currentRestaurantIndex] point.image = images[currentRestaurantIndex] // 3 // Calculate Transit ETA Request let request = MKDirectionsRequest() /* Source MKMapItem */ let sourceItem = MKMapItem(placemark: MKPlacemark(coordinate: mapView.userLocation.coordinate, addressDictionary: nil)) request.source = sourceItem /* Destination MKMapItem */ let destinationItem = MKMapItem(placemark: MKPlacemark(coordinate: locationCoordinates, addressDictionary: nil)) request.destination = destinationItem request.requestsAlternateRoutes = false // Looking for Transit directions, set the type to Transit request.transportType = .transit // Center the map region around the restaurant coordinates mapView.setCenter(locationCoordinates, animated: true) // You use the MKDirectionsRequest object constructed above to initialise an MKDirections object let directions = MKDirections(request: request) directions.calculateETA { (etaResponse, error) -> Void in if let error = error { print("Error while requesting ETA : \(error.localizedDescription)") point.eta = error.localizedDescription }else{ point.eta = "\(Int((etaResponse?.expectedTravelTime)!/60)) min" } // 4 var isExist = false for annotation in self.mapView.annotations{ if annotation.coordinate.longitude == point.coordinate.longitude && annotation.coordinate.latitude == point.coordinate.latitude{ isExist = true point = annotation as! StadiumAnnotation } } if !isExist{ self.mapView.addAnnotation(point) } self.mapView.selectAnnotation(point, animated: true) self.currentRestaurantIndex += 1 } } } <file_sep>// // ButeurViewCell.swift // iosProject // // Created by <NAME> on 23/04/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class ButeurViewCell: UITableViewCell { @IBOutlet weak var nomButeur: UILabel! @IBOutlet weak var nombreButButeur: UILabel! @IBOutlet weak var clubButeur: UILabel! } <file_sep>// // CustomImage.swift // iosProject // // Created by <NAME> on 03/05/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit @IBDesignable class CustomImage: UIImageView { @IBInspectable var cornerRadius : CGFloat = 0 { didSet{ layer.cornerRadius = cornerRadius } } @IBInspectable var borderWidth: CGFloat = 0 { didSet{ layer.borderWidth = borderWidth } } @IBInspectable var borderColor: CGColor = UIColor.black.cgColor { didSet{ layer.borderColor = borderColor } } } <file_sep>// // CustonCalendarCell.swift // iosProject // // Created by <NAME> on 14/04/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class CustonCalendarCell: UITableViewCell { @IBOutlet weak var heureMatch: UILabel! @IBOutlet weak var dateMatch: UILabel! @IBOutlet weak var stadeName: UILabel! @IBOutlet weak var cellView: UIView! @IBOutlet weak var nameeq1: UILabel! @IBOutlet weak var nameeq2: UILabel! @IBOutlet weak var eq1: UIImageView! @IBOutlet weak var eq2: UIImageView! } <file_sep>// // JoueurViewCell.swift // iosProject // // Created by <NAME> on 19/04/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class JoueurViewCell: UITableViewCell { @IBOutlet weak var joueurName: UILabel! @IBOutlet weak var posteJoueur: UILabel! } <file_sep>// // CalendarController.swift // iosProject // // Created by <NAME> on 25/03/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import SDWebImage import Alamofire import CoreData class CalendarController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var dateLabelOutlet: UILabel! @IBOutlet weak var hourLabel: UILabel! @IBOutlet weak var imge: UIImageViewX! @IBOutlet weak var minLabel: UILabel! @IBOutlet weak var secLabel: UILabel! @IBOutlet weak var calenderTableView: UITableView! let currentDate = Date() let dateFormatter = DateFormatter() var G1Liste = [AnyObject]() let userCalendar = Calendar.current var selectedSegment = 1 let requestedComponent: Set<Calendar.Component> = [.day,.hour,.minute,.second] var favArray : [String] = [] var dateMatch = "" var heureMatch = "" var equipe1 = "" var equipe2 = "" var selectedMatch = "" let URL_USER_LOGIN = String(AppDelegate.adresseIP)+"AndroidBD/teams.php" override func viewDidLoad() { super.viewDidLoad() imge.addBlur() let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(printTime), userInfo: nil, repeats: true) timer.fire() let parameters: Parameters=["id": 1] Alamofire.request(URL_USER_LOGIN, method: .post, parameters: parameters).responseJSON { response in //printing response print(response) //getting the json value from the server let result = response.result //getting the user from response if let groups = result.value as? Dictionary<String,AnyObject>{ if let inner=groups["matchs"]{ self.G1Liste = inner as! [AnyObject] self.calenderTableView.reloadData() } } } } @objc func printTime() { dateFormatter.dateFormat = "dd/MM/yy hh:mm:ss" let startTime = Date() let endTime = dateFormatter.date(from: "14/06/2018 00:4:00") let timeDifference = userCalendar.dateComponents(requestedComponent, from: startTime, to: endTime!) dateLabelOutlet.text = "\(timeDifference.day!)" hourLabel.text = "\(timeDifference.hour!)" minLabel.text = "\(timeDifference.minute!)" secLabel.text = "\(timeDifference.second!)" } @IBAction func segmentedJourneeController(_ sender: UISegmentedControl) { if sender.selectedSegmentIndex == 0 { selectedSegment = 1 selectPool(id: selectedSegment) } else if sender.selectedSegmentIndex == 1{ selectedSegment = 2 selectPool(id: selectedSegment) } else if sender.selectedSegmentIndex == 2{ selectedSegment = 3 selectPool(id: selectedSegment) } else if sender.selectedSegmentIndex == 3{ selectedSegment = 4 selectPool(id: selectedSegment) } else if sender.selectedSegmentIndex == 4{ selectedSegment = 5 selectPool(id: selectedSegment) } else if sender.selectedSegmentIndex == 5{ selectedSegment = 6 selectPool(id: selectedSegment) } else if sender.selectedSegmentIndex == 6{ selectedSegment = 7 selectPool(id: selectedSegment) } else if sender.selectedSegmentIndex == 7{ selectedSegment = 8 selectPool(id: selectedSegment) } self.calenderTableView.reloadData() } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = calenderTableView.dequeueReusableCell(withIdentifier: "CalendarCell") as! CustonCalendarCell // cell.cellView.layer.cornerRadius = cell.cellView.frame.height / 2 cell.eq1.layer.cornerRadius = cell.eq1.frame.height / 2 cell.eq2.layer.cornerRadius = cell.eq2.frame.height / 2 cell.eq1.sd_setImage(with: URL(string: (G1Liste[indexPath.row]["drapeau1"] as? String)!)) cell.eq2.sd_setImage(with: URL(string: (G1Liste[indexPath.row]["drapeau2"] as? String)!)) cell.stadeName.text = G1Liste[indexPath.row]["date_match"] as? String cell.nameeq1.text = G1Liste[indexPath.row]["equipe1"] as? String cell.nameeq2.text = G1Liste[indexPath.row]["equipe2"] as? String cell.heureMatch.text = G1Liste[indexPath.row]["heure_match"] as? String return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return G1Liste.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 80 } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "toDetailMatch"{ if let controller = segue.destination as? DetailControllerViewController, let indexPath = calenderTableView.indexPathForSelectedRow { controller.image = (G1Liste[indexPath.row]["drapeau1"] as? String)! controller.imageEquipe = (G1Liste[indexPath.row]["drapeau2"] as? String)! controller.labelDate = (G1Liste[indexPath.row]["date_match"] as? String)! controller.labelHeure = (G1Liste[indexPath.row]["heure_match"] as? String)! controller.labelEq1 = (G1Liste[indexPath.row]["equipe1"] as? String)! controller.labelEq2 = (G1Liste[indexPath.row]["equipe2"] as? String)! controller.labelStade = (G1Liste[indexPath.row]["stades"] as? String)! } } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectedMatch = (G1Liste[indexPath.row]["date_match"] as? String)! performSegue(withIdentifier: "toDetailMatch", sender: nil) } func selectPool(id : Int){ let URL_USER_LOGIN = String(AppDelegate.adresseIP)+"AndroidBD/teams.php" let parameters: Parameters=["id": id] Alamofire.request(URL_USER_LOGIN, method: .post, parameters: parameters).responseJSON { response in //printing response print(response) //getting the json value from the server let result = response.result //getting the user from response if let groups = result.value as? Dictionary<String,AnyObject>{ if let inner=groups["matchs"]{ self.G1Liste = inner as! [AnyObject] self.calenderTableView.reloadData() } } } } } protocol Bluring { func addBlur(_ alpha: CGFloat) } extension Bluring where Self: UIView { func addBlur(_ alpha: CGFloat = 0.75) { // create effect let effect = UIBlurEffect(style: .light) let effectView = UIVisualEffectView(effect: effect) // set boundry and alpha effectView.frame = self.bounds effectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] effectView.alpha = alpha self.addSubview(effectView) } } extension UIView: Bluring {} <file_sep>platform :ios, '9.0' source 'https://github.com/CocoaPods/Specs.git' target 'iosProject' do use_frameworks! pod 'Alamofire', '4.4.0' pod 'SDWebImage', '~> 4.0' pod 'GoogleMaps' pod 'GooglePlaces' pod ‘Firebase/Core’ pod ‘Firebase/Messaging’ end <file_sep>World Cup Russia 2018 : est une application iOS permettant la veille sur les actualités de la coupe du monde 2018. <file_sep>// // ScrollViewController.swift // iosProject // // Created by <NAME> on 13/04/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import AVFoundation class ScrollViewController: UIViewController, UIScrollViewDelegate { @IBOutlet weak var textView: UITextView! @IBOutlet weak var startButton: UIButton! @IBOutlet weak var pageControl: UIPageControl! @IBOutlet weak var scrollView: UIScrollView! var welcomeMusic : AVAudioPlayer? override func viewDidLoad() { super.viewDidLoad() let path = Bundle.main.path(forResource: "welcomeMusic.mp3", ofType:nil)! let url = URL(fileURLWithPath: path) let delay = max(0.0, 7.0) do { welcomeMusic = try AVAudioPlayer(contentsOf: url) welcomeMusic?.play() DispatchQueue.main.asyncAfter(deadline: .now() + delay) { self.welcomeMusic?.stop() } } catch { // couldn't load file :( } self.scrollView.frame = CGRect(x:0, y:0, width:self.view.frame.width, height:self.view.frame.height) let scrollViewWidth:CGFloat = self.scrollView.frame.width let scrollViewHeight:CGFloat = self.scrollView.frame.height //2 textView.textAlignment = .center textView.text = "World Cup Russia 2018" textView.textColor = UIColor.white self.startButton.layer.cornerRadius = 4.0 //3 let imgOne = UIImageView(frame: CGRect(x:0, y:0,width:scrollViewWidth, height:scrollViewHeight)) imgOne.image = UIImage(named: "fifa1") let imgTwo = UIImageView(frame: CGRect(x:scrollViewWidth, y:0,width:scrollViewWidth, height:scrollViewHeight)) imgTwo.image = UIImage(named: "fifa2") let imgThree = UIImageView(frame: CGRect(x:scrollViewWidth*2, y:0,width:scrollViewWidth, height:scrollViewHeight)) imgThree.image = UIImage(named: "fifa3") let imgFour = UIImageView(frame: CGRect(x:scrollViewWidth*3, y:0,width:scrollViewWidth, height:scrollViewHeight)) imgFour.image = UIImage(named: "fifa4") self.scrollView.addSubview(imgOne) self.scrollView.addSubview(imgTwo) self.scrollView.addSubview(imgThree) self.scrollView.addSubview(imgFour) //4 self.scrollView.contentSize = CGSize(width:self.scrollView.frame.width * 4, height:self.scrollView.frame.height) self.scrollView.delegate = self self.pageControl.currentPage = 0 // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView){ // Test the offset and calculate the current page after scrolling ends let pageWidth:CGFloat = scrollView.frame.width let currentPage:CGFloat = floor((scrollView.contentOffset.x-pageWidth/2)/pageWidth)+1 // Change the indicator self.pageControl.currentPage = Int(currentPage); textView.font = UIFont.boldSystemFont(ofSize: 30) startButton.setTitleColor(.white, for: .normal) // Change the text accordingly if Int(currentPage) == 0{ textView.text = "World Cup Russia 2018" }else if Int(currentPage) == 1{ textView.text = "Who is the winner ?" }else if Int(currentPage) == 2{ textView.text = "2018 FIFA World Cup Tickets: Official Partner" }else{ textView.text = "Russia World Cup 2018" UIView.animate(withDuration: 1.0, animations: { () -> Void in self.startButton.alpha = 1.0 }) } } } <file_sep>// // Actuality.swift // iosProject // // Created by <NAME> on 13/04/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class Actuality: NSObject { var title : String? var desc : String? var url : String? var urlImg : String? } <file_sep>// // ActualityCell.swift // iosProject // // Created by <NAME> on 14/04/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class ActualityCell: UITableViewCell { @IBOutlet weak var imageCell: UIImageView! @IBOutlet weak var titleCell: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } <file_sep> import UIKit import Alamofire class ClassementButeurController: UIViewController, UITableViewDataSource, UITableViewDelegate { var selectedSegment = 1 @IBOutlet weak var buteurTable: UITableView! let URL_USER_LOGIN = String(AppDelegate.adresseIP)+"AndroidBD/joueurParBut.php" var buteurListe = [AnyObject]() override func viewDidLoad() { super.viewDidLoad() buteurTable.delegate = self buteurTable.dataSource = self Alamofire.request(URL_USER_LOGIN, method: .post, parameters: nil).responseJSON { response in //printing response print(response) //getting the json value from the server let result = response.result //getting the user from response if let groups = result.value as? Dictionary<String,AnyObject>{ if let inner=groups["joueurs"]{ self.buteurListe = inner as! [AnyObject] self.buteurTable.reloadData() } } } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = buteurTable.dequeueReusableCell(withIdentifier: "buteurCell") as! ButeurViewCell cell.nomButeur.text = buteurListe[indexPath.row]["nom_joueur"] as? String cell.clubButeur.text = buteurListe[indexPath.row]["Club"] as? String if selectedSegment == 1 { cell.nombreButButeur.text = (buteurListe[indexPath.row]["nb_but"] as? String)!+" Goals" }else { cell.nombreButButeur.text = (buteurListe[indexPath.row]["nb_but"] as? String)!+" /10" } return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return buteurListe.count } @IBAction func SegmentedValueChanged(_ sender: UISegmentedControl) { if sender.selectedSegmentIndex == 0 { selectedSegment = 1 selectButeur() } else if sender.selectedSegmentIndex == 1{ selectedSegment = 2 selectRating() } self.buteurTable.reloadData() } func selectRating(){ let URL_USER_LOGIN = String(AppDelegate.adresseIP)+"AndroidBD/ratingJoueur.php" Alamofire.request(URL_USER_LOGIN, method: .post, parameters: nil).responseJSON { response in //printing response print(response) //getting the json value from the server let result = response.result //getting the user from response if let groups = result.value as? Dictionary<String,AnyObject>{ if let inner=groups["ratings"]{ self.buteurListe = inner as! [AnyObject] self.buteurTable.reloadData() } } } } func selectButeur(){ let URL_USER_LOGIN = String(AppDelegate.adresseIP)+"AndroidBD/joueurParBut.php" Alamofire.request(URL_USER_LOGIN, method: .post, parameters: nil).responseJSON { response in //printing response print(response) //getting the json value from the server let result = response.result //getting the user from response if let groups = result.value as? Dictionary<String,AnyObject>{ if let inner=groups["joueurs"]{ self.buteurListe = inner as! [AnyObject] self.buteurTable.reloadData() } } } } } <file_sep>// // CustomStadiumCell.swift // iosProject // // Created by <NAME> on 26/03/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class CustomStadiumCell: UICollectionViewCell { @IBOutlet weak var stadiumImage: UIImageView! @IBOutlet weak var stadiumName: UILabel! } <file_sep>// // MapStadiumController.swift // iosProject // // Created by <NAME> on 27/03/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class MapStadiumController: UIViewController { @IBOutlet weak var stadiumImg: UIImageView! @IBOutlet weak var stadiumName: UILabel! @IBOutlet weak var stadiumDesc: UILabel! @IBOutlet weak var equipeRes: UILabel! @IBOutlet weak var capacite: UILabel! var image = String() var titleStadium = "" var descStadium = "" var capaciteStadium = "" var equipeStadium = "" var longitude = "" var latitude = "" var lat = Int() var long = Int() override func viewDidLoad() { LoadingOverlay.shared.showProgressView(view) let delay = max(0.0, 1.0) DispatchQueue.main.asyncAfter(deadline: .now() + delay) { LoadingOverlay.shared.hideProgressView() } super.viewDidLoad() stadiumImg.sd_setImage(with: URL(string: (image)), placeholderImage: UIImage(named: "tunisie")) stadiumName.text! = titleStadium stadiumDesc.text! = descStadium equipeRes.text! = equipeStadium capacite.text! = capaciteStadium lat = Int(latitude)! long = Int(longitude)! } @IBAction func visitStadium(_ sender: Any) { } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "visitStadium"{ if let destinationVC = segue.destination as? MapsViewController { destinationVC.latitude = lat destinationVC.longitude = long destinationVC.nameStadium = titleStadium } } } } <file_sep>import UIKit import MapKit class StadiumAnnotation: NSObject, MKAnnotation { var coordinate: CLLocationCoordinate2D var title: String? var image: UIImage? var eta: String? init(coordinate: CLLocationCoordinate2D) { self.coordinate = coordinate } } <file_sep>// // TeamViewController.swift // iosProject // // Created by <NAME> on 15/04/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class TeamViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate{ var listofAfriqueTeams = [Team]() var listofEuropeTeams = [Team]() var listofAsieTeams = [Team]() var listofSouthTeams = [Team]() var listofCaribbeanTeams = [Team]() var currentTeam = [Team]() var currentTeam1 = [Team]() var currentTeam2 = [Team]() var currentTeam3 = [Team]() var currentTeam4 = [Team]() var TeamContinent = ["Europe", "Afrique", "Asie", "South America", "North And Central Caribbean"] @IBOutlet weak var tableListTeams: UITableView! @IBOutlet weak var searchBar: UISearchBar! override func viewDidLoad() { super.viewDidLoad() SetUpSearchBar() listofAfriqueTeams.append(Team(name: "Tunisie", coupeNumb: "0", image: "tun")) listofAfriqueTeams.append(Team(name: "Senegal", coupeNumb: "0" , image: "sen")) listofAfriqueTeams.append(Team(name: "Nigeria", coupeNumb: "0", image: "nga")) listofAfriqueTeams.append(Team(name: "Maroc", coupeNumb: "0", image: "mar")) listofEuropeTeams.append(Team(name: "Belgique", coupeNumb: "0" , image: "bel")) listofEuropeTeams.append(Team(name: "Croatie", coupeNumb: "0", image: "cro")) listofEuropeTeams.append(Team(name: "Denmark", coupeNumb: "0", image: "den")) listofEuropeTeams.append(Team(name: "England", coupeNumb: "1" , image: "eng")) listofEuropeTeams.append(Team(name: "France", coupeNumb: "1", image: "fra")) listofEuropeTeams.append(Team(name: "Germany", coupeNumb: "3", image: "ger")) listofEuropeTeams.append(Team(name: "Iceland", coupeNumb: "0" , image: "isl")) listofEuropeTeams.append(Team(name: "Pologne", coupeNumb: "0", image: "pol")) listofEuropeTeams.append(Team(name: "Portugal", coupeNumb: "0", image: "por")) listofEuropeTeams.append(Team(name: "Russia", coupeNumb: "0" , image: "rus")) listofEuropeTeams.append(Team(name: "Serbia", coupeNumb: "0", image: "srb")) listofEuropeTeams.append(Team(name: "Espagne", coupeNumb: "1", image: "esp")) listofEuropeTeams.append(Team(name: "Sweden", coupeNumb: "0" , image: "swe")) listofEuropeTeams.append(Team(name: "Suisse", coupeNumb: "0", image: "sui")) listofAsieTeams.append(Team(name: "Australie", coupeNumb: "0", image: "aus")) listofAsieTeams.append(Team(name: "Iran", coupeNumb: "0" , image: "irn")) listofAsieTeams.append(Team(name: "Japan", coupeNumb: "0", image: "jpn")) listofAsieTeams.append(Team(name: "Korea", coupeNumb: "0", image: "kor")) listofAsieTeams.append(Team(name: "Saudia Arabia", coupeNumb: "0" , image: "ksa")) listofSouthTeams.append(Team(name: "Argentina", coupeNumb: "2", image: "arg")) listofSouthTeams.append(Team(name: "Brazil", coupeNumb: "5", image: "bra")) listofSouthTeams.append(Team(name: "Colombie", coupeNumb: "0" , image: "col")) listofSouthTeams.append(Team(name: "Uruguay", coupeNumb: "2", image: "uru")) listofSouthTeams.append(Team(name: "Peru", coupeNumb: "0", image: "per")) listofCaribbeanTeams.append(Team(name: "Panama", coupeNumb: "0" , image: "pan")) listofCaribbeanTeams.append(Team(name: "Mexique", coupeNumb: "0", image: "mex")) listofCaribbeanTeams.append(Team(name: "Costa Rica", coupeNumb: "0", image: "crc")) tableListTeams.delegate = self tableListTeams.dataSource = self currentTeam = listofEuropeTeams currentTeam1 = listofAfriqueTeams currentTeam2 = listofAsieTeams currentTeam3 = listofSouthTeams currentTeam4 = listofCaribbeanTeams } private func SetUpSearchBar(){ searchBar.delegate = self } func numberOfSections(in tableView: UITableView) -> Int { return 5 } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return TeamContinent[section] } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return UITableViewAutomaticDimension } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0{ return currentTeam.count } else if section == 1 { return currentTeam1.count } else if section == 2 { return currentTeam2.count } else if section == 3 { return currentTeam3.count } else { return currentTeam4.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellTeam:CustomTeamCell = tableView.dequeueReusableCell(withIdentifier: "cellTeam", for: indexPath) as! CustomTeamCell if indexPath.section == 0 { cellTeam.SetTeam(team: currentTeam[indexPath.row]) } else if indexPath.section == 1{ cellTeam.SetTeam(team: currentTeam1[indexPath.row]) } else if indexPath.section == 2 { cellTeam.SetTeam(team: currentTeam2[indexPath.row]) } else if indexPath.section == 3 { cellTeam.SetTeam(team: currentTeam3[indexPath.row]) } else { cellTeam.SetTeam(team: currentTeam4[indexPath.row]) } return cellTeam } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { guard !searchText.isEmpty else { currentTeam = listofEuropeTeams; currentTeam1 = listofAfriqueTeams; currentTeam2 = listofAsieTeams; currentTeam3 = listofSouthTeams; currentTeam4 = listofCaribbeanTeams; tableListTeams.reloadData() return } currentTeam = listofEuropeTeams.filter({ team -> Bool in return team.name!.contains(searchText) }) currentTeam1 = listofAfriqueTeams.filter({ team -> Bool in return team.name!.contains(searchText) }) currentTeam2 = listofAsieTeams.filter({ team -> Bool in return team.name!.contains(searchText) }) currentTeam3 = listofSouthTeams.filter({ team -> Bool in return team.name!.contains(searchText) }) currentTeam4 = listofCaribbeanTeams.filter({ team -> Bool in return team.name!.contains(searchText) }) tableListTeams.reloadData() } func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } <file_sep>// // StadiumController.swift // iosProject // // Created by <NAME> on 25/03/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import SDWebImage import Alamofire class StadiumController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource{ @IBOutlet weak var stadiumCollectionView: UICollectionView! let stadiumArray = ["stadium1", "stadium2", "stadium3"] let URL_USER_LOGIN = String(AppDelegate.adresseIP)+"AndroidBD/stades.php" var stadiumListe = [AnyObject]() override func viewDidLoad() { super.viewDidLoad() LoadingOverlay.shared.showProgressView(view) let delay = max(0.0, 1.0) DispatchQueue.main.asyncAfter(deadline: .now() + delay) { LoadingOverlay.shared.hideProgressView() } stadiumCollectionView.delegate = self stadiumCollectionView.dataSource = self Alamofire.request(URL_USER_LOGIN, method: .post, parameters: nil).responseJSON { response in //printing response print(response) //getting the json value from the server let result = response.result //getting the user from response if let actualities = result.value as? Dictionary<String,AnyObject>{ if let inner=actualities["stadiums"]{ self.stadiumListe = inner as! [AnyObject] self.stadiumCollectionView.reloadData() } } } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return stadiumListe.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = stadiumCollectionView.dequeueReusableCell(withReuseIdentifier: "stadiumCell", for: indexPath) as! CustomStadiumCell cell.stadiumImage.sd_setImage(with: URL(string: (stadiumListe[indexPath.row]["image"] as? String)!), placeholderImage: UIImage(named: "coupedumonde")) cell.stadiumName.text = stadiumListe[indexPath.row]["nom_stade"] as? String return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let mainStoryBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let desVC = mainStoryBoard.instantiateViewController(withIdentifier: "MapStadiumController") as! MapStadiumController desVC.image = (stadiumListe[indexPath.row]["image"] as? String)! desVC.titleStadium = (stadiumListe[indexPath.row]["nom_stade"] as? String)! desVC.descStadium = (stadiumListe[indexPath.row]["description"] as? String)! desVC.capaciteStadium = (stadiumListe[indexPath.row]["nombre_spec"] as? String)! desVC.equipeStadium = (stadiumListe[indexPath.row]["equipe_res"] as? String)! desVC.longitude = (stadiumListe[indexPath.row]["longitude"] as? String)! desVC.latitude = (stadiumListe[indexPath.row]["latitude"] as? String)! self.navigationController?.pushViewController(desVC, animated: true) } } <file_sep>// // LoadingOverlay.swift // FastRide // // Created by s on 18/04/2018. // import Foundation import UIKit open class LoadingOverlay { var containerView = UIView() var progressView = UIView() var activityIndicator = UIActivityIndicatorView() open class var shared: LoadingOverlay { struct Static { static let instance: LoadingOverlay = LoadingOverlay() } return Static.instance } open func showProgressView(_ view: UIView) { containerView.frame = view.frame containerView.center = view.center containerView.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) progressView.frame = CGRect(x: 0, y: 0, width: containerView.widthAnchor.hashValue, height: containerView.heightAnchor.hashValue) progressView.center = view.center progressView.backgroundColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1) progressView.clipsToBounds = true progressView.layer.cornerRadius = 10 activityIndicator.frame = CGRect(x: 0, y: 0, width: 80, height: 80) activityIndicator.activityIndicatorViewStyle = .whiteLarge activityIndicator.center = CGPoint(x: progressView.bounds.width / 2, y:progressView.bounds.height / 2) progressView.addSubview(activityIndicator) containerView.addSubview(progressView) view.addSubview(containerView) activityIndicator.startAnimating() } public func hideProgressView() { activityIndicator.stopAnimating() containerView.removeFromSuperview() } } <file_sep>// // CustomTeamCell.swift // iosProject // // Created by <NAME> on 15/04/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class CustomTeamCell: UITableViewCell { @IBOutlet weak var eqImage: UIImageView! @IBOutlet weak var eqName: UILabel! @IBOutlet weak var coupeNumber: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } func SetTeam(team:Team) { self.eqName.text = team.name! self.coupeNumber.text = team.coupeNumb! self.eqImage.image = UIImage(named: team.image!) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } <file_sep> // // CustomCollectionViewCell.swift // iosProject // // Created by <NAME> on 25/03/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class CustomCollectionViewCell: UICollectionViewCell { } <file_sep>// // CustomizeAlerte.swift // iosProject // // Created by <NAME> on 03/05/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit extension UIAlertController { func addImage(image : UIImage) { let maxSize = CGSize(width : 135, height : 190) let imageSize = image.size var ratio : CGFloat! if (imageSize.width > imageSize.height){ ratio = maxSize.width / imageSize.width } else { ratio = maxSize.height / imageSize.height } let scaledSize = CGSize(width : imageSize.width * ratio, height : imageSize.height * ratio) var resizedImage = image.imageWithSize(scaledSize) if(imageSize.height > imageSize.width){ let left = (maxSize.width - resizedImage.size.width) / 2 resizedImage = resizedImage.withAlignmentRectInsets(UIEdgeInsetsMake(0, -left, 0, 0)) } let imgAlerte = UIAlertAction(title : "", style : .default, handler : nil) imgAlerte.isEnabled = false imgAlerte.setValue(resizedImage.withRenderingMode(.alwaysOriginal), forKey: "image") self.addAction(imgAlerte) } }
3cb1694a4b7ecc1fbc7b1b11966efd89839fba3a
[ "Swift", "Ruby", "Markdown" ]
30
Swift
karimslim/iosProjectFinal
d61bfcb4ea876cbcec67d5c7ab79ba5c70d1969a
152f8d9b70ca16ac16c9628567702bf37f5b02be
refs/heads/master
<file_sep>wanted all my settings in one place <file_sep> # MacPorts Installer addition on 2011-05-05_at_14:02:00: adding an appropriate PATH variable for use with MacPorts. export PATH=/opt/local/bin:/opt/local/sbin:$PATH export PATH=/Users/seanchan/Android/platform-tools:$PATH # Finished adapting your PATH environment variable for use with MacPorts. alias ls='ls -G' alias curl='/usr/local/bin/curl' [[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm" # This loads RVM into a shell session. # Set git autocompletion and PS1 integration if [ -f /usr/local/git/contrib/completion/git-completion.bash ]; then . /usr/local/git/contrib/completion/git-completion.bash fi GIT_PS1_SHOWDIRTYSTATE=true if [ -f /opt/local/etc/bash_completion ]; then . /opt/local/etc/bash_completion fi GREEN="\[\033[32m\]" RED="\[\033[31m\]" YELLOW="\[\033[33m\]" CYAN="\[\033[36m\]" NO_COLOR="\[\033[00m\]" PS1="$GREEN\u@SeansMBP$NO_COLOR:$CYAN\W$RED\$(__git_ps1)$NO_COLOR\$ " EUPHROSYNE_ROOT='/Applications/AMPPS/www/euphrosyne'
8df83a27faa26e7fe7ce87c77e1d08833510aa91
[ "Markdown", "Shell" ]
2
Markdown
seanfchan/Settings
5be5d9a946c282aa777cc65e685bc950506675be
b7beaa94449f1ecad8d4df50daf93e121c9d7e9f