branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>const express = require('express'); const app = express(); const path = require('path'); // const db = require('./models') // const exphbs = require('express-handlebars'); const PORT = process.env.PORT || 3000; let manatees = [ { name:'steve', color:'grey', favoriteFood: 'seagrass' }, { name:'bob', color:'differnt grey', favoriteFood: 'other seagrass' } ] // app.engine('handlebars', exphbs({ defaultLayout: 'main' })); // app.set('view engine', 'handlebars'); app.use(express.urlencoded({ extended: true })); app.use(express.json()); // app.use('/', express.static(__dirname + '/static')); app.get('/',function(req,res){ res.sendFile(path.join(__dirname, 'views/home.html')); }) app.get('/manatee',function(req,res){ res.sendFile(path.join(__dirname, 'views/manatee.html')); }) //add new manatee to the array app.post('/manatee',function(req,res){ newManateeObj = { name:req.body.name, color:req.body.color, favoriteFood:req.body.favoriteFood } manatees.push(newManateeObj); res.json(manatees); }) app.listen(PORT);
8de66c3fc02011f328d6704167543738f894c2c0
[ "JavaScript" ]
1
JavaScript
Rufasa85/manateePicsExpress
6c4d7e716c4b44b098bec278443c7ae83481cd19
93bc680fef43cf2d19e387154b0f8576c6b76b7a
refs/heads/master
<file_sep>import { createStore, applyMiddleware } from 'redux'; import createSagaMiddleware from 'redux-saga'; import rootReducer from './reducers'; import * as actions from './actions'; import * as sagas from './sagas'; import * as selectors from './selectors'; const sagaMiddleware = createSagaMiddleware(); const configureStore = (initialState = {}, optionalMiddlewares = []) => ({ ...createStore( rootReducer, initialState, applyMiddleware(...optionalMiddlewares, sagaMiddleware) ), runSaga: sagaMiddleware.run }); export { rootReducer, actions, sagas, selectors, configureStore }; <file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux'; import { selectors } from 'app/stores'; import ArticleList from './ArticleList'; class App extends Component { articleActions = { getAuthorByAuthorId: authorId => this.props.authorById(authorId) }; render() { return ( <ArticleList articles={ this.props.articles } articleActions={ this.articleActions } /> ); } } const mapStateToProps = state => { const { demoDataSelectors: { getArticles, getAuthors, getAuthorByAuthorId } } = selectors; return { articles: getArticles(state), authors: getAuthors(state), authorById: authorId => getAuthorByAuthorId(state, authorId) }; }; export default connect(mapStateToProps)(App); <file_sep>import axios from 'axios'; class ApiClient { async get( url = '', options = { params: {} } ) { try { const res = await axios.get(url, options); return res; } catch(err) { throw err; } } } export default ApiClient; <file_sep>import DEMO_DATA_ACTIONS from './demo-data.action'; export { DEMO_DATA_ACTIONS };<file_sep>import { combineReducers } from 'redux'; import demoDataReducer from './demo-data.reducer'; const rootReducer = combineReducers({ demoDataReducer }); export default rootReducer;<file_sep>import React from 'react'; import ReactDOMServer from 'react-dom/server'; import { Provider } from 'react-redux'; import App from 'app/components/App'; import { configureStore, actions, sagas } from 'app/stores'; const store = configureStore(); store.runSaga(sagas.demoDataSaga); store.dispatch(actions.DEMO_DATA_ACTIONS.fetchDemoData()); const serverRenderer = () => { const initialState = store.getState(); return { initializeMarkup: ReactDOMServer.renderToString( <Provider store={ store }> <App /> </Provider> ), initialState, title: 'Advanced React App' }; }; export default serverRenderer; <file_sep>import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import logger from 'redux-logger'; import App from 'app/components/App'; import { configureStore } from '../stores'; const initialState = window.__PRELOADED_STATE__ || { articles: [], authors: [] }; delete window.__PRELOADED_STATE__; const store = configureStore(initialState, [logger]); ReactDOM.hydrate( <Provider store={ store }> <App /> </Provider>, document.getElementById('root') ); <file_sep>import ApiClient from './api-client'; export { ApiClient }; <file_sep>import DEMO_DATA_ACTION_TYPES from 'app/stores/action-types/demo-data.action-type'; import demoDataInitialState from 'app/stores/states/demo-data.state'; function demoDataReducer(state = demoDataInitialState, action) { switch (action.type) { case DEMO_DATA_ACTION_TYPES.FETCH_DEMO_DATA_ACTION: return { ...state, isFetching: true, error: null }; case DEMO_DATA_ACTION_TYPES.FETCH_DEMO_DATA_ACTION_SUCCESS: return { ...state, isFetching: false, data: action.payload && action.payload.data }; case DEMO_DATA_ACTION_TYPES.FETCH_DEMO_DATA_ACTION_FAILURE: return { ...state, isFetching: false, error: action.payload && action.payload.error }; default: return state; } } export default demoDataReducer;<file_sep>import demoDataSaga from './demo-data.saga'; export { demoDataSaga };<file_sep>import { call, put, takeLatest } from 'redux-saga/effects'; import DEMO_DATA_ACTION_TYPES from 'app/stores/action-types/demo-data.action-type'; import { DemoDataService } from 'app/services'; const demoDataService = new DemoDataService(); function* demoDataSaga() { yield takeLatest(DEMO_DATA_ACTION_TYPES.FETCH_DEMO_DATA_ACTION, fetchDemoData); } function* fetchDemoData() { try { const demoData = yield call(demoDataService.fetchDemoData); yield put({ type: DEMO_DATA_ACTION_TYPES.FETCH_DEMO_DATA_ACTION_SUCCESS, payload: { data: demoData } }); } catch(err) { yield put({ type: DEMO_DATA_ACTION_TYPES.FETCH_DEMO_DATA_ACTION_FAILURE, payload: { error: err } }); } } export default demoDataSaga;<file_sep># leaning-advanced-react <file_sep>const demoDataInitialState = { isFetching: false, data: null, error: null }; export default demoDataInitialState;<file_sep>import React from 'react'; const convertShowingDate = dateStr => new Date(dateStr).toDateString(); const Article = props => { const { article, actions: { getAuthorByAuthorId } } = props; const author = (article && getAuthorByAuthorId(article.authorId)) || {}; return ( <div className="Article"> <div className="title">{ article.title }</div> <div className="timestamp"> { convertShowingDate(article.date) } </div> <div className="author"> <a href={ author.website }> { author.firstName } { author.lastName } </a> </div> <div className="body">{ article.body }</div> </div> ); }; export default Article; <file_sep>import { DataApi } from 'app/models'; import { testData as data } from 'app/raw-data'; const api = new DataApi(data); describe('DataApi', () => { it('exposes articles as an object', () => { const articles = api.fetchArticles(); const firstArticleId = data.articles[0].id; const firstArticleTitle = data.articles[0].title; expect(articles).toHaveProperty(firstArticleId); expect(articles[firstArticleId].title).toBe(firstArticleTitle); }); it('exposes authors as an object', () => { const authors = api.fetchAuthors(); const firstAuthorId = data.authors[0].id; const firstAuthorFirstName = data.authors[0].firstName; expect(authors).toHaveProperty(firstAuthorId); expect(authors[firstAuthorId].firstName).toBe(firstAuthorFirstName); }); }); <file_sep>import * as demoDataSelectors from './demo-data.selector'; export { demoDataSelectors };
55078ef0f89af2728c01fb43fd16da8435e78abc
[ "JavaScript", "Markdown" ]
16
JavaScript
nisil-thaing/leaning-advanced-react
919aa8391ae73fe0772a237e78108e4498c7ae54
0eb53d7d18b2db254083ad068cb593c5f0edc1ef
refs/heads/master
<file_sep>module.exports = [ { role: "harvester", roleMinimum: 2, taskMinimum: 0, body: [MOVE, MOVE, CARRY, CARRY, CARRY, CARRY, WORK, WORK, WORK], precedence: 8, startingMemory: { role: "harvester", task: "harvest" } }, { role: "builder", roleMinimum: 2, taskMinimum: 0, body: [MOVE, MOVE, CARRY, CARRY, CARRY, CARRY, WORK, WORK, WORK], precedence: 10, startingMemory: { role: "builder", task: "build", working: false } }, { role: "upgrader", roleMinimum: 1, taskMinimum: 1, body: [MOVE, MOVE, CARRY, CARRY, CARRY, CARRY, WORK, WORK, WORK], precedence: 9, startingMemory: { role: "upgrader", task: "upgrade", working: false } }, { role: "repairer", roleMinimum: 1, taskMinimum: 1, body: [MOVE, MOVE, CARRY, CARRY, CARRY, CARRY, WORK, WORK, WORK], precedence: 9, startingMemory: { role: "repairer", task: "repair", working: false } }, { role: "scouter", roleMinimum: 0, taskMinimum: 0, body: [MOVE, CLAIM], precedence: 15, startingMemory: { role: "scouter", task: "scout", scouting: false } } ]; <file_sep>moveOutOfTheWay = (creep) => { var sources = creep.room.find(FIND_FLAGS); creep.moveTo(sources[0], {visualizePathStyle: {stroke: '#ffaa00'}}); } harvestMinerals = (creep) => { var sources = creep.room.find(FIND_SOURCES); if(creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) { creep.moveTo(sources[0], {visualizePathStyle: {stroke: '#ffaa00'}}); } } mainSpawnIsAtFullCapacity = () => { return Game.spawns['MainSpawn'].energy == Game.spawns['MainSpawn'].energyCapacity } getNonFullExtensionsByCreep = (creep) => { var extensions = creep.room.find(FIND_MY_STRUCTURES); return extensions.filter((extension) => { return extension.energy != 50 && extension.structureType == STRUCTURE_EXTENSION }) } moveAndDepositEnergy = (creep, structure) => { if(creep.transfer(structure, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) { creep.moveTo(structure, {visualizePathStyle: {stroke: '#ffaa00'}}); } } getNumberOfHarvesters = () => { return _.filter(Game.creeps, (gameCreep) => { return gameCreep.memory.task == "harvest" }).length; } var roleHarvester = { run: function(creep, taskRequester) { if(creep.memory.working && creep.carry.energy == 0) { creep.memory.working = false; } if(!creep.memory.working && creep.carry.energy == creep.carryCapacity) { creep.memory.working = true; } if(!creep.memory.working) { harvestMinerals(creep) } else { // if the spawn is full, fill the extensions if(mainSpawnIsAtFullCapacity()) { let extensions = getNonFullExtensionsByCreep(creep) if(extensions.length) { moveAndDepositEnergy(creep, extensions[0]) } else { taskRequester.getTask(creep); } } // if the spawn is not full, fill the spawn first else { let depositStructure = Game.spawns['MainSpawn']; moveAndDepositEnergy(creep, depositStructure); } } } }; module.exports = roleHarvester;<file_sep>var roleHarvester = require('role.harvester'); var roleUpgrader = require('role.upgrader'); var roleBuilder = require('role.builder'); var roleRepairer = require('role.repairer'); var roleNothing = require('role.nothing'); var roleScouter = require('role.scouter'); var spawner = require('creep.spawner'); var taskRequester = require('task.requester'); module.exports.loop = function () { spawner.run(); taskRequester.getRoomState(); displaySpawningStatus(); for(var name in Game.creeps) { let creep = Game.creeps[name]; // every 5 seconds, reassign the creeps to do the most important task if (Game.time % 1 === 0) { taskRequester.getTask(creep) } // And start the creep working assignTask(creep); } } assignTask = (creep) => { if(creep.memory.task == 'harvest') { roleHarvester.run(creep, taskRequester); } if(creep.memory.task == 'upgrade') { roleUpgrader.run(creep, taskRequester); } if(creep.memory.task == 'build') { roleBuilder.run(creep, taskRequester); } if(creep.memory.task == 'repair') { roleRepairer.run(creep, taskRequester); } if(creep.memory.task == 'scout') { roleScouter.run(creep, taskRequester); } if(creep.memory.task == 'nothing') { roleNothing.run(creep, taskRequester); } } displaySpawningStatus = () => { if(Game.spawns['MainSpawn'].spawning) { var spawningCreep = Game.creeps[Game.spawns['MainSpawn'].spawning.name]; Game.spawns['MainSpawn'].room.visual.text( '🛠️' + spawningCreep.memory.role, Game.spawns['MainSpawn'].pos.x + 1, Game.spawns['MainSpawn'].pos.y, {align: 'left', opacity: 0.8}); } }<file_sep>var creepsToSpawn = require('creep.spawns') class TaskRequester { constructor() { this.vacantEnergySpaceInRoom = 0; this.objectsToConstruct = []; this.objectsToRepair = []; } // if the new task is different from the old one, check if the current number of workers for that task is above the minimum: // if it is, then you can assign the next task, // otherwise, keep it on it's own task getMinimumForTask(task) { for(var creepType in creepsToSpawn) { creepType = creepsToSpawn[creepType]; if(creepType.startingMemory.task == task) { return creepType.taskMinimum; } } } getRoomState() { this.vacantEnergySpaceInRoom = this.getTotalEnergyInRoom(); this.objectsToConstruct = this.getObjectsToConstruct(); this.objectsToRepair = this.getObjectsToRepair(); } getCreepsByTask(task) { return _.filter(Game.creeps, { memory: { task: task }}); } assignNewTask(creep, task) { // if the creep is being assigned a new task if(creep.memory.task != task) { // check if the current number of creeps doing the current task is greater than the minimum number of workers required for the current task if(this.getCreepsByTask(creep.memory.task).length > this.getMinimumForTask(creep.memory.task)) { // if it is greater, than the worker can safely change tasks creep.memory.task = task } } } getTask(creep) { if(this.vacantEnergySpaceInRoom != 0) { this.assignNewTask(creep, 'harvest') } else if (this.objectsToConstruct.length > 0) { this.assignNewTask(creep, 'build') } else if (this.objectsToRepair.length > 0) { this.assignNewTask(creep, 'repair') } else { this.assignNewTask(creep, 'upgrade') } } getTotalEnergyInRoom() { let spawnEnergy = Game.spawns['MainSpawn'].energyCapacity - Game.spawns['MainSpawn'].energy; var extensions = Game.spawns['MainSpawn'].room.find(FIND_MY_STRUCTURES).filter((extension) => { return extension.structureType == STRUCTURE_EXTENSION }); var vacantEnergyStorage = spawnEnergy; for(var extension in extensions) { extension = extensions[extension]; vacantEnergyStorage += extension.energyCapacity - extension.energy; } return vacantEnergyStorage; } getObjectsToConstruct() { var targets = Game.spawns['MainSpawn'].room.find(FIND_CONSTRUCTION_SITES); return targets; } getObjectsToRepair() { const targets = Game.spawns['MainSpawn'].room.find(FIND_STRUCTURES, { filter: object => object.hits < object.hitsMax }); return targets.sort((a,b) => a.hits - b.hits); } } module.exports = new TaskRequester();<file_sep>findFlags = (creep) => { var flag = Game.flags['Scout']; creep.moveTo(flag, {visualizePathStyle: {stroke: '#ffaa00'}}); } module.exports = { run(creep) { if(creep.memory.scouting) { findFlags(creep) } } }<file_sep>moveOutOfTheWay = (creep) => { var sources = creep.room.find(FIND_FLAGS); creep.moveTo(sources[0], {visualizePathStyle: {stroke: '#ffaa00'}}); } harvestMinerals = (creep) => { var sources = creep.room.find(FIND_SOURCES); if(creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) { creep.moveTo(sources[0], {visualizePathStyle: {stroke: '#ffaa00'}}); } } buildNearestObject = (creep) => { var targets = creep.room.find(FIND_CONSTRUCTION_SITES); if(targets.length) { if(creep.build(targets[0]) == ERR_NOT_IN_RANGE) { creep.moveTo(targets[0], {visualizePathStyle: {stroke: '#ffffff'}}); } } } thereAreConstructionSitesAvailable = (creep) => { let constructionSites = creep.room.find(FIND_CONSTRUCTION_SITES); return constructionSites.length != 0 } var roleBuilder = { run: function(creep, taskRequester) { if(creep.memory.working && creep.carry.energy == 0) { creep.memory.working = false; } if(!creep.memory.working && creep.carry.energy == creep.carryCapacity) { creep.memory.working = true; } if(thereAreConstructionSitesAvailable(creep)) { if(creep.memory.working) { buildNearestObject(creep); } else { harvestMinerals(creep); } } else { if(creep.memory.working) { taskRequester.getTask(creep); } else { if(creep.carry.energy < creep.carryCapacity) { harvestMinerals(creep); } else { taskRequester.getTask(creep); } } } } }; module.exports = roleBuilder;<file_sep>var creepsToSpawn = require('creep.spawns') spawnCreepIfNeeded = (creep) => { var creepsOfType = _.filter(Game.creeps, (gameCreep) => { return gameCreep.memory.role == creep.role }); if(creepsOfType.length < creep.roleMinimum) { if(Game.spawns["MainSpawn"].spawnCreep(creep.body, creep.role + Game.time, {memory: creep.startingMemory}) == OK) { console.log("Spawning creep: " + creep.role) } } } getCreepsSortedByPrecedence= () => { return creepsToSpawn.sort(compare) } compare = (a,b) => { if (a.precedence > b.precedence) return 1; if (a.precedence < b.precedence) return -1; return 0; } removeDeadCreepsFromMemory = () => { for(var name in Memory.creeps) { if(!Game.creeps[name]) { delete Memory.creeps[name]; console.log('Creep ' + name + " died..."); } } } module.exports = { run: function() { removeDeadCreepsFromMemory(); let creeps = getCreepsSortedByPrecedence(); for(let creep in creeps) { creep = creeps[creep]; spawnCreepIfNeeded(creep) } } };
de9d2959d7ef0b932bd90de108fd525607fddfde
[ "JavaScript" ]
7
JavaScript
McMainsLiam/Liam-Screeps
57739199796218519e7c52652aa373fb5830ab3a
3e410ee1d11d5a684dddd4dc91a69c9a4db3ea2e
refs/heads/master
<repo_name>oliviervanbulck/IoTHackTheFuture<file_sep>/tts.js /** * Created by olivier on 8/12/16. */ var SpeechToTextV1 = require('watson-developer-cloud/speech-to-text/v1'); var fs = require('fs'); var speech_to_text = new SpeechToTextV1({ username: 'a19c0feb-6802-4c57-bd2d-c5621e9f020a', password: '<PASSWORD>' }); var params = { // From file audio: fs.createReadStream('./uploads/file.wav'), content_type: 'audio/wav; rate=44100' }; speech_to_text.recognize(params, function(err, res) { if (err) console.log(err); else console.log(JSON.stringify(res, null, 2)); }); // or streaming /*fs.createReadStream('./resources/end.wav') .pipe(speech_to_text.createRecognizeStream({ content_type: 'audio/l16; rate=44100' })) .pipe(fs.createWriteStream('./transcription.txt'));*/
4449c58426ab31e45988b0f285df2ededa607990
[ "JavaScript" ]
1
JavaScript
oliviervanbulck/IoTHackTheFuture
d9ad4b17edd93c00a7fc91de45822196b626c828
e619cbc8a59a143e08941dad93dc25b04d120e32
refs/heads/master
<file_sep>// // Needle.swift // Truth-O-Meter // // Created by <NAME> on 02/09/2021. // import Foundation import GameKit /// for GKGaussianDistribution import SwiftUI class Needle: ObservableObject { /// The NeedleView uses @ObservedObject /// Views that change the value use the singleton, but do not use @ObservedObject /// to avoid invalidating these views when the needle value changes /// The class is implemented as singleton for easy access in these Views /// Using Environment Object was not a good option, because all views that use Needle /// would be invalidated on all value changes of Needle @Published private(set) var noisyValue: Double = 0.5 @Published private(set) var colorful = false /// singleton: private init and static shared object static var shared = Needle() private init() { } private var _value: Double = 0 private var needleNoiseTimer: Timer? private let distribution = GKGaussianDistribution(lowestValue: -100, highestValue: 100) private var strongNoise = false func setValue(_ newValue: Double) { _value = newValue DispatchQueue.main.async { self.noisyValue = newValue } } func setValueInSteps(_ newValue: Double, totalTime: Double) { self.active(true, strongNoise: true) let now = DispatchTime.now() var whenWhen: DispatchTime whenWhen = now + DispatchTimeInterval.milliseconds(Int(1000.0 * 0.25 * totalTime)) DispatchQueue.main.asyncAfter(deadline: whenWhen) { self.setValue(self._value + 0.3 * (newValue - self._value)) } whenWhen = now + DispatchTimeInterval.milliseconds(Int(1000.0 * 0.5 * totalTime)) DispatchQueue.main.asyncAfter(deadline: whenWhen) { self.setValue(self._value + 0.6 * (newValue - self._value)) } whenWhen = now + DispatchTimeInterval.milliseconds(Int(1000.0 * 0.675 * totalTime)) DispatchQueue.main.asyncAfter(deadline: whenWhen) { self.active(true, strongNoise: false) self.setValue(self._value + 0.7 * (newValue - self._value)) } whenWhen = now + DispatchTimeInterval.milliseconds(Int(1000.0 * 0.85 * totalTime)) DispatchQueue.main.asyncAfter(deadline: whenWhen) { self.active(true, strongNoise: false) self.setValue(newValue) } } func active(_ onOff: Bool, strongNoise: Bool) { self.strongNoise = strongNoise if onOff { colorful = true if needleNoiseTimer == nil { needleNoiseTimer = Timer.scheduledTimer(timeInterval: 0.25, target: self, selector: #selector(addNoise), userInfo: nil, repeats: true) needleNoiseTimer?.tolerance = 0.1 } } else { colorful = false if needleNoiseTimer != nil { needleNoiseTimer!.invalidate() needleNoiseTimer = nil } } } @objc private func addNoise() { DispatchQueue.main.async { let n = self.distribution.nextInt() var noiseLevel = 0.001 if self.strongNoise { noiseLevel *= 3 } let noise = noiseLevel * Double(n) self.noisyValue = self._value + noise } } } extension Double { var s: String { String(format: "%7.1f", self) } } extension CGFloat { var s: String { String(format: "%10.5f", self) } } <file_sep>// // SmartButton.swift // Truth-O-Meter // // Created by <NAME> on 30/08/2021. // import SwiftUI import GameKit /// for Audio struct SmartButtonView: View { let color: Color let gray: Color let paleColor: Color let listenTime: Double let analysisTime: Double @Binding var displayColorful: Bool let callback: (Precision) -> Void @State private var smartButtonSize: CGSize = CGSize(width: 10, height: 10) private struct FrameCatcher: View { @Binding var into: CGSize var body: some View { Rectangle() .foregroundColor(.clear)//.blue.opacity(0.2)) .background( Rectangle() .foregroundColor(.clear) .captureSize(in: $into) ) } } func tapped(_ precision: Precision) { let startRecording:UInt32 = 1113 let stopRecording:UInt32 = 1114 /// source: https://github.com/TUNER88/iOSSystemSoundsLibrary DispatchQueue.main.async { AudioServicesPlaySystemSound(startRecording) } Needle.shared.active(true, strongNoise: true) let v: Double switch precision { case .edge: v = 1.0 case .outer: v = 0.75 case .middle: v = 0.5 case .inner: v = 0.25 case .bullsEye: v = 0.0 } Needle.shared.setValueInSteps(v, totalTime: listenTime + analysisTime) displayColorful = true animateRingView = true let whenWhen: DispatchTime = DispatchTime.now() + DispatchTimeInterval.milliseconds(Int(1000.0 * listenTime)) DispatchQueue.main.asyncAfter(deadline: whenWhen) { AudioServicesPlaySystemSound(stopRecording) callback(precision) } } struct Config { let padding: Double let ringWidth: Double let fiveDisksRadius: Double init(radius: Double) { ringWidth = 0.05 * radius fiveDisksRadius = radius - 3.0 * ringWidth padding = 0.5 * ringWidth } } @State private var animateRingView: Bool = false var body: some View { let config = Config(radius: min(smartButtonSize.width, smartButtonSize.height)) ZStack { FrameCatcher(into: $smartButtonSize) if animateRingView { RingView( time: listenTime, width: config.ringWidth, activeColor: color, passiveColor: gray) } else { Circle() .stroke(gray, lineWidth: config.ringWidth) } FiveDisks(preferenceScreen: false, radius: config.fiveDisksRadius, color: color, paleColor: paleColor, callback: tapped) } .padding(config.padding) } } struct SmartButton_Previews: PreviewProvider { static var previews: some View { SmartButtonView( color: Color.red, gray: Color.gray, paleColor: Color.orange, listenTime: 1.0, analysisTime: 1.0, displayColorful: .constant(true)) { p in } } } <file_sep>// // PreferencesView.swift // Truth-O-Meter // // Created by <NAME> on 11/12/20. // import SwiftUI struct PreferencesView: View { @EnvironmentObject var preferences: Preferences private struct ThemeCell: View { @EnvironmentObject var preferences: Preferences let name: String let isSelected: Bool let isCustom: Bool var body: some View { HStack { if isSelected { Text(name == "" ? "Custom" : name) .font(.headline) NavigationLink( destination: PreferencesDetailView(displayTitle: $preferences.title)) { Group { if isCustom { Text("Edit") .padding(.leading, 10) .font(.headline) } else { Image(systemName: "info.circle") .font(.title2.weight(.semibold)) } } } } else { Text(name == "" ? "Custom" : name) } Spacer() if isSelected { Image(systemName: "checkmark") .font(.title2.weight(.bold)) .foregroundColor(.accentColor) } } .padding(.leading) .padding(.trailing) .frame(height: 30) } } private struct ThemesList: View { @EnvironmentObject var preferences: Preferences var body: some View { let themeNames = preferences.themeNames VStack { ForEach(themeNames) { themeName in ThemeCell( name: themeName.name, isSelected: themeName.id == preferences.selectedThemeIndex, isCustom: themeName.isCustom) .contentShape(Rectangle()) .onTapGesture { preferences.selectedThemeIndex = themeName.id } Rectangle().fill(preferences.lightGray) .frame(height: 0.5) .padding(.leading) } } } } private struct TimePicker: View { @EnvironmentObject var preferences: Preferences var body: some View { VStack(alignment: .leading) { HStack { Text("Listening time") .frame(width:150, alignment: .leading) Picker(selection: $preferences.listenTimingIndex, label: Text("")) { Text(preferences.listenTimeStrings[0]).tag(0) Text(preferences.listenTimeStrings[1]).tag(1) Text(preferences.listenTimeStrings[2]).tag(2) } .pickerStyle(SegmentedPickerStyle()) .frame(width: 150) } .padding(.leading) HStack { Text("Analysis time") .frame(width:150, alignment: .leading) Picker(selection: $preferences.analysisTimingIndex, label: Text("")) { Text(preferences.analysisTimeStrings[0]).tag(0) Text(preferences.analysisTimeStrings[1]).tag(1) Text(preferences.analysisTimeStrings[2]).tag(2) } .pickerStyle(SegmentedPickerStyle()) .frame(width: 150) Spacer() } .padding(.leading) .padding(.bottom, 30) } } } var body: some View { VStack { HStack { Spacer() NavigationLink(destination: InstructionView()) { Text("Instructions") } Spacer() } .padding(.vertical, 40) TimePicker() Rectangle().fill(preferences.lightGray) .frame(height: 0.5) .padding(.leading) ThemesList() Spacer() } .frame(maxWidth: 600) } } struct PreferencesView_Previews: PreviewProvider { static var previews: some View { PreferencesView() .environmentObject(Preferences(colorScheme: .light)) .padding(.top, 70) } } <file_sep>// // HorizontalProgressBar.swift // Truth-O-Meter // // Created by <NAME> on 20/08/2021. // import Foundation import SwiftUI struct HorizontalProgressBar: View { let activeColor: Color let passiveColor: Color let animationTime: Double let height:CGFloat = 4 @State var animate: Bool = false var body: some View { ZStack(alignment: Alignment.leading) { Rectangle() .foregroundColor(passiveColor) .frame(height: height) .opacity(0.2) Rectangle() .foregroundColor(activeColor) .frame(width: animate ? .infinity : 0, height: height) .animation(.easeIn(duration: animationTime), value: animate) .onAppear() { animate = true } } } } struct HorizontalProgressbar_Previews: PreviewProvider { static var previews: some View { func doNothing() {} return HorizontalProgressBar(activeColor: Color.red, passiveColor: Color.gray, animationTime: 2) } } <file_sep>// // DisplayView.swift // Truth-O-Meter // // Created by <NAME> on 11/11/20. // import SwiftUI struct CustomTitleTextFieldStyle: TextFieldStyle { let activeColor:Color let darkColor: Color @Binding var focused: Bool let cornerRadius = 5.0 func _body(configuration: TextField<Self._Label>) -> some View { configuration .disableAutocorrection(true) .padding(6) .background( RoundedRectangle(cornerRadius: cornerRadius) .strokeBorder(activeColor, lineWidth: focused ? 3 : 0)) .background(activeColor.opacity(0.1)) .multilineTextAlignment(TextAlignment.center) .lineLimit(1) .cornerRadius(cornerRadius) .accentColor(darkColor) .foregroundColor(darkColor) .offset(y: 15) } } struct DisplayView: View { @Binding var title: String var colorful: Bool var editTitle: Bool @State private var editing = false let activeColor:Color let passiveColor:Color let gray: Color private let aspectRatio = 1.9 var body: some View { // print("redrawing Display, colorful = \(String(colorful))") /// I do not want to see this message very often. /// Specifically, it should not appear every time, the needle is redrawn GeometryReader { geo in let model = DisplayModel(size: geo.size) ZStack { DisplayBackground( model: model, colorful: colorful, passiveColor: passiveColor, gray: gray, activeColor: activeColor, aspectRatio: aspectRatio) if !editTitle { Text(title) .lineLimit(1) .font(.system(size: 500).bold()) .minimumScaleFactor(0.01) .frame(width: geo.size.width*0.6, height: geo.size.height, alignment: .center) .offset(y: geo.size.height*0.15) .foregroundColor(colorful ? gray : passiveColor) } NeedleView( displayMeasures:model.measures, activeColor: activeColor, passiveColor: passiveColor) .opacity(editTitle ? 0.5 : 1.0) if editTitle { TextField("", text: $title, onEditingChanged: { edit in self.editing = edit }) .textFieldStyle(CustomTitleTextFieldStyle(activeColor: activeColor, darkColor: gray, focused: $editing)) } } } .aspectRatio(aspectRatio, contentMode: .fit) } } struct Display_Previews: PreviewProvider { static var previews: some View { Needle.shared.active(true, strongNoise: false) return DisplayView(title: .constant("title"), colorful: true, editTitle: false, activeColor: Color.red, passiveColor: Color(white: 0.7), gray: Color.gray) .padding() .frame(width: 390, height: 400, alignment: .center) } } <file_sep>// // Stamp.swift // Draws a stamp // // Created by <NAME> on 13/09/2021. // import SwiftUI // uses captureSize struct Stamp: View { let firstLine: String let secondLine: String? let color: Color let angle: Angle @State private var frameSize = CGSize(width: 1.0, height: 1.0) @State private var textSize = CGSize(width: 1.0, height: 1.0) static let defaultColor = Color( red: 255.0/255.0, green: 83.0/255.0, blue: 77.0/255.0) static let singleLineDefaultAngle = Angle(degrees: -25) static let doubleLineDefaultAngle = Angle(degrees: -18) private struct FrameCatcher: View { @Binding var into: CGSize var body: some View { Rectangle() .foregroundColor(.clear)//.blue.opacity(0.2)) .background( Rectangle() .foregroundColor(.clear) .stampCaptureSize(in: $into) ) } } init( _ firstLine: String, _ secondLine: String? = nil, color: Color = Self.defaultColor, angle userDefinedAngle: Angle? = nil ) { self.firstLine = firstLine self.secondLine = secondLine self.color = color if let userDefinedAngle = userDefinedAngle { self.angle = userDefinedAngle } else { if secondLine != nil { self.angle = Self.doubleLineDefaultAngle } else { self.angle = Self.singleLineDefaultAngle } } } struct Lines : View { let firstLine: String let secondLine: String? var body: some View { VStack { Text(firstLine) if let secondLine = secondLine { Text(secondLine) } } } } struct OneOrTwoLines: View { let firstLine: String let secondLine: String? let color: Color let stampModel: StampModel @Binding var textSize: CGSize var body: some View { Lines(firstLine: firstLine, secondLine: secondLine) .font(.system(size: stampModel.largeFontSize).bold()) .foregroundColor(color) .fixedSize() .lineLimit(1) .stampCaptureSize(in: $textSize) .padding(stampModel.padding-stampModel.borderWidth/2) .overlay( RoundedRectangle(cornerRadius: stampModel.cornerRadius) .stroke(color, lineWidth: stampModel.borderWidth)) .padding(stampModel.borderWidth/2) } } var body: some View { let stampModel = StampModel( fw: Float(frameSize.width), fh: Float(frameSize.height), tw: Float(textSize.width), th: Float(textSize.height), angle: Float(angle.radians)) ZStack { FrameCatcher(into: $frameSize) VStack { ZStack { Rectangle() .foregroundColor(.clear)//green.opacity(0.2)) .background( OneOrTwoLines( firstLine: firstLine, secondLine: secondLine, color: color, stampModel: stampModel, textSize: $textSize) ) .mask(Image(uiImage: UIImage(named: "mask")!) .resizable() .scaledToFill() .frame(width: stampModel.maskSize, height: stampModel.maskSize, alignment: SwiftUI.Alignment.center) ) } .fixedSize(horizontal: true, vertical: true) } .scaleEffect(stampModel.scale) .rotationEffect(angle) } } } struct Stamp_Previews: PreviewProvider { static var previews: some View { Stamp("Stamp Text") .frame(width: 330, height: 400, alignment: .center) } } // from https://newbedev.com/swiftui-rotationeffect-framing-and-offsetting private struct StampSizeKey: PreferenceKey { static let defaultValue: CGSize = .zero static func reduce(value: inout CGSize, nextValue: () -> CGSize) { value = nextValue() } } private extension View { func stampCaptureSize(in binding: Binding<CGSize>) -> some View { return overlay(GeometryReader { proxy in Color.clear.preference(key: StampSizeKey.self, value: proxy.size) }) .onPreferenceChange(StampSizeKey.self) { size in DispatchQueue.main.async { binding.wrappedValue = size } } } } <file_sep>// // DisplayModel.swift // Truth-O-Meter (iOS) // // Created by <NAME> on 15/09/2021. // import SwiftUI struct DisplayModel { var measures: DisplayMeasures let boldStrokeStyle: StrokeStyle let fineStrokeStyle: StrokeStyle let startAngle: Angle let midAngle: Angle let endAngle: Angle init(size: CGSize) { measures = DisplayMeasures(size) boldStrokeStyle = StrokeStyle(lineWidth: measures.thickLine, lineCap: .butt) fineStrokeStyle = StrokeStyle(lineWidth: measures.thinLine, lineCap: .butt) startAngle = Angle(radians: measures.startAngle) midAngle = Angle(radians: measures.midAngle) endAngle = Angle(radians: measures.endAngle) } } <file_sep>// // TruthView.swift // Truth-O-Meter // // Created by <NAME> on 16/08/2021. // import SwiftUI struct NeedleView: View { @ObservedObject var needle = Needle.shared let displayMeasures: DisplayMeasures let activeColor:Color let passiveColor:Color func angle(_ v: Double) -> Angle { return Angle(radians: displayMeasures.completeAngle * (-0.5 + v)) } var body: some View { ZStack { Rectangle() .foregroundColor(.clear) .background(Capsule() .fill(needle.colorful ? activeColor : passiveColor) .clipShape(Rectangle()) .frame(width: displayMeasures.thickLine, height: displayMeasures.radius2+displayMeasures.thickLine) .rotationEffect(angle(needle.noisyValue), anchor: .bottom) .offset(y:displayMeasures.needleYOffset) .animation(.linear(duration: 0.4), value: needle.noisyValue) ) .clipped() } } init(displayMeasures: DisplayMeasures, activeColor: Color, passiveColor: Color) { self.displayMeasures = displayMeasures self.activeColor = activeColor self.passiveColor = passiveColor } } struct NeedleView_Previews: PreviewProvider { static var previews: some View { Needle.shared.active(true, strongNoise: false) Needle.shared.setValue(1.0) return GeometryReader { geo in NeedleView(displayMeasures: DisplayMeasures(geo.size), activeColor: Color.red, passiveColor: Color.gray) .background(Color.green.opacity(0.2)) } } } <file_sep>// // FiveDisks.swift // Truth-O-Meter (iOS) // // Created by <NAME> on 16/09/2021. // import SwiftUI struct FiveDisks: View { let preferenceScreen: Bool let radius: Double let color: Color let paleColor: Color let callback: (Precision) -> Void @State var isTapped: Bool = false @State var grayDisk: Precision = .middle let diskData = [ DiskData(.outer, 0.8 - 0.05), DiskData(.middle, 0.6 - 0.0125), DiskData(.inner, 0.4 + 0.0125), DiskData(.bullsEye, 0.2 + 0.05)] @State private var pale = false struct Config { let cr: Double let p: Double let c: Color let gray = Color(white: 0.7) let down: () -> Void let up: (Precision) -> Void init(isTapped: Bool, radius: Double, color: Color, pale: Bool, paleColor: Color, down: @escaping () -> Void, up: @escaping (Precision) -> Void) { cr = isTapped ? radius/14.0 : radius*0.5 p = isTapped ? radius*0.25 : 0.0 c = pale ? paleColor : color self.down = down self.up = up } } private struct Edge: View { let config: Config let color: Color var body: some View { Rectangle() .fill(color) .cornerRadius(config.cr) .padding(config.p) .gesture( DragGesture(minimumDistance: 0) .onChanged { value in config.down() } .onEnded { value in config.up(.edge) } ) } } private struct Disk: View { let config: Config let color: Color let border: Bool let precision: Precision var body: some View { Circle() .fill(color) .gesture( DragGesture(minimumDistance: 0) .onChanged { value in config.down() } .onEnded { value in config.up(precision) } ) if border { Circle() .stroke(config.gray, lineWidth: 1) } } } func down() { if !preferenceScreen && !pale { pale = true } } func up(_ tappedPrecision: Precision) { if preferenceScreen { grayDisk = tappedPrecision } else { isTapped = true pale = false } callback(tappedPrecision) } var body: some View { let config = Config( isTapped: isTapped, radius: radius, color: color, pale: pale, paleColor: paleColor, down: down, up: up) func fc(for precision: Precision) -> Color { if preferenceScreen { if grayDisk == precision { return config.gray } else { return config.c } } else { return config.c } } return ZStack { Edge(config: config, color: fc(for: .edge)) ForEach(diskData) { data in Disk(config: config, color: fc(for: data.precision), border: preferenceScreen, precision: data.precision) .padding(data.padding*radius) } .isHidden(isTapped) } .animation(.easeIn(duration: 0.25), value: isTapped) .animation(.easeIn(duration: 0.1), value: pale) .frame(width: radius, height: radius) } struct DiskData: Identifiable { var id = UUID() let precision: Precision let padding: Double init(_ precision: Precision, _ r: Double) { self.precision = precision self.padding = (1.0 - r) * 0.5 } } } struct FiveDisks_Previews: PreviewProvider { static var previews: some View { FiveDisks( preferenceScreen: true, radius: 200, color: Color.red, paleColor: Color.orange) { p in } } } extension View { /// Hide or show the view based on a boolean value. /// /// Example for visibility: /// /// Text("Label") /// .isHidden(true) /// /// Example for complete removal: /// /// Text("Label") /// .isHidden(true, remove: true) /// /// - Parameters: /// - hidden: Set to `false` to show the view. Set to `true` to hide the view. /// - remove: Boolean value indicating whether or not to remove the view. @ViewBuilder func isHidden(_ hidden: Bool, remove: Bool = false) -> some View { if hidden { if !remove { self.hidden() } } else { self } } } <file_sep>// // DisplayBackground.swift // Truth-O-Meter // // Created by <NAME> on 11/10/20. // import SwiftUI struct DisplayBackground: View { let model: DisplayModel var colorful: Bool var passiveColor: Color var gray: Color var activeColor: Color var aspectRatio: Double var body: some View { ZStack { MainArcBlack(model: model) .stroke(colorful ? gray : passiveColor, style: model.boldStrokeStyle) MainArcRed(model: model) .stroke(colorful ? activeColor : passiveColor, style: model.boldStrokeStyle) TopArcBlack(model: model) .stroke(colorful ? gray : passiveColor, style: model.fineStrokeStyle) TopArcRed(model: model) .stroke(colorful ? activeColor : passiveColor, style: model.fineStrokeStyle) .clipped() RoundedRectangle(cornerRadius: 25, style: .continuous) .stroke(passiveColor, lineWidth: model.measures.borderLine) } .aspectRatio(aspectRatio, contentMode: .fit) } private struct MainArcBlack: Shape { let model: DisplayModel func path(in rect: CGRect) -> Path { var path = Path() path.addArc( center: model.measures.displayCenter, radius: model.measures.radius1, startAngle: model.startAngle, endAngle: model.midAngle, clockwise: false) return path } } private struct MainArcRed: Shape { let model: DisplayModel func path(in rect: CGRect) -> Path { var path = Path() path.addArc( center: model.measures.displayCenter, radius: model.measures.radius1, startAngle: model.midAngle, endAngle: model.endAngle, clockwise: false) return path } } private struct TopArcBlack: Shape { let model: DisplayModel let proportions = [0.12, 0.2, 0.265, 0.32, 0.37, 0.42, 0.47, 0.52, 0.57, 0.62, 0.66] func path(in rect: CGRect) -> Path { var temp = Path() let p: Path = Path { path in path.addArc( center: model.measures.displayCenter, radius: model.measures.radius2, startAngle: model.startAngle, endAngle: model.midAngle, clockwise: false) for proportion in proportions { let end = Angle(radians: model.measures.angle(forProportion: proportion)) temp.addArc( center: model.measures.displayCenter, radius: model.measures.radius2, startAngle: model.startAngle, endAngle: end, clockwise: false) let a = temp.currentPoint! temp.addArc( center: model.measures.displayCenter, radius: model.measures.radius3, startAngle: model.startAngle, endAngle: end, clockwise: false) let b = temp.currentPoint! path.move(to: a) path.addLine(to: b) } } return p } } private struct TopArcRed: Shape { let model: DisplayModel func path(in rect: CGRect) -> Path { var temp = Path() let p: Path = Path { path in /// top arc path.addArc( center: model.measures.displayCenter, radius: model.measures.radius2, startAngle: model.midAngle, endAngle: model.endAngle, clockwise: false) /// little red ticks on the right for proportion in [0.79, 0.87, 0.94] { let end = Angle(radians: model.measures.angle(forProportion: proportion)) temp.addArc( center: model.measures.displayCenter, radius: model.measures.radius2, startAngle: model.startAngle, endAngle: end, clockwise: false) path.move(to: temp.currentPoint!) temp.addArc( center: model.measures.displayCenter, radius: model.measures.radius3, startAngle: model.startAngle, endAngle: end, clockwise: false) path.addLine(to: temp.currentPoint!) } /// red divider line temp.addArc( center: model.measures.displayCenter, radius: model.measures.radius1, startAngle: model.startAngle, endAngle: model.midAngle, clockwise: false) path.move(to: temp.currentPoint!) temp.addArc( center: model.measures.displayCenter, radius: model.measures.radius3, startAngle: model.startAngle, endAngle: model.midAngle, clockwise: false) path.addLine(to: temp.currentPoint!) /// line at the beginning path.move(to: model.measures.displayCenter) temp.addArc( center: model.measures.displayCenter, radius: model.measures.radius3, startAngle: model.startAngle, endAngle: model.startAngle, clockwise: false) path.addLine(to: temp.currentPoint!) /// line at the end path.move(to: model.measures.displayCenter) temp.addArc( center: model.measures.displayCenter, radius: model.measures.radius3, startAngle: model.startAngle, endAngle: model.endAngle, clockwise: false) path.addLine(to: temp.currentPoint!) } return p } } } struct DisplayBackground_Previews: PreviewProvider { static var previews: some View { GeometryReader { geo in DisplayBackground(model: DisplayModel(size: geo.size), colorful: true, passiveColor: Color(white: 0.7), gray: Color.gray, activeColor: Color.red, aspectRatio: 1.9) .background(Color.yellow.opacity(0.2)) .frame(width: 300, height: 200, alignment: .center) } } } <file_sep>// // Instructions.swift // Truth-O-Meter // // Created by <NAME> on 03/09/2021. // import SwiftUI struct InstructionView: View { var body: some View { VStack(alignment: .center) { Image("instructionBullsEye") .resizable() .scaledToFit() Text("Tap the center and the needle will go to the left") .italic() .padding(.bottom, 50) Image("instructionEdge") .resizable() .scaledToFit() Text("Tap the edge and the needle will go to the right") .italic() Spacer() } .padding() } } struct Instructions_Previews: PreviewProvider { static var previews: some View { InstructionView() } } <file_sep>// // RingView.swift // Truth-O-Meter // // Created by <NAME> on 30/08/2021. // import SwiftUI struct RingView: View { let time: Double let width: Double let activeColor: Color let passiveColor: Color @State private var animateValue: Double = 0.0 var body: some View { ZStack { Circle() .stroke(passiveColor, lineWidth: width) Circle() .trim(from: 0, to: animateValue) .stroke(activeColor, lineWidth: width) .rotationEffect(Angle(degrees:-90)) .animation(.linear(duration: time), value: animateValue) } .onAppear() { animateValue = 1.0 } } } struct RingView_Previews: PreviewProvider { static var previews: some View { func doNothing() {} return RingView( time: 1.0, width: 10, activeColor: Color.red, passiveColor: Color.gray) } } <file_sep>// // MainView.swift // Truth-O-Meter // // Created by <NAME> on 27/08/2021. // import SwiftUI struct ContentView: View { @EnvironmentObject var preferences: Preferences @State private var displayColorful = false @State private var showAnalysisView = false @State private var showSmartButton = true @State private var showStampView = false @State private var stampTop: String = "" @State private var stampBottom: String? = nil let analyseTitleFont: Font = Font.system(size: UIScreen.main.bounds.width * 0.04).bold() var body: some View { VStack { VStack { PreferencesButton() .opacity(displayColorful ? 0.0 : preferences.preferencesButtonOpacity) .animation(.easeIn(duration: 0.1), value: displayColorful) #if targetEnvironment(macCatalyst) .padding(.top, 20.0) #endif .padding(.trailing, 10.0) } VStack { DisplayView( title: $preferences.title, colorful: displayColorful, editTitle: false, activeColor: preferences.primaryColor, passiveColor: preferences.lightGray, gray: preferences.gray) if showAnalysisView { HorizontalProgressBar( activeColor: preferences.lightGray, passiveColor: preferences.lightGray.opacity(0.7), animationTime: preferences.analysisTime) Text("Analysing...") #if targetEnvironment(macCatalyst) .font(.title) #else .font(.headline) #endif .foregroundColor(preferences.lightGray) } Spacer() if showSmartButton { SmartButtonView( color: preferences.primaryColor, gray: preferences.lightGray, paleColor: preferences.secondaryColor, listenTime: preferences.listenTime, analysisTime: preferences.analysisTime, displayColorful: $displayColorful) { precision in stampTop = preferences.stampTop(precision) stampBottom = preferences.stampBottom(precision) Needle.shared.active(true, strongNoise: true) displayColorful = true showAnalysisView = true showSmartButton = false DispatchQueue.main.asyncAfter(deadline: .now() + preferences.analysisTime) { Needle.shared.active(true, strongNoise: false) displayColorful = true showAnalysisView = false showStampView = true } } .padding() } if showStampView { Stamp(stampTop, stampBottom, color: preferences.primaryColor) .onTapGesture { Needle.shared.active(false, strongNoise: false) Needle.shared.setValue(0.5) showStampView = false showSmartButton = true displayColorful = false } } Spacer() } .padding() } } } struct PreferencesButton: View { @EnvironmentObject var preferences: Preferences var body: some View { HStack { Spacer() NavigationLink(destination: PreferencesView()) { Image(preferences.preferencesButton) .resizable() .frame(width: 30, height: 30) .padding(.trailing, 5) } .padding() } } } struct MainView: View { @Environment(\.colorScheme) var colorScheme var body: some View { NavigationView { ContentView() .onAppear() { Needle.shared.active(false, strongNoise: false) Needle.shared.setValue(0.5) } .ignoresSafeArea() .navigationBarHidden(true) } // .navigationViewStyle(StackNavigationViewStyle()) // <- add here .environmentObject(Preferences(colorScheme: colorScheme)) .accentColor(colorScheme == .light ? .blue : .white) } } struct MainView_Previews: PreviewProvider { static var previews: some View { MainView() } } <file_sep>// // PreferencesData.swift // Truth-O-Meter // // Created by <NAME> on 01/09/2021. // import Foundation import SwiftUI struct Key { /// some key names might seem stange, but this is /// for compatibility with older app versions static let listenTiming = "fastResponseTimeKey" static let analysisTiming = "analysisTimingIndexkey" static let selectedTheme = "selectedTheme" struct custom { static let title = "CustomiseddisplayTextkey" struct edge { static let top = "CustomisedfarLeftText1key" static let bottom = "CustomisedfarLeftText2key" } struct outer { static let top = "CustomisedleftText1key" static let bottom = "CustomisedleftText2key" } struct middle { static let top = "CustomisedcenterText1key" static let bottom = "CustomisedcenterText2key" } struct inner { static let top = "CustomisedrightText1key" static let bottom = "CustomisedrightText2key" } struct bullsEye { static let top = "CustomisedfarRightText1key" static let bottom = "CustomisedfarRightText2key" } } } struct Theme: Identifiable, Equatable { private(set) var id: Int var title: String = "" mutating func setTop(top: String, forPrecision precision: Precision) { switch precision { case .edge: edge.top = top case .outer: outer.top = top case .middle: middle.top = top case .inner: inner.top = top case .bullsEye: bullsEye.top = top } } mutating func setBottom(bottom: String, forPrecision precision: Precision) { switch precision { case .edge: edge.bottom = bottom case .outer: outer.bottom = bottom case .middle: middle.bottom = bottom case .inner: inner.bottom = bottom case .bullsEye: bullsEye.bottom = bottom } } func top(forPrecision precision: Precision) -> String { switch precision { case .edge: return edge.top case .outer: return outer.top case .middle: return middle.top case .inner: return inner.top case .bullsEye: return bullsEye.top } } func bottom(forPrecision precision: Precision) -> String? { switch precision { case .edge: return edge.bottom case .outer: return outer.bottom case .middle: return middle.bottom case .inner: return inner.bottom case .bullsEye: return bullsEye.bottom } } struct StampTexts { var top: String var bottom: String init(_ top_: String, _ bottom_: String) { top = top_; bottom = bottom_ } } var edge: StampTexts var outer: StampTexts var middle: StampTexts var inner: StampTexts var bullsEye: StampTexts var isCustomisable: Bool mutating func setTop(_ newTop: String, forPrecision: Precision) { switch forPrecision { case .edge: edge.top = newTop if isCustomisable { PreferencesData.customEdgeTop = newTop } case .outer: outer.top = newTop if isCustomisable { PreferencesData.customOuterTop = newTop } case .middle: middle.top = newTop if isCustomisable { PreferencesData.customMiddleTop = newTop } case .inner: inner.top = newTop if isCustomisable { PreferencesData.customInnerTop = newTop } case .bullsEye: bullsEye.top = newTop if isCustomisable { PreferencesData.customBullsEyeTop = newTop } } } mutating func setBottom(_ newBottom: String, forPrecision: Precision) { switch forPrecision { case .edge: edge.bottom = newBottom if isCustomisable { PreferencesData.customEdgeBottom = newBottom } case .outer: outer.bottom = newBottom if isCustomisable { PreferencesData.customOuterBottom = newBottom } case .middle: middle.bottom = newBottom if isCustomisable { PreferencesData.customMiddleBottom = newBottom } case .inner: inner.bottom = newBottom if isCustomisable { PreferencesData.customInnerBottom = newBottom } case .bullsEye: bullsEye.bottom = newBottom if isCustomisable { PreferencesData.customBullsEyeBottom = newBottom } } } static func == (lhs: Theme, rhs: Theme) -> Bool { return lhs.id == rhs.id } } struct ThemeName: Identifiable { let id: Int let name: String let isCustom: Bool } struct PreferencesData { @AppStorage("listenTimingIndex") static var listenTimingIndex: Int = 1 @AppStorage("analysisTimingIndex") static var analysisTimingIndex: Int = 1 @AppStorage("customTitle") static var customTitle: String = "" @AppStorage("customEdgeTop") static var customEdgeTop = "" @AppStorage("customEdgeBottom") static var customEdgeBottom = "" @AppStorage("customOuterTop") static var customOuterTop = "" @AppStorage("customOuterBottom") static var customOuterBottom = "" @AppStorage("customMiddleTop") static var customMiddleTop = "" @AppStorage("customMiddleBottom") static var customMiddleBottom = "" @AppStorage("customInnerTop") static var customInnerTop = "" @AppStorage("customInnerBottom") static var customInnerBottom = "" @AppStorage("customBullsEyeTop") static var customBullsEyeTop = "" @AppStorage("customBullsEyeBottom") static var customBullsEyeBottom = "" @AppStorage("selectedThemeIndex") static var selectedThemeIndex: Int = 1 mutating func setTop(top: String, forPrecision precision: Precision) { custom.setTop(top, forPrecision: precision) } mutating func setBottom(bottom: String, forPrecision precision: Precision) { custom.setBottom(bottom, forPrecision: precision) } func stampBottom(forprecision precision: Precision) -> String? { seletedTheme.bottom(forPrecision: precision) } var themeNames: [ThemeName] { get { var ret = [ThemeName]() ret.append(ThemeName(id: 0, name: bullshit.title, isCustom: false)) ret.append(ThemeName(id: 1, name: singing.title, isCustom: false)) ret.append(ThemeName(id: 2, name: custom.title, isCustom: true)) return ret } } var seletedTheme: Theme { let s = PreferencesData.selectedThemeIndex if s == 0 { return bullshit } if s == 1 { return singing } return custom } var title: String { seletedTheme.title } mutating func setTitle(_ newTitle: String) { custom.title = newTitle } let waitTimes = [2, 4, 10] var listenTime: Double { Double(waitTimes[PreferencesData.listenTimingIndex]) } let analysisTimes = [2, 4, 10] var analysisTime: Double { Double(waitTimes[PreferencesData.analysisTimingIndex]) } private let bullshit = Theme( id: 0, title: "Bullshit-O-Meter", edge: Theme.StampTexts("Absolute", "Bullshit"), outer: Theme.StampTexts("Bullshit", ""), middle: Theme.StampTexts("undecided", ""), inner: Theme.StampTexts("Mostly", "True"), bullsEye: Theme.StampTexts("True", ""), isCustomisable: false) private let singing = Theme( id: 2, title: "Voice-O-Meter", edge: Theme.StampTexts("Sexy", ""), outer: Theme.StampTexts("impressive", ""), middle: Theme.StampTexts("good", ""), inner: Theme.StampTexts("could be", "better"), bullsEye: Theme.StampTexts("flimsy", ""), isCustomisable: false) private var custom = Theme( id: 3, title: PreferencesData.customTitle, edge: Theme.StampTexts(PreferencesData.customEdgeTop, PreferencesData.customEdgeBottom), outer: Theme.StampTexts(PreferencesData.customOuterTop, PreferencesData.customOuterBottom), middle: Theme.StampTexts(PreferencesData.customMiddleTop, PreferencesData.customMiddleBottom), inner: Theme.StampTexts(PreferencesData.customInnerTop, PreferencesData.customInnerBottom), bullsEye: Theme.StampTexts(PreferencesData.customBullsEyeTop, PreferencesData.customBullsEyeBottom), isCustomisable: true) } <file_sep>// // MaskView.swift // Truth-O-Meter // // Created by <NAME> on 05/09/2021. // import SwiftUI struct MaskView: View { var body: some View { Image(uiImage: UIImage(named: "mask")!) .resizable() .scaledToFill() } } struct MaskView_Previews: PreviewProvider { static var previews: some View { MaskView() } } <file_sep>// // PreferencesDetailView.swift // Truth-O-Meter // // Created by <NAME> on 23/08/2021. // import SwiftUI struct PreferencesDetailView: View { @EnvironmentObject var preferences: Preferences @Binding var displayTitle: String @State private var stampTop: String = "" @State private var stampBottom: String? = nil func callback(_ precision: Precision) { stampTop = preferences.stampTop(precision) stampBottom = preferences.stampBottom(precision) let newNeedleValue = preferences.needleValue(forPrecision: precision) Needle.shared.active(true, strongNoise: false) Needle.shared.setValue(newNeedleValue) } var body: some View { VStack { Spacer(minLength: 20) HStack { DisplayView( title: $preferences.title, colorful: true, editTitle: preferences.isCustom, activeColor: preferences.primaryColor, passiveColor: preferences.lightGray, gray: preferences.gray) .padding(.trailing, 5) Stamp(stampTop, stampBottom, color: preferences.primaryColor, angle: Angle(degrees: 0)) //.background(Color.yellow.opacity(0.2)) } .fixedSize(horizontal: false, vertical: true) if preferences.isCustom { EditableStampView() } else { EmptyView() } Spacer(minLength: 0) FiveDisks( preferenceScreen: true, radius: 200, color: preferences.primaryColor, paleColor: Color.white, callback: callback) .aspectRatio(contentMode: .fit) .frame(maxWidth: 600) Spacer(minLength: 0) } .padding() .onAppear() { Needle.shared.active(true, strongNoise: false) } } } struct CustomTextFieldStyle: TextFieldStyle { @EnvironmentObject var preferences: Preferences @Binding var focused: Bool let fontsize = 40.0 let cornerRadius = 6.0 func _body(configuration: TextField<Self._Label>) -> some View { configuration .disableAutocorrection(true) .accentColor(preferences.primaryColor) .mask(MaskView()) .autocapitalization(.none) .background( RoundedRectangle(cornerRadius: cornerRadius) .strokeBorder(preferences.primaryColor, lineWidth: focused ? 3 : 0)) .background(preferences.primaryColor.opacity(0.1)) .multilineTextAlignment(.center) .lineLimit(1) .cornerRadius(cornerRadius) .font(.system(size: fontsize, weight: .bold)) .foregroundColor(preferences.primaryColor) } } struct EditableStampView: View { @State private var editingTop = false @State private var editingBottom = false let fontsize = 40.0 var body: some View { Text("xx") // VStack { // TextField("Top", text: $stampTop, onEditingChanged: { edit in // self.editingTop = edit // }) // .textFieldStyle(CustomTextFieldStyle(focused: $editingTop)) // .padding(.top, 24) // // TextField("Bottom", text: $preferences.nonNilStampBottom, onEditingChanged: { edit in // self.editingBottom = edit // }) // .textFieldStyle(CustomTextFieldStyle(focused: $editingBottom)) // .padding(.bottom, 12) // } } } struct PreferencesDetailView_Previews: PreviewProvider { static var previews: some View { return PreferencesDetailView(displayTitle: .constant("xx")) } } <file_sep>// // CaptureSize.swift // Truth-O-Meter // // from https://newbedev.com/swiftui-rotationeffect-framing-and-offsetting // import SwiftUI private struct SizeKey: PreferenceKey { static let defaultValue: CGSize = .zero static func reduce(value: inout CGSize, nextValue: () -> CGSize) { value = nextValue() } } extension View { func captureSize(in binding: Binding<CGSize>) -> some View { return overlay(GeometryReader { proxy in Color.clear.preference(key: SizeKey.self, value: proxy.size) }) .onPreferenceChange(SizeKey.self) { size in DispatchQueue.main.async { binding.wrappedValue = size } } } } <file_sep>// // PlaygroundView.swift // Truth-O-Meter // // Created by <NAME> on 08/09/2021. // import SwiftUI struct PlaygroundView: View { private var privateFrameWidth = 100.0 @State private var frameWidth = 100.0 @State private var frameHeight = 100.0 @State private var angle = Angle(degrees: 0.0) var body: some View { ZStack { Stamp("É", angle: angle) .frame(width: frameWidth, height: frameHeight) //.background(Color.blue.opacity(0.1)) .border(Color.blue, width: 1) VStack { Spacer() HStack { Text("W") Slider(value: $frameWidth, in: 50...300) } HStack { Text("H") Slider(value: $frameHeight, in: 50...600) } HStack { Text("𝝰") Slider(value: $angle.degrees, in: -90...90) } } .padding() } } } struct PlaygroundView_Previews: PreviewProvider { static var previews: some View { PlaygroundView() } } <file_sep># Truth-O-Meter fake bullshit detection <file_sep>// // SnapshotView.swift // Truth-O-Meter // // Created by <NAME> on 11/09/2021. // import SwiftUI class StampImage: ObservableObject { var angle: Angle @Published var snapshot: UIImage? func snap(image: UIImage) { snapshot = image.rotate(radians: angle.radians) } init() { self.angle = Angle(degrees: 5) snapshot = nil } } struct Stamp: View { var text: String var color: Color var angle: Angle let fontSize:CGFloat = 100.0 @StateObject var snapshotViewModel = StampImage() var Snapshot: some View { let margin = fontSize * 0.4 let borderWidth = fontSize * 0.4 return Text(text) .foregroundColor(color) .font(.system(size: fontSize)) .lineLimit(1) .padding(margin) .padding(borderWidth/2) .overlay( RoundedRectangle( cornerRadius: borderWidth*1.5) .stroke(color, lineWidth: borderWidth)) .padding(borderWidth/2) .mask(MaskView()) } var body: some View { VStack { if let i = snapshotViewModel.snapshot { Image(uiImage: i) .resizable() .scaledToFit() } else { EmptyView() } } .onAppear() { DispatchQueue.main.async { snapshotViewModel.angle = angle // angle has not been set in init() snapshotViewModel.snap(image: Snapshot.snapshot()) } } } } struct SnapshotView_Previews: PreviewProvider { static var previews: some View { Stamp( text: "BullShit", color: C.color.bullshitRed, angle: Angle(degrees: -25.0)) } } extension View { func snapshot() -> UIImage { let controller = UIHostingController(rootView: self) let view = controller.view let targetSize = controller.view.intrinsicContentSize view?.bounds = CGRect(origin: .zero, size: targetSize) view?.backgroundColor = .clear let renderer = UIGraphicsImageRenderer(size: targetSize) return renderer.image { _ in view?.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true) } } } extension UIImage { func rotate(radians: Double) -> UIImage? { var newSize = CGRect(origin: CGPoint.zero, size: self.size).applying(CGAffineTransform(rotationAngle: CGFloat(radians))).size // Trim off the extremely small float value to prevent core graphics from rounding it up newSize.width = floor(newSize.width) newSize.height = floor(newSize.height) UIGraphicsBeginImageContextWithOptions(newSize, false, self.scale) let context = UIGraphicsGetCurrentContext()! // Move origin to middle context.translateBy(x: newSize.width/2, y: newSize.height/2) // Rotate around middle context.rotate(by: CGFloat(radians)) // Draw the image at its center self.draw(in: CGRect(x: -self.size.width/2, y: -self.size.height/2, width: self.size.width, height: self.size.height)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } } <file_sep>// // DisplayMeasures.swift // Truth-O-Meter (iOS) // // Created by <NAME> on 15/09/2021. // import CoreGraphics struct DisplayMeasures { let startAngle: Double let endAngle: Double let midAngle: Double let thinLine: Double let thickLine: Double let borderLine: Double let radius1: Double let radius2: Double let radius3: Double let needleYOffset: Double let displayCenter: CGPoint let completeAngle: Double = 102.0 * .pi / 180.0 func angle(forProportion proportion: Double) -> Double { startAngle + (endAngle - startAngle) * proportion } private let size: CGSize private let thickLineFactor: Double = 7.0 init(_ forSize: CGSize) { self.size = forSize let centerAngle: Double = -90.0 * .pi / 180.0 startAngle = centerAngle - completeAngle/2 endAngle = centerAngle + completeAngle/2 midAngle = startAngle+(endAngle-startAngle)*0.7 thinLine = self.size.width / 320 thickLine = thickLineFactor * thinLine borderLine = 2.0 * thinLine radius1 = size.height * 0.95 radius2 = radius1 * 1.07 radius3 = radius2 * 1.045 let r = CGRect(x: 0, y: 0, width: size.width, height: size.height) displayCenter = CGPoint(x: r.midX, y: r.origin.y + 1.2 * r.size.height) let w: Double = thickLine let h: Double = radius2 + thickLine needleYOffset = Double(displayCenter.y) - h + 2.0 * w / 3.0 } } <file_sep>// // Preferences.swift // Truth-O-Meter // // Created by <NAME> on 25/08/2021. // import Foundation import SwiftUI enum Precision { case edge, outer, middle, inner, bullsEye } class Preferences: ObservableObject { private var data = PreferencesData() private(set) var preferencesButton: String = "" private(set) var preferencesButtonOpacity: Double = 1.0 private(set) var primaryColor: Color = Color(white: 0.5) private(set) var secondaryColor: Color = Color(white: 0.5) private(set) var gray: Color = Color(white: 0.5) private(set) var lightGray: Color = Color(white: 0.5) var title: String { get { data.title } set { data.setTitle(newValue) objectWillChange.send() } } var isCustom: Bool { data.seletedTheme.isCustomisable } func stampTop(_ precision: Precision) -> String { data.seletedTheme.top(forPrecision: precision) } // var nonNilStampBottom: String { // /// needed for binding in TextField // get { // stampBottom ?? "" // } // set { // stampBottom = newValue == "" ? nil : newValue // } // } func stampBottom(_ precision: Precision) -> String? { data.seletedTheme.bottom(forPrecision: precision) } var selectedThemeIndex: Int { get { PreferencesData.selectedThemeIndex } set { PreferencesData.selectedThemeIndex = newValue objectWillChange.send() } } var themeNames: [ThemeName] { data.themeNames } var listenTimingIndex: Int { get { PreferencesData.listenTimingIndex } set { PreferencesData.listenTimingIndex = newValue } } var analysisTimingIndex: Int { get { PreferencesData.analysisTimingIndex } set { PreferencesData.analysisTimingIndex = newValue } } var listenTime: Double { data.listenTime } var analysisTime: Double { data.analysisTime } var listenAndAnalysisTime: Double { listenTime + analysisTime } var listenTimeStrings: [String] { get { var ret = [String]() ret.append("\(data.waitTimes[0]) sec") ret.append("\(data.waitTimes[1]) sec") ret.append("\(data.waitTimes[2]) sec") return ret } } var analysisTimeStrings: [String] { get { var ret = [String]() ret.append("\(data.analysisTimes[0]) sec") ret.append("\(data.analysisTimes[1]) sec") ret.append("\(data.analysisTimes[2]) sec") return ret } } func needleValue(forPrecision precision: Precision) -> Double { switch precision { case .bullsEye: return 0.00 case .inner: return 0.25 case .middle: return 0.50 case .outer: return 0.75 case .edge: return 1.00 } } init(colorScheme: ColorScheme) { if colorScheme == .light { preferencesButton = "settings" preferencesButtonOpacity = 0.6 primaryColor = Color(red: 255.0/255.0, green: 83.0/255.0, blue: 77.0/255.0) secondaryColor = Color(red: 255.0/255.0, green: 220.0/255.0, blue: 218.0/255.0) gray = Color(red: 88/255.0, green: 89/255.0, blue: 82/255.0) lightGray = Color(red: 188/255.0, green: 189/255.0, blue: 182/255.0) } else { // dark preferencesButton = "settings.dark" preferencesButtonOpacity = 1.0 primaryColor = Color(red: 242.0/255.0, green: 224.0/255.0, blue: 136.0/255.0) secondaryColor = Color(white: 0.7) gray = Color(white: 0.5) lightGray = Color(white: 0.7) } Needle.shared.setValue(needleValue(forPrecision: .middle)) } } <file_sep>// // StampModel.swift // Truth-O-Meter (iOS) // // Created by <NAME> on 15/09/2021. // import CoreGraphics struct StampModel { let padding: Double let borderWidth: Double let cornerRadius: Double let scale: Double let maskSize: Double let largeFontSize = 300.0 init(fw: Float, fh: Float, tw: Float, th: Float, angle: Float) { /// /// for the math, see rectangleRotation.pptx /// /// swift is very slow to compile Double atan, etc. Float precision is sufficient here let marginFactor: Float = 0.4 let borderWidthFactor: Float = 0.25 /// make sure that border is smaller than the margin. /// The border is drawn inside the margin let alpha:Float = max(angle, -angle) let m: Float = th * marginFactor let twm: Float = tw + 2.0 * m let thm: Float = th + 2.0 * m let b:Float = th * borderWidthFactor let thr: Float = sin( alpha + atan( thm / twm ) ) * sqrt(twm*twm+thm*thm) let twr: Float = sin(alpha)*thm + cos(alpha)*twm let outerCornerRadius: Float = Float(1.5) * b + Float(0.5) * b let beta2: Float = (Float(45.0) * Float.pi / Float(180.0)) - alpha let offset: Float = outerCornerRadius * ( sqrt(Float(2.0)) * cos(beta2) - Float(1.0)) /// set the mask size large /// this allows me to handle single characters /// with angles like 80 degrees let sw: Float = fw / (twr - Float(2.0) * offset) let sh: Float = fh / (thr - Float(2.0) * offset) padding = Double(m) borderWidth = Double(b) cornerRadius = Double(1.5*b) maskSize = Double(max(twr, thr)) scale = Double(min(sw, sh)) } } <file_sep>// // Truth_O_MeterApp.swift // Shared // // Created by <NAME> on 11/10/20. // import SwiftUI @main struct Truth_O_MeterApp: App { // force window size on Mac #if targetEnvironment(macCatalyst) @UIApplicationDelegateAdaptor var delegate: FSAppDelegate #endif @State private var isTapped = false var body: some Scene { return WindowGroup { MainView() } } } #if targetEnvironment(macCatalyst) class FSSceneDelegate: NSObject, UIWindowSceneDelegate, ObservableObject { func scene( _ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions ) { UIApplication.shared.connectedScenes .compactMap { $0 as? UIWindowScene } .forEach { windowScene in if let restrictions = windowScene.sizeRestrictions { let size = CGSize(width: 375.0 * 1.5, height: 667.0 * 1.5) restrictions.minimumSize = size restrictions.maximumSize = size } } } } class FSAppDelegate: NSObject, UIApplicationDelegate { func application( _ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions ) -> UISceneConfiguration { let sceneConfig = UISceneConfiguration(name: nil, sessionRole: connectingSceneSession.role) sceneConfig.delegateClass = FSSceneDelegate.self return sceneConfig } } #endif
8bb6f19b3ae4526ef5874e193a2c13a4b638ccc8
[ "Swift", "Markdown" ]
24
Swift
joachimneumann/Truth-O-Meter
9188688ea83d36578772cdd067fbc052a5b10a15
56cc0e0d92f1f05599faaed4acf5c9fbeb026b63
refs/heads/master
<file_sep>// // main.swift // ByPass // // Created by <NAME> on 4/4/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import SystemConfiguration class ByPass { static func doByPass() { let authFlags: AuthorizationFlags = [.Defaults , .ExtendRights , .InteractionAllowed , .PreAuthorize] var authRef: AuthorizationRef = AuthorizationRef.init(nilLiteral: ()) let fileManager = NSFileManager() let path = fileManager.currentDirectoryPath + "/ByPassList.plist" guard fileManager.fileExistsAtPath(path), let byPassList = NSArray.init(contentsOfFile: path) else { print("invalid plist / plist path") return } let authErr = AuthorizationCreate(nil, nil, authFlags, &authRef) if authErr != noErr{ print("authErr") return } let prefRef = SCPreferencesCreateWithAuthorization(nil, "ByPass", nil, authRef)! let sets = SCPreferencesGetValue(prefRef, kSCPrefNetworkServices)! var proxies = [NSObject : AnyObject]() proxies[kCFNetworkProxiesHTTPEnable] = 0//关闭 http 代理 proxies[kCFNetworkProxiesHTTPSEnable] = 0 proxies[kCFNetworkProxiesProxyAutoConfigEnable] = 0 proxies[kCFNetworkProxiesSOCKSProxy] = "127.0.0.1"//打开 SS 代理 proxies[kCFNetworkProxiesSOCKSPort] = 1080 proxies[kCFNetworkProxiesSOCKSEnable] = 1 proxies[kCFNetworkProxiesExceptionsList] = byPassList //设置例外 print(sets) print("---") //// 遍历系统中的网络设备列表,设置 AirPort 和 Ethernet 的代理 sets.allKeys!.forEach { (key) in let dict = sets.objectForKey(key)! let hardware = dict.valueForKeyPath("Interface.Hardware") as! NSString if ["AirPort","Wi-Fi","Ethernet"].contains(hardware) { print("\(kSCPrefNetworkServices)/\(key)/\(kSCEntNetProxies)") print(SCPreferencesPathSetValue(prefRef, "/\(kSCPrefNetworkServices)/\(key)/\(kSCEntNetProxies)", proxies))//注意这里的路径,一开始少了一个'/' } } SCPreferencesCommitChanges(prefRef) SCPreferencesApplyChanges(prefRef) SCPreferencesSynchronize(prefRef) } } ByPass.doByPass()<file_sep># ProxyBypass It's a OS X program to set the proxy&amp; its exceptional bypass rules.
97c2f777a9c0ed0fa42cca903df03cac7d00afbd
[ "Swift", "Markdown" ]
2
Swift
zzyyzz1992/ProxyBypass
74be35e19446630018692359df5bc680ef1bb72a
25e2e91cca59e819bf8b50c88111a2c633dc4aa1
refs/heads/master
<file_sep># -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html from datetime import datetime import scrapy from scrapy.loader import ItemLoader from scrapy import Field from scrapy.loader.processors import TakeFirst, MapCompose, Join, Compose class NewItemLoader(ItemLoader): default_output_processor = TakeFirst() def get_text(value): return value.strip() def get_source(value): return value.strip() def get_date_time(value): date = datetime.strptime(value, '%Y-%m-%d %H:%M:%S') return date class NewItem(scrapy.Item): title = Field() time = Field(input_processor=MapCompose(get_date_time)) url = Field() text = Field( input_processor=MapCompose(get_text), output_processor = Join() ) source = Field(input_processor=MapCompose(get_source)) <file_sep># Technology_news_spider https://tech.china.com/articles/ 用crawlspider快速爬取中华科技网,并存入mysql ![image](https://github.com/FrankYang3110/img-folder/blob/master/News.png) <file_sep># -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html from twisted.enterprise import adbapi import MySQLdb from MySQLdb.cursors import DictCursor class NewPipeline(object): def process_item(self, item, spider): return item class MysqlPipeline(object): def __init__(self, dbpool): self.dbpool = dbpool @classmethod def from_crawler(cls, crawler): params= dict(host=crawler.settings.get('HOST'), user=crawler.settings.get('USER'), passwd=crawler.settings.get('PASSWORD'), db=crawler.settings.get('DB'), charset='utf8', use_unicode=True, cursorclass=DictCursor, ) dbpool = adbapi.ConnectionPool('MySQLdb', **params) return cls(dbpool) def process_item(self, item, spider): query = self.dbpool.runInteraction(self.insert_into, item) query.addErrback(self.handle_failure, item, spider) def handle_failure(self, failure, item, spider): print(failure) def insert_into(self, cursor, item): insert_sql = """ INSERT INTO news(title, url, text, source, time) VALUES(%s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE text=VALUES(text), source=VALUES(source), time=VALUES(time) """ cursor.execute(insert_sql, (item['title'],item['url'],item['text'],item['source'],item['time'])) <file_sep># -*- coding: utf-8 -*- import scrapy from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule from New.items import NewItem, NewItemLoader class TechSpider(CrawlSpider): name = 'tech' allowed_domains = ['tech.china.com'] start_urls = ['https://tech.china.com/articles/'] rules = ( Rule(LinkExtractor(allow='http://tech.china.com/article/.*\.html', restrict_xpaths='//div[@id="left_side"]'), callback='parse_item'), Rule(LinkExtractor(restrict_xpaths='//div[@id="pageStyle"]//a[contains(text(),"下一页")]')) ) def parse_item(self, response): item_loader = NewItemLoader(NewItem(), response) item_loader.add_xpath('title', '//div[@id="chan_newsBlk"]/h1/text()') item_loader.add_xpath('time', '//div[@id="chan_newsInfo"]/text()', re='(\d+-\d+-\d+\s\d+:\d+:\d+)') item_loader.add_value('url', response.url) item_loader.add_xpath('text', '//div[@id="chan_newsDetail"]//text()') item_loader.add_xpath('source', '//div[@id="chan_newsInfo"]/text()', re='来源:(.*)') new_item = item_loader.load_item() yield new_item <file_sep>#!/usr/bin/env python # -*- coding:utf-8 -*- import os import sys from scrapy import cmdline sys.path.append(os.path.dirname(os.path.abspath(__file__))) cmdline.execute(['scrapy', 'crawl', 'tech'])
d72f2377aa7866cc16aa5c141c3d58a6f98a3d19
[ "Markdown", "Python" ]
5
Python
FrankYang3110/Technology_news_spider
f282d4e312b38201fdac423c5e9b13a1902017ef
74314d37ae4d549fa5d174fe6fc9d357cbc094ae
refs/heads/main
<file_sep><?php // autoload_classmap.php @generated by Composer $vendorDir = dirname(dirname(__FILE__)); $baseDir = dirname($vendorDir); return array( 'Attribute' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Attribute.php', 'JsonException' => $vendorDir . '/symfony/polyfill-php73/Resources/stubs/JsonException.php', 'Normalizer' => $vendorDir . '/symfony/polyfill-intl-normalizer/Resources/stubs/Normalizer.php', 'Stringable' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Stringable.php', 'UnhandledMatchError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php', 'ValueError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/ValueError.php', 'WebToPay' => $vendorDir . '/webtopay/libwebtopay/src/WebToPay.php', 'WebToPayException' => $vendorDir . '/webtopay/libwebtopay/src/WebToPayException.php', 'WebToPay_CallbackValidator' => $vendorDir . '/webtopay/libwebtopay/src/WebToPay/CallbackValidator.php', 'WebToPay_Exception_Callback' => $vendorDir . '/webtopay/libwebtopay/src/WebToPay/Exception/Callback.php', 'WebToPay_Exception_Configuration' => $vendorDir . '/webtopay/libwebtopay/src/WebToPay/Exception/Configuration.php', 'WebToPay_Exception_Validation' => $vendorDir . '/webtopay/libwebtopay/src/WebToPay/Exception/Validation.php', 'WebToPay_Factory' => $vendorDir . '/webtopay/libwebtopay/src/WebToPay/Factory.php', 'WebToPay_PaymentMethod' => $vendorDir . '/webtopay/libwebtopay/src/WebToPay/PaymentMethod.php', 'WebToPay_PaymentMethodCountry' => $vendorDir . '/webtopay/libwebtopay/src/WebToPay/PaymentMethodCountry.php', 'WebToPay_PaymentMethodGroup' => $vendorDir . '/webtopay/libwebtopay/src/WebToPay/PaymentMethodGroup.php', 'WebToPay_PaymentMethodList' => $vendorDir . '/webtopay/libwebtopay/src/WebToPay/PaymentMethodList.php', 'WebToPay_PaymentMethodListProvider' => $vendorDir . '/webtopay/libwebtopay/src/WebToPay/PaymentMethodListProvider.php', 'WebToPay_RequestBuilder' => $vendorDir . '/webtopay/libwebtopay/src/WebToPay/RequestBuilder.php', 'WebToPay_Sign_SS1SignChecker' => $vendorDir . '/webtopay/libwebtopay/src/WebToPay/Sign/SS1SignChecker.php', 'WebToPay_Sign_SS2SignChecker' => $vendorDir . '/webtopay/libwebtopay/src/WebToPay/Sign/SS2SignChecker.php', 'WebToPay_Sign_SignCheckerInterface' => $vendorDir . '/webtopay/libwebtopay/src/WebToPay/Sign/SignCheckerInterface.php', 'WebToPay_SmsAnswerSender' => $vendorDir . '/webtopay/libwebtopay/src/WebToPay/SmsAnswerSender.php', 'WebToPay_UrlBuilder' => $vendorDir . '/webtopay/libwebtopay/src/WebToPay/UrlBuilder.php', 'WebToPay_Util' => $vendorDir . '/webtopay/libwebtopay/src/WebToPay/Util.php', 'WebToPay_WebClient' => $vendorDir . '/webtopay/libwebtopay/src/WebToPay/WebClient.php', ); <file_sep><?php namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; class TestController extends AbstractController { /** * @Route("/", name="test") */ public function index(): Response { return $this->json([ 'message' => 'Welcome to your new controller!', 'path' => 'src/Controller/TestController.php', ]); } }
3b1b69992d754d0c26a81be989630721d2406529
[ "PHP" ]
2
PHP
kenrebane/symfony-skeleton
afecd588a6e78e6073c79ac5ef2125a9330ac9e0
1df57522cbe30ce1e0de25050b2127e85ee05947
refs/heads/main
<repo_name>Qniceeee/chromeExt<file_sep>/script.js "use strict" let buttonClick = document.getElementById('buttonId'); if(buttonClick){ buttonClick.addEventListener('click', onClick1, false); } let domElements = { docX1: document.getElementById('text1'), docX2: document.getElementById('text2'), docX3: document.getElementById('text3'), docImage: document.getElementById('image'), } function onClick1 () { domElements.docImage.innerHTML = '<img title="Только не нажимай на нее" height="200" src="images/onTap.gif">'; domElements.docX1.innerHTML = 'Не кликай'; setTimeout(onLoaded, 2000); } function onLoaded () { domElements.docImage.innerHTML = '<img title="Только не нажимай на нее" height="200" src="images/start.gif">'; domElements.docX1.innerHTML = 'Привет я тут новенькая ;0'; }
9a91f25fad1f3a7600bfbb9d53cce3a2ea22a0f7
[ "JavaScript" ]
1
JavaScript
Qniceeee/chromeExt
122e37f367f91aee398cf8395ce6c60ae6001cbc
a4460b277780cfe72c75849d1856434be923dc63
refs/heads/master
<repo_name>MayraPerpetua/PRD-Telemetry-IoT<file_sep>/lora-transmissor.ino #include <SoftwareSerial.h> #include <HCSR04.h> SoftwareSerial loraSerial(2, 3); // TX, RX String water = "water"; String no_water = "no_water"; // Initialize sensor that uses digital pins 13 and 12. int triggerPin = 13; int echoPin = 12; UltraSonicDistanceSensor distanceSensor (triggerPin, echoPin); void setup() { Serial.begin(9600); loraSerial.begin(9600); } void loop() { float estado = analogRead (A5); Serial.println(estado); delay(10); if(estado > 300) { loraSerial.print(water); while(analogRead(A5) > 300); delay(50); } else if(estado <= 200) { loraSerial.print(no_water); while(analogRead(A5) <= 200); delay(50); } // Every 500 miliseconds, do a measurement using the sensor and print the distance in centimeters. double distance = distanceSensor.measureDistanceCm(); Serial.println(distance); delay(500); loraSerial.print(distance); delay(500); } <file_sep>/README.md # Telemetria - IoT Pequeno projeto de IoT com módulos LoRa(Long Range), nele foi implemetado um sensor de umidade, sensor ultrassônico e alguns atuadores para a sinalzação. <file_sep>/lora-receptor (1).ino #include <SoftwareSerial.h> #include <HCSR04.h> #define LEDV 4 #define LEDA 6 SoftwareSerial loraSerial(2, 3); // TX, RX void setup() { pinMode(LEDV, OUTPUT); // led vermelho pinMode(LEDA, OUTPUT); // led Azul Serial.begin(9600); loraSerial.begin(9600); } void loop() { if(loraSerial.available() > 1){ String input = loraSerial.readString(); Serial.println(input); if(input == "water") { digitalWrite(LEDA, HIGH); digitalWrite(LEDV, LOW); } if(input == "no_water") { digitalWrite(LEDA, LOW); digitalWrite(LEDV, HIGH); } } delay(20); String input = loraSerial.readString(); Serial.println(input); if(input == "distance"); loraSerial.print("distance"); delay (500); }
48d7f510400895cb65e90cbc1fc17eb653ae2f62
[ "Markdown", "C++" ]
3
C++
MayraPerpetua/PRD-Telemetry-IoT
33257803a48e9840393468f37ab68198345fef80
7f5ccda93dea7ec4e38fa4f5bdacf96c397a3efe
refs/heads/main
<repo_name>Dhruvil30/todo-api<file_sep>/src/utils/helper.js module.exports = { getUserId: (req) => { const env = process.env.NODE_ENV; if (env === 'local') return req.session.userId; return req.get('userId'); }, }; <file_sep>/src/components/user/user.validation.js const Joi = require('joi'); module.exports = { createUserSchema: Joi.object().keys({ name: Joi.string().min(3).max(30).required(), email: Joi.string() .email({ tlds: { allow: false } }) .required(), password: Joi.string().min(3).max(15).required(), }), loginUserSchema: Joi.object().keys({ email: Joi.string() .email({ tlds: { allow: false } }) .required(), password: Joi.string().min(3).max(15).required(), }), }; <file_sep>/src/utils/constant.js module.exports = { rateLimitTime: 5 * 60 * 1000, rateLimitMaxReq: 5, rateLimitApis: ['/users/verify-reg/', '/users/disapprove-reg/'], }; <file_sep>/src/utils/discord-bot.js require('dotenv').config(); const rp = require('request-promise'); const discordWebhookUrl = process.env.DISCORD_URL; const defineDiscordObject = (data) => { const fieldsList = []; for (const note of data) { const value = `${note.description}\n${note.reminderTime.toISOString().substring(11, 19)}`; fieldsList.push({ name: note.name, value: value, }); } return { fields: fieldsList, color: 14177041, }; }; const message = (userName, data) => { const discordObject = { username: 'Todos Bot', content: '**```Todos for ' + userName + '```**', embeds: [], }; discordObject.embeds.push(defineDiscordObject(data)); return discordObject; }; module.exports.sentDiscordNotification = (userName, data) => { const options = { method: 'POST', uri: discordWebhookUrl, body: message(userName, data), json: true, }; rp(options); }; <file_sep>/src/utils/registraction-email.js const API_KEY = process.env.MAILGUN_API_KEY; const DOMAIN = process.env.MAILGUN_DOMAIN; const JWT_KEY = process.env.JWT_KEY; const jwt = require('jsonwebtoken'); const mailgun = require('mailgun-js')({ apiKey: API_KEY, domain: DOMAIN }); const createMailOpions = (data, urls) => { const options = { from: '<EMAIL>', to: data.email, subject: 'Registration Confirmation from nodemailer', text: `Hello ${data.name} \nPlease confirm registration by clicking on below link. \n${urls.verificationUrl} \nNot you, click below link to disapprove registration. \n${urls.disapproveUrl}`, }; return options; }; const generateUrl = (id) => { const token = jwt.sign(id, JWT_KEY); const hostUrl = process.env.HOST_URL; const verificationUrl = `${hostUrl}/users/verify-reg/${token}`; const disapproveUrl = `${hostUrl}/users/disapprove-reg/${token}`; return { verificationUrl, disapproveUrl, }; }; const sendRegistrationEmail = async (data) => { try { const urls = generateUrl(data.id); const mailOptions = createMailOpions(data, urls); await mailgun.messages().send(mailOptions); } catch (error) { throw error; } }; module.exports = { sendRegistrationEmail, }; <file_sep>/src/socket/index.js const socketServer = require('socket.io'); const noteEvent = require('./note-events/noteEvent.route'); module.exports.listen = (server, app) => { const io = socketServer.listen(server); app.set('io', io); noteEvent.connectUser(io); }; <file_sep>/src/components/note/note.validation.js const Joi = require('joi'); module.exports = { createNoteSchema: Joi.object().keys({ name: Joi.string().min(3).max(30).required(), description: Joi.string().min(5).max(200).required(), reminderTime: Joi.date().iso().required(), }), updateNoteSchema: Joi.object().keys({ name: Joi.string().min(3).max(30), description: Joi.string().min(5).max(200), reminderTime: Joi.date().iso(), }), }; <file_sep>/src/components/index.js const userRoutes = require('./user/user.route'); const noteRoutes = require('./note/note.route'); module.exports = { userRoutes, noteRoutes, }; <file_sep>/src/components/note/note.test.js process.env.NODE_ENV = 'TEST'; const chai = require('chai'); const chaiHttp = require('chai-http'); const server = require('../../../bin/www'); const errorCodes = require('../../utils/error-codes'); const UserModel = require('../../lib/mongooseConfig').models.userModel; const { noteTestData } = require('../../utils/test-vars'); chai.should(); chai.use(chaiHttp); const baseRoute = '/notes'; const userId = noteTestData.userId; const noteId = noteTestData.noteId; const invalidNoteId = '000000000000'; const checkValidNoteData = (note) => { note.should.have.property('name').be.a('string'); note.should.have.property('description').be.a('string'); note.should.have.property('reminderTime'); }; describe('Note APIs', () => { before(async () => { const userData = new UserModel(noteTestData.testData); await userData.save(); }); describe('GET /notes', () => { it('Should return all notes', () => chai .request(server) .get(baseRoute) .set('userId', userId) .then((res) => { res.status.should.be.equal(200); res.body.should.be.an('array'); res.body.forEach((note) => checkValidNoteData(note)); })); it('Unauthorizaed Access on get all notes route', () => chai .request(server) .get(baseRoute) .then((res) => { res.status.should.be.equal(errorCodes.UNAUTHORIZED.statusCode); })); }); describe('GET /notes/search/today', () => { it('Should return note for today', () => chai .request(server) .get(`${baseRoute}/search/today`) .set('userId', userId) .then((res) => { res.status.should.be.equal(200); res.body.should.be.an('array'); res.body.forEach((note) => checkValidNoteData(note)); })); it("Unauthorizaed Access on search today's note route", () => chai .request(server) .get(`${baseRoute}/search/today`) .then((res) => { res.status.should.be.equal(errorCodes.UNAUTHORIZED.statusCode); })); }); describe('GET /notes/search?name=searchName', () => { it('Should return note that match search name', () => chai .request(server) .get(`${baseRoute}/search?name=implement`) .set('userId', userId) .then((res) => { res.status.should.be.equal(200); res.body.should.be.an('array'); res.body.forEach((note) => checkValidNoteData(note)); })); it('Unauthorizaed Access on search note by name route', () => chai .request(server) .get(`${baseRoute}/search?name=implement`) .then((res) => { res.status.should.be.equal(errorCodes.UNAUTHORIZED.statusCode); })); }); describe('GET /notes/note/:id', () => { it('Valid id to get', () => chai .request(server) .get(`${baseRoute}/note/${noteId}`) .set('userId', userId) .then((res) => { res.status.should.be.equal(200); checkValidNoteData(res.body); })); it('Invalid id to get', () => chai .request(server) .get(`${baseRoute}/note/${invalidNoteId}`) .set('userId', userId) .then((res) => { res.status.should.be.equal(errorCodes.RESOURCE_NOT_FOUND.statusCode); })); it('Unauthorizaed Access on get note route', () => chai .request(server) .get(`${baseRoute}/note/${noteId}`) .then((res) => { res.status.should.be.equal(errorCodes.UNAUTHORIZED.statusCode); })); }); describe('POST /notes', () => { const validDataToPost = { name: '<NAME>', description: 'Post note when testing', reminderTime: '2021-05-24T05:30:00.000+00:00', }; const invalidDataToPost = { name: '<NAME>', description: 'Post note when testing', }; it('Valid data to post', () => chai .request(server) .post(baseRoute) .set('userId', userId) .send(validDataToPost) .then((res) => { res.status.should.be.equal(201); })); it('Invalid data to post', () => chai .request(server) .post(baseRoute) .set('userId', userId) .send(invalidDataToPost) .then((res) => { res.status.should.be.equal(errorCodes.DATA_INVALID.statusCode); })); it('Unauthorizaed Access on post route', () => chai .request(server) .post(baseRoute) .send(validDataToPost) .then((res) => { res.status.should.be.equal(errorCodes.UNAUTHORIZED.statusCode); })); }); describe('PUT /notes/note/:id', () => { const validDataToUpdate = { name: 'Updated name', description: 'Updated description', }; const invalidDataToUpdate = { note_name: 'Updated name', description: 'Updated description', }; it('Valid data to update', () => chai .request(server) .put(`${baseRoute}/note/${noteId}`) .set('userId', userId) .send(validDataToUpdate) .then((res) => { res.status.should.be.equal(200); })); it('Invalid data to update', () => chai .request(server) .put(`${baseRoute}/note/${noteId}`) .set('userId', userId) .send(invalidDataToUpdate) .then((res) => { res.status.should.be.equal(errorCodes.DATA_INVALID.statusCode); })); it('Invalid id to update', () => chai .request(server) .put(`${baseRoute}/note/${invalidNoteId}`) .set('userId', userId) .send(validDataToUpdate) .then((res) => { res.status.should.be.equal(errorCodes.RESOURCE_NOT_FOUND.statusCode); })); it('Unauthorizaed Access on put route', () => chai .request(server) .put(`${baseRoute}/note/${noteId}`) .send(validDataToUpdate) .then((res) => { res.status.should.be.equal(errorCodes.UNAUTHORIZED.statusCode); })); }); describe('Delete /notes/note/:id', () => { it('Valid id to delete', async () => chai .request(server) .delete(`${baseRoute}/note/${noteId}`) .set('userId', userId) .then((res) => { res.status.should.be.equal(204); })); it('Invalid id to delete', async () => chai .request(server) .delete(`${baseRoute}/note/${invalidNoteId}`) .set('userId', userId) .then((res) => { res.status.should.be.equal(errorCodes.RESOURCE_NOT_FOUND.statusCode); })); it('Unauthorizaed Access on delete route', () => chai .request(server) .delete(`${baseRoute}/note/${noteId}`) .then((res) => { res.status.should.be.equal(errorCodes.UNAUTHORIZED.statusCode); })); }); }); <file_sep>/src/components/user/user.test.js process.env.NODE_ENV = 'TEST'; const chai = require('chai'); const chaiHttp = require('chai-http'); const sinon = require('sinon'); const server = require('../../../bin/www'); const errorCodes = require('../../utils/error-codes'); const UserModel = require('../../lib/mongooseConfig').models.userModel; const { userTestData } = require('../../utils/test-vars'); const registrationEmail = require('../../utils/registraction-email'); chai.should(); chai.use(chaiHttp); const baseRoute = '/users'; const userId = userTestData.userId; describe('User APIs', () => { before(async () => { const users = userTestData.users; for (userData of users) { const user = new UserModel(userData); await user.save(); } }); describe('POST /users/login', () => { const validLoginData = { email: '<EMAIL>', password: '<PASSWORD>', }; const invalidLoginData = { name: 'Dhruvil', password: '<PASSWORD>', }; it('Valid data to login', () => chai .request(server) .post(`${baseRoute}/login`) .send(validLoginData) .then((res) => { res.status.should.be.equal(200); res.body.should.have.property('id').be.a('string'); res.body.should.have.property('name').be.a('string'); })); it('Invalid data to login', () => chai .request(server) .post(`${baseRoute}/login`) .send(invalidLoginData) .then((res) => { res.status.should.be.equal(errorCodes.DATA_INVALID.statusCode); })); it('User already logged in', () => chai .request(server) .post(`${baseRoute}/login`) .set('userId', userId) .send(validLoginData) .then((res) => { res.status.should.be.equal(errorCodes.USER_LOGGED_IN.statusCode); })); }); describe('POST /users/register', () => { const validRegisterData = { name: '<NAME>', email: '<EMAIL>', password: '<PASSWORD>', }; const invalidRegisterData = { id: '000user01236', name: '<NAME>', password: '<PASSWORD>', }; it('Valid data to register', () => { sinon.stub(registrationEmail, 'sendRegistrationEmail') .callsFake((req, res, next) => next()); chai .request(server) .post(`${baseRoute}/register`) .send(validRegisterData) .then((res) => { res.status.should.be.equal(201); res.body.should.have.property('id').be.a('string'); res.body.should.have.property('name').be.a('string'); }); }); it('Duplicate data to register', () => chai .request(server) .post(`${baseRoute}/register`) .send(validRegisterData) .then((res) => { res.status.should.be.equal(errorCodes.DUPLICATE_KEY_ERROR.statusCode); })); it('Invalid data to register', () => chai .request(server) .post(`${baseRoute}/register`) .send(invalidRegisterData) .then((res) => { res.status.should.be.equal(errorCodes.DATA_INVALID.statusCode); })); it('User already logged in', () => chai .request(server) .post(`${baseRoute}/register`) .set('userId', userId) .send(validRegisterData) .then((res) => { res.status.should.be.equal(errorCodes.USER_LOGGED_IN.statusCode); })); }); describe('GET /users/logout', () => { it('Valid user logout', () => chai .request(server) .get(`${baseRoute}/logout`) .set('userId', userId) .then((res) => { res.status.should.be.equal(200); })); it('Unauthorizaed Access on logout route', () => chai .request(server) .get(`${baseRoute}/logout`) .then((res) => { res.status.should.be.equal(errorCodes.UNAUTHORIZED.statusCode); })); }); }); <file_sep>/src/socket/note-events/noteEvent.controller.js module.exports = { connectUser: (socket) => { const userId = socket.handshake.query.userId; if (userId) socket.join(userId); }, disconnectUser: (socket) => { const userId = socket.handshake.query.userId; if (userId) socket.leave(userId); }, sendUpdatedData: (data, userId, io) => { io.to(userId).emit('newNoteAdded', data); }, }; <file_sep>/src/components/user/user.controller.js const userService = require('./user.service'); const { sendRegistrationEmail } = require('../../utils/registraction-email'); const filterData = (data) => { const returnObj = { id: data.id, name: data.name, email: data.email, }; return returnObj; }; module.exports = { login: async (req, res, next) => { try { const data = req.body; const eventData = await userService.authenticate(data); req.session.userId = eventData.id; req.session.userName = eventData.name; const filteredData = filterData(eventData); res.status(200).json(filteredData); } catch (error) { next(error); } }, register: async (req, res, next) => { try { const data = req.body; const eventData = await userService.create(data); const filteredData = filterData(eventData); await sendRegistrationEmail(filteredData); res.status(201).json(filteredData); } catch (error) { next(error); } }, logout: async (req, res) => { req.session.userId = null; res.status(200).json({ message: 'User Logged Out.' }); }, verifyReg: async (req, res, next) => { try { const userId = req.jwtId; await userService.verifyUser(userId); res.status(200).json({ message: 'Your email is verified.' }); } catch (error) { next(error); } }, disapproveReg: async (req, res, next) => { try { const userId = req.jwtId; await userService.disapproveUser(userId); res.status(200).json({ message: 'Your registration is disapproved.' }); } catch (error) { next(error); } }, }; <file_sep>/src/utils/todo-scheduler.js require('dotenv').config(); const { CronJob } = require('cron'); const { sentDiscordNotification } = require('./discord-bot'); const userService = require('../components/user/user.service'); const noteService = require('../components/note/note.service'); const formatNotesData = (data) => { if (!data.length) return []; return data[0].notes.map((note) => { const formatedData = { name: note.name, description: note.description, reminderTime: note.reminderTime, }; return formatedData; }); }; const sendTodayTask = async (user) => { const data = await noteService.getTodayNotes(user.id); const formatedData = formatNotesData(data); if (formatedData.length) sentDiscordNotification(user.name, formatedData); }; const sendNotification = async (users) => { const usersPromises = []; users.forEach((user) => usersPromises.push(new Promise(() => sendTodayTask(user)))); try { await Promise.all(usersPromises); } catch (error) { throw error; } }; module.exports = { getUsersData: async () => { const userData = await userService.getAllUserForTodoScheduler(); return userData; }, runScheduler: (users) => { const job = new CronJob('* * * * *', () => { sendNotification(users); }); job.start(); }, }; <file_sep>/src/utils/test/error.res.test.js require('dotenv').config(); const chai = require('chai'); const resGenerator = require('../response-generator'); chai.should(); describe('Error Response Test', () => { it('Should return error message with http status code', () => { const error = new Error('RESOURCE_NOT_FOUND'); const response = resGenerator.generateErrorResponse(error); response.statusCode.should.be.a('number'); response.body.should.have.property('code').be.a('string'); response.body.should.have.property('message').be.a('string'); }); }); <file_sep>/src/utils/test-vars.js module.exports = { userTestData: { userId: '000user01234', users: [ { _id: '000user01234', name: 'Dhruvil', email: '<EMAIL>', password: '<PASSWORD>', notes: [], }, { _id: '000user01235', name: 'Kunal', email: '<EMAIL>', password: '<PASSWORD>', notes: [], }, ], }, noteTestData: { userId: '000user12345', noteId: '000note12345', testData: { _id: '000user12345', name: 'Dhruvil', email: '<EMAIL>', password: '<PASSWORD>', notes: [ { _id: '000note12345', name: 'Meeting', description: 'Meeting regarding discord message format', reminderTime: '2021-05-24T05:30:00.000+00:00', }, { _id: '000note12346', name: 'Implement', description: 'Implement discord message format task', reminderTime: '2021-05-24T05:30:00.000+00:00', }, { _id: '000note12347', name: 'Issue', description: 'Work on search by name issue in todo list', reminderTime: '2021-05-22T05:30:00.000+00:00', }, ], }, }, getNoteTestData: [ { name: 'Meeting', description: 'Meeting regarding discord message format', reminderTime: '2021-05-24T05:30:00.000Z', }, { name: 'Implement', description: 'Implement discord message format task', reminderTime: '2021-05-24T05:30:00.000Z', }, { name: 'Issue', description: 'Work on search by name issue in todo list', reminderTime: '2021-05-22T05:30:00.000Z', }, ], }; <file_sep>/src/components/user/user.route.js const express = require('express'); const validator = require('express-joi-validation').createValidator({ passError: true }); const userController = require('./user.controller'); const { checkSessionForLoggedInUser, checkSessionForLoggedOutUser, } = require('../../utils/verification'); const userValidation = require('./user.validation'); const { getIdFromToken, checkIsUserVerified } = require('../../utils/verification'); const router = express.Router(); router .route('/login') .post( checkSessionForLoggedOutUser, validator.body(userValidation.loginUserSchema), checkIsUserVerified, userController.login, ); router .route('/register') .post( checkSessionForLoggedOutUser, validator.body(userValidation.createUserSchema), userController.register, ); router.route('/logout').get(checkSessionForLoggedInUser, userController.logout); router.route('/verify-reg/:token').get(getIdFromToken, userController.verifyReg); router.route('/disapprove-reg/:token').get(getIdFromToken, userController.disapproveReg); module.exports = router; <file_sep>/src/utils/response-generator.js const errorCodes = require('./error-codes'); const { mongoose } = require('../lib/mongooseConfig'); module.exports = { generateErrorResponse: (error) => { if (error.name === 'MongoError') { if (error.code === 11000) return errorCodes.DUPLICATE_KEY_ERROR; if (error.code === 51270) return errorCodes.RESOURCE_NOT_FOUND; } if (error instanceof mongoose.Error.CastError) { return errorCodes.RESOURCE_NOT_FOUND; } if (error instanceof SyntaxError || error.error?.isJoi) { return errorCodes.DATA_INVALID; } return errorCodes[error.message] || errorCodes.INTERNAL_SERVER_ERROR; } }; <file_sep>/src/utils/verification.js const { JWT_KEY } = process.env; const jwt = require('jsonwebtoken'); const helper = require('./helper'); const { getUserByEmail } = require('../components/user/user.service'); module.exports = { checkSessionForLoggedOutUser: (req, res, next) => { const userId = helper.getUserId(req); if (!userId) next(); else throw new Error('USER_LOGGED_IN'); }, checkSessionForLoggedInUser: (req, res, next) => { const userId = helper.getUserId(req); if (userId) { req.user = {}; req.user.id = userId; next(); } else throw new Error('UNAUTHORIZED'); }, getIdFromToken: async (req, res, next) => { const { token } = req.params; try { const userId = jwt.verify(token, JWT_KEY); req.jwtId = userId; next(); } catch (error) { next(new Error('TOKEN_INVALID')); } }, checkIsUserVerified: async (req, res, next) => { const { email } = req.body; const user = await getUserByEmail(email); if (user) { if (user.verified) next(); else next(new Error('NOT_VERIFIED')); } else next(new Error('UNAUTHORIZED')); }, }; <file_sep>/src/socket/note-events/noteEvent.route.js const noteEventController = require('./noteEvent.controller'); module.exports = { connectUser: (io) => { io.on('connection', (socket) => { noteEventController.connectUser(socket); socket.on('disconnect', () => { noteEventController.disconnectUser(socket); }); }); }, }; <file_sep>/src/components/user/user.service.js const User = require('../../lib/mongooseConfig').models.userModel; module.exports = { authenticate: async (data) => { const eventData = data; const queryResult = await User.findOne(eventData); if (!queryResult) throw new Error('UNAUTHORIZED'); return queryResult; }, create: async (data) => { const eventData = new User(data); const queryResult = await eventData.save(); return queryResult; }, getAllUserForTodoScheduler: async () => { const queryResult = await User.find({}, { _id: 1, name: 1 }); return queryResult; }, getUserByEmail: async (email) => { const queryResult = await User.findOne({ email }); return queryResult; }, verifyUser: async (userId) => { const queryResult = await User.findById(userId); if (!queryResult) throw new Error('TOKEN_INVALID'); if (queryResult.verified === true) throw new Error('EMAIL_ALREADY_VERIFIED'); await queryResult.updateOne({ verified: true }); return queryResult; }, disapproveUser: async (userId) => { const queryResult = await User.findById(userId); if (!queryResult) throw new Error('TOKEN_INVALID'); if (queryResult.verified === true) throw new Error('EMAIL_ALREADY_VERIFIED'); await queryResult.delete(); return queryResult; }, }; <file_sep>/src/utils/error-codes.js module.exports = { DATA_NOT_MODIFIED: { statusCode: 304, body: { code: 'not_modified', message: 'Data not modified.', }, }, DATA_INVALID: { statusCode: 400, body: { code: 'bad_request', message: 'Invalid data.', }, }, TOKEN_INVALID: { statusCode: 400, body: { code: 'bad_request', message: 'Invalid token.', }, }, PARAMS_INVALID: { statusCode: 400, body: { code: 'bad_request', message: 'Invalid parameter.', }, }, EMAIL_ALREADY_VERIFIED: { statusCode: 400, body: { code: 'bad_request', message: 'Email is already verified.', }, }, UNAUTHORIZED: { statusCode: 401, body: { code: 'unauthorized', message: 'User is unauthorized for access.', }, }, NOT_VERIFIED: { statusCode: 401, body: { code: 'unauthorized', message: 'Email is not verified.', }, }, RESOURCE_NOT_FOUND: { statusCode: 404, body: { code: 'not_found', message: 'Resource not found.', }, }, USER_LOGGED_IN: { statusCode: 409, body: { code: 'conflict', message: 'User is already logged in.', }, }, DUPLICATE_KEY_ERROR: { statusCode: 409, body: { code: 'conflict', message: 'Duplicate key error.', }, }, INTERNAL_SERVER_ERROR: { statusCode: 500, body: { code: 'internal_server_error', message: 'Something wrong with the server.', }, }, }; <file_sep>/.eslintrc.js module.exports = { env: { browser: true, es6: true, }, extends: [ 'airbnb-base', ], globals: { Atomics: 'readonly', SharedArrayBuffer: 'readonly', }, parserOptions: { ecmaVersion: 10, sourceType: 'module', }, // eslintIgnore: [ // '*.test.js', // ], rules: { 'no-useless-catch': 0, 'no-underscore-dangle': 0, 'class-methods-use-this': 0, 'max-len': ['error', { code: 100 }], 'no-unused-vars': ['error', { argsIgnorePattern: '^_' }], }, }; <file_sep>/src/lib/mongooseConfig.js const mongoose = require('mongoose'); const { MongoMemoryServer } = require('mongodb-memory-server'); const userModel = require('../components/user/user.model'); const makeTestDbConnection = () => { const mongoServer = new MongoMemoryServer(); const mongooseOptions = { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: false, }; mongoServer.getUri().then((mongoUri) => { mongoose.connect(mongoUri, mongooseOptions); }); }; const makeDbConnection = async () => { const mongooseOptions = { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: false, }; await mongoose.connect(process.env.DATABASE_URL, mongooseOptions); }; const env = process.env.NODE_ENV; if (env === 'TEST') makeTestDbConnection(); else if (env === 'local') makeDbConnection(); mongoose.connection.on('error', (error) => { if (error) throw error; }); module.exports = { mongoose, models: { userModel, }, };
916500835fd6284079e2ee696951ef65bfda8768
[ "JavaScript" ]
23
JavaScript
Dhruvil30/todo-api
b427d1f840c9bc41e80159aff5184d279830598a
572c2613911beb06df7b83f87d7b91c4c4d54386
refs/heads/master
<repo_name>khandaker71/khandaker<file_sep>/NewProject/src/lesson/Exercise_1.java package lesson; import java.util.Scanner; public class Exercise_1 { public static void main(String[] args) { // convert ferenheit to celcious Scanner sca = new Scanner(System.in); System.out.println("Enter a degree in Fahrenheit: "); double ferenheit = sca.nextDouble(); double celsious = (5.0 / 9) * (ferenheit - 32); System.out.println("ferenheit " + ferenheit + " is " + celsious + " in celcious "); System.out.println("-------------------------------------------------------------------------"); //convert pounds to kilogram Scanner pca = new Scanner(System.in); System.out.println("Enter a number in pounds : "); double pound = pca.nextDouble(); double kilo = (pound * 0.454); System.out.println( pound + " pounds is " + kilo + " kilogram "); } }
8923540295f71edf845866c87d0b5b433d96e54e
[ "Java" ]
1
Java
khandaker71/khandaker
b228b9296377e7b1fd6c74a42462b190e3e12de3
242a4767fc8b5b3f48123e17a1aa90e1b78efac3
refs/heads/master
<file_sep>def ATM(amount): # ATM machine change given in $50s and $20s initalAmount = amount n50s = 0; n20s = 0; finish = False; while finish == False: if amount % 50 == 0: n50s = amount / 50; finish = True; else: amount = amount - 20; n20s = n20s + 1; print ("you have withdrawn " + str(amount+(n20s*20))); print ("you will receive " + str(n50s) + " $50 notes and " + str(n20s) + " $20 notes");
169b819e73ed2f09f4647e50c4aa24b0b8d8d5d0
[ "Python" ]
1
Python
michaelstanfield/Stan-Glen-GitHub
e088b19351f6df92ea414125a415f78f9b9de382
ba917f435667a3e59017ab16fbf8587e57914c30
refs/heads/master
<repo_name>livrush/animation<file_sep>/index.js const iframeSrcs = [ '', '', '', '', '', '', '', '', '', '', 'https://daneden.github.io/animate.css/', 'http://ianlunn.github.io/Hover/', 'http://www.joerezendes.com/projects/Woah.css/', '', // 'http://mojs.io/', 'http://airbnb.io/lottie/', 'https://greensock.com/', 'https://www.delac.io/wow/', 'http://animejs.com/', ]; $(document).ready(function() { $.scrollify({ section : ".section", easing: "easeOutExpo", scrollSpeed: 200, overflowScroll: false, before: function(x) { console.log(x); const $firstSection = $('.section').first(); const currentSection = $('.section').get(x); const $currentSection = $(currentSection); const iframeExists = $currentSection.children().children('iframe').length; if (iframeExists) $currentSection.children('.section-inner').children('iframe').attr('src', iframeSrcs[x]); $currentSection.addClass('empty') setTimeout(() => $currentSection.removeClass('empty')); } }); $('.btn-begin').click(function(e) { $(e.currentTarget).removeClass('infinite pulse').addClass('fadeOutDown'); setTimeout(function() { $('.title').removeClass('d-none'); }, 500) }) let venusKeyframeState = true; $('.img-venus.action').click(e => { if (venusKeyframeState) $('.img-venus-keyframes').fadeOut(1000); else $('.img-venus-keyframes').fadeIn(1000); venusKeyframeState = !venusKeyframeState; }); }); var lineDrawing = anime({ targets: '#Bottle path', strokeDashoffset: [anime.setDashoffset, 0], easing: 'linear', duration: 3000, delay: function(el, i) { return i * 250 }, direction: 'alternate', loop: true });
4b44d4148e9f3b01cff3b1ab88ec0fee66c4b2eb
[ "JavaScript" ]
1
JavaScript
livrush/animation
74d3b5cbdcaf9e32bf26523feac96366a5bd5a26
096007041998b92447f9e631178d25ae72d1762d
refs/heads/master
<file_sep>def roll_call_dwarves(dwarf_names) dwarf_names.each_with_index {|name, index| puts "#{index+1}. #{name}"} end def summon_captain_planet(planeteer_calls) planeteer_calls.map {|word| "#{word.capitalize}!"} end def long_planeteer_calls(words) words.any? {|word| word.size > 4} end def find_the_cheese(snacks) # the array below is here to help cheese_types = ["cheddar", "gouda", "camembert"] snack_index = snacks.index do |snack| cheese_types.any? do |cheese| cheese == snack end end if snack_index == nil return nil else return snacks[snack_index] end end
65cd0645ef264725184451a114df819cae70fa18
[ "Ruby" ]
1
Ruby
HopefulFire/ruby-enumerables-cartoon-collections-lab-online-web-prework
9843a36401ce4752a3ef4b827dc78967082bbf89
ba20729c3f4e6b00bbfa53a626764cef56014b99
refs/heads/master
<file_sep><?php /** * Created by PhpStorm. * User: oleg * Date: 05.12.17 * Time: 10:22 */ namespace App; class TaskController { } <file_sep><?php /** * Created by PhpStorm. * User: oleg * Date: 04.12.17 * Time: 6:06 */ /** * This class implement Singleton pattern. */ namespace Core; use Doctrine\ORM\EntityManager; use Doctrine\ORM\Tools\Setup; class DB { private static $me = null; private $entityManager = null; private function __construct() { include_once BASE_PATH . "config/db.php"; $config = Setup::createAnnotationMetadataConfiguration([BASE_PATH . 'app'], true); $this->entityManager = EntityManager::create($connectionConfig,$config); } public static function db(){ if (is_null(self::$me)){ self::$me = new self(); } return self::$me; } } <file_sep><?php /** * Created by PhpStorm. * User: oleg * Date: 03.12.17 * Time: 15:38 */ /** * This class implement Singleton pattern. */ namespace Core; use FastRoute\Dispatcher; use FastRoute\RouteCollector; use function FastRoute\simpleDispatcher; class Route { const ROUTE_CONFIG_PATH = BASE_PATH."config/routes.php"; private static $me = null; private $dispatcher = null; private function __construct() { } public static function route() { if (is_null(self::$me)) { self::$me = new self(); } return self::$me; } /** * Register routes from config. * * @return $this */ public function loadRoutes() { $this->dispatcher = simpleDispatcher( function (RouteCollector $routeCollector) { include_once self::ROUTE_CONFIG_PATH; } ); return $this; } /** * Search route from uri and method, and parse uri params. * * @param string $httpMethod * @param string $uri * * @return array * @throws \Exception */ public function findRoute(string $httpMethod, string $uri) { $uri = rawurldecode($uri); $info = $this->dispatcher->dispatch($httpMethod, $uri); switch ($info[0]) { case Dispatcher::NOT_FOUND: throw new \Exception('not found url', 404); case Dispatcher::METHOD_NOT_ALLOWED: throw new \Exception('this method not allowed', 405); case Dispatcher::FOUND: return [ 'controller' => $info[1], 'params' => $info[2], ]; } throw new \Exception("unexpected error in Core\\Route class"); } } <file_sep><?php /** * Created by PhpStorm. * User: oleg * Date: 03.12.17 * Time: 15:20 */ define("BASE_PATH", __DIR__."/../"); require_once BASE_PATH."vendor/autoload.php"; Core\App::app() ->run(); <file_sep><?php /** * Created by PhpStorm. * User: oleg * Date: 05.12.17 * Time: 10:40 */ namespace App; class User { } <file_sep><?php /** * Created by PhpStorm. * User: oleg * Date: 03.12.17 * Time: 17:51 */ namespace App; use Core\App; use Core\View; use Symfony\Component\HttpFoundation\Response; class DefaultController { /** * Controller for 404 http error. */ public function notFound() { View::view() ->render('404'); } /** * Controller for 500 http error. */ public function internalError() { View::view() ->render('500'); } /** * Controller for index page. * Now this controller redirect on "http(s)://host/task" page * but you can change this controller how you like for index page. */ public function index() { $host = App::app() ->getRequest() ->getSchemeAndHttpHost(); View::view() ->setHttpStatus(Response::HTTP_FOUND) ->getResponse()->headers->set("Location", $host.'/task/'); } } <file_sep><?php /** * Created by PhpStorm. * User: oleg * Date: 05.12.17 * Time: 2:17 */ namespace Core; class Model { } <file_sep><?php /** * Created by PhpStorm. * User: oleg * Date: 03.12.17 * Time: 17:04 */ /** * This class implement Singleton pattern. */ namespace Core; use Symfony\Component\HttpFoundation\Response; class View { const VIEWS_PATH = BASE_PATH."views/"; const HTML_TYPE = "text/html"; const JSON_TYPE = "application/json"; private static $me = null; private $response = null; private function __construct() { $this->response = new Response(); $request = App::app() ->getRequest(); $this->response->prepare($request); } public static function view() { if (is_null(self::$me)) { self::$me = new self(); } return self::$me; } /** * @param string $key * @param string $value * * @return $this */ public function setHeader(string $key, string $value) { $this->response->headers->set($key, $value); return $this; } /** * @param int $statusCode * * @return $this */ public function setHttpStatus(int $statusCode) { $this->response->setStatusCode($statusCode); return $this; } /** * Set content for response from view file or from array to json * * @param string $view * @param array $params * * @return $this * @throws \Exception */ public function render(string $view, array $params = []) { if ($view === 'json') { $this->response->headers->set('Content-Type', 'application/json'); $this->response->setContent(json_encode($params)); } elseif (file_exists($file_path = self::VIEWS_PATH.$view.".html")) { $data = file_get_contents($file_path); $this->response->setContent($data); } else { throw new \Exception("not isset view", 404); } return $this; } /** * @return null|\Symfony\Component\HttpFoundation\Response */ public function getResponse() { return $this->response; } } <file_sep><?php /** * Created by PhpStorm. * User: oleg * Date: 03.12.17 * Time: 15:35 */ /** * This class implement Singleton pattern. */ namespace Core; use Symfony\Component\HttpFoundation\Request; class App { private static $me = null; private $request = null; private $errCodes = [404]; private function __construct() { Route::route() ->loadRoutes(); $this->request = Request::createFromGlobals(); } public static function app() { if (is_null(self::$me)) { self::$me = new self(); } return self::$me; } public function run() { $db = DB::db(); try { $config = $this->getRoute(); $this->runRoute($config); } catch (\Exception $exception) { $this->errorRedirect($exception); } View::view() ->getResponse() ->send(); } /** * @return null|static */ public function getRequest() { return $this->request; } /** * @param \Exception $exception * * redirect user on page what isset info for error */ private function errorRedirect(\Exception $exception) { $host = $this->request->getSchemeAndHttpHost(); $code = $exception->getCode(); $code = $this->checkError($code); View::view() ->setHttpStatus($code) ->setHeader('Refresh', "0; url=".$host."/$code/"); } /** * this function check if register error code in app * * @param int $code * * @return int */ private function checkError(int $code) { if (in_array($code, $this->errCodes, true)) { return $code; } return 500; } /** * search route and params from uri * * @return array */ private function getRoute() { $method = $this->request->getRealMethod(); $uri = $this->request->getRequestUri(); $route = Route::route() ->findRoute($method, $uri); return $route; } /** * execute route controller with parameters * * @param $config */ private function runRoute($config) { $controller = "\\App\\".$config['controller']; $params = array_values($config['params']); call_user_func($controller, ...$params); } } <file_sep><?php /** * Created by PhpStorm. * User: oleg * Date: 03.12.17 * Time: 15:42 */ /** * For more information see https://github.com/nikic/FastRoute . */ $routeCollector->get("/", "DefaultController::index"); $routeCollector->get("/404/", "DefaultController::notFound"); $routeCollector->get("/500/", "DefaultController::internalError"); $routeCollector->get("/task/", "TaskController::show"); $routeCollector->post("/task/", "TaskController::create"); $routeCollector->put("/task/{id:[0-9]*}/", "TaskController::update"); $routeCollector->get("/task/{page:[0-9]*}/{count:[0-9]*}/{field}/{condition}/", "TaskController::list"); $routeCollector->post("/user/login/", "UserController::login"); $routeCollector->get("/user/logout/", "UserController::logout");
5a1c7a8bca85fc6be7a4599352db11be006cd440
[ "PHP" ]
10
PHP
zhyravskiyo/test3
f3414b932d6e7d47c545018fbf7edd9a5f5ab3bd
921c7bc2a50cbc1943e832e2572e54f5f97359d9
refs/heads/main
<file_sep>// # Math // **Perform Mathematical Tasks with JavaScript. Remember: you must use the `Math` functions and print all results to the console!** // ## 1. Minimum and maximum // ### a. Lowest Number console.log("the min:" + Math.min(-1, 4)); // Print out the lowest number between -1 and 4. // ### b. Highest Number console.log("the max:" + Math.max(-1, 4)); // Print out the highest number between -1 and 4. // ## 2. Rounding // ### a. Round up //Round up each of the following numbers to the nearest integer: 3321.32321, 326.76, 76788.7, -9.78, 43.342. console.log("Floor: " + Math.floor(3321.32321)); console.log("Floor: " + Math.floor(326.76)); console.log("Floor: " + Math.floor(76788.7)); console.log("Floor: " + Math.floor(-9.78,)); console.log("Floor: " + Math.floor(43.342)); // ### b. Round down //Round down each of the following numbers to the nearest integer: 3321.32321, 326.76, 76788.7, -9.78, 28.329. console.log("Ceil: " + Math.ceil(3321.32321)); console.log("Ceil: " + Math.ceil(326.76)); console.log("Ceil: " + Math.ceil(76788.7)); console.log("Ceil: " + Math.ceil(-9.78)); console.log("Ceil: " + Math.ceil(28.329)); // ## 3. Dice Roll! // Print a random integer between 1 and 6. console.log(Math.ceil(Math.random() * 6));
37ecb6724c4cd3db24dbf81fd113a98e15ff4f25
[ "JavaScript" ]
1
JavaScript
FbW-E01/pb-language-math-ronniejuan
0a863575ca738cb4ca1e855b7ab4f10c0bc70d01
d0256fb93083e153e4d5a0a274a437ca8ba966e0
refs/heads/master
<repo_name>AlAminKabbo/eA<file_sep>/App.js import * as React from 'react'; import {View, Text} from 'react-native'; import { NavigationContainer, DefaultTheme} from '@react-navigation/native'; import {createNativeStackNavigator} from '@react-navigation/native-stack'; import Home from './src/screens/home'; import Create from './src/screens/create'; import Update from './src/screens/update'; import Login from './src/screens/login'; import Signup from './src/screens/signup'; const Stack = createNativeStackNavigator(); const AppTheme = { ...DefaultTheme, colors: { ...DefaultTheme.colors, background: 'white', }, }; function App(){ const [user, setUser] = React.useState(true) return( <NavigationContainer theme={AppTheme}> <Stack.Navigator> { user ? ( <> <Stack.Screen name='Home' component={Home} options={{headerShown:false}}/> <Stack.Screen name='Create' component={Create} options={{headerShown:false}}/> <Stack.Screen name='Update' component={Update}/> </> ) : ( <> <Stack.Screen name='Login' component={Login} options={{headerShown:false}}/> <Stack.Screen name='Signup' component={Signup}/> </> ) } </Stack.Navigator> </NavigationContainer> ) } export default App;<file_sep>/src/screens/home.js import React from 'react' import { View, Text, StyleSheet, Image } from 'react-native' import Button from '../components/Button' export default function home({navigation}) { const navigateToCreate = () =>{ navigation.navigate('Create') } return ( <View> <Text style={styles.title}>My Employee</Text> <View style={{alignItems:'center', justifyContent:'center', marginTop: 200}}> <Image source={require('../../assets/emptyEmployee.png')} /> <Text style={{textAlign:'center', fontSize: 14, fontWeight:'bold'}}>Sorry you do not have employees</Text> <Button title="Add an employee" customStyles={styles.customStyles} onPress={navigateToCreate}/> </View> </View> ) } const styles = StyleSheet.create({ title:{ fontSize: 22, fontWeight: 'bold', color: '#000', margin: 20, }, customStyles:{ marginTop:25, alignSelf:'center' }, }) <file_sep>/src/components/Input.js import React from "react"; import { View, Text, TextInput, StyleSheet } from "react-native"; export default function Input({ placeholder, onChangeText, secureTextEntry, value, }) { return ( <View> <TextInput onChangeText={onChangeText} placeholder={placeholder} style={styles.Input} secureTextEntry={secureTextEntry} value={value} /> </View> ); } const styles = StyleSheet.create({ Input: { borderBottomWidth: 2, borderBottomColor: "#BBBBBB", padding: 10, margin: 20, }, });
3d131e4bdf9a10bf095af14043393c247cddf500
[ "JavaScript" ]
3
JavaScript
AlAminKabbo/eA
23de4d11d0d88c2e6f103fccccd24fa5ee0e8856
aaff93164acb8d86926a5ebecf7be3bbba4c8b50
refs/heads/master
<repo_name>SigitAri/parking_lot<file_sep>/src/com/test/parkinglot/core/ParkingIntruction.java package com.test.parkinglot.core; import com.test.parkinglot.model.Slot; /** * Created by Sigit on 20/05/2017. */ public class ParkingIntruction { Slot[] slots; public String Intruction(String intr){ String results = "Introduction not recognized"; String[] partsIntr = intr.split("\\s+"); if(partsIntr.length > 0) { switch (partsIntr[0]){ case "create_parking_lot" : return createParkingLot(partsIntr[1]); case "park" : return park(partsIntr[1], partsIntr[2]); case "leave" : return leave(partsIntr[1]); case "status" : return status(); case "registration_numbers_for_cars_with_colour" : return registrationByColour(partsIntr[1]); case "slot_numbers_for_cars_with_colour" : return slotByColour(partsIntr[1]); case "slot_number_for_registration_number" : return slotByRegistration(partsIntr[1]); default: return results; } } return results; } private String isCreateLot(){ if(slots == null){ return "please create a parking lot"; } return ""; } private String createParkingLot(String lotSize){ int size = Integer.parseInt(lotSize); slots = new Slot[size]; return "Created a parking lot with "+size+" slots"; } private String park(String registration, String colour){ if(!isCreateLot().equals("")){ return isCreateLot(); } Slot slot = new Slot(); slot.setRegistration(registration); slot.setColour(colour); for (int i = 0; i<slots.length; i++){ if (slots[i] == null) { slot.setId(i+1); slots[i] = slot; return "Allocated slot number : "+ (i+1); } } return "Sorry, parking lot is full"; } private String leave(String noSlaot){ if(!isCreateLot().equals("")){ return isCreateLot(); } int nomor = Integer.parseInt(noSlaot); if(nomor <= slots.length){ slots[nomor-1] = null; return "Slot number "+noSlaot+" is free"; } return "not found"; } private String status(){ if(!isCreateLot().equals("")){ return isCreateLot(); } String message = "Slot No. \t Registration No \t Colour\n"; for (Slot slot : slots){ if(slot != null) { message += slot.getId() + "\t" + slot.getRegistration() + "\t" + slot.getColour() + "\n"; } } return message; } private String registrationByColour(String colour){ if(!isCreateLot().equals("")){ return isCreateLot(); } String message = ""; for (int i=0; i<slots.length; i++){ if(slots[i] != null && slots[i].getColour().equals(colour)){ if(!message.equals("")){ message +=", "; } message += slots[i].getRegistration(); } } return message; } private String slotByColour(String colour){ if(!isCreateLot().equals("")){ return isCreateLot(); } String message = ""; for (int i=0; i<slots.length; i++){ if(slots[i] != null && slots[i].getColour().equals(colour)){ if(!message.equals("")){ message +=", "; } message += slots[i].getId(); } } return message; } private String slotByRegistration(String registration){ if(!isCreateLot().equals("")){ return isCreateLot(); } for(Slot slot : slots){ if( slot != null && slot.getRegistration().equals(registration)){ return String.valueOf(slot.getId()); } } return "Not found"; } } <file_sep>/src/com/test/parkinglot/model/Slot.java package com.test.parkinglot.model; /** * Created by Sigit on 20/05/2017. */ public class Slot { private int id; private String registration; private String colour; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getRegistration() { return registration; } public void setRegistration(String registration) { this.registration = registration; } public String getColour() { return colour; } public void setColour(String colour) { this.colour = colour; } }
c34249a46700e54ef7edf453f189df7385e75660
[ "Java" ]
2
Java
SigitAri/parking_lot
ed93ca0e62561e40f1ba59d62058248e108d7f27
a8380e153052474df20bdca541240b37a9a61c20
refs/heads/master
<repo_name>JakubDadela/Bmi-calc<file_sep>/main.js var plec=document.getElementById('plec'); var waga=document.getElementById('waga'); var wzrost=document.getElementById('wzrost'); var klikacz=document.getElementById('btn'); var text=document.querySelector('p'); function Oblicz(event){ event.preventDefault(); let wp=plec.value; let wh=waga.value; let hg=wzrost.value; let res=0; res=wh/(Math.pow(hg/100,2)); let bmi=res.toString(); let str=""; if(res<16) str='O nie twoje bmi wynosi: '+ bmi +'. Jesteś wygłodzony'; else if(res>16 && res<17) str='Bmi: ' + bmi + '. Jesteś wychudony!!'; else if(res>17 && res<18.5) str='Prawie dobrze bmi: '+bmi+ '. Delikatna niedowaga jedz więcej!'; else if(res>18 && res<24.9) str='Super bmi: ' + bmi +'.'; else if(res>25 && res<29.8) str='Kurde bmi: '+ bmi +'. Nadwaga jedz mniej!'; else if(res>29.8) str='Ojoj bmi: '+ bmi +'. Jesteś otyły!'; else str=""; text.innerText=str; } klikacz.addEventListener('click',Oblicz);
633c9bd82bfd2171038e7f7182e0accc38d5bcd4
[ "JavaScript" ]
1
JavaScript
JakubDadela/Bmi-calc
0d1c9a503c3c16ca273e489d3ac9e5bd82c32589
58c45c353156522ba160452ed5b52efa2519f34b
refs/heads/master
<file_sep>package com.easoncheng.appsample; /** * Author by 子勋 on 2016/9/13 00:59. * Function Describe */ public class GuideActivity extends BaseActivity { @Override public void initView() { } @Override public void initListener() { } @Override public void initData() { } }
4973da0f2d4a700cd36b699d4251bd77362ea3ca
[ "Java" ]
1
Java
loongche/CoreFrame
b68c8545e79e49566f07ef6fb07cc04fb5c1466f
c89ece6c7b337b97e08a35efe4b7a2f4f3e2630d
refs/heads/master
<file_sep>package nerdhub.cardinalenergy.impl; import nerdhub.cardinal.components.api.component.BlockComponentProvider; import nerdhub.cardinal.components.api.component.extension.CloneableComponent; import nerdhub.cardinalenergy.DefaultTypes; import nerdhub.cardinalenergy.api.IEnergyHandler; import nerdhub.cardinalenergy.api.IEnergyStorage; import nerdhub.cardinalenergy.impl.example.BlockEntityEnergyImpl; import net.minecraft.nbt.CompoundTag; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; /** * An implementation of {@link IEnergyStorage} * * An example implementation of this can be found at {@link BlockEntityEnergyImpl} */ public class EnergyStorage implements IEnergyStorage { private int capacity; private int energyStored; public EnergyStorage() { this(0, 0); } public EnergyStorage(int capacity) { this(capacity, 0); } public EnergyStorage(int capacity, int amount) { this.capacity = capacity; this.energyStored = amount; } @Override public int receiveEnergy(int amount) { int received = amount; if (received + energyStored > capacity) { received = amount - ((amount + energyStored) - capacity); } this.energyStored += received; return received; } @Override public int sendEnergy(World world, BlockPos pos, int amount) { if(amount <= energyStored) { if(isEnergyReceiver(world, pos)) { int amountReceived = getEnergyReceiver(world, pos).receiveEnergy(amount); this.extractEnergy(amountReceived); return amountReceived; } } return 0; } @Override public int extractEnergy(int amount) { int extracted = amount; if(extracted > energyStored) { extracted = energyStored; } this.energyStored -= extracted; return extracted; } @Override public int getEnergyStored() { return energyStored; } @Override public int getCapacity() { return this.capacity; } @Override public void setCapacity(int maxCapacity) { this.capacity = maxCapacity; } @Override public void setEnergyStored(int energy) { this.energyStored = energy; } @Override public boolean canReceive(int amount) { return energyStored + amount <= capacity; } @Override public boolean canExtract(int amount) { return amount <= energyStored; } @Override public CompoundTag toTag(CompoundTag nbt) { nbt.putInt("capacity", capacity); nbt.putInt("energyStored", energyStored); return nbt; } @Override public void fromTag(CompoundTag nbt) { capacity = nbt.getInt("capacity"); energyStored = nbt.getInt("energyStored"); } @Override public CloneableComponent newInstance() { return new EnergyStorage(capacity, energyStored); } public IEnergyStorage getEnergyReceiver(World world, BlockPos pos) { BlockComponentProvider componentProvider = (BlockComponentProvider) world.getBlockState(pos).getBlock(); if(world.getBlockEntity(pos) instanceof IEnergyHandler && componentProvider.hasComponent(world, pos, DefaultTypes.CARDINAL_ENERGY, null)) { IEnergyHandler energyHandler = (IEnergyHandler) world.getBlockEntity(pos); return energyHandler.canConnectEnergy(null, DefaultTypes.CARDINAL_ENERGY) ? componentProvider.getComponent(world, pos, DefaultTypes.CARDINAL_ENERGY, null) : null; } return null; } public boolean isEnergyReceiver(World world, BlockPos pos) { BlockComponentProvider componentProvider = (BlockComponentProvider) world.getBlockState(pos).getBlock(); if(world.getBlockEntity(pos) instanceof IEnergyHandler && componentProvider.hasComponent(world, pos, DefaultTypes.CARDINAL_ENERGY, null)) { return ((IEnergyHandler) world.getBlockEntity(pos)).isEnergyReceiver(null, DefaultTypes.CARDINAL_ENERGY); } return false; } }<file_sep># Cardinal Energy An Energy API for Fabric Cardinal Energy depends on `Cardinal Components API`, be sure to depend on it or jar-in-jar it ``` repositories { maven { name = "NerdHubMC" url = "https://maven.abusedmaster.xyz" } } dependencies { modCompile "com.github.NerdHubMC:Cardinal-Energy:${cardinal_version}" modCompile "com.github.NerdHubMC:Cardinal-Components-API:${cardinal_components}" include "com.github.NerdHubMC:Cardinal-Components-API:${cardinal_components}" } ```<file_sep>package nerdhub.cardinalenergy.api; import nerdhub.cardinal.components.api.component.Component; import net.minecraft.nbt.CompoundTag; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; /** * Implemented on an item energy handler object * * An example implementation can be found at {@link nerdhub.cardinalenergy.impl.ItemEnergyStorage} */ public interface IEnergyItemStorage extends IEnergyStorage { @Override boolean isComponentEqual(Component other); @Override default int sendEnergy(World world, BlockPos pos, int amount) { throw new IllegalStateException("Tried to access IEnergyStorage methods from an IEnergyItemStorage"); } } <file_sep>package nerdhub.cardinalenergy; import nerdhub.cardinal.components.api.ComponentRegistry; import nerdhub.cardinal.components.api.ComponentType; import nerdhub.cardinalenergy.api.IEnergyItemStorage; import nerdhub.cardinalenergy.api.IEnergyStorage; import net.minecraft.util.Identifier; /** * Default Cardinal Energy component type * Can be used or a custom Energy Component can be created using a new ComponentType */ public class DefaultTypes { public static final String MODID = "cardinalenergy"; /** * The default Cardinal Energy ComponentType * To create your own energy type simply create a new ComponentType of IEnergyHandler */ public static final ComponentType<IEnergyStorage> CARDINAL_ENERGY = ComponentRegistry.INSTANCE.registerIfAbsent(new Identifier(MODID, "cardinal_energy"), IEnergyStorage.class); /** * The default Cardinal Energy mana ComponentType, meant for entities */ public static final ComponentType<IEnergyItemStorage> MANA_COMPONENT = ComponentRegistry.INSTANCE.registerIfAbsent(new Identifier(MODID, "mana_type"), IEnergyItemStorage.class); } <file_sep>mc_version = 1.14.4 yarn_mappings = 1.14.4+build.5 loader_version = 0.4.8+build.159 fabric_version = 0.3.0+build.207 cardinal_components = 2.0.1-SNAPSHOT mod_version = 1.3.0<file_sep>package nerdhub.cardinalenergy.impl.example; import nerdhub.cardinal.components.api.event.ItemComponentCallback; import nerdhub.cardinalenergy.DefaultTypes; import nerdhub.cardinalenergy.api.IEnergyItemHandler; import nerdhub.cardinalenergy.api.IEnergyStorage; import nerdhub.cardinalenergy.impl.EnergyStorage; import nerdhub.cardinalenergy.impl.ItemEnergyStorage; import net.minecraft.entity.Entity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; import net.minecraft.util.TypedActionResult; import net.minecraft.world.World; /** * An example implementation of {@link ItemEnergyStorage}, {@link IEnergyItemHandler} and {@link ItemComponentCallback} */ public class ItemEnergyImpl extends Item implements IEnergyItemHandler { public ItemEnergyImpl(Settings settings) { super(settings); ItemComponentCallback.event(this).register((stack, components) -> components.put(DefaultTypes.CARDINAL_ENERGY, new EnergyStorage(1000))); } @Override public TypedActionResult<ItemStack> use(World world, PlayerEntity playerEntity, Hand hand) { //Example extracting energy when the item is used ItemStack stack = playerEntity.getMainHandStack(); IEnergyStorage storage = DefaultTypes.CARDINAL_ENERGY.get(stack); storage.extractEnergy(100); return new TypedActionResult(ActionResult.SUCCESS, playerEntity.getMainHandStack()); } @Override public void inventoryTick(ItemStack stack, World world, Entity entity, int int_1, boolean boolean_1) { //Example adding energy every tick IEnergyStorage storage = DefaultTypes.CARDINAL_ENERGY.get(stack); storage.receiveEnergy(1); } } <file_sep>package nerdhub.cardinalenergy.impl.example; import nerdhub.cardinalenergy.api.IEnergyHandler; import nerdhub.cardinalenergy.impl.EnergyStorage; import net.minecraft.block.entity.BlockEntity; import net.minecraft.block.entity.BlockEntityType; import net.minecraft.nbt.CompoundTag; /** * An example impl of {@link IEnergyHandler} */ public class BlockEntityEnergyImpl extends BlockEntity implements IEnergyHandler { /** * Create an EnergyStorage instance that stores 10,000 energy * BlockComponentProvider is implemented on the Block to reference this */ public EnergyStorage storage = new EnergyStorage(10000); public BlockEntityEnergyImpl(BlockEntityType<?> blockEntityType) { super(blockEntityType); } @Override public CompoundTag toTag(CompoundTag tag) { super.toTag(tag); //Write energy to nbt this.storage.toTag(tag); return tag; } @Override public void fromTag(CompoundTag tag) { super.fromTag(tag); //Read energy from nbt this.storage.fromTag(tag); } }
6ca2756cc53f051cf1c0fffb4c3561960bb0e118
[ "Markdown", "Java", "INI" ]
7
Java
NerdHubMC/Cardinal-Energy
1c68725756cc2ae0633ae7d757df4d7791d15355
016f4c4c1ed68a430a13c3d5a8c785b01f4bd343
refs/heads/master
<file_sep># Nichiyu Inventory Monitoring App ## Screenshots <a href="url"><img src="https://raw.githubusercontent.com/andreycruz16/Nichiyu-Inventory-App/master/screenshots/Screenshot_20170628_232641.png" align="left" height="640" width="360" ></a> <a href="url"><img src="https://raw.githubusercontent.com/andreycruz16/Nichiyu-Inventory-App/master/screenshots/Screenshot_20170628_232658.png" align="left" height="640" width="360" ></a> <a href="url"><img src="https://raw.githubusercontent.com/andreycruz16/Nichiyu-Inventory-App/master/screenshots/Screenshot_20170628_232711.png" align="left" height="640" width="360" ></a> <a href="url"><img src="https://raw.githubusercontent.com/andreycruz16/Nichiyu-Inventory-App/master/screenshots/Screenshot_20170628_232725.png" align="left" height="640" width="360" ></a> <file_sep>package com.markandreydelacruz.nichiyuinventory; import android.app.Activity; import android.app.ProgressDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.webkit.WebResourceError; import android.webkit.WebResourceRequest; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; public class BoxNumbers extends AppCompatActivity { AdView adView; AdRequest adRequest; private String urlString; private WebView webViewSisGrades; private ProgressDialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_boxnumbers); if(getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); } setTitle("Box Numbers"); urlString = getIntent().getExtras().getString("urlString"); // loadGrades(); //show ads adView = (AdView) findViewById(R.id.adView); adRequest = new AdRequest.Builder().build(); adView.loadAd(adRequest); } private void loadGrades() { dialog = new ProgressDialog(BoxNumbers.this); dialog.setMessage("Please wait..."); dialog.setIndeterminate(false); dialog.setCancelable(false); dialog.show(); webViewSisGrades = (WebView) findViewById(R.id.webViewSisGrades); webViewSisGrades.getSettings().setJavaScriptEnabled(true); // enable javascript webViewSisGrades.getSettings().setLoadWithOverviewMode(true); webViewSisGrades.getSettings().setUseWideViewPort(true); webViewSisGrades.getSettings().setBuiltInZoomControls(true); webViewSisGrades.getSettings().setDisplayZoomControls(false); final Activity activity = this; webViewSisGrades.setWebViewClient(new WebViewClient() { // public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { // Toast.makeText(activity, description, Toast.LENGTH_SHORT).show(); // } @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error){ Toast.makeText(getApplicationContext(), "Connection Failed. Try Again.", Toast.LENGTH_LONG).show(); } @Override public boolean shouldOverrideUrlLoading (WebView view, String url){ //True if the host application wants to leave the current WebView and handle the url itself, otherwise return false. if (dialog.isShowing()) { dialog.dismiss(); } Toast.makeText(getApplicationContext(), "Invalid Login Details. Try Again.", Toast.LENGTH_LONG).show(); finish(); return true; } @Override public void onPageFinished(WebView view, String url) { if (dialog.isShowing()) { dialog.dismiss(); } } }); webViewSisGrades .loadUrl(urlString); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_all_records, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_refresh) { // new LowStocks.BackgroundTaskLowStocks().execute(); loadGrades(); return true; } else if (id == android.R.id.home) { finish(); } return super.onOptionsItemSelected(item); } }
ef70b48c47aec798f139662fc7cec809d8c1de15
[ "Markdown", "Java" ]
2
Markdown
Monyancha/Nichiyu-Inventory-App
b62422225b3a6284e4798084760112766ad1be71
a46e16bfebca6acd9028d295319470d4eaece579
refs/heads/master
<repo_name>TechsCode/AirhockeyV2<file_sep>/src/main/java/me/TechsCode/Airhockey/SerialCommunication.java package me.TechsCode.Airhockey; import arduino.Arduino; import arduino.PortDropdownMenu; import gnu.io.CommPortIdentifier; import jssc.*; import java.util.Enumeration; public abstract class SerialCommunication implements SerialPortEventListener { private StringBuilder inputBuffer; private SerialPort serialPort; public SerialCommunication() { inputBuffer = null; for(String port : SerialPortList.getPortNames()){ System.out.println("- "+port); } serialPort = new SerialPort("/dev/cu.wchusbserial14130"); try { serialPort.openPort(); serialPort.setParams(115200, 8, 1, 0, true, true); serialPort.addEventListener(this); } catch (SerialPortException e) { e.printStackTrace(); } try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } public void close(){ try { serialPort.closePort(); } catch (SerialPortException e) { e.printStackTrace(); } } @Override public void serialEvent(SerialPortEvent evt) { if (this.inputBuffer == null) { this.inputBuffer = new StringBuilder(); } try { final byte[] buf = this.serialPort.readBytes(); if (buf != null && buf.length > 0) { final String s = new String(buf, 0, buf.length); this.inputBuffer.append(s); onReceive(inputBuffer.toString()); } } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } public abstract void onReceive(String line); public void send(String line){ try { serialPort.writeString(line+"\n"); } catch (SerialPortException e) { e.printStackTrace(); } } } <file_sep>/src/main/java/me/TechsCode/Airhockey/ImageProducer.java package me.TechsCode.Airhockey; public interface ImageProducer { public void registerListener(CameraListener listener); } <file_sep>/src/main/java/me/TechsCode/Airhockey/FPSCounter.java package me.TechsCode.Airhockey; public class FPSCounter { private int fps = 0; private long lastSecond = 0; private int frames = 0; public void count(){ long current = System.currentTimeMillis(); if(lastSecond == 0 || current-lastSecond > 1000){ lastSecond = current; fps = frames; frames = 0; } frames++; } public int getCurrentFPS(){ return fps; } } <file_sep>/src/main/java/me/TechsCode/Airhockey/Airhockey.java package me.TechsCode.Airhockey; // Datenschutz import org.bytedeco.javacv.CanvasFrame; import org.bytedeco.javacv.Frame; import java.util.ArrayList; import java.util.List; import static org.bytedeco.javacpp.opencv_core.*; public class Airhockey { static final int width = 640; static final int height = 480; static final int fps = 60; static final int cameraNum = 1; static GameArea gameArea = new GameArea(new CvPoint(15, 58), new CvPoint(615, 422)); private GameThread gameThread; public static void main(String[] args){ boolean debug = false; ImageProducer camera = !debug ? new Camera(width, height, fps, cameraNum) : new FakeCamera(width, height, fps, cameraNum); VisionSettingsPanel visionSettingsPanel = new VisionSettingsPanel(){ public void onContinue(ColorRange visionSettings) { new Airhockey(camera, visionSettings); } }; camera.registerListener(visionSettingsPanel); } public Airhockey(ImageProducer camera, final ColorRange colorRange) { TrackStream trackStream = new TrackStream(colorRange, camera); MovementManager movementManager = new MovementManager(); TraceManager traceManager = new TraceManager(trackStream, gameArea); gameThread = new GameThread(movementManager, traceManager); new DebugScreen(trackStream, traceManager, gameThread); } } <file_sep>/src/main/java/me/TechsCode/Airhockey/TrackListener.java package me.TechsCode.Airhockey; import org.bytedeco.javacpp.opencv_core; public interface TrackListener { public void onTrack(opencv_core.IplImage image, opencv_core.CvPoint puck); } <file_sep>/src/main/java/me/TechsCode/Airhockey/VisionUtil.java package me.TechsCode.Airhockey; import org.bytedeco.javacpp.opencv_core; import org.bytedeco.javacpp.opencv_imgproc; import static org.bytedeco.javacpp.opencv_core.cvCreateImage; import static org.bytedeco.javacpp.opencv_core.cvGetSize; import static org.bytedeco.javacpp.opencv_core.cvInRangeS; import static org.bytedeco.javacpp.opencv_imgproc.*; import static org.opencv.imgproc.Imgproc.CV_MEDIAN; public class VisionUtil { public static opencv_core.IplImage getThresholdImage(opencv_core.IplImage orgImg, ColorRange visionSettings, boolean smooth) { opencv_core.IplImage imgThreshold = cvCreateImage(cvGetSize(orgImg), 8, 1); cvInRangeS(orgImg, visionSettings.getMin(), visionSettings.getMax(), imgThreshold); if(smooth) cvSmooth(imgThreshold, imgThreshold, CV_MEDIAN, 15,0,0,0); return imgThreshold; } public static opencv_core.CvPoint calculateCenter(opencv_core.IplImage thresholdImage){ opencv_imgproc.CvMoments moments = new opencv_imgproc.CvMoments(); cvMoments(thresholdImage, moments, 1); double mom10 = cvGetSpatialMoment(moments, 1, 0); double mom01 = cvGetSpatialMoment(moments, 0, 1); double area = cvGetCentralMoment(moments, 0, 0); double posX = (mom10 / area); double posY = (mom01 / area); return new opencv_core.CvPoint((int) posX, (int) posY); } } <file_sep>/src/main/java/me/TechsCode/Airhockey/PuckTrace.java package me.TechsCode.Airhockey; import org.bytedeco.javacpp.opencv_core; public class PuckTrace { private opencv_core.CvPoint first, second; private double m; private double yMin, yMax, xMin, xMax; public PuckTrace(opencv_core.CvPoint first, opencv_core.CvPoint second, double m, double yMin, double yMax, double xMin, double xMax) { this.first = first; this.second = second; this.m = m; this.yMin = yMin; this.yMax = yMax; this.xMin = xMin; this.xMax = xMax; } public opencv_core.CvPoint next(){ double p1X = first.x(); double p1Y = first.y(); double p2X = second.x(); double p2Y = second.y(); double n = p1Y - m * p1X; double x1 = (-n/m); double x2 = (yMax - n) / m; double y1 = n; double y2 = m * xMax + n; double x = 0; double y = 0; if(isValidX(x1) || isValidX(x2)){ boolean direction = p1Y < p2Y; x = direction ? x2 : x1; y = direction ? yMax : yMin; } if(isValidY(y1) || isValidY(y2)){ boolean direction = p1X < p2X; x = direction ? xMax : xMin; y = direction ? y2 : y1; } if(x == 0 && y == 0){ //System.out.println(""); //System.out.println("x "+xMin+"-"+xMax+" y "+yMin+"-"+yMax); //System.out.println("RIP: x"+x1+" x"+x2+" y"+y1+" y"+y2); } opencv_core.CvPoint nextPoint = new opencv_core.CvPoint((int) x,(int) y); this.m = -m; this.second = first; this.first = nextPoint; return nextPoint; } /* public boolean isValidY(double y){ return y >= 0 && y <= Airhockey.height; } public boolean isValidX(double x){ return x >= 0 && x <= Airhockey.width; }*/ public boolean isValidY(double y){ return y <= yMax+58 && y >= yMin+58; } public boolean isValidX(double x){ return x <= xMax+15 && x >= xMin+15; } public PuckTrace clone(){ return new PuckTrace(new opencv_core.CvPoint(first.x(), first.y()), new opencv_core.CvPoint(second.x(), second.y()), m, yMin, yMax, xMin, xMax); } } <file_sep>/src/main/java/me/TechsCode/Airhockey/SettingsFile.java package me.TechsCode.Airhockey; import org.apache.commons.io.FileUtils; import org.bytedeco.javacpp.opencv_core; import java.io.File; import java.io.IOException; import java.util.Arrays; public class SettingsFile { public static void save(ColorRange colorRange){ try { File file = new File("Settings.dat"); file.createNewFile(); opencv_core.CvScalar min = colorRange.getMin(); opencv_core.CvScalar max = colorRange.getMax(); FileUtils.writeStringToFile(file, min.val(0)+" "+min.val(1)+" "+min.val(2)+" "+max.val(0)+" "+max.val(1)+" "+max.val(2)); } catch (IOException e) { e.printStackTrace(); } } public static ColorRange retrieve(){ try { File file = new File("Settings.dat"); String[] data = FileUtils.readLines(file).get(0).split(" "); Double[] values = Arrays.stream(data).map(s -> Double.valueOf(s)).toArray(Double[]::new); opencv_core.CvScalar min = new opencv_core.CvScalar(values[0], values[1], values[2], 0); opencv_core.CvScalar max = new opencv_core.CvScalar(values[3], values[4], values[5], 0); return new ColorRange(min, max); } catch (Exception e) { e.printStackTrace(); return new ColorRange(new opencv_core.CvScalar(85, 85, 85, 0), new opencv_core.CvScalar(170, 170, 170, 0)); } } }
eb4bb152a99e3985e041301f819b657655ae5b71
[ "Java" ]
8
Java
TechsCode/AirhockeyV2
5094e7fb7373f2b3f8b9b021b3a0171bf3d0d6a7
08344150d24f45ea98e9b5e5b69c12affe7c0a4c
refs/heads/master
<file_sep>package net.pl3x.emeralds.item.tool; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.ItemPickaxe; import net.pl3x.emeralds.item.ModItems; import net.pl3x.emeralds.material.EmeraldMaterial; public class EmeraldPickaxe extends ItemPickaxe { public static final String name = "emerald_pickaxe"; public EmeraldPickaxe() { super(EmeraldMaterial.TOOL); setRegistryName(name); setUnlocalizedName(name); setCreativeTab(CreativeTabs.TOOLS); ModItems.__ITEMS__.add(this); } } <file_sep>package net.pl3x.emeralds.item; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.inventory.EntityEquipmentSlot; import net.pl3x.emeralds.material.EmeraldMaterial; public class EmeraldArmor extends net.minecraft.item.ItemArmor { public EmeraldArmor(EntityEquipmentSlot slot, String name) { super(EmeraldMaterial.ARMOR, 0, slot); setRegistryName(name); setUnlocalizedName(name); setCreativeTab(CreativeTabs.COMBAT); ModItems.__ITEMS__.add(this); } } <file_sep>package net.pl3x.emeralds.item; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.Item; import net.minecraftforge.registries.IForgeRegistry; import net.pl3x.emeralds.Emeralds; import net.pl3x.emeralds.item.tool.EmeraldAxe; import net.pl3x.emeralds.item.tool.EmeraldHoe; import net.pl3x.emeralds.item.tool.EmeraldPickaxe; import net.pl3x.emeralds.item.tool.EmeraldSpade; import net.pl3x.emeralds.item.tool.EmeraldSword; import java.util.HashSet; import java.util.Set; public class ModItems { public static final Set<Item> __ITEMS__ = new HashSet<>(); public static final EmeraldAxe EMERALD_AXE = new EmeraldAxe(); public static final EmeraldHoe EMERALD_HOE = new EmeraldHoe(); public static final EmeraldPickaxe EMERALD_PICKAXE = new EmeraldPickaxe(); public static final EmeraldSpade EMERALD_SHOVEL = new EmeraldSpade(); public static final EmeraldSword EMERALD_SWORD = new EmeraldSword(); public static final EmeraldArmor EMERALD_BOOTS = new EmeraldArmor(EntityEquipmentSlot.FEET, "emerald_boots"); public static final EmeraldArmor EMERALD_CHESTPLATE = new EmeraldArmor(EntityEquipmentSlot.CHEST, "emerald_chestplate"); public static final EmeraldArmor EMERALD_HELMET = new EmeraldArmor(EntityEquipmentSlot.HEAD, "emerald_helmet"); public static final EmeraldArmor EMERALD_LEGGINGS = new EmeraldArmor(EntityEquipmentSlot.LEGS, "emerald_leggings"); public static void register(IForgeRegistry<Item> registry) { __ITEMS__.forEach(registry::register); } public static void registerModels() { __ITEMS__.forEach(item -> Emeralds.proxy.registerItemRenderer(item, 0, item.getUnlocalizedName().substring(5))); } } <file_sep>package net.pl3x.emeralds.item.tool; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.ItemSword; import net.pl3x.emeralds.item.ModItems; import net.pl3x.emeralds.material.EmeraldMaterial; public class EmeraldSword extends ItemSword { public static final String name = "emerald_sword"; public EmeraldSword() { super(EmeraldMaterial.TOOL); setRegistryName(name); setUnlocalizedName(name); setCreativeTab(CreativeTabs.COMBAT); ModItems.__ITEMS__.add(this); } } <file_sep>package net.pl3x.emeralds.proxy; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.item.Item; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.pl3x.emeralds.Emeralds; @SideOnly(Side.CLIENT) public class ClientProxy extends ServerProxy { @Override public void preInit(FMLPreInitializationEvent event) { super.preInit(event); } @Override public void registerItemRenderer(Item item, int meta, String id) { ModelLoader.setCustomModelResourceLocation(item, meta, new ModelResourceLocation(Emeralds.modId + ":" + id, "inventory")); } } <file_sep>package net.pl3x.emeralds.proxy; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.living.LivingHurtEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.pl3x.emeralds.item.EmeraldArmor; public class ServerProxy { public void preInit(FMLPreInitializationEvent event) { MinecraftForge.EVENT_BUS.register(this); } public void registerItemRenderer(Item item, int meta, String id) { } @SubscribeEvent public void on(LivingHurtEvent event) { float reduction = event.getAmount() / 16 * 1.5F; for (ItemStack armor : event.getEntity().getArmorInventoryList()) { if (armor.getItem() instanceof EmeraldArmor) { event.setAmount(event.getAmount() - reduction); } } } } <file_sep>package net.pl3x.emeralds.item.tool; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.ItemSpade; import net.pl3x.emeralds.item.ModItems; import net.pl3x.emeralds.material.EmeraldMaterial; public class EmeraldSpade extends ItemSpade { public static final String name = "emerald_shovel"; public EmeraldSpade() { super(EmeraldMaterial.TOOL); setRegistryName(name); setUnlocalizedName(name); setCreativeTab(CreativeTabs.TOOLS); ModItems.__ITEMS__.add(this); } }
f703a100c31eb18834b29ba0a8e0dd10c7b4d4b4
[ "Java" ]
7
Java
BillyGalbreath/Emeralds
437012fa3c054c1b8e1684a15f1f92676e73c576
5c38b35473110a895ccecdae3666c77663b43a08
refs/heads/master
<file_sep>import { Component, OnInit, ViewEncapsulation } from '@angular/core'; import { WeatherService } from './../weather.service'; @Component({ selector: 'app-chicago', templateUrl: './chicago.component.html', styleUrls: ['./chicago.component.css'], encapsulation: ViewEncapsulation.None }) export class ChicagoComponent implements OnInit { humidity; avgtemp; hightemp; lowtemp; status; constructor(private _weatherService: WeatherService) { this._weatherService.retrieveForecast("Chicago, IL", (forecast)=>{ this.humidity=forecast.main.humidity; this.avgtemp=Math.round((forecast.main.temp-273.15)*9/5+32); this.hightemp=Math.round((forecast.main.temp_max-273.15)*9/5+32); this.lowtemp=Math.round((forecast.main.temp_min-273.15)*9/5+32); this.status=forecast.weather; }) } ngOnInit() { } } <file_sep>import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; @Injectable() export class WeatherService { apikey="GETYOUROWN"; constructor(private _http: Http) { } retrieveForecast(location, callback){ this._http.get(`http://api.openweathermap.org/data/2.5/weather?q=${location}&APPID=${this.apikey}`).subscribe( (response)=>{ callback(response.json()); }, (error)=>{ callback(null); } ) } }
ac2f8fadbfdf47acbbd9cbf78b8819d4905a60b2
[ "TypeScript" ]
2
TypeScript
ctdoan33/dojoWeatherForecastAngular
e350bb9f3e277a390ee0051a463f60ac1f505b96
d56252643af0204acc55b50b694786ffbd1c3dd2
refs/heads/master
<repo_name>GreenSMod/FitFoster<file_sep>/app/src/main/java/com/greensmod/FitFoster/ProfileFragment.java package com.greensmod.FitFoster; import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.google.android.gms.auth.api.signin.GoogleSignIn; import com.google.android.gms.auth.api.signin.GoogleSignInClient; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.fitness.Fitness; public class ProfileFragment extends Fragment { public void signOut() { GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestProfile() .build(); GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(getActivity(), gso); Fitness.getConfigClient(getActivity(), GoogleSignIn.getLastSignedInAccount(getActivity())).disableFit(); mGoogleSignInClient.signOut(); Intent intent = new Intent(getActivity(), GoogleAuth.class); startActivity(intent); getActivity().finish(); } @SuppressLint("SetTextI18n") @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_profile, container, false); // Button clear_database_button = view.findViewById(R.id.clear_database_button); // clear_database_button.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // AchievementsRoomDatabase dbAchievements = App.getInstance().getDatabaseAchievements(); // AchievementsDao achievementsDao = dbAchievements.achievementsDao(); // achievementsDao.deleteAll(); // // DaysRoomDatabase dbDays = App.getInstance().getDatabaseDays(); // DaysDao daysDao = dbDays.daysDao(); // daysDao.deleteAll(); // // PetInfoRoomDatabase dbPetInfo = App.getInstance().getDatabasePetInfo(); // PetInfoDao petInfoDao = dbPetInfo.petInfoDao(); // petInfoDao.deleteAll(); // // StatisticsRoomDatabase dbStatistics = App.getInstance().getDatabaseStatistics(); // StatisticsDao statisticsDao = dbStatistics.statisticsDao(); // statisticsDao.deleteAll(); // // WardrobeRoomDatabase dbWardrobe = App.getInstance().getDatabaseWardrobe(); // WardrobeDao wardrobeDao = dbWardrobe.wardrobeDao(); // wardrobeDao.deleteAll(); // // WeeklyMissionsRoomDatabase dbWeeklyMissions = App.getInstance().getDatabaseWeeklyMissions(); // WeeklyMissionsDao weeklyMissionsDao = dbWeeklyMissions.weeklyMissionsDao(); // weeklyMissionsDao.deleteAll(); // } // }); Button updateButton = view.findViewById(R.id.sign_out_button); updateButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { signOut(); } }); return view; } } <file_sep>/app/src/main/java/com/greensmod/FitFoster/PetInfoRoomDatabase.java package com.greensmod.FitFoster; import androidx.room.Database; import androidx.room.RoomDatabase; @Database(entities = {PetInfo.class}, version = 2, exportSchema = false) public abstract class PetInfoRoomDatabase extends RoomDatabase { public abstract PetInfoDao petInfoDao(); }<file_sep>/app/src/main/java/com/greensmod/FitFoster/AchievementsRoomDatabase.java package com.greensmod.FitFoster; import androidx.room.Database; import androidx.room.RoomDatabase; @Database(entities = {Achievements.class}, version = 2, exportSchema = false) public abstract class AchievementsRoomDatabase extends RoomDatabase { public abstract AchievementsDao achievementsDao(); }<file_sep>/app/src/main/java/com/greensmod/FitFoster/GoogleAuth.java package com.greensmod.FitFoster; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import android.Manifest; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.view.View; import com.google.android.gms.auth.api.signin.GoogleSignIn; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.common.SignInButton; import com.google.android.gms.fitness.FitnessOptions; import com.google.android.gms.fitness.data.DataType; import java.util.LinkedList; public class GoogleAuth extends AppCompatActivity { private static final int REQUEST_OAUTH_REQUEST_CODE = 0x1001; private static final String[] REQUIRED_PERMISSIONS = new String[]{Manifest.permission.ACTIVITY_RECOGNITION, Manifest.permission.ACCESS_FINE_LOCATION}; public void goToMain() { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); } public void doSignIn() { FitnessOptions fitnessOptions = FitnessOptions.builder() .addDataType(DataType.TYPE_STEP_COUNT_CUMULATIVE) .addDataType(DataType.TYPE_STEP_COUNT_DELTA) .addDataType(DataType.TYPE_CALORIES_EXPENDED) .addDataType(DataType.TYPE_DISTANCE_DELTA) .addDataType(DataType.TYPE_MOVE_MINUTES) .build(); GoogleSignIn.requestPermissions( this, REQUEST_OAUTH_REQUEST_CODE, GoogleSignIn.getLastSignedInAccount(this), fitnessOptions); GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestProfile() .requestEmail() .requestId() .build(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.googleauth); SignInButton signInButton = findViewById(R.id.sign_in_button); signInButton.setSize(SignInButton.SIZE_WIDE); signInButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { doSignIn(); } }); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { signInButton.setEnabled(false); LinkedList<String> missingPermissions = new LinkedList<>(); for (String p : REQUIRED_PERMISSIONS) { if (checkSelfPermission(p) != PackageManager.PERMISSION_GRANTED) { missingPermissions.add(p); } } if (!missingPermissions.isEmpty()) { String[] mpArray = new String[missingPermissions.size()]; missingPermissions.toArray(mpArray); ActivityCompat.requestPermissions(this, mpArray, 1); } else { signInButton.setEnabled(true); } } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case 1: if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { SignInButton signInButton = findViewById(R.id.sign_in_button); signInButton.setEnabled(true); } else { Intent intent = new Intent(this, SplashScreen.class); startActivity(intent); finish(); } return; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { if (requestCode == REQUEST_OAUTH_REQUEST_CODE) { goToMain(); } } } }<file_sep>/app/src/main/java/com/greensmod/FitFoster/SubFragmentPet.java package com.greensmod.FitFoster; import android.annotation.SuppressLint; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; public class SubFragmentPet extends Fragment { FragmentManager myFragmentManager; public void toNextSubFragment() { FragmentTransaction fragmentTransaction = myFragmentManager .beginTransaction(); fragmentTransaction.replace(R.id.fragment_container, new SubFragmentWardrobe()); fragmentTransaction.commit(); } @SuppressLint("SetTextI18n") @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.subfragment_pet, container, false); TextView steps_points_amount = view.findViewById(R.id.steps_points_amount); TextView events_points_amount = view.findViewById(R.id.events_points_amount); PetInfoRoomDatabase dbPetInfo = App.getInstance().getDatabasePetInfo(); PetInfoDao petInfoDao = dbPetInfo.petInfoDao(); PetInfo pet_info_db = petInfoDao.getById(1); steps_points_amount.setText(pet_info_db.steps_points + ""); events_points_amount.setText(pet_info_db.events_points + ""); WardrobeRoomDatabase dbWardrobe = App.getInstance().getDatabaseWardrobe(); WardrobeDao wardrobeDao = dbWardrobe.wardrobeDao(); ImageView texture_image = view.findViewById(R.id.texture_image); ImageView body_image = view.findViewById(R.id.body_image); if (pet_info_db.texture_id != 0) { texture_image.setImageResource(wardrobeDao.getById(pet_info_db.texture_id).resource_id); } if (pet_info_db.body_id != 0) { body_image.setImageResource(wardrobeDao.getById(pet_info_db.body_id).resource_id); } myFragmentManager = getFragmentManager(); Button nextSubFragment = view.findViewById(R.id.button_next_subfragment); nextSubFragment.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { toNextSubFragment(); } }); return view; } } <file_sep>/app/src/main/java/com/greensmod/FitFoster/Achievements.java package com.greensmod.FitFoster; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.Index; import androidx.room.PrimaryKey; @Entity(tableName = "achievements_table", indices = {@Index(value = "label", unique = true)}) public class Achievements { @PrimaryKey(autoGenerate = true) public long id; public String label; public String name; public String description; // 0 - not completed, 1 - completed, -1 - unavailable to complete @ColumnInfo(defaultValue = "0") public int completed_type_id; // 1 - 1 action to complete, 2 - fill the progress to complete, -1 - unavailable to complete public int type_id; }<file_sep>/app/src/main/java/com/greensmod/FitFoster/WardrobeRoomDatabase.java package com.greensmod.FitFoster; import androidx.room.Database; import androidx.room.RoomDatabase; @Database(entities = {Wardrobe.class}, version = 2, exportSchema = false) public abstract class WardrobeRoomDatabase extends RoomDatabase { public abstract WardrobeDao wardrobeDao(); }<file_sep>/app/src/main/java/com/greensmod/FitFoster/StatisticsRoomDatabase.java package com.greensmod.FitFoster; import androidx.room.Database; import androidx.room.RoomDatabase; @Database(entities = {Statistics.class}, version = 2, exportSchema = false) public abstract class StatisticsRoomDatabase extends RoomDatabase { public abstract StatisticsDao statisticsDao(); }
6adb2334856731175d407b6da93ecf42ac6c01fc
[ "Java" ]
8
Java
GreenSMod/FitFoster
3ce72cf49234e32c188d47d7af429eedc87abefc
8ecaec9337e3dbfcb1f7f45522c74d558d0f4da6
refs/heads/main
<repo_name>singhbalr/moodleABKDSubmition<file_sep>/message/viewCourse.php <?php require_once(__DIR__ . '/../../config.php'); global $DB; $PAGE->set_url(new moodle_url('/local/message/viewCourse.php')); $PAGE->set_context(\context_system::instance()); $PAGE->set_title('View Course'); echo $OUTPUT->header(); // $courses = $DB->get_records('course'); $array = enrol_get_all_users_courses($_GET["userId"]); // var_dump($castArray); $context = (object)[ "courses" => array_values($array), "viewUrl" => new moodle_url('/local/message/viewCourse.php'), ]; echo $OUTPUT->render_from_template('local_message/viewCourse',$context); echo $OUTPUT->footer(); // $templatecontext = (object)[ // 'messages' => array_values($messages), // 'editurl' => new moodle_url('/local/message/edit.php'), // ];<file_sep>/message/version.php <?php defined('MOODLE_INTERNAL') || die(); $plugin->component = 'local_message'; $plugin->version = 2020071900; $plugin->requires = 2016052300; // Moodle version<file_sep>/message/index.php <?php require_once(__DIR__ . '/../../config.php'); global $DB; $PAGE->set_url(new moodle_url('/local/message/index.php')); $PAGE->set_context(\context_system::instance()); $PAGE->set_title('Manage messages'); echo $OUTPUT->header(); $student = $DB->get_records('user'); $context = (object)[ "student" => array_values($student), "viewUrl" => new moodle_url('/local/message/viewCourse.php'), ]; echo $OUTPUT->render_from_template('local_message/index',$context); echo $OUTPUT->footer(); // $templatecontext = (object)[ // 'messages' => array_values($messages), // 'editurl' => new moodle_url('/local/message/edit.php'), // ];<file_sep>/message/scripts/scripts.js $('document').ready(function(){ console.log("Hello World"); $('.list-item-subject').each(function(i, obj) { if($(this).find(".visible-item").text() == 1){ $(this).find(".visible-item").text("complete") }else{ $(this).find(".visible-item").text("not complete") } var dateString = moment.unix($(this).find(".time-item").text()).format("MM/DD/YYYY"); $(this).find(".time-item").text(dateString); }); });<file_sep>/message/lib.php <?php function local_message_extend_settings_navigation(settings_navigation $settingsnav, context $context){ global $CFG, $PAGE; $settingnode = $settingsnav->find('root', navigation_node::TYPE_SITE_ADMIN); if( $settingnode ) { $setMotdMenuLbl = get_string('reports', 'local_message'); $setMotdUrl = new moodle_url('/local/message/index.php'); $setMotdnode = navigation_node::create( $setMotdMenuLbl, $setMotdUrl, navigation_node::NODETYPE_LEAF); $settingnode->add_node($setMotdnode); } }
663203cc748bf2e66672a2856a5f19a5cd35325e
[ "JavaScript", "PHP" ]
5
PHP
singhbalr/moodleABKDSubmition
5241c71075ab9e6045aee68ebc8a6a7e28fa8bea
0660a586b6cc8da747b5f6794c6609396c3d6252
refs/heads/main
<file_sep># 🍎 vimlife_with_hammerspoon 🔨🥄 Config file and modules in this repository help to apply the key map anywhere in Typora and others. Enjoy your vimlife with Hammerspoon! 설정파일 구현과정은 [블로그](https://humblego.tistory.com/11)에서 확인하실 수 있습니다. # 🍎 Feature 1. **Add English conversion to Esc key.** - When you put 'esc' key, input source will be chagned to English if current input source is not English. - It will be helpful when usinge vim with non-English input source. 2. **'vim_keymap mode' for text editor like typora, tistory..etc.** - In fact, it's just a simulation of acting like a vim keymap in a text editor like typora. - You can turn on and off 'vim_keymap mode'. **Default shorcut is {"cmd' + "shift"} + "space".** You can customize it with `~/.hammerspoon/init.lua`. - Marked by a menu icon, it is easy to see if the function is turned on. #### List of keys supported | From | To | | --------- | ------------------------------ | | h | left | | j | down | | k | up | | l | right | | x | forward Delete (not cut) | | w | next word | | b | prev word | | i | insert mode | | a | append | | o | open below | | p | paste after | | u | undo | | shift + d | delete cursor to eol (not cut) | | shift + a | append at eol | | shift + o | open above | | y + y | copy one line | | d + d | delete one line (not cut) | | d + w | delete next word (not cut) | | d + b | delete prev word (not cut) | # 🍎 Install If you are a skillful Hammerspoon user, just copy and paste the init.lua and modules. If you are new to Hammerspoon, follow the process below. ## 1️⃣ Install hammerspoon first. #### Case 1) With homebrew cask ``` brew install --cask hammerspoon ``` #### Case 2) With zip link 1. Download Hammerspoon-x.x.xx.zip from this [link](https://github.com/Hammerspoon/hammerspoon/releases/tag/0.9.82) 2. Unzip downloaded file and move 'hammerspoon' file to `Applications` directory (한국어로 응용 프로그램 폴더) ## 2️⃣ Clone this repository && Execute init.sh ``` git clone https://github.com/humblEgo/vimlife_with_hammerspoon.git && cd vimlife_with_hammerspoon && ./init.sh ``` ## 3️⃣ Execute Hammerspoon Maybe you can find 'Hammerspoon' icon in launchpad. Click it. Or just use Spotlight/Alfred. In my case, execute hammerspoon with 'spotlight'. ![image](https://user-images.githubusercontent.com/54612343/103273247-2ff66900-4a02-11eb-8448-1fd6a4e97468.png) # 🍎 Contributor I'd appreciate it if you could tell me about the modifications. Also, if you want to add a vim keymap, please feel free to send me PR or issue! :) <file_sep>local obj = {} local mod = { empty = {}, shift = {"shift"}, alt = {"alt"}, cmd = {"cmd"}, ctrl = {"ctrl"}, cmd_and_shift = {"cmd", "shift"}, } local inputEnglish = "com.apple.keylayout.ABC" local esc_bind function obj:change_input_source_if_ko() local inputSource = hs.keycodes.currentSourceID() if not (inputSource == inputEnglish) then hs.eventtap.keyStroke(mod.empty, 'right') hs.keycodes.currentSourceID(inputEnglish) end esc_bind:disable() hs.eventtap.keyStroke(mod.empty, 'escape') esc_bind:enable() end function obj:bind_change_input_source_with(modifier, key) print(modifier) print(key) esc_bind = hs.hotkey.new(modifier, key, obj.change_input_source_if_ko) esc_bind:enable() end return obj<file_sep> -- init.lua from vimlife_with_hammerspoon require('./modules/change_input_source_if_ko'):bind_change_input_source_with({}, "escape") -- You can turn on/off 'vim_mode' by shortcuts. -- Default shortcuts are {"cmd, shift"}, "space". -- You can customize modifier and key. -- If you want to use {"cmd"} + "v" as shortcuts, set as below. -- require('./modules/vim_keymap'):bind_vim_keymap_with({"cmd"}, "v") -- --------------------------------------------------------------------- -- Check key code of hammerspoon as below -- | f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, f13, f14, f15, -- | f16, f17, f18, f19, f20, pad, pad*, pad+, pad/, pad-, pad=, -- | pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7, pad8, pad9, -- | padclear, padenter, return, tab, space, delete, escape, help, -- | home, pageup, forwarddelete, end, pagedown, left, right, down, up, -- | shift, rightshift, cmd, rightcmd, alt, rightalt, ctrl, rightctrl, -- | capslock, fn -- --------------------------------------------------------------------- require('./modules/vim_keymap'):bind_vim_keymap_with({"cmd", "shift"}, "space") <file_sep>local vim_keymap_obj = {} -- vim mode draft local mod = { empty = {}, shift = {"shift"}, alt = {"alt"}, cmd = {"cmd"}, ctrl = {"ctrl"}, cmd_and_shift = {"cmd", "shift"}, } local vim_mode = true local fastKeyStroke = function(modifier, event_char) hs.eventtap.keyStroke(modifier, event_char, 30) end local h_bind = hs.hotkey.new({}, "h", function() fastKeyStroke(mod.empty, "left") end, nil, function() fastKeyStroke(mod.empty, "left") end):enable() local j_bind = hs.hotkey.new({}, "j", function() fastKeyStroke(mod.empty, "down") end, nil, function() fastKeyStroke(mod.empty, "down") end):enable() local k_bind = hs.hotkey.new({}, "k", function() fastKeyStroke(mod.empty, "up") end, nil, function() fastKeyStroke(mod.empty, "up") end):enable() local l_bind = hs.hotkey.new({}, "l", function() fastKeyStroke(mod.empty, "right") end, nil, function() fastKeyStroke(mod.empty, "right") end):enable() local x_bind = hs.hotkey.new({}, "x", function() fastKeyStroke(mod.empty, "forwarddelete") end, nil, function() fastKeyStroke(mod.empty, "forwarddelete") end):enable() local w_bind = hs.hotkey.new({}, "w", function() fastKeyStroke(mod.alt, "right") end, nil, function() fastKeyStroke(mod.alt, "right") end):enable() local b_bind = hs.hotkey.new({}, "b", function() fastKeyStroke(mod.alt, "left") end, nil, function() fastKeyStroke(mod.alt, "left") end):enable() local i_bind = hs.hotkey.new({}, "i", function() vim_keymap_obj.set_vim_mode() end):enable() local a_bind = hs.hotkey.new({}, "a", function() fastKeyStroke(mod.empty, "right") vim_keymap_obj.set_vim_mode() end):enable() local o_bind = hs.hotkey.new({}, "o", function() fastKeyStroke(mod.cmd, "right") fastKeyStroke(mod.empty, "return") vim_keymap_obj.set_vim_mode() end):enable() local p_bind = hs.hotkey.new({}, "p", function() fastKeyStroke(mod.cmd, "v") end):enable() local u_bind = hs.hotkey.new({}, "u", function() fastKeyStroke(mod.cmd, "z") end):enable() local shift_d_bind = hs.hotkey.new({"shift"}, "d", function() fastKeyStroke(mod.cmd_and_shift, "right") fastKeyStroke(mod.empty, "forwarddelete") end):enable() local shift_a_bind = hs.hotkey.new({"shift"}, "a", function() fastKeyStroke(mod.cmd, "right") vim_keymap_obj.set_vim_mode() end):enable() local shift_o_bind = hs.hotkey.new({"shift"}, "o", function() fastKeyStroke(mod.cmd, "left") fastKeyStroke(mod.empty, "return") fastKeyStroke(mod.empty, "up") vim_keymap_obj.set_vim_mode() end):enable() local shift_i_bind = hs.hotkey.new({"shift"}, "i", function() fastKeyStroke(mod.cmd, "left") vim_keymap_obj.set_vim_mode() end):enable() -- bind 'y' + 'w' and 'd' + 'b' local y_modal = hs.hotkey.modal.new() y_modal:bind({}, "y", function() fastKeyStroke(mod.cmd, "left") fastKeyStroke(mod.cmd_and_shift, "right") fastKeyStroke(mod.cmd, "c") y_modal:exit() end) local y_with_other_bind = hs.hotkey.new({}, "y", function() y_modal:enter() end ):enable() -- bind 'd' + 'w' and 'd' + 'b' local d_modal = hs.hotkey.modal.new() d_modal:bind({}, "w", function() fastKeyStroke(mod.alt, "forwarddelete") d_modal:exit() end) d_modal:bind({}, "b", function() fastKeyStroke(mod.alt, "delete") d_modal:exit() end) d_modal:bind({}, "d", function() fastKeyStroke(mod.cmd, "left") fastKeyStroke(mod.cmd_and_shift, "right") fastKeyStroke(mod.cmd, "x") d_modal:exit() end) local d_with_other_bind = hs.hotkey.new({}, "d", function() d_modal:enter() end ):enable() function set_vim_keymap() h_bind:enable() j_bind:enable() k_bind:enable() l_bind:enable() x_bind:enable() o_bind:enable() w_bind:enable() b_bind:enable() i_bind:enable() a_bind:enable() p_bind:enable() u_bind:enable() shift_d_bind:enable() shift_a_bind:enable() shift_o_bind:enable() shift_i_bind:enable() y_with_other_bind:enable() d_with_other_bind:enable() hs.alert.show("set vim keymap") end function unset_vim_keymap() h_bind:disable() j_bind:disable() k_bind:disable() l_bind:disable() x_bind:disable() o_bind:disable() w_bind:disable() b_bind:disable() i_bind:disable() a_bind:disable() p_bind:disable() u_bind:disable() shift_d_bind:disable() shift_a_bind:disable() shift_o_bind:disable() shift_i_bind:disable() y_with_other_bind:disable() d_with_other_bind:disable() hs.alert.show("unset vim keymap") end local vim_mode_menubar = hs.menubar.new() function vim_keymap_obj:set_vim_mode() if vim_mode == true then unset_vim_keymap() vim_mode_menubar:setTitle("𝑽_OFF") vim_mode = false else set_vim_keymap() vim_mode_menubar:setTitle("𝑽_ON") vim_mode = true end end function vim_keymap_obj:make_menubar_clickable() if vim_mode_menubar then vim_mode_menubar:setClickCallback(vim_keymap_obj.set_vim_mode) vim_mode_menubar:setTitle("𝑽_ON") end end function vim_keymap_obj:bind_vim_keymap_with(modifier, key) hs.hotkey.bind(modifier, key, vim_keymap_obj.set_vim_mode) vim_keymap_obj.make_menubar_clickable() end return vim_keymap_obj <file_sep>#!/bin/bash CONFIG_PATH=~/.hammerspoon echo -e "\033[1;33m" mkdir -p ${CONFIG_PATH} mkdir -p ${CONFIG_PATH}/Spoons # Copy init.lua to ${CONFIG_PATH} # If init.lua already exists in your mac, append it. if [ ! -e ${CONFIG_PATH}/init.lua ] then echo "init.lua is copied at ~/.hammerspoon" cp ./hammerspoon_config/init.lua ${CONFIG_PATH}/init.lua else echo "New settings are appended in your init.lua" cat ./hammerspoon_config/init.lua >> ${CONFIG_PATH}/init.lua fi if [ ! -d ${CONFIG_PATH}/modules ] then cp -rf ./hammerspoon_config/modules ${CONFIG_PATH}/modules else if [ -e ${CONFIG_PATH}/vim_keymap.lua ] then mv ${CONFIG_PATH}/vim_keymap.lua ${CONFIG_PATH}/vim_keymap.lua_backup fi cp ./hammerspoon_config/vim_keymap.lua ${CONFIG_PATH}/vim_keymap.lua if [ -e ${CONFIG_PATH}/change_input_source_if_ko.lua ] then mv ${CONFIG_PATH}/change_input_source_if_ko.lua ${CONFIG_PATH}/change_input_source_if_ko.lua_backup fi cp ./hammerspoon_config/change_input_source_if_ko.lua ${CONFIG_PATH}/change_input_source_if_ko.lua fi echo -e "Please remove this directory(vimlife_with_hammerspoon) 👍" echo -e "\033[0m"
e324152152a10bfb3dca63c856263e6d9988ec0e
[ "Markdown", "Shell", "Lua" ]
5
Markdown
humblEgo/vimlife_with_hammerspoon
8daf14d91b33f8b873f1322cd9c3a748222b6c3f
2acf39412be53909aa29a3b8df51b1849516047d
refs/heads/master
<repo_name>garystafford/chef-cookbooks2<file_sep>/README.md # chef-cookbooks2 <file_sep>/database-server/recipes/default.rb # # Cookbook Name:: database-server # Recipe:: default # # Copyright 2015, YOUR_COMPANY_NAME # # All rights reserved - Do Not Redistribute # mysql_service 'default' do version '5.6' bind_address '0.0.0.0' port '3306' data_dir '/data' initial_root_password '<PASSWORD>' action [:create, :start] end mysql_client 'default' do action :create end <file_sep>/database-server/test/integration/default/serverspec/default_spec.rb require 'spec_helper' describe 'database-server::default' do # Serverspec examples can be found at # http://serverspec.org/resource_types.html describe command('mysql -h 127.0.0.1 --user=root --password=<PASSWORD> --version') do its(:stdout) { should contain('/mysql Ver ') } end if os[:family] == 'redhat' if os[:arch] == 'i386' # 32bit environment spec else describe command('systemctl status mysql-default.service') do its(:stdout) { should contain('Active: active \(running\)') } end describe command('mysql -h 127.0.0.1 --user=root --password=<PASSWORD> --version') do its(:stdout) { should match 'mysql Ver 14.14 Distrib 5.6.27, for Linux \(x86_64\) using EditLine wrapper\n' } end end elsif ['debian', 'ubuntu'].include?(os[:family]) describe command('service mysql status') do its(:stdout) { should match /mysql stop\/waiting/ } end describe command('mysql -h 127.0.0.1 --user=root --password=<PASSWORD> --version') do its(:stdout) { should match 'mysql Ver 14.14 Distrib 5.5.44, for debian-linux-gnu \(x86_64\) using readline 6.3' } end end end
7eea9f81140f332ae18faf893b061872edee4b71
[ "Markdown", "Ruby" ]
3
Markdown
garystafford/chef-cookbooks2
a38668740a27c9b6883aa3e2c349c8142580e4c1
af351bcdc695dfad972fe1060f1426b2f11c454c
refs/heads/master
<file_sep># Maintainer: BigfootACA <<EMAIL>> _pyname=glance-store _pycname=${_pyname//-/_} pkgname=python-$_pyname pkgver=2.7.0 pkgrel=1 pkgdesc="OpenStack Image Service Store library" arch=(any) url="https://docs.openstack.org/glance_store/latest/" license=(Apache) depends=( python python-oslo-config python-oslo-i18n python-oslo-serialization python-oslo-utils python-oslo-concurrency python-stevedore python-eventlet python-six python-jsonschema python-keystoneauth1 python-keystoneclient python-requests ) makedepends=( python-setuptools python-sphinx python-openstackdocstheme python-reno python-sphinxcontrib-apidoc ) checkdepends=( python-hacking python-doc8 python-coverage python-fixtures python-subunit python-requests-mock python-retrying python-stestr python-testscenarios python-testtools python-oslotest python-boto3 python-oslo-vmware python-httplib2 python-swiftclient python-cinderclient python-os-brick python-oslo-rootwrap python-oslo-privsep ) source=("https://pypi.io/packages/source/${_pycname::1}/$_pycname/$_pycname-$pkgver.tar.gz") md5sums=('264a478c9fb01372e7d88baa99e280ba') sha256sums=('8f7faf76e76f2170ea124f9e5e71752da71d1db25053e73581a6291330f687b3') sha512sums=('fc5b<KEY>') export PBR_VERSION=$pkgver build(){ cd $_pycname-$pkgver python setup.py build sphinx-build -b html doc/source doc/build/html } check(){ cd $_pycname-$pkgver stestr run } package(){ cd $_pycname-$pkgver python setup.py install --root "$pkgdir" --optimize=1 install -Dm644 LICENSE "$pkgdir"/usr/share/licenses/$pkgname/LICENSE mkdir -p "${pkgdir}/usr/share/doc" cp -r doc/build/html "${pkgdir}/usr/share/doc/${pkgname}" rm -r "${pkgdir}/usr/share/doc/${pkgname}/.doctrees" mv "$pkgdir"{/usr,}/etc }
4163edf7c404055474520e4e5a0c53027d73bb88
[ "Shell" ]
1
Shell
StackArch/pkg-glance-store
e8ffb5b5ad0912166ea851e4d0aaa2aa2d0126ca
4f5289f515f9b98622100165aed211c8c7ede027
refs/heads/main
<file_sep># frl-online-proxy Reverse proxy solution for Adobe customers using FRL-Online on isolated networks. In addition to a basic terminating passthrough mode, it also supports caching, storage and forwarding. [Read the User Guide](https://opensource.adobe.com/frl-online-proxy/) ## Getting help All bug requests, feature requests, questions and feedback submissions are handled with Github issues. Please create a new [issue](https://github.com/adobe/frl-online-proxy/issues) if you need any assisance or support. ## Installation We provide automated builds for each release. These builds currently target Windows and Linux. ### Windows 1. Download the [latest release](https://github.com/adobe/frl-online-proxy/releases/latest). 2. Open the application zip 3. Copy the `frl-proxy` directory to your desired root location 4. Open a PowerShell terminal 5. Change directory to the frl-proxy location ``` > cd c:\path\to\frl-proxy ``` 6. Run the proxy ``` > .\frl-proxy.exe start ``` ### Linux 1. Download the [latest release](https://github.com/adobe/frl-online-proxy/releases/latest). We recommend downloading it to the root of the proxy directory (e.g. `/home/[user]`) ``` $ wget https://github.com/adobe/frl-online-proxy/releases/download/v0.5.1/frl-proxy-linux-0.5.1.tar.gz ``` 2. Extract the archive ``` $ tar xf frl-proxy-linux-0.5.1.tar.gz ``` 3. The archive will extract to the directory `frl-proxy`, which contains the application binary ``` $ cd frl-proxy $ ./frl-proxy start ``` ## Usage See the [User Guide](https://opensource.adobe.com/frl-online-proxy/) for details on setting up and running the FRL Online Proxy. ## Building and Running **NOTE:** We currently provide [builds](https://github.com/adobe/frl-online-proxy/releases/latest) for Windows and Linux. If you plan to run the proxy on these platforms, we recommend installing the latest build. It is generally only necessary to build the tool if you are doing development work, need to run it on a different platform, or if your system is unable to execute the binary. To build the proxy application, make sure you have the [Rust toolchain](https://rustup.rs/) installed on your system. Then, from a terminal, clone this project. ``` $ git clone https://github.com/adobe/frl-online-proxy.git $ cd frl-online-proxy ``` ### Running with Cargo To run the proxy application, invoke `cargo run`. This installs dependencies, compiles, links, assembles and runs the executable. ``` $ cargo run -- start ``` Any commands or options specified after the `--` will be sent to the proxy application. For example, to start the proxy in a different mode: ``` $ cargo run -- start --mode cache ``` The first time you invoke `cargo run` it will take some time to install and build all dependencies. Subsequent `cargo run` invocations will skip the build and run the binary. ### Building Build the proxy application with `cargo build`. Once the build process completes, the `frl-proxy` binary can be found in the `target/debug` directory. The proxy can also be built for release (which creates and optimized binary) with `cargo build --release`. This binary can be found in `target/release`. ### Buliding on Ubuntu Ubuntu requires a few system packages to be installed in order to build the application. ``` $ sudo apt-get update $ sudo apt install -y build-essential libssl-dev pkg-config ``` NOTE: This is known to be sufficient for Ubuntu 18.04, but should also work for Debian and other Debian variants. ### Buliding on CentOS CentOS/RHEL also requires some system packages before the application can be built. ``` $ sudo yum install -y gcc openssl-devel ``` <file_sep>#!/usr/bin/env node /* * Copyright 2020 Adobe * All Rights Reserved. * * NOTICE: Adobe permits you to use, modify, and distribute this file in * accordance with the terms of the Adobe license agreement accompanying * it. */ import pkg from 'shelljs'; const { rm, mkdir, cp, cd } = pkg; import archiver from 'archiver'; import tar from 'tar'; import { join } from 'path'; import fs from 'fs'; const version = process.env.npm_package_version; const packageFile = 'frl-proxy-'+platform()+'-'+version+(platform() == 'win' ? '.zip' : '.tar.gz'); const binary = releasePath(); const externalDir = join('external', platform()); const releaseDir = 'dist'; const packageDir = 'frl-proxy'; const archive = (platform() == 'win' ? makeZip : makeTar); // prepare the release directory rm('-rf', releaseDir); mkdir(releaseDir); cd(releaseDir); mkdir(packageDir); // copy external files to package dir cp('-r', join('..', externalDir, '*'), packageDir); // copy the release binary to package dir cp(join('..', binary), packageDir); makeRelease(); async function makeRelease() { await archive(packageDir, packageFile, packageDir); console.log(packageFile+' created successfully'); } function platform() { const platform = process.platform; if (platform == 'win32') { return 'win'; } if (platform == 'darwin') { return 'macos'; } return platform; } function releasePath() { if (platform() == 'linux') { return join('target', 'x86_64-unknown-linux-musl', 'release', 'frl-proxy'); } return join('target', 'release', (platform() == 'win' ? 'frl-proxy.exe' : 'frl-proxy')); } function makeZip(source, out, innerDir) { const archive = archiver('zip', { zlib: { level: 9 }}); const stream = fs.createWriteStream(out); return new Promise((resolve, reject) => { archive .directory(source, innerDir) .on('error', err => reject(err)) .pipe(stream); stream.on('close', () => resolve()); archive.finalize(); }); } async function makeTar(source, out, _) { await tar.c( {gzip: true, file: out}, [source] ); } <file_sep>[package] name = "frl-proxy" version = "1.0.1" authors = ["<NAME> <<EMAIL>>", "<NAME> <<EMAIL>>"] edition = "2018" [dependencies] tokio-stream = "~0.1.2" # declare specific version to resolve conflicting dependencies tokio = { version = "~1.0.3", features = ["full"] } hyper = { version = "~0.14.2", features = ["full"] } hyper-tls = "~0.5" native-tls = "~0.2.7" tokio-native-tls = "~0.3" async-stream = "~0.3.0" futures = "~0.3.1" futures-util = "~0.3.1" config = "~0.10" serde = { version = "~1.0.123", features = ["derive"] } serde_json = "~1.0.62" toml = "~0.5" structopt = "~0.3" eyre = "~0.6" log = "~0.4" fern = "~0.6" chrono = "~0.4" ctrlc = { version = "~3.1", features = ["termination"] } openssl-probe = "~0.1.2" sqlx = { version = "~0.5.1", default-features = false, features = [ "runtime-tokio-native-tls", "sqlite" ] } url = "~2.1.1" sys-info = "~0.7.0" dialoguer = "~0.7.1" <file_sep>/* Copyright 2020 Adobe All Rights Reserved. NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms of the Adobe license agreement accompanying it. */ use chrono::{DateTime, Local}; use hyper::{http::request::Parts, Body, Method, Response as HResponse}; use serde_json::Value; use std::collections::HashMap; use url::Url; #[derive(Default, Debug, Clone)] /// The data values found in a COPS request. /// /// Some of these are held in headers, some in URL parameters, and /// some in the body. Where they go and which are required depend /// on whether the request is for activation or deactivation. /// /// We add our own timestamp so we can sort by it, even if the request /// does not have a device timestamp attached. pub struct Request { pub kind: Kind, pub api_key: String, pub request_id: String, pub session_id: String, pub package_id: String, pub asnp_id: String, pub device_id: String, pub device_date: String, pub is_vdi: bool, pub is_virtual: bool, pub os_name: String, pub os_version: String, pub os_user_id: String, pub is_domain_user: bool, pub app_id: String, pub app_version: String, pub ngl_version: String, pub timestamp: String, } impl Request { /// Create a COPS request from a network request received by the proxy. pub fn from_network(parts: &Parts, body: &[u8]) -> Result<Request, BadRequest> { match parts.uri.path() { ACTIVATION_ENDPOINT => { if parts.method == Method::POST { Request::from_activation(parts, body) } else { Err(BadRequest::from("Activation method must be POST")) } } DEACTIVATION_ENDPOINT => { if parts.method == Method::DELETE { Request::from_deactivation(parts) } else { Err(BadRequest::from("Deactivation method must be DELETE")) } } path => { let message = format!("Unknown endpoint path: {}", path); Err(BadRequest::from(&message)) } } } /// Create a network request which submits this COPS request to the given server. pub fn to_network(&self, scheme: &str, host: &str) -> hyper::Request<Body> { match self.kind { Kind::Activation => self.to_activation(scheme, host), Kind::Deactivation => self.to_deactivation(scheme, host), } } fn from_activation(parts: &Parts, body: &[u8]) -> Result<Request, BadRequest> { let mut req = Request { kind: Kind::Activation, timestamp: current_timestamp(), ..Default::default() }; req.update_from_headers(parts)?; let map: HashMap<String, Value> = serde_json::from_slice(body).unwrap_or_default(); if map.is_empty() { return Err(BadRequest::from("Malformed activation request body")); } if let Some(package_id) = map["npdId"].as_str() { req.package_id = package_id.to_string(); } else { return Err(BadRequest::from("Missing npdId field in request.")); } if let Some(asnp_id) = map["asnpTemplateId"].as_str() { req.asnp_id = asnp_id.to_string(); } else { return Err(BadRequest::from("Missing asnpTemplateId field in request.")); } if map.get("appDetails").is_none() { return Err(BadRequest::from("Missing appDetails object in request.")); } let app_map: HashMap<String, Value> = serde_json::from_value(map["appDetails"].clone()).unwrap_or_default(); if let Some(app_id) = app_map["nglAppId"].as_str() { req.app_id = app_id.to_string(); } else { return Err(BadRequest::from("Missing nglAppId field in request.")); } if let Some(app_version) = app_map["nglAppVersion"].as_str() { req.app_version = app_version.to_string(); } else { return Err(BadRequest::from("Missing nglAppVersion field in request.")); } if let Some(ngl_version) = app_map["nglLibVersion"].as_str() { req.ngl_version = ngl_version.to_string(); } else { return Err(BadRequest::from("Missing nglLibVersion field in request.")); } if map.get("deviceDetails").is_none() { return Err(BadRequest::from("Missing deviceDetails object in request.")); } let device_map: HashMap<String, Value> = serde_json::from_value(map["deviceDetails"].clone()).unwrap_or_default(); if let Some(device_date) = device_map["currentDate"].as_str() { req.device_date = device_date.to_string(); } else { return Err(BadRequest::from("Missing currentDate field in request.")); } if let Some(device_id) = device_map["deviceId"].as_str() { req.device_id = device_id.to_string(); } else { return Err(BadRequest::from("Missing deviceId field in request.")); } if let Some(os_user_id) = device_map["osUserId"].as_str() { req.os_user_id = os_user_id.to_string(); } else { return Err(BadRequest::from("Missing osUserId field in request.")); } if let Some(os_name) = device_map["osName"].as_str() { req.os_name = os_name.to_string(); } else { return Err(BadRequest::from("Missing osName field in request.")); } if let Some(os_version) = device_map["osVersion"].as_str() { req.os_version = os_version.to_string(); } else { return Err(BadRequest::from("Missing osVersion field in request.")); } if let Some(is_vdi) = device_map["enableVdiMarkerExists"].as_bool() { req.is_vdi = is_vdi; } else { req.is_vdi = false; } if let Some(is_domain_user) = device_map["isOsUserAccountInDomain"].as_bool() { req.is_domain_user = is_domain_user; } else { req.is_domain_user = false; } if let Some(is_virtual) = device_map["isVirtualEnvironment"].as_bool() { req.is_virtual = is_virtual; } else { req.is_virtual = false; } Ok(req) } fn from_deactivation(parts: &Parts) -> Result<Request, BadRequest> { let mut req = Request { kind: Kind::Deactivation, timestamp: current_timestamp(), ..Default::default() }; req.update_from_headers(parts)?; let request_url = format!("http://placeholder{}", &parts.uri.to_string()); let pairs: HashMap<String, String> = Url::parse(&request_url) .expect("Bad deactivation query string") .query_pairs() .map(|(k, v)| (k.to_string(), v.to_string())) .collect(); if let Some(npd_id) = pairs.get("npdId") { req.package_id = npd_id.clone(); } else { return Err(BadRequest::from("Missing 'npdId' parameter")); } if let Some(device_id) = pairs.get("deviceId") { req.device_id = device_id.clone() } else { return Err(BadRequest::from("Missing 'deviceId' parameter")); } if let Some(os_user_id) = pairs.get("osUserId") { req.os_user_id = os_user_id.clone() } else { return Err(BadRequest::from("Missing 'osUserId' parameter")); } if let Some(is_vdi) = pairs.get("enableVdiMarkerExists") { req.is_vdi = is_vdi.eq_ignore_ascii_case("true") } else { req.is_vdi = false } Ok(req) } /// Convert a COPS activation request to its network form. fn to_activation(&self, scheme: &str, host: &str) -> hyper::Request<Body> { let body = serde_json::json!({ "npdId" : &self.package_id, "asnpTemplateId" : &self.asnp_id, "appDetails" : { "nglAppId" : &self.app_id, "nglAppVersion" : &self.app_version, "nglLibVersion" : &self.ngl_version }, "deviceDetails" : { "currentDate" : &self.device_date, "deviceId" : &self.device_id, "enableVdiMarkerExists" : &self.is_vdi, "isOsUserAccountInDomain" : &self.is_domain_user, "isVirtualEnvironment" : &self.is_virtual, "osName" : &self.os_name, "osUserId" : &self.os_user_id, "osVersion" : &self.os_version } }); let builder = hyper::Request::builder() .method("POST") .uri(format!("{}://{}{}", scheme, host, ACTIVATION_ENDPOINT).as_str()) .header("host", host) .header("x-api-key", &self.api_key) .header("x-session-id", &self.session_id) .header("x-request-id", &self.request_id) .header("content-type", "application/json") .header("accept", "application/json") .header("user-agent", agent()); builder .body(Body::from(body.to_string())) .expect("Error building activation request body") } /// Convert a COPS deactivation request to its network form. fn to_deactivation(&self, scheme: &str, host: &str) -> hyper::Request<Body> { let uri = format!( "{}://{}{}?npdId={}&deviceId={}&osUserId={}&enableVdiMarkerExists={}", scheme, host, DEACTIVATION_ENDPOINT, &self.package_id, &self.device_id, &self.os_user_id, self.is_vdi, ); let builder = hyper::Request::builder() .method("DELETE") .uri(uri) .header("host", host) .header("x-api-key", &self.api_key) .header("x-request-id", &self.request_id) .header("accept", "application/json") .header("user-agent", agent()); builder.body(Body::empty()).expect("Error building deactivation request body") } /// update a request with info from network headers fn update_from_headers(&mut self, parts: &Parts) -> Result<&mut Request, BadRequest> { for (k, v) in parts.headers.iter() { if let Ok(val) = v.to_str() { match k.as_str() { "x-api-key" => self.api_key = val.to_string(), "x-request-id" => self.request_id = val.to_string(), "x-session-id" => self.session_id = val.to_string(), _ => (), } } } match self.kind { Kind::Activation => { if self.api_key.is_empty() || self.request_id.is_empty() || self.session_id.is_empty() { return Err(BadRequest::from("Missing required header field")); } } Kind::Deactivation => { if self.api_key.is_empty() || self.request_id.is_empty() { return Err(BadRequest::from("Missing required header field")); } } } Ok(self) } } pub struct Response { pub kind: Kind, pub request_id: String, pub body: Vec<u8>, pub timestamp: String, } impl Response { pub fn from_network(request: &Request, body: &[u8]) -> Response { Response { kind: request.kind.clone(), request_id: request.request_id.clone(), body: Vec::from(body), timestamp: current_timestamp(), } } pub fn to_network(&self) -> HResponse<Body> { HResponse::builder() .status(200) .header("server", agent()) .header("x-request-id", self.request_id.clone()) .header("content-type", "application/json;charset=UTF-8") .body(Body::from(self.body.clone())) .unwrap() } } const ACTIVATION_ENDPOINT: &str = "/asnp/frl_connected/values/v2"; const DEACTIVATION_ENDPOINT: &str = "/asnp/frl_connected/v1"; #[derive(Debug, Clone)] pub enum Kind { Activation, Deactivation, } impl std::fmt::Display for Kind { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Kind::Activation => "Activation".fmt(f), Kind::Deactivation => "Deactivation".fmt(f), } } } impl Default for Kind { fn default() -> Self { Kind::Activation } } #[derive(Debug, Clone)] pub struct BadRequest { pub reason: String, } impl BadRequest { pub fn from(why: &str) -> BadRequest { BadRequest { reason: why.to_string() } } } pub fn agent() -> String { format!( "FRL-Online-Proxy/{} ({}/{})", env!("CARGO_PKG_VERSION"), std::env::consts::OS, sys_info::os_release().as_deref().unwrap_or("Unknown") ) } pub fn current_timestamp() -> String { let now: DateTime<Local> = Local::now(); now.format("%Y-%m-%dT%H:%M:%S%.3f%z").to_string() } <file_sep>**NOTE:** The only new addition for this release is the macOS build, so we are re-posting the notes for the last release. ### Added * Cache functionality with store and forward modes ([#4]) * New commands for cache control ([#8], [#10]): * `clear` to clear the cache with confirmation * `export` to export requests to an external forwarder * `import` to import responses from an external forwarder * Guided wizard for creating config files ([#14]) * command-line flags for overriding configuration file options: * `-d` global option to force debug log level * `-l` global option to choose log destination (console or file) * `--mode` option on `start` command to choose cache mode * `--ssl` option on `start` command to enable/disable SSL * environment variables can be used for sensitive configuration data (such as certificate password) ### Changed * added/updated package dependencies ([#4], [#17]) * latest tokio for general async support * native-tls rather than rustls for SSL support * certificates in `pkcs` rather than `pem` format * latest sqlx for async sqlite support * use of config file is now required ([#11]) ### Fixed * database updates are now transactional ([#17]) * database files are explicitly closed at end of each run ([#17]) [#4]: https://github.com/adobe/frl-online-proxy/pull/4 [#8]: https://github.com/adobe/frl-online-proxy/pull/8 [#10]: https://github.com/adobe/frl-online-proxy/pull/10 [#11]: https://github.com/adobe/frl-online-proxy/pull/11 [#14]: https://github.com/adobe/frl-online-proxy/pull/14 [#17]: https://github.com/adobe/frl-online-proxy/pull/17 <file_sep>/* Copyright 2020 Adobe All Rights Reserved. NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms of the Adobe license agreement accompanying it. */ use crate::cops::{Kind, Request as CRequest, Response as CResponse}; use crate::settings::{ProxyMode, Settings}; use dialoguer::Confirm; use eyre::{eyre, Result, WrapErr}; use log::{debug, error, info}; use sqlx::sqlite::SqliteRow; use sqlx::{ sqlite::{SqliteConnectOptions, SqlitePool, SqlitePoolOptions}, ConnectOptions, Row, }; use std::{env, str::FromStr, sync::Arc}; #[derive(Default)] pub struct Cache { enabled: bool, mode: ProxyMode, db_pool: Option<SqlitePool>, } impl Cache { pub async fn from(conf: &Settings, can_create: bool) -> Result<Arc<Cache>> { if let ProxyMode::Passthrough = conf.proxy.mode { return Ok(Arc::new(Cache::default())); } let db_name = &conf.cache.db_path; let mode = if can_create { "rwc" } else { std::fs::metadata(db_name) .wrap_err(format!("Can't open cache db: {}", db_name))?; "rw" }; let pool = db_init(db_name, mode) .await .wrap_err(format!("Can't connect to cache db: {}", db_name))?; info!("Valid cache database: {}", &db_name); Ok(Arc::new(Cache { enabled: true, mode: conf.proxy.mode.clone(), db_pool: Some(pool), })) } pub async fn close(&self) { if self.enabled { if let Some(pool) = &self.db_pool { if !pool.is_closed() { pool.close().await; } } } } pub async fn clear(&self, yes: bool) -> Result<()> { let confirm = match yes { true => true, false => Confirm::new() .with_prompt("Really clear the cache? This operation cannot be undone.") .default(false) .show_default(true) .interact()?, }; if confirm { let pool = self.db_pool.as_ref().unwrap(); let mut tx = pool.begin().await?; sqlx::query(CLEAR_ALL).execute(&mut tx).await?; tx.commit().await?; eprintln!("Cache has been cleared."); } self.close().await; Ok(()) } pub async fn import(&self, path: &str) -> Result<()> { std::fs::metadata(path)?; // first read the forwarded pairs let in_pool = db_init(path, "rw").await?; let pairs = fetch_forwarded_pairs(&in_pool).await?; in_pool.close().await; // now add them to the cache let out_pool = self.db_pool.as_ref().unwrap(); let pairs_count = pairs.len(); for (req, resp) in pairs.iter() { match req.kind { Kind::Activation => { store_activation_response(ProxyMode::Cache, out_pool, req, resp) .await?; } Kind::Deactivation => { store_deactivation_response(ProxyMode::Cache, out_pool, req, resp) .await?; } } } out_pool.close().await; eprintln!( "Imported {} forwarded request/response pair(s) from {}", pairs_count, path ); Ok(()) } pub async fn export(&self, path: &str) -> Result<()> { if std::fs::metadata(path).is_ok() { return Err(eyre!("Cannot export to an existing file: {}", path)); } // first read the unanswered requests let in_pool = self.db_pool.as_ref().unwrap(); let requests = fetch_unanswered_requests(in_pool).await?; in_pool.close().await; // now store them to the other database let request_count = requests.len(); let out_pool = db_init(path, "rwc").await?; for req in requests.iter() { match req.kind { Kind::Activation => store_activation_request(&out_pool, req).await?, Kind::Deactivation => store_deactivation_request(&out_pool, req).await?, } } out_pool.close().await; eprintln!("Exported {} stored request(s) to {}", request_count, path); Ok(()) } pub async fn store_request(&self, req: &CRequest) { if !self.enabled { return; } let pool = self.db_pool.as_ref().unwrap(); if let Err(err) = match req.kind { Kind::Activation => store_activation_request(pool, req).await, Kind::Deactivation => store_deactivation_request(pool, req).await, } { error!("Cache of {} request {} failed: {:?}", req.kind, req.request_id, err); } } pub async fn store_response(&self, req: &CRequest, resp: &CResponse) { if !self.enabled { return; } let pool = self.db_pool.as_ref().unwrap(); let mode = self.mode.clone(); if let Err(err) = match req.kind { Kind::Activation => store_activation_response(mode, pool, req, resp).await, Kind::Deactivation => { store_deactivation_response(mode, pool, req, resp).await } } { error!("Cache of {} response {} failed: {:?}", req.kind, req.request_id, err); } } pub async fn fetch_response(&self, req: &CRequest) -> Option<CResponse> { if !self.enabled { return None; } let pool = self.db_pool.as_ref().unwrap(); match match req.kind { Kind::Activation => fetch_activation_response(pool, req).await, Kind::Deactivation => fetch_deactivation_response(pool, req).await, } { Ok(resp) => resp, Err(err) => { error!( "Fetch of {} response {} failed: {:?}", req.kind, req.request_id, err ); None } } } pub async fn fetch_forwarding_requests(&self) -> Vec<CRequest> { if !self.enabled { return Vec::new(); } let pool = self.db_pool.as_ref().unwrap(); match fetch_unanswered_requests(pool).await { Ok(result) => result, Err(err) => { error!("Fetch of forwarding requests failed: {:?}", err); Vec::new() } } } } async fn db_init(db_name: &str, mode: &str) -> Result<SqlitePool> { let db_url = format!("file:{}?mode={}", db_name, mode); let mut options = SqliteConnectOptions::from_str(&db_url).map_err(|e| eyre!(e))?; if env::var("FRL_PROXY_ENABLE_STATEMENT_LOGGING").is_err() { options.disable_statement_logging(); } let pool = SqlitePoolOptions::new().max_connections(5).connect_with(options).await?; sqlx::query(ACTIVATION_REQUEST_SCHEMA).execute(&pool).await?; sqlx::query(DEACTIVATION_REQUEST_SCHEMA).execute(&pool).await?; sqlx::query(ACTIVATION_RESPONSE_SCHEMA).execute(&pool).await?; sqlx::query(DEACTIVATION_RESPONSE_SCHEMA).execute(&pool).await?; Ok(pool) } async fn store_activation_request(pool: &SqlitePool, req: &CRequest) -> Result<()> { let field_list = r#" ( activation_key, deactivation_key, api_key, request_id, session_id, device_date, package_id, asnp_id, device_id, os_user_id, is_vdi, is_domain_user, is_virtual, os_name, os_version, app_id, app_version, ngl_version, timestamp )"#; let value_list = "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; let i_str = format!( "insert or replace into activation_requests {} values {}", field_list, value_list ); let a_key = activation_id(req); debug!("Storing activation request {} with key: {}", &req.request_id, &a_key); let mut tx = pool.begin().await?; let result = sqlx::query(&i_str) .bind(&a_key) .bind(deactivation_id(req)) .bind(&req.api_key) .bind(&req.request_id) .bind(&req.session_id) .bind(&req.device_date) .bind(&req.package_id) .bind(&req.asnp_id) .bind(&req.device_id) .bind(&req.os_user_id) .bind(req.is_vdi) .bind(req.is_domain_user) .bind(req.is_virtual) .bind(&req.os_name) .bind(&req.os_version) .bind(&req.app_id) .bind(&req.app_version) .bind(&req.ngl_version) .bind(&req.timestamp) .execute(&mut tx) .await?; tx.commit().await?; debug!("Stored activation request has rowid {}", result.last_insert_rowid()); Ok(()) } async fn store_deactivation_request(pool: &SqlitePool, req: &CRequest) -> Result<()> { let field_list = r#" ( deactivation_key, api_key, request_id, package_id, device_id, os_user_id, is_vdi, is_domain_user, is_virtual, timestamp )"#; let value_list = "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; let i_str = format!( "insert or replace into deactivation_requests {} values {}", field_list, value_list ); let d_key = deactivation_id(req); debug!("Storing deactivation request {} with key: {}", &req.request_id, &d_key); let mut tx = pool.begin().await?; let result = sqlx::query(&i_str) .bind(&d_key) .bind(&req.api_key) .bind(&req.request_id) .bind(&req.package_id) .bind(&req.device_id) .bind(&req.os_user_id) .bind(req.is_vdi) .bind(req.is_domain_user) .bind(req.is_virtual) .bind(&req.timestamp) .execute(&mut tx) .await?; tx.commit().await?; debug!("Stored deactivation request has rowid {}", result.last_insert_rowid()); Ok(()) } async fn store_activation_response( mode: ProxyMode, pool: &SqlitePool, req: &CRequest, resp: &CResponse, ) -> Result<()> { let field_list = "(activation_key, deactivation_key, body, timestamp)"; let value_list = "(?, ?, ?, ?)"; let i_str = format!( "insert or replace into activation_responses {} values {}", field_list, value_list ); let a_key = activation_id(req); let d_key = deactivation_id(req); let mut tx = pool.begin().await?; debug!("Storing activation response {} with key: {}", &req.request_id, &a_key); let result = sqlx::query(&i_str) .bind(&a_key) .bind(&d_key) .bind(std::str::from_utf8(&resp.body).unwrap()) .bind(&req.timestamp) .execute(&mut tx) .await?; debug!("Stored activation response has rowid {}", result.last_insert_rowid()); if let ProxyMode::Forward = mode { // if we are forwarding, then we just remember the response } else { // otherwise we remove all stored deactivation requests/responses as they are now invalid let d_key = deactivation_id(req); debug!("Removing deactivation requests with key: {}", d_key); let d_str = "delete from deactivation_requests where deactivation_key = ?"; sqlx::query(d_str).bind(&d_key).execute(&mut tx).await?; debug!("Removing deactivation responses with key: {}", d_key); let d_str = "delete from deactivation_responses where deactivation_key = ?"; sqlx::query(d_str).bind(&d_key).execute(&mut tx).await?; } tx.commit().await?; Ok(()) } async fn store_deactivation_response( mode: ProxyMode, pool: &SqlitePool, req: &CRequest, resp: &CResponse, ) -> Result<()> { let mut tx = pool.begin().await?; if let ProxyMode::Forward = mode { // when we are forwarding, we store the response for later processing let field_list = "(deactivation_key, body, timestamp)"; let value_list = "(?, ?, ?)"; let i_str = format!( "insert or replace into deactivation_responses {} values {}", field_list, value_list ); let d_key = deactivation_id(req); debug!("Storing deactivation response {} with key: {}", &req.request_id, &d_key); let result = sqlx::query(&i_str) .bind(&d_key) .bind(std::str::from_utf8(&resp.body).unwrap()) .bind(&req.timestamp) .execute(&mut tx) .await?; debug!("Stored deactivation response has rowid {}", result.last_insert_rowid()); } else { // when we are live, we remove all activation requests/responses as they are now invalid let d_key = deactivation_id(req); debug!("Removing activation requests with deactivation key: {}", d_key); let d_str = "delete from activation_requests where deactivation_key = ?"; sqlx::query(d_str).bind(&d_key).execute(&mut tx).await?; debug!("Removing activation responses with deactivation key: {}", d_key); let d_str = "delete from activation_responses where deactivation_key = ?"; sqlx::query(d_str).bind(&d_key).execute(&mut tx).await?; // Remove any pending deactivation requests & responses as they have been completed. debug!("Removing deactivation requests with key: {}", d_key); let d_str = "delete from deactivation_requests where deactivation_key = ?"; sqlx::query(&d_str).bind(&d_key).execute(&mut tx).await?; debug!("Removing deactivation responses with key: {}", d_key); let d_str = "delete from deactivation_responses where deactivation_key = ?"; sqlx::query(&d_str).bind(&d_key).execute(&mut tx).await?; } tx.commit().await?; Ok(()) } async fn fetch_activation_response( pool: &SqlitePool, req: &CRequest, ) -> Result<Option<CResponse>> { let a_key = activation_id(req); let q_str = "select body, timestamp from activation_responses where activation_key = ?"; debug!("Finding activation response with key: {}", &a_key); let result = sqlx::query(&q_str).bind(&a_key).fetch_optional(pool).await?; match result { Some(row) => { let body: String = row.get("body"); let timestamp: String = row.get("timestamp"); Ok(Some(CResponse { kind: req.kind.clone(), request_id: req.request_id.clone(), timestamp, body: body.into_bytes(), })) } None => { debug!("No activation response found for key: {}", &a_key); Ok(None) } } } async fn fetch_deactivation_response( pool: &SqlitePool, req: &CRequest, ) -> Result<Option<CResponse>> { let a_key = activation_id(req); let q_str = "select body from activation_responses where activation_key = ?"; debug!("Finding deactivation response with key: {}", &a_key); let result = sqlx::query(&q_str).bind(&a_key).fetch_optional(pool).await?; match result { Some(row) => { let body: String = row.get("body"); let timestamp: String = row.get("timestamp"); Ok(Some(CResponse { kind: req.kind.clone(), request_id: req.request_id.clone(), timestamp, body: body.into_bytes(), })) } None => { debug!("No deactivation response found for key: {}", &a_key); Ok(None) } } } async fn fetch_unanswered_requests(pool: &SqlitePool) -> Result<Vec<CRequest>> { let mut activations = fetch_unanswered_activations(pool).await?; let mut deactivations = fetch_unanswered_deactivations(pool).await?; activations.append(&mut deactivations); activations.sort_unstable_by(|r1, r2| r1.timestamp.cmp(&r2.timestamp)); Ok(activations) } async fn fetch_unanswered_activations(pool: &SqlitePool) -> Result<Vec<CRequest>> { let mut result: Vec<CRequest> = Vec::new(); let q_str = r#"select * from activation_requests req where not exists (select 1 from activation_responses where activation_key = req.activation_key and timestamp >= req.timestamp )"#; let rows = sqlx::query(q_str).fetch_all(pool).await?; for row in rows.iter() { result.push(request_from_activation_row(row)) } Ok(result) } async fn fetch_unanswered_deactivations(pool: &SqlitePool) -> Result<Vec<CRequest>> { let mut result: Vec<CRequest> = Vec::new(); let q_str = r#"select * from deactivation_requests"#; let rows = sqlx::query(q_str).fetch_all(pool).await?; for row in rows.iter() { result.push(request_from_deactivation_row(row)) } Ok(result) } async fn fetch_forwarded_pairs(pool: &SqlitePool) -> Result<Vec<(CRequest, CResponse)>> { let mut activations = fetch_forwarded_activations(pool).await?; let mut deactivations = fetch_forwarded_deactivations(pool).await?; activations.append(&mut deactivations); activations.sort_unstable_by(|r1, r2| r1.0.timestamp.cmp(&r2.0.timestamp)); Ok(activations) } async fn fetch_forwarded_activations( pool: &SqlitePool, ) -> Result<Vec<(CRequest, CResponse)>> { let mut result: Vec<(CRequest, CResponse)> = Vec::new(); let q_str = r#" select req.*, resp.body from activation_requests req inner join activation_responses resp on req.activation_key = resp.activation_key"#; let rows = sqlx::query(q_str).fetch_all(pool).await?; for row in rows.iter() { result.push((request_from_activation_row(row), response_from_activation_row(row))) } Ok(result) } async fn fetch_forwarded_deactivations( pool: &SqlitePool, ) -> Result<Vec<(CRequest, CResponse)>> { let mut result: Vec<(CRequest, CResponse)> = Vec::new(); let q_str = r#" select req.*, resp.body from deactivation_requests req inner join deactivation_responses resp on req.deactivation_key = resp.deactivation_key"#; let rows = sqlx::query(q_str).fetch_all(pool).await?; for row in rows.iter() { result.push(( request_from_deactivation_row(row), response_from_deactivation_row(row), )); } Ok(result) } fn activation_id(req: &CRequest) -> String { let factors: Vec<String> = vec![req.app_id.clone(), req.ngl_version.clone(), deactivation_id(req)]; factors.join("|") } fn deactivation_id(req: &CRequest) -> String { let factors: Vec<&str> = vec![ req.package_id.as_str(), if req.is_vdi { req.os_user_id.as_str() } else { req.device_id.as_str() }, ]; factors.join("|") } fn request_from_activation_row(row: &SqliteRow) -> CRequest { CRequest { kind: Kind::Activation, api_key: row.get("api_key"), request_id: row.get("request_id"), session_id: row.get("session_id"), package_id: row.get("package_id"), asnp_id: row.get("asnp_id"), device_id: row.get("device_id"), device_date: row.get("device_date"), is_vdi: row.get("is_vdi"), is_virtual: row.get("is_virtual"), os_name: row.get("os_name"), os_version: row.get("os_version"), os_user_id: row.get("os_user_id"), is_domain_user: row.get("is_domain_user"), app_id: row.get("app_id"), app_version: row.get("app_version"), ngl_version: row.get("ngl_version"), timestamp: row.get("timestamp"), } } fn request_from_deactivation_row(row: &SqliteRow) -> CRequest { CRequest { kind: Kind::Deactivation, api_key: row.get("api_key"), request_id: row.get("request_id"), package_id: row.get("package_id"), device_id: row.get("device_id"), is_vdi: row.get("is_vdi"), is_virtual: row.get("is_virtual"), os_user_id: row.get("os_user_id"), is_domain_user: row.get("is_domain_user"), timestamp: row.get("timestamp"), ..Default::default() } } fn response_from_activation_row(row: &SqliteRow) -> CResponse { let body: String = row.get("body"); CResponse { kind: Kind::Activation, request_id: row.get("request_id"), body: body.into_bytes(), timestamp: row.get("timestamp"), } } fn response_from_deactivation_row(row: &SqliteRow) -> CResponse { let body: String = row.get("body"); CResponse { kind: Kind::Deactivation, request_id: row.get("request_id"), body: body.into_bytes(), timestamp: row.get("timestamp"), } } const ACTIVATION_REQUEST_SCHEMA: &str = r#" create table if not exists activation_requests ( activation_key text not null unique, deactivation_key text not null, api_key text not null, request_id text not null, session_id text not null, device_date text not null, package_id text not null, asnp_id text not null, device_id text not null, os_user_id text not null, is_vdi boolean not null, is_domain_user boolean not null, is_virtual boolean not null, os_name text not null, os_version text not null, app_id text not null, app_version text not null, ngl_version text not null, timestamp string not null ); create index if not exists deactivation_request_index on activation_requests ( deactivation_key );"#; const ACTIVATION_RESPONSE_SCHEMA: &str = r#" create table if not exists activation_responses ( activation_key text not null unique, deactivation_key text not null, body text not null, timestamp string not null ); create index if not exists deactivation_response_index on activation_responses ( deactivation_key );"#; const DEACTIVATION_REQUEST_SCHEMA: &str = r#" create table if not exists deactivation_requests ( deactivation_key text not null unique, api_key text not null, request_id text not null, package_id text not null, device_id text not null, os_user_id text not null, is_domain_user boolean not null, is_vdi boolean not null, is_virtual boolean not null, timestamp string not null )"#; const DEACTIVATION_RESPONSE_SCHEMA: &str = r#" create table if not exists deactivation_responses ( deactivation_key text not null unique, body text not null, timestamp string not null );"#; const CLEAR_ALL: &str = r#" delete from deactivation_responses; delete from deactivation_requests; delete from activation_responses; delete from activation_requests; "#; <file_sep>| tag | date | title | |---|---|---| | v1.0.0 | 2021-02-25 | frl-online-proxy v1.0.0 | ### Added * Cache functionality with store and forward modes ([#4]) * New commands for cache control ([#8], [#10]): * `clear` to clear the cache with confirmation * `export` to export requests to an external forwarder * `import` to import responses from an external forwarder * Guided wizard for creating config files ([#14]) * command-line flags for overriding configuration file options: * `-d` global option to force debug log level * `-l` global option to choose log destination (console or file) * `--mode` option on `start` command to choose cache mode * `--ssl` option on `start` command to enable/disable SSL * environment variables can be used for sensitive configuration data (such as certificate password) ### Changed * added/updated package dependencies ([#4], [#17]) * latest tokio for general async support * native-tls rather than rustls for SSL support * certificates in `pkcs` rather than `pem` format * latest sqlx for async sqlite support * use of config file is now required ([#11]) ### Fixed * database updates are now transactional ([#17]) * database files are explicitly closed at end of each run ([#17]) [#4]: https://github.com/adobe/frl-online-proxy/pull/4 [#8]: https://github.com/adobe/frl-online-proxy/pull/8 [#10]: https://github.com/adobe/frl-online-proxy/pull/10 [#11]: https://github.com/adobe/frl-online-proxy/pull/11 [#14]: https://github.com/adobe/frl-online-proxy/pull/14 [#17]: https://github.com/adobe/frl-online-proxy/pull/17 --- | tag | date | title | |---|---|---| | v0.5.1 | 2021-01-05 | frl-online-proxy v0.5.1 | Improved error handling for invalid SSL key. --- | tag | date | title | |---|---|---| | v0.5.0 | 2020-11-12 | frl-online-proxy v0.5.0 | First release of the Adobe FRL Online Proxy. Feature Summary: * Live proxy mode (offline caching is planned for a future release) * SSL Support * Service management tools for Windows <file_sep>/* Copyright 2020 Adobe All Rights Reserved. NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms of the Adobe license agreement accompanying it. */ use crate::cli::FrlProxy; use config::{Config, Environment, File as ConfigFile, FileFormat}; use dialoguer::{Confirm, Input, Password, Select}; use eyre::{eyre, Report, Result, WrapErr}; use serde::{Deserialize, Serialize}; use std::convert::{TryFrom, TryInto}; use std::fs::File; use std::io::prelude::*; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Proxy { pub mode: ProxyMode, pub host: String, pub port: String, pub ssl_port: String, pub remote_host: String, pub ssl: bool, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Ssl { pub cert_path: String, pub cert_password: String, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Logging { pub level: LogLevel, pub destination: LogDestination, pub file_path: String, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Cache { pub db_path: String, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Settings { pub proxy: Proxy, pub ssl: Ssl, pub logging: Logging, pub cache: Cache, } impl Settings { pub fn load_config(args: &FrlProxy) -> Result<Option<Self>> { let path = args.config_file.as_str(); if std::fs::metadata(path).is_ok() { let mut s = Config::new(); s.merge(ConfigFile::from_str( include_str!("res/defaults.toml"), FileFormat::Toml, ))?; s.merge(ConfigFile::with_name(path).format(FileFormat::Toml))?; s.merge(Environment::with_prefix("frl_proxy"))?; let mut conf: Self = s.try_into()?; match args.debug { 1 => conf.logging.level = LogLevel::Debug, 2 => conf.logging.level = LogLevel::Trace, _ => {} } if let Some(log_to) = &args.log_to { let destination: LogDestination = log_to .as_str() .try_into() .wrap_err(format!("Not a recognized log destination: {}", log_to))?; conf.logging.destination = destination; } Ok(Some(conf)) } else { eprintln!("Creating initial configuration file..."); let template = include_str!("res/defaults.toml"); let mut file = File::create(path) .wrap_err(format!("Cannot create config file: {}", path))?; file.write_all(template.as_bytes()) .wrap_err(format!("Cannot write config file: {}", path))?; Ok(None) } } pub fn update_config_file(&mut self, path: &str) -> Result<()> { // update proxy settings including cache db eprintln!("The proxy has four modes: cache, store, forward, and passthrough."); eprintln!("Read the user guide to understand which is right for each situation."); let choices = vec!["cache", "store", "forward", "passthrough"]; let default = match self.proxy.mode { ProxyMode::Cache => 0, ProxyMode::Store => 1, ProxyMode::Forward => 2, ProxyMode::Passthrough => 3, }; let choice = Select::new() .items(&choices) .default(default) .with_prompt("Proxy mode") .interact()?; let choice: ProxyMode = choices[choice].try_into().unwrap(); self.proxy.mode = choice; if let ProxyMode::Cache | ProxyMode::Store | ProxyMode::Forward = self.proxy.mode { eprintln!("The proxy uses a SQLite database to keep track of requests and responses."); eprintln!( "The proxy will create this database if one does not already exist." ); let choice: String = Input::new() .allow_empty(false) .with_prompt("Name of (or path to) your database file") .with_initial_text(&self.cache.db_path) .interact_text()?; self.cache.db_path = choice; } eprintln!( "The host and port of the proxy must match the one in your license package." ); let choice: String = Input::new() .with_prompt("Host IP to listen on") .with_initial_text(&self.proxy.host) .interact_text()?; self.proxy.host = choice; let choice: String = Input::new() .with_prompt("Host port for http (non-ssl) mode") .with_initial_text(&self.proxy.port) .interact_text()?; self.proxy.port = choice; eprintln!("Your proxy server must contact one of two Adobe licensing servers."); eprintln!("Use the variable IP server unless your firewall doesn't permit it."); let choices = vec![ "Variable IP server (lcs-cops.adobe.io)", "Fixed IP server (lcs-cops-proxy.adobe.com)", ]; let default = if self.proxy.remote_host == "https://lcs-cops-proxy.adobe.com" { 1 } else { 0 }; let choice = Select::new() .items(&choices) .default(default) .with_prompt("Adobe licensing server") .interact()?; self.proxy.remote_host = if choice == 0usize { String::from("https://lcs-cops.adobe.io") } else { String::from("https://lcs-cops-proxy.adobe.com") }; eprintln!("MacOS applications can only connect to the proxy via SSL."); eprintln!("Windows applications can use SSL, but they don't require it."); let choice = Confirm::new() .default(self.proxy.ssl) .show_default(true) .wait_for_newline(false) .with_prompt("Use SSL?") .interact()?; self.proxy.ssl = choice; // update ssl settings if self.proxy.ssl { let choice: String = Input::new() .with_prompt("Host port for https mode") .with_initial_text(&self.proxy.ssl_port) .interact_text()?; self.proxy.ssl_port = choice; eprintln!( "The proxy requires a certificate store in PKCS format to use SSL." ); eprintln!( "Read the user guide to learn how to obtain and prepare this file." ); let mut need_cert = true; let mut choice = self.ssl.cert_path.clone(); while need_cert { choice = Input::new() .with_prompt("Name of (or path to) your cert file") .with_initial_text(choice) .interact_text()?; if std::fs::metadata(&choice).is_ok() { self.ssl.cert_path = choice.clone(); need_cert = false; } else { eprintln!("There is no certificate at that path, try again."); } } eprintln!("Usually, for security, PKCS files are encrypted with a password."); eprintln!( "Your proxy will require that password in order to function properly." ); eprintln!( "You have the choice of storing your password in your config file or" ); eprintln!( "in the value of an environment variable (FRL_PROXY_SSL.CERT_PASSWORD)." ); let prompt = if self.ssl.cert_password.is_empty() { "Do you want to store a password in your configuration file?" } else { "Do you want to update the password in your configuration file?" }; let choice = Confirm::new() .default(false) .wait_for_newline(false) .with_prompt(prompt) .interact()?; if choice { let choice = Password::new() .with_prompt("Enter password") .with_confirmation("Confirm password", "Passwords don't match") .allow_empty_password(true) .interact()?; self.ssl.cert_password = choice; } } // update log settings let prompt = if let LogLevel::Off = self.logging.level { "Do you want your proxy server to log information about its operation?" } else { "Do you want to customize your proxy server's logging configuration?" }; let choice = Confirm::new() .default(false) .wait_for_newline(false) .with_prompt(prompt) .interact()?; if choice { eprintln!("The proxy can log to the console (standard output) or to a file on disk."); let choices = vec!["console", "disk file"]; let choice = Select::new() .items(&choices) .default(1) .with_prompt("Log destination") .interact()?; self.logging.destination = if choice == 0 { LogDestination::Console } else { LogDestination::File }; if choice == 1 { let choice: String = Input::new() .allow_empty(false) .with_prompt("Name of (or path to) your log file") .with_initial_text(&self.logging.file_path) .interact_text()?; self.logging.file_path = choice; } let mut choice = !matches!(self.logging.level, LogLevel::Info); if !choice { eprintln!("The proxy will log errors, warnings and summary information."); choice = Confirm::new() .default(false) .wait_for_newline(false) .with_prompt("Do you want to adjust the level of logged information?") .interact()?; } if choice { eprintln!("Read the user guide to find out more about logging levels."); let choices = vec!["no logging", "error", "warn", "info", "debug", "trace"]; let default = match self.logging.level { LogLevel::Off => 0, LogLevel::Error => 1, LogLevel::Warn => 2, LogLevel::Info => 3, LogLevel::Debug => 4, LogLevel::Trace => 5, }; let choice = Select::new() .items(&choices) .default(default) .with_prompt("Log level") .interact()?; let choice: LogLevel = choices[choice].try_into().unwrap(); self.logging.level = choice; } } else { self.logging.level = LogLevel::Off; self.logging.destination = LogDestination::Console; } // save the configuration let toml = toml::to_string(self) .wrap_err(format!("Cannot serialize configuration: {:?}", self))?; let mut file = File::create(path) .wrap_err(format!("Cannot create config file: {}", path))?; file.write_all(toml.as_bytes()) .wrap_err(format!("Cannot write config file: {}", path))?; eprintln!("Wrote config file '{}'", path); Ok(()) } pub fn validate(&mut self) -> Result<()> { if self.proxy.ssl { let path = &self.ssl.cert_path; if path.is_empty() { return Err(eyre!("Certificate path can't be empty when SSL is enabled")); } std::fs::metadata(path) .wrap_err(format!("Invalid certificate path: {}", path))?; } if self.proxy.host.contains(':') { return Err(eyre!("Host must not contain a port (use the 'port' and 'ssl_port' config options)")); } if let ProxyMode::Cache | ProxyMode::Store | ProxyMode::Forward = self.proxy.mode { if self.cache.db_path.is_empty() { return Err(eyre!("Database path can't be empty when cache is enabled")); } } if let LogDestination::File = self.logging.destination { if self.logging.file_path.is_empty() { return Err(eyre!("File path must be specified when logging to a file")); } } Ok(()) } } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum ProxyMode { Cache, Store, Forward, Passthrough, } impl Default for ProxyMode { fn default() -> Self { ProxyMode::Cache } } impl TryFrom<&str> for ProxyMode { type Error = Report; fn try_from(s: &str) -> Result<Self> { let sl = s.to_ascii_lowercase(); if "cache".starts_with(&sl) { Ok(ProxyMode::Cache) } else if "store".starts_with(&sl) { Ok(ProxyMode::Store) } else if "forward".starts_with(&sl) { Ok(ProxyMode::Forward) } else if "passthrough".starts_with(&sl) { Ok(ProxyMode::Passthrough) } else { Err(eyre!("proxy mode '{}' must be a prefix of cache, store, forward or passthrough", s)) } } } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum LogDestination { #[serde(alias = "c")] Console, #[serde(alias = "f")] File, } impl Default for LogDestination { fn default() -> Self { LogDestination::Console } } impl TryFrom<&str> for LogDestination { type Error = Report; fn try_from(s: &str) -> Result<Self> { let sl = s.to_ascii_lowercase(); if "console".starts_with(&sl) { Ok(LogDestination::Console) } else if "file".starts_with(&sl) { Ok(LogDestination::File) } else { Err(eyre!("log destination '{}' must be a prefix of console or file", s)) } } } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum LogLevel { Off, Error, Warn, Info, Debug, Trace, } impl Default for LogLevel { fn default() -> Self { LogLevel::Info } } impl TryFrom<&str> for LogLevel { type Error = Report; fn try_from(s: &str) -> Result<Self> { let sl = s.to_ascii_lowercase(); if "off".starts_with(&sl) { Ok(LogLevel::Off) } else if "error".starts_with(&sl) { Ok(LogLevel::Error) } else if "warn".starts_with(&sl) { Ok(LogLevel::Warn) } else if "info".starts_with(&sl) { Ok(LogLevel::Info) } else if "debug".starts_with(&sl) { Ok(LogLevel::Debug) } else if "trace".starts_with(&sl) { Ok(LogLevel::Trace) } else { Err(eyre!("log level '{}' must be a prefix of off, error, warn, info, debug, or trace", s)) } } } <file_sep>/* Copyright 2020 Adobe All Rights Reserved. NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms of the Adobe license agreement accompanying it. */ use eyre::{Result, WrapErr}; use hyper::service::{make_service_fn, service_fn}; use hyper::Server; use log::info; use std::net::SocketAddr; use std::sync::Arc; use super::{ctrl_c_handler, serve_req}; use crate::cache::Cache; use crate::settings::Settings; pub async fn run_server(conf: &Settings, cache: Arc<Cache>) -> Result<()> { let full_host = format!("{}:{}", conf.proxy.host, conf.proxy.port); let addr: SocketAddr = full_host.parse()?; info!("Listening on http://{}", addr); let make_svc = make_service_fn(move |_| { let conf = conf.clone(); let cache = Arc::clone(&cache); async move { Ok::<_, hyper::Error>(service_fn(move |_req| { let conf = conf.clone(); let cache = Arc::clone(&cache); async move { serve_req(_req, conf, cache).await } })) } }); let (tx, rx) = tokio::sync::oneshot::channel::<()>(); ctrl_c_handler(move || tx.send(()).unwrap_or(())); let server = Server::bind(&addr).serve(make_svc); let graceful = server.with_graceful_shutdown(async { rx.await.ok(); }); // Run the server, keep going until an error occurs. info!("Starting to serve on http://{}", full_host); graceful.await.wrap_err("Unexpected server shutdown")?; Ok(()) } <file_sep>/* Copyright 2020 Adobe All Rights Reserved. NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms of the Adobe license agreement accompanying it. */ use structopt::StructOpt; #[derive(Debug, StructOpt)] #[structopt(about = "A caching, store/forward, reverse proxy for Adobe FRL licensing")] pub struct FrlProxy { #[structopt(short, long, default_value = "proxy-conf.toml")] /// Path to config file. pub config_file: String, #[structopt(short, parse(from_occurrences))] /// Specify once to force log level to debug. /// Specify twice to force log level to trace. pub debug: u8, #[structopt(short, long)] /// Override configured log destination: 'console' or 'file'. /// You can use just the first letter, so '-l c' and '-l f' work. pub log_to: Option<String>, #[structopt(subcommand)] pub cmd: Command, } #[derive(Debug, StructOpt)] /// FRL Proxy pub enum Command { /// Start the proxy server Start { #[structopt(short, long)] /// Mode to run the proxy in, one of passthrough, cache, store, or forward. /// You can use any prefix of these names (minimally p, c, s, or f) mode: Option<String>, #[structopt(long, parse(try_from_str))] /// Enable SSL? (true or false) ssl: Option<bool>, }, /// Interactively create the config file Configure, /// Clear the cache (requires confirmation) Clear { #[structopt(short, long)] /// Bypass confirmation prompt yes: bool, }, /// Import stored responses from a forwarder Import { import_path: String }, /// Export stored requests for a forwarder Export { export_path: String }, } <file_sep>/* Copyright 2020 Adobe All Rights Reserved. NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms of the Adobe license agreement accompanying it. */ pub mod plain; pub mod secure; use crate::cache::Cache; use crate::cops::{agent, BadRequest, Request as CRequest, Response as CResponse}; use crate::settings::ProxyMode; use hyper::{Body, Client, Request as HRequest, Response as HResponse, Uri}; use hyper_tls::HttpsConnector; use log::{debug, error, info}; use std::sync::{Arc, Mutex}; use crate::settings::Settings; fn ctrl_c_handler<F>(f: F) where F: FnOnce() + Send + 'static, { let call_once = Mutex::new(Some(f)); ctrlc::set_handler(move || { if let Some(f) = call_once.lock().unwrap().take() { info!("Starting graceful shutdown"); f(); } else { info!("Already sent signal to start graceful shutdown"); } }) .unwrap(); } async fn serve_req( req: HRequest<Body>, conf: Settings, cache: Arc<Cache>, ) -> Result<HResponse<Body>, hyper::Error> { let (parts, body) = req.into_parts(); let body = hyper::body::to_bytes(body).await?; info!("Received request for {:?}", parts.uri); debug!("Received request method: {:?}", parts.method); debug!("Received request headers: {:?}", parts.headers); debug!("Received request body: {}", std::str::from_utf8(&body).unwrap()); // Analyze and handle the request match CRequest::from_network(&parts, &body) { Err(err) => Ok(bad_request_response(&err)), Ok(req) => { info!("Received request id: {}", &req.request_id); cache.store_request(&req).await; let net_resp = if let ProxyMode::Store = conf.proxy.mode { debug!("Store mode - not contacting COPS"); proxy_offline_response() } else { match call_cops(&conf, &req).await { Ok(resp) => resp, Err(err) => cops_failure_response(err), } }; let (parts, body) = net_resp.into_parts(); let body = hyper::body::to_bytes(body).await?; if parts.status.is_success() { // the COPS call succeeded, info!("Received success response ({:?}) from COPS", parts.status); debug!("Received success response headers {:?}", parts.headers); debug!( "Received success response body {}", std::str::from_utf8(&body).unwrap() ); // cache the response let resp = CResponse::from_network(&req, &body); cache.store_response(&req, &resp).await; // return the response Ok(HResponse::from_parts(parts, Body::from(body))) } else if let Some(resp) = cache.fetch_response(&req).await { // COPS call failed, but we have a cached response to use info!("Using previously cached response to request"); let net_resp = resp.to_network(); Ok(net_resp) } else { // COPS call failed, and no cache, so tell client info!("Returning failure response ({:?}) from COPS", parts.status); debug!("Received failure response headers {:?}", parts.headers); debug!( "Received failure response body {}", std::str::from_utf8(&body).unwrap() ); Ok(HResponse::from_parts(parts, Body::from(body))) } } } } pub async fn forward_stored_requests(conf: &Settings, cache: Arc<Cache>) { let requests = cache.fetch_forwarding_requests().await; if requests.is_empty() { eprintln!("No requests to forward."); return; } eprintln!("Starting to forward {} request(s)...", requests.len()); let (mut successes, mut failures) = (0u64, 0u64); for req in requests.iter() { info!("Forwarding stored {} request {}", req.kind, &req.request_id); match call_cops(&conf, &req).await { Ok(net_resp) => { let (parts, body) = net_resp.into_parts(); let body = hyper::body::to_bytes(body).await.unwrap(); if parts.status.is_success() { // the COPS call succeeded, info!("Received success response ({:?}) from COPS", parts.status); debug!("Received success response headers {:?}", parts.headers); debug!( "Received success response body {}", std::str::from_utf8(&body).unwrap() ); // cache the response let resp = CResponse::from_network(&req, &body); cache.store_response(&req, &resp).await; successes += 1; } else { // the COPS call failed info!("Received failure response ({:?}) from COPS", parts.status); debug!("Received failure response headers {:?}", parts.headers); debug!( "Received failure response body {}", std::str::from_utf8(&body).unwrap() ); failures += 1; } } Err(err) => { error!("No response received from COPS: {:?}", err) } }; } eprintln!( "Received {} success response(s) and {} failure response(s).", successes, failures ); } async fn call_cops( conf: &Settings, req: &CRequest, ) -> Result<HResponse<Body>, hyper::Error> { let cops_uri = conf.proxy.remote_host.parse::<Uri>().unwrap_or_else(|_| { panic!("failed to parse uri: {}", conf.proxy.remote_host) }); // if no scheme is specified for remote_host, assume http let cops_scheme = match cops_uri.scheme_str() { Some("https") => "https", _ => "http", }; let cops_host = match cops_uri.port() { Some(port) => { let h = cops_uri.host().unwrap(); format!("{}:{}", h, port.as_str()) } None => String::from(cops_uri.host().unwrap()), }; info!( "Forwarding request {} to COPS at {}://{}", req.request_id, cops_scheme, cops_host ); let net_req = req.to_network(&cops_scheme, &cops_host); if cops_scheme == "https" { let https = HttpsConnector::new(); let client = Client::builder().build::<_, hyper::Body>(https); client.request(net_req).await } else { Client::new().request(net_req).await } } fn bad_request_response(err: &BadRequest) -> HResponse<Body> { info!("Rejecting request with 400 response: {}", err.reason); let body = serde_json::json!({"statusCode": 400, "message": err.reason}); HResponse::builder() .status(400) .header("content-type", "application/json;charset=UTF-8") .header("server", agent()) .body(Body::from(body.to_string())) .unwrap() } fn cops_failure_response(err: hyper::Error) -> HResponse<Body> { let msg = format!("Failed to get a response from COPS: {:?}", err); error!("{}", msg); let body = serde_json::json!({"statusCode": 502, "message": msg}); HResponse::builder() .status(502) .header("content-type", "application/json;charset=UTF-8") .header("server", agent()) .body(Body::from(body.to_string())) .unwrap() } fn proxy_offline_response() -> HResponse<Body> { let msg = "Proxy is operating offline: request stored for later replay"; debug!("{}", msg); let body = serde_json::json!({"statusCode": 502, "message": msg}); HResponse::builder() .status(502) .header("content-type", "application/json;charset=UTF-8") .header("server", agent()) .body(Body::from(body.to_string())) .unwrap() } <file_sep>/* Copyright 2020 Adobe All Rights Reserved. NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms of the Adobe license agreement accompanying it. */ use crate::settings::{LogDestination, LogLevel, Settings}; use eyre::{Result, WrapErr}; use fern::{log_file, Dispatch}; use log::LevelFilter; use std::io; pub fn init(conf: &Settings) -> Result<()> { let mut base_config = Dispatch::new().format(|out, message, record| { out.finish(format_args!( "{}[{}][{}] {}", chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"), record.target(), record.level(), message )) }); let level = log_level(&conf.logging.level); match conf.logging.destination { LogDestination::Console => { base_config = base_config.chain(Dispatch::new().level(level).chain(io::stdout())) } LogDestination::File => { base_config = base_config.chain( Dispatch::new().level(level).chain(log_file(&conf.logging.file_path)?), ) } } base_config.apply().wrap_err("Cannot initialize logging subsystem")?; Ok(()) } fn log_level(level: &LogLevel) -> LevelFilter { match level { LogLevel::Off => LevelFilter::Off, LogLevel::Error => LevelFilter::Error, LogLevel::Warn => LevelFilter::Warn, LogLevel::Info => LevelFilter::Info, LogLevel::Debug => LevelFilter::Debug, LogLevel::Trace => LevelFilter::Trace, } } <file_sep>[proxy] mode = "cache" host = "0.0.0.0" port = "8080" ssl_port = "8443" remote_host = "https://lcs-cops.adobe.io" ssl = true [ssl] cert_path = "proxy-cert.pfx" cert_password = "" [logging] level = "info" destination = "file" file_path = "proxy-log.log" [cache] db_path = "proxy-cache.sqlite" <file_sep># allow unstable features is only allowed in nightly builds #unstable_features = true # set the options that control other options max_width = 90 use_small_heuristics = "Max" # width_heuristics = "Max" # alphabetic list of non-default options # (unstable ones are commented out) #combine_control_expr = false #empty_item_single_line = false fn_args_layout = "Compressed" #format_code_in_doc_comments = true #force_multiline_blocks = true #format_strings = true #match_block_trailing_comma = true #merge_imports = true #normalize_comments = true #overflow_delimited_expr = true #trailing_comma = "Vertical" use_field_init_shorthand = true use_try_shorthand = true #wrap_comments = true <file_sep>/* Copyright 2020 Adobe All Rights Reserved. NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms of the Adobe license agreement accompanying it. */ use structopt::StructOpt; mod cache; mod cli; mod cops; mod logging; mod proxy; mod settings; use crate::cli::Command; use crate::settings::{LogDestination, ProxyMode}; use cache::Cache; use cli::FrlProxy; use eyre::{Result, WrapErr}; use log::debug; use proxy::{plain, secure}; use settings::Settings; use std::convert::TryInto; use std::sync::Arc; #[tokio::main] async fn main() -> Result<()> { openssl_probe::init_ssl_cert_env_vars(); let args: FrlProxy = FrlProxy::from_args(); // make sure we have a config file. if not, make one if let Some(mut conf) = Settings::load_config(&args)? { match args.cmd { cli::Command::Start { mode, ssl } => { if let Some(mode) = mode { conf.proxy.mode = mode.as_str().try_into()?; }; if let Some(ssl) = ssl { conf.proxy.ssl = ssl; } conf.validate()?; logging::init(&conf)?; debug!("conf: {:?}", conf); if let ProxyMode::Forward = conf.proxy.mode { let cache = Cache::from(&conf, false).await?; proxy::forward_stored_requests(&conf, Arc::clone(&cache)).await; cache.close().await; } else { let cache = Cache::from(&conf, true).await?; if conf.proxy.ssl { secure::run_server(&conf, Arc::clone(&cache)).await?; } else { plain::run_server(&conf, Arc::clone(&cache)).await?; } cache.close().await; } } cli::Command::Configure => { conf.validate()?; // do not log configuration changes, because // logging might interfere with the interactions // and there really isn't anything to log. conf.update_config_file(&args.config_file)?; } Command::Clear { yes } => { conf.proxy.mode = ProxyMode::Cache; // log to file, because this command is interactive conf.logging.destination = LogDestination::File; conf.validate()?; logging::init(&conf)?; let cache = Cache::from(&conf, true).await?; cache.clear(yes).await.wrap_err("Failed to clear cache")?; } Command::Import { import_path } => { conf.proxy.mode = ProxyMode::Cache; // log to file, because this command is interactive conf.logging.destination = LogDestination::File; conf.validate()?; logging::init(&conf)?; let cache = Cache::from(&conf, true).await?; cache .import(&import_path) .await .wrap_err(format!("Failed to import from {}", &import_path))?; } Command::Export { export_path } => { conf.proxy.mode = ProxyMode::Cache; // log to file, because this command is interactive conf.logging.destination = LogDestination::File; conf.validate()?; logging::init(&conf)?; let cache = Cache::from(&conf, false).await?; cache .export(&export_path) .await .wrap_err(format!("Failed to export to {}", &export_path))?; } } } else { let mut conf = Settings::load_config(&args)?.unwrap(); conf.update_config_file(&args.config_file) .wrap_err("Failed to update configuration file")?; } Ok(()) } <file_sep>/* Copyright 2020 Adobe All Rights Reserved. NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms of the Adobe license agreement accompanying it. */ use super::{ctrl_c_handler, serve_req}; use crate::cache::Cache; use crate::settings::Settings; use async_stream::stream; use core::task::{Context, Poll}; use eyre::{Result, WrapErr}; use futures_util::stream::{Stream, StreamExt}; use hyper::server::Server; use hyper::service::{make_service_fn, service_fn}; use log::{error, info}; use std::fs::File; use std::io::Read; use std::pin::Pin; use std::sync::Arc; use tokio::io; use tokio::net::{TcpListener, TcpStream}; use tokio_native_tls::{native_tls, TlsAcceptor, TlsStream}; pub async fn run_server(conf: &Settings, cache: Arc<Cache>) -> Result<()> { let acceptor = { let path = &conf.ssl.cert_path; let password = &conf.ssl.cert_password; let mut file = File::open(path) .wrap_err(format!("Can't open SSL certificate file: {}", path))?; let mut identity = vec![]; file.read_to_end(&mut identity) .wrap_err(format!("Can't read SSL cert data from file: {}", path))?; let identity = native_tls::Identity::from_pkcs12(&identity, password) .wrap_err("Can't decrypt SSL cert data - incorrect password?")?; let sync_acceptor = native_tls::TlsAcceptor::new(identity) .wrap_err("Can't create TLS socket listener - is the port free?")?; let async_acceptor: TlsAcceptor = sync_acceptor.into(); async_acceptor }; let full_host = format!("{}:{}", conf.proxy.host, conf.proxy.ssl_port); let tcp = TcpListener::bind(&full_host).await?; let incoming_tls_stream = incoming(tcp, acceptor).boxed(); let hyper_acceptor = HyperAcceptor { acceptor: incoming_tls_stream }; let service = make_service_fn(move |_| { let conf = conf.clone(); let cache = Arc::clone(&cache); async move { Ok::<_, hyper::Error>(service_fn(move |_req| { let conf = conf.clone(); let cache = Arc::clone(&cache); async move { serve_req(_req, conf, cache).await } })) } }); let server = Server::builder(hyper_acceptor).serve(service); let (tx, rx) = tokio::sync::oneshot::channel::<()>(); ctrl_c_handler(move || tx.send(()).unwrap_or(())); let graceful = server.with_graceful_shutdown(async { rx.await.ok(); }); // Run the server, keep going until an error occurs. info!("Starting to serve on https://{}", full_host); graceful.await.wrap_err("Unexpected server shutdown")?; Ok(()) } fn incoming( listener: TcpListener, acceptor: TlsAcceptor, ) -> impl Stream<Item = TlsStream<TcpStream>> { stream! { loop { // just swallow errors and wait again if necessary match listener.accept().await { Ok((stream, _)) => { match acceptor.accept(stream).await { Ok(x) => { yield x; } Err(e) => { error!("SSL Failure with client: {}", e); } } } Err(e) => { error!("Connection failure with client: {}", e); } } }; } } struct HyperAcceptor<'a> { acceptor: Pin<Box<dyn Stream<Item = TlsStream<TcpStream>> + 'a>>, } impl hyper::server::accept::Accept for HyperAcceptor<'_> { type Conn = TlsStream<TcpStream>; type Error = io::Error; fn poll_accept( mut self: Pin<&mut Self>, cx: &mut Context, ) -> Poll<Option<Result<Self::Conn, Self::Error>>> { let result = Pin::new(&mut self.acceptor).poll_next(cx); match result { Poll::Ready(Some(stream)) => Poll::Ready(Some(Ok(stream))), Poll::Ready(None) => Poll::Ready(None), Poll::Pending => Poll::Pending, } } }
afe0168225b8c4aed610c90567e58d141cf42143
[ "Markdown", "TOML", "JavaScript", "Rust" ]
16
Markdown
keshagriffin-adobe/frl-online-proxy
9d03e0300663ddbf66506fa28af9a406bb9f72c3
573adf1355b8c3ac22439322f1791d7ad52e0631
refs/heads/master
<repo_name>akshaykatre/databuild<file_sep>/build_tables/home_ownership.sql /** Create a separate table with home ownership data. This table contains the ID as the primary key from both tables, the new and old customer. The boolean fields are also created in this table. **/ drop table if exists inter.home_ownership create table inter.home_ownership ( id int not null, home_ownership char(20), IS_MORTGAGE bit, IS_RENT bit, IS_OWN bit, IS_ANY bit, IS_OTHER bit, constraint PK_hownership_ID primary key (id) ); with CTE as ( select id, home_ownership ,case when home_ownership = 'MORTGAGE' then 1 ELSE 0 END AS IS_MORTGAGE, CASE when home_ownership = 'RENT' then 1 ELSE 0 END AS IS_RENT, CASE when home_ownership = 'OWN' then 1 ELSE 0 END AS IS_OWN, CASE when home_ownership = 'ANY' then 1 else 0 end as IS_ANY, CASE when home_ownership = 'OTHER' THEN 1 ELSE 0 END AS IS_OTHER from [raw].api_oldcustomer union -- When joining with the new table in the future, let's keep in mind the -- ID should be joined with a negative value select newc.id * -1 , hown.name as home_ownership , case when hown.name = 'MORTGAGE' then 1 ELSE 0 END AS IS_MORTGAGE, CASE when hown.name = 'RENT' then 1 ELSE 0 END AS IS_RENT, CASE when hown.name = 'OWN' then 1 ELSE 0 END AS IS_OWN, CASE when hown.name = 'ANY' then 1 else 0 end as IS_ANY, CASE when hown.name = 'OTHER' THEN 1 ELSE 0 END AS IS_OTHER from [raw].api_newcustomer newc left join [raw].api_homeownership hown on newc.home_ownership_id = hown.id ) insert into inter.home_ownership select * from CTE <file_sep>/data_quality/data_quality.py import pandas import json import pymssql from pysqldq import dqchecks cfile = open("dbconfig.json") login = json.load(cfile) conn = pymssql.connect(server=login['server'], database="customer", user=login['username'], password=login['password']) columns = pandas.read_sql_query('select column_name, table_name, table_schema from information_schema.columns', conn) allchecks = [] for index, rows in columns.iterrows(): print("running check for.. : ", rows['column_name']) connectionmap = {'schema': rows['table_schema'], 'table': rows['table_name']} comp_query = dqchecks.getCompleteness(connectionMap=connectionmap, attribute=rows['column_name']) check = pandas.read_sql_query(comp_query, conn) check['schema'] = rows['table_schema'] check['table'] = rows['table_name'] check['attribute'] = rows['column_name'] allchecks.append(check) df = pandas.concat(allchecks) df.to_csv("test_data.csv", index=False)<file_sep>/requirements.txt adcpipeline==0.2.0 backcall==0.2.0 Brotli==1.0.9 click==8.0.1 colorama==0.4.4 dash==1.20.0 dash-core-components==1.16.0 dash-html-components==1.1.3 dash-renderer==1.9.1 dash-table==4.11.3 decorator==5.0.9 Flask==2.0.1 Flask-Compress==1.9.0 future==0.18.2 ipython==7.24.1 ipython-genutils==0.2.0 itsdangerous==2.0.1 jedi==0.18.0 Jinja2==3.0.1 MarkupSafe==2.0.1 matplotlib-inline==0.1.2 numpy==1.20.3 pandas==1.2.4 parso==0.8.2 pexpect==4.8.0 pickleshare==0.7.5 plotly==4.14.3 prompt-toolkit==3.0.18 ptyprocess==0.7.0 Pygments==2.9.0 pymssql==2.2.1 pysqldq==0.0.2 python-dateutil==2.8.1 pytz==2021.1 PyYAML==5.4.1 retrying==1.3.3 six==1.16.0 style==1.1.0 traitlets==5.0.5 update==0.0.1 wcwidth==0.2.5 Werkzeug==2.0.1 <file_sep>/build_tables/loan_amnt.sql /** In the new customer table, the format of the column loan_amount is in varchar with a 'k' at the end to indicate thousand. We will just remove it, convert it to a thousand and construct a new loan_amount table. We will also add to this table, Term, which has a similar treatment, but to convert Y to months. **/ drop table if exists inter.loan_term_details create table inter.loan_term_details( id int not null, loan_amount int, term int, constraint PK_loanamnt_ID primary key (id) ); with CTE as ( SELECT id * -1 as id ,convert(float, left(loan_amnt, len(loan_amnt)-1))* 1000 as loan_amount ,convert(float, left(term, len(term)-1))*12 as term from [customer].[raw].api_newcustomer union SELECT id, loan_amnt as loan_amount, term from [customer].[raw].[api_oldcustomer] ) insert into inter.loan_term_details select id, convert(int, loan_amount), convert(int, term) from cte <file_sep>/build_tables/delivery_table.sql /** This script is for the final delivery table **/ drop table if exists freeze.deliver_tables create table freeze.deliver_tables( id int not null, loan_status bit, loan_amnt int, term int, int_rate float, installment float, sub_grade char(3), emp_length int, home_ownership char(20), IS_MORTGAGE bit, IS_RENT bit, IS_OWN bit, IS_ANY bit, IS_OTHER bit, annual_inc int, verification_status char(20), is_verified bit, is_not_verified bit, is_source_verified bit, issue_d datetime, issue_month varchar(8), purpose char(30), addr_state char(2), dti float, fico_range_low int, fico_range_high int, open_acc int, pub_rec int, revol_bal int, revol_util float, mort_acc int, pub_rec_backruptcies int, age int, pay_status int constraint PK_delivery_ID primary key (id) ); insert into freeze.deliver_tables select customers.id ,customers.loan_status ,ltdeets.loan_amount as loan_amnt ,ltdeets.term ,customers.int_rate ,customers.installment ,subgrade.subgrade as sub_grade ,customers.emp_length ,homeown.home_ownership ,homeown.IS_MORTGAGE ,homeown.IS_RENT ,homeown.IS_OWN ,homeown.IS_ANY ,homeown.IS_OTHER ,anninc.annual_inc ,vstat.verification_status ,vstat.is_verified ,vstat.is_not_verified ,vstat.is_source_verified ,issdates.issue_datetime as issue_d ,issdates.issue_month ,purp.purpose ,stat.addr_state ,customers.dti ,customers.fico_range_low ,customers.fico_range_high ,customers.open_acc ,customers.pub_rec ,customers.revol_bal ,customers.revol_util ,customers.mort_acc ,customers.pub_rec_backruptcies ,customers.age ,customers.pay_status from inter.newoldcustomers customers left join inter.loan_term_details ltdeets on ltdeets.id = customers.id left join inter.subgrade subgrade on customers.id = subgrade.id left join inter.home_ownership homeown on customers.id = homeown.id left join inter.verification_status vstat on customers.id = vstat.id left join inter.issue_dates issdates on customers.id = issdates.id left join inter.state stat on customers.id = stat.id left join inter.purpose purp on purp.id = customers.id left join inter.annual_inc anninc on anninc.id = customers.id<file_sep>/build_tables/subgrade.sql /** This need a simple consolidation into one table based on the subgroup_ID from new customer **/ drop table if exists inter.subgrade drop index if exists PK_subgrade_ID on inter.subgrade; create table inter.subgrade( id int not null, subgrade varchar(30), subgrade_id int, constraint PK_subgrade_ID primary key (id) ) insert into inter.subgrade select * from ( select oldc.id, sub_grade, sub.id as subgrade_id from [customer].[raw].[api_oldcustomer] oldc left join [customer].[raw].[api_subgrade] sub on oldc.sub_grade = sub.name union select ncust.id * -1 as id, sub.name as sub_grade, sub.id from [customer].[raw].[api_newcustomer] ncust left join [customer].[raw].[api_subgrade] sub on ncust.sub_grade_id = sub.id ) A <file_sep>/README.md # Data delivery The following document is based on the delivery of data as requested in the following document: [Assignment Data Engineering](https://github.com/akshaykatre/databuild/blob/c4fdabc97f122c4243d4bb9fbed586790449a172/Assignment%20data%20engineering%20description%20pdf%20format.pdf) ## Plan of action During the data delivery process, the following steps were followed: 1. Converted SQLite database into an SQL Server database 2. Performed an initial analysis into the data 3. Build the data tables and uploaded the scripts on GIT 4. Build a data quality check to check for completeness of the data 5. Build a dashboard for the data quality check and deploy it on the web The next few paragraphs documents in details the above five steps. ### 1. Conversion of database from SQLite to SQL Server The motivation to build the database on MS SQL Server is to be able to test and reuse existing python libraries for data quality and data lineage purposes. (See below for more details). The following are the steps followed to convert the tables from SQLite to SQL Server: To perform a dump of the data from SQLite to SQL Server, is done by literally creating the SQL scripts required and then running the SQL scripts on the database. Open the sqlite database with: ``` sqlite3 <nameofdb>.sqlite3``` ``` .output alloutput.sql .dump ``` You may have to perform some small corrections to the SQL script, but essentially the script is then all you need. With ```sqlcmd``` you can now create your tables/ databases as described in the script ``` sqlcmd -S localhost -i alloutput.sql ``` The scripts used in converting these tables can be found: [sqlserver_tables](https://github.com/akshaykatre/databuild/tree/master/sqlserver_tables) --- ### 2. Initial analysis on the data Based on the [Assignment Data Engineering](https://github.com/akshaykatre/databuild/blob/c4fdabc97f122c4243d4bb9fbed586790449a172/Assignment%20data%20engineering%20description%20pdf%20format.pdf) the final dataset is a combination of user data from two underlying tables. An initial analysis is performed on the attributes from the source tables *api_newcustomer* and *api_oldcustomer* tables. The following table summarises the differences and changes required to align the data from the two sources. --- Table below: | column | delivery data type | Required fixes | |----------------------|--------------------|-------------------------------------------------------------------------------------------------------------------------------| | loan_status | boolean | Convert the column to bit | | loan_amnt | int | - convert the x.0k into thousands | | | | - change the format to integer to match the required output | | term | int | - convert the x.0Y into months | | | | - change the format to integer to match the required output | | int_rate | double? | This is a consistent field across the two sources. | | installment | double? | This is a consistent field across the two sources. | | sub_grade | char | - In the newcustomer table, there is an ID to the sub_grade; | | | | - Delivery requires we give the grade itself. So need to convert this ID into the actual value | | emp_length | int | - Comes from two differently named attributes in the two tables | | | | - Align into a single attribute with data type integer | | | | - Perform DQ checks on source, observe some missing values | | home_ownership | char | Available from two different source fields in the two tables | | is_mortgage | boolean? | missing | | is_rent | boolean? | missing | | is_own | boolean? | missing | | is_any | boolean? | missing | | is_other | boolean? | missing | | annual_inc | int | - How is the income from oldcustomer a range and not a number? | | | | - What should be the choice? | | | | - Interestingly, it has only 12 distinct values for these ranges! | | | | - Align data type to integer | | verification_status | char | - Deliver this as a field with a character data type | | | | - therefore convert the newcustomer attribute from integer to character | | is_verified | boolean? | missing | | is_not_verified | boolean? | missing | | is_source_verified | booleans? | missing | | issue_d | date | - Called "issued" in newcustomer table | | | | - Align formatting to date format | | | | - Request says it wants the month, so what is the format in which this data is expected to be delivered? YYYYMM | | purpose | char | - The IDs have a small mis-match, is that an issue? how should it be resolved? | | | - The tables need alignment since from the newcustomer it is again the ID that is mentioned and char itself | | addr_state | char | - The IDs have a small mis-match, is that an issue? how should it be resolved? | | | | - The tables need alignment since from the newcustomer it is again the ID that is mentioned and char itself | | dti | | This is a consistent field across the two sources. | | fico_range_low | | This is a consistent field across the two sources. | | fico_range_high | | This is a consistent field across the two sources. | | open_acc | | This is a consistent field across the two sources. | | pub_rec | | This is a consistent field across the two sources. | | revol_bal | | This is a consistent field across the two sources. | | revol_util | | This is a consistent field across the two sources. | | mort_acc | | This is a consistent field across the two sources. | | pub_rec_backruptcies | | This is a consistent field across the two sources. | | age | | This is a consistent field across the two sources. | | pay_status | | Old customer table has max value only till 8? is that expected? | --- --- ### 3. Building data tables and assumptions #### ID ID is not distinct between the customer tables, but these are indeed distinct customers. To keep the IDs different in the final table, the customers from the *api_newcustomer* table have been assigned a negative value. #### Loan Amount This attribute is delivered as an integer and has a base of 1000. The string 'k' has been converted to '000s to be in line with the data in the table *api_oldcustomer*. #### Term This attribute is delivered as an integer and has been delivered as number of months, consistent with the table *api_oldcustomer*. The above two changes can be found in: [loan_amnt.sql](https://github.com/akshaykatre/databuild/blob/0fb3b6351c5065871d1b3f6104b366758f5613d4/build_tables/loan_amnt.sql) #### Annual Inc The annual income is delivered as an integer. The data from the *api_oldcustomer* table was provided as a *list* stating the range of the annual income instead of a number. In these cases we have used the average value between the two. This can be found in the file: [annual_inc.py](https://github.com/akshaykatre/databuild/blob/0fb3b6351c5065871d1b3f6104b366758f5613d4/build_tables/annual_inc.py) #### Purpose The values of keys between the *api_newcustomer* and *api_oldcustomer* were misaligned by singular and plural words, the choice was made to convert all values to singular. #### Addr_state The key of this attribute was offset by 51 in the *api_addr_state* table causing a misalignment between the two source tables when combined. Therefore, the key value was subtracted by 51 when building the final set. The above two changes can be found in the file: [keychanges.sql](https://github.com/akshaykatre/databuild/blob/0fb3b6351c5065871d1b3f6104b366758f5613d4/build_tables/keychanges.sql) ### 4. Build a data quality check An existing library [pysqldq](https://pypi.org/project/pysqldq/) was used to run an out of the box completeness check that detects NULLs, empty strings and fields filled "NA". The output of the DQ can be visualised as a dataframe that can be converted into your preferred output format choice. ### 5. DQ Dashboard The dashboard for the data quality check of completeness is available via a heroku app: [https://dq-dashboard-app.herokuapp.com/](https://dq-dashboard-app.herokuapp.com/) A threshold of 1% is set such that any column missing more than 1% of the data is highlighted as red. The selection of the threshold was arbitrary. ## Conclusions and further developments The final delivery table is available in **freeze.deliver_table**, the script for the delivery table is available here: [delivery_table.sql](https://github.com/akshaykatre/databuild/blob/b1a3b9a7d8b844b52bdaa8dcd34854609232cba7/build_tables/delivery_table.sql). The DQ dashboard shows that the completeness of data is acceptable based on the input RAW data that is available. In the future, these tests can be complemented by descriptive statistics tests, outlier tests etc. In addition, we can also extract the lineage of each individual attribute that is delivered in the final table. This requires further development, but essentailly we can deliver the images such as the following to trace the lineage of the attributes. ![](https://github.com/akshaykatre/databuild/blob/655c89cce2ef927820024e1ee26bda6b2882954d/fico_high.png)<file_sep>/build_tables/verification_status.sql /** Create a separate table with verification statuses. This table contains the ID as the primary key from both tables, the new and old customer. The boolean fields are also created in this table. **/ drop table if exists inter.verification_status create table inter.verification_status ( id int not null, verification_status char(20), is_verified bit, is_not_verified bit, is_source_verified bit, constraint PK_vstatus_ID primary key (id) ); with CTE as ( select id ,verification_status , case when verification_status = 'Source Verified' then 1 ELSE 0 END AS is_source_verified, CASE when verification_status = 'Verified' then 1 ELSE 0 END AS is_verified, CASE when verification_status = 'Not Verified' then 1 ELSE 0 END AS is_not_verified from [raw].api_oldcustomer union -- When joining with the new table in the future, let's keep in mind the -- ID should be joined with a negative value select newc.id * -1 , verf.name as verification_status , CASE when verf.name = 'Source Verified' then 1 ELSE 0 END AS is_source_verified, CASE when verf.name = 'Verified' then 1 ELSE 0 END AS is_verified, CASE when verf.name = 'Not Verified' then 1 ELSE 0 END AS is_not_verified from [raw].api_newcustomer newc left join [raw].api_verificationstatus verf on newc.verification_status_id = verf.id ) insert into inter.verification_status select * from CTE <file_sep>/build_tables/issue_date.sql /** The format of the issued column in the newcustomer table is all over the place. 1> select len(issued), max(issued) from [raw].api_newcustomer group by len(issued) 2> go ----------- -------------------------------- 9 12-Jan-18 7 2018-01 10 2018-01-12 19 2018-01-12 00:00:00 Therefore, this first needs to be made into a single format, and then combined with the data in the oldcustomer table. **/ drop table if exists inter.issue_dates create table inter.issue_dates( id int not null, issue_datetime datetime, issue_month varchar(8), constraint PK_issuedates_ID primary key (id) ); with CTE as ( select id, issue_d as issue_datetime from [customer].[raw].api_oldcustomer union select id * - 1 as id, case when len(issued) = 19 or len(issued) = 10 or len(issued) = 9 then convert(datetime, issued) when len(issued) = 7 then convert(datetime, issued+'-01') -- need this for standarisation end as issue_datetime from [customer].[raw].api_newcustomer ) insert into inter.issue_dates select * , LEFT(CONVERT(varchar, issue_datetime,112),6) as issue_month from CTE --where len(issued) = 19 or len(issued) = 10 or len(issued) = 7<file_sep>/build_tables/newoldcustomers.sql drop table if exists inter.newoldcustomers create table inter.newoldcustomers( id int not null, loan_status bit, int_rate float, installment float, emp_length int, dti float, fico_range_low int, fico_range_high int, open_acc int, pub_rec int, revol_bal int, revol_util float, mort_acc int, pub_rec_backruptcies int, age int, pay_status int constraint PK_newoldcust_ID primary key (id) ) insert into inter.newoldcustomers select * from ( SELECT id ,loan_status ,int_rate ,installment ,emp_length ,dti ,fico_range_low ,fico_range_high ,open_acc ,pub_rec ,revol_bal ,revol_util ,mort_acc ,pub_rec_bankruptcies ,age ,pay_status from [raw].api_oldcustomer union SELECT id * -1 as id ,loan_status ,int_rate ,installment ,employment_length as emp_length ,dti ,fico_range_low ,fico_range_high ,open_acc ,pub_rec ,revol_bal ,revol_util ,mort_acc ,pub_rec_bankruptcies ,age ,payment_status as pay_status from [raw].api_newcustomer ) A <file_sep>/data_quality/dq_dashboard.py import dash import dash_table import pandas as pd df = pd.read_csv('test_data.csv', index_col=False) df = df.fillna(0) app = dash.Dash(__name__) app.layout = dash_table.DataTable( id='table', columns=[{"name": i, "id": i} for i in df.columns], data=df.to_dict('records'), filter_action="native", sort_action="native", sort_mode="multi", page_size=25, style_data_conditional=[ { 'if':{ 'filter_query': '{Per_Missing_val} > 0.01', }, 'backgroundColor': '#FF4136', 'color': 'white' } ] ) external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] if __name__ == '__main__': app.run_server(debug=True) <file_sep>/build_tables/keychanges.sql /** The following tables need to have their keys changed in order to align with the other tables and have a consistent naming convention. purpose: convert plurals to singular state: remove 'US_' **/ drop table if exists inter.api_purpose create table inter.api_purpose( id int not null, [name] varchar(30) ) insert into inter.api_purpose select id , case when right([name], 1) = 'S' and [name] != 'SMALL_BUSINESS' then left([name], len([name])-1) else [name] end as [name] from [raw].api_purpose drop table if exists inter.api_state create table inter.api_state( id int not null, [name] varchar(30) ) insert into inter.api_state select id-51 -- It seems in the table there is an offset by 51 :) , right([name], 2) as [name] from [raw].api_state --- Now with these new keys, lets construct their intermediate tables drop table if exists inter.purpose drop index if exists PK_purpose_ID on inter.purpose; create table inter.purpose( id int not null, purpose varchar(30), purpose_id int, constraint PK_purpose_ID primary key (id) ) insert into inter.purpose select * from ( select oldc.id, purpose, purp.id as purpose_id from [customer].[raw].[api_oldcustomer] oldc left join [customer].[inter].[api_purpose] purp on oldc.purpose = purp.name union select ncust.id * -1 as id, purp.name as purpose, purp.id from [customer].[raw].[api_newcustomer] ncust left join [customer].[inter].[api_purpose] purp on ncust.purpose_id = purp.id ) A --- Same for state drop table if exists inter.state drop index if exists PK_state_ID on inter.state; create table inter.state( id int not null, addr_state varchar(30), addr_state_id int, constraint PK_state_ID primary key (id) ) insert into inter.state select * from ( select oldc.id, addr_state, stat.id as state_id from [customer].[raw].[api_oldcustomer] oldc left join [customer].[inter].[api_state] stat on oldc.addr_state = stat.name union select ncust.id * -1 as id, stat.name as addr_state, stat.id from [customer].[raw].[api_newcustomer] ncust left join [customer].[inter].[api_state] stat on ncust.addr_state_id = stat.id ) A <file_sep>/initial_analysis/outputlist.py import pandas import json import pymssql cfile = open("dbconfig.json") login = json.load(cfile) ## Create a map of all the expected output fields, with their datatypes map_output = { "loan_status" : "boolean", "loan_amnt" : "integer", "term": "integer", "int_rate": "double", "installment": "double", "sub_grade": "char", "emp_length": "integer", "home_owners_hip": "char", "is_mortgage": "boolean", "is_rent": "boolean", "is_own": "boolean", "is_any": "boolean", "is_other": "boolean", "annual_inc": "integer", "verification_status": "char", "is_verified": "boolean", "is_not_verified": "boolean", "is_source_verified": "boolean", "issue_d": "date", "purpose": "char", "addr_state": "char", "dti": "double", "fico_range_high": "integer", "open_acc": "integer", "pub_rec": "integer", "revol_bal": "integer", "revol_util": "double", "mort_acc": "integer", "pub_rec_bankruptcies": "integer", "age": "integer", "pay_status": "integer" } out_df = pandas.DataFrame(map_output.items(), columns = ['colname', 'datatype']) conn = pymssql.connect(server="localhost", database="customer", user=login['username'], password=login['password']) ## Loop through the fields for the expected output, to get an indication of which fields are ## existing with the same name in the two tables, and which ones do not for rows in out_df.iterrows(): colname, datatype = rows[1]['colname'], rows[1]['datatype'] print("For column: ", colname, " having datatype: ", datatype) df = pandas.read_sql_query("SELECT column_name, data_type, table_name from information_schema.columns where column_name='{0}'".format(colname), conn) if not df.empty: #continue print(df) else: # continue print("Dataframe is empty") print("*"*20) ''' The following fields are missing from the final deliverable: - is_mortgage - is_rent - is_own - is_any - is_other - is_verified - is_not_verified - is_source_verified: how is this different from is_verified? Is this the same as verification_status_id? For the others, let's look at a SQL notebook to verify if everything in order '''<file_sep>/build_tables/annual_inc.py import pymssql import pandas import json import statistics f = open("../dbconfig.json") config = json.load(f) conn = pymssql.connect(server="localhost", database="customer", user=config['username'], password=config['password']) ## Import the old customer dataset as a dataframe df_oldcust = pandas.read_sql_query("SELECT id, annual_inc from [raw].[api_oldcustomer]", conn) ## Fun one-liner in python to split, convert and average the income! df_oldcust['annual_inc'] = df_oldcust["annual_inc"].apply(lambda x: round(statistics.mean([float(y.replace("(","").replace("]", "")) for y in x.split(",")]))) ## Import the new customer dataset as a dataframe df_newcust = pandas.read_sql_query("SELECT id*-1 as id, annual_inc from [raw].[api_newcustomer]", conn) df_custs = pandas.concat([df_oldcust, df_newcust]) cursor = conn.cursor() cursor.execute(''' DROP TABLE IF EXISTS [inter].annual_inc CREATE TABLE [inter].annual_inc ( id int not null, annual_inc int, constraint PK_annualinc_ID primary key (id) ) ''') for index, rows in df_custs.iterrows(): cursor.execute('insert into [inter].annual_inc values %r' %(tuple(rows.values) ,)) conn.commit() conn.close()<file_sep>/sqlserver_tables/createtable.sql --CREATE TABLE sqlite_sequence([name] ,seq); DROP TABLE IF EXISTS [raw].api_oldcustomer; CREATE TABLE [raw].api_oldcustomer (id integer NOT NULL PRIMARY KEY , loan_status_2 varchar(16) NULL, loan_status integer NULL, loan_amnt real NULL, term integer NULL, int_rate real NULL, installment real NULL, sub_grade varchar(2) NULL, emp_length integer NULL, home_ownership varchar(16) NULL, annual_inc varchar(32) NULL, verification_status varchar(16) NULL, issue_d varchar(32) NULL, purpose varchar(32) NULL, addr_state varchar(2) NULL, dti real NULL, fico_range_low integer NULL, fico_range_high integer NULL, open_acc integer NULL, pub_rec integer NULL, revol_bal integer NULL, revol_util real NULL, mort_acc integer NULL, pub_rec_bankruptcies integer NULL, age integer NULL, pay_status integer NULL); DROP TABLE IF EXISTS [raw].api_homeownership; CREATE TABLE [raw].api_homeownership (id integer NOT NULL PRIMARY KEY , [name] varchar(16) NULL); DROP TABLE IF EXISTS [raw].api_purpose; CREATE TABLE [raw].api_purpose (id integer NOT NULL PRIMARY KEY , [name] varchar(32) NULL); DROP TABLE IF EXISTS [raw].api_state; CREATE TABLE [raw].api_state (id integer NOT NULL PRIMARY KEY , [name] varchar(8) NULL); DROP TABLE IF EXISTS [raw].api_subgrade; CREATE TABLE [raw].api_subgrade (id integer NOT NULL PRIMARY KEY , [name] varchar(2) NULL); DROP table if exists [raw].api_verificationstatus; CREATE TABLE [raw].api_verificationstatus (id integer NOT NULL PRIMARY KEY , [name] varchar(16) NULL); drop table if exists [raw].api_newcustomer; CREATE TABLE [raw].api_newcustomer (id integer NOT NULL PRIMARY KEY , loan_status integer NULL, loan_amnt varchar(16) NULL, term varchar(8) NULL, int_rate real NULL, installment real NULL, sub_grade_id integer NULL, employment_length integer NULL, home_ownership_id integer NULL, annual_inc integer NULL, verification_status_id integer NULL, issued varchar(32) NULL, purpose_id integer NULL, addr_state_id integer NULL, dti real NULL, fico_range_low real NULL, fico_range_high real NULL, open_acc real NULL, pub_rec real NULL, revol_bal real NULL, revol_util real NULL, mort_acc real NULL, pub_rec_bankruptcies real NULL, age real NULL, payment_status real NULL);
45fc9c2b9d1d7f655633594b1a57e6815030751d
[ "Markdown", "SQL", "Python", "Text" ]
15
SQL
akshaykatre/databuild
d9d122844dbaac765687b0c42179a034c93c8807
ff6e1a58a73efb32f23c5acafbccf6a2bb96639f
refs/heads/master
<file_sep><?php /* Plugin Name: Plugin Title Plugin URI: http://teolopez.com Description: Version: 0.5 Author: <NAME> Author URI: http://teolopez.com License: GPL2 */ /* // ---------------------------------------------- ---- TABLE OF CONTENTS -- // ---------------------------------------------- * 1. Add Custom Post Type Named * 2. Add Taxonomy for Custom Post Type * 3. Change the Title Text * 4. Add Custome Meta Boxes * 6. Add Custome CSS for plugin */ // ---------------------------------------------- // 1. Title // ----------------------------------------------
659f2ab1b02f1c080049112f1d05dc96af4ab7a6
[ "PHP" ]
1
PHP
teolopez/tl_plugintemplate
37125b816ffe7aa615ca54309bff211ef6d30c31
ba28a719f2daf3ef4630981f18b9443dd3690c80
refs/heads/master
<file_sep>#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <sys/stat.h> #include <errno.h> typedef uint8_t BYTE; int main(int argc, char *argv[]) { char *sourceFile = argv[1]; char *pch; // check does program was correctly initiated if (argc != 2) { printf("Usage: ./recover image\n"); return 1; } else if((pch=strstr(argv[1],".raw")) == NULL ) { printf("The parameter must be a .raw file format\n"); return 2; } // else if((pch=strstr(argv[1],"./")) == NULL ) // { // printf("You need to specify a path leding to a .raw file\n"); // return 3; // } // open raw file FILE *inPointer = fopen(argv[1], "r"); if (inPointer == NULL) { fprintf(stderr, "Could not open %s.\n", sourceFile); return 4; } // create directory if doesn't exist mkdir("images", 0777); // declare needed variables BYTE buffer[512]; int imageNumber = 0; char intToString[10]; char nameOfAfile[128]; char nameConcat1[] = {"./images/image-"}; char nameConcat2[] = {".jpg"}; BYTE isNewJpeg = 0; BYTE isJpeg = 0; BYTE compare[3] = { 255, 216, 255}; FILE *image; while (fread(buffer, 512,1,inPointer) == 1) { // check is it start of a new jpeg if(buffer[0] == 255) { isNewJpeg++; for(int i = 1; i < 3; i++) { if (buffer[i] == compare[i]) { isNewJpeg++; } } for (BYTE i = 224; i < 240; i++) { if (buffer[3] == i) { isNewJpeg++; break; } } if (isNewJpeg != 4) { isNewJpeg = 0; } } // create jpeg file if was found if (isNewJpeg == 4) { sprintf(nameOfAfile,"./images/%03i.jpg",imageNumber); image = fopen(nameOfAfile, "w"); if (image == NULL) { fprintf(stderr, "Could not create %s.\n", nameOfAfile); return 5; } fwrite(buffer, 512, 1, image); imageNumber++; isNewJpeg = 0; isJpeg = 1; } else if(isJpeg ==1) { // check is it an end of a jpeg's file if (buffer[511] == 0 || (buffer[511] == 0xD9 && buffer[510] == 0xFF)) { // find last byte of a jpeg's file for (int i = 511; i > 0 ; i--) { if (buffer[i] != 0) { // if found last two closing bytes write down and cloase a file if (buffer[i] == 0xD9 && buffer[i-1] == 0xFF) { fwrite(buffer, 512, 1, image); printf("%s has been recovered\n", nameOfAfile); isJpeg = 0; fclose(image); break; } // if closing bytes not found just write down whole buffer to a file else { fwrite(buffer, 512, 1, image); break; } } } } // if there is no ending sign just write down buffer else { fwrite(buffer, 512, 1, image); } } } printf("\nAll images are successfully restored.\n\n"); fclose(inPointer); return 0; }<file_sep>// Implements a dictionary's functionality #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <strings.h> #include <inttypes.h> #include "dictionary.h" // Represents number of children for each node in a trie #define N 27 char alphabet[N] = {'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', '\0'}; //char alphabet2[N] = {"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", "\'"}; // Represents a node in a trie typedef struct node { bool is_word; struct node *children[N]; } node; // Represents a trie node *root; // Number of words in a dictionary unsigned int dictNrOfWords = 0; // Loads dictionary into memory, returning true if successful else false bool load(const char *dictionary) { // Initialize trie root = malloc(sizeof(node)); if (root == NULL) { return false; } root->is_word = false; for (int i = 0; i < N; i++) { root->children[i] = NULL; } // Open dictionary FILE *file = fopen(dictionary, "r"); if (file == NULL) { unload(); return false; } // Buffer for a word char word[LENGTH + 1]; // create index for children array in a trie int index = 0; // Insert words into trie node *trie; int nodeNumber; while (fscanf(file, "%s", word) != EOF) { dictNrOfWords++; nodeNumber = 0; // TODO trie = root; for (int i = 0; word[i] != '\0'; i++) { // printf("node number: %i, letter: %c\n", nodeNumber, word[i]); nodeNumber++; if ((index = tolower(word[i]) % 97) == 39) { index = 26; } // printf("index: %i\n", index); if (!trie->children[index]) { trie->children[index] = malloc(sizeof(node)); if (trie->children[index] == NULL) { printf("Couldn't create a trie node\n"); dictNrOfWords = 0; return false; } trie->children[index]->is_word = false; for (int j = 0; j < N; j++) { trie->children[index]->children[j] = NULL; } } if (trie->children[index]) { trie = trie->children[index]; // printf("memory: %0lx\n", (uintptr_t) trie->children[index]); } if (word[i+1] == '\0') { trie->is_word = true; } // if (word[i+1] == '\0') // { // printf("end of a word\n"); // } } // printf("\n\n\n"); } // Close dictionary fclose(file); // Indicate success return true; } // Returns number of words in dictionary if loaded else 0 if not yet loaded unsigned int size(void) { return dictNrOfWords; } // Returns true if word is in dictionary else false bool check(const char *word) { node *trie = root; int index = 0; for (int i = 0; word[i] != '\0'; i++) { if ((index = tolower(word[i]) % 97) == 39) { index = 26; } if (trie->children[index] && word[i+1]) { trie = trie->children[index]; } else if (!trie->children[index]) { // printf("too long word\n"); return false; } else if (!word[i+1]) { if (trie->children[index]->is_word == true) { return true; } else { // printf("too short word\n"); return false; } } else { return false; } } return false; } void freeTrie(node *arg) { for (int i = 0; i < N; i++) { if (arg->children[i]) { freeTrie(arg->children[i]); } } free(arg); } // Unloads dictionary from memory, returning true if successful else false bool unload(void) { freeTrie(root); return true; }<file_sep># Usage: # make # compile all binary # make clean # remove ALL binaries and objects .PHONY = all clean CC = gcc # compiler to use LINKERFLAG = -lm SRCS := resize.c BINS := resize all: resize resize: resize.o @echo "Checking.." gcc resize.o -o resize -lm resize.o: resize.c @echo "Creating object.." gcc -c resize.c clean: @echo "Cleaning up..." rm -rvf resize.o resize<file_sep>#include <stdio.h> #include <stdint.h> #include "bmp.h" void main() { FILE *inptr = fopen("smiley.bmp", "r"); BITMAPFILEHEADER bf; BITMAPINFOHEADER bi; fread(&bf,sizeof(BITMAPFILEHEADER),1, inptr); fread(&bi,sizeof(BITMAPINFOHEADER),1, inptr); printf("bitmapfileheader size in bytes: %li\n", sizeof(BITMAPFILEHEADER)); printf("bitmapinfoheader size in bytes: %li\n", sizeof(BITMAPINFOHEADER)); printf("bfSize: %i\n", bf.bfSize); printf("bfType: %i\n", bf.bfType); printf("bfOffBits: %i\n", bf.bfOffBits); printf("biSize: %i\n", bi.biSize); printf("biHeight: %i\n", bi.biHeight); printf("biWidth: %i\n", bi.biWidth); printf("RGBTRIPLE size: %li\n", sizeof(RGBTRIPLE)); }<file_sep>#include <stdio.h> #include <stdlib.h> typedef struct node { int value; struct node *child[3]; }node; int main(const int argc, const char *argv[]) { node *element1 = malloc(sizeof(node)); element1->child[0] = malloc(sizeof(node)); printf("%p\n", element1); printf("%p\n", element1->child[0]); printf("%p\n", element1->child[0]->child[0]); element1->child[0]->child[0] = malloc(sizeof(node)); printf("%p\n", element1->child[0]->child[0]); return 0; }<file_sep>// TODO // convert jquery to vanilla js // window.pageYOffset(); let sections = $('section').toArray(); let pageHeight = $(document).innerHeight(); let windowHeight = $(window).innerHeight(); window.addEventListener("scroll", () => { let windowOffset = $(window).scrollTop(); console.log('window height: ' + windowHeight); console.log('page height: ' + pageHeight); console.log('window offset: ' + windowOffset); sections.forEach(element => { let elementYoffset = $(element).offset().top; console.log(elementYoffset); if (windowOffset + (windowHeight / 1.6) > elementYoffset) { $(element).addClass('show'); $(element).find('.h1bg').addClass('h1bg--show'); $(element).find('.heading').addClass('heading--yellow'); } else { $(element).removeClass('show'); $(element).find('.h1bg').removeClass('h1bg--show'); $(element).find('.heading').removeClass('heading--yellow'); } if (($(element).height() + elementYoffset) < (windowOffset + windowHeight / 4)) { $(element).removeClass('show'); $(element).find('.h1bg').removeClass('h1bg--show'); $(element).find('.heading').removeClass('heading--yellow'); } }); console.log(sections); }) // $('section').toggleClass("show", ($(window).scrollTop() > 1000)); // }); // }); // $(document).ready(() => { // $('section').hover(function () { // $(this).toggleClass('show'); // $(this).find('.h1bg').toggleClass('h1bg--show'); // $(this).find('.heading').toggleClass('heading--yellow'); // }), // () => { // } // }) function closeMenu(event) { if (event.keyCode === 27) { let element = document.getElementsByClassName('navbar__burger')[0]; element.classList.remove("open"); element = document.getElementsByClassName('navbar__menu')[0]; element.classList.remove("open"); } } $('.navbar__toggler').click(function () { $('.navbar__burger').toggleClass('open'); $('.navbar__menu').toggleClass('open'); if ($('.navbar__menu').hasClass('open')) { document.addEventListener("keyup", closeMenu(event)); $('.navbar__menu').click(() => { $('.navbar__burger').removeClass('open'); $('.navbar__menu').removeClass('open'); }) document.removeEventListener("keyup", closeMenu(event)); } }); $('.container').find('.myRecentWorkBox').find('img').each(function () { let imgClass = (this.width / this.height > 1) ? 'wide' : 'tall'; $(this).addClass(imgClass); }); function setMyRecentWorkBoxHeight() { let MyRecentWorkBox = document.getElementsByClassName("myRecentWorkBox"); let MyRecentWorkBoxWidth = MyRecentWorkBox[0].clientWidth; // console.log(MyRecentWorkBoxWidth); for (let i = 0; i < MyRecentWorkBox.length; i++) { MyRecentWorkBox[i].style.height = `${MyRecentWorkBoxWidth}px`; } } setMyRecentWorkBoxHeight(); window.addEventListener("resize", setMyRecentWorkBoxHeight); //functions used in inline HTML //autoresize contact textarea function addAutoResize() { document.querySelectorAll('[data-autoresize]').forEach(function (element) { element.style.boxSizing = 'border-box'; var offset = element.offsetHeight - element.clientHeight; document.addEventListener('input', function (event) { event.target.style.height = 'auto'; event.target.style.height = event.target.scrollHeight + offset + 'px'; }); element.removeAttribute('data-autoresize'); }); }<file_sep>#include <stdio.h> #include <stdlib.h> typedef struct node { int value; struct node *children[2]; }node; void trieAdd(node *trie, int value); void triePrint(node *trie); int main(int argc, const char *argv[]) { node *trie = malloc(sizeof(node)); trieAdd(trie, 50); trieAdd(trie, 11); trieAdd(trie, 12); trieAdd(trie, 12); trieAdd(trie, 14); trieAdd(trie, 55); trieAdd(trie, 122); trieAdd(trie, 43); trieAdd(trie, 35); trieAdd(trie, 156); trieAdd(trie, 1); trieAdd(trie, 5); trieAdd(trie, 87); trieAdd(trie, 15); trieAdd(trie, 16); trieAdd(trie, 1); trieAdd(trie, 87); trieAdd(trie, 5); trieAdd(trie, 156); trieAdd(trie, 15); triePrint(trie); printf("\n"); free(trie); return 0; } void trieAdd(node *trie, int value) { if (!trie->value) { trie->value = value; trie->children[0] = '\0'; trie->children[1] = '\0'; } else if (trie->value > value && trie->children[0]) { trieAdd(trie->children[0], value); } else if (trie->value < value && trie->children[1]) { trieAdd(trie->children[1], value); } else if (trie->value > value) { trie->children[0] = malloc(sizeof(node)); trieAdd(trie->children[0], value); } else if (trie->value < value) { trie->children[1] = malloc(sizeof(node)); trieAdd(trie->children[1], value); } return; } void triePrint(node *trie) { if (trie->value) { printf("%i, ", trie->value); } if (trie->children[0]) { triePrint(trie->children[0]); } if (trie->children[1]) { triePrint(trie->children[1]); } return; }<file_sep>CS50's problem sets from edx.org
da70b7c5e56438110f0f8ca59cb254c5134778dd
[ "JavaScript", "C", "Makefile", "Markdown" ]
8
C
PatrycjuszNowaczyk/cs50
cdd49197bb9c9b767df4b8f9053bc546f32764c4
fe0ff3a06e7038cee365fdd361ea44dd402a4520
refs/heads/master
<repo_name>suyashrkhandekar/intern<file_sep>/src/main/java/com/intern/jerseyrest/StudentResourceDelete.java package com.intern.jerseyrest; import java.util.Iterator; import java.util.List; import javax.ws.rs.DELETE; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import org.hibernate.Session; import com.intern.util.HibernateUtil; @Path("/delete/{idd}") public class StudentResourceDelete { @DELETE public List<Student> deleteStudent(@PathParam("idd") int stid) { Session session= HibernateUtil.getSessionFactory().openSession(); Student ss= session.get(Student.class, stid); System.out.println(ss); session.delete(ss); session.beginTransaction().commit(); List<Student> list= session.createQuery("From Student").getResultList(); Iterator<Student> itr = list.iterator(); while(itr.hasNext()) { Student t= itr.next(); System.out.println(t.getStudent_name()); System.out.println(t.getStudent_id()); System.out.println(t.getStudent_doj()); System.out.println(t.getStudent_dob()); System.out.println("-------------------------------------"); } return list; /* * System.out.println(s_id.getStudent_id()); s_id=session.get(Student.class, 3); * System.out.println(s_id); */ } }
ec6530a6c111cb834be593715fe6849a9dddefec
[ "Java" ]
1
Java
suyashrkhandekar/intern
45aa120e25d91c2968d0943f7f11a248647fd85f
b7b93094664e71e471baad0d14806a367430fc70
refs/heads/master
<repo_name>17kong/yiqikong-sensor<file_sep>/class/IoT/Sensor/Wechat/App.php <?php namespace IoT\Sensor\Wechat; class App extends \Wechat\App { public function __construct() { parent::__construct(\Gini\Config::get('wechat.app_id'), \Gini\Config::get('wechat.app_secret')); } protected function getStoragePath($id) { $appId = $this->getAppId(); return APP_PATH.'/'.DATA_DIR."/wechat_{$appId}_{$id}"; } public function getOAuth() { return \Gini\IoC::construct('\Wechat\OAuth', $this->getAppId(), $this->getAppSecret()); } public function getTempQRCode($sceneId, $expire_seconds = 600) { $token = $this->getAccessToken(); if (!$token) { return false; } $url = URL('https://api.weixin.qq.com/cgi-bin/qrcode/create', ['access_token' => $token]); $http = new \Gini\HTTP(); $response = $http->post($url, J([ 'expire_seconds' => $expire_seconds, 'action_name' => 'QR_SCENE', 'action_info' => [ 'scene' => [ 'scene_id' => $sceneId, ] ], ])); return @json_decode($response->body, true) ?: false; } public function gtWarnBinding($sensor, $user, $name) { if ($sensor->model !== 'gt' || !$user) { return ; } $remark = '如果非知情操作,请及时处理'; $url = strtr('http://tank.giot.in/sensor/%id', ['%id' => $sensor->id]); $first = '您的GT设备已与您解除绑定'; $content = strtr('此设备已被 %name 重新绑定', ['%name' => $name]); $time = date('Y-m-d H:i:s', time()); return $this->userAlert($user, $first, $sensor->name, $time, $content, $remark, $url); } public function gtAlert($sensor, $now) { if ($sensor->model !== 'gt') { return false; } $remark = strtr('第 %c 次警报,请及时处理', ['%c' => ($sensor->config['alert_count'])]); if ($sensor->config['alert_times'] > 0 && ($sensor->config['alert_count']) >= $sensor->config['alert_times']){ $remark = '最后一次警报,请及时处理!'; } $url = strtr('http://tank.giot.in/sensor/%id', ['%id' => $sensor->id]); $first = '您的GT设备有警报提醒:'; $content = strtr('当前温度 %t 超出阈值', ['%t' => round($sensor->data['t'], 1)]); $time = date('Y-m-d H:i:s', $now); $users = []; if ($sensor->wx_openid ) { array_push($users, $sensor->wx_openid); } $subscribes = those('subscribe')->whose('sensor_id')->is($sensor->id); foreach($subscribes as $sub) { if (!in_array($sub->wx_openid, $users)) { array_push($users, $sub->wx_openid); } } $result = true; foreach($users as $user) { $result &= $this->userAlert($user, $first, $sensor->name, $time, $content, $remark, $url); } return $result; } public function userAlert($wx_openid, $first, $name, $time, $content, $remark, $url) { $info = [ 'touser' => $wx_openid, 'template_id' => 'qooUM4Ndnc9KsyPM0kH6qFJrsaqS5m9krAPIB8UI07U', 'url' => $url, 'topcolor' => '#FF0000', 'data' => [ 'first' => [ 'value' => $first, ], 'keyword1' => [ 'value' => $name, 'color' => '#173177' ], 'keyword2' => [ 'value' => $time, 'color' => '#173177' ], 'keyword3' => [ 'value' => $content, 'color' => '#FF0000' ], 'remark' => [ 'value' => $remark, 'color' => '#173177' ] ], ]; $http = new \Gini\HTTP(); $response = $http ->post( URL('https://api.weixin.qq.com/cgi-bin/message/template/send', ['access_token' => $this->getAccessToken()]), J($info) ); $result = json_decode($response->body, true); return $result['errcode'] === 0 ; } } <file_sep>/class/Gini/Controller/CGI/WechatOAuth.php <?php namespace Gini\Controller\CGI; abstract class WechatOAuth extends \Gini\Controller\CGI { public function __preAction($action, &$params) { // 如果当前用户无身份, 尝试oauth检查当前用户微信身份 $app = new \IoT\Sensor\Wechat\App(); $openId = $app->getOAuth()->getOpenId(); if ($openId) { _G('WX_OPENID', $openId); } return parent::__preAction($action, $params); } } <file_sep>/class/Gini/Controller/API/IoT/Sensor.php <?php namespace Gini\Controller\API\IoT; class Sensor extends \Gini\Controller\API { /** * 通过token获取传感器. * * @param string $token * * @return false|object * * @author <NAME> */ public function actionGetSensorByToken($token) { $sensor = a('sensor', ['code' => $token]); if (!$sensor->id) { return false; } return [ 'id' => $sensor->id, 'token' => $sensor->token, ]; } /** * 通过uuid获取传感器. * * @param string $uuid * * @return object * * @author <NAME> */ public function actionGetSensorByUUID($uuid) { $sensor = a('sensor', ['uuid' => $uuid]); if (!$sensor->id) { return false; } return [ 'id' => $sensor->id, 'uuid' => $sensor->uuid, 'secret' => $sensor->secret, 'model' => $sensor->model, ]; } /** * 绑定传感器. * * @param string $uuid * @param string $token * * @return object|false * * @author <NAME> */ public function actionBindSensor($uuid, $token, $model) { $sensor = a('sensor', ['code' => $token]); if (!$sensor->id || $sensor->uuid) { return false; } // 确认如果有其他同样uuid的sensor需要disable $olds = those('sensor')->whose('uuid')->is($uuid) ->andWhose('disabled')->is(false) ->andWhose('id')->isNot($sensor->id); foreach($olds as $old_sensor) { $old_sensor->old_uuid = $sensor->uuid; $old_sensor->uuid = null; $old_sensor->disabled = true; $old_sensor->save(); } $sensor->code = null; $sensor->uuid = $uuid; $sensor->model = $model; $sensor->secret = uniqid(); $success = $sensor->save(); return $success ? [ 'id' => $sensor->id, 'secret' => $sensor->secret, ] : false; } /** * 提交数据. * * @param string $uuid * @param string $data * * @return bool * * @author <NAME> */ public function actionSubmitSensorData($uuid, $data) { $sensor = a('sensor', ['uuid' => $uuid]); if (!$sensor->id || !$sensor->model) { return false; } // not graceful below if ($sensor->model === 'gt' && $data['t'] === -999) { // 探头脱落等原因导致读取不到数据,默认 -999 // 不记录 return true; } $model = $sensor->model; $point = a("sensor/$model"); $point->sensor = $sensor; foreach ($data as $k => $v) { $point->$k = $v; } $point->save(); $sensor->data = (array) $data; // Record time to show status of the sensor easily. $now = time(); $sensor->data['time'] = $now; //determine whether to alert gt wx user or not. $alert = false; if ($sensor->model === 'gt') { $alert = $this->gtCheck($sensor); if ($alert) { $sensor->config['alert_count'] = $sensor->config['alert_count'] + 1; $sensor->config['alert_last_time'] = $now; } } //先存数据库, 以避免下一次提交数据时的重复报警 $sensor->save(); if ($alert) { $app = new \IoT\Sensor\Wechat\App(); $app->gtAlert($sensor, $now); } return !!$point->id; } private function gtCheck($sensor) { if ($sensor->model !== 'gt') { return false; } if ($sensor->data['t'] > $sensor->config['alert_threshold_min'] && $sensor->data['t'] < $sensor->config['alert_threshold_max']) { $sensor->config['alert_count'] = 0; // 警报次数清0 return false; } if ($sensor->config['alert_times'] > 0 && $sensor->config['alert_count'] >= $sensor->config['alert_times']) { return false; } $now = time(); if ( ($sensor->config['alert_interval'] * 60) > ($now - $sensor->config['alert_last_time']) ) { return false; } return true; } } <file_sep>/class/Gini/ORM/User.php <?php namespace Gini\ORM; class User extends Gapper\User { public function isAllowedTo( $action, $object = null, $when = null, $where = null) { if ($object === null) { return \Gini\Event::trigger( "user.is_allowed_to[$action]", $this, $action, null, $when, $where); } $oname = is_string($object) ? $object : $object->name(); return \Gini\Event::trigger( [ "user.is_allowed_to[$action].$oname", "user.is_allowed_to[$action].*", ], $this, $action, $object, $when, $where); /* TODO 是否需要将权限判断也通过rpc的方式进行验证处理,但是貌似比较废效率*/ } public function fromWechat($openId) { try { $info = self::getRPC()->gapper->user->getUserByIdentity('wechat', $openId); if ($info['username']) { $this->criteria(['username' => $info['username']]); $this->fetch(true); $this->wx_openid = $openId; } } catch (\Gini\RPC\Exception $e) { } } } <file_sep>/class/Gini/Controller/CGI/Identicon.php <?php namespace Gini\Controller\CGI; class Identicon extends \Gini\Controller\CGI { public function __index($ident = '', $size = null) { $size = max($size, 12); (new \Identicon\Identicon())->displayImage($ident, $size); } } <file_sep>/class/Gini/Controller/CGI/Layout/Wechat.php <?php namespace Gini\Controller\CGI\Layout; abstract class Wechat extends \Gini\Controller\CGI\Layout { protected static $layout_name = 'layout/wechat'; public function __preAction($action, &$params) { // 如果当前用户无身份, 尝试oauth检查当前用户微信身份 $app = new \IoT\Sensor\Wechat\App(); $openId = $app->getOAuth()->getOpenId(); if ($openId) { _G('WX_OPENID', $openId); } return parent::__preAction($action, $params); } } <file_sep>/class/Gini/Controller/CGI/WiFi.php <?php namespace Gini\Controller\CGI; class WiFi extends Layout\Wechat { public function actionAdd($id = 0) { $openId = _G('WX_OPENID'); $sensor = a('sensor', ['id' => $id, 'wx_openid' => $openId]); if ($_SERVER['REQUEST_METHOD'] == 'POST') { $form = $this->form(); if (isset($form['pair'])) { $ssid = $form['wifi-ssid']; $pass = $form['wifi-pass']; $tried = 0; while (true) { $sensor->name = ''; $sensor->code = \Gini\Util::randPassword(8, 3); $sensor->wifi = [ 'ssid' => $ssid, 'pass' => $pass, ]; $sensor->wx_openid = $openId; $sensor->save(); $tried++; if ($sensor->id || $tried > 3) { break; } } $this->redirect("wifi/pair/{$sensor->id}"); } elseif (isset($form['remove'])) { if ($sensor->id) { $sensor->delete(); } $this->redirect('/'); } } $this->view->body = V('wifi/form', ['sensor' => $sensor]); } public function actionPair($id = '') { $sensor = a('sensor', ['id' => $id, 'wx_openid' => _G('WX_OPENID')]); $this->view->body = V('wifi/pair', [ 'sensor' => $sensor, ]); } public function actionSuccess() { $this->view->body = V('wifi/success'); } // TODO public function actionAudio($hash = '') { // Play the audio $file = APP_PATH.'/'.DATA_DIR.'/test.mp3'; header('Content-Type: audio/mpeg'); header('Content-Length: '.filesize($file)); readfile($file); return false; } } <file_sep>/class/Gini/Controller/CGI/Index.php <?php namespace Gini\Controller\CGI; class Index extends Layout\Wechat { public function __index() { $openId = _G('WX_OPENID'); a('sensor')->db() ->query('DELETE FROM "sensor" WHERE "uuid" IS NULL AND "ctime" < SUBDATE(NOW(), INTERVAL 15 MINUTE)'); //todo 直接用 sql 语句连表查询 $subs = those('subscribe')->whose('wx_openid')->is($openId); $ids = []; foreach ($subs as $sub) { array_push( $ids, $sub->sensor_id); } $sensors = those('sensor') ->whose('wx_openid')->is($openId) ->andWhose('uuid')->isNot(null) ->andWhose('disabled')->is(false) ->orWhose('id')->isIn($ids) ->andWhose('uuid')->isNot(null) ->andWhose('disabled')->is(false); $now = time(); $vars = [ 'sensors' => $sensors, 'openId' => $openId, ]; $this->view->body = V('index', $vars); } } <file_sep>/class/Gini/Controller/CGI/Sensor.php <?php namespace Gini\Controller\CGI; class Sensor extends Layout\Wechat { public function __index($id = 0) { $openId = _G('WX_OPENID'); $app = new \IoT\Sensor\Wechat\App(); $info = $app->getUserInfo($openId); if ($info['errcode']) { $this->redirect('error/500'); }elseif ($info['subscribe'] != 1) { $this->redirect('follow/'.$id); } $sensor = a('sensor', $id); if (!$sensor->id || !$sensor->model) { $this->redirect('error/404'); } if ($sensor->wx_openid != $openId) { $subscribe = a('subscribe', [ 'sensor_id' => intval($id), 'wx_openid' => $openId, ]); if (!$subscribe->id) { $this->redirect("sensor/subscribe/{$id}"); } } $func = "_view{$sensor->model}"; if (!is_callable([$this, $func])) { $this->redirect('error/404'); } return $this->$func($sensor); } public function actionSubscribe($id = 0) { $openId = _G('WX_OPENID'); $sensor = a('sensor', $id); if (!$sensor->id || !$sensor->model) { $this->redirect('error/404'); } if ($_SERVER['REQUEST_METHOD'] == 'POST') { $subscriber = a('subscribe', [ 'sensor_id' => intval($id), 'wx_openid' => $openId, ]); $subscriber->wx_openid = $openId; $subscriber->sensor_id = $id; $subscriber->save(); $this->redirect("sensor/{$id}"); } $this->view->body = V('sensor/subscribe',['sensor' => $sensor]); } private function _viewPM25($sensor) { $st = a('sensor/pm25')->db()->query('SELECT date("time") AS "date", AVG("pm25") AS "pm25", AVG("t") AS "t", AVG("h") AS "h" FROM "sensor_pm25" WHERE "sensor_id"=? AND "time"<NOW() AND "time">SUBDATE(NOW(), INTERVAL 1 WEEK) GROUP BY DAY("time")', null, [$sensor->id]); $sensor_data = []; if ($st) { while ($row = $st->row()) { $sensor_data[$row->date] = [ 'pm25' => $row->pm25, 't' => $row->t, 'h' => $row->h, ]; } } $st24 = a('sensor/pm25')->db()->query('SELECT date_format("time", \'%Y-%m-%d %H\') AS "time", AVG("pm25") AS "pm25", AVG("t") AS "t", AVG("h") AS "h" FROM "sensor_pm25" WHERE "sensor_id"=? AND "time"<NOW() AND "time">SUBDATE(NOW(), INTERVAL 1 DAY) GROUP BY HOUR("time") ORDER BY "time"', null, [$sensor->id]); $sensor_data_24 = []; if ($st24) { while ($row = $st24->row()) { $sensor_data_24[$row->time] = [ 'pm25' => $row->pm25, 't' => $row->t, 'h' => $row->h, ]; } } $vars = [ 'sensor' => $sensor, 'sensor_data' => $sensor_data, 'sensor_data_24' => $sensor_data_24, 'jsapi' => $this->getJSParams(WXURL('sensor/'.$sensor->id)), ]; $this->view->body = V('sensor/pm25/now', $vars); } private function _viewGT($sensor) { $st = a('sensor/gt')->db()->query('SELECT date("time") AS "date", AVG("t") AS "t" FROM "sensor_gt" WHERE "sensor_id"=? AND "time"<NOW() AND "time">SUBDATE(NOW(), INTERVAL 1 WEEK) GROUP BY DAY("time")', null, [$sensor->id]); $sensor_data = []; if ($st) { while ($row = $st->row()) { $sensor_data[$row->date] = [ 't' => $row->t, ]; } } $st24 = a('sensor/gt')->db()->query('SELECT date_format("time", \'%Y-%m-%d %H\') AS "time", AVG("t") AS "t" FROM "sensor_gt" WHERE "sensor_id"=? AND "time"<NOW() AND "time">SUBDATE(NOW(), INTERVAL 1 DAY) GROUP BY HOUR("time") ORDER BY "time"', null, [$sensor->id]); $sensor_data_24 = []; if ($st24) { while ($row = $st24->row()) { $sensor_data_24[$row->time] = [ 't' => $row->t, ]; } } $vars = [ 'subscribe' => $sensor->wx_openid != _G('WX_OPENID'), 'sensor' => $sensor, 'sensor_data' => $sensor_data, 'sensor_data_24' => $sensor_data_24, 'jsapi' => $this->getJSParams(WXURL('sensor/'.$sensor->id)), ]; $this->view->body = V('sensor/gt/now', $vars); } private function getJSParams($url) { if (isset($_SERVER['REQUEST_URI'])){ $url = rtrim(\Gini\Config::get('wechat.base_url'), '/').$_SERVER['REQUEST_URI']; } $app = new \IoT\Sensor\Wechat\App(); $jsapi_ticket = $app->getTicket(); $timestamp = time(); $noncestr = \Gini\Util::randPassword(12, 2); // 不能用 http_build_query, 某些字符会被转义. //$string1 = http_build_query($data); $string1 = 'jsapi_ticket='.$jsapi_ticket .'&noncestr='.$noncestr .'&timestamp='.$timestamp .'&url='.$url; $signature = sha1($string1); return [ 'appid' => $app->getAppId(), 'timestamp' => $timestamp, 'noncestr' => $noncestr, 'signature' => $signature ]; } } <file_sep>/class/Gini/Controller/CLI/Sensor.php <?php namespace Gini\Controller\CLI; class Sensor extends \Gini\Controller\CLI { public function actionNewGT($args) { //echo yaml_emit($args, YAML_UTF8_ENCODING); $uuid = $args[0]; echo "uuid:".$uuid."\r\n"; $sensor = a('sensor', ['uuid' => $uuid]); if($sensor->model && $sensor->secret ){ echo "Already exist\r\n"; return; } $sensor->uuid = $uuid; $sensor->name = $args[1] ? $args[1] : 'my gt'; $sensor->model = 'gt'; $sensor->secret = uniqid(); $sensor->wx_openid = $args[2] ? $args[2] : ''; $success = $sensor->save(); if($success){ echo "Successful.\r\n"; echo yaml_emit(['uuid' => $uuid, 'model' => 'gt', 'secret' => $sensor->secret], YAML_UTF8_ENCODING); echo "\r\n"; }else{ echo "Fail!\r\n"; } } /** 为了把之前pm25 uuid从base64改为hex表示*/ public function actionUUID2Hex() { $sensors = those('sensor')->whose('uuid')->isNot(null); $count = 0; foreach ( $sensors as $sensor) { if( strlen($sensor->uuid) < 32 ){ $b_uuid = base64_decode($sensor->uuid, true); if($b_uuid){ $sensor->uuid = bin2hex($b_uuid); $sensor->save(); $count++; } } } echo "done! covert ".$count; } }<file_sep>/class/Gini/ORM/Sensor.php <?php namespace Gini\ORM; class Sensor extends Object { public $name = 'string:120'; public $model = 'string:10'; public $code = 'string:40,null:true'; public $uuid = 'string:40,null:true'; public $address = 'string:120,null:true'; public $icon = 'string:40'; public $owner = 'object:user'; public $wx_openid = 'string:40'; public $ctime = 'timestamp'; public $disabled = 'bool'; public $secret = 'string:40'; public $data = 'array'; public $config = 'array'; protected static $db_index = [ 'unique:uuid', 'unique:code', 'wx_openid', 'owner', 'ctime', ]; public function status() { if ($this->data['time']) { return $this->data['time'] + 20 > time(); } else { return false; } } public function icon($size = null) { $url = $this->icon; if (!$url) { return; } $scheme = parse_url($url)['scheme']; if ($scheme != 'http') { return $url; } return \Gini\ImageCache::makeURL($url, $size); } } <file_sep>/class/Gini/Controller/CGI/Add.php <?php namespace Gini\Controller\CGI; class Add extends Layout\Wechat { public function actionChoice() { $this->view->body = V('add/choice', [ 'models' => [ [ 'path' => 'add/qrcode', 'name' => 'gt', 'desc' => '智能温度传感器GT' ], [ 'path' => 'wifi/add', 'name' => 'pm25', 'desc' => '智能PM2.5传感器', ] ] ]); } public function actionQRCode() { $app = new \IoT\Sensor\Wechat\App(); $jsapi_ticket = $app->getTicket(); $timestamp = time(); $noncestr = \Gini\Util::randPassword(12, 2); $url = WXURL('add/qrcode'); // 不能用 http_build_query, 某些字符会被转义. //$string1 = http_build_query($data); $string1 = 'jsapi_ticket='.$jsapi_ticket .'&noncestr='.$noncestr .'&timestamp='.$timestamp .'&url='.$url; $signature = sha1($string1); $this->view->body = V('add/qrcode', [ 'wx_appid' => $app->getAppId(), 'wx_timestamp' => $timestamp, 'wx_noncestr' => $noncestr, 'wx_signature' => $signature ]); } } <file_sep>/class/Gini/Controller/CGI/AJAX/Sensor.php <?php namespace Gini\Controller\CGI\AJAX; class Sensor extends \Gini\Controller\CGI\WechatOAuth { public function actionStatus($id = 0) { $openId = _G('WX_OPENID'); $sensor = a('sensor', $id); $subscribe = a('subscribe', [ 'sensor_id' => $id, 'wx_openid' => $openId, ]); if (!$sensor->id || ($sensor->wx_openid != $openId && !$subscribe->id )) { return false; } return new \Gini\CGI\Response\JSON([ 'id' => $sensor->id, 'uuid' => $sensor->uuid, 'model' => $sensor->model, 'data' => $sensor->data, 'status' => $sensor->status(), ]); } public function actionRename($id = 0) { $openId = _G('WX_OPENID'); $sensor = a('sensor', $id); $subscribe = a('subscribe', [ 'sensor_id' => $id, 'wx_openid' => $openId, ]); if (!$sensor->id || ($sensor->wx_openid != $openId && !$subscribe->id )) { return false; } if ($_SERVER['REQUEST_METHOD'] == 'POST') { $form = $this->form(); $sensor->name = $form['name']; $sensor->save(); return new \Gini\CGI\Response\JSON([ 'name' => $sensor->name, ]); } return false; } public function actionConfig($id = 0) { $openId = _G('WX_OPENID'); $subscribe = a('subscribe', [ 'sensor_id' => $id, 'wx_openid' => $openId, ]); $sensor = a('sensor', $id); if (!$sensor->id || ($sensor->wx_openid != $openId && !$subscribe->id )) { return false; } if ($_SERVER['REQUEST_METHOD'] == 'POST') { if ($sensor->wx_openid != $openId && $sensor->config['config_lock']) { return new \Gini\CGI\Response\JSON([ 'error' => '您没有权限修改,请联系设备管理员', ]); } $form = $this->form(); // check values $threshold_min = intval($form['alert_threshold_min']); $threshold_max = intval($form['alert_threshold_max']); $alert_interval = intval($form['alert_interval']); $alert_times = intval($form['alert_times']); // 这些数字是 wyj 顺手写的, 可能要改动. if ( $form['name'] == '' || $form['address'] == '' || $threshold_min < -200 || $threshold_min > $threshold_max || $threshold_max > 999 || $alert_interval < 1 || $alert_interval > 100 || $alert_times < 1 || $alert_times > 100 ) { return new \Gini\CGI\Response\JSON([ 'error' => '参数错误', ]); } // if ($sensor->wx_openid == $openId) { $sensor->config['config_lock'] = $form['config_lock']; } $sensor->name = $form['name']; $sensor->address = $form['address']; $sensor->config['alert_threshold_min'] = $threshold_min; $sensor->config['alert_threshold_max'] = $threshold_max; $sensor->config['alert_interval'] = $alert_interval; $sensor->config['alert_times'] = $alert_times; $sensor->save(); return new \Gini\CGI\Response\JSON([ 'id' => $sensor->id, 'name' => $sensor->name, 'address' => $sensor->address, 'alert_threshold_min' => $sensor->config['alert_threshold_min'], 'alert_threshold_max' => $sensor->config['alert_threshold_max'], 'alert_interval' => $sensor->config['alert_interval'], 'alert_times' => $sensor->config['alert_times'], ]); } return false; } public function actionRemove($id = 0) { $openId = _G('WX_OPENID'); $sensor = a('sensor', $id); if (!$sensor->id || $sensor->wx_openid != $openId) { return new \Gini\CGI\Response\JSON(false); } if ($_SERVER['REQUEST_METHOD'] == 'POST') { if ($sensor->model === 'gt') { $sensor->wx_openid = null; $sensor->save(); }else{ $sensor->delete(); } return new \Gini\CGI\Response\JSON(true); } return new \Gini\CGI\Response\JSON(false); } public function actionUnsubscribe($id = 0) { $openId = _G('WX_OPENID'); $subscribe = a('subscribe', [ 'sensor_id' => $id, 'wx_openid' => $openId, ]); if (!$subscribe->id) { return new \Gini\CGI\Response\JSON(true); } if ($_SERVER['REQUEST_METHOD'] == 'POST') { $subscribe->delete(); return new \Gini\CGI\Response\JSON(true); } return new \Gini\CGI\Response\JSON(false); } public function actionBind() { $openId = _G('WX_OPENID'); if ($_SERVER['REQUEST_METHOD'] == 'POST') { $form = $this->form(); $ver = $form['ver']; $uuid = $form['str1']; $check = $form['str2']; if(!$ver || !$uuid || !$check){ return new \Gini\CGI\Response\JSON([ 'error' => 'invalid codes' ]); } $salt = <PASSWORD>$'; $cipher = md5(crypt($uuid, $salt)); $verify = ( 0 == strcasecmp($check, $cipher) ); if (!$verify) { return new \Gini\CGI\Response\JSON([ 'error' => 'fail to verify' ]); } $sensor = a('sensor', ['uuid' => $uuid]); if (!$sensor->id) { return new \Gini\CGI\Response\JSON([ 'error' => 'invalid uuid' ]); } $olduser = $sensor->wx_openid; $sensor->wx_openid = $openId; //给GT初始化 config if (!$sensor->config['alert_interval']) { $sensor->config = [ 'alert_threshold_min' => -10, //警报阈值下限,单位摄氏度 'alert_threshold_max' => 50, //警报阈值上限 'alert_interval' => 10, //警报间隔,单位分钟 'alert_times' => 3, //警报最大次数,超过次数不警报 'alert_last_time' => 0, //记录上次警报时间 'alert_count' => 0, //记录警报累积次数, 恢复正常情况则清零 'config_lock' => false, ]; }; // reset alert status $sensor->config['alert_last_time'] = 0; $sensor->config['alert_count'] = 0; $sensor->save(); // 给原GT绑定人员通知 if($sensor->model == 'gt' && $olduser && $olduser != $openId){ $app = new \IoT\Sensor\Wechat\App(); $info = $app->getUserInfo($openId); $app->gtWarnBinding($sensor, $olduser, $info['nickname']); } return new \Gini\CGI\Response\JSON([ 'id' => $sensor->id ]); } return new \Gini\CGI\Response\JSON(false); } } <file_sep>/class/Gini/Controller/CLI/Wechat.php <?php namespace Gini\Controller\CLI; class Wechat extends \Gini\Controller\CLI { public function actionUpdateMenu($args) { $app = new \IoT\Sensor\Wechat\App(); $menu = [ 'button' => [ [ 'name' => '+ 添加', 'type' => 'view', 'url' => WXURL('add/choice') ], [ 'name' => '我的"探块儿"', 'type' => 'view', 'url' => WXURL(''), ], ], ]; $token = $app->getAccessToken(); $http = new \Gini\HTTP(); $response = $http ->post( URL('https://api.weixin.qq.com/cgi-bin/menu/create', ['access_token' => $token]), J($menu) ); echo yaml_emit(json_decode($response->body, true), YAML_UTF8_ENCODING); } public function actionShowMenu($args) { $app = new \IoT\Sensor\Wechat\App(); $token = $app->getAccessToken(); $http = new \Gini\HTTP(); $response = $http ->get( 'https://api.weixin.qq.com/cgi-bin/menu/get', ['access_token' => $token] ); echo yaml_emit(json_decode($response->body, true), YAML_UTF8_ENCODING); } public function actionTestAlert($args) { $app = new \IoT\Sensor\Wechat\App(); $uuid = '2f200507c98c4dae373b7b54451900f5'; $sensor = a('sensor', ['uuid' => $uuid]); $token = $app->getAccessToken(); $http = new \Gini\HTTP(); $info = [ 'touser' => $sensor->wx_openid, 'template_id' => 'qooUM4Ndnc9KsyPM0kH6qFJrsaqS5m9krAPIB8UI07U', 'url' => strtr('http://tank.giot.in/sensor/%id', ['%id' => $sensor->id]), 'topcolor' => '#FF0000', 'data' => [ 'first' => [ 'value' => '您的GT设备有警报提醒:', ], 'keyword1' => [ 'value' => $sensor->name, 'color' => '#173177' ], 'keyword2' => [ 'value' => date('Y-m-d H:i:s'), 'color' => '#173177' ], 'keyword3' => [ 'value' => strtr('当前温度 %t 超出阈值', ['%t' => round($sensor->data['t'], 1)]), 'color' => '#FF0000' ], 'remark' => [ 'value' => '请及时处理', 'color' => '#173177' ] ], ]; $response = $http ->post( URL('https://api.weixin.qq.com/cgi-bin/message/template/send', ['access_token' => $token]), J($info) ); echo yaml_emit(json_decode($response->body, true), YAML_UTF8_ENCODING); } } <file_sep>/class/IoT/Sensor/Wechat/Server.php <?php namespace IoT\Sensor\Wechat; class Server extends \Wechat\Server { private $_app; public function __construct() { parent::__construct(\Gini\Config::get('wechat.token')); } // 用户关注 protected function onSubscribe() { $content = '感谢关注探块儿公众号,请点击下方的"+添加"按钮,扫描设备二维码来绑定设备。'; $eventkey = $this->getRequest('eventkey'); $sensor_id = substr($eventkey, 8); // qrscene_1 if ( $sensor_id && $sensor_id !== '0' ) { $sensor_url = WXURL('sensor/'.$sensor_id); $content = '感谢关注探块儿公众号, 您之前访问的设备为 '.$sensor_url.' 请点击访问'; } return $this->respondText($content); } // 用户取消关注 protected function onUnsubscribe() { } // 收到文本消息时触发,此处为响应代码 protected function onText() { } // 收到图片消息 protected function onImage() { } // 收到地理位置消息 protected function onLocation() { } // 收到链接消息 protected function onLink() { } // 收到未知类型消息 protected function onUnknown() { } // 接收到扫描消息 protected function onScan() { } protected function onScanCodeWaitMsg() { } protected function onClick() { } protected function onView() { } } <file_sep>/class/Gini/ORM/Sensor/PM25.php <?php namespace Gini\ORM\Sensor; class PM25 extends \Gini\ORM\Object { public $sensor = 'object:sensor'; public $time = 'timestamp'; public $pm25 = 'int'; public $t = 'double'; public $h = 'double'; protected static $db_index = [ 'sensor,time', 'sensor', 'time', ]; } <file_sep>/class/Gini/Controller/CLI/test.php <?php namespace Gini\Controller\CLI; class Test extends \Gini\Controller\CLI { public function actionTTT($args) { $subscribe = a('subscribe', ['sensor_id' => 999, 'wx_openid' => 'ttt']); if(!$subscribe){ echo 'not find'; } echo json_encode($subscribe); echo "done!".$subscribe->id; } }<file_sep>/class/Gini/Controller/CGI/Wechat.php <?php namespace Gini\Controller\CGI; class Wechat extends \Gini\Controller\CGI { public function __index() { $form = $this->form('get'); $server = new \IoT\Sensor\Wechat\Server(); $response = $server->handleRequest([ 'get' => $form, 'post' => $GLOBALS['HTTP_RAW_POST_DATA'], ]); return new \Gini\CGI\Response\HTML((string) $response); } } <file_sep>/class/Gini/Controller/CGI/Follow.php <?php namespace Gini\Controller\CGI; class Follow extends Layout\Wechat { public function __index($id = 0) { $openId = _G('WX_OPENID'); $app = new \IoT\Sensor\Wechat\App(); $qrcode = $app->getTempQRCode(intval($id)); $img = URL('https://mp.weixin.qq.com/cgi-bin/showqrcode', ['ticket' => $qrcode['ticket']]); $vars = [ 'url' => $qrcode['url'], 'img' => $img, ]; $this->view->body = V('follow', $vars); } } <file_sep>/class/Gini/ORM/Subscribe.php <?php namespace Gini\ORM; class Subscribe extends Object { public $wx_openid = 'string:40'; public $sensor = 'object:sensor'; public $role = 'int'; protected static $db_index = [ 'wx_openid', 'sensor', ]; }
e9cb8ce5718761468f194c652044be59d1253089
[ "PHP" ]
20
PHP
17kong/yiqikong-sensor
e0cdda47fa1539615e23151d47749347ebe9cd2a
82d2144586f34a727f2078233a2981b646def310
refs/heads/master
<file_sep>import React from "react"; import { View, ScrollView, Text, Button, DatePickerIOS, Platform, StatusBar } from "react-native"; import StyleSheet from '../estilo/style.js'; import { AdMobBanner } from 'react-native-admob'; class SobreScreen extends React.Component { static navigationOptions = { title: 'Sobre', headerStyle: { backgroundColor: StyleSheet.primaryColor.color, }, headerTintColor: StyleSheet.textoBranco.color, headerTitleStyle: { fontWeight: 'bold', }, }; render() { return ( <View style={{ flex: 1 }}> <ScrollView> <StatusBar backgroundColor={StyleSheet.primaryDarkColor.color} barStyle="light-content" /> <Text style={StyleSheet.textoJustificadoSobre}>A numerologia é o estudo do significado oculto dos números e sua influência no comportamento e no destino dos homens.</Text> <Text style={StyleSheet.textoJustificadoSobre}>O cálculo do Ano Pessoal mostra a partir da data do aniversário possíveis influências do ano que está por vir. O cálculo do Ano Pessoal se da por ciclos de 9 em 9 anos que a partir de cada data de aniversário é feito o cálculo e identificando em que estágio se encontra a vida pessoal.</Text> <Text style={StyleSheet.textoJustificadoSobre}>Para calcular o seu Ano Pessoal, basta preencher a data de aniversário do ano que deseja saber e apertar em ˜Calcular˜. O aplicativo trará o valor calculado e informações sobre o resultado do cálculo.</Text> <Text style={StyleSheet.textoJustificadoSobre}>Exemplo: Aniversário em 17/05/2022, ao colocar esta data você saberá como será o seu ano de 2022, lembrando que se da a partir da data do aniversário e não da data inicial do ano.</Text> <Text style={StyleSheet.textoJustificadoSobre}>Este aplicativo tem o objetivo de entreterimento e jamais deverá ser levado em consideração como único instrumento numerológico.</Text> <Text style={StyleSheet.tituloJustificadoSobre}>Referências utilizadas:</Text> <Text style={StyleSheet.textoJustificadoSobre}>https://anamariabraga.globo.com/materia/como-calcular-seu-ano-pessoal-a-partir-da-data-de-aniversario</Text> <Text style={StyleSheet.textoJustificadoSobre}>https://www.wemystic.com.br/artigos/ano-pessoal-2019/</Text> <Text style={StyleSheet.textoJustificadoSobre}>https://www.astrocentro.com.br/blog/previsoes/ano-pessoal-2019/</Text> <Text style={StyleSheet.textoJustificadoSobre}>https://numerologiacabalistica.org/ano-pessoal-em-2019/</Text> </ScrollView> </View> ); } } export default SobreScreen <file_sep>import React from "react"; import { ScrollView, View, Text, TouchableOpacity, DatePickerIOS, Platform, StatusBar, Share, Clipboard } from "react-native"; import StyleSheet from '../estilo/style.js'; import { AdMobBanner, AdMobInterstitial } from 'react-native-admob'; class DetailsScreen extends React.Component { constructor(props){ super(props); dataNascimento = props.navigation.getParam('dataNascimento', '01/01/1900'); let dia = dataNascimento.substring(0,2); let mes = dataNascimento.substring(3,5); let ano = dataNascimento.substring(6,10); let totalString = dia + mes + ano; total = 0; for(i = 0; i < totalString.length; i++){ total += Number(totalString.charAt(i)); } while(total > 9){ totalAux = total; total = 0; for(i = 0; i < String(totalAux).length; i++){ total += Number(String(totalAux).charAt(i)); } } textoResultado = ""; if(total == 1){ tituloResultado = "Ano 1 - O plantio"; textoResultado = "Ano 1 é o início de um ciclo de 9 anos. Ter o ano 1 significa um ano de ação, muitas mudanças ocorrerão, indicando o começo de novas fases ou recomeço de ideias. E hora de ir atrás de suas oportunidades e definir seus objetivos pessoais e profissionais. Tudo precisa estar bem definido para que toda oportunidade seja aproveitada. Estar pronto para o futuro significa se abrir para o novo, aceitar o desconhecido, enfrentar o medo, aceitar o desconhecido e não se abalar com imprevistos.\n\nVocê terá que por a mão na massa, acreditar na sua intuição e investir no seu futuro. Tudo que se planta no ano 1 você colhe nos próximos anos."; }else if(total == 2){ tituloResultado = "Ano 2 - As sementes germinam"; textoResultado = "É o ano de praticar a paciência, será importante saber esperar. Após ter um ano 1, é preciso ter calma para as sementes plantadas germinarem. Não se precipite e saiba o momento certo de dar cada passo. Muita cautela em todas áreas da vida, principalmente na área financeira.\n\nÉ hora de praticar as parcerias para prosperar, reforce as amizades, a parceria amorosa e a afinidade com os colegadas de trabalho. Ótimo momento para novas amizades e novos relacionamentos se for o caso."; }else if(total == 3){ tituloResultado = "Ano 3 - Os brotos surgem"; textoResultado = "O ano 3 é um ano repleto de alegria, otimismo e criatividade, aproveite tudo isso para se expressar ao máximo. Utilize todo seu poder de comunicação e sedução para desenvolver seu lado profissional e pessoal. Com lado artístico aflorado aproveite para desenvolver sua carreira e aliviar o stress.\n\nConcentre-se para canalizar as energias nos objetivos reais e palpáveis, projetos do ano 1 podem estar começando a dar resultados, dê atenção a eles. Para que o ano seja de sucesso dependerá de algumas atitudes"; }else if(total == 4){ tituloResultado = "Ano 4 - Capinando a terra"; textoResultado = "Um ano rigoroso, exigirá concentração, foco, estabilidade e segurança para construir o que tanto sonha. Não bastará recorrer a atalhos ou praticidades se a disciplina não estiver presente em sua vida. Dedique-se ao trabalho hoje para sentir os frutos dos resultados amanhã. Ano de foco total.\n\nTenha cuidado para não abandonar a vida pessoal, apesar de todo esforço saiba balancear sua atenção. Sua vida sentimental poderá ficar estagnada, de atenção às pessoas que te amam. É um bom ano para lidar com imóveis, propriedades e patrimônio."; }else if(total == 5){ tituloResultado = "Ano 5 - Nascem os botões"; textoResultado = "Este ano representa a mudança, viva o presente, siga seus próprios instintos. Você se encontra no meio do ciclo de 9 anos. Liberte-se, abrace ideias novas e deixe a fluidez tomar espaço. Não deixe se levar pela rotina, alivie a pressão dos anos anteriores. Amplie seus relacionamentos sociais, conhecendo novas pessoas e estabelecendo novas amizades.\n\nO ano 5 está propenso a acidentes e muitas mudanças inesperadas, que podem ser do bom para o ruim ou do ruim para o bom. Um ano cheio de oportunidades, que devem ser bem aproveitadas."; }else if(total == 6){ tituloResultado = "Ano 6 - Abrem-se as flores"; textoResultado = "O ano 6 representa o lar, as responsabilidades domésticas, sendo ótimo para o casamento. É um ano ligado à família e ao desejo de achar seu lugar no mundo. Dedique parte de seu tempo à família e aos amigos também.\n\nLute contra a indecisão que lhe impede de evoluir com sua vida afetiva. Não há problema em ponderar, mas todo relacionamento exigirá que você assuma culpas, responsabilidades e deveres. Se assumires alguma promessa nunca exite, leve até o fim." }else if(total == 7){ tituloResultado = "Ano 7 - Os frutos nascem"; textoResultado = "Ano de muitas reflexões, questionamentos, dúvidas positivas. O universo coloca questionamentos para que as pessoas busquem respostas. É um ano de desenvolvimento, busque técnicas de autoconhecimento. Quando enter esta lição, você crescerá ainda mais.\n\nAproveite esse momento para calmaria, você mesmo sentirá necessidade de desacelerar, ter mais sossego, introspecção e compreensão da sua espiritualidade.\n\nNão será um ano para investimentos financeiros, apesar de ser um período de boa energia para sua conta bancária."; }else if(total == 8){ tituloResultado = "Ano 8 - A colheita"; textoResultado = "Representa o materialismo, onde os resultados deste ciclo de 9 anos aparecem, e dependendo de como foi os anos anteriores será um ano de fartura e prosperidade. Entretanto se os anos passados foram negligenciados, este ano poderá representar perdas e gastos. Afinal está se colhendo o que se plantou.\n\nÉ um ano dinâmico e ótimo para tratar de assuntos financeiros, como vender ou comprar imóveis e pagar ou cobrar dívidas. Nesse ano o dinheiro surge de fontes inesperadas, devendo ficar-se atento as oportunidades que surgirão para ganhar dinheiro."; }else if(total == 9){ tituloResultado = "Ano 9 - Limpar a terra após a colheita e prepará-la para um novo plantio"; textoResultado = "É o ano mais complexo, por tudo que ele traz. É fim de ciclo, imagina que você passe por uma sequência de 8 anos, você construiu, agora você vai começar a separar o que está ruim e deixar tudo que está bom para o próximo ciclo. Uma palavra para representar este ano é \"Limpeza\".\n\nAlguns ciclos chegarão ao esperado fim e você precisará se desapegar do que é antigo para que a nova energia desse ano pessoal traga as merecidas bênçãos. Pratique o desapego, deixe de lado tudo que passou, o novo está logo à frente.\n\nÚltima dica importante: não iniciar nada novo em ano 9. Quer começar algo, espere um ano até o próximo Ano 1."; } this.state = {dataNascimento, dia, mes, ano, total, tituloResultado, textoResultado}; AdMobInterstitial.setAdUnitID('XXX'); AdMobInterstitial.requestAd().catch(error => console.warn(error)); } onShare = async (mensagem) => { try { const result = await Share.share({ message: mensagem, }); if (result.action === Share.sharedAction) { if (result.activityType) { // shared with activity type of result.activityType } else { // shared } } else if (result.action === Share.dismissedAction) { // dismissed } } catch (error) { alert(error.message); } } compartilharInter = () => { AdMobInterstitial.showAd().catch(this.compartilhar); AdMobInterstitial.addEventListener('adClosed', this.compartilhar); } compartilhar = () => { mensagem = 'Data do Aniversário ' + this.state.dataNascimento + "\n\n" + this.state.tituloResultado + "\n\n" + this.state.textoResultado; this.onShare(mensagem); } copiar = () => { mensagem = 'Data do Aniversário ' + this.state.dataNascimento + "\n\n" + this.state.tituloResultado + "\n\n" + this.state.textoResultado; Clipboard.setString(mensagem); } static navigationOptions = { title: 'Resultado', headerStyle: { backgroundColor: StyleSheet.primaryColor.color, }, headerTintColor: StyleSheet.textoBranco.color, headerTitleStyle: { fontWeight: 'bold', }, } render() { return ( <View style={{flex: 1}}> <ScrollView> <StatusBar backgroundColor={StyleSheet.primaryDarkColor.color} barStyle="light-content" /> <Text style={StyleSheet.textoCentralizado}>Data do Aniversário {JSON.stringify(this.state.dataNascimento)}</Text> <Text style={StyleSheet.textoCentralizado}>{this.state.tituloResultado}</Text> <Text style={StyleSheet.textoJustificado}>{this.state.textoResultado}</Text> <TouchableOpacity onPress={this.compartilharInter}> <View style = {StyleSheet.botaoCentralizado}> <Text style = {StyleSheet.textoBotaoCentralizado}>Compartilhar</Text> </View> </TouchableOpacity> <TouchableOpacity onPress={this.copiar}> <View style = {StyleSheet.botaoCentralizado}> <Text style = {StyleSheet.textoBotaoCentralizado}>Copiar</Text> </View> </TouchableOpacity> </ScrollView> </View> ); } } export default DetailsScreen <file_sep>import React from "react"; import { View, Text, TouchableOpacity, DatePickerIOS, Platform, StatusBar, ScrollView } from "react-native"; import { createStackNavigator, createAppContainer, createBottomTabNavigator } from "react-navigation"; // import DatePicker from 'react-native-datepicker'; import StyleSheet from '../estilo/style.js'; import { AdMobBanner } from 'react-native-admob'; const formatar = (data) => { const ano = data.getFullYear(); const mes = (data.getMonth() + 1).toString().padStart(2, '0'); const dia = data.getDate().toString().padStart(2, '0'); return dia+"/"+mes+"/"+ano; }; class HomeScreen extends React.Component { constructor(props){ super(props); this.state = {date: formatar(new Date())} } setDate(newDate) { this.setState({chosenDate: newDate}); } static navigationOptions = { title: 'Ano Pessoal', headerStyle: { backgroundColor: StyleSheet.primaryColor.color, }, headerTintColor: StyleSheet.textoBranco.color, headerTitleStyle: { fontWeight: 'bold', }, }; render() { return ( <View style={{flex: 1}}> <ScrollView> <StatusBar backgroundColor={StyleSheet.primaryDarkColor.color} barStyle="light-content" /> <Text style={StyleSheet.textoCentralizado}>O Ano Pessoal é considerado a partir de cada aniversário, e cada ano representa uma fase conforme a numerologia.</Text> <Text style={StyleSheet.textoCentralizado}>Preencha a data do seu aniversário e descubra o Ano Pessoal atual</Text> <DatePicker style={{width: 200}} date={this.state.date} mode="date" format="DD/MM/YYYY" confirmBtnText="Confirmar" cancelBtnText="Cancelar" customStyles={{ dateIcon: { display: 'none' }, dateInput: { marginLeft: 10 } }} style={StyleSheet.inputCentralizado} onDateChange={(date) => {this.setState({date: date})}} /> <TouchableOpacity onPress={() => this.props.navigation.navigate('Details', { dataNascimento: this.state.date.toString() })}> <View style = {StyleSheet.botaoCentralizado}> <Text style = {StyleSheet.textoBotaoCentralizado}>Calcular</Text> </View> </TouchableOpacity> </ScrollView> <AdMobBanner adSize="smartBanner" adUnitID="XXX" onAdFailedToLoad={error => console.error(error)} /> </View> ); } } export default HomeScreen <file_sep>import { StyleSheet } from 'react-native'; export default StyleSheet.create({ primaryColor: { color: '#E91E63', }, primaryDarkColor: { color: '#C2185B', }, textoBranco: { color: '#FFF', }, textoCinza: { color: 'gray', }, textoCentralizado: { margin: 20, fontSize: 20, textAlign: 'center', }, textoJustificado: { margin: 20, fontSize: 18, textAlign: 'left', }, textoJustificadoSobre: { margin: 10, marginBottom: 0, fontSize: 16, textAlign: 'left', }, tituloJustificadoSobre: { margin: 10, fontSize: 16, textAlign: 'center', fontWeight: 'bold', }, inputCentralizado: { alignSelf: 'center' }, botaoCentralizado: { alignSelf: 'center', flex: 1, justifyContent: 'center', width: 200, height: 40, marginTop: 20, marginBottom: 20, borderRadius: 5, backgroundColor: '#E91E63', color: '#FFF', }, textoBotaoCentralizado: { alignSelf: 'center', fontSize: 18, color: '#FFF', } }); <file_sep>import React from "react"; import { View, Text, Button, DatePickerIOS, Platform} from "react-native"; import { createStackNavigator, createAppContainer, createBottomTabNavigator} from "react-navigation"; import DatePicker from 'react-native-datepicker'; import HomeScreen from './paginas/Home.js'; import DetailsScreen from './paginas/Details.js'; import SobreScreen from './paginas/Sobre.js'; import StyleSheet from './estilo/style.js'; import FontAwesome from 'react-native-vector-icons/FontAwesome' const HomeStack = createStackNavigator({ Home: HomeScreen, Details: DetailsScreen, }); const SobreStack = createStackNavigator({ Sobre: SobreScreen, }); export default createAppContainer(createBottomTabNavigator( { Home: HomeStack, Sobre: SobreStack }, { defaultNavigationOptions: ({ navigation }) => ({ tabBarIcon: ({ focused, horizontal, tintColor }) => { const { routeName } = navigation.state; let IconComponent = FontAwesome; let iconName; if (routeName === 'Home') { iconName = 'birthday-cake'; } else if (routeName === 'Sobre') { iconName = 'info-circle'; } // You can return any component that you like here! return <IconComponent name={iconName} size={25} color={tintColor} />; }, }), tabBarOptions: { activeTintColor: StyleSheet.primaryColor.color, inactiveTintColor: StyleSheet.textoCinza.color, }/*Other configuration remains unchanged */ } ));
e88ce1dc290c02f79b884c096020c0077bbe4c4e
[ "JavaScript" ]
5
JavaScript
rogerionj/anopessoal
f31063b9302829f6af909fd12f8e598d2bf5b910
d6ccf72c8037d00e11a705f816af568a88d4136c
refs/heads/master
<repo_name>osama-ahmed220/ziro-front-end<file_sep>/graphql/user/query/me.ts import gql from "graphql-tag"; import { UserBasicFragment } from "../fragements"; export const meQuery = gql` query Me { me { ...UserBasicFragment } } ${UserBasicFragment} `; <file_sep>/hooks/useForm.ts import { useState, useEffect, FormEvent, ChangeEvent } from 'react'; type ObjectLiteral = { [key: string]: any }; function useForm<T>(callback: () => void, validate: any): { handleChange: (event: ChangeEvent<{ name: string; value: any; }>) => void, handleSubmit: (event: FormEvent<Element>) => void, values: T | ObjectLiteral, errors: any } { const [values, setValues] = useState<T | ObjectLiteral>({}); const [errors, setErrors] = useState<{}>({}); const [isSubmitting, setIsSubmitting] = useState(false); useEffect(() => { if (Object.keys(errors).length === 0 && isSubmitting) { callback(); } }, [errors]); const handleSubmit = (event: FormEvent) => { if (event) event.preventDefault(); setErrors(validate(values)); setIsSubmitting(true); }; const handleChange = (event: ChangeEvent<{ name: string, value: any }>) => { event.persist(); setValues(values => ({ ...(values as object), [event.target.name]: event.target.value })); }; return { handleChange, handleSubmit, values, errors, } }; export default useForm;<file_sep>/interfaces/LoginFormInterface.ts export interface LoginFormInterface { email?: string; password?: string; } export interface LoginFormInterfaceError extends LoginFormInterface {}<file_sep>/README.md # TODO application The TODO app on next.js with server side rendering and typescript ## Start - `npm install` Install packages. - `npm run dev` Run in development. - `npm run build` Build. - `npm run start` Run in production. <file_sep>/graphql/user/fragements.ts import gql from "graphql-tag"; export const UserBasicFragment = gql` fragment UserBasicFragment on User { id firstName lastName name email password } `; <file_sep>/graphql/user/mutation/logout.ts import gql from "graphql-tag"; export const LogoutMutaion = gql` mutation Logout { logout } `; <file_sep>/server/routes.ts import Routes from "next-routes"; export const routes = new Routes(); export const Router = routes.Router; export const Link = routes.Link;
2d415e18c5e43fa86e358678fc9a1830265f3c82
[ "Markdown", "TypeScript" ]
7
TypeScript
osama-ahmed220/ziro-front-end
e4b603edef010dd91a43e7d8c3639085266de55b
1c682145585ebc5d315b1c2f34685f3703657c41
refs/heads/master
<file_sep><?php class Universe { private $userBasket = array(); private $ordinaryBaskets = array(); private $basketCount = 30; function __construct(){ $this->generateOrdinaryBaskets(); } public function displayOrdinaryBaskets(){ $basketsContent = array(); $counter = 1; foreach ( $this->ordinaryBaskets as $singleBasket ){ $basketContent[$counter] = array( 'counter' => $counter, 'numbers' => implode( ", ", $singleBasket->getContent() ) ); $counter++; } return $basketContent; } public function generateUserBasket( $amount = null ){ $result = array(); if ( $amount ){ $this->userBasket = new UserBasket( $amount ); } else { $this->userBasket = new UserBasket(); } $result['amount'] = count( $this->userBasket->getContent() ); $result['numbers'] = implode ( ", ", $this->userBasket->getContent() ); return $result; } protected function generateOrdinaryBaskets(){ for ( $i=0; $i<$this->basketCount; $i++ ){ $this->ordinaryBaskets[$i] = new OrdinaryBasket(); } } public function checkTaskB(){ $taskB = array(); $counter = 0; $innerCounter = 0; foreach ( $this->ordinaryBaskets as $singleBasket ){ $tempIntersectionB = array_intersect( $singleBasket->getContent(), $this->userBasket->getContent() ); // I had doubts whether a single ball (when ordinaryBasket contains one ball only) should be also valid or not. //Plural "balls" may be considered ambiguous in this context so I decided so ("B. find baskets, that have only balls owned by the user") if ( $singleBasket->getCurrentAmount() == count( $tempIntersectionB ) ){ $taskB[$innerCounter] = array( 'basketNumber' => $counter + 1, 'numbers' => implode( ", ", $tempIntersectionB ) ); $innerCounter++; } $counter++; } return count( $taskB ) ? $taskB : 0; } public function checkTaskC(){ $taskC = array(); $counter = 0; $innerCounter = 0; foreach ( $this->ordinaryBaskets as $singleBasket ){ $tempIntersectionC = array_intersect( $singleBasket->getContent(), $this->userBasket->getContent() ); if ( count( $tempIntersectionC ) == 1 ){ $taskC[$innerCounter] = array( 'basketNumber' => $counter + 1, 'number' =>implode( ", ", $tempIntersectionC ) ); $innerCounter++; } $counter++; } return count( $taskC ) ? $taskC : 0; } } <file_sep><?php $root_dir = $_SERVER['DOCUMENT_ROOT'].'/Balls'; require_once $root_dir.'/Classes/ball.class.php'; require_once $root_dir.'/Classes/basket.class.php'; require_once $root_dir.'/Classes/ordinaryBasket.class.php'; require_once $root_dir.'/Classes/output.class.php'; require_once $root_dir.'/Classes/resultOutput.class.php'; require_once $root_dir.'/Classes/standardOutput.class.php'; require_once $root_dir.'/Classes/universe.class.php'; require_once $root_dir.'/Classes/userBasket.class.php'; if (isset($_POST['back'])){ unset ($_POST); $output = new standardOutput(); $output -> renderStandardView(); } elseif ($_SERVER['REQUEST_METHOD'] == 'POST'){ $universe = new Universe(); $basketsContent = $universe -> displayOrdinaryBaskets(); if (preg_match( '/^[0-9]{1,3}$/', $_POST['usersBasketAmount'] )){ if ( $_POST['usersBasketAmount'] >=1 AND $_POST['usersBasketAmount'] <=100 ){ $userBasketContent = $universe -> generateUserBasket( $_POST['usersBasketAmount'] ); } else { $error = true; } } else { if ( $_POST['usersBasketAmount'] != '' ){ $error = true; } else { $userBasketContent = $universe -> generateUserBasket(); } } if ( !isset( $error )){ $taskB = $universe->checkTaskB(); $taskC = $universe->checkTaskC(); $output = new resultOutput(); $output -> renderResultView( $basketsContent, $userBasketContent, $taskB, $taskC ); } else { $output = new standardOutput(); $output -> renderStandardView( $error ); } } else { $output = new standardOutput(); $output -> renderStandardView(); }<file_sep><?php /* /ballsTemplate.twig.html */ class __TwigTemplate_c25a311fe91f35c15d7ca4a1ea38dbaa767f425e16735f4eacf0939c1231fd62 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); // line 1 $this->parent = $this->loadTemplate("baseTemplate.twig.html", "/ballsTemplate.twig.html", 1); $this->blocks = array( 'title' => array($this, 'block_title'), 'body' => array($this, 'block_body'), ); } protected function doGetParent(array $context) { return "baseTemplate.twig.html"; } protected function doDisplay(array $context, array $blocks = array()) { $this->parent->display($context, array_merge($this->blocks, $blocks)); } // line 3 public function block_title($context, array $blocks = array()) { // line 4 echo "\t<h1 class=\"finish1\">Welcome to the World of Balls!</h1> "; } // line 7 public function block_body($context, array $blocks = array()) { // line 8 echo "\t<fieldset> \t"; // line 9 $context['_parent'] = (array) $context; $context['_seq'] = twig_ensure_traversable((isset($context["basketsContent"]) ? $context["basketsContent"] : null)); foreach ($context['_seq'] as $context["_key"] => $context["singleContent"]) { // line 10 echo "\t\t<p>"; echo twig_escape_filter($this->env, $context["singleContent"], "html", null, true); echo "</p> \t"; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['singleContent'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 12 echo "\t</fieldset> \t<fieldset> \t\t<p>User`s Basket consists of the folowing Numbers: "; // line 14 echo twig_escape_filter($this->env, (isset($context["userBasketContent"]) ? $context["userBasketContent"] : null), "html", null, true); echo "</p> \t</fieldset> "; } public function getTemplateName() { return "/ballsTemplate.twig.html"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 60 => 14, 56 => 12, 47 => 10, 43 => 9, 40 => 8, 37 => 7, 32 => 4, 29 => 3, 11 => 1,); } } <file_sep><?php class resultOutput extends Output{ public function renderResultView( $basketsContent, $userBasketContent, $taskB, $taskC ){ $output = $this->twig->render('/ballsTemplate.twig.html', array( 'basketsContent' => $basketsContent, 'userBasketContent' => $userBasketContent, 'taskB' => $taskB, 'taskC' => $taskC, )); echo $output; } }<file_sep><?php /* baseTemplate.twig.html */ class __TwigTemplate_48819e2abd2d5e3ae6ecd9e01a774ee133ef5ce71310106f88c73768c92aa47d extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( 'headTitle' => array($this, 'block_headTitle'), 'body' => array($this, 'block_body'), ); } protected function doDisplay(array $context, array $blocks = array()) { // line 1 echo "<!DOCTYPE html> <html lang=\"pl\"> <head> \t<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /> \t"; // line 5 $this->displayBlock('headTitle', $context, $blocks); // line 7 echo "\t \t<link rel=\"stylesheet\" href=\"/Balls/Assets/styles.css\" type=\"text/css\" /> \t<script src=\"/Balls/Assets/jquery.js\" ></script> \t<script src=\"/Balls/Assets/jscript.js\"></script> </head> <body> \t"; // line 13 $this->displayBlock('body', $context, $blocks); // line 15 echo "</body> "; } // line 5 public function block_headTitle($context, array $blocks = array()) { // line 6 echo "\t"; } // line 13 public function block_body($context, array $blocks = array()) { // line 14 echo "\t"; } public function getTemplateName() { return "baseTemplate.twig.html"; } public function getDebugInfo() { return array ( 54 => 14, 51 => 13, 47 => 6, 44 => 5, 39 => 15, 37 => 13, 29 => 7, 27 => 5, 21 => 1,); } } <file_sep><?php abstract class Output{ protected $twig; public function __construct(){ $root_dir = $_SERVER['DOCUMENT_ROOT'].'/Balls'; $vendor_dir = $root_dir.'/Vendor'; $cache_dir = $root_dir.'/Cache'; $templates_dir = $root_dir.'/Templates'; $twig_lib = $vendor_dir.'/Twig/lib/Twig'; require_once $twig_lib . '/Autoloader.php'; Twig_Autoloader::register(); $loader = new Twig_Loader_Filesystem( $templates_dir ); $this->twig = new Twig_Environment( $loader, array( 'cache' => $cache_dir, )); } } <file_sep><?php class standardOutput extends Output{ public function renderStandardView( $error = null ){ if ( !isset( $error )){ $output = $this->twig->render('/startPage.twig.html'); } else { $output = $this->twig->render('/startPage.twig.html', array( 'error' => 'Please insert the number between 1 and 100', )); } echo $output; } }<file_sep># Balls Balls-project allows the user to draw 30 standard baskets with randomly chosen (from 1 to 10) amount of unique-numbered balls (between 1 and 999). The user may also dispose of his own basket that contains up to 100 items (the amount of user`s basket may be set before the drawing begins). The script displays the content of every basket and check if any of the following situations happened: - single basket contains only balls (but a single ball in the basket can be also valid) owned by the user - there is only one user`s ball in the single basket The project has been written in following technologies: - PHP - Twig for rendering View layer - JavaScript (JQuery) Original online version: http://modele-ad9bis.pl/Balls <file_sep><?php abstract class Basket { protected $minimumAmount = 1; protected $currentAmount; protected $content = array(); function __construct( $amount = null ){ if ($amount){ $this->generateAmount( $amount ); } else { $this->generateAmount(); } $this->generateNumbers(); } protected function generateAmount( $amount = null){ if ( $amount ){ $this->currentAmount = $amount; } else { $this->currentAmount = mt_rand( $this->minimumAmount, $this->maximumAmount ); } } protected function generateNumbers(){ for ( $i = 0; $i < $this->currentAmount; ){ $singleBall = Ball::generateBall(); if ( !isset( $this->content[$singleBall] )){ $this->content[$singleBall] = $singleBall; $i++; } } usort( $this->content, "strnatcmp" ); } public function getContent(){ return $this->content; } public function getCurrentAmount(){ return $this->currentAmount; } } <file_sep><?php class UserBasket extends Basket { protected $maximumAmount = 100; }<file_sep><?php class Ball { const minimumRange = 1; const maximumRange = 999; static function generateBall(){ return mt_rand( self::minimumRange, self::maximumRange ); } } <file_sep><?php class OrdinaryBasket extends Basket { protected $maximumAmount = 10; }
c2d7b68bc776eb8fc3db59368f1e3fda833f828a
[ "Markdown", "PHP" ]
12
PHP
aducin/Balls
7104caa45df4cdcc26590c8a690fa83f61b20c44
709f9ae283dae48d2ababfdb08a01a2c092e2295
refs/heads/master
<repo_name>Klaus-Nyrnberg/emendare<file_sep>/TestProjekt/MainWindow.cs using System; using Gtk; using GLib; public partial class MainWindow: Gtk.Window { Button gtkClickMe; public MainWindow () : base (Gtk.WindowType.Toplevel) { gtkClickMe = new Button (); gtkClickMe.Label = "str"; this.Add (gtkClickMe); foreach (var w in this.Children) { Console.WriteLine (w.Name); } Build (); } protected void OnDeleteEvent (object sender, DeleteEventArgs a) { Application.Quit (); } }
8b9a1f557c2a7d4fd706059f503b6c7a37895068
[ "C#" ]
1
C#
Klaus-Nyrnberg/emendare
8f6487da3158e98fc60a6ef659e7789f8a3c7cf2
912693d2bfff5337a37e38fb9e2ef2d8bebdf73b
refs/heads/master
<repo_name>harlam/php-minimal<file_sep>/src/RouteCollector.php <?php namespace Mfw; /** * Class RouteCollector (with middleware support) * @package Mfw */ class RouteCollector extends \FastRoute\RouteCollector { protected $middlewares = []; /** * @param mixed $httpMethod * @param mixed $route * @param mixed $handler */ public function addRoute($httpMethod, $route, $handler) { $handler = array_merge($this->middlewares, (array)$handler); parent::addRoute($httpMethod, $route, $handler); } /** * @param mixed $prefix * @param callable $callback * @param array $middlewares */ public function addGroup($prefix, callable $callback, array $middlewares = []) { $previousGroupPrefix = $this->currentGroupPrefix; $previousMiddlewares = $this->middlewares; $this->currentGroupPrefix = $previousGroupPrefix . $prefix; $this->middlewares = array_merge($previousMiddlewares, $middlewares); $callback($this); $this->currentGroupPrefix = $previousGroupPrefix; $this->middlewares = $previousMiddlewares; } }<file_sep>/src/Exception/CoreException.php <?php namespace Mfw\Exception; use Exception; class CoreException extends Exception { /** @var array */ protected $context = []; /** * @param array $context * @return CoreException */ public function setContext(array $context): self { $this->context = $context; return $this; } /** * @return array */ public function getContext(): array { return $this->context; } } <file_sep>/src/RequestHandler.php <?php namespace Mfw; use DI\Resolver\ResolverInterface; use Exception; use FastRoute\Dispatcher; use Mfw\Exception\CoreException; use Mfw\Exception\HttpException; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; use Relay\Relay; /** * Class WebApp */ class RequestHandler implements RequestHandlerInterface { /** @var ResolverInterface */ private $resolver; /** @var Dispatcher */ private $dispatcher; /** @var array */ private $middleware = []; /** * @param Dispatcher $dispatcher * @param ResolverInterface $resolver * @param array $middleware */ public function __construct(Dispatcher $dispatcher, ResolverInterface $resolver, array $middleware = []) { $this->resolver = $resolver; $this->dispatcher = $dispatcher; $this->middleware = $middleware; } /** * @param ServerRequestInterface $request * @return ResponseInterface * @throws HttpException * @throws CoreException * @throws Exception */ public function handle(ServerRequestInterface $request): ResponseInterface { $routeInfo = $this->dispatcher->dispatch($request->getMethod(), $request->getUri()->getPath()); switch ($routeInfo[0]) { case Dispatcher::FOUND: $chain = array_merge($this->middleware, (array)$routeInfo[1]); $relay = new Relay($chain, function ($entry) { return is_string($entry) ? $this->resolver->resolve($entry) : $entry; }); $request = $this->buildAttributes($request, $routeInfo[2]); return $relay->handle($request); case Dispatcher::NOT_FOUND: throw new HttpException('Not found', 404); case Dispatcher::METHOD_NOT_ALLOWED: throw new HttpException('Not allowed', 405); default: throw new Exception("Unknown action with code '{$routeInfo[0]}'"); } } /** * @param ServerRequestInterface $request * @param array $attributes * @return ServerRequestInterface */ protected function buildAttributes(ServerRequestInterface $request, array $attributes): ServerRequestInterface { foreach ($attributes as $attribute => $value) { $request = $request->withAttribute($attribute, $value); } return $request; } } <file_sep>/src/Exception/HttpException.php <?php namespace Mfw\Exception; class HttpException extends CoreException { }
1d06931ad217e30a4eccddd0f69317aa39fbc741
[ "PHP" ]
4
PHP
harlam/php-minimal
0f0118087422bd7a3bbf0aa55811a465b8dfc29a
0f3e8f023a696ed48dc6b3f54183fb6482e1c7d8
refs/heads/main
<file_sep># TDOT Some of the work I did for the Tennessee Department of Transportation in the summer of 2021 ## Finding Missing EDL's R script + Data. Comparing the state's different sources of information on Embedded Detection Loops. Looking for those which are in some sources but not others. ## Lane Comparison tool ArcGIS ModelBuilder model. Comparing state's different sources of information on how many lanes are on a given segment of raod <file_sep>library(tidyverse) library(sf) library(tmap) #---------------------------------------------------- #read in data #trims data comes spatial trims <- st_read("data/edls_etrims.shp") #tntimes data read as csv, then converted to spatial. Converted to same crs as trims data (EPSG:2274) tntimes <- read_csv("data/edls_tntimes.csv") %>% st_as_sf(coords = c("Longitude", "Latitude"), crs = 4326) %>% st_transform(st_crs(trims)) %>% rename("station_id" = `Loc ID`) #data from Chris stays as a csv chris <- read_csv("data/edls_chris.csv") #county names and numbers counties <- read_csv("data/County Numbers.csv") #---------------------------------------------------- #CREATING STATION ID IN CHRIS' DATA #adding county numbers to Chris' data to use for id chris <- chris %>% select(c(jj, `Route Feature Description`)) %>% left_join(counties, by = c("jj" = "County Name")) #parsing station number from route feature description chris$station_number <- chris$`Route Feature Description` %>% #matches all digits until the first non digit after the digit #has the effect of matching all digits after # but before some other interrupting character (mostly ], sometimes space or ) str_extract(pattern = '\\d+\\D') %>% #drops the interrupting character from the match before, leaves only the digits we want str_extract(pattern = '\\d+') #creates a new field to store appropriate number of zeroes for station id #first line creates all the zeroes, second two clean them up so they are a string without extra characters chris$zeroes = map(8 - str_length(chris$station_number) - 2, ~rep('0', .)) %>% map(~toString(.)) %>% map(~str_remove_all(., pattern = '\\D+')) #Creates actual station id (county number + zeroes + station number) chris$station_id <- chris$`County Number` %>% paste(chris$zeroes, sep = "") %>% paste(chris$station_number, sep = "") chris <- distinct(chris, station_id, .keep_all = TRUE) #CREATING STATION ID IN TRIMS DATA (basically identical to process for Chris' data) #adding county numbers to TRIMS' data to use for id trims <- trims %>% left_join(counties, by = c("NBR_TENN_C" = "County Name")) #parsing station number from route feature description trims$station_number <- trims$RTE_FEAT_D %>% #matches all digits until the first non digit after the digit #has the effect of matching all digits after # but before some other interrupting character (mostly ], sometimes space or ) str_extract(pattern = '\\d+\\D') %>% #drops the interrupting character from the match before, leaves only the digits we want str_extract(pattern = '\\d+') #creates a new field to store appropriate number of zeroes for station id #first line creates all the zeroes, second two clean them up so they are a string without extra characters trims$zeroes = map(8 - str_length(trims$station_number) - 2, ~rep('0', .)) %>% map(~toString(.)) %>% map(~str_remove_all(., pattern = '\\D+')) #Creates actual station id (county number + zeroes + station number) trims$station_id <- trims$`County Number` %>% paste(trims$zeroes, sep = "") %>% paste(trims$station_number, sep = "") tntimes$exists <- 1 trims$exists <- 1 chris$exists <- 1 #full_join makes a column for each id present in the tables joined #the join is by id and the "exists" columns all get copied over #exists will be equal to 1 for all the tables the id is found in, NA if the id is missing #this line joins the first two tables results_full <- full_join(as.data.frame(tntimes), as.data.frame(trims), by = c("station_id")) %>% #this line joins the last table to the results from the previous two full_join(chris, by = c("station_id")) %>% #this renames the columns to more descriptive names. the join by default just tacks .x and .y onto columns rename(exists.tntimes = exists.x, exists.trims = exists.y, exists.chris = exists) %>% #sort by most recent update in E-TRIMS arrange(desc(UPDT_O2)) %>% distinct() results_full$dist_tntimes_trims <- st_distance(results_full$geometry.x, results_full$geometry.y, by_element = TRUE) #--------------------------------------------------- #makes a nice data frame with only relevant columns to write out pretty_results <- results_full %>% select(c(station_id, exists.tntimes, exists.trims, exists.chris, dist_tntimes_trims, geometry.x, geometry.y, RTE_FEAT_D, UPDT_O2, `Region Nbr.x`)) %>% mutate(more_than_300_ft_apart = as.numeric(dist_tntimes_trims) > 300) %>% mutate(exists.chris = replace_na(exists.chris, 0)) %>% mutate(exists.tntimes = replace_na(exists.tntimes, 0)) %>% mutate(exists.trims = replace_na(exists.trims, 0)) %>% rename(geometry.tntimes = geometry.x) %>% rename(geometry.trims = geometry.y) %>% rename(route.feature.description.trims = `RTE_FEAT_D`) %>% rename(regions = `Region Nbr.x`) #makes a nice-ish data frame with all columns included literally_everything <- results_full %>% mutate(more_than_3000_ft_apart = as.numeric(dist_tntimes_trims) > 3000) %>% mutate(exists.chris = replace_na(exists.chris, 0)) %>% mutate(exists.tntimes = replace_na(exists.tntimes, 0)) %>% mutate(exists.trims = replace_na(exists.trims, 0)) %>% rename(geometry.tntimes = geometry.x) %>% rename(geometry.trims = geometry.y) write_csv(pretty_results, "data/edl_location_validation.csv")
0fa740478838058984055f8e0ea373ac1159ee81
[ "Markdown", "R" ]
2
Markdown
isaac-rand/TDOT
e4c6ddc86623abe8673ae2ea37a4a8e4cbaecc1c
3b96e5030b5829cd7a18d360567023e1f9987fc1
refs/heads/master
<file_sep>#include "bootloader.h" #include "mac.h" #include "infra.h" BYTE GetFlashFlag = 0; BYTE RxBuf[96]={0}; BYTE Buffer[PM_ROW_SIZE*3];//从上位机收到的1536字节 BYTE Parameter[PARAMETER_NUM]=//各个参数的默认值 { 10, //定时上传时间 0x00, //xzy预留 0x00, //xzy预留 5, 0, 0xff, 0xff, //时间段1和灯控选择1 11, 0, 0xff, 0xff, 14, 0, 0xff, 0xff, 17, 0, 0xff, 0xff, 22, 0, 0xff, //五个时间点 0xff, 17, 71, 45, 4, 0x34, //转发地址route_high 0x83, //转发地址route_low }; BInfo SourceAddr; BInfo TacticsAddr; BInfo codeAddr_hot; BInfo codeAddr_cold; BInfo codeAddr_off; void BufferInit(void)// 将所有BUffer填充为FF { WORD jj=0; for(jj=0;jj<96;jj++) { RxBuf[jj]=0xFF; } for(jj=0;jj<PM_ROW_SIZE*3;jj++) { Buffer[jj]=0xFF; } TacticsAddr.Val32=Tactics; codeAddr_hot.Val32=code8000; codeAddr_cold.Val32=code8400; codeAddr_off.Val32=code8800; } void GetAddr(BYTE *addr)//获取PM的地址 { BYTE i_GA; SourceAddr.Val[3]=0x00;//最高字节赋值为0 for(i_GA=0;i_GA<3;i_GA++) { SourceAddr.Val[i_GA]=*addr++; } } void ErasePage(void) //擦除一页 { Erase(SourceAddr.Word.HW,SourceAddr.Word.LW,PM_ROW_ERASE); // 页擦除 } void WritePM(BYTE * ptrData, BInfo SourceAddr) //写程序存储器 { int Size,Size1; BInfo Temp; for(Size = 0,Size1=0; Size < PM_ROW_SIZE; Size++) { Temp.Val[0]=ptrData[Size1+0]; Temp.Val[1]=ptrData[Size1+1]; Temp.Val[2]=ptrData[Size1+2]; Temp.Val[3]=0; Size1+=3; WriteLatch(SourceAddr.Word.HW, SourceAddr.Word.LW,Temp.Word.HW,Temp.Word.LW); // 先写到写锁存器中 if((Size !=0) && (((Size + 1) % 64) == 0)) // 判断是不是正好是一行 { WriteMem(PM_ROW_WRITE); // 执行 行写 操作 } SourceAddr.Val32 = SourceAddr.Val32 + 2; //目标地址加2 指向下一个地址 } } void ReadPM(BYTE * ptrData, BInfo SourceAddr) //读取程序存储器 { int Size; //BInfo Temp; WORD addrOffset; for(Size = 0; Size < PM_ROW_SIZE; Size++) //读取8行数据 { //Temp.Val32 = ReadLatch(SourceAddr.Word.HW, SourceAddr.Word.LW); TBLPAG = ((SourceAddr.Val32 & 0x7F0000)>>16); addrOffset = (SourceAddr.Val32 & 0x00FFFF); asm("tblrdl.b [%1], %0" : "=r"(ptrData[0]) : "r"(addrOffset)); asm("tblrdl.b [%1], %0" : "=r"(ptrData[1]) : "r"(addrOffset + 1)); asm("tblrdh.b [%1], %0" : "=r"(ptrData[2]) : "r"(addrOffset)); /*ptrData[0] = Temp.Val[0]; ptrData[1] = Temp.Val[1]; ptrData[2] = Temp.Val[2];*/ ptrData = ptrData + 3; SourceAddr.Val32 = SourceAddr.Val32 + 2; } } BOOL GetParameters(void) { BYTE i; WORD j; /********************************** 以下是bootloader.c加载参数有关有关 **********************************/ ReadPM(Buffer,(BInfo)TacticsAddr);//从Flash中读出到数组RE中 for(i=0;i<=PARAMETER_NUM;i++) { if(Buffer[i] != 0xFF) { Parameter[i]=Buffer[i]; GetFlashFlag = 0x40;//已经获取到Flash中控制信息 } } BufferInit(); /********************************** 以下是空调有关 **********************************/ ReadPM(Buffer,(BInfo)codeAddr_hot);//从Flash中读出到数组RE中 if((Buffer[0] != 0xFF)&&(Buffer[1] != 0xFF)) sizecode_hot=((WORD)Buffer[1]<<8&0xff00)|((WORD)Buffer[0]&0x00ff); else return 0; for(j=1;j<=sizecode_hot;j++) { codearray_hot[j]=((WORD)Buffer[j*2+1]<<8&0xff00)|((WORD)Buffer[j*2+0]&0x00ff); } BufferInit(); ReadPM(Buffer,(BInfo)codeAddr_cold);//从Flash中读出到数组RE中 if((Buffer[0] != 0xFF)&&(Buffer[1] != 0xFF)) sizecode_cold=((WORD)Buffer[1]<<8&0xff00)|((WORD)Buffer[0]&0x00ff); else return 0; for(j=1;j<=sizecode_cold;j++) { codearray_cold[j]=((WORD)Buffer[j*2+1]<<8&0xff00)|((WORD)Buffer[j*2+0]&0x00ff); } BufferInit(); ReadPM(Buffer,(BInfo)codeAddr_off);//从Flash中读出到数组RE中 if((Buffer[0] != 0xFF)&&(Buffer[1] != 0xFF)) sizecode_off=((WORD)Buffer[1]<<8&0xff00)|((WORD)Buffer[0]&0x00ff); else return 0; for(j=1;j<=sizecode_off;j++) { codearray_off[j]=((WORD)Buffer[j*2+1]<<8&0xff00)|((WORD)Buffer[j*2+0]&0x00ff); } BufferInit(); IEC0bits.IC1IE = 0; IEC0bits.T3IE = 0; return 1; }<file_sep>#ifndef _NVM_FLASH_H #define _NVM_FLASH_H #include "common.h" #include "zigbee.h" #include "mcu.h" #include "flash.h" #include "FlashMM.h" #define IEEE_VALID_CODE 0x9968 #define FREQIndex 0x4452 #define TXPOWERIndex 0x3658 #define BAUDRATEIndex 0x7639 /**********************************************************************************************/ //利用程序存储器作为存储时的操作函数 /**********************************************************************************************/ //定义存储位置,逻辑扇区号 #define ConstIEEEAddrPN 0 #define ConstMacAddrPN 1 #define ConstStatusAddrPN 2 #define ConstCoordAddrPN 3 #define ConstRTUAddrPN 4 #define ConstPhyFreqAddrPN 5 #define ConstPhyBaudRateAddrPN 6 #define ConstPhyTxPowerAddrPN 7 #define CntNeighborTabNO 8 //存储分配的IEEE地址 void PutIEEEAddrInfo(WORD Indication,const LONG_ADDR *IEEEAddr); //读取存储地址标志 BOOL GetIEEEIndication(WORD *Indication); //读取自动获得地址信息 BOOL GetIEEEAddr(LONG_ADDR *IEEEAddr); //读取状态 BOOL GetMACStatus(void); //存储MAC层状态 void PutMACStatus(void); //读出网络PANId BOOL GetMACPANId(void); //读出短地址 BOOL GetMACShortAddr(void); //读出长地址 BOOL GetMACLongAddr(void); //存储MAC地址 void PutMACAddr(void); //获取协调器信息 BOOL GetCoordDescriptor(void); //存储协调器信息 void PutCoordDescriptor(void); //获取信道 BOOL GetPHYFreq(WORD *Index); //存储信道 void PutPHYFreq(WORD FreqIndex); //获取发射功率 BOOL GetPHYTxPower(WORD *Index); //存储发射功率 void PutPHYTxPower(WORD TxPowerIndex); //获取波特率 BOOL GetPHYBaudRate(WORD *Index); //存储波特率 void PutPHYBaudRate(WORD BaudRateIndex); #endif <file_sep>#include "led.h" #include "mac.h" #include "common.h" #include "bootloader.h" #include "Mac.H" WORD WenduSave[10]={0,0,0,0,0,0,0,0,0,0}; BYTE WenduCnt=0; WORD tem_wendu; extern BYTE Parameter[PARAMETER_NUM]; extern BYTE dark; extern BYTE Type;//系统查询到系统消息TEM_SENT_REQ时,根据全局变量Type进行数据的回复 BYTE FLAG; extern IO_INFO AD_Value[]; void Delay_nus(WORD i) { while(--i); } void DS18B20_Reset(void) { WORD j=0; WORD k=0; DQ_LOW; Delay_nus(500); DQ_HIGH; Delay_nus(60); while(DQ) { j++; if(j>1000)break;//防死机 } while(!DQ) { k++; if(k>1000)break;//防死机 } } void DS18B20_Write_Byte(BYTE Data) { BYTE i; for(i=0;i<8;i++) { DQ_LOW; Delay_nus(10); if(Data&0x01) DQ_HIGH; Delay_nus(40); DQ_HIGH; Delay_nus(2); Data>>=1; } } BYTE DS18B20_Read_Byte(void) { BYTE i,Data; for(i=0;i<8;i++) { Data>>=1; DQ_LOW; Delay_nus(1); DQ_HIGH; Delay_nus(15); if(DQ) Data|=0x80; Delay_nus(45); } return Data; } WORD DS18B20_Get_Temp(void) { WORD temp1,temp2,temperature; DS18B20_Reset(); DS18B20_Write_Byte(0xCC); DS18B20_Write_Byte(0x44); DS18B20_Reset(); DS18B20_Write_Byte(0xCC); DS18B20_Write_Byte(0xBE); temp1=DS18B20_Read_Byte(); temp2=DS18B20_Read_Byte(); if(temp2&0xF0) { FLAG=1; temperature=(temp2<<8)|temp1; temperature=~temperature+1; temperature*=0.625;//扩大了10倍 } else { temperature=(temp2<<8)|temp1; temperature*=0.625; FLAG=0; } return temperature; } void GET_wendu(void) { BYTE a,c=0; WORD i = 0; for(a=0;a<9;a++) { WenduSave[a]=WenduSave[a+1]; } WenduSave[9]=DS18B20_Get_Temp(); for(a=0;a<9;a++) { if( ((WenduSave[a]-WenduSave[a+1])< 50) || ((WenduSave[a]-WenduSave[a+1])>-50)) { c++; i=i+WenduSave[a]; } } if(c!=0) { i=i/c; AD_Value[0].val1[0]=i&0x00ff; AD_Value[0].val1[1]=(i&0xff00)>>8; AD_Value[0].type=0x81; if(FLAG==1) //flag为正,则为0x01 { AD_Value[0].type=0x81; } else { AD_Value[0].type=0x01; } } } void Condi_Control(void) { } void TemTask(void) { BYTE i; BYTE cSize = 0; BYTE cPtrTx[50]; NODE_INFO macAddr; i=emWaitMesg(TEM_SENT_REQ,RealTimeMesg,0,0); if(i==1) { macAddr.AddrMode = MAC_DST_SHORT_ADDR; macAddr.PANId.nVal = PANDescriptor.CoordPANId.nVal; macAddr.ShortAddr.nVal = PANDescriptor.CoordShortAddr.nVal; MACPutHeader(&macAddr,MAC_FRAME_DATA | MAC_INTRA_PAN_YES | MAC_ACK_NO); LATBbits.LATB1=0;//读取18B20的必备步骤 tem_wendu=DS18B20_Get_Temp(); cPtrTx[cSize++]=0x02; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x01; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=30; //数据总长度30=0x1E cPtrTx[cSize++]=macPIB.macPANId.nVal>>8; cPtrTx[cSize++]=macPIB.macPANId.nVal; cPtrTx[cSize++]=macPIB.macShortAddr.nVal>>8; cPtrTx[cSize++]=macPIB.macShortAddr.nVal; cPtrTx[cSize++]=0x85; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x01; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=tem_wendu>>8; cPtrTx[cSize++]=tem_wendu; //温度数据 cPtrTx[cSize++]=0x40; //控制继电器状态 cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=(BYTE)(AD_Value[1].Value>>8); //反馈为高电平表示上电 cPtrTx[cSize++]=!(BYTE)(AD_Value[1].Value&0x00FF); cPtrTx[cSize++]=0x43; //电灯控制继电器状态 cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=(BYTE)(AD_Value[4].Value>>8); //反馈为低电平表示上电 cPtrTx[cSize++]=!(BYTE)(AD_Value[4].Value&0x00FF); MACPutTxBuffer(cPtrTx,cSize); MACTransmitPacket(); } i=emWaitMesg(NET_ADDR_ACK,RealTimeMesg,0,0); if(i==1) { macAddr.AddrMode = MAC_DST_SHORT_ADDR; macAddr.PANId.nVal = PANDescriptor.CoordPANId.nVal; macAddr.ShortAddr.nVal = PANDescriptor.CoordShortAddr.nVal; MACPutHeader(&macAddr,MAC_FRAME_DATA | MAC_INTRA_PAN_YES | MAC_ACK_NO); cPtrTx[cSize++]=0xaa; cPtrTx[cSize++]=0xbb; cPtrTx[cSize++]=0xcc; cPtrTx[cSize++]=macPIB.macPANId.nVal>>8; cPtrTx[cSize++]=macPIB.macPANId.nVal; cPtrTx[cSize++]=macPIB.macShortAddr.nVal>>8; cPtrTx[cSize++]=macPIB.macShortAddr.nVal; MACPutTxBuffer(cPtrTx,cSize); MACTransmitPacket(); CoordID[0] = 0; CoordID[1] = 0; } i=emWaitMesg(TIME_DATA_REQ,RealTimeMesg,0,0); if(i==1) { macAddr.AddrMode = MAC_DST_SHORT_ADDR; macAddr.PANId.nVal = PANDescriptor.CoordPANId.nVal; macAddr.ShortAddr.nVal = PANDescriptor.CoordShortAddr.nVal; MACPutHeader(&macAddr,MAC_FRAME_DATA | MAC_INTRA_PAN_YES | MAC_ACK_NO); cPtrTx[cSize++]=0x0d; cPtrTx[cSize++]=CoordID[0]; cPtrTx[cSize++]=CoordID[1]; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x01; cPtrTx[cSize++]=CurrentSysTime.year; cPtrTx[cSize++]=CurrentSysTime.month; cPtrTx[cSize++]=CurrentSysTime.day; cPtrTx[cSize++]=CurrentSysTime.hour; cPtrTx[cSize++]=CurrentSysTime.minute; cPtrTx[cSize++]=CurrentSysTime.second; cPtrTx[cSize++]=macPIB.macShortAddr.nVal>>8; cPtrTx[cSize++]=macPIB.macShortAddr.nVal; MACPutTxBuffer(cPtrTx,cSize); MACTransmitPacket(); CoordID[0] = 0; CoordID[1] = 0; } CurrentTaskWait(); SchedTask(); } <file_sep>#include "mcu.h" //本文档的功能是把与硬件有关的初始化都再次调用完成 //对CC2500的通信接口初始化 void SPIInit(void) { TRISBbits.TRISB15=0; //PA TRISBbits.TRISB14=0; //SI TRISBbits.TRISB13=0; //SCLK TRISBbits.TRISB12=1; //SO TRISBbits.TRISB11=1;//定义为GDO2输入 TRISBbits.TRISB10=1; //GDO0引脚,外部中断 TRISBbits.TRISB9=0; //CS TRISBbits.TRISB2=0; //LNA } void SPIInitCC2500off(void) { TRISBbits.TRISB15=0; //PA TRISBbits.TRISB14=0; //SI TRISBbits.TRISB13=0; //SCLK TRISBbits.TRISB12=0; //SO TRISBbits.TRISB11=0;//定义为GDO2输入 TRISBbits.TRISB10=0; //GDO0引脚,外部中断 TRISBbits.TRISB9=0; //CS TRISBbits.TRISB2=0; //LNA } //使用定时器1的初始化 void InitTicks(void) { INTCON1bits.NSTDIS=0;//1禁止中断嵌套 IFS0bits.T1IF=0;//清除定时器中断标志位 IEC0bits.T1IE=1;//定时器1允许位 //设置定时器1的优先级为7,最高优先级 IPC0bits.T1IP=7; T1CONbits.TON=0;//关闭定时器,开始设置寄存器 T1CONbits.TCS=0;//内部时钟源 T1CONbits.TSIDL=0;//空闲模式下继续工作 T1CONbits.TGATE=0; T1CONbits.TSYNC=0; //64分频 T1CONbits.TCKPS1=1; T1CONbits.TCKPS0=0; //内部晶振是8MHZ,Fcy=Fosc/2 //准备定时10ms=x/(8MHZ/2/64) TMR1=0x0000; PR1=0x0271; T1CONbits.TON=1;//开启定时器 } //AD采样有关的初始化 void ADInitSetup(void) { AD1CON2bits.VCFG=0; //参考电压源 AD1CON2&=0xEFFF; //置位 AD1CON2bits.CSCNA=0; //输入扫描 AD1CON2bits.SMPI=0; //采样1次中断 AD1CON2bits.BUFM=0; //缓冲器模式 AD1CON2bits.ALTS=0; //MUX选择 AD1CON3bits.ADRC=0; //时钟源;1 = A/D 内部的RC 时钟;0 = 时钟由系统时钟产生 AD1CON3bits.SAMC=2; //自动采样时间 AD1CON3bits.ADCS=3; //转换时钟选择位Tad,时钟分频器 AD1PCFG=0xF9FD; //1,9,10通道 AD1CON1bits.FORM=0; //输出整数 AD1CON1bits.SSRC=0; //7代表内部计数器结束采样并启动转换(自动转换);0为清零SAMP 位结束采样并启动转换 AD1CON1bits.ADSIDL=1; //空闲模式停止 AD1CON1bits.ASAM=0; //0为SAMP 位置1 时开始采样;1为转换完成后自动启动,SAMP 位自动置1 AD1CON1bits.ADON=1; //启动 } //输出控制引脚初始化 void DeviceInitSetup(void) { TRISAbits.TRISA3=0; TRISAbits.TRISA4=0; } void UnlockREG(void) { asm("push w1"); asm("push w2"); asm("push w3"); asm("mov #OSCCON, w1"); asm("mov #0x46, w2"); asm("mov #0x57, w3"); asm("mov.b w2, [w1]"); asm("mov.b w3, [w1]"); asm("bclr OSCCON, #6"); asm("pop w3"); asm("pop w2"); asm("pop w1"); } void LockREG(void) { asm("push w1"); asm("push w2"); asm("push w3"); asm("mov #OSCCON, w1"); asm("mov #0x46, w2"); asm("mov #0x57, w3"); asm("mov.b w2, [w1]"); asm("mov.b w3, [w1]"); asm("bset OSCCON, #6"); asm("pop w3"); asm("pop w2"); asm("pop w1"); } void emDint(WORD *prio) { *prio=SRbits.IPL; INTCON1bits.NSTDIS=0; SRbits.IPL=7; } void emEint(WORD *prio) { INTCON1bits.NSTDIS=0; SRbits.IPL=*prio; //其它中断源的优先级要设置为7 INTCON1bits.NSTDIS=1; } void LEDInitSetup(void) { TRISBbits.TRISB8=0; //初始化LED P1引脚 TRISBbits.TRISB7=0; //初始化LED P2引脚 PORTBbits.RB8=1; PORTBbits.RB7=1; } void LEDBlinkYellow(void) { PORTBbits.RB8=0; Delay(0x3000); PORTBbits.RB8=1; //方向不同,到底引脚的设置不同 } void LEDBlinkRed(void) { PORTBbits.RB7=0; Delay(0x3000); PORTBbits.RB7=1; } <file_sep> #include "Tick.h" #include "driver.h" BYTE cDebug[5]; void RFWriteStrobe(BYTE addr) { CS=0; //Csn while(RF_CHIP_RDYn); //Using SPI SPIPut(addr|CMD_WRITE); //Strobe CS=1; } void RFWriteReg(BYTE addr, BYTE value) { CS=0; while(RF_CHIP_RDYn); SPIPut(addr|CMD_WRITE); //Address SPIPut(value); //Value CS=1; } BYTE RFReadReg(BYTE addr) { BYTE value,cCmd; CS=0; while(RF_CHIP_RDYn); cCmd = addr|CMD_READ; SPIPut(cCmd); value = SPIGet(); CS=1; return value; } BYTE RFGetStatus(BYTE addr) { BYTE value; CS=0; while(RF_CHIP_RDYn); SPIPut(addr|CMD_BURST_READ); value = SPIGet(); CS=1; return value; } void RFWriteBurstReg(BYTE addr, BYTE *pWriteValue, BYTE size) { BYTE i; CS=0; while(RF_CHIP_RDYn); SPIPut(addr|CMD_BURST_WRITE); //Address for(i=0; i<size; i++) { SPIPut(*pWriteValue); pWriteValue++; } CS=1; } void RFReadBurstReg(BYTE addr, BYTE *pReadValue, BYTE size) { BYTE i; CS=0; while(RF_CHIP_RDYn); SPIPut(addr|CMD_BURST_READ); //Address for(i=0; i<size; i++) { *pReadValue = SPIGet(); pReadValue++; } CS=1; } BYTE RFReadRxFIFO(void) { BYTE value; CS=0; while(RF_CHIP_RDYn); SPIPut(REG_TRXFIFO|CMD_BURST_READ); //Address value=SPIGet(); CS=1; return value; } void RFWriteTxFIFO(BYTE *pTxBuffer,BYTE size) { BYTE i; CS=0; while(RF_CHIP_RDYn); SPIPut(REG_TRXFIFO|CMD_BURST_WRITE); //Address for(i=0;i<size;i++) { SPIPut(pTxBuffer[i]); } CS=1; } void RFReset(void) //复位过后,内部寄存器和状态都回到默认 { SCLK=1; SO=0; //以上两条指令用作防止潜在的错误出现 CS=1; Delay(30); CS=0; //CS先低后高 Delay(30); CS=1; //高保持大约40us Delay(45); CS=0; //拉低,等待晶振稳定后发送复位命令 while(RF_CHIP_RDYn); //稳定 SPIPut(CMD_WRITE|STROBE_SRES);// 发送复位命令 while(RF_CHIP_RDYn); //再次等待晶振稳定 CS=1; //结束此次操作 } void RFClearRxBuffer(void) { RFWriteStrobe(STROBE_SIDLE); RFWriteStrobe(STROBE_SFRX); RFWriteStrobe(STROBE_SRX); } void RFClearTxBuffer(void) { RFWriteStrobe(STROBE_SIDLE); RFWriteStrobe(STROBE_SFTX); RFWriteStrobe(STROBE_SRX); } void RFSetBaudRate(BYTE BaudRate) { switch (BaudRate) { case 0x01: //通讯速率为2.4K //频率校正 RFWriteReg(REG_FSCTRL1, 0x08); // Freq synthesizer control. RFWriteReg(REG_FSCTRL0, 0x00); // Freq synthesizer control. //通信频率设定,载波频率 2433 MHz RFWriteReg(REG_FREQ2, 0x5D); // Freq control word, high byte RFWriteReg(REG_FREQ1, 0x93); // Freq control word, mid byte. RFWriteReg(REG_FREQ0, 0xB1); // Freq control word, low byte. RFWriteReg(REG_MDMCFG4, 0x86); // Modem configuration. RFWriteReg(REG_MDMCFG3, 0x83); // Modem configuration. RFWriteReg(REG_MDMCFG2, 0x03); // Modem configuration. RFWriteReg(REG_MDMCFG1, 0x22); // Modem configuration. RFWriteReg(REG_MDMCFG0, 0xF8); // Modem configuration. //设置通信速率和调制方式 RFWriteReg(REG_DEVIATN, 0x44); // Modem dev (when FSK mod en) RFWriteReg(REG_MCSM1, 0x3F); //始终出于接收状态 RFWriteReg(REG_MCSM0, 0x18); //MainRadio Cntrl State Machine RFWriteReg(REG_AGCCTRL2, 0x03); // AGC control. RFWriteReg(REG_AGCCTRL1, 0x40); // AGC control. RFWriteReg(REG_AGCCTRL0, 0x91); // AGC control. RFWriteReg(REG_FREND1, 0x56); // Front end RX configuration. RFWriteReg(REG_FREND0, 0x10); // Front end RX configuration. RFWriteReg(REG_FOCCFG, 0x16); // Freq Offset Compens. Config RFWriteReg(REG_BSCFG, 0x6C); // Bit synchronization config. RFWriteReg(REG_FSCAL3, 0xA9); // Frequency synthesizer cal. RFWriteReg(REG_FSCAL2, 0x0A); // Frequency synthesizer cal. RFWriteReg(REG_FSCAL1, 0x00); // Frequency synthesizer cal. RFWriteReg(REG_FSCAL0, 0x11); // Frequency synthesizer cal. RFWriteReg(REG_FSTEST, 0x59); // Frequency synthesizer cal. RFWriteReg(REG_TEST2, 0x88); // Various test settings. RFWriteReg(REG_TEST1, 0x31); // Various test settings. RFWriteReg(REG_TEST0, 0x0B); // Various test settings. CLR_WDT(); break; case 0x02: //通讯速率为10K //频率校正 RFWriteReg(REG_FSCTRL1, 0x06); // Freq synthesizer control. RFWriteReg(REG_FSCTRL0, 0x00); // Freq synthesizer control. //通信频率设定,载波频率 2433 MHz RFWriteReg(REG_FREQ2, 0x5D); // Freq control word, high byte RFWriteReg(REG_FREQ1, 0x93); // Freq control word, mid byte. RFWriteReg(REG_FREQ0, 0xB1); // Freq control word, low byte. RFWriteReg(REG_MDMCFG4, 0x78); // Modem configuration. RFWriteReg(REG_MDMCFG3, 0x93); // Modem configuration. RFWriteReg(REG_MDMCFG2, 0x03); // Modem configuration. RFWriteReg(REG_MDMCFG1, 0x22); // Modem configuration. RFWriteReg(REG_MDMCFG0, 0xF8); // Modem configuration. //设置通信速率和调制方式 RFWriteReg(REG_DEVIATN, 0x44); // Modem dev (when FSK mod en) RFWriteReg(REG_MCSM1, 0x3F); //始终出于接收状态 RFWriteReg(REG_MCSM0, 0x18); //MainRadio Cntrl State Machine RFWriteReg(REG_AGCCTRL2, 0x43); // AGC control. RFWriteReg(REG_AGCCTRL1, 0x40); // AGC control. RFWriteReg(REG_AGCCTRL0, 0x91); // AGC control. RFWriteReg(REG_FREND1, 0x56); // Front end RX configuration. RFWriteReg(REG_FREND0, 0x10); // Front end RX configuration. RFWriteReg(REG_FOCCFG, 0x16); // Freq Offset Compens. Config RFWriteReg(REG_BSCFG, 0x6C); // Bit synchronization config. RFWriteReg(REG_FSCAL3, 0xA9); // Frequency synthesizer cal. RFWriteReg(REG_FSCAL2, 0x0A); // Frequency synthesizer cal. RFWriteReg(REG_FSCAL1, 0x00); // Frequency synthesizer cal. RFWriteReg(REG_FSCAL0, 0x11); // Frequency synthesizer cal. RFWriteReg(REG_FSTEST, 0x59); // Frequency synthesizer cal. RFWriteReg(REG_TEST2, 0x88); // Various test settings. RFWriteReg(REG_TEST1, 0x31); // Various test settings. RFWriteReg(REG_TEST0, 0x0B); // Various test settings. CLR_WDT(); break; case 0x03: //通信速率为250K //通信频率设定,载波频率 2433 MHz RFWriteReg(REG_FREQ2, 0x5D); // Freq control word, high byte RFWriteReg(REG_FREQ1, 0x93); // Freq control word, mid byte. RFWriteReg(REG_FREQ0, 0xB1); // Freq control word, low byte. //频率校正 RFWriteReg(REG_FSCTRL1, 0x07); // Freq synthesizer control. RFWriteReg(REG_FSCTRL0, 0x00); // Freq synthesizer control. RFWriteReg(REG_MDMCFG4, 0x2D); // Modem configuration. RFWriteReg(REG_MDMCFG3, 0x3B); // Modem configuration. RFWriteReg(REG_MDMCFG2, 0x73); // Modem configuration. RFWriteReg(REG_MDMCFG1, 0x22); // Modem configuration. RFWriteReg(REG_MDMCFG0, 0xF8); // Modem configuration. //设置通信速率和调制方式 RFWriteReg(REG_DEVIATN, 0x01); // Modem dev (when FSK mod en) RFWriteReg(REG_MCSM1, 0x3F); //始终出于接收状态 RFWriteReg(REG_MCSM0, 0x18); //MainRadio Cntrl State Machine RFWriteReg(REG_AGCCTRL2, 0xC7); // AGC control. RFWriteReg(REG_AGCCTRL1, 0x00); // AGC control. RFWriteReg(REG_AGCCTRL0, 0xB2); // AGC control. RFWriteReg(REG_FREND1, 0xB6); // Front end RX configuration. RFWriteReg(REG_FREND0, 0x10); // Front end RX configuration. RFWriteReg(REG_FOCCFG, 0x1D); // 频率偏移补偿 RFWriteReg(REG_BSCFG, 0x1C); // 位同步设置 RFWriteReg(REG_FSCAL3, 0xEA); // Frequency synthesizer cal. RFWriteReg(REG_FSCAL2, 0x0A); // Frequency synthesizer cal. RFWriteReg(REG_FSCAL1, 0x00); // Frequency synthesizer cal. RFWriteReg(REG_FSCAL0, 0x11); // Frequency synthesizer cal. RFWriteReg(REG_FSTEST, 0x59); // Frequency synthesizer cal. RFWriteReg(REG_TEST2, 0x88); // Various test settings. RFWriteReg(REG_TEST1, 0x31); // Various test settings. RFWriteReg(REG_TEST0, 0x0B); // Various test settings. CLR_WDT(); break; case 0x04: //通讯速率为500K //通信频率设定,载波频率 2433 MHz RFWriteReg(REG_FREQ2, 0x5D); // Freq control word, high byte RFWriteReg(REG_FREQ1, 0x93); // Freq control word, mid byte. RFWriteReg(REG_FREQ0, 0xB1); // Freq control word, low byte. //频率校正 RFWriteReg(REG_FSCTRL1, 0x10); // Freq synthesizer control. RFWriteReg(REG_FSCTRL0, 0x00); // Freq synthesizer control. RFWriteReg(REG_MDMCFG4, 0x0E); // Modem configuration. RFWriteReg(REG_MDMCFG3, 0x3B); // Modem configuration. RFWriteReg(REG_MDMCFG2, 0x73); // Modem configuration. RFWriteReg(REG_MDMCFG1, 0x42); // Modem configuration. RFWriteReg(REG_MDMCFG0, 0xF8); // Modem configuration. //设置通信速率和调制方式 RFWriteReg(REG_DEVIATN, 0x00); // Modem dev (when FSK mod en) RFWriteReg(REG_MCSM1, 0x3F); //始终出于接收状态 RFWriteReg(REG_MCSM0, 0x18); //MainRadio Cntrl State Machine RFWriteReg(REG_FOCCFG, 0x1D); // Freq Offset Compens. Config RFWriteReg(REG_BSCFG, 0x1C); // Bit synchronization config. RFWriteReg(REG_AGCCTRL2, 0xC7); // AGC control. RFWriteReg(REG_AGCCTRL1, 0x40); // AGC control. RFWriteReg(REG_AGCCTRL0, 0xB0); // AGC control. RFWriteReg(REG_FREND1, 0xB6); // Front end RX configuration. RFWriteReg(REG_FREND0, 0x10); // Front end RX configuration. RFWriteReg(REG_FSCAL3, 0xEA); // Frequency synthesizer cal. RFWriteReg(REG_FSCAL2, 0x0A); // Frequency synthesizer cal. RFWriteReg(REG_FSCAL1, 0x00); // Frequency synthesizer cal. RFWriteReg(REG_FSCAL0, 0x19); // Frequency synthesizer cal. RFWriteReg(REG_FSTEST, 0x59); // Frequency synthesizer cal. RFWriteReg(REG_TEST2, 0x88); // Various test settings. RFWriteReg(REG_TEST1, 0x31); // Various test settings. RFWriteReg(REG_TEST0, 0x0B); // Various test settings. CLR_WDT(); break; default: break; } } void RFInitSetup(void) { WORD prio; //保存中断寄存器的值 emDint(&prio); //首先要复位 RFReset(); //延时一下 Delay(20); //改变一下方式,GDO0只用作接收,GDO2用作检测载波CS RFWriteReg(REG_IOCFG2, 0x0E); // 高电平说明是有载波 RFWriteReg(REG_IOCFG0, 0x06); // GDO0 用作接收. RFWriteReg(REG_PKTLEN, 0x3F); // Packet length,最大是64字节加上长度共64字节 RFWriteReg(REG_PKTCTRL1, 0x0C); // CRC校验失败,自动清除缓冲区,包含RSSI和CRC校验码 //地址校验,0x00和0xFF是广播地址 RFWriteReg(REG_PKTCTRL0, 0x05); // 可变长度的数据报 RFWriteReg(REG_ADDR, 0x00); // ID号已经不起作用,地址辨识关闭 //默认是通信速率10K RFSetBaudRate(1); //默认信道是0x00 RFSetChannel(0x00); //默认发射功率是0xFE RFSetTxPower(0xFF); cDebug[0]=RFReadReg(REG_IOCFG2); cDebug[1]=RFReadReg(REG_IOCFG0); cDebug[2]=RFReadReg(REG_PKTLEN); cDebug[3]=RFReadReg(REG_PKTCTRL1); Nop(); CLR_WDT(); emEint(&prio); } BYTE RFDetectEnergy(void) { BYTE cVal,cRssi;//RSSI的计算方法 WORD prio; emDint(&prio); cVal=RFReadReg(CMD_READ|REG_RSSI); emEint(&prio); if(cVal>=128) cRssi=(cVal-256)/2-RSSI_OFFSET; else cRssi=cVal/2-RSSI_OFFSET; return cRssi; } void RFSetChannel(BYTE channel) { WORD prio; emDint(&prio); RFWriteStrobe(STROBE_SIDLE); //先转成接收状态 RFWriteReg(CMD_WRITE|REG_CHANNR,channel);//信道设置 //接收状态啊 RFWriteStrobe(STROBE_SIDLE); RFWriteStrobe(STROBE_SFRX); RFWriteStrobe(STROBE_SRX); emEint(&prio); } void RFSetTxPower(BYTE power) { WORD prio; emDint(&prio); RFWriteBurstReg(REG_PATABLE,&power,1);//功率设置 emEint(&prio); } void RFSetTRxState(RF_TRX_STATE state) { WORD prio; emDint(&prio); switch (state) { case RF_TRX_RX: RFWriteStrobe(STROBE_SIDLE); RFWriteStrobe(STROBE_SRX); //接收状态 break; case RF_TRX_OFF: RFWriteStrobe(STROBE_SIDLE); RFWriteStrobe(STROBE_SXOFF);//射频关闭 break; case RF_TRX_IDLE: RFWriteStrobe(STROBE_SIDLE);//空闲状态 break; case RF_TRX_TX: RFWriteStrobe(STROBE_SIDLE); RFWriteStrobe(STROBE_STX); //发射状态 break; default: break; } emEint(&prio); } RF_TRX_STATE RFGetTRxState(void) { BYTE cVal,cState; WORD prio; emDint(&prio); cVal=RFGetStatus(REG_MARCSTATE)&0x1F; emEint(&prio); switch (cVal) { case 0x01:cState=RF_TRX_IDLE;break; case 0x02:cState=RF_TRX_OFF;break; case 0x0D:cState=RF_TRX_RX;break; case 0x13: cState=RF_TRX_TX;break; default:cState=0xFF;break; } return cState; } void RFDetectStatus(void) { BYTE cState; WORD prio; emDint(&prio); cState=RFGetStatus(REG_MARCSTATE)&0x1F; emEint(&prio); CLR_WDT(); //喂狗,防止正常情况进入复位 if(cState==0x11)//接收溢出 { RFWriteStrobe(STROBE_SFRX); RFWriteStrobe(STROBE_SRX); } else if(cState==0x16)//发送溢出 { RFWriteStrobe(STROBE_SFTX); RFWriteStrobe(STROBE_SRX); } else if(cState==0x01)//空闲状态 { RFWriteStrobe(STROBE_SRX);//如果空闲状态转到接收状态 } else if(cState==0x00)//睡眠状态 { RFWriteStrobe(STROBE_SIDLE); RFWriteStrobe(STROBE_SRX); } else if(cState==0x0D)//接收状态 { Nop(); Nop(); } } BOOL RFTranmitByCSMA(void) { BYTE status; WORD prio; BOOL bSucceed=TRUE; DWORD dwStartTick; LATBbits.LATB2=0; //LNA LATBbits.LATB15=1; //PA //Delay(0x5000); RFSetTRxState(RF_TRX_RX); RFDint(); emDint(&prio); status=RFGetStatus(REG_PKTSTATUS)&0x10; //取出CCA位0001 0000 emEint(&prio); dwStartTick=GetTicks(); while(!status)//cca is not clear { if(DiffTicks(dwStartTick,GetTicks())>50)//超时////ZXY MODIFIED { RFSetTRxState(RF_TRX_RX); break; } emDint(&prio); status=RFGetStatus(REG_PKTSTATUS)&0x10; emEint(&prio); Delay(100); } dwStartTick=GetTicks(); RFSetTRxState(RF_TRX_TX); while(!RF_GDO0)//等待发送成功 { if(DiffTicks(dwStartTick,GetTicks())>50)//ZXY MODIFIED { RFSetTRxState(RF_TRX_RX); bSucceed=FALSE; break; } } dwStartTick=GetTicks(); while(bSucceed && RF_GDO0) { if(DiffTicks(dwStartTick,GetTicks())>50)//ZXY MODIFIED { RFSetTRxState(RF_TRX_RX); bSucceed=FALSE; break; } } CLR_WDT(); //喂狗,防止正常情况进入复位 RFEint(); //打开接收中断,并清除引发送引起的中断 if(bSucceed) { LEDBlinkYellow(); LATBbits.LATB15=0; //PA LATBbits.LATB2=1; //LNA return TRUE; } else { emDint(&prio); RFClearTxBuffer(); emEint(&prio); return FALSE; } } <file_sep>#include "mac.h" #include "timeds.h" #include "bootloader.h" #include "common.h" #include "infra.h" #include "Loc.h" //定位变量 BYTE Loc_Buffer[20]; WORD distance_Buffer[20]; BYTE Loc_i=35,Loc_j=0; BYTE Loc_Times=0; BYTE Type = 0; //系统查询到系统消息TEM_SENT_REQ时,根据全局变量Type进行数据的回复(本版本已弃用)) extern BYTE infrared_correct; //定义协调器列表大小 #define ConstCoordQueSize 2 extern IO_INFO AD_Value[IO_NUM]; BYTE CoordID[2]={0,0}; static BYTE PreviousRxmacDSN[4] = {0xff,0xff,0xff,0xff}; BYTE Route_flag = 0; //0表示本地;1表示协调器;2表示转发目的节点;3表示广播 /* 目前关于Mac层Flash中的内容从地址0X9000开始。 0X9000~0X907E存放的是节点的长地址 0X9080~0X90FE存放的节点的MAC层属性,也包括长地址。 0X9100~0X91AE存放的是节点的状态 0X9280~0X92FE存放的是所属网络协调器的相关信息 */ //用于自组网的变量 BYTE JoinNwkIndction = 0;//可以申请入网的标志位。 //BYTE RssiLevel = 180;//通过这个值节点判断链路质量,然后选择加入网络 BYTE RssiLevel = 160;//通过这个值节点判断链路质量,然后选择加入网络 //定义基本的全局变量 MAC_PIB macPIB; //用于记录mac层的PIB属性 MAC_STATUS macStatus; //记录MAC状态 CFG_RSP_BUFFER MACCfgRspBuf; CFG_RSP_SHARE_BUFFER MACCfgRspSharBuf; BYTE MACBuffer[ConstMacBufferSize]; extern PHY_PIB phyPIB; //用来临时存储发送的数据,用来重发 MAC_TX_QUEUE TxFrameQue[ConstMacTxQueSize]; //用于形成一个完整的接收数据帧 MAC_RX_FRAME macCurrentRxFrame; //用于做发送数据的缓冲区 MAC_TX_BUFFER TxBuffer; //定义一个协调器列表 PAN_DESCRIPTOR CoordQue[ConstCoordQueSize]; //定义网络信息 PAN_DESCRIPTOR PANDescriptor; //初始化的时候可能需要更改的是节点的标示 void MACInitSetup(void) { BYTE i; //初始化 for(i=0;i<ConstMacTxQueSize;i++) { TxFrameQue[i].Flags.bits.bInUse=0; } MACCfgRspBuf.Ptr=0; MACCfgRspSharBuf.bReady=0; MACCfgRspSharBuf.Ptr=0; macPIB.macPANId.nVal=0; macPIB.macShortAddr.nVal=0; macPIB.macLongAddr.byte.dwLsb=0; macPIB.macLongAddr.byte.dwMsb=0; macPIB.macDSN=0; //状态初始化 macStatus.nVal=0; macStatus.bits.addrMode=MAC_SRC_LONG_ADDR; macPIB.macCoordShortAddr.nVal=0; macPIB.macCoordLongAddr.byte.dwLsb=0; macPIB.macCoordLongAddr.byte.dwMsb=0; //控制重发的时间 macPIB.macAckWaitDuration=60; //GTS macPIB.macGTSPermit=0; //设备属性 macPIB.DeviceInfo.bits.StackProfile=0; macPIB.DeviceInfo.bits.ZigBeeVersion=ZIGBEE_VERSION; macPIB.DeviceInfo.bits.RxOnWhenIdle=1; macPIB.DeviceInfo.bits.AutoRequest=1; macPIB.DeviceInfo.bits.PromiscuousMode=1; macPIB.DeviceInfo.bits.BattLifeExtPeriods=0; macPIB.DeviceInfo.bits.PotentialParent=1; macPIB.DeviceInfo.bits.PermitJoin=1; //下面是需要改变的参数,初始化全部为0 //标示设备是协调器还是节点。 macPIB.DeviceInfo.bits.DeviceType=ZIGBEE_RFD; //网络描述初始化 PANDescriptor.CoordAddrMode=0; PANDescriptor.GTSPermit=0; PANDescriptor.SecurityUse=0; PANDescriptor.SecurityFailure=0; PANDescriptor.ACLEntry=0; PANDescriptor.CoordPANId.nVal=0; PANDescriptor.CoordShortAddr.nVal=0; PANDescriptor.CoordLongAddr.nVal[0]=0; PANDescriptor.CoordLongAddr.nVal[1]=0; PANDescriptor.CoordLongAddr.nVal[2]=0; PANDescriptor.CoordLongAddr.nVal[3]=0; PANDescriptor.SuperframeSpec.nVal=0; //MAC层接收数据帧 macCurrentRxFrame.packetSize=0; macCurrentRxFrame.frameCON.nVal=0; macCurrentRxFrame.sequenceNumber=0; macCurrentRxFrame.srcAddress.AddrMode=0; macCurrentRxFrame.srcAddress.PANId.nVal=0; macCurrentRxFrame.srcAddress.ShortAddr.nVal=0; macCurrentRxFrame.srcAddress.LongAddr.byte.dwLsb=0; macCurrentRxFrame.srcAddress.LongAddr.byte.dwMsb=0; macCurrentRxFrame.dstAddress.AddrMode=0; macCurrentRxFrame.dstAddress.PANId.nVal=0; macCurrentRxFrame.dstAddress.ShortAddr.nVal=0; macCurrentRxFrame.dstAddress.LongAddr.nVal[0]=0; macCurrentRxFrame.dstAddress.LongAddr.nVal[1]=0; macCurrentRxFrame.dstAddress.LongAddr.nVal[2]=0; macCurrentRxFrame.dstAddress.LongAddr.nVal[3]=0; macCurrentRxFrame.rssi=0; macCurrentRxFrame.crc=0; macCurrentRxFrame.bReady=0; //节点身份标识 macPIB.CDNum = 0xaa; //发送缓冲区 for(i=0;i<ConstMacPacketSize;i++) { TxBuffer.cTxBuffer[i]=0; } TxBuffer.cSize=0; //首先判断是否已经入网 //上电,首先读取MAC层状态,查看是否入网 GetMACStatus(); //如果没有入网,即第一次上电的时候.FLASH的这个存储位全部为空。 if(macStatus.nVal == 0XFFFF) { //状态初始化 macStatus.nVal=0; macStatus.bits.addrMode=MAC_SRC_LONG_ADDR; macStatus.bits.isAssociated = 1;//由于FLASH区域在不写的时候默认是0XFFFF,所以不能是0,否则会被认为已经入网 //地址信息设置,主要是获取一个长地址 MACInitIEEEAddr(); } //如果已经入网,则把相应的地址从Flash中读出来 else { MACGetAddrInfo(); } /* { macStatus.nVal=0; macStatus.bits.addrMode=MAC_SRC_LONG_ADDR; macStatus.bits.isAssociated = 0;//由于FLASH区域在不写的时候默认是0XFFFF,所以不能是0,否则会被认为已经入网 //地址信息设置,主要是获取一个长地址 MACInitIEEEAddr(); } */ //初始化协调器列表 MACFormatPANRecord(); } //程序运行的地址信息及状态信息的初始化 void MACInitIEEEAddr(void) { WORD Index,Indication,Number; LONG_ADDR addr,allocAddr; BOOL bIndication; //首先从标志位区域读出标志位 bIndication=GetIEEEIndication((WORD *)&Index); //判断是否已经自动获取过地址 while((Index!=IEEE_VALID_CODE) || (!bIndication)) { AllocIEEEAddr(&addr); //已经分配了地址,进行存储 Indication=IEEE_VALID_CODE; //存储标志及分配的地址 PutIEEEAddrInfo(Indication,&addr); //首先从标志位区域读出标志位,来看看情况 bIndication=GetIEEEIndication((WORD *)&Index); } //读出分配的地址 GetIEEEAddr(&allocAddr); //读出长地址 GetMACLongAddr(); //判断两者是否一致 Number=memcmp((BYTE *)&allocAddr,(BYTE *)&macPIB.macLongAddr,sizeof(LONG_ADDR)); while(Number!=0) { //设置长地址 memcpy((BYTE *)&macPIB.macLongAddr,(BYTE *)&allocAddr,sizeof(LONG_ADDR)); //网络标示 macPIB.macPANId.nVal=0xFFFF; //短地址为0 macPIB.macShortAddr.nVal=0; //目的地址 macPIB.macCoordShortAddr.nVal=0xFFFF; //设备类型 macPIB.DeviceInfo.bits.DeviceType=ZIGBEE_RFD; //设置状态 macStatus.nVal=0; //允许信标帧 macStatus.bits.allowBeacon=1; //地址模式 macStatus.bits.addrMode=MAC_SRC_LONG_ADDR; //比较 Number=memcmp((BYTE *)&allocAddr,(BYTE *)&macPIB.macLongAddr,sizeof(LONG_ADDR)); } } //存储地址信息 void MACSetAddrInfo(void) { //存储短地址 PutMACAddr(); //存储PAN描述信息 PutCoordDescriptor(); //存储状态 PutMACStatus(); CLR_WDT(); } //读取地址信息 void MACGetAddrInfo(void) { //读取网络地址 GetMACPANId(); //读取短地址 GetMACShortAddr(); //读取长地址 GetMACLongAddr(); //读取网络描述 GetCoordDescriptor(); CLR_WDT(); } //地址辨识 BOOL MACCheckAddress(NODE_INFO *pAddr) { BYTE cNumber,cSize,cLength; BYTE cVal[8]; BYTE cZero[8]; BYTE i; for(i=0;i<8;i++) { cVal[i]=0xFF; cZero[i]=0; } //若已入网,则使用网络标识验证 if(macStatus.bits.isAssociated) { //如果网络地址既不是广播也不是本机地址,则退出 if(((*pAddr).PANId.nVal!=macPIB.macPANId.nVal) && ((*pAddr).PANId.nVal!=0xFFFF)) return FALSE; } //若是短地址,则判断是否是本机地址或者是广播地址 if((macStatus.bits.isAssociated) && (*pAddr).AddrMode==MAC_DST_SHORT_ADDR) { //若为空,则退出 if((*pAddr).ShortAddr.nVal==macPIB.macShortAddr.nVal) { if(macCurrentRxFrame.sequenceNumber!= PreviousRxmacDSN[0]) { Route_flag = 0; PreviousRxmacDSN[0] = macCurrentRxFrame.sequenceNumber; return TRUE; } else return FALSE; } else if((*pAddr).ShortAddr.nVal==0xFFFF) { if(macCurrentRxFrame.sequenceNumber!= PreviousRxmacDSN[3]) { Route_flag = 3; PreviousRxmacDSN[3] = macCurrentRxFrame.sequenceNumber; return TRUE; } else return FALSE; } else if(macCurrentRxFrame.srcAddress.ShortAddr.nVal == (((WORD)Parameter[route_high]<<8&0xff00)|(WORD)Parameter[route_low]&0x00ff)) { if(macCurrentRxFrame.sequenceNumber!= PreviousRxmacDSN[1]) { Route_flag = 1; //表示该数据为节点上传给协调器 PreviousRxmacDSN[1] = macCurrentRxFrame.sequenceNumber; return TRUE; } else return FALSE; } else if((*pAddr).ShortAddr.nVal==(((WORD)Parameter[route_high]<<8&0xff00)|(WORD)Parameter[route_low]&0x00ff)) { if(macCurrentRxFrame.sequenceNumber!= PreviousRxmacDSN[2]) { Route_flag = 2; //表示该数据为协调器下传给节点 PreviousRxmacDSN[2] = macCurrentRxFrame.sequenceNumber; return TRUE; } else return FALSE; } else return FALSE; } else if((*pAddr).AddrMode==MAC_DST_LONG_ADDR) { //判断是否为空 cLength=memcmp((BYTE *)&(*pAddr).LongAddr,(BYTE *)cZero,sizeof(LONG_ADDR)); //判断是否为本机地址 cNumber=memcmp((BYTE *)&(*pAddr).LongAddr,(BYTE *)&macPIB.macLongAddr,sizeof(LONG_ADDR)); //判断是否为广播 cSize=memcmp((BYTE *)&(*pAddr).LongAddr,(BYTE *)cVal,sizeof(LONG_ADDR)); CLR_WDT(); //若是为空,则退出 if(cLength==0) return FALSE; else if(cNumber==0) return TRUE; else if(cSize==0) return TRUE; else return FALSE; } return FALSE; } //发送ACK确认帧 BOOL MACSendACK(BYTE dsn) { BYTE cPtrTx[6]; BYTE cPktSize; CRC_RESULT crcRes; BYTE cSize=0; //不包含长度,CRC,RSSI cPtrTx[cSize++]=3; cPtrTx[cSize++]=MAC_FRAME_ACK; cPtrTx[cSize++]=0; cPtrTx[cSize++]=dsn; //计算自己加的CRC校验和 crcRes=CrcCalc(cPtrTx,cSize); cPtrTx[cSize++]=crcRes.cVal[0]; cPtrTx[cSize++]=crcRes.cVal[1]; //重新修改长度 cPtrTx[0]+=sizeof(CRC_RESULT); //长度,FCS,dsn PHYPutTxBuffer((BYTE *)&cPtrTx,cSize); //喂狗,防止正常情况进入复位 CLR_WDT(); cPktSize=PHYGetTxNumber(); //若写入发送缓冲区的长度不正确则退出 if(cPktSize!=6) { PHYClearTx(); return FALSE; } CLR_WDT(); //发送 return MACTransmitByCSMA(); } //接收缓冲区内,丢弃一定长度的数据 void MACDiscardRx(BYTE size) { BYTE i; for(i=0;i<size;i++) { MACGet(); } } //取出MAC帧 BOOL MACGetPacket(void) { BYTE i; BYTE cNumber=0; BYTE frameType; CRC_RESULT crcResult; i=emSearchMesg(RF_REV_MESSAGE_NOTIFY); //已经收到不少于一个完整的数据包 if((i!=InvalidMesg) && !macCurrentRxFrame.bReady) { emRxMesg(i,NRealTimeMesg,0,0); TxBuffer.cSize=0; //长度字节,不包含长度本身,但是不包含自己加的crc校验,RSSI,CRC macCurrentRxFrame.packetSize=MACGet(); macCurrentRxFrame.packetSize-=4; //去掉2个自己加的CRC校验和,2个字节硬件自动加上的 TxBuffer.cTxBuffer[TxBuffer.cSize++]=macCurrentRxFrame.packetSize; //读出控制域,低字节在前 macCurrentRxFrame.frameCON.cVal[0]=MACGet(); macCurrentRxFrame.frameCON.cVal[1]=MACGet(); TxBuffer.cTxBuffer[TxBuffer.cSize++]=macCurrentRxFrame.frameCON.cVal[0]; TxBuffer.cTxBuffer[TxBuffer.cSize++]=macCurrentRxFrame.frameCON.cVal[1]; //取出序列号 macCurrentRxFrame.sequenceNumber=MACGet(); TxBuffer.cTxBuffer[TxBuffer.cSize++]=macCurrentRxFrame.sequenceNumber; //取出帧类型 frameType=macCurrentRxFrame.frameCON.bits.FrameType; cNumber+=3; //喂狗,防止正常情况进入复位 CLR_WDT(); //若是确认帧进行处理 if((frameType==MAC_FRAME_ACK) && (macCurrentRxFrame.packetSize==5)) { macCurrentRxFrame.dstAddress.AddrMode=MAC_DST_SHORT_ADDR; macCurrentRxFrame.dstAddress.ShortAddr.cVal[0]=MACGet(); macCurrentRxFrame.dstAddress.ShortAddr.cVal[1]=MACGet(); TxBuffer.cTxBuffer[TxBuffer.cSize++]=macCurrentRxFrame.dstAddress.ShortAddr.cVal[0]; TxBuffer.cTxBuffer[TxBuffer.cSize++]=macCurrentRxFrame.dstAddress.ShortAddr.cVal[1]; macCurrentRxFrame.crcRes.cVal[0]=MACGet(); macCurrentRxFrame.crcRes.cVal[1]=MACGet(); //计算CRC校验和 crcResult=CrcCalc(TxBuffer.cTxBuffer,TxBuffer.cSize); macCurrentRxFrame.rssi=MACGet(); macCurrentRxFrame.crc=MACGet(); if(!MACCheckAddress(&macCurrentRxFrame.dstAddress)) { macCurrentRxFrame.bReady=0; return FALSE; } //判断自己加上的CRC校验和 if(crcResult.nVal==macCurrentRxFrame.crcRes.nVal) { //判断硬件的CRC校验结果 if(macCurrentRxFrame.crc & 0x80) { macCurrentRxFrame.bReady=1; return TRUE; } } //校验出错,退出 macCurrentRxFrame.bReady=0; return FALSE; } //若是命令帧或数据帧或信标帧 if((frameType==MAC_FRAME_DATA) || (frameType==MAC_FRAME_CMD) || (frameType==MAC_FRAME_BEACON)) { //地址模式必须存在,要么是长地址,要么是短地址。若目的地址模式是短地址 if(macCurrentRxFrame.frameCON.bits.DstAddrMode==2) { //取出目的网络地址,低字节在前,高字节在后 macCurrentRxFrame.dstAddress.PANId.cVal[0]=MACGet(); macCurrentRxFrame.dstAddress.PANId.cVal[1]=MACGet(); //取出目的地址,低字节在前,高字节在后 macCurrentRxFrame.dstAddress.AddrMode=MAC_DST_SHORT_ADDR; macCurrentRxFrame.dstAddress.ShortAddr.cVal[0]=MACGet(); macCurrentRxFrame.dstAddress.ShortAddr.cVal[1]=MACGet(); cNumber+=4; TxBuffer.cTxBuffer[TxBuffer.cSize++]=macCurrentRxFrame.dstAddress.PANId.cVal[0]; TxBuffer.cTxBuffer[TxBuffer.cSize++]=macCurrentRxFrame.dstAddress.PANId.cVal[1]; TxBuffer.cTxBuffer[TxBuffer.cSize++]=macCurrentRxFrame.dstAddress.ShortAddr.cVal[0]; TxBuffer.cTxBuffer[TxBuffer.cSize++]=macCurrentRxFrame.dstAddress.ShortAddr.cVal[1]; } else if(macCurrentRxFrame.frameCON.bits.DstAddrMode==3) { //若地址模式是长地址 //取出目的网络地址,低字节在前,高字节在后 macCurrentRxFrame.dstAddress.PANId.cVal[0]=MACGet(); macCurrentRxFrame.dstAddress.PANId.cVal[1]=MACGet(); //取出目的地址,低字节在前,高字节在后 macCurrentRxFrame.dstAddress.AddrMode=MAC_DST_LONG_ADDR; macCurrentRxFrame.dstAddress.LongAddr.cVal[0]=MACGet(); macCurrentRxFrame.dstAddress.LongAddr.cVal[1]=MACGet(); macCurrentRxFrame.dstAddress.LongAddr.cVal[2]=MACGet(); macCurrentRxFrame.dstAddress.LongAddr.cVal[3]=MACGet(); macCurrentRxFrame.dstAddress.LongAddr.cVal[4]=MACGet(); macCurrentRxFrame.dstAddress.LongAddr.cVal[5]=MACGet(); macCurrentRxFrame.dstAddress.LongAddr.cVal[6]=MACGet(); macCurrentRxFrame.dstAddress.LongAddr.cVal[7]=MACGet(); cNumber+=10; TxBuffer.cTxBuffer[TxBuffer.cSize++]=macCurrentRxFrame.dstAddress.PANId.cVal[0]; TxBuffer.cTxBuffer[TxBuffer.cSize++]=macCurrentRxFrame.dstAddress.PANId.cVal[1]; memcpy((BYTE *)&TxBuffer.cTxBuffer[TxBuffer.cSize],(BYTE *)&macCurrentRxFrame.dstAddress.LongAddr,sizeof(LONG_ADDR)); TxBuffer.cSize+=8; } else if(macCurrentRxFrame.frameCON.bits.DstAddrMode==0) { //若没有目的地址信息,则是信标帧,否则丢弃该数据帧 if(frameType!=MAC_FRAME_BEACON) { MACDiscardRx(macCurrentRxFrame.packetSize+4-cNumber); macCurrentRxFrame.bReady=0; return FALSE; } } else { //若是地址模式出错,丢弃该数据帧 MACDiscardRx(macCurrentRxFrame.packetSize+4-cNumber); macCurrentRxFrame.bReady=0; return FALSE; } //源地址模式可以不存在,此时可能为信标请求指令 if(macCurrentRxFrame.frameCON.bits.SrcAddrMode) { //若是源地址和目的地址不在一个网段内,读出源网络地址 if(!macCurrentRxFrame.frameCON.bits.IntraPAN) { macCurrentRxFrame.srcAddress.PANId.cVal[0]=MACGet(); macCurrentRxFrame.srcAddress.PANId.cVal[1]=MACGet(); cNumber+=2; TxBuffer.cTxBuffer[TxBuffer.cSize++]=macCurrentRxFrame.srcAddress.PANId.cVal[0]; TxBuffer.cTxBuffer[TxBuffer.cSize++]=macCurrentRxFrame.srcAddress.PANId.cVal[1]; } //判断地址模式 if(macCurrentRxFrame.frameCON.bits.SrcAddrMode==2) { //若是短地址模式,取出源地址 macCurrentRxFrame.srcAddress.AddrMode=MAC_SRC_SHORT_ADDR; macCurrentRxFrame.srcAddress.ShortAddr.cVal[0]=MACGet(); macCurrentRxFrame.srcAddress.ShortAddr.cVal[1]=MACGet(); cNumber+=2; TxBuffer.cTxBuffer[TxBuffer.cSize++]=macCurrentRxFrame.srcAddress.ShortAddr.cVal[0]; TxBuffer.cTxBuffer[TxBuffer.cSize++]=macCurrentRxFrame.srcAddress.ShortAddr.cVal[1]; } else if(macCurrentRxFrame.frameCON.bits.SrcAddrMode==3) { //若是长地址模式,读出长地址 macCurrentRxFrame.srcAddress.AddrMode=MAC_SRC_LONG_ADDR; macCurrentRxFrame.srcAddress.LongAddr.cVal[0]=MACGet(); macCurrentRxFrame.srcAddress.LongAddr.cVal[1]=MACGet(); macCurrentRxFrame.srcAddress.LongAddr.cVal[2]=MACGet(); macCurrentRxFrame.srcAddress.LongAddr.cVal[3]=MACGet(); macCurrentRxFrame.srcAddress.LongAddr.cVal[4]=MACGet(); macCurrentRxFrame.srcAddress.LongAddr.cVal[5]=MACGet(); macCurrentRxFrame.srcAddress.LongAddr.cVal[6]=MACGet(); macCurrentRxFrame.srcAddress.LongAddr.cVal[7]=MACGet(); cNumber+=8; memcpy((BYTE *)&TxBuffer.cTxBuffer[TxBuffer.cSize],(BYTE *)&macCurrentRxFrame.srcAddress.LongAddr,sizeof(LONG_ADDR)); TxBuffer.cSize+=8; } else { //若是源地址模式出错,丢弃该数据帧 MACDiscardRx(macCurrentRxFrame.packetSize+4-cNumber); macCurrentRxFrame.bReady=0; return FALSE; } } else { //若是源地址模式为空,则看是否是信标请求帧,否则退出 if(frameType!=MAC_FRAME_CMD) { MACDiscardRx(macCurrentRxFrame.packetSize+4-cNumber); macCurrentRxFrame.bReady=0; return FALSE; } } CLR_WDT(); //若是该MAC帧的长度超过上限,则丢弃该数据帧 if((macCurrentRxFrame.packetSize+4-cNumber)>ConstMacPayloadSize) { MACDiscardRx(macCurrentRxFrame.packetSize+4-cNumber); macCurrentRxFrame.bReady=0; return FALSE; } //负载装入到接收数据帧结构体中 for(i=0;i<macCurrentRxFrame.packetSize-cNumber;i++) { //pMsdu指向存储的payload的初始地址 macCurrentRxFrame.pMsdu[i]=MACGet(); TxBuffer.cTxBuffer[TxBuffer.cSize++]=macCurrentRxFrame.pMsdu[i]; } //取出自己增加的CRC校验和 macCurrentRxFrame.crcRes.cVal[0]=MACGet(); macCurrentRxFrame.crcRes.cVal[1]=MACGet(); //取出RSSI和CRC结果 macCurrentRxFrame.rssi=MACGet(); //macCurrentRxFrame.rssi=PHYGetLinkQuality(macCurrentRxFrame.rssi); macCurrentRxFrame.crc=MACGet(); //若是信标帧,不需要地址辨识,否则需要进行地址辨识 if(frameType!=MAC_FRAME_BEACON) { if(!MACCheckAddress(&macCurrentRxFrame.dstAddress)) { macCurrentRxFrame.bReady=0; return FALSE; } } //计算自己加的CRC校验和 crcResult=CrcCalc(TxBuffer.cTxBuffer,TxBuffer.cSize); CLR_WDT(); //CRC校验结果 if((macCurrentRxFrame.crcRes.nVal==crcResult.nVal) && (macCurrentRxFrame.crc & 0x80)) { if(macCurrentRxFrame.frameCON.bits.AckRequest) { //若是需要回复ACk,发送确认帧 MACSendACK(macCurrentRxFrame.sequenceNumber); } //修改接收标志位及负载长度 macCurrentRxFrame.bReady=1; macCurrentRxFrame.packetSize=macCurrentRxFrame.packetSize-cNumber; LEDBlinkRed(); //喂狗,防止正常情况进入复位 CLR_WDT(); return TRUE; } else { //CRC校验出错,丢弃该数据帧 macCurrentRxFrame.bReady=0; return FALSE; } } else { //帧类型出错,丢弃该数据帧 MACDiscardRx(macCurrentRxFrame.packetSize+4-cNumber); macCurrentRxFrame.bReady=0; CLR_WDT(); return FALSE; } } else if((i!=InvalidMesg)&&(macCurrentRxFrame.bReady==1)) { emTxMesg(RF_OVERFLOW_SYS_EROR,RealTimeMesg,0,0); return FALSE; } return FALSE; } //封装MAC帧头 BOOL MACPutHeader(NODE_INFO *pDestAddr, BYTE frameCON) { BYTE IntraPAN; BYTE srcAddrMode,dstAddrMode; //读取地址模式 srcAddrMode=macStatus.bits.addrMode; dstAddrMode=(*pDestAddr).AddrMode; //是否是在一个网络内 IntraPAN=frameCON & MAC_INTRA_PAN_YES; //清空发送缓冲区 TxBuffer.cSize=0; //写入长度 TxBuffer.cTxBuffer[TxBuffer.cSize++]=0; //写入帧控制域,低字节在前,高字节在后 TxBuffer.cTxBuffer[TxBuffer.cSize++]=frameCON; TxBuffer.cTxBuffer[TxBuffer.cSize++]=srcAddrMode|dstAddrMode; //写入MAC层序列码 TxBuffer.cTxBuffer[TxBuffer.cSize++]=++macPIB.macDSN; CLR_WDT(); //若目的地址模式为空,则可能为信标帧 if(dstAddrMode) { //判断目的地址模式 if(dstAddrMode==MAC_DST_SHORT_ADDR) { //短地址模式 TxBuffer.cTxBuffer[TxBuffer.cSize++]=(*pDestAddr).PANId.cVal[0]; TxBuffer.cTxBuffer[TxBuffer.cSize++]=(*pDestAddr).PANId.cVal[1]; TxBuffer.cTxBuffer[TxBuffer.cSize++]=(*pDestAddr).ShortAddr.cVal[0]; TxBuffer.cTxBuffer[TxBuffer.cSize++]=(*pDestAddr).ShortAddr.cVal[1]; //若是广播,ACK强制设置成不允许 if((*pDestAddr).ShortAddr.nVal==0xFFFF) TxBuffer.cTxBuffer[1]&=0xDF; } else if(dstAddrMode==MAC_DST_LONG_ADDR) { //长地址模式 TxBuffer.cTxBuffer[TxBuffer.cSize++]=(*pDestAddr).PANId.cVal[0]; TxBuffer.cTxBuffer[TxBuffer.cSize++]=(*pDestAddr).PANId.cVal[1]; memcpy((BYTE *)&TxBuffer.cTxBuffer[TxBuffer.cSize],(BYTE *)&(*pDestAddr).LongAddr.cVal[0],8); TxBuffer.cSize+=8; //若是广播,ACK强制设置成不允许 if(((*pDestAddr).LongAddr.byte.dwLsb==0xFFFFFFFF) && ((*pDestAddr).LongAddr.byte.dwMsb==0xFFFFFFFF)) TxBuffer.cTxBuffer[1]&=0xDF; } else { //如果地址模式不正确,则丢弃该包 TxBuffer.cSize=0; return FALSE; } } //短地址模式可以有,也可以没有,例如信标请求帧中,源地址信息不存在 if(srcAddrMode) { //若目的地址与源地址不在一个网络内,加入源地址模式 if(!IntraPAN) { TxBuffer.cTxBuffer[TxBuffer.cSize++]=macPIB.macPANId.cVal[0]; TxBuffer.cTxBuffer[TxBuffer.cSize++]=macPIB.macPANId.cVal[1]; } //若是短地址模式 if(srcAddrMode==MAC_SRC_SHORT_ADDR) { switch(Route_flag) { case 0: //表示目的地址为本身 case 2: //表示目的地址为下一层节点 TxBuffer.cTxBuffer[TxBuffer.cSize++]=macPIB.macShortAddr.cVal[0]; TxBuffer.cTxBuffer[TxBuffer.cSize++]=macPIB.macShortAddr.cVal[1]; break; case 1: //表示式转发下层节点数据,目的地址为协调器 TxBuffer.cTxBuffer[TxBuffer.cSize++]=Parameter[route_high]; TxBuffer.cTxBuffer[TxBuffer.cSize++]=Parameter[route_low]; break; } } else if(srcAddrMode==MAC_SRC_LONG_ADDR) { //若是长地址模式 memcpy((BYTE *)&TxBuffer.cTxBuffer[TxBuffer.cSize],(BYTE *)&macPIB.macLongAddr.cVal[0],sizeof(LONG_ADDR)); TxBuffer.cSize+=8; } else { //若是源地址模式出错,丢弃该帧 TxBuffer.cSize=0; return FALSE; } } //修改MAC帧的长度 TxBuffer.cTxBuffer[0]=TxBuffer.cSize-1; CLR_WDT(); return TRUE; } //封装MAC帧负载部分 void MACPutTxBuffer(BYTE *ptr,BYTE cSize) { WORD i; WORD Number; //读取帧头的长度 Number=TxBuffer.cTxBuffer[0]; //判断帧头封装是否正确 if(Number+1==TxBuffer.cSize) { for(i=0;i<cSize;i++) { TxBuffer.cTxBuffer[TxBuffer.cSize++]=*ptr; ptr++; } //修改长度 TxBuffer.cTxBuffer[0]=TxBuffer.cSize-1; CLR_WDT(); } else { //若是帧头封装不正确,丢弃本次发送 TxBuffer.cSize=0; } } //MAC帧数据发送 BOOL MACTransmitPacket(void) { BYTE cPktSize; BYTE cNumber; CRC_RESULT crcRes; WORD prio; //读取长度 cNumber=TxBuffer.cSize; cPktSize=TxBuffer.cTxBuffer[0]; //如果长度两者关系不一致,则出错 if(cNumber!=cPktSize+1) { TxBuffer.cSize=0; return FALSE; } emDint(&prio); //加入CRC校验 crcRes=CrcCalc(TxBuffer.cTxBuffer,cPktSize+1); //写入CRC校验 MACPutTxBuffer(&crcRes.cVal[0],sizeof(CRC_RESULT)); //读取长度 cNumber=TxBuffer.cSize; //写入射频 PHYPutTxBuffer(TxBuffer.cTxBuffer,TxBuffer.cSize); //检验写入的是否正确 cPktSize=PHYGetTxNumber(); //数据帧结构中的长度不含长度本身,又增加了两个字节的CRC校验和 if(cPktSize!=cNumber) { PHYClearTx(); emEint(&prio); return FALSE;//发送溢出 } //喂狗,防止正常情况进入复位 CLR_WDT(); emEint(&prio); //放入重发队列 MACEnqueTxFrame(); //发送缓冲区清空 TxBuffer.cSize=0; //发送 return MACTransmitByCSMA(); } //信标帧处理 void MACProcessBeacon(void) { BYTE cSize=0; PAN_DESCRIPTOR PANDesc; //信标帧没有目的地址信息,所以忽略处理 //判断FFD的地址模式,协调器回复的超帧进入这个if,因为协调器有源地址模式。 if(macCurrentRxFrame.srcAddress.AddrMode == MAC_SRC_SHORT_ADDR) { //短地址模式 PANDesc.CoordAddrMode=0; //网络标识 PANDesc.CoordPANId.nVal=macCurrentRxFrame.srcAddress.PANId.nVal; //短地址 PANDesc.CoordShortAddr.nVal=macCurrentRxFrame.srcAddress.ShortAddr.nVal; } else { //长地址模式 PANDesc.CoordAddrMode=1; //网络标识 PANDesc.CoordPANId.nVal=macCurrentRxFrame.srcAddress.PANId.nVal; //长地址 memcpy((BYTE *)&PANDesc.CoordLongAddr,(BYTE *)&macCurrentRxFrame.srcAddress.LongAddr,sizeof(LONG_ADDR)); } //记录超帧描述 PANDesc.SuperframeSpec.cVal[0]=macCurrentRxFrame.pMsdu[cSize++]; PANDesc.SuperframeSpec.cVal[1]=macCurrentRxFrame.pMsdu[cSize++]; CLR_WDT(); //该位显示协调器的邻居表是否满。 PANDesc.bits.allowJoin=PANDesc.SuperframeSpec.bits.AssociationPermit; //修改链路质量 PANDesc.LinkQuality=PHYGetLinkQuality(macCurrentRxFrame.rssi); //将协调器加入节点的协调器列表中,可以有多个,目前只需要一个。 MACRefreshPANRecord(&PANDesc); //释放资源 macCurrentRxFrame.bReady=0; CLR_WDT(); } void MACFillSourAddr(BYTE *ptr) { *ptr++=macPIB.macPANId.cVal[0]; *ptr++=macPIB.macPANId.cVal[1]; *ptr++=macPIB.macShortAddr.cVal[0]; *ptr++=macPIB.macShortAddr.cVal[1]; } //MAC层命令帧处理 void MACProcessCommand(void) { BYTE command; BYTE flag; BYTE i; BYTE PramaNum; BYTE Channel,TxPower,BaudRate; BYTE offset=0; BYTE cSize=0; NODE_INFO DestShortAddr; BYTE cPtrTx[20]; // WORD Index,prio; WORD NodeId; BYTE Status; SHORT_ADDR shortAddr; // ASSOC_REQUEST_CAP CapInfo; // NEIGHBOR_RECORD_INFO DeviceInfo; BYTE DeviceType; command=macCurrentRxFrame.pMsdu[offset++]; DestShortAddr.PANId.nVal=macPIB.macPANId.nVal; DestShortAddr.AddrMode=MAC_DST_SHORT_ADDR; DestShortAddr.ShortAddr.cVal[0]=macCurrentRxFrame.srcAddress.ShortAddr.cVal[0]; DestShortAddr.ShortAddr.cVal[1]=macCurrentRxFrame.srcAddress.ShortAddr.cVal[1]; switch(command) { case RF_SET_FREQ_REQ: cSize=0; cPtrTx[cSize++]=RF_SET_FREQ_RSP; Channel=macCurrentRxFrame.pMsdu[offset++]; if((Channel <= ConstRFChannelSize) && (Channel > 0)) { phyPIB.phyCurrentChannel = Channel; PHYSetChannel(phyPIB.phyCurrentChannel); //PutPHYFreq(Channel); cPtrTx[cSize++]=0x01; } else { cPtrTx[cSize++]=0x00; } MACFillSourAddr(&cPtrTx[cSize]); cSize+=4; cPtrTx[cSize++]=Channel; MACPutHeader(&DestShortAddr,MAC_FRAME_CMD|MAC_ACK_NO); MACPutTxBuffer(cPtrTx,cSize); MACTransmitPacket(); macCurrentRxFrame.bReady=0; break; case RF_SET_FREQ_RSP: flag=macCurrentRxFrame.pMsdu[offset++]; if(flag==1&&(ConstCfgRspBufferSize-MACCfgRspBuf.Ptr)>=6) { MACCfgRspBuf.Buffer[MACCfgRspBuf.Ptr++]=RF_SET_FREQ_RSP; for(i=0;i<5;i++) { MACCfgRspBuf.Buffer[MACCfgRspBuf.Ptr++]=macCurrentRxFrame.pMsdu[offset++]; } } else if(flag==1&&(ConstCfgRspBufferSize-MACCfgRspBuf.Ptr)<6) { MACCfgRspSharBuf.bReady=1; MACCfgRspSharBuf.Ptr=0; MACCfgRspSharBuf.Buffer[MACCfgRspSharBuf.Ptr++]=RF_SET_FREQ_RSP; for(i=0;i<5;i++) { MACCfgRspSharBuf.Buffer[MACCfgRspSharBuf.Ptr++]=macCurrentRxFrame.pMsdu[offset++]; } emTxMesg(RF_FLUSH_RSPBUFFER_REQ,RealTimeMesg,0,0); } macCurrentRxFrame.bReady=0; break; case RF_SET_POWER_REQ: cSize=0; cPtrTx[cSize++]=RF_SET_POWER_RSP; TxPower=macCurrentRxFrame.pMsdu[offset++]; if((TxPower <= ConstRFPowerSize) && (TxPower > 0)) { phyPIB.phyTransmitPower=TxPower; PHYSetTxPower(TxPower); //PutPHYTxPower(TXPOWERIndex); cPtrTx[cSize++]=0x01; } else { cPtrTx[cSize++]=0x00; } MACFillSourAddr(&cPtrTx[cSize]); cSize+=4; cPtrTx[cSize++]=TxPower; MACPutHeader(&DestShortAddr,MAC_FRAME_CMD|MAC_ACK_YES); MACPutTxBuffer(cPtrTx,cSize); MACTransmitPacket(); macCurrentRxFrame.bReady=0; break; case RF_SET_POWER_RSP: flag=macCurrentRxFrame.pMsdu[offset++]; if(flag==1&&(ConstCfgRspBufferSize-MACCfgRspBuf.Ptr)>=6) { MACCfgRspBuf.Buffer[MACCfgRspBuf.Ptr++]=RF_SET_POWER_RSP; for(i=0;i<5;i++) { MACCfgRspBuf.Buffer[MACCfgRspBuf.Ptr++]=macCurrentRxFrame.pMsdu[offset++]; } } else if(flag==1&&(ConstCfgRspBufferSize-MACCfgRspBuf.Ptr)<6) { MACCfgRspSharBuf.bReady=1; MACCfgRspSharBuf.Ptr=0; MACCfgRspSharBuf.Buffer[MACCfgRspSharBuf.Ptr++]=RF_SET_POWER_RSP; for(i=0;i<5;i++) { MACCfgRspSharBuf.Buffer[MACCfgRspSharBuf.Ptr++]=macCurrentRxFrame.pMsdu[offset++]; } emTxMesg(RF_FLUSH_RSPBUFFER_REQ,RealTimeMesg,0,0); } macCurrentRxFrame.bReady=0; break; case RF_SET_RATE_REQ: cSize=0; cPtrTx[cSize++]=RF_SET_RATE_RSP; BaudRate=macCurrentRxFrame.pMsdu[offset++]; if((BaudRate > 0) && (BaudRate <= ConstRFBaudRateSize)) { phyPIB.phyBaudRate = BaudRate; PHYSetBaudRate(BaudRate); Delay(1500); PHYSetTRxState(RF_TRX_RX); PHYSetTRxState(RF_TRX_IDLE); PHYSetTRxState(RF_TRX_RX); //PutPHYBaudRate(BAUDRATEIndex); cPtrTx[cSize++]=0x01; } else { cPtrTx[cSize++]=0x00; } MACFillSourAddr(&cPtrTx[cSize]); cSize+=4; cPtrTx[cSize++]=BaudRate; MACPutHeader(&DestShortAddr,MAC_FRAME_CMD|MAC_ACK_NO); MACPutTxBuffer(cPtrTx,cSize); MACTransmitPacket(); macCurrentRxFrame.bReady=0; break; case RF_SET_RATE_RSP: flag=macCurrentRxFrame.pMsdu[offset++]; if(flag==1&&(ConstCfgRspBufferSize-MACCfgRspBuf.Ptr)>=6) { MACCfgRspBuf.Buffer[MACCfgRspBuf.Ptr++]=RF_SET_RATE_RSP; for(i=0;i<5;i++) { MACCfgRspBuf.Buffer[MACCfgRspBuf.Ptr++]=macCurrentRxFrame.pMsdu[offset++]; } } else if(flag==1&&(ConstCfgRspBufferSize-MACCfgRspBuf.Ptr)<6) { MACCfgRspSharBuf.bReady=1; MACCfgRspSharBuf.Ptr=0; MACCfgRspSharBuf.Buffer[MACCfgRspSharBuf.Ptr++]=RF_SET_RATE_RSP; for(i=0;i<5;i++) { MACCfgRspSharBuf.Buffer[MACCfgRspSharBuf.Ptr++]=macCurrentRxFrame.pMsdu[offset++]; } emTxMesg(RF_FLUSH_RSPBUFFER_REQ,RealTimeMesg,0,0); } macCurrentRxFrame.bReady=0; break; case RF_SET_IEEEADDR_REQ: cSize=0; cPtrTx[cSize++]=RF_SET_IEEEADDR_RSP; PramaNum=macCurrentRxFrame.packetSize-1; if(PramaNum==sizeof(LONG_ADDR)) { memcpy(macPIB.macLongAddr.cVal,(BYTE *)&macCurrentRxFrame.pMsdu[offset],PramaNum); PutMACAddr(); // PutIEEEAddrInfo(IEEE_VALID_CODE, &macPIB.macLongAddr); cPtrTx[cSize++]=0x01; } else { cPtrTx[cSize++]=0x00; } MACFillSourAddr(&cPtrTx[cSize]); cSize+=4; memcpy(&cPtrTx[cSize],(BYTE *)&macCurrentRxFrame.pMsdu[offset],PramaNum); cSize+=PramaNum; MACPutHeader(&DestShortAddr,MAC_FRAME_CMD|MAC_ACK_YES); MACPutTxBuffer(cPtrTx,cSize); MACTransmitPacket(); macCurrentRxFrame.bReady=0; break; case RF_SET_IEEEADDR_RSP: flag=macCurrentRxFrame.pMsdu[offset++]; PramaNum=macCurrentRxFrame.packetSize-1; if(flag==1&&(ConstCfgRspBufferSize-MACCfgRspBuf.Ptr)>=13) { MACCfgRspBuf.Buffer[MACCfgRspBuf.Ptr++]=RF_SET_IEEEADDR_RSP; for(i=0;i<PramaNum;i++) { MACCfgRspBuf.Buffer[MACCfgRspBuf.Ptr++]=macCurrentRxFrame.pMsdu[offset++]; } } else if(flag==1&&(ConstCfgRspBufferSize-MACCfgRspBuf.Ptr)<13) { MACCfgRspSharBuf.bReady=1; MACCfgRspSharBuf.Ptr=0; MACCfgRspSharBuf.Buffer[MACCfgRspSharBuf.Ptr++]=RF_SET_IEEEADDR_RSP; for(i=0;i<PramaNum;i++) { MACCfgRspSharBuf.Buffer[MACCfgRspSharBuf.Ptr++]=macCurrentRxFrame.pMsdu[offset++]; } emTxMesg(RF_FLUSH_RSPBUFFER_REQ,RealTimeMesg,0,0); } macCurrentRxFrame.bReady=0; break; case RF_SET_PANSADDR_REQ: cSize=0; cPtrTx[cSize++]=RF_SET_PANSADDR_RSP; PramaNum=macCurrentRxFrame.packetSize-1; if(PramaNum==sizeof(SHORT_ADDR)) { macPIB.macPANId.cVal[0]=macCurrentRxFrame.pMsdu[offset++]; macPIB.macPANId.cVal[1]=macCurrentRxFrame.pMsdu[offset++]; //开始设置 macStatus.bits.isAssociated=1; PutMACStatus(); PutMACAddr(); cPtrTx[cSize++]=0x01; } else { cPtrTx[cSize++]=0x00; } MACFillSourAddr(&cPtrTx[cSize]); cSize+=4; memcpy(&cPtrTx[cSize],(BYTE *)&macCurrentRxFrame.pMsdu[offset],PramaNum); cSize+=PramaNum; MACPutHeader(&DestShortAddr,MAC_FRAME_CMD|MAC_ACK_YES); MACPutTxBuffer(cPtrTx,cSize); MACTransmitPacket(); macCurrentRxFrame.bReady=0; break; case RF_SET_PANSADDR_RSP: flag=macCurrentRxFrame.pMsdu[offset++]; PramaNum=macCurrentRxFrame.packetSize-1; if(flag==1&&(ConstCfgRspBufferSize-MACCfgRspBuf.Ptr)>=7) { MACCfgRspBuf.Buffer[MACCfgRspBuf.Ptr++]=RF_SET_PANSADDR_RSP; for(i=0;i<PramaNum;i++) { MACCfgRspBuf.Buffer[MACCfgRspBuf.Ptr++]=macCurrentRxFrame.pMsdu[offset++]; } } else if(flag==1&&(ConstCfgRspBufferSize-MACCfgRspBuf.Ptr)<7) { MACCfgRspSharBuf.bReady=1; MACCfgRspSharBuf.Ptr=0; MACCfgRspSharBuf.Buffer[MACCfgRspSharBuf.Ptr++]=RF_SET_PANSADDR_RSP; for(i=0;i<PramaNum;i++) { MACCfgRspSharBuf.Buffer[MACCfgRspSharBuf.Ptr++]=macCurrentRxFrame.pMsdu[offset++]; } emTxMesg(RF_FLUSH_RSPBUFFER_REQ,RealTimeMesg,0,0); } macCurrentRxFrame.bReady=0; break; case RF_SET_SHORTADDR_REQ: cSize=0; cPtrTx[cSize++]=RTU_SET_SHORTADDR_RSP; //macCurrentRxFrame.packetSize这个时候表示的其实是负载的长度,前面已经经过层层拆减,帧头的长度已经去除 PramaNum=macCurrentRxFrame.packetSize-1; if(PramaNum==sizeof(SHORT_ADDR)) { macPIB.macShortAddr.cVal[0]=macCurrentRxFrame.pMsdu[offset++]; macPIB.macShortAddr.cVal[1]=macCurrentRxFrame.pMsdu[offset++]; macStatus.bits.addrMode = MAC_SRC_SHORT_ADDR; //有了短地址模式说明可以利用短地址通信了 PutMACStatus(); PutMACAddr(); cPtrTx[cSize++]=0x01; //1表示地址分配成功 } else { cPtrTx[cSize++]=0x00; //0表示地址没有分配成功 } cPtrTx[cSize++] = macPIB.CDNum; MACFillSourAddr(&cPtrTx[cSize]); //将本机的子网地址和短地址填充以便发送给协调器 cSize+=4; //又拷贝了两个字节,这个时候这两个字节应该为空,难道是作为结束标志?? //memcpy(&cPtrTx[cSize],(BYTE *)&macCurrentRxFrame.pMsdu[offset],PramaNum); //cSize+=PramaNum; MACPutHeader(&DestShortAddr,MAC_FRAME_CMD|MAC_INTRA_PAN_YES|MAC_ACK_NO); MACPutTxBuffer(cPtrTx,cSize); MACTransmitPacket(); macCurrentRxFrame.bReady=0; break; case MAC_ASSOC_RESPONSE://节点地址要写入FLASH中 DeviceType=macPIB.DeviceInfo.bits.DeviceType; //if((DeviceType==ZIGBEE_RFD || DeviceType==ZIGBEE_ROUTER) && (!macStatus.bits.isAssociated)) if((DeviceType==ZIGBEE_RFD || DeviceType==ZIGBEE_ROUTER) ) { BYTE inum; //读出分配给自己的地址 shortAddr.cVal[0]=macCurrentRxFrame.pMsdu[offset++]; shortAddr.cVal[1]=macCurrentRxFrame.pMsdu[offset++]; //读出加入网络的状态 Status=macCurrentRxFrame.pMsdu[offset++]; //说明加入网络成功,并且给分配了一个短地址 if((Status==MAC_ASSOCIATION_PAN_SUCCESS) && (shortAddr.nVal!=0xFFFF)) { //从接收帧中取得网络标识 macPIB.macPANId.nVal=macCurrentRxFrame.srcAddress.PANId.nVal; //记录分配的地址 macPIB.macShortAddr.nVal=shortAddr.nVal; memcpy((BYTE *)&macPIB.macLongAddr,(BYTE *)&macCurrentRxFrame.dstAddress.LongAddr,sizeof(LONG_ADDR)); for(inum=0;inum<8;inum++) { macPIB.macLongAddr.cVal[inum]=macCurrentRxFrame.pMsdu[offset++]; } PANDescriptor.CoordPANId.nVal = macCurrentRxFrame.srcAddress.PANId.nVal; PANDescriptor.CoordShortAddr.nVal = macCurrentRxFrame.srcAddress.ShortAddr.nVal; //存储短地址 PutMACAddr(); //修改地址模式 macStatus.bits.addrMode=MAC_SRC_SHORT_ADDR; //修改入网状态 macStatus.bits.isAssociated=1; //存储MAC状态 PutMACStatus(); //保存父节点信息 PutCoordDescriptor(); emTxMesg(NET_ADDR_ACK,RealTimeMesg,0,0); } else if((Status==MAC_ASSOCIATION_PAN_SUCCESS) && (shortAddr.nVal==0xFFFF)) { //表明自己不需要分配短地址,利用长地址通信 macPIB.macPANId.nVal=macCurrentRxFrame.srcAddress.PANId.nVal; //存储 //PutMACAddr(); //修改地址模式 macStatus.bits.addrMode=MAC_SRC_LONG_ADDR; //修改入网标志 macStatus.bits.isAssociated=1; //存储 //PutMACStatus(); //保存父节点信息 //PutCoordDescriptor(); } } macCurrentRxFrame.bReady=0; break; case MAC_ASSOC_CHECK: cSize = 0; NodeId = macCurrentRxFrame.pMsdu[offset]; cPtrTx[cSize++]=MAC_CHECK_RSP; cPtrTx[cSize++]=NodeId; if(NodeId == macPIB.CDNum) { MACPutHeader(&DestShortAddr,MAC_FRAME_CMD|MAC_ACK_NO); MACPutTxBuffer(cPtrTx,cSize); MACTransmitPacket(); } macCurrentRxFrame.bReady=0; break; //收到出网请求 case MAC_DISASSOC_NOTIFY: JoinNwkIndction = 0;//标志位清零 //初始化网络协调器列表 MACFormatPANRecord(); //修改标志位 macStatus.bits.isAssociated=0; //地址模式也回到长地址模式 macStatus.bits.addrMode=MAC_SRC_LONG_ADDR; macPIB.macShortAddr.nVal=0; macPIB.macPANId.nVal = 0; macCurrentRxFrame.bReady=0; break; default: break; } } //MAC确认帧处理 void MACProcessAck(void) { BYTE dsn; dsn=macCurrentRxFrame.sequenceNumber; MACRemoveTxFrame(dsn); macCurrentRxFrame.bReady=0; CLR_WDT(); } //MAC层状态机 void MACProcessPacket(void) { BYTE cNumber; BYTE DeviceType; BYTE FrameType; BYTE i,j; //仅作计数用 BYTE cSize = 0; BYTE cPtrTx[40]; NODE_INFO macAddr; //初始化 cNumber=0; //若是接收到一个MAC帧 i = MACGetPacket(); if(i == TRUE) { //取出MAC帧类型 FrameType=macCurrentRxFrame.frameCON.bits.FrameType; if((0 == Route_flag)||(3 == Route_flag)) // 表明该数据帧是给本节点的或广播的 { switch (FrameType) { //若是数据帧 case MAC_FRAME_DATA: DeviceType=macPIB.DeviceInfo.bits.DeviceType; if((DeviceType==ZIGBEE_COORD) && (!macStatus.bits.bEstablishPAN)) { cNumber=0; macCurrentRxFrame.bReady=0; } else if((DeviceType==ZIGBEE_RFD) && (!macStatus.bits.isAssociated)) { cNumber=0; macCurrentRxFrame.bReady=0; } else if(DeviceType==0x00) { cNumber=0; macCurrentRxFrame.bReady=0; } else { // emTxMesg(RF_UPLOAD_MESSAGE_REQ,RealTimeMesg,&macCurrentRxFrame.pMsdu[0],macCurrentRxFrame.packetSize); MACProcessData(); } break; //若是信标帧 case MAC_FRAME_BEACON: MACProcessBeacon(); break; //若是确认帧 case MAC_FRAME_ACK: MACProcessAck(); break; //若是命令帧 case MAC_FRAME_CMD: MACProcessCommand(); break; //否则丢弃 default: macCurrentRxFrame.bReady=0; break; } } else if((1 == Route_flag)||(2 == Route_flag)) //1代表目的为协调器;2代表节点;3代表广播 { switch(Route_flag) { case 1: //目的地址为协调器 macAddr.ShortAddr.nVal = macAddr.ShortAddr.nVal = PANDescriptor.CoordShortAddr.nVal;; break; case 2: //协调器来的数据,转发给下层节点 macAddr.ShortAddr.nVal = ((WORD)Parameter[route_high]<<8&0xff00)|(WORD)Parameter[route_low]&0x00ff; break; default: macCurrentRxFrame.bReady=0; return 0; break; } //路由数据转发 { macAddr.AddrMode = MAC_DST_SHORT_ADDR; macAddr.PANId.nVal = PANDescriptor.CoordPANId.nVal; macPIB.macDSN = macCurrentRxFrame.sequenceNumber; MACPutHeader(&macAddr,FrameType | MAC_INTRA_PAN_YES | MAC_ACK_NO); for(j=0;j<macCurrentRxFrame.packetSize;j++) { cPtrTx[cSize++] = macCurrentRxFrame.pMsdu[j]; } MACPutTxBuffer(cPtrTx,cSize); MACTransmitPacket(); macCurrentRxFrame.bReady=0; } //此花括号为数据转发 } } else { Nop(); Nop(); } Route_flag = 0; //处理重发部分 MACRefreshTxFrame(); //超时处理协调器队列 // MACProccessPANRecordByTimeout(); CLR_WDT(); } void MACProcessData(void) { BYTE CMDData[3] = {0,0,0}; BYTE ErrorFlag = 0; BYTE TACTICE_NUM,TACTICE_DATA[4]; BYTE i_Local = 0; BYTE i=0; BYTE cSize = 0; BYTE cPtrTx[40]; NODE_INFO macAddr; Type = macCurrentRxFrame.pMsdu[0]; CoordID[0] = macCurrentRxFrame.pMsdu[1]; CoordID[1] = macCurrentRxFrame.pMsdu[2]; if(macCurrentRxFrame.packetSize >=6) { CMDData[0] = macCurrentRxFrame.pMsdu[3]; CMDData[1] = macCurrentRxFrame.pMsdu[4]; CMDData[2] = macCurrentRxFrame.pMsdu[5]; } switch(Type) { case 0x00: emTxMesg(LOC_HEART_REQ,RealTimeMesg,0,0); break; case 0x01: emTxMesg(TEM_SENT_REQ,RealTimeMesg,0,0); break; case 0x04: emTxMesg(INFRACOLD_SENT_REQ,RealTimeMesg,0,0); break; case 0x02: emTxMesg(INFRAHOT_SENT_REQ,RealTimeMesg,0,0); break; case 0x0f: emTxMesg(INFRAOFF_SENT_REQ,RealTimeMesg,0,0); break; case 0x12: code_flag=HOT; break; case 0x14: code_flag=COLD; break; case 0x1f: code_flag=OFF; break; case 0x2f: IEC0bits.IC1IE = 0; IEC0bits.T3IE = 0; break; case 0x2e: IC1_Init(); T3_Init(); break; case 0x06: RESET();//复位 break; case 0x20://第一路继电器线圈通电 data = data | 0x0020; HC595Put(data); HC595Out(); break; case 0x21://第一路继电器线圈断电 data = data & 0xffdf; HC595Put(data); HC595Out(); break; case 0x22://第二路继电器线圈通电 data = data | 0x0010; HC595Put(data); HC595Out(); break; case 0x23://第二路继电器线圈断电 data = data & 0xffef; HC595Put(data); HC595Out(); break; case 0x24://第三路继电器线圈通电 data = data | 0x0008; HC595Put(data); HC595Out(); break; case 0x25://第三路继电器线圈断电 data = data & 0xfff7; HC595Put(data); HC595Out(); break; case 0x26://第四路继电器线圈通电 data = data | 0x0004; HC595Put(data); HC595Out(); break; case 0x27://第四路继电器线圈断电 data = data & 0xfffb; HC595Put(data); HC595Out(); break; case 0xBB: if(6 == macCurrentRxFrame.packetSize) { TACTICE_NUM = CMDData[0]; TACTICE_DATA[0] = CMDData[1]; if(TACTICE_NUM<PARAMETER_NUM) i_Local = 1; else i_Local = 0; {//安全控制策略 if((TACTICE_NUM==0x85)&&(TACTICE_DATA[0]==0x92)) {data = data | 0xffff;emDelHardTimer(1);emDelHardTimer(3);IEC1bits.T5IE = 0; } else if((TACTICE_NUM==0x47)&&(TACTICE_DATA[0]==0x31)) {data = data & 0x0000;emDelHardTimer(1);emDelHardTimer(3);IEC1bits.T5IE = 0; } else if((TACTICE_NUM==0x72)&&(TACTICE_DATA[0]==0x64)) {data = data | 0xffff;emStartHardTimer(1);emStartHardTimer(3);T5_Init(); } else if((TACTICE_NUM==0x95)&&(TACTICE_DATA[0]==0x48)) {data = data & 0x0000;emStartHardTimer(1);emStartHardTimer(3);T5_Init(); } } if(i_Local == 1) { GetAddr(&TacticsAddr); ReadPM(Buffer,SourceAddr); Buffer[TACTICE_NUM]=TACTICE_DATA[0];//策略写入缓存区 Parameter[TACTICE_NUM]=TACTICE_DATA[0]; ErasePage(); WritePM(Buffer, SourceAddr); BufferInit();//清空Buffer } } else ErrorFlag = 1; break; case 0xbc: macAddr.AddrMode = MAC_DST_SHORT_ADDR; macAddr.PANId.nVal = PANDescriptor.CoordPANId.nVal; macAddr.ShortAddr.nVal = PANDescriptor.CoordShortAddr.nVal; MACPutHeader(&macAddr,MAC_FRAME_DATA | MAC_INTRA_PAN_YES | MAC_ACK_NO); cPtrTx[cSize++]=Type+1; cPtrTx[cSize++]=CoordID[0]; cPtrTx[cSize++]=CoordID[1]; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x01; for(i=0;i<PARAMETER_NUM;i++) { cPtrTx[cSize++] = Parameter[i]; } cPtrTx[cSize++]=macPIB.macShortAddr.nVal>>8; cPtrTx[cSize++]=macPIB.macShortAddr.nVal; MACPutTxBuffer(cPtrTx,cSize); MACTransmitPacket(); CoordID[0] = 0; CoordID[1] = 0; break; case 0x0b: if(10 == macCurrentRxFrame.packetSize) { //Delay(0xffff); ServerTime.year = macCurrentRxFrame.pMsdu[3]; ServerTime.month = macCurrentRxFrame.pMsdu[4]; ServerTime.day = macCurrentRxFrame.pMsdu[5]; ServerTime.hour = macCurrentRxFrame.pMsdu[6]; ServerTime.minute = macCurrentRxFrame.pMsdu[7]; ServerTime.second = macCurrentRxFrame.pMsdu[8]; dark = macCurrentRxFrame.pMsdu[9]; StartmSeconds = GetmSecinds(); memcpy(&CurrentSysTime,&ServerTime,sizeof(RTIME));//将服务器时间赋值给最初时刻的系统时间 emTxMesg(TIME_DATA_REQ,RealTimeMesg,0,0); } else ErrorFlag = 1; break; case 0x0d: emTxMesg(TIME_DATA_REQ,RealTimeMesg,0,0); break; case 0xee: //接收命令后发送广播包,广播自己所在网络、保存的协调器短地址和自己macPIB短地址 macAddr.AddrMode = MAC_DST_SHORT_ADDR; macAddr.PANId.nVal = 0xffff; macAddr.ShortAddr.nVal = 0xffff; MACPutHeader(&macAddr,MAC_FRAME_DATA | MAC_INTRA_PAN_YES | MAC_ACK_NO); cPtrTx[cSize++]=Type+1; cPtrTx[cSize++]=CoordID[0]; cPtrTx[cSize++]=CoordID[1]; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x01; cPtrTx[cSize++]=macPIB.macPANId.nVal>>8; cPtrTx[cSize++]=macPIB.macPANId.nVal; cPtrTx[cSize++]=PANDescriptor.CoordShortAddr.nVal>>8; cPtrTx[cSize++]=PANDescriptor.CoordShortAddr.nVal; cPtrTx[cSize++]=macPIB.macShortAddr.nVal>>8; cPtrTx[cSize++]=macPIB.macShortAddr.nVal; MACPutTxBuffer(cPtrTx,cSize); MACTransmitPacket(); break; case 0x66: emTxMesg(LOC_RSSI_REQ,RealTimeMesg,0,0); break; case 0x68: emTxMesg(LOC_DEL_REQ,RealTimeMesg,0,0); memset(Loc_Buffer,0,20*sizeof(unsigned char)); memset(distance_Buffer,0,20*sizeof(unsigned int)); infrared_correct = 0; break; case 0x6A: if(Loc_Times<20) { Loc_Buffer[Loc_Times] = macCurrentRxFrame.rssi; distance_Buffer[Loc_Times] = register2distance(Loc_Buffer[Loc_Times]) ; Loc_Times++; } else Loc_Times = 0; break; case 0x6C: Loc_Times = 0; emTxMesg(LOC_DIS_REQ,RealTimeMesg,0,0); break; default: ErrorFlag = 1; break; } if(0 == ErrorFlag) { macAddr.AddrMode = MAC_DST_SHORT_ADDR; macAddr.PANId.nVal = PANDescriptor.CoordPANId.nVal; macAddr.ShortAddr.nVal = PANDescriptor.CoordShortAddr.nVal; MACPutHeader(&macAddr,MAC_FRAME_DATA | MAC_INTRA_PAN_YES | MAC_ACK_NO); ////////// if( (Type!=0x0c)&&(Type!=0xbc)&&(Type!=0x0d)&&(Type!=0xee)&&(Type!=0x66)&&(Type!=0xbb)&&(Type!=0x03)&&(Type!=0x01)&&(Type!=0x03)&&(Type!=0x6A)&&(Type!=0x6c)) if(Type!=0x6A) { cPtrTx[cSize++]=Type+1; cPtrTx[cSize++]=CoordID[0]; cPtrTx[cSize++]=CoordID[1]; cPtrTx[cSize++]=macPIB.macShortAddr.nVal>>8; cPtrTx[cSize++]=macPIB.macShortAddr.nVal; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x01; } ////////// else if((0xbb==Type)||(0x03==Type))//因为这两条指令的长度比较长,需要专门的回复格式 ////////// { ////////// cPtrTx[cSize++]=Type+1; ////////// cPtrTx[cSize++]=CoordID[0]; ////////// cPtrTx[cSize++]=CoordID[1]; ////////// cPtrTx[cSize++]=CMDData[0]; ////////// cPtrTx[cSize++]=CMDData[1]; ////////// cPtrTx[cSize++]=CMDData[2]; ////////// cPtrTx[cSize++]=macPIB.macShortAddr.nVal>>8; ////////// cPtrTx[cSize++]=macPIB.macShortAddr.nVal; ////////// cPtrTx[cSize++]=0x00; ////////// cPtrTx[cSize++]=0x01; ////////// } ////////// MACPutTxBuffer(cPtrTx,cSize); MACTransmitPacket(); CoordID[0] = 0; CoordID[1] = 0; } else if(1 == ErrorFlag) { macAddr.AddrMode = MAC_DST_SHORT_ADDR; macAddr.PANId.nVal = PANDescriptor.CoordPANId.nVal; macAddr.ShortAddr.nVal = PANDescriptor.CoordShortAddr.nVal; MACPutHeader(&macAddr,MAC_FRAME_DATA | MAC_INTRA_PAN_YES | MAC_ACK_NO); ////////// ////////// if((Type!=0xbb)&&(Type!=0x03))//因为这两条指令的长度比较长,需要专门的回复格式 ////////// { cPtrTx[cSize++]=Type+1; cPtrTx[cSize++]=CoordID[0]; cPtrTx[cSize++]=CoordID[1]; cPtrTx[cSize++]=macPIB.macShortAddr.nVal>>8; cPtrTx[cSize++]=macPIB.macShortAddr.nVal; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x00; ////////// } ////////// else ////////// { ////////// cPtrTx[cSize++]=Type+1; ////////// cPtrTx[cSize++]=CoordID[0]; ////////// cPtrTx[cSize++]=CoordID[1]; ////////// cPtrTx[cSize++]=CMDData[0]; ////////// cPtrTx[cSize++]=CMDData[1]; ////////// cPtrTx[cSize++]=CMDData[2]; ////////// cPtrTx[cSize++]=macPIB.macShortAddr.nVal>>8; ////////// cPtrTx[cSize++]=macPIB.macShortAddr.nVal; ////////// cPtrTx[cSize++]=0x00; ////////// cPtrTx[cSize++]=0x00; ////////// } MACPutTxBuffer(cPtrTx,cSize); MACTransmitPacket(); CoordID[0] = 0; CoordID[1] = 0; ErrorFlag = 0; } macCurrentRxFrame.bReady=0; } //重发队列入队 WORD MACEnqueTxFrame(void) { BYTE i; BYTE AckRequest; //判断是否需要ACK确认 AckRequest=TxBuffer.cTxBuffer[1] & MAC_ACK_YES; if(!AckRequest) { //若是不需要ACK,则不用存储 return InValid_Index; } for(i=0;i<ConstMacTxQueSize;i++) { if(!TxFrameQue[i].Flags.bits.bInUse) { memcpy(TxFrameQue[i].cTxBuffer,TxBuffer.cTxBuffer,TxBuffer.cSize); //记录发送时间,进行超时判断 TxFrameQue[i].dwStartTime=GetTicks(); //重发次数 TxFrameQue[i].cRetries=0; //修改存储标志位 TxFrameQue[i].Flags.bits.bInUse=1; //喂狗,防止正常情况进入复位 CLR_WDT(); return i; } } return InValid_Index; } //删除重发队列内一条记录 WORD MACRemoveTxFrame(BYTE dsn) { BYTE i; BYTE SequenceNumber; for(i=0;i<ConstMacTxQueSize;i++) { //取出MAC帧的DSN SequenceNumber=TxFrameQue[i].cTxBuffer[3]; //根据DSN查找MAC帧 if((SequenceNumber==dsn) && (TxFrameQue[i].Flags.bits.bInUse)) { TxFrameQue[i].Flags.bits.bInUse=0; //把帧长度、把MAC层帧头和序列码置成空 TxFrameQue[i].cTxBuffer[TxBuffer.cSize++]=0; TxFrameQue[i].cTxBuffer[TxBuffer.cSize++]=0; TxFrameQue[i].cTxBuffer[TxBuffer.cSize++]=0; TxFrameQue[i].cTxBuffer[TxBuffer.cSize++]=0; CLR_WDT(); return i; } } return InValid_Index; } //查找重发记录 WORD MACSearchTxFrame(BYTE dsn) { BYTE i; BYTE SequenceNumber; for(i=0;i<ConstMacTxQueSize;i++) { //取出MAC帧的DSN SequenceNumber=TxFrameQue[i].cTxBuffer[3]; //根据DSN查找MAC帧 if((SequenceNumber==dsn) && (TxFrameQue[i].Flags.bits.bInUse)) return i; } return InValid_Index; } //MAC帧重发、超时处理函数 void MACRefreshTxFrame(void) { BYTE i; BYTE PacketSize; for(i=0;i<ConstMacTxQueSize;i++) { //若重发次数超过规定值,则丢弃 if(TxFrameQue[i].Flags.bits.bInUse) { if(TxFrameQue[i].cRetries>=aMaxFrameRetries) TxFrameQue[i].Flags.bits.bInUse=0; else if(DiffTicks(TxFrameQue[i].dwStartTime,GetTicks())>macPIB.macAckWaitDuration) { //否则对顶时间内,没有接收到ACK,重发 //取出长度 PacketSize=TxFrameQue[i].cTxBuffer[0]; //写入射频,已经包含了crc校验 PHYPutTxBuffer(TxFrameQue[i].cTxBuffer,PacketSize); //发送 MACTransmitByCSMA(); //记录发送时间 TxFrameQue[i].dwStartTime=GetTicks(); //重发次数加1 TxFrameQue[i].cRetries++; CLR_WDT(); } } } } //MAC帧重发队列统计 BYTE MACRecordTxFrame(void) { BYTE i; BYTE Number=0; for(i=0;i<ConstMacTxQueSize;i++) { //统计重发队列的记录 if(TxFrameQue[i].Flags.bits.bInUse) Number++; } return Number; } /**************************************************** //通过对协调器队列的管理,来选择一个可靠的网络加入 ****************************************************/ //格式化协调器列表 void MACFormatPANRecord(void) { WORD i; for(i=0;i<ConstCoordQueSize;i++) { CoordQue[i].bits.bInUse=0; CoordQue[i].LinkQuality=0; CoordQue[i].bits.RxNumber=0; } } //增加一个协调器节点 WORD MACAddPANRecord(PAN_DESCRIPTOR *Record) { WORD i; for(i=0;i<ConstCoordQueSize;i++) { if(!CoordQue[i].bits.bInUse) { CoordQue[i].bits.bInUse=1; //接收次数 CoordQue[i].bits.RxNumber=1; //允许加入 CoordQue[i].bits.allowJoin=1; //地址模式 CoordQue[i].CoordAddrMode=(*Record).CoordAddrMode; //其它值默认为0 CoordQue[i].SecurityUse=0; CoordQue[i].SecurityFailure=0; CoordQue[i].ACLEntry=0; //信道 CoordQue[i].LogicalChannel=PHYGetChannel(); //地址 CoordQue[i].CoordPANId.nVal=(*Record).CoordPANId.nVal; CoordQue[i].CoordShortAddr.nVal=(*Record).CoordShortAddr.nVal; memcpy((BYTE *)&CoordQue[i].CoordLongAddr,(BYTE *)&((*Record).CoordLongAddr),sizeof(LONG_ADDR)); //超帧描述 CoordQue[i].SuperframeSpec.nVal=(*Record).SuperframeSpec.nVal; //时间戳 CoordQue[i].TimeStamp=GetTicks(); //链路质量 CoordQue[i].LinkQuality=(*Record).LinkQuality; //网络深度 CoordQue[i].NwkDepth=(*Record).NwkDepth; CoordQue[i].CoorCDNum=(*Record).NwkDepth; CLR_WDT(); return i; } } return InValid_Index; } //查找协调器节点 WORD MACSearchPANRecord(PAN_DESCRIPTOR *Record) { WORD i; BYTE Number; for(i=0;i<ConstCoordQueSize;i++) { if(CoordQue[i].bits.bInUse) { //若是短地址,0代表短地址,1代表长地址 if(!CoordQue[i].CoordAddrMode) { (*Record).CoordAddrMode=0; if((*Record).CoordPANId.nVal == CoordQue[i].CoordPANId.nVal) { return i; } } else { //若是长地址 (*Record).CoordAddrMode=1; Number=memcmp((BYTE *)&CoordQue[i].CoordLongAddr, (BYTE *)&((*Record).CoordLongAddr),sizeof(LONG_ADDR)); if(Number==0) return i; } } } return InValid_Index; } //根据网络标示查询协调器列表 WORD MACSearchPANRecordByPAN(SHORT_ADDR PANId) { WORD i; for(i=0;i<ConstCoordQueSize;i++) { if(CoordQue[i].bits.bInUse) { if(CoordQue[i].CoordPANId.nVal==PANId.nVal) return i; } } return InValid_Index; } //修改协调器节点的通信次数 void MACRefreshPANRecord(PAN_DESCRIPTOR *Record) { WORD Index; // WORD LinkQuality; // WORD NwkNumber; //查询目前节点的列表中是否已经存在该网络 Index=MACSearchPANRecord(Record); //如果不存在网络,则把协调器加入列表中 if(Index==InValid_Index) { //根据链路质量判断是否加入。 if((*Record).LinkQuality >= RssiLevel) { MACAddPANRecord(Record); JoinNwkIndction = 1; } } } //根据所属的网络,加入到网络中 WORD MACSearchSuitPANRecord(PAN_DESCRIPTOR *Record) { WORD i; for(i=0;i<ConstCoordQueSize;i++) { if(CoordQue[i].bits.bInUse) { memcpy((BYTE *)Record,(BYTE *)&CoordQue[i],sizeof(PAN_DESCRIPTOR)); return i; } } return InValid_Index; } //选择一个最好的网络,选择的条件是链路的质量 WORD MACSearchPrioPANRecord(PAN_DESCRIPTOR *Record) { WORD i; WORD MaxCount=0; BOOL allowCoord; WORD Index=InValid_Index; for(i=0;i<ConstCoordQueSize;i++) { allowCoord=CoordQue[i].SuperframeSpec.bits.AssociationPermit & CoordQue[i].bits.allowJoin; if(CoordQue[i].bits.bInUse && allowCoord && CoordQue[i].LinkQuality>MaxCount) { MaxCount=CoordQue[i].LinkQuality; Index=i; } } if((MaxCount>0) && (Index!=InValid_Index)) { memcpy((BYTE *)Record,(BYTE *)&CoordQue[Index],sizeof(PAN_DESCRIPTOR)); return Index; } return InValid_Index; } //统计网络的数量 WORD MACCountPANRecord(void) { WORD i; WORD Number=0; BOOL allowCoord; for(i=0;i<ConstCoordQueSize;i++) { allowCoord=CoordQue[i].SuperframeSpec.bits.AssociationPermit & CoordQue[i].bits.allowJoin; if(CoordQue[i].bits.bInUse && allowCoord) { Number++; } } return Number; } //超时处理 void MACProccessPANRecordByTimeout(void) { WORD i; for(i=0;i<ConstCoordQueSize;i++) { if(CoordQue[i].bits.bInUse) { if(DiffTicks(CoordQue[i].TimeStamp,GetTicks())>1000) { CoordQue[i].bits.bInUse=0; } } } } //路由器、节点加入网络函数 void MACJoinPAN(void) { WORD Index; NODE_INFO Record; ASSOC_REQUEST_CAP CapInfo; //只要收到了协调器发来的信标帧,则不会再发送信标请求,直接查找自己的记录,自己所属的协调器。 if(JoinNwkIndction == 1) { //查找自己所属的协调器 Index=MACSearchPrioPANRecord(&PANDescriptor); if(Index!=InValid_Index) { CapInfo.cVal=0; //不能成为协调器 CapInfo.bits.EnableCoord=0; //RFD CapInfo.bits.DeviceType=MACGetDeviceType(); //供电方式永在 CapInfo.bits.PowerSource=1; //空闲处于接收状态 CapInfo.bits.ReceiveIdle=1; //没有使用安全模式 CapInfo.bits.EnableSecur=0; //要求协调器分配地址 CapInfo.bits.AllocAddress=1; //发送入网请求,若是短地址,应该进入这个if if(PANDescriptor.CoordAddrMode==0) { Record.AddrMode=MAC_DST_SHORT_ADDR; Record.PANId.nVal=PANDescriptor.CoordPANId.nVal; Record.ShortAddr.nVal=PANDescriptor.CoordShortAddr.nVal; memcpy((BYTE *)&PANDescriptor,(BYTE *)&PANDescriptor,sizeof(PAN_DESCRIPTOR)); MACSendAssociationReq(&Record,CapInfo); } else if(PANDescriptor.CoordAddrMode==1) { Record.AddrMode=MAC_DST_LONG_ADDR; Record.PANId.nVal=PANDescriptor.CoordPANId.nVal; Record.PANId.nVal=PANDescriptor.CoordPANId.nVal; memcpy((BYTE *)&Record.LongAddr,(BYTE *)&PANDescriptor.CoordLongAddr,sizeof(LONG_ADDR)); memcpy((BYTE *)&PANDescriptor,(BYTE *)&PANDescriptor,sizeof(PAN_DESCRIPTOR)); MACSendAssociationReq(&Record,CapInfo); } } } else { if((!macStatus.bits.isAssociated)) { //首先要发送一个信标请求 MACSendBeaconReq(); } } } //节点发送信标请求命令 BOOL MACSendBeaconReq(void) { BYTE cSize=0; BYTE cPtrTx[5]; BYTE addrMode; NODE_INFO macAddr; //封装MAC帧头 //目的地址模式为短地址 macAddr.AddrMode = MAC_DST_SHORT_ADDR; //目的网络标识为广播 macAddr.PANId.nVal=0xFFFF; //目的地址为广播 macAddr.ShortAddr.nVal=0xFFFF; //临时存储源地址模式,MAC层初始化的时候默认为长地址模式。 addrMode=macStatus.bits.addrMode; //源地址模式为空,即信标请求帧中不包含源地址信息 macStatus.bits.addrMode=0; MACPutHeader(&macAddr,MAC_FRAME_CMD); //恢复地址模式 macStatus.bits.addrMode=addrMode; //封装数据 cPtrTx[cSize++]=MAC_BEACON_REQUEST; MACPutTxBuffer(cPtrTx,cSize); CLR_WDT(); //发送 return MACTransmitPacket(); } /**************************************************************************/ // 节点发送入网请求 //目的地址:网络PAN,目的地址根据信标帧确定 //源地址:源PAN为广播,长地址模式 //挂起设置为0,确认帧为1 /**************************************************************************/ BOOL MACSendAssociationReq(NODE_INFO *macAddr,ASSOC_REQUEST_CAP CapInfo) { BYTE cSize=0; BYTE cPtrTx[5]; SHORT_ADDR PANId; //封装MAC帧头 //临时存储源网络标识 PANId.nVal=macPIB.macPANId.nVal; //源地址网络标示为广播 macPIB.macPANId.nVal=0xFFFF; //目的地址模式根据信标帧来确定 MACPutHeader(macAddr,MAC_FRAME_CMD); //发送入网请求命令帧 //恢复源网络标识 macPIB.macPANId.nVal=PANId.nVal; //封装数据 cPtrTx[cSize++]=MAC_ASSOC_REQUEST; cPtrTx[cSize++]=CapInfo.cVal; cPtrTx[cSize++]=macPIB.CDNum; MACPutTxBuffer(cPtrTx,cSize); //发送 return MACTransmitPacket(); } /******************************************************************************/ // 离开网络命令 //协调器或RFD发起 //目的地址:长地址模式,网络标识为macPANId //源地址:长地址模式 //挂起为0,ACK设为1, /******************************************************************************/ BOOL MACSendDisassociationNotify(LONG_ADDR *LongAddr,MAC_DISASSOCIATION_REASON Reason) { BYTE cSize=0; BYTE cPtrTx[5]; BYTE addrMode; NODE_INFO macAddr; //封装MAC帧头 //地址模式要用长地址 macAddr.AddrMode=MAC_DST_LONG_ADDR; macAddr.PANId.nVal=0xFFFF; memcpy((BYTE *)&macAddr.LongAddr,(BYTE *)LongAddr,sizeof(LONG_ADDR)); //临时存储地址模式 addrMode=macStatus.bits.addrMode; //源地址模式临时设为长地址 macStatus.bits.addrMode=MAC_SRC_LONG_ADDR; MACPutHeader(&macAddr,MAC_FRAME_CMD|MAC_ACK_YES); //恢复源地址模式 macStatus.bits.addrMode=addrMode; //封装数据 cPtrTx[cSize++]=MAC_DISASSOC_NOTIFY; cPtrTx[cSize++]=Reason; MACPutTxBuffer(cPtrTx,cSize); CLR_WDT(); //发送 return MACTransmitPacket(); } void MACFlushTxFrame(void) { macCurrentRxFrame.bReady=0; } void MACTask(void) { int i; BYTE size; BYTE *ptr; BYTE **pptr; BYTE *psize; pptr=&ptr; psize=&size; BYTE DeviceType; NODE_INFO DestShortAddr; BYTE frameCON; BYTE cSize=0; i=emWaitMesg(RF_REV_MESSAGE_REQ,RealTimeMesg,0,0); if(i==1) { MACProcessPacket(); } i=emWaitMesg(RF_SENT_MESSAGE_REQ,RealTimeMesg,pptr,psize); if(i==1) { DestShortAddr.AddrMode=*ptr++; DestShortAddr.PANId.cVal[0]=*ptr++; DestShortAddr.PANId.cVal[1]=*ptr++; DestShortAddr.ShortAddr.cVal[0]=*ptr++; DestShortAddr.ShortAddr.cVal[1]=*ptr++; //发送数据包; memcpy((BYTE *)&DestShortAddr.LongAddr.cVal[0],ptr,8); ptr+=8; size=size-13; frameCON=*ptr++; size--; MACPutHeader(&DestShortAddr,frameCON); MACPutTxBuffer(ptr,size); MACTransmitPacket(); } //MAC层的任务之一,用于组网。 i=emWaitMesg(RF_JOIN_NETWORK_REQ,RealTimeMesg,0,0); if(i==1) { DeviceType=macPIB.DeviceInfo.bits.DeviceType; //如果设备类型是节点并且没有入网 if((DeviceType==ZIGBEE_RFD) && (!MACIsNetworkJoined())) { MACJoinPAN(); } } i=emWaitMesg(RF_FLUSH_RSPBUFFER_RSP,RealTimeMesg,0,0); if(i==1) { //清除缓冲区 MACCfgRspBuf.Ptr=0; cSize=0; if(MACCfgRspSharBuf.bReady==1) { for(i=0;i<MACCfgRspSharBuf.Ptr;i++) { MACCfgRspBuf.Buffer[MACCfgRspBuf.Ptr++]=MACCfgRspSharBuf.Buffer[cSize++]; } MACCfgRspSharBuf.bReady=0; MACCfgRspSharBuf.Ptr=0; } } MACRefreshTxFrame(); PHYDetectStatus(); CurrentTaskWait(); SchedTask(); } <file_sep>/************************************************************ 文件描述:本文件主要是用来实现无限传感器网络的PHY层的基本功能,包括信道选择, 激活射频状态,能量检测,发送和接收数据 版本信息:v1.0 修改时间:2008/03/ *************************************************************/ #ifndef _PHY_H #define _PHY_H #include "zigbee.h" #include "driver.h" #include "mcu.h" #include "em16RTOS24.h" #include "Nvm_Flash.h" //定义信道的最大值 #define ConstRFChannelSize 16 //定义功率的最大等级数 #define ConstRFPowerSize 18 //定义波特率的最大等级数 #define ConstRFBaudRateSize 4 /**********不同通信速率,RSSI_OFFSET的值不一样**************** 2.4K 71 10K 69 250K 72 500K 72 ***************************************************************/ typedef RF_TRX_STATE PHY_TRX_STATE; typedef struct _RHY_RX_BUFFER //接收缓冲区 { BYTE RxBuffer[ConstPhyRxBufferSize]; struct { WORD cWrite; //记录写入的位置 WORD cRead; //记录读出的位置 }Postion; //记录接收缓冲区读写位置 }PHY_RX_BUFFER; /********************************************************************* * 函数名: void PHYInitSetup(void) * 前提条件: SPIInit()已经调用 * 输入参数: BYTE *pTxBuffer,写入值的指针,BYTE size写入的字节数 * 输出参数: 无 * 注意事项: 无 * 功能描述: 实现物理层的一些基本设置,phyPIB,信道,速率,校验,RF的激活 ********************************************************************/ void PHYInitSetup(void); /********************************************************************* * 函数名: BYTE PHYDetectEnergy(void); * 前提条件: PHYInitSetup()已经调用 * 输入参数: 无 * 输出参数: 返回当前信道的能量值 * 注意事项: 无 * 功能描述: 用来检测信号的强弱 ********************************************************************/ BYTE PHYDetectEnergy(void);//能量检测 /********************************************************************* * 函数名: void PHYSetTxPower(BYTE cPower) * 前提条件: SPIInit()已经调用 * 输入参数: BYTE cPower,发射的功率值 * 输出参数: 无 * 注意事项: 无 * 功能描述: 用于设定发射功率值 ********************************************************************/ //设置发送功率 WORD PHYSetTxPower(BYTE Index); //设置波特率 void PHYSetBaudRate(BYTE BaudRate); /********************************************************************* * 函数名: BOOL PHYRevPacket(void) * 前提条件: 接收到数据包后触发中断 * 输入参数: 无 * 输出参数: 如果接收到一个正确的数据包,返回TRUE * 注意事项: 如果接收到一个错误的数据包后,进行错误处理是关键中的关键 * 功能描述: 把接收到的数据包都放到自定义的接收缓冲区中去 ********************************************************************/ void PHYPut(BYTE cVal); BYTE PHYGet(void); void PHYGetArray(BYTE *ptr,BYTE cSize); WORD PHYSetChannel(BYTE Index); BOOL PHYExistPacket(void); BYTE PHYGetLinkQuality(BYTE rssi); #define PHY_RF_GDO0 RF_GDO0 #define PHY_RF_GDO2 RF_GDO2 #define PHYSetTRxState(state) RFSetTRxState(state) //设置射频的收发状态 #define PHYGetTRxState() RFGetTRxState //读取射频的状态 #define PHYSetBaud(v) RFSetBaudRate(v) #define PHYSetTxPwr(v) RFSetTxPower(v) #define PHYSetChan(v) RFSetChannel(v) #define PHYGetChannel() phyPIB.phyCurrentChannel //获取信道 #define PHYGetTxPower() phypIB.phyTransmitPower #define PHYDetectStatus() RFDetectStatus() #define PHYGetTxNumber() RFGetStatus(REG_TXBYTES)&0x7F; #define PHYGetRxStatus() RFGetStatus(REG_RXBYTES); #define PHYDetectChannels() RFGetStatus(REG_PKTSTATUS)&0x10 //取出CCA位0001 0000 #define PHYClearTx() RFClearTxBuffer() #define PHYClearRx() RFClearRxBuffer() //RF FlushFIFO #define PHYReadRx() RFReadRxFIFO() //从RF接收缓冲区中读一个数 #define PHYPutTxBuffer(ptr,size) RFWriteTxFIFO(ptr,size) #define PHYTranmitByCSMA() RFTranmitByCSMA() WORD PHYGetPosition(void); BOOL PHYPutRxBuffer(void); #endif <file_sep>#ifndef _SPI_H_ #define _SPI_H_ #include "common.h" #include "mcu.h" extern WORD data; #define HCK LATAbits.LATA4 // 片选信号 #define DS LATAbits.LATA3 // 输入引脚 void HC595Put(WORD cByte); void HC595Out(void); /************************************************************ *下面是函数的声明 *************************************************************/ /********************************************************************* * 函数名: BYTE SPIGet(void) * 前提条件: SPIInit()已经调用 * 输入参数: 无 * 输出参数: SPI总线上的一个字节的数据值 * 注意事项: SPI总线上得到数据是一位一位的得到,然后组成一个字节返回。 * 功能描述: 从SPI总线上读取一个字节的数据 ********************************************************************/ BYTE SPIGet(void); /********************************************************************* * 函数名: void SPIPut(BYTE cValue) * 前提条件: SPIInit()已经调用 * 输入参数: BYTE cValue,要写入SPI总线上的数据 * 输出参数: 无 * 注意事项: 无。 * 功能描述: 向SPI总线上写一个字节的数据 ********************************************************************/ void SPIPut(BYTE v); #endif <file_sep>#include "common.h" void Delay(WORD t) //延时时间t*2+5us { WORD i; for(i=t;i>0;i--) { Delay_2us(); ClrWdt(); } for(i=1;i>0;i--); Nop(); } /************************************************* //1、链接指针lnk,1个周期 //2、 1个周期nop //3、1个周期, ulnk,释放堆栈 //4、3个周期 return,从函数中返回 **************************************************/ void Delay_2us(void) //1/(8MHZ/2)=0.25us { Nop(); Nop(); Nop(); } <file_sep>#ifndef _INFRA_H #define _INFRA_H #include "common.h" extern BYTE Parameter[PARAMETER_NUM]; #define HIGH LATAbits.LATA2=1 #define LOW LATAbits.LATA2=0 #define DEVIATION 0 //本参数可变 #define CODELENTH 400 #define HOT 1 #define COLD 2 #define OFF 3 extern BYTE dark; extern WORD code_n; extern BYTE code_flag; //1:hot 2:cold 3:off extern BYTE sent_flag; extern WORD codearray_hot[CODELENTH]; extern WORD codearray_cold[CODELENTH]; extern WORD codearray_off[CODELENTH]; extern WORD count; extern WORD sizecode_hot; extern WORD sizecode_cold; extern WORD sizecode_off; void cleararray(void); void infraInit(void); BOOL hot_to_flash(void); BOOL cold_to_flash(void); BOOL off_to_flash(void); void IC1_Init(void); void T5_Init(void); void T3_Init(void); void PWM_Init(void); void infra_open(void); void InfraTask(void); void infra_sent_hot(void); void infra_sent_cold(void); void infra_sent_off(void); #endif <file_sep>#ifndef _LED_H #define _LED_H #include "mcu.h" void Light_Control(void); void InOut_Control(void); void Condi_Control(void); void ADInit(void); #define DQ_HIGH TRISBbits.TRISB1=1 #define DQ_LOW TRISBbits.TRISB1=0 #define DQ PORTBbits.RB1 WORD DS18B20_Get_Temp(void); void wendu_change(void); void TemTask(void); #endif <file_sep>#include <p24FJ64GA002.h> #include <stdlib.h> #include "em16RTOS24.h" unsigned char CurrentTaskId;// 当前运行任务的ID unsigned char CurrentTaskPrio;//当前运行任务的优先级 unsigned char TaskStatusMask = 0; //任务状态掩码,每个位对应一个任务,当任务就绪时,对应位为1, volatile unsigned int CurrentTaskPCL; volatile unsigned int CurrentTaskPCH; volatile unsigned int CurrentTaskSPTop; volatile unsigned int CurrentTaskSPRoot; volatile unsigned long mSeconds=0; TCB pTcb[TaskNum]; // tasknum 不能超过maxtasknum MCB pMcb[TaskNum]; HardTimer pHt[MaxTimer]; LAYMESG pLayMesg[MaxLayMesg]; void emSysInit(void) { int j; for(j=0;j<TaskNum;j++) { pTcb[j].TaskStatus=TASKNULL; //先将所有任务设为空,以备后面应用 pTcb[j].TaskPrioty=15; } pMcb[15].MessageContext=NULLMESG;//将系统消息先设为空 for(j=0;j<MaxLayMesg;j++) { pLayMesg[j].LayerChangMesg=NULLMESG; pLayMesg[j].Msg_Info_Ptr.Ptr=0; pLayMesg[j].Msg_Info_Ptr.cSize=0; pLayMesg[j].TaskQueue.TaskWaitId=0; pLayMesg[j].Flags.cVal=0; } } void ChangeStatus(unsigned char id)//测试用函数 用完删除 { pTcb[id].TaskStatus =READY; } void CurrentTaskWait() { pTcb[CurrentTaskId].TaskStatus = WAIT; } void SetTimerTick(unsigned int Tick)//Timer1做时钟节拍 { T1CON=0x00; T1CONbits.TCKPS=1;//分频 TMR1=0x00; PR1 = Tick;// IPC0bits.T1IP = 0x07;//优先级7 IFS0bits.T1IF = 0; IEC0bits.T1IE = 1; T1CONbits.TON = 1; } void DisInt()// 禁止中断,进入临界区 { SRbits.IPL = 7; //禁止中断嵌套后IPL只读,写无效 //CORCON中IPL3(只读)与SR中IPL3位组成CPU中断优先级,>=7禁止用户中断 IEC0bits.U1RXIE=0; IEC0bits.T1IE = 0; } void EnInt()//允许中断,退出临界区 { SRbits.IPL = 0; IEC0bits.U1RXIE=1; IEC0bits.T1IE = 1; } void IdleTask()//默认的空闲任务 { while(1) { Nop(); } } void CreateTask(void (* TaskName)(), unsigned char Id, unsigned char Prio, unsigned char stat) { TaskStack * stacktemp; unsigned int Idtemp = Id; unsigned long tempTaskPC = 0; unsigned int tempPCL = 0; unsigned int tempPCH = 0; unsigned int TestName; TestName=TaskName; tempTaskPC = (unsigned long) TestName; tempPCL = tempTaskPC; tempPCH = tempTaskPC >> 16; stacktemp = (TaskStack *) malloc(sizeof(TaskStack)); if(NULL == stacktemp) { Idtemp = Id; //这里留着可以设个断点 看是否分配成功 return ; //注意这里将来要完善 } stacktemp->TaskPCL = tempPCL; stacktemp->TaskPCH = tempPCH; stacktemp->TaskPSVPAG = 0; stacktemp->TaskRCOUNT = 0; stacktemp->TaskCORCON = 0; stacktemp->TaskTBLPAG = 0; stacktemp->TaskW0 = 0; stacktemp->TaskW1 = 0; stacktemp->TaskW2 = 0; stacktemp->TaskW3 = 0; stacktemp->TaskW4 = 0; stacktemp->TaskW5 = 0; stacktemp->TaskW6 = 0; stacktemp->TaskW7 = 0; stacktemp->TaskW8 = 0; stacktemp->TaskW9 = 0; stacktemp->TaskW10 = 0; stacktemp->TaskW11 = 0; stacktemp->TaskW12 = 0; stacktemp->TaskW13 = 0; stacktemp->TaskW14 = 0; pTcb[Idtemp].TaskSP = (unsigned int) stacktemp; pTcb[Idtemp].TaskId = Id; pTcb[Idtemp].TaskStatus = stat; pTcb[Idtemp].TaskPrioty = Prio; pTcb[Idtemp].TaskPCL = tempPCL; pTcb[Idtemp].TaskPCH = tempPCH; } void StartTask() { unsigned char i = 0; unsigned char MaxPrioTaskId = 0; unsigned char MaxPrio = 16; DisInt(); for(i=0; i<TaskNum; i++) { if ( READY == pTcb[i].TaskStatus && pTcb[i].TaskPrioty < MaxPrio ) { MaxPrio = pTcb[i].TaskPrioty; MaxPrioTaskId = i; } } ///以下为开机首次任务调度 CurrentTaskId = MaxPrioTaskId; CurrentTaskPrio = MaxPrio; CurrentTaskSPRoot = (unsigned int) pTcb[CurrentTaskId].TaskSP; CurrentTaskSPTop = (unsigned int) pTcb[CurrentTaskId].TaskSP+42;//0x2C; CurrentTaskPCL = pTcb[CurrentTaskId].TaskPCL; CurrentTaskPCH = pTcb[CurrentTaskId].TaskPCH; EnInt(); asm volatile ("push _CurrentTaskPCL"); asm volatile ("push _CurrentTaskPCH"); asm volatile ("return"); } unsigned int FindMaxPrioTask() //在任务中调用 { unsigned char i = 0; unsigned char MaxPrioTaskId = 0; // 这里可以把这两个临时变量去掉 直接用CurrentId来进入循环判断 unsigned char MaxPrio = 16; //优先级越高 值越小 for(i=0; i<TaskNum; i++) { if ( READY == pTcb[i].TaskStatus && pTcb[i].TaskPrioty < MaxPrio ) { MaxPrio = pTcb[i].TaskPrioty; MaxPrioTaskId = i; } } if(CurrentTaskId == MaxPrioTaskId) { return 0;//返回值被放到w0 } CurrentTaskId = MaxPrioTaskId; CurrentTaskPrio = MaxPrio; CurrentTaskSPRoot = (unsigned int)pTcb[CurrentTaskId].TaskSP; CurrentTaskSPTop = (unsigned int)pTcb[CurrentTaskId].TaskSP+42; CurrentTaskPCL = pTcb[CurrentTaskId].TaskPCL; CurrentTaskPCH = pTcb[CurrentTaskId].TaskPCH; return 1; } unsigned int IntFindMaxPrioTask() //在中断中调用 { unsigned char i = 0; unsigned char MaxPrioTaskId = 0; // 这里可以把这两个临时变量去掉 直接用CurrentId来进入循环判断 unsigned char MaxPrio = 16;//优先级越高 值越小 MaxPrio = CurrentTaskPrio; MaxPrioTaskId = CurrentTaskId; // 接下来查找优先级最高的就绪任务 //查找中断服务程序是否唤醒了比当前任务更高优先级的任务,是,跳转, 否 ,回到当前任务 for(i=0; i<TaskNum; i++) { if ( READY == pTcb[i].TaskStatus && pTcb[i].TaskPrioty < MaxPrio ) { MaxPrio = pTcb[i].TaskPrioty; MaxPrioTaskId = i; } } if(CurrentTaskId == MaxPrioTaskId) { return 0;//返回值被放到w0 } pTcb[CurrentTaskId].TaskStatus = READY; //这里是和任务中调用不同的地方 没有设当前任务为WAIT而是READY CurrentTaskId = MaxPrioTaskId; CurrentTaskPrio = MaxPrio; CurrentTaskSPRoot = (unsigned int)pTcb[CurrentTaskId].TaskSP; CurrentTaskSPTop = (unsigned int)pTcb[CurrentTaskId].TaskSP+42; CurrentTaskPCL = pTcb[CurrentTaskId].TaskPCL; CurrentTaskPCH = pTcb[CurrentTaskId].TaskPCH; return 1; } unsigned char TxMessage(unsigned char RxMesgTaskId,unsigned char message) { if(pMcb[RxMesgTaskId].MessageContext!=NULLMESG) return 0; //pMcb[RxMesgTaskId].TxMessageTaskId = CurrentTaskId; pMcb[RxMesgTaskId].MessageContext = message; pTcb[RxMesgTaskId].TaskStatus = READY; return 1; } unsigned char RxMessage(unsigned char message) { if(message == pMcb[CurrentTaskId].MessageContext) { pMcb[CurrentTaskId].MessageContext=NULLMESG; return 1; } else return 0; } unsigned char emSetHardTimer(unsigned char tid, unsigned int value)//设置定时器 { pHt[tid].htstatus.IDtimer.Flg=HARD_TIMER_NULL; pHt[tid].Lt_value=value; return 1; } unsigned char emStartHardTimer(unsigned char tid) { if(pHt[tid].htstatus.IDtimer.Flg!=HARD_TIMER_NULL) return 0; pHt[tid].htstatus.IDtimer.Flg=HARD_TIMER_WORK; pHt[tid].temp=mSeconds; return 1; } unsigned char emCheckHardTimer(unsigned char tid) { unsigned long tv,ttv; if(pHt[tid].htstatus.IDtimer.Flg!=HARD_TIMER_WORK) return 0; tv=pHt[tid].Lt_value; if(mSeconds<pHt[tid].temp)//mSecond overflow { ttv=4294967295-pHt[tid].temp+mSeconds; //4294967296 if(ttv<tv)//没有到设定的定时值,返回0 return 0; if(ttv>tv) { pHt[tid].temp=mSeconds; return 5;//pHt[tid].htstatus.IDtimer.Flg=5; } else { pHt[tid].temp=mSeconds; return 1; } } else { ttv=mSeconds-pHt[tid].temp; if(ttv>tv) { pHt[tid].temp=mSeconds; return 5; } if(ttv<tv) return 0; else { pHt[tid].temp=mSeconds; return 1; } } } void emDelHardTimer(unsigned char tid) { pHt[tid].htstatus.IDtimer.Flg=HARD_TIMER_NULL; } void emTxSysMesg(unsigned char message) { unsigned char i; DisInt(); pMcb[15].MessageContext=message; for(i=0;i<15;i++)//将所有任务都变成READY,以便于所有任务都能接收此消息,前提是RTOS相当于任务15 { if((pTcb[i].TaskStatus>1)&&(pTcb[i].TaskStatus<15)) pTcb[i].TaskStatus=READY; } EnInt(); } unsigned char emRxSysMesg(void)//用此函数接收系统消息 { unsigned char i; if(pMcb[15].MessageContext==NULLMESG) return 0; i=pMcb[15].MessageContext; return i; } void emDelSysMesg(void) { if(pMcb[15].MessageContext!=NULLMESG) pMcb[15].MessageContext=NULLMESG; } int emWaitMesg(unsigned char message,unsigned char state,unsigned char **ptr,unsigned char *size)//如果消息指向了某处,即消息结构体中的ptr值不为0,则将size字节的数据读取到形参ptr中。 { unsigned char i; // DisInt(); for(i=0;i<MaxLayMesg;i++) { //for messges in use if(pLayMesg[i].Flags.bits.bInUse==1&&pLayMesg[i].LayerChangMesg==message) { if(pLayMesg[i].Flags.bits.bRealMesg) //真正产生了消息了 { if(pLayMesg[i].Msg_Info_Ptr.cSize!=0) { *ptr=pLayMesg[i].Msg_Info_Ptr.Ptr; *size=pLayMesg[i].Msg_Info_Ptr.cSize; } else { ptr=0; size=0; } if(pLayMesg[i].Flags.bits.bRealTime!=1) //不是实时信息,则当消息数为0时,要除去该消息;如果消息数不为0,则不除去该消息 { pLayMesg[i].Flags.bits.bMesgNum--; //已经处理了一个该消息 if(pLayMesg[i].Flags.bits.bMesgNum==0) { pLayMesg[i].LayerChangMesg=NULLMESG; pLayMesg[i].TaskQueue.TaskWaitId=0; pLayMesg[i].Msg_Info_Ptr.Ptr=0; pLayMesg[i].Msg_Info_Ptr.cSize=0; pLayMesg[i].Flags.cVal=0; } else { pLayMesg[i].Flags.bits.bWaitMesg=0; //目前如果只能是每种消息只能是一个任务发送的话,就可以这样做,但是如果是每种消息可以由多个任务发送的话 //就要做相应的处理了,这里需要注意! pLayMesg[i].Flags.bits.bRealTime=0; pLayMesg[i].TaskQueue.TaskWaitId=0; pLayMesg[i].Msg_Info_Ptr.Ptr=0; pLayMesg[i].Msg_Info_Ptr.cSize=0; pLayMesg[i].Flags.bits.bRealMesg=1; } } else pLayMesg[i].Flags.bits.bRealMesg=0; pLayMesg[i].Msg_Info_Ptr.Ptr=0; pLayMesg[i].Msg_Info_Ptr.cSize=0; return 1; //返回值为1,说明等到了消息,则进行相应的操作 } else //没有产生消息 return -1; } } for(i=0;i<MaxLayMesg;i++) { //for messages not using if(pLayMesg[i].Flags.bits.bInUse==0) { if(state==RealTimeMesg) pLayMesg[i].Flags.bits.bRealTime=1; else pLayMesg[i].Flags.bits.bRealTime=0; pLayMesg[i].LayerChangMesg=message; pLayMesg[i].TaskQueue.TaskWaitId=CurrentTaskId; pLayMesg[i].TaskQueue.TaskPrioty=CurrentTaskPrio; pLayMesg[i].Flags.bits.bInUse=1; pLayMesg[i].Flags.bits.bWaitMesg=1; pLayMesg[i].Flags.bits.bRealMesg=0; //并不是真正的产生该消息了,而是创建了该消息。 pLayMesg[i].Flags.bits.bMesgNum=0; pLayMesg[i].Msg_Info_Ptr.Ptr=0; pLayMesg[i].Msg_Info_Ptr.cSize=0; return -1; //返回值为-1,说明没有等到消息,但是已经发送命令,待下次收到消息后即可执行相应的操作了。 } } return 0; //没有空间才存储等待message的任务了,需要通知该任务,该任务等待消息失败了,不会被 //消息唤醒了,除非重新发送消息。 } unsigned char emTxMesg(unsigned char message,unsigned char state,unsigned char *ptr,unsigned char size)//如果发送的消息带有数据,则数据存在于形参ptr中,此时,需要将该数据传递到消息结构体中,以便等待消息函数或者发送消息函数来读取。 { unsigned char i; unsigned char RxLayTaskId; //DisInt(); for(i=0;i<MaxLayMesg;i++) { if(pLayMesg[i].Flags.bits.bInUse==1&&pLayMesg[i].LayerChangMesg==message) { if(size!=0) { pLayMesg[i].Msg_Info_Ptr.Ptr=ptr; pLayMesg[i].Msg_Info_Ptr.cSize=size; } pLayMesg[i].Flags.bits.bRealMesg=1; if(pLayMesg[i].Flags.bits.bRealTime)//如果是实时消息 { pLayMesg[i].Flags.bits.bMesgNum=1; if(pLayMesg[i].Flags.bits.bWaitMesg==1) { RxLayTaskId=pLayMesg[i].TaskQueue.TaskWaitId; pTcb[RxLayTaskId].TaskStatus = READY; return 1; } else return 0; //虽然是实时性消息,但是没有任务在等待该实时性消息,所以返回错误。 } else //如果是非实时性消息 { pLayMesg[i].Flags.bits.bMesgNum++; if(pLayMesg[i].Flags.bits.bWaitMesg==1) { RxLayTaskId=pLayMesg[i].TaskQueue.TaskWaitId; pTcb[RxLayTaskId].TaskStatus = READY; } return 1; } //else } //如果消息存在 } if(state==1) { return 0; //说明虽然是实时性消息,但是没有任务在等待该消息。 } for(i=0;i<MaxLayMesg;i++) { if(pLayMesg[i].Flags.bits.bInUse==0) { pLayMesg[i].Flags.bits.bInUse=1; pLayMesg[i].LayerChangMesg=message; pLayMesg[i].Flags.bits.bMesgNum=0; pLayMesg[i].Flags.bits.bMesgNum++; pLayMesg[i].Flags.bits.bRealMesg=1; if(!size) { pLayMesg[i].Msg_Info_Ptr.Ptr=ptr; pLayMesg[i].Msg_Info_Ptr.cSize=size; } return 1; } } //EnInt(); return 0; } unsigned char emSearchMesg(unsigned char message) { unsigned char i; for(i=0;i<MaxLayMesg;i++) { if(pLayMesg[i].Flags.bits.bInUse==1&&pLayMesg[i].LayerChangMesg==message) { if(pLayMesg[i].Flags.bits.bRealMesg) //真正产生了消息了 { return i; } } } return InvalidMesg; //搜索的消息不存在 } unsigned char emRxMesg(unsigned char Index,unsigned char state,unsigned char *ptr,unsigned char size) { if((pLayMesg[Index].Flags.bits.bInUse==1)&&(pLayMesg[Index].Flags.bits.bRealMesg==1)) { if(pLayMesg[Index].Flags.bits.bRealTime!=1) //不是实时信息,则当消息数为0时,要除去该消息;如果消息数不为0,则不除去该消息 { pLayMesg[Index].Flags.bits.bMesgNum--; //已经处理了一个该消息 if(pLayMesg[Index].Flags.bits.bMesgNum==0) { pLayMesg[Index].LayerChangMesg=NULLMESG; pLayMesg[Index].TaskQueue.TaskWaitId=0; pLayMesg[Index].Msg_Info_Ptr.cSize=0; pLayMesg[Index].Flags.cVal=0; } else { pLayMesg[Index].Flags.bits.bRealMesg=1; pLayMesg[Index].Flags.bits.bWaitMesg=0; pLayMesg[Index].Flags.bits.bRealTime=0; pLayMesg[Index].TaskQueue.TaskWaitId=0; pLayMesg[Index].Msg_Info_Ptr.Ptr=0; pLayMesg[Index].Msg_Info_Ptr.cSize=0; } return 1; } else { return 0; } } return 0; } void emDelMesg(unsigned char message) { unsigned char i; for(i=0;i<MaxLayMesg;i++) { if(pLayMesg[i].Flags.bits.bInUse==1&&pLayMesg[i].LayerChangMesg==message) { pLayMesg[i].LayerChangMesg=NULLMESG; pLayMesg[i].TaskQueue.TaskWaitId=0; pLayMesg[i].Msg_Info_Ptr.Ptr=0; pLayMesg[i].Msg_Info_Ptr.cSize=0; pLayMesg[i].Flags.cVal=0; } } } <file_sep>#include "tick.h" //设定一个时间片,每到中断,dwSeconds自增 #define MAX_COUNT_VALUE 0xFFFFFFFF //用于实现定时器的中断次数累计 extern unsigned long mSeconds; //全局变量在哪个文件中定义,一定在相应文件中初始化 //获取当前时间 TICK GetTicks(void) { return mSeconds; } //计算时间间隔 TICK DiffTicks(TICK start,TICK end) { TICK dwValue; if(end>=start) dwValue=end-start; else dwValue=MAX_COUNT_VALUE+end-start; return dwValue; } //同步时间 void SynTicks(TICK tick) { mSeconds=tick; } <file_sep>#ifndef _ADDR_H #define _ADDR_H #include "common.h" #include "zigbee.h" #include "Interface.h" //自动获取长地址算法 //void AllocIEEEAddr(LONG_ADDR *LongAddr); //指数运算,Rm^(Lm-d-1) WORD CalcExponentVal(WORD v,BYTE exp); //自动分配地址算法 SHORT_ADDR AllocShortAddr(WORD InitialVal) ; #endif <file_sep>#include "common.h" #include "infra.h" #include "Mac.H" #include "bootloader.h" WORD code_n=0; BYTE code_flag=0; //1:hot 2:cold 3:off BYTE sent_flag=0; WORD codearray_hot[CODELENTH]={0}; WORD codearray_cold[CODELENTH]={0}; WORD codearray_off[CODELENTH]={0}; WORD count=0; WORD sizecode_hot = 0; WORD sizecode_cold = 0; WORD sizecode_off = 0; void T3_Init(void) { IPC2bits.T3IP = 6; IFS0bits.T3IF = 0; IEC0bits.T3IE = 1; T3CONbits.TON = 0; T3CONbits.TCS = 0; T3CONbits.TSIDL = 0; T3CONbits.TGATE = 0; T3CONbits.TCKPS1 = 0; T3CONbits.TCKPS0 = 1; //内部晶振是8MHZ,Fcy=Fosc/2 //准备定时n(ms)=x/(8MHZ/2) TMR3=0x0000; PR3=0xffff; } void IC1_Init(void) { TRISBbits.TRISB4 = 1; RPINR7bits.IC1R = 0x04; IC1CON = 0x0000; IC1CON = 0x0001; IFS0bits.IC1IF = 0; IEC0bits.IC1IE = 1; IPC0bits.IC1IP = 6; } void T5_Init(void) { IPC7bits.T5IP = 6; IFS1bits.T5IF = 0; IEC1bits.T5IE = 1; T5CONbits.TON = 0; T5CONbits.TCS = 0; T5CONbits.TSIDL = 0; T5CONbits.TGATE = 0; T5CONbits.TCKPS1 = 0; T5CONbits.TCKPS0 = 1; //内部晶振是8MHZ,Fcy=Fosc/2 //准备定时n(ms)=x/(8MHZ/2) TMR5=0x0000; PR5=0x0020; } void PWM_Init(void) { TRISBbits.TRISB3=0; RPOR1bits.RP3R =18; T2CON=0; TMR2=0; OC1CON=0x0000; OC1R=0x0022; OC1RS=0x0022; OC1CON=0x0006; PR2=0x0067; IPC1bits.T2IP = 6; IFS0bits.T2IF = 0; IEC0bits.T2IE = 1; } void cleararray(void) { WORD i; for(i=0;i<CODELENTH;i++) { codearray_hot[i]=0; codearray_cold[i]=0; codearray_off[i]=0; } } void infraInit(void) { cleararray(); IC1_Init(); T3_Init(); TRISAbits.TRISA2=0; //红外编码引脚设置为输出 LOW; PWM_Init(); //pwm功能初始化 T5_Init(); //定时器5初始化 HC595Put(data); HC595Out(); } BOOL hot_to_flash(void) { WORD i=0; GetAddr(&codeAddr_hot); ReadPM(Buffer,SourceAddr); Buffer[0]=sizecode_hot; Buffer[1]=sizecode_hot>>8; for(i=1;i<=sizecode_hot;i++) { Buffer[i*2+0]=codearray_hot[i]; //先写低位 Buffer[i*2+1]=codearray_hot[i]>>8; //后写高位 } ErasePage(); WritePM(Buffer, SourceAddr); BufferInit();//清空Buffer return 1; } BOOL cold_to_flash(void) { WORD i=0; GetAddr(&codeAddr_cold); ReadPM(Buffer,SourceAddr); Buffer[0]=sizecode_cold; Buffer[1]=sizecode_cold>>8; for(i=1;i<=sizecode_cold;i++) { Buffer[i*2+0]=codearray_cold[i]; //先写低位 Buffer[i*2+1]=codearray_cold[i]>>8; //后写高位 } ErasePage(); WritePM(Buffer, SourceAddr); BufferInit();//清空Buffer return 1; } BOOL off_to_flash(void) { WORD i=0; GetAddr(&codeAddr_off); ReadPM(Buffer,SourceAddr); Buffer[0]=sizecode_off; Buffer[1]=sizecode_off>>8; for(i=1;i<=sizecode_off;i++) { Buffer[i*2+0]=codearray_off[i]; //先写低位 Buffer[i*2+1]=codearray_off[i]>>8; //后写高位 } ErasePage(); WritePM(Buffer, SourceAddr); BufferInit();//清空Buffer return 1; } void infra_open(void) { code_n=1; T1CONbits.TON=0; T2CONbits.TON=1; //定时器2开启 LATAbits.LATA2=0; //引脚拉低初始化 T5CONbits.TON = 1;//开启定时器 } void infra_sent_hot(void) { if(code_n<=sizecode_hot) { if(1==code_n%2) {HIGH;PR5=codearray_hot[code_n++];} else if(0==code_n%2) {LOW;PR5=codearray_hot[code_n++];} } else {T2CONbits.TON=0;T5CONbits.TON = 0;TMR5=0;T1CONbits.TON=1;code_flag=0;LEDBlinkYellow();LOW;} } void infra_sent_cold(void) { if(code_n<=sizecode_cold) { if(1==code_n%2) {HIGH;PR5=codearray_cold[code_n++];} else if(0==code_n%2) {LOW;PR5=codearray_cold[code_n++];} } else {T2CONbits.TON=0;T5CONbits.TON = 0;TMR5=0;T1CONbits.TON=1;code_flag=0;LEDBlinkYellow();LOW;} } void infra_sent_off(void) { if(code_n<=sizecode_off) { if(1==code_n%2) {HIGH;PR5=codearray_off[code_n++];} else if(0==code_n%2) {LOW;PR5=codearray_off[code_n++];} } else {T2CONbits.TON=0;T5CONbits.TON = 0;TMR5=0;T1CONbits.TON=1;code_flag=0;LEDBlinkYellow();LOW;} } void InfraTask(void) { BYTE i,j,k; BYTE cSize = 0; BYTE cPtrTx[10]; NODE_INFO macAddr; i=emWaitMesg(INFRAHOT_SENT_REQ,RealTimeMesg,0,0); if(i==1) { if(sizecode_hot>50) { sent_flag=HOT; infra_open(); Delay(0xffff); } } j=emWaitMesg(INFRACOLD_SENT_REQ,RealTimeMesg,0,0); if(j==1) { if(sizecode_cold>50) { sent_flag=COLD; infra_open(); Delay(0xffff); } } k=emWaitMesg(INFRAOFF_SENT_REQ,RealTimeMesg,0,0); if(k==1) { if(sizecode_off>50) { sent_flag=OFF; infra_open(); Delay(0xffff); } } CurrentTaskWait(); SchedTask(); } <file_sep>#include "Mac.H" #include "SysTask.h" #include "led.h" #include "infra.h" #include "bootloader.h" #include "timeds.h" #include "Loc.h" _CONFIG1(JTAGEN_OFF // JTAG Diabled & GCP_OFF // Code Protection Disabled & GWRP_OFF // Write Protection Disabled & BKBUG_OFF // Background Debugger Disabled // & COE_OFF // Clip-on Emulation Mode Disabled & ICS_PGx3 // ICD Pins Select: EMUC/EMUD share PGC2/PGD2 & FWDTEN_OFF // Watchdog Timer Enabled & WINDIS_OFF // Windowed WDT Disabled & FWPSA_PR128 //预分频7位 & WDTPS_PS2048); //后分频1:2048 _CONFIG2(IESO_OFF //Internal External switch over mode & FNOSC_FRC // Oscillator Selection: Fast RC oscillator & FCKSM_CSDCMD // Clock switching and clock monitor: Both disabled & OSCIOFNC_ON // OSCO/RC15 function: RC15 & POSCMOD_NONE); // Oscillator Selection: Primary disabled /* 修改日期:2017年1月20日 修改者:李延超 通信速率变为2.4k 这是节点的程序,加入了组网的功能。 节点在底层循环中通过定时器2不断的向协调器发送入网请求,入网主要通过RSSI的值的大小判断加入哪个网络,不会判断有多少网络 当入网成功之后,节点仍然通过定时器2不断向协调器发送数据包告知自己的存在。 同时当收到协调器的出网请求后,会重新开始申请地址,但是上电时获得的长地址不会变。 由于节点上电随机获得地址,在MAC层初始化时需要给节点一个唯一的标示。 */ /* 组网流程:组网的难题主要在于Flash的操作。 定时器2用于定时向协调器申请地址信息,以下流程是在节点的角度考虑。 1. MAC层初始化的时候要获得一个长地址。 2. 定时器2时间到,进入MACJoinPAN(void)函数,发送信标命令请求帧,这是一个命令帧。 3. 协调器回应一个信标帧,广播并让所有节点收到。节点进入MACProcessBeacon()函数,处理接收到的信标帧,目的将协调器加入自己列表, 注意关键函数MACRefreshPANRecord(PAN_DESCRIPTOR *Record),决定了加入网络的条件。 4. 在第3步完成之后,节点等待下一个定时器2的时间,向协调器发送分配地址请求帧,请求短地址。 5. 收到协调器的响应之后,除了修改MAC层的PIB属性之外,还应该对相关的地址状态等进行存储。 6. FLASH的操作流程详见FLASHMM.c文件开头处 7. 读取节点长地址有两种方法,其一是节点以数据帧形式封装长地址到负载中,协调器当做数据帧上传; * 其二是节点发送普通数据包,协调器解析数据包后将长地址单独加入到以太网数据包中上传到服务器。 */ extern BYTE Parameter[PARAMETER_NUM]; extern IO_INFO AD_Value[]; void PutOut(void); void HardTimer_Init(void); extern WORD data;//继电器动作标志位 void CircleTask(void) { BYTE i; if(emCheckHardTimer(1)) { emDelHardTimer(1); ////////// InOut_Control(); //信息采集,控制逻辑 ////////// PutOut(); //继电器控制 SysRealTime(); //系统时间计算 emStartHardTimer(1); } if(emCheckHardTimer(2)) { emDelHardTimer(2); if(!MACIsNetworkJoined()) { emTxMesg(RF_JOIN_NETWORK_REQ,RealTimeMesg,0,0); } else {} emStartHardTimer(2); } if(emCheckHardTimer(3))//心跳包 { emDelHardTimer(3); emTxMesg(TEM_SENT_REQ,RealTimeMesg,0,0); emStartHardTimer(3); } if(emCheckHardTimer(4))//进行状态转换 { emDelHardTimer(4); while (RF_TRX_TX == PHYGetTRxState());// 等待不是TX的状态 //10分钟左右做一次状态转换,RX->IDLE—>RX //在状态转换时候,CC2500会自动做频率校准的。消耗时间大约是800us。 PHYSetTRxState(RF_TRX_RX); PHYSetTRxState(RF_TRX_IDLE); PHYSetTRxState(RF_TRX_RX); emStartHardTimer(4); } if(emCheckHardTimer(5)) { emDelHardTimer(5); data=(data|0x0004); HC595Put(data); HC595Out(); emStartHardTimer(6); } if(emCheckHardTimer(6)) { emDelHardTimer(6); data=(data&0xfffb); HC595Put(data); HC595Out(); emStartHardTimer(5); } if(emCheckHardTimer(7)) { emDelHardTimer(7); //第一路继电器线圈断电 data=(data&0xfff7); HC595Put(data); HC595Out(); } if(emCheckHardTimer(8)) { emDelHardTimer(8); LEDBlinkRed(); emStartHardTimer(8); } i=emSearchMesg(RF_FLUSH_RSPBUFFER_REQ); if(i!=InvalidMesg) { emTxMesg(RF_FLUSH_RSPBUFFER_RSP,RealTimeMesg,0,0); } i=emSearchMesg(RF_REV_MESSAGE_NOTIFY); if(i!=InvalidMesg) { emTxMesg(RF_REV_MESSAGE_REQ,RealTimeMesg,0,0); } SchedTask(); } void main(void) { WORD prio; emDint(&prio); //端口数字化 AD1PCFG=0xFFFF; //把模拟输入改成数字I/O //硬件初始化 BufferInit(); //UnlockREG(); //LockREG(); //ADInit(); DeviceInitSetup(); FlashInitSetup(); LEDInitSetup(); InitTicks(); SPIInit(); ////// SPIInitCC2500off(); //外部中断1(无线中断)初始化 ////// RPINR0bits.INT1R=10; //GDO0 接收时输入引脚 ////// LATBbits.LATB2=1; //LNA ////// LATBbits.LATB15=0; //PA //外部中断1(树莓派看门狗)初始化 TRISBbits.TRISB0=1; RPINR0bits.INT1R=0; //树莓派看门狗 IFS1bits.INT1IF=0; IEC1bits.INT1IE=1;//关闭无线中断 IPC5bits.INT1IP=7;//最高优先级为7,依次递减6直至1 INTCON2bits.INT1EP=1;//1为下降沿,0为上升沿 //外部中断2(树莓派开门中断)初始化 TRISBbits.TRISB1=1; RPINR1bits.INT2R=1;//原来的无线中断映射RP10,记得替换 IFS1bits.INT2IF=0; IEC1bits.INT2IE=1; IPC7bits.INT2IP=6;//最高优先级为7,依次递减6直至1 INTCON2bits.INT2EP=0;//1为下降沿,0为上升沿 //将FLASH的格式化 //FlashFormatMem(); //协议栈初始化 emSysInit(); ////// RFInitSetup(); //可设置通信速率 ////// PHYInitSetup(); //可设置通信速率 ////// MACInitSetup(); LEDBlinkRed(); LEDBlinkYellow(); CurSysTimeInit(); HC595Put(0x00); HC595Out(); emEint(&prio); GetParameters(); HardTimer_Init(); CreateTask(SYSTask,0,0,READY); ////// CreateTask(MACTask,9,9,READY); ////// CreateTask(TemTask,6,6,READY); ////// CreateTask(LocTask,7,7,READY); ////// CreateTask(InfraTask,5,5,READY); CreateTask(CircleTask,15,15,READY); StartTask(); } void HardTimer_Init(void) { emSetHardTimer(1,40);//感知循环检测 emSetHardTimer(2,100); emSetHardTimer(3,Parameter[update]*6000); //温度感知定时上传时间设置 //测试用 10min emSetHardTimer(4,30000);//640s进行一次状态转换,防止晶振偏离 emSetHardTimer(5,1000);//树莓派每秒一个低电平与PIC进行心跳通信;如果2分钟没检测到则PIC20S强制断电。 emSetHardTimer(6,200);//开合闸时间间隔2s; emSetHardTimer(7,50);//开锁后,0.5s自动恢复继电器 //start the timer, discard the returning value emSetHardTimer(8,500);//心跳灯 emStartHardTimer(1); emStartHardTimer(5);//开启树莓派看门狗 emStartHardTimer(8); ////// emStartHardTimer(2); ////// emStartHardTimer(3); ////// emStartHardTimer(4); } <file_sep>#include "addr.h" #include "Interface.h" #include "stdlib.h" #include "time.h" WORD AllocAddr=1; extern MAC_PIB macPIB; //获取随机值算法 /*WORD GetRANDValue(void) { WORD Result; WORD regVal; regVal=AD1PCFG; //得到寄存器的设置;当AD1PCFG引脚为0时,AD引脚为模拟模式,A/D对引脚电压进行采样。 AD1PCFG=0xFFFE; // 首先全部制成AN模式,AN0为模拟输入 AD1CON1=0; // 采样时钟源 AD1CON2=0; // 采样参考电压 AD1CON3=0x0002; // Configure A/D conversion clock as Tcy/2 AD1CHS=0; // 采样频道 AD1CSSL=0; // No inputs are scanned. IFS0bits.AD1IF=0; // Clear A/D conversion interrupt. IEC0bits.AD1IE=0; // Disable A/D conversion interrupt AD1CON1bits.ADON=1; // Turn on A/D AD1CON1bits.SAMP=1; //开始采样 Delay(300); AD1CON1bits.SAMP=0; while(!AD1CON1bits.DONE); { AD1CON1bits.DONE=0; Result=ADC1BUF0; } AD1PCFG=regVal; //非常关键啊,完成以后再恢复到原先的设定值 return Result; }*/ //自动获取地址算法 void AllocIEEEAddr(LONG_ADDR *LongAddr) { srand(time(NULL)); LongAddr->cVal[0]=rand()%256; LongAddr->cVal[1]=rand()%256; LongAddr->cVal[2]=rand()%256; LongAddr->cVal[3]=rand()%256; LongAddr->cVal[4]=rand()%256; LongAddr->cVal[5]=rand()%256; LongAddr->cVal[6]=rand()%256; LongAddr->cVal[7]=macPIB.CDNum; /* BYTE i; WORD nTemp; BYTE cResult[16]; CRC_RESULT checksum; srand(time(NULL)); for(i=0;i<16;i++) { // cResult[i]=GetRANDValue(); cResult[i]=rand()%256; } checksum=CrcCalc((BYTE *)cResult,16); while(checksum.nVal==0xFFFF) { for(i=0;i<5;i++) { // cResult[i]=GetRANDValue(); cResult[i]=rand()%256; } checksum=CrcCalc((BYTE *)cResult,5); } LongAddr->cVal[0]=checksum.cVal[0]; LongAddr->cVal[1]=checksum.cVal[1]; nTemp=IEEE_PAN_ID; LongAddr->cVal[2]=nTemp; LongAddr->cVal[3]=nTemp>>8; nTemp=(WORD)AREA_CODE; LongAddr->cVal[4]=nTemp; LongAddr->cVal[5]=nTemp>>8; nTemp=(WORD)(AREA_CODE>>16); LongAddr->cVal[6]=nTemp; LongAddr->cVal[7]=nTemp>>8; */ } //自动分配地址算法 SHORT_ADDR AllocShortAddr(WORD InitialVal) { SHORT_ADDR ShortAddr; ShortAddr.nVal=InitialVal+AllocAddr; AllocAddr++; return ShortAddr; } <file_sep>#ifndef _COMMON_H_ #define _COMMON_H_ #include "p24FJ64GA002.h" #include "string.h" #define IO_NUM 10 #define InValid_Index 0xFFFF #define InValidVal 0xFFFF #define ConstCfgRspBufferSize 128 #define ConstCfgRspShareBufSize 16 typedef unsigned char BYTE; typedef unsigned int WORD; typedef unsigned long DWORD; typedef unsigned char BOOL; typedef int INT16S; typedef char INT8S; typedef short Word16; typedef unsigned short UWord16; typedef long Word32; typedef unsigned long UWord32; typedef BYTE BUFFER; typedef struct { unsigned char IO_Pro; unsigned char type; unsigned char val0[2]; union{ unsigned int Value; unsigned char val1[2]; }; } IO_INFO; typedef union _DWORD_VAL { BYTE cVal[4]; WORD nVal[2]; DWORD dwVal; }DWORD_VAL; typedef union _WORD_VAL { BYTE cVal[2]; WORD nVal; }WORD_VAL; typedef struct _CFG_RSP_BUFFER { BYTE Buffer[ConstCfgRspBufferSize]; BYTE Ptr; }CFG_RSP_BUFFER; typedef struct _CFG_RSP_SHARE_BUFFER { BYTE Ptr; BOOL bReady; BYTE Buffer[ConstCfgRspShareBufSize]; }CFG_RSP_SHARE_BUFFER; /*typedef struct _SYS_LED { WORD bWsnRx : 1; WORD bWsnTx : 1; WORD bBusRx : 1; WORD bBusTx : 1; WORD : 12; }SYS_LED;*/ typedef struct _RTime{ BYTE year; BYTE month; BYTE day; BYTE hour; BYTE minute; BYTE second; }RTIME; typedef struct _CONTime{ BYTE hour; BYTE minute; BYTE second; }CONTIME; typedef struct _IO_CONTROL { BYTE Addr; //1BYTE CONTIME StartTime; //3BYTE CONTIME EndTime; //3BYTE BYTE Times; //1BYTE BYTE Action; //1BYTE 在规定的时间段内采取的行动 }IO_CONINF; typedef union tuReg32 { DWORD Val32; struct { UWord16 LW;//unsigned short UWord16 HW; } Word; BYTE Val[4]; } BInfo; #define DEVICE_NUM 0 //1:有两个设备 0:有一个设备 #define SERVER_ID 0 //1:本机 0:服务器 #define OutPutCN 8 //输出控制的通道数目 #define PARAMETER_NUM 29 //参数数量 (如实写,即开辟了多少就填充多少) #define update 0x00 #define xzyReserved1 0x01 #define xzyReserved2 0x02 #define h1 0x03 #define m1 0x04 #define open_data1_0 0x05 #define open_data1 0x06 #define h2 0x07 #define m2 0x08 #define open_data2_0 0x09 #define open_data2 0x0a #define h3 0x0b #define m3 0x0c #define open_data3_0 0x0d #define open_data3 0x0e #define h4 0x0f #define m4 0x10 #define open_data4_0 0x11 #define open_data4 0x12 #define h5 0x13 #define m5 0x14 #define open_data5_0 0x15 #define open_data5 0x16 #define TransmitPower 0x17 #define _rssi_offset 0x18 #define _rssi_standard 0x19 #define _rssi_factor 0x1a #define route_high 0x1b #define route_low 0x1c #define Tactics 0xA400 //定义策略存储的地址 #define code8000 0x8000 #define code8400 0x8400 #define code8800 0x8800 #define TRUE 1 #define FALSE 0 //以下定义消息的类型 //定义系统消息 #define RTU_OVERFLOW_SYS_EROR 0xF0 #define RF_OVERFLOW_SYS_EROR 0xF1 //定义基本消息 /*#define RTU_REV_MESSAGE_NOTIFY 0x01 #define RTU_REV_MESSAGE_REQ 0x02 #define RTU_UPLOAD_MESSAGE_REQ 0x03 #define RTU_SENT_MESSAGE_REQ 0x04*/ #define RF_REV_MESSAGE_NOTIFY 0x05 #define RF_REV_MESSAGE_REQ 0x06 #define RF_UPLOAD_MESSAGE_REQ 0x07 #define RF_SENT_MESSAGE_REQ 0x08 #define RF_JOIN_NETWORK_REQ 0x09 //定义系统报警信息 /*#define RTU_FLUSH_RSPBUFFER_REQ 0x0A #define RTU_FLUSH_RSPBUFFER_RSP 0x0B*/ #define RF_FLUSH_RSPBUFFER_REQ 0x0C #define RF_FLUSH_RSPBUFFER_RSP 0x0D //定义经串口可配置的命令 /*#define RTU_SET_FREQ_REQ 0x10 #define RTU_SET_FREQ_RSP 0x11 #define RTU_SET_POWER_REQ 0x12 #define RTU_SET_POWER_RSP 0x13 #define RTU_SET_RATE_REQ 0x14 #define RTU_SET_RATE_RSP 0x15 #define RTU_SET_IEEEADDR_REQ 0x16 #define RTU_SET_IEEEADDR_RSP 0x17 #define RTU_SET_PANSADDR_REQ 0x18 #define RTU_SET_PANSADDR_RSP 0x19 #define RTU_SET_SHORTADDR_REQ 0x1A #define RTU_SET_SHORTADDR_RSP 0X1B #define RTU_SET_BUSADDR_REQ 0x1C #define RTU_SET_BUSADDR_RSP 0X1D #define RTU_SET_PHY_REQ 0x1E #define RTU_SET_PHY_RSP 0X1F #define RTU_RESET_REQ 0x20 #define RTU_RESET_RSP 0X21 #define RTU_GET_PHY_REQ 0x22 #define RTU_GET_PHY_RSP 0x23 #define RTU_GET_ADDR_REQ 0x24 #define RTU_GET_ADDR_RSP 0x25 #define RTU_GET_BUSADDR_REQ 0x26 #define RTU_GET_BUSADDR_RSP 0x27*/ #define RTU_SET_SHORTADDR_RSP 0X1B //定义经射频可配置的命令 #define RF_SET_FREQ_REQ 0x30 #define RF_SET_FREQ_RSP 0x31 #define RF_SET_POWER_REQ 0x32 #define RF_SET_POWER_RSP 0x33 #define RF_SET_RATE_REQ 0x34 #define RF_SET_RATE_RSP 0x35 #define RF_SET_IEEEADDR_REQ 0x36 #define RF_SET_IEEEADDR_RSP 0x37 #define RF_SET_PANSADDR_REQ 0x38 #define RF_SET_PANSADDR_RSP 0x39 #define RF_SET_SHORTADDR_REQ 0x3A #define RF_SET_SHORTADDR_RSP 0x3B #define RF_SET_BUSADDR_REQ 0x3C #define RF_SET_BUSADDR_RSP 0x3D #define RF_SET_PHY_REQ 0x3E #define RF_SET_PHY_RSP 0x3F #define RF_RESET_REQ 0x40 #define RF_RESET_RSP 0x41 #define RF_GET_PHY_REQ 0x42 #define RF_GET_PHY_RSP 0x43 #define RF_GET_ADDR_REQ 0x44 #define RF_GET_ADDR_RSP 0x45 #define RF_GET_BUSADDR_REQ 0x46 #define RF_GET_BUSADDR_RSP 0x47 #define RF_CMD_PARA_REQ 0x50 #define RF_CMD_PARA_RSP 0x51 #define TEM_SENT_REQ 0x60 //温度 #define INFRAHOT_SENT_REQ 0x61 #define INFRACOLD_SENT_REQ 0x62 #define INFRAOFF_SENT_REQ 0x63 #define TIME_SENT_REQ 0x64 //定位任务创建的系统消息 #define LOC_HEART_REQ 0x65//心跳包 #define LOC_RSSI_REQ 0x66//协调器和锚节点之间的RSSI #define LOC_DEL_REQ 0x67//删除锚节点历史记录 #define LOC_DIS_REQ 0x68//请求定位数据 #define INFRAHOT_DATA_REQ 0x71 #define INFRACOLD_DATA_REQ 0x72 #define INFRAOFF_DATA_REQ 0x73 #define TIME_DATA_REQ 0x74 #define NET_ADDR_ACK 0x88 void Delay_2us(void); void Delay(WORD t); #endif <file_sep>#include <stdio.h> #include "common.h" #define PM_ROW_SIZE 64 * 8 //程序存储器 size 定义 #define CM_ROW_SIZE 8 #define PM_ROW_ERASE 0x4042 //程序存储器操作定义 将来要写到 NVMCON 中去的 #define PM_ROW_WRITE 0x4001 //write 1 row extern BInfo SourceAddr; extern BInfo TacticsAddr; extern BInfo codeAddr_hot; extern BInfo codeAddr_cold; extern BInfo codeAddr_off; extern BYTE Buffer[PM_ROW_SIZE*3];//从上位机收到的1536字节 extern BYTE Parameter[PARAMETER_NUM]; void GetAddr(BYTE *addr); void BufferInit(void); void WritePM(BYTE * ptrData, BInfo SourceAddr); void ReadPM(BYTE * ptrData, BInfo SourceAddr) ; void ErasePage(void); BOOL GetParameters(void); <file_sep>#ifndef _MCU_H #define _MCU_H #include "common.h" /************************************************************ *SPI通信的引脚定义,本次采用软件模拟SPI通信过程,引脚的定义是相对于单片机来说 *************************************************************/ #define CS LATBbits.LATB9 // 片选信号 #define SCLK LATBbits.LATB13 // 时钟信号 #define SO LATBbits.LATB14 // 串行输出 #define SI PORTBbits.RB12 // 串行输入 /************************************************************ *与CC2500有关的状态引脚宏定义 *************************************************************/ #define RF_CHIP_RDYn PORTBbits.RB12 #define RF_GDO0 PORTBbits.RB10 #define RF_GDO0_IE CNEN2bits.CN16IE #define RF_GDO0_IF IFS1bits.CNIF #define RF_GDO2 PORTBbits.RB11 /***********************************************************/ //禁止射频的接收和发送中断 #define RFDint() IEC1bits.INT1IE=0 #define RFEint() \ { \ IFS1bits.INT1IF=0; \ IEC1bits.INT1IE=1; \ } //定义看门狗清除 #define CLR_WDT() ClrWdt() #define RESET() asm("RESET") //进行一定功能引脚映射时候,解锁寄存器和上锁寄存器 void UnlockREG(void); void LockREG(void); //禁止中断,允许中断,一定要把中断嵌套打开 void emDint(WORD *prio); void emEint(WORD *prio); //SPI通信初始化 void SPIInit(void); //定时器通信初始化 void InitTicks(void); //再开启一个定时器 void InitTime(void); //AD采样通信初始化 void ADInitSetup(void); //输出控制初始化 void DeviceInitSetup(void); //LED指示灯闪烁函数 void LEDInitSetup(void); void LEDBlinkRed(void); void LEDBlinkYellow(void); #endif <file_sep>#include "Mac.H" void SYSTask(void); <file_sep>#include "zigbee.h" #include "phy.h" #include "bootloader.h" /* 信道忙碌状态的相关信息被删除,一直没有用到。 物理层的最大包长为64,最小包长为7 */ //PHY Constant #define aMaxPHYPacketSize 64 //物理层最大的包长度 //全局变量,要在相应定义文件中进行初始化 PHY_PIB phyPIB; //物理层PIB属性 PHY_RX_BUFFER PhyRxBuffer; //接收缓冲区 BYTE ChanTab[ConstRFChannelSize]={0x00,0x10,0x20,0x30,0x40,0x50,0x60,0x70,0x80,0x90,0xA0,0xB0,0xC0,0xD0,0xE0,0xF0}; BYTE PowerTab[ConstRFPowerSize]={0x00,0x50,0x44,0xC0,0x84,0x81,0x46,0x93,0x55,0x8D,0xC6,0x97,0x6E,0x7F,0xA9,0xBB,0xFE,0xFF}; //关于频率和信道扫描的事情 /*********************************************************************** //基带频率:2433MHZ //每两个信道间频带宽度:200KHZ //将256个信道重新划分,每隔16个为一个,信道间频宽为200*16=3200KHZ,共16个信道 ***********************************************************************/ WORD PHYSetChannel(BYTE Index) { if((Index<ConstRFChannelSize) && (Index>0)) { PHYSetChan(ChanTab[Index-1]); return Index; } return InValid_Index; } //设置发送功率 WORD PHYSetTxPower(BYTE Index) { if((Index<ConstRFPowerSize) && (Index>0)) { PHYSetTxPwr(PowerTab[Index-1]); return Index; } return InValid_Index; } //设置波特率 void PHYSetBaudRate(BYTE BaudRate) { PHYSetBaud(BaudRate); } BYTE PHYGetLinkQuality(BYTE rssi) { BYTE cResult; INT8S cTemp; if(rssi>=128) cTemp=(rssi-256)/2-RSSI_OFFSET; else cTemp=rssi/2-RSSI_OFFSET; cResult=(BYTE)cTemp; return cResult; } void PHYInitSetup(void) { // BYTE i; // BYTE index; //PIB属性初始化 phyPIB.phyCurrentChannel=5; phyPIB.phyChannelSuppoerted=16; //支持16个信道 ////////// phyPIB.phyTransmitPower=Parameter[route_high];//0-17 phyPIB.phyTransmitPower=17; phyPIB.phyCCAMode=2;//取值范围1-3 phyPIB.phyBaudRate=1;//1-4 //接收缓冲区初始化 PhyRxBuffer.Postion.cWrite=0; PhyRxBuffer.Postion.cRead=0; PHYSetBaud(phyPIB.phyBaudRate); PHYSetTxPwr(PowerTab[phyPIB.phyTransmitPower]); PHYSetChannel(phyPIB.phyCurrentChannel); PHYSetTRxState(RF_TRX_RX); } void PHYPut(BYTE cVal) { //往接收缓冲区写入数据 PhyRxBuffer.RxBuffer[PhyRxBuffer.Postion.cWrite]=cVal; //修改写入指针 PhyRxBuffer.Postion.cWrite=(PhyRxBuffer.Postion.cWrite+1)%ConstPhyRxBufferSize; } BYTE PHYGet(void) { BYTE cReturn; //从接收缓冲区中读取数据 cReturn=PhyRxBuffer.RxBuffer[PhyRxBuffer.Postion.cRead]; //修改读出指针 PhyRxBuffer.Postion.cRead=(PhyRxBuffer.Postion.cRead+1)%ConstPhyRxBufferSize; return cReturn; } void PHYGetArray(BYTE *ptr,BYTE cSize) { WORD i; for(i=0;i<cSize;i++) *ptr++=PHYGet(); } BOOL PHYPutRxBuffer(void) { WORD i; WORD prio; WORD cRest=0; BYTE cTemp; BYTE cSize; BYTE cValue; emDint(&prio); //首先判断是否接收溢出 cValue=PHYGetRxStatus(); cValue=cValue&0x80; if(cValue==0x80)//接收溢出 { PHYClearRx(); emEint(&prio); return FALSE; } cSize=PHYReadRx(); cSize=cSize+2; //长度包含2个字节的CRC和RSSI if((cSize >= aMaxPHYPacketSize)||(cSize<7)) { PHYClearRx(); emEint(&prio); return FALSE; } if(PhyRxBuffer.Postion.cWrite<PhyRxBuffer.Postion.cRead) cRest=PhyRxBuffer.Postion.cRead-PhyRxBuffer.Postion.cWrite-1;//减一的目的是去掉长度字节 else cRest=ConstPhyRxBufferSize-PhyRxBuffer.Postion.cWrite+PhyRxBuffer.Postion.cRead-1;//写时先写再增 if(cRest>=cSize+1) //因为cSize指示的是不包含长度字节的剩余字节数,所以要加1 { PHYPut(cSize); //写入长度 for(i=0;i<cSize;i++) { cTemp=PHYReadRx(); PHYPut(cTemp); } //ZXY MODIFIED emTxMesg(RF_REV_MESSAGE_NOTIFY,NRealTimeMesg,0,0); emEint(&prio); return TRUE; } else { PHYClearRx(); PhyRxBuffer.Postion.cWrite=0;//若缓冲区满,则清除缓冲区,和消息 PhyRxBuffer.Postion.cRead=0; emDelMesg(RF_REV_MESSAGE_NOTIFY); emEint(&prio); return FALSE; } } <file_sep>#include "SysTask.h" BYTE RFSysError=0; void SYSTask(void) { BYTE i; i=emWaitMesg(RF_OVERFLOW_SYS_EROR,RealTimeMesg,0,0); if(i==1) { RFSysError++; if(RFSysError==2) { MACFlushTxFrame(); RFSysError=0; } } CurrentTaskWait(); SchedTask(); } <file_sep>/* * File: Loc.h * Author: Sparrow * * Created on 2017Äê11ÔÂ22ÈÕ, ÉÏÎç9:45 */ #ifndef LOC_H #define LOC_H void LocTask(void); unsigned int register2distance (float ); #ifdef __cplusplus extern "C" { #endif #ifdef __cplusplus } #endif #endif /* LOC_H */ <file_sep>#include "Interface.h" /********************************************************* 函 数 名:crcCalc 功 能:CRC16位校验 说 明:add() calc()为子函数 返 回 值:高字节crch 低字节crcl ***********************************************************/ CRC_RESULT CrcCalc(const BYTE *pBuf,WORD nSize) { WORD CrcReg,nTemp; CRC_RESULT Result; WORD i,j; CrcReg=0xFFFF; for(i=0;i<nSize;i++) { CrcReg^=pBuf[i]; for(j=0;j<8;j++) { nTemp=CrcReg&0x0001; CrcReg=CrcReg>>1; if(nTemp==0x0001) CrcReg^=0xA001; } } Result.nVal=CrcReg; return Result; } //指数计算 WORD CalcExponent(BYTE num,BYTE exp) { WORD i,Result;; Result=1; for(i=0;i<exp;i++) { Result=Result*num; } return Result; } //随机值 /*WORD GetRandom(WORD rnd) { BYTE bStr; WORD nVal; bStr=rnd&0x0F; nVal=bStr; bStr=(rnd>>8)&0x0F; nVal<<=4; nVal|=bStr; nVal=nVal*(rnd&0x000F); return nVal; }*/ <file_sep>#ifndef _ZGB_H #define _ZGB_H #include "common.h" #define macMinBE 2 #define macMaxBE 5 #define macMaxCSMABackoffs 5 //修改日期:2009-4-7 #define ZIGBEE_VERSION 0x02 //网络ID #define IEEE_PAN_ID 0x0531 #define ZIGBEE_PAN 4 #define CDrangeLow 0x00 #define CDrangeHigh 0x21 //定义长地址方式:固定值+可变部分,其中固定部分代表区域 /****************************************************/ //1Byte 1Byte 2Byte 2Byte 2Byte //国家 省份 城市 PANID Addr /*****************************************************/ #define AREA_CODE 0x01030001 //定义PHY层缓冲区大小 #define ConstPhyRxBufferSize 256 //表示长度,而非数组下标 //MAC层宏定义 #define ConstMacTxQueSize 5 //定义MAC层重发队列大小 #define ConstMacPayloadSize 45 //定义MAC层PAYLOAD的大小 #define ConstNeighborTableSize 20 //定义邻居表的大小 //网络层宏定义 #define ConstNwkPayloadSize ConstMacPayloadSize-8 #define ConstNwkMaxResponseTime 20 #define ConstRouteTableSize 10 #define ConstRouteDiscSize 5 //默认的NIB属性 #define DEFAULT_nwkRadius 60 #define DEFAULT_nwkMaxDepth 30 #define DEFAULT_nwkMaxRouters 30 #define DEFAULT_PathCost 40 #define DEFAULT_BRDCastAddress (0xFFFF) #define DEFAULT_NULLAddress (0x0000) //应用层定义 #define ConstAppPayloadSize 30 #define ConstRtuPayloadSize 36 //定义超帧GTS列表的大小 #define ConstGTSListSize 4 //范围是0-7 //定义挂起地址列表 #define ConstPendingListSize 4 //范围是0-7 //定义节点记录表的大小 #define ConstRecordTableSize 60 //定义通用数据结构 //短地址数据结构 typedef union _SHORT_ADDR { struct { BYTE cLsb; BYTE cMsb; }byte; WORD nVal; BYTE cVal[2]; }SHORT_ADDR; //长地址数据结构 typedef union _LONG_ADDR { struct { DWORD dwLsb; DWORD dwMsb; }byte; WORD nVal[4]; BYTE cVal[8]; } LONG_ADDR; //地址信息 //定义PAN地址信息数据结构 typedef SHORT_ADDR PAN_ADDR; typedef struct _NODE_INFO { BYTE AddrMode; PAN_ADDR PANId; SHORT_ADDR ShortAddr; LONG_ADDR LongAddr; }NODE_INFO; //定义设备类型 typedef enum _DEVICE_TYPE { ZIGBEE_COORD=0x01, ZIGBEE_ROUTER=0x02, ZIGBEE_RFD=0x03, }DEVICE_TYPE; //PHY层的PIB属性结构 typedef struct _PHY_PIB { BYTE phyCurrentChannel; BYTE phyChannelSuppoerted; BYTE phyTransmitPower; BYTE phyCCAMode; BYTE phyBaudRate; }PHY_PIB; //MAC层的设备信息 typedef union _DEVICE_INFO { struct { WORD StackProfile:4; // Needed for network discovery WORD ZigBeeVersion:4; // Needed for network discovery WORD DeviceType:2; WORD RxOnWhenIdle:1; WORD PermitJoin:1; WORD AutoRequest; WORD PromiscuousMode:1; WORD BattLifeExtPeriods:1; WORD PotentialParent:1; } bits; WORD nVal; }DEVICE_INFO; //MAC层的PIB属性 typedef struct _MAC_PIB { PAN_ADDR macPANId;//存储网络标识 SHORT_ADDR macShortAddr;//存储短地址 LONG_ADDR macLongAddr;//存储长地址 SHORT_ADDR macCoordShortAddr; LONG_ADDR macCoordLongAddr; BYTE macDSN; // BYTE macMaxCSMABackoffs;//CSMA-CA机制的退避时间 BYTE macAckWaitDuration;//等待ACK确认的时间 // BYTE macMinBE; BYTE macGTSPermit; DEVICE_INFO DeviceInfo; BYTE CDNum; }MAC_PIB; //MAC层的状态 typedef union _MAC_STATUS { WORD nVal; struct { WORD addrMode:8; WORD bEstablishPAN:1; WORD isAssociated:1; WORD allowBeacon:1; WORD nwkDepth:5; }bits; }MAC_STATUS; //超帧说明 typedef union _SUPERFRAME_SPEC { WORD nVal; BYTE cVal[2]; struct { WORD BeaconOrder:4; WORD SuperframeOrder:4; WORD FinalCAPSlot:4; WORD BatteryLifeExtension:1; WORD :1; WORD PANCoordinator:1; WORD AssociationPermit:1; } bits; } SUPERFRAME_SPEC; //网络描述,普通节点使用 typedef struct _PAN_DESCRIPTOR { BYTE CoordAddrMode : 1; // spec uses 0x02 and 0x03, we'll use 0 and 1 (short/long) BYTE GTSPermit : 1; BYTE SecurityUse : 1; BYTE SecurityFailure : 1; BYTE ACLEntry : 4; BYTE LogicalChannel; SHORT_ADDR CoordPANId; SHORT_ADDR CoordShortAddr; LONG_ADDR CoordLongAddr; SUPERFRAME_SPEC SuperframeSpec; DWORD TimeStamp; BYTE LinkQuality; BYTE NwkDepth; struct { WORD RxNumber:14; WORD allowJoin:1; WORD bInUse:1; }bits; BYTE CoorCDNum; } PAN_DESCRIPTOR; typedef union _NEIGHBOR_RECORD_INFO { struct { BYTE LQI : 8; BYTE Depth : 4; BYTE StackProfile : 4; // Needed for network discovery BYTE ZigBeeVersion : 4; // Needed for network discovery BYTE DeviceType : 2; BYTE Relationship : 2; BYTE RxOnWhenIdle : 1; BYTE bInUse : 1; BYTE PermitJoining : 1; BYTE PotentialParent : 1; } bits; DWORD dwVal; } NEIGHBOR_RECORD_INFO; //整个结构体设置成偶数字节,方便使用FLASH操作 typedef struct _NEIGHBOR_RECORD { LONG_ADDR LongAddr; SHORT_ADDR ShortAddr; SHORT_ADDR PANId; NEIGHBOR_RECORD_INFO DeviceInfo; BYTE CdNum; } NEIGHBOR_RECORD; // #endif <file_sep>#include "common.h" #include "flash.h" //用户一次可编程闪存程序存储器的一行。 要实现此操作,有必要擦除包含该行在内的一个8行大小的块。 //程序存储器操作定义 将来要写到 NVMCON 中去的 #define PM_BLOCK_ERASE 0x404F //整体擦除,只有在ICSP模式下使用 #define PM_PAGE_ERASE 0x4042 //页擦除命令,每页512条指令,8行 #define PM_ROW_WRITE 0x4001 //行写命令 #define PM_WORD_WRITE 0x4003 //字写命令 #define CONFIG_WORD_WRITE 0x4000 //寄存器配置 //引用汇编文件里的函数 extern void WriteLatch(WORD highAddr,WORD lowAddr,WORD highVal,WORD lowVal); extern DWORD ReadLatch(WORD highAddr,WORD lowAddr); extern void WriteMem(WORD cmd); extern void Erase(WORD highAddr,WORD lowAddr,WORD cmd); void FLASHErasePage(uReg32 addr) { WORD prio; emDint(&prio); Erase(addr.byte.HW,addr.byte.LW,PM_PAGE_ERASE); Delay(10);//20us emEint(&prio); } void FLASHGetArray(uReg32 addr,WORD *pRxBuf, WORD size) { WORD i; uReg32 Temp; WORD prio; emDint(&prio); for(i=0;i<size;i++) { Temp.dwVal = ReadLatch(addr.byte.HW, addr.byte.LW); pRxBuf[i]=Temp.byte.LW; addr.dwVal+=2; } emEint(&prio); Nop(); } void FLASHPutArray(uReg32 addr,const WORD *pTxBuf,WORD size) { WORD i; uReg32 Temp; WORD prio; emDint(&prio); for(i=0;i<size;i++) { Temp.byte.LW=pTxBuf[i]; Temp.byte.HW=0; WriteLatch(addr.byte.HW, addr.byte.LW,Temp.byte.HW,Temp.byte.LW); // 先写到写锁存器中 WriteMem(PM_WORD_WRITE); // 执行 行写 操作 addr.dwVal+=2; //目标地址加2 指向下一个地 址 } emEint(&prio); Nop(); } void FLASHReadBytes(uReg32 addr,BYTE *pRxBuf, WORD size) { WORD i; uReg32 Temp; WORD prio; emDint(&prio); for(i=0;i<size;i++) { Temp.dwVal = ReadLatch(addr.byte.HW, addr.byte.LW); pRxBuf[i]=(BYTE)Temp.byte.LW; //将WORD型截取低字节部分 addr.dwVal+=2; } Nop(); emEint(&prio); Nop(); } void FLASHWriteBytes(uReg32 addr,const BYTE *pTxBuf,WORD size) { WORD i; uReg32 Temp; WORD prio; emDint(&prio); for(i=0;i<size;i++) { Temp.byte.LW=(WORD)pTxBuf[i];//高字节部分补0 Temp.byte.HW=0; WriteLatch(addr.byte.HW, addr.byte.LW,Temp.byte.HW,Temp.byte.LW); // 先写到写锁存器中 WriteMem(PM_WORD_WRITE); // 执行 行写 操作 addr.dwVal+=2; //目标地址加2 指向下一个地址 } Nop(); emEint(&prio); Nop(); } <file_sep>#ifndef _TIMEDS_H #define _TIMEDS_H #include "p24FJ64GA002.h" /****************************************************************** 此函数是针对于时钟来说的,有年月日 时分秒 ******************************************************************/ #include "common.h" //存放日期和时间的结构体 typedef struct _TIME_FLAG { BYTE t[6]; }TIME_FLAG; void CalCurSysTime(DWORD time , RTIME *p); void SysRealTime(void); void CurSysTimeInit(void); #endif <file_sep>#ifndef _FLASH_MM_H #define _FLASH_MM_H #include "common.h" #include "flash.h" /* Flash总共分为4块 第一块:0X8C00~0X8FFF 第二块:0X9000~0X93FF(其中,0X9000 = 0X8C00+8*128,一块有8页,一页有128个字节) 第三块:0X9400~0X97FF 第四块:0X9800~0X9C00 依次类推 */ //定义存储区的起始物理地址、起始物理页 #define ConstPhyBeginAddr 0x008C00 //定义FLASH的起始地址 //定义存储区的页数、块数、每页大小 #define ConstBlockSize 8 //定义块大小,每块包含的页数 #define ConstTotalPhyPages 48 //总共页数,6块 #define ConstPageSize 128 //每页大小按照字节来计算 //确定初始扇区,扇区实际上就是页 #define ConstPhyBeginSector (ConstPhyBeginAddr/ConstPageSize) //计算是按照字节来计算扇区 #define ConstDataBeginSector (ConstPhyBeginSector+ConstBlockSize) #define ConstWordPageSize (ConstPageSize/2) //每页大小,按照字来计算,带计算的宏定义一定加括号 #define ConstDataPageSize (ConstWordPageSize-4) //把128个字节中的最后8个字节拿出来存储CRC校验和状态和逻辑号 //定义坏扇区的大小 #define ConstBadSectorSize (ConstTotalPhyPages-ConstBlockSize) //最大为数据扇区大小,带计算的宏定义一定加括号 //定义数据页数多少,存储区页数去掉管理扇区页数 #define ConstDataSectorSize (ConstTotalPhyPages-ConstBlockSize) //定义数据区大小带计算的宏定义一定加括号 //定义状态存储偏移 #define ConstStatusOffSet (ConstWordPageSize-2) //偏移量是按照字来计算的,带计算的宏定义一定加括号,目前为62 #define ConstCheckSumOffSet (ConstWordPageSize-3) //定义存储CRC校验和的位置 #define ConstLogicOffSet (ConstWordPageSize-1) //每页中存储逻辑地址的偏移量,按照字来计算,目前为63 //定义空 #define MEM_NULL 0xFFFF //代表为空 //定义在此函数中调用的长度计算函数 #define lengthof(a) (sizeof(a)/2) //计算长度 //定义每页扇区状态,状态依次变迁 #define FREE 0x0F //扇区是空闲的 #define INVALID 0x0E //扇区是无效的 #define INUSE 0x0C //扇区是正在使用的 #define DIRTY 0x08 //扇区是可以擦除的 //定义整体FLASH信息 typedef struct _FLASH_INFO { WORD Version; //版本号 WORD EraseNumber; //擦除次数 WORD Identifier; //用户标示 WORD BadSector[ConstDataSectorSize/sizeof(WORD)+1];//无效扇区,每位代表一个扇区 }FLASH_INFO; //定义映射表 typedef struct _MEM_MAP_INFO { WORD PhySector[ConstDataSectorSize]; //物理扇区,逻辑扇区用数组下标代替 WORD FreeNumber; WORD DirtyNumber; }MEM_MAP_INFO; //擦数块,根据逻辑块,可以擦除管理块,也可以擦除数据块 void FlashEraseMem(WORD LogicBlockNum); //读写扇区,物理扇区号、偏移,偏移是按照字计算 WORD FlashPutMem(WORD PhySector,WORD OffSet,WORD *Ptr,WORD Number); WORD FlashGetMem(WORD PhySector,WORD OffSet,WORD *Ptr,WORD Number); //设置数据扇区的状态,输入参数是物理扇区号 void FlashPutStatus(WORD PhySector,WORD Status); WORD FlashGetStatus(WORD PhySector); void FlashSearchMemStatus(void); //设置数据扇区的校验和,输入参数是物理扇区号 void FlashPutCheckSum(WORD PhySector,WORD CheckSum); WORD FlashGetCheckSum(WORD PhySector); //在管理扇区坏区表中,根据物理页来设置其出现坏区标志,0表示坏区,1表示正常 void FlashSetBadSector(WORD PhySector); //格式化存储区 void FlashFormatMem(void); //增加映射表的一条记录 WORD AddMemMapRecord(WORD LogicSector,WORD PageNum); //删除映射表的一条记录 WORD RemoveMemMapRecord(WORD LogicSector); //修改映射表记录 WORD RefreshMemMapRecord(WORD LogicSector,WORD PageNum); //根据逻辑扇区得到物理扇区 WORD GetMemMapRecord(WORD LogSector); //查询一个为空闲的物理扇区 WORD SearchFreePhySector(void); //创建管理扇区表 #define FlashCreateMemInfo() FlashGetMem(ConstPhyBeginSector,0,(WORD *)&MemInfo,lengthof(FLASH_INFO)) //创建映射表 void FlashCreateMapInfo(void); //初始化 void FlashInitSetup(void); //整理块把Dirty的擦除,逻辑块号 BOOL FlashCleanMem(WORD nBlkNum); //存储区整理 void FlashManageMem(void); //确定整理数据块的函数,思想是先找空闲扇区的数量,看能否把需要整理的内容写到空闲区域 //第二个是先整理那些每页中DIRTY的数量超过INUSE的 WORD FlashRefreshMem(void); //读写数据,按照逻辑扇区来读写。提供给上层使用 WORD FlashWriteMem(WORD LogSector,WORD OffSet,WORD *Ptr,WORD Number); //写数据,根据逻辑扇区 WORD FlashReadMem(WORD LogSector,WORD OffSet,WORD *Ptr,WORD Number); //读数据,根据逻辑扇区 #endif <file_sep>#include "p24FJ64GA002.h" #include "em16RTOS24.h" #include "common.h" #include "cc2500.h" #include "spi.h" extern BYTE Parameter[PARAMETER_NUM]; extern RTIME CurrentSysTime; #define Caiyang_Times 5 //每个AD采样的次数 IO_INFO AD_Value[IO_NUM]; //定义网络总线控制器上的IO BYTE dark=1; void AD_Info(void)//赋地址和类型 { int i=0; for( i=0;i<5;i++)//数字输入0是温度,1-4是感知和强制 { AD_Value[i].IO_Pro= 0x80+i; AD_Value[i].type=0; AD_Value[i].Value=0; } for(i=5;i<10;i++)//数字输出5-8是继电器输出,9是空调控制 { AD_Value[i].IO_Pro=0x40 + i - 4; AD_Value[i].type=0; AD_Value[i].Value=1; } AD_Value[0].type=0xFF;//初始化为非法避免误控制 } void ADInit(void) //AD采样初始化 { AD_Info(); AD1CON2bits.VCFG = 0; //参考电压源 AD1CON2 &= 0xEFFF; //置位 AD1CON2bits.CSCNA = 0; //输入扫描 AD1CON2bits.SMPI = 0; //采样1次中断 AD1CON2bits.BUFM = 0; //缓冲器模式 AD1CON2bits.ALTS = 0; //MUX选择 AD1CON3bits.ADRC = 0; //时钟源;1 = A/D 内部的RC 时钟;0 = 时钟由系统时钟产生 AD1CON3bits.SAMC = 2; //自动采样时间 AD1CON3bits.ADCS = 3; //转换时钟选择位Tad,时钟分频器 AD1PCFG &= 0xFFF8; //低4个AN为模拟通道应该是0xfff0或者是其他james AD1CON1bits.FORM = 0; //输出整数 AD1CON1bits.SSRC = 0; //7代表内部计数器结束采样并启动转换(自动转换);0为清零SAMP //位结束采样并启动转换 AD1CON1bits.ADSIDL = 1; //空闲模式停止 AD1CON1bits.ASAM = 0; //0为SAMP 位置1 时开始采样;1为转换完成后自动启动,SAMP 位自动置1 AD1CON1bits.ADON = 1; //启动 } void PutOut(void)//循环执行的输出任务,直接控制继电器的状态 { HC595Put(data); HC595Out(); } void GET_Ganzhi(void) { BYTE i; WORD Tem1Dig[Caiyang_Times]={0}; WORD Tem2Dig[Caiyang_Times]={0}; WORD Tem3Dig[Caiyang_Times]={0}; WORD Tem4Dig[Caiyang_Times]={0}; WORD Tem1_sum = 0; WORD Tem2_sum = 0; WORD Tem3_sum = 0; WORD Tem4_sum = 0; for (i = 0; i < Caiyang_Times; i ++) { AD1CON1bits.SAMP = 1; AD1CHS = 0x00; //通道0 Delay(30); AD1CON1bits.SAMP = 0; while (!AD1CON1bits.DONE); Tem1Dig[i] = ADC1BUF0; Tem1_sum += Tem1Dig[i]; AD1CON1bits.SAMP = 1; //开始采样 AD1CHS = 0x01; //通道1 Delay(30); //延时以等待采样结束 AD1CON1bits.SAMP = 0; //结束采样 while (!AD1CON1bits.DONE); Tem2Dig[i] = ADC1BUF0; //AD转换的值都在一个缓冲器中,所以和前面的一样 Tem2_sum += Tem2Dig[i]; AD1CON1bits.SAMP = 1; AD1CHS = 0x02; //通道2 Delay(30); AD1CON1bits.SAMP = 0; while (!AD1CON1bits.DONE); Tem3Dig[i] = ADC1BUF0; Tem3_sum += Tem3Dig[i]; AD1CON1bits.SAMP = 1; //开始采样 AD1CHS = 0x03; //通道3 Delay(30); //延时以等待采样结束 AD1CON1bits.SAMP = 0; //结束采样 while (!AD1CON1bits.DONE); Tem4Dig[i] = ADC1BUF0; //AD转换的值都在一个缓冲器中,所以和前面的一样 Tem4_sum += Tem4Dig[i]; } Tem1_sum=Tem1_sum/Caiyang_Times; Tem2_sum=Tem2_sum/Caiyang_Times; Tem3_sum=Tem3_sum/Caiyang_Times; Tem4_sum=Tem4_sum/Caiyang_Times; AD_Value[1].Value=Tem2_sum;//供暖阀反馈 AD_Value[2].Value=Tem1_sum;//人体感应1 AD_Value[3].Value=Tem4_sum;// AD_Value[4].Value=Tem3_sum;//电灯反馈 AD_Value[1].Value=(AD_Value[1].Value>200);//供暖阀反馈 AD_Value[2].Value=(AD_Value[2].Value>200);//人体感应1 AD_Value[3].Value=(AD_Value[3].Value>200);// AD_Value[4].Value=(AD_Value[4].Value>200);//电灯反馈 /**/ } void InOut_Control(void) { if((CurrentSysTime.hour == Parameter[h1])&&(CurrentSysTime.minute == Parameter[m1])) data = ((WORD)Parameter[open_data1_0]<<8&0xff00)|((WORD)Parameter[open_data1]&0x00ff); if((CurrentSysTime.hour == Parameter[h2])&&(CurrentSysTime.minute == Parameter[m2])) data = ((WORD)Parameter[open_data2_0]<<8&0xff00)|((WORD)Parameter[open_data2]&0x00ff); if((CurrentSysTime.hour == Parameter[h3])&&(CurrentSysTime.minute == Parameter[m3])) data = ((WORD)Parameter[open_data3_0]<<8&0xff00)|((WORD)Parameter[open_data3]&0x00ff); if((CurrentSysTime.hour == Parameter[h4])&&(CurrentSysTime.minute == Parameter[m4])) data = ((WORD)Parameter[open_data4_0]<<8&0xff00)|((WORD)Parameter[open_data4]&0x00ff); if((CurrentSysTime.hour == Parameter[h5])&&(CurrentSysTime.minute == Parameter[m5])) data = ((WORD)Parameter[open_data5_0]<<8&0xff00)|((WORD)Parameter[open_data5]&0x00ff); } <file_sep>#include "Nvm_flash.h" extern PHY_PIB phyPIB; extern MAC_PIB macPIB; extern MAC_STATUS macStatus; extern PAN_DESCRIPTOR PANDescriptor; //存储分配的IEEE地址 void PutIEEEAddrInfo(WORD Indication,const LONG_ADDR *IEEEAddr) { WORD OffSet; WORD cPtrTx[10]; //全部读出来 FlashReadMem(ConstIEEEAddrPN,0,cPtrTx,5); //找到修改位置 OffSet=0; //修改 cPtrTx[OffSet]=Indication; //找到修改位置 OffSet=1; //修改 memcpy((BYTE *)&cPtrTx[OffSet],(BYTE *)IEEEAddr,sizeof(LONG_ADDR)); //重新写入 FlashWriteMem(ConstIEEEAddrPN,0,cPtrTx,5); CLR_WDT(); } //读取存储地址标志 BOOL GetIEEEIndication(WORD *Indication) { WORD Number; Number=FlashReadMem(ConstIEEEAddrPN,0,Indication,lengthof(WORD)); if(Number==lengthof(WORD)) return TRUE; return FALSE; } //读取自动获得地址信息 BOOL GetIEEEAddr(LONG_ADDR *IEEEAddr) { WORD Number; Number=FlashReadMem(ConstIEEEAddrPN,1,(WORD *)IEEEAddr,lengthof(LONG_ADDR)); if(Number==lengthof(LONG_ADDR)) return TRUE; return FALSE; } //读取状态 BOOL GetMACStatus(void) { WORD Number; Number=FlashReadMem(ConstStatusAddrPN,0,(WORD *)&macStatus,lengthof(MAC_STATUS)); if(Number==lengthof(MAC_STATUS)) return TRUE; return FALSE; } //存储MAC层状态 void PutMACStatus(void) { WORD OffSet; WORD cPtrTx[4]; //全部读出来 FlashReadMem(ConstStatusAddrPN,0,cPtrTx,lengthof(MAC_STATUS)); //找到修改位置 OffSet=0; //修改相应参数 cPtrTx[OffSet++]=macStatus.nVal; //把所有的都重新写入 FlashWriteMem(ConstStatusAddrPN,0,cPtrTx,lengthof(MAC_STATUS)); } //读出网络PANId BOOL GetMACPANId(void) { WORD Number; Number=FlashReadMem(ConstMacAddrPN,0,(WORD *)&macPIB.macPANId,lengthof(SHORT_ADDR)); if(Number==lengthof(SHORT_ADDR)) return TRUE; return FALSE; } //读出短地址 BOOL GetMACShortAddr(void) { WORD Number; Number=FlashReadMem(ConstMacAddrPN,1,(WORD *)&macPIB.macShortAddr,lengthof(SHORT_ADDR)); if(Number==lengthof(SHORT_ADDR)) return TRUE; return FALSE; } //读出长地址 BOOL GetMACLongAddr(void) { WORD Number; Number=FlashReadMem(ConstMacAddrPN,2,(WORD *)&macPIB.macLongAddr,lengthof(LONG_ADDR)); if(Number==lengthof(LONG_ADDR)) return TRUE; return FALSE; } //存储MAC地址 void PutMACAddr(void) { WORD OffSet; WORD cPtrTx[6]; //全部读出来 FlashReadMem(ConstMacAddrPN,0,cPtrTx,6); //把该页全部读出来 //找到修改位置 OffSet=0; //修改相应参数 cPtrTx[OffSet]=macPIB.macPANId.nVal; //找到修改位置 OffSet=1; //修改相应参数 cPtrTx[OffSet]=macPIB.macShortAddr.nVal; //找到修改位置, OffSet=2; //修改 memcpy((BYTE *)&cPtrTx[OffSet],(BYTE *)&macPIB.macLongAddr,sizeof(LONG_ADDR)); //把所有的都重新写入 FlashWriteMem(ConstMacAddrPN,0,cPtrTx,6); } //获取协调器信息 BOOL GetCoordDescriptor(void) { WORD Number; Number=FlashReadMem(ConstCoordAddrPN,0,(WORD *)&PANDescriptor,lengthof(PAN_DESCRIPTOR)); if(Number==lengthof(PAN_DESCRIPTOR)) return TRUE; return FALSE; } //存储协调器信息 void PutCoordDescriptor(void) { WORD OffSet; WORD cPtrTx[20]; //把该页全部读出来 FlashReadMem(ConstCoordAddrPN,0,cPtrTx,20); //找到修改位置 OffSet=0; //修改相应参数 memcpy((BYTE *)&cPtrTx[OffSet],(BYTE *)&PANDescriptor,sizeof(PAN_DESCRIPTOR)); //从新写入 FlashWriteMem(ConstCoordAddrPN,0,cPtrTx,lengthof(PAN_DESCRIPTOR)); } BOOL GetPHYFreq(WORD *Index) { WORD OffSet; WORD Number; WORD cPtrTx[4]; Number=FlashReadMem(ConstPhyFreqAddrPN,0,(WORD *)&cPtrTx[0],2); OffSet=0; *Index=cPtrTx[OffSet++]; phyPIB.phyCurrentChannel=(BYTE)cPtrTx[OffSet++]; if(Number==2) return TRUE; return FALSE; } void PutPHYFreq(WORD FreqIndex) { WORD OffSet; WORD cPtrTx[4]; //把该页全部读出来 FlashReadMem(ConstPhyFreqAddrPN,0,cPtrTx,2); //找到修改位置 OffSet=0; //修改相应参数 cPtrTx[OffSet++]=FreqIndex; cPtrTx[OffSet++]=phyPIB.phyCurrentChannel; //从新写入 FlashWriteMem(ConstPhyFreqAddrPN,0,cPtrTx,2); CLR_WDT(); } BOOL GetPHYTxPower(WORD *Index) { WORD OffSet; WORD Number; WORD cPtrTx[4]; Number=FlashReadMem(ConstPhyTxPowerAddrPN,0,(WORD *)&cPtrTx[0],2); OffSet=0; *Index=cPtrTx[OffSet++]; phyPIB.phyTransmitPower=(BYTE)cPtrTx[OffSet++]; if(Number==2) return TRUE; return FALSE; } void PutPHYTxPower(WORD TxPowerIndex) { WORD OffSet; WORD cPtrTx[4]; //把该页全部读出来 FlashReadMem(ConstPhyTxPowerAddrPN,0,cPtrTx,2); //找到修改位置 OffSet=0; //修改相应参数 cPtrTx[OffSet++]=TxPowerIndex; cPtrTx[OffSet++]=phyPIB.phyTransmitPower; //从新写入 FlashWriteMem(ConstPhyTxPowerAddrPN,0,cPtrTx,2); CLR_WDT(); } BOOL GetPHYBaudRate(WORD *Index) { WORD OffSet; WORD Number; WORD cPtrTx[4]; Number=FlashReadMem(ConstPhyBaudRateAddrPN,0,(WORD *)&cPtrTx[0],2); OffSet=0; *Index=cPtrTx[OffSet++]; phyPIB.phyBaudRate=(BYTE)cPtrTx[OffSet++]; if(Number==2) return TRUE; return FALSE; } void PutPHYBaudRate(WORD BaudRateIndex) { WORD OffSet; WORD cPtrTx[4]; //把该页全部读出来 FlashReadMem(ConstPhyBaudRateAddrPN,0,cPtrTx,2); //找到修改位置 OffSet=0; //修改相应参数 cPtrTx[OffSet++]=BaudRateIndex; cPtrTx[OffSet++]=phyPIB.phyBaudRate; //从新写入 FlashWriteMem(ConstPhyBaudRateAddrPN,0,cPtrTx,2); CLR_WDT(); } <file_sep>#ifndef _RF_H #define _RF_H // ÅäÖüĴæÆ÷µÄºê¶¨Òå #define REG_IOCFG2 0x00 // GDO2 output pin configuration #define REG_IOCFG1 0x01 // GDO1 output pin configuration #define REG_IOCFG0 0x02 // GDO0 output pin configuration #define REG_FIFOTHR 0x03 // RX FIFO and TX FIFO thresholds #define REG_SYNC1 0x04 // Sync word, high byte #define REG_SYNC0 0x05 // Sync word, low byte #define REG_PKTLEN 0x06 // Packet length #define REG_PKTCTRL1 0x07 // Packet automation control #define REG_PKTCTRL0 0x08 // Packet automation control #define REG_ADDR 0x09 // Device address #define REG_CHANNR 0x0A // Channel number #define REG_FSCTRL1 0x0B // Frequency synthesizer control #define REG_FSCTRL0 0x0C // Frequency synthesizer control #define REG_FREQ2 0x0D // Frequency control word, high byte #define REG_FREQ1 0x0E // Frequency control word, middle byte #define REG_FREQ0 0x0F // Frequency control word, low byte #define REG_MDMCFG4 0x10 // Modem configuration #define REG_MDMCFG3 0x11 // Modem configuration #define REG_MDMCFG2 0x12 // Modem configuration #define REG_MDMCFG1 0x13 // Modem configuration #define REG_MDMCFG0 0x14 // Modem configuration #define REG_DEVIATN 0x15 // Modem deviation setting #define REG_MCSM2 0x16 // Main Radio Cntrl State Machine config #define REG_MCSM1 0x17 // Main Radio Cntrl State Machine config #define REG_MCSM0 0x18 // Main Radio Cntrl State Machine config #define REG_FOCCFG 0x19 // Frequency Offset Compensation config #define REG_BSCFG 0x1A // Bit Synchronization configuration #define REG_AGCCTRL2 0x1B // AGC control #define REG_AGCCTRL1 0x1C // AGC control #define REG_AGCCTRL0 0x1D // AGC control #define REG_WOREVT1 0x1E // High byte Event 0 timeout #define REG_WOREVT0 0x1F // Low byte Event 0 timeout #define REG_WORCTRL 0x20 // Wake On Radio control #define REG_FREND1 0x21 // Front end RX configuration #define REG_FREND0 0x22 // Front end TX configuration #define REG_FSCAL3 0x23 // Frequency synthesizer calibration #define REG_FSCAL2 0x24 // Frequency synthesizer calibration #define REG_FSCAL1 0x25 // Frequency synthesizer calibration #define REG_FSCAL0 0x26 // Frequency synthesizer calibration #define REG_RCCTRL1 0x27 // RC oscillator configuration #define REG_RCCTRL0 0x28 // RC oscillator configuration #define REG_FSTEST 0x29 // Frequency synthesizer cal control #define REG_PTEST 0x2A // Production test #define REG_AGCTEST 0x2B // AGC test #define REG_TEST2 0x2C // Various test settings #define REG_TEST1 0x2D // Various test settings #define REG_TEST0 0x2E // Various test settings #define REG_PATABLE 0x3E //OutPower #define REG_TRXFIFO 0x3F // FIFO // É䯵ÃüÁî #define STROBE_SRES 0x30 // Reset chip. #define STROBE_SFSTXON 0x31 // Enable/calibrate freq synthesizer #define STROBE_SXOFF 0x32 // Turn off crystal oscillator. #define STROBE_SCAL 0x33 // Calibrate freq synthesizer & disable #define STROBE_SRX 0x34 // Enable RX. #define STROBE_STX 0x35 // Enable TX. #define STROBE_SIDLE 0x36 // Exit RX / TX #define STROBE_SAFC 0x37 // AFC adjustment of freq synthesizer #define STROBE_SWOR 0x38 // Start automatic RX polling sequence #define STROBE_SPWD 0x39 // Enter pwr down mode when CSn goes hi #define STROBE_SFRX 0x3A // Flush the RX FIFO buffer. #define STROBE_SFTX 0x3B // Flush the TX FIFO buffer. #define STROBE_SWORRST 0x3C // Reset real time clock. #define STROBE_SNOP 0x3D // No operation. // ״̬¼Ä´æÆ÷µÄºê¶¨Òå #define REG_PARTNUM 0x30 // Part number #define REG_VERSION 0x31 // Current version number #define REG_FREQEST 0x32 // Frequency offset estimate #define REG_LQI 0x33 // Demodulator estimate for link quality #define REG_RSSI 0x34 // Received signal strength indication #define REG_MARCSTATE 0x35 // Control state machine state #define REG_WORTIME1 0x36 // High byte of WOR timer #define REG_WORTIME0 0x37 // Low byte of WOR timer #define REG_PKTSTATUS 0x38 // Current GDOx status and packet status #define REG_VCO_VC_DAC 0x39 // Current setting from PLL cal module #define REG_TXBYTES 0x3A // Underflow and # of bytes in TXFIFO #define REG_RXBYTES 0x3B // Overflow and # of bytes in RXFIFO #define REG_NUM_RXBYTES 0x7F // Mask "# of bytes" field in _RXBYTES //ÃüÁîÑÚÂë #define CMD_WRITE (0x00) #define CMD_BURST_WRITE (0x40) #define CMD_READ (0x80) #define CMD_BURST_READ (0xC0) #endif <file_sep>#include "spi.h" WORD data=0x0000; void SPIPut(BYTE cByte) //发送一个字节 { BYTE i; SCLK=0; // 开始为低 for(i=0;i<8;i++) // 每次发送一位 { if(cByte&0x80) // 检测该位是1还是0 SO=1; // 如果为高,则输出高电平 else SO=0; // 如果为0,则输出低电平 SCLK=1; // 时钟信号为高 Nop(); // 延时等待 SCLK=0; // 时钟信号为低 cByte=cByte<<1; // 移位,发送下一位数据 } } BYTE SPIGet(void) //接收一个字节 { BYTE i; // 循环变量 BYTE cVal; // 返回值 cVal=0; SCLK=0; // 确保时钟信号为低 for(i=0;i<8;i++) // 每次发送一位数据 { cVal=cVal<<1; // 移位 SCLK=1; // 时钟信号为高 if (SI==1) // 检测总线为高电平还是低电平 cVal |= 0x01; // 如果为高电平,进行相应位置1 else cVal &= 0xFE; //如果为低电平,相应位置0 SCLK = 0; // 时钟信号拉低 } return cVal; } void HC595Put(WORD cByte) //写入一个字 { BYTE temp; temp = CS; CS=1; BYTE i; for(i=0;i<16;i++) // 每次发送一位 { if(cByte&0x8000) // 检测该位是1还是0 DS=1; // 如果为高,则移入高电平 else DS=0; // 如果为0,则移入低电平 SO=0; Nop(); // 延时等待 Nop(); SO=1; cByte=cByte<<1; // 移位,发送下一位数据 } CS = temp; } void HC595Out(void) { HCK=0; Nop(); Nop(); HCK=1; } <file_sep> #ifndef _RTOS_H #define _RTOS_H #include <stdio.h> #define true 0x01 #define false 0x00 #define MaxTaskNum 256 #define TaskNum 16 //任务的数量 #define MaxTimer 16 #define MaxLayMesg 30 //最大的消息数量 #define HARD_TIMER_NULL 7 #define HARD_TIMER_WORK 6 #define RUNNING 00 //运行状态 #define READY 01 #define WAIT 02 //待消息或事件 #define DELAY 03 //准确延时 #define TERMINATED 04 //超时造成这种状态 #define FINISHED 05 #define SUPEND 06 //当中断时 #define TASKNULL 15 /*表示此任务没有用*/ #define NULLMESG 0 #define InvalidMesg 0xFF //#define NULLTASK 0 #define RealTimeMesg 1 #define NRealTimeMesg 0 #define RecACKMesg 0x20 //接收到ACK消息。 typedef struct TaskSoftStack { unsigned int TaskPCL; unsigned int TaskPCH; unsigned int TaskPSVPAG; unsigned int TaskRCOUNT; unsigned int TaskCORCON; unsigned int TaskTBLPAG; unsigned int TaskW0; unsigned int TaskW1; unsigned int TaskW2; unsigned int TaskW3; unsigned int TaskW4; unsigned int TaskW5; unsigned int TaskW6; unsigned int TaskW7; unsigned int TaskW8; unsigned int TaskW9; unsigned int TaskW10; unsigned int TaskW11; unsigned int TaskW12; unsigned int TaskW13; unsigned int TaskW14; }TaskStack; typedef struct TaskControlBlock { TaskStack * TaskSP; unsigned char TaskId; unsigned char TaskStatus; unsigned char TaskPrioty; unsigned int TaskPCL; unsigned int TaskPCH; }TCB; typedef struct SystemMessage //系统消息 { unsigned char TxMessageTaskId; unsigned char MessageContext; }MCB; typedef struct TaskforMsgQueue { unsigned char TaskWaitId; unsigned char TaskPrioty; }TaskMsgQueue; typedef struct _MSG_INFO_PTR { unsigned char *Ptr; unsigned char cSize; }MSG_INFO_PTR; typedef struct SysLayerMesg //层交换信息 { unsigned char LayerChangMesg; TaskMsgQueue TaskQueue; MSG_INFO_PTR Msg_Info_Ptr; union { unsigned char cVal; struct { unsigned char bInUse:1; unsigned char bRealTime:1; unsigned char bWaitMesg:1; unsigned char bMesgNum:4; unsigned char bRealMesg:1; }bits; }Flags; }LAYMESG; typedef struct{ unsigned char Ht_value:5; unsigned char Flg:3; } emHardtStatus; typedef struct{ union{ emHardtStatus IDtimer; unsigned char bIDtimer; }htstatus; unsigned int Lt_value; unsigned long temp; }HardTimer; void CreateTask(void (* TaskName)(), unsigned char Id, unsigned char Prio,unsigned char stat); void StartTask(); //开始多任务环境,即创建完任务后的第一次调度 void IdleTask(); //默认的空闲任务 void EnInt(); //退出临界区 void DisInt(); //进入临界区 unsigned int FindMaxPrioTask(); extern void SchedTask(); //在任务末尾调用 void CurrentTaskWait(); //g挂起当前任务 unsigned char TxMessage(unsigned char RxMesgTaskId,unsigned char message); unsigned char RxMessage(unsigned char message); void SetTimerTick(unsigned int Tick); //Tick 为时钟周期 void ChangeStatus(unsigned char id); //测试用函数 unsigned char emSetHardTimer(unsigned char tid, unsigned int value); unsigned char emStartHardTimer(unsigned char tid); unsigned char emCheckHardTimer(unsigned char tid); void emDelHardTimer(unsigned char tid); void emTxSysMesg(unsigned char message); unsigned char emRxSysMesg(void); void emDelSysMesg(void); void emSysInit(void); int emWaitMesg(unsigned char message,unsigned char state,unsigned char **ptr,unsigned char *size); unsigned char emTxMesg(unsigned char message,unsigned char state,unsigned char *ptr,unsigned char size); unsigned char emSearchMesg(unsigned char message); unsigned char emRxMesg(unsigned char Index,unsigned char state,unsigned char *ptr,unsigned char size); void emDelMesg(unsigned char message); #endif <file_sep>/********************************************************************** * Microchip Technology Inc. * * FileName: traps.c * Dependencies: Header (.h) files if applicable, see below * Processor: PIC24Fxxxx * Compiler: MPLAB?C30 v3.00 or higher * **********************************************************************/ #include "common.h" #include "driver.h" #include "infra.h" #include "Phy.h" #include "Mac.H" unsigned char infrared_times = 0; unsigned char infrared_correct = 0; unsigned char testnumber=0; void __attribute__((__interrupt__)) _OscillatorFail(void); void __attribute__((__interrupt__)) _AddressError(void); void __attribute__((__interrupt__)) _StackError(void); void __attribute__((__interrupt__)) _MathError(void); void __attribute__((__interrupt__)) _AltOscillatorFail(void); void __attribute__((__interrupt__)) _AltAddressError(void); void __attribute__((__interrupt__)) _AltStackError(void); void __attribute__((__interrupt__)) _AltMathError(void); //中断入口 void __attribute__((__interrupt__)) _T1Interrupt(void); void __attribute__((__interrupt__)) _INT1Interrupt(void); extern DWORD mSeconds; extern DWORD dwTimes; void __attribute__((interrupt, no_auto_psv)) _OscillatorFail(void) { INTCON1bits.OSCFAIL = 0; //Clear the trap flag while (1); } void __attribute__((interrupt, no_auto_psv)) _AddressError(void) { INTCON1bits.ADDRERR = 0; //Clear the trap flag while (1); } void __attribute__((interrupt, no_auto_psv)) _StackError(void) { INTCON1bits.STKERR = 0; //Clear the trap flag while (1); } void __attribute__((interrupt, no_auto_psv)) _MathError(void) { INTCON1bits.MATHERR = 0; //Clear the trap flag while (1); } void __attribute__((interrupt, no_auto_psv)) _AltOscillatorFail(void) { INTCON1bits.OSCFAIL = 0; while (1); } void __attribute__((interrupt, no_auto_psv)) _AltAddressError(void) { INTCON1bits.ADDRERR = 0; while (1); } void __attribute__((interrupt, no_auto_psv)) _AltStackError(void) { INTCON1bits.STKERR = 0; while (1); } void __attribute__((interrupt, no_auto_psv)) _AltMathError(void) { INTCON1bits.MATHERR = 0; while (1); } //定义中断入口 void __attribute__((interrupt,no_auto_psv)) _T1Interrupt(void) { TMR1=0x0000; mSeconds++; IFS0bits.T1IF=0;//这个一定要 } void __attribute__((interrupt,no_auto_psv)) _INT1Interrupt(void) { ////// if(PHYPutRxBuffer())//否则是接收进入的中断 ////// { ////// Nop(); ////// } ////// IFS1bits.INT1IF=0; emDelHardTimer(5); emStartHardTimer(5); IFS1bits.INT1IF=0; } void __attribute__((interrupt,no_auto_psv)) _INT2Interrupt(void) { //第一路继电器线圈通电 data=(data|0x0008); HC595Put(data); HC595Out(); emStartHardTimer(7); IFS1bits.INT2IF=0; } void __attribute__((interrupt,no_auto_psv)) _T2Interrupt(void) { TMR2=0; IFS0bits.T2IF = 0; } void __attribute__((interrupt,no_auto_psv)) _T5Interrupt(void) { switch(sent_flag) { case HOT: infra_sent_hot(); break; case COLD: infra_sent_cold(); break; case OFF: infra_sent_off(); break; default: break; } IFS1bits.T5IF = 0; } /* *****************************空调自学习得输入捕捉中断服务子程序**************************** */ //void __attribute__((interrupt,no_auto_psv)) _IC1Interrupt(void) //{ // T3CONbits.TON = 1; // switch(code_flag) // { // case HOT: // codearray_hot[count++] = IC1BUF; // break; // case COLD: // codearray_cold[count++] = IC1BUF; // break; // case OFF: // codearray_off[count++] = IC1BUF; // break; // default: // break; // } // TMR3 = 0; // IFS0bits.IC1IF = 0; //} /* *****************************红外辅助定位输入捕捉中断服务子程序**************************** */ void __attribute__((interrupt,no_auto_psv)) _IC1Interrupt(void) { // T3CONbits.TON = 1; ////// capture1 = IC1BUF; ////// if((capture1>0x1200)&&(capture1<0x1500)) ////// { ////// infrared_times++; ////// if(4 == infrared_times) ////// { ////// infrared_times = 1; ////// LEDBlinkYellow(); ////// infrared_times = 0; ////// ////// } ////// } ////// else ////// { ////// infrared_correct = 0; ////// infrared_times = 0; ////// } ////// TMR3 = 0; infrared_times++; if(infrared_times == 4) { LEDBlinkYellow(); infrared_times = 0; infrared_correct = 1; } IFS0bits.IC1IF = 0; } void __attribute__((interrupt,no_auto_psv)) _T3Interrupt(void) { IFS0bits.T3IF = 0; } <file_sep>#ifndef _CRC_H #define _CRC_H #include "common.h" typedef union _CRC_RESULT { WORD nVal; BYTE cVal[2]; struct { BYTE cLsb; BYTE cMsb; }byte; }CRC_RESULT; //CRC校验程序 CRC_RESULT CrcCalc(const BYTE *pBuf,WORD nSize); //指数计算 WORD CalcExponent(BYTE num,BYTE exp); //随机值 //WORD GetRandom(WORD rnd); #endif <file_sep>/************************************************************ 文件描述:本文件主要是用来实现无限传感器网络的MAC层的基本功能, 包括数据包的解析,数据包的发送,命令的处理等 版本信息:v7.0 修改时间:2017/03/ *************************************************************/ #ifndef _MAC_H #define _MAC_H #include "zigbee.h" #include "tick.h" #include "mcu.h" #include "Interface.h" #include "phy.h" #include "addr.h" #include "Nvm_Flash.h" extern BYTE CoordID[2]; extern BYTE Route_flag; //0表示本地;1表示协调器;2表示转发目的节点;3表示广播 //定义发送MAC包的长度 #define ConstMacPacketSize (ConstMacPayloadSize+20) #define ConstMacBufferSize 20 //MAC Constant #define aMaxFrameRetries 3 //重发次数 #define aMaxMACFrameSize 64 //MAC帧的最大长度 #define aResponseWaitTime 10 //命令的最大响应时间 //用于CSMA机制的常量 #define aUnitBackoffPeriod 1 #define aMaxBE 5 //定义MAC层的基本命令 #define MAC_ASSOC_REQUEST 0x01 #define MAC_ASSOC_RESPONSE 0x02 #define MAC_DISASSOC_NOTIFY 0x03 #define MAC_DATA_REQUEST 0x04 #define MAC_PANCONFLICT_NOTIFY 0x05 #define MAC_ORPHAN_NOTIFY 0x06 #define MAC_BEACON_REQUEST 0x07 #define MAC_COORD_REALIGN 0x08 #define MAC_ASSOC_CHECK 0x0A #define MAC_CHECK_RSP 0x0B #define MAC_NEIGH_NOTIFY 0x40 //定义帧类型 #define MAC_FRAME_TYPE_MASK (0x03) #define MAC_FRAME_BEACON (0x00) #define MAC_FRAME_DATA (0x01) #define MAC_FRAME_ACK (0x02) #define MAC_FRAME_CMD (0x03) #define MAC_SECURITY_YES (0x08) #define MAC_SECURITY_NO (0x00) #define MAC_FRAME_PENDING_YES (0x10) #define MAC_FRAME_PENDING_NO (0x00) #define MAC_ACK_YES (0x20) #define MAC_ACK_NO (0x00) #define MAC_INTRA_PAN_YES (0x40) #define MAC_INTRA_PAN_NO (0x00) #define MAC_BEACON_YES (0x40) #define MAC_BEACON_NO (0x00) //地址模式的宏定义 #define MAC_DST_NO_ADDR (0x00) #define MAC_DST_SHORT_ADDR (0x08) #define MAC_DST_LONG_ADDR (0x0c) #define MAC_DST_ADDR_RESERVED (0x04) #define MAC_SRC_NO_ADDR (0x00) #define MAC_SRC_SHORT_ADDR (0x80) #define MAC_SRC_LONG_ADDR (0xc0) #define MAC_SRC_ADDR_RESERVED (0x40) //MAC帧头的控制域部分 typedef union _MAC_FRAME_CONTROL { struct { WORD FrameType : 3; WORD SecurityEnabled : 1; WORD FramePending : 1; WORD AckRequest : 1; WORD IntraPAN : 1;//1表示在一个网内 WORD :1; WORD :1; WORD :1; WORD DstAddrMode :2;//10代表短地址,11代表长地址 WORD :1; WORD :1; WORD SrcAddrMode :2; }bits; WORD nVal; BYTE cVal[2]; }MAC_FRAME_CONTROL; typedef union _ASSOC_REQUEST_CAP { BYTE cVal; struct { BYTE EnableCoord:1; //是否可能成为协调器 BYTE DeviceType:2; //是FFD 还是RFD BYTE PowerSource:1; //供电方式 BYTE ReceiveIdle:1; //是否是一直处于接收状态 BYTE :1; BYTE EnableSecur:1; //是否安全 BYTE AllocAddress:1;//要求分配一个短地址 }bits; }ASSOC_REQUEST_CAP; typedef enum _MAC_ASSOCIATION_RESPONSE_STATUS { MAC_ASSOCIATION_PAN_SUCCESS, //分配成功 MAC_ASSOCIATION_PAN_EXITST, //网络中已经有一个这样的短地址,主要是应用与不需要分配短地址的地方 MAC_ASSOCIATION_PAN_REFUSE //拒绝加入网络 }MAC_ASSOCIATION_RESPONSE_STATUS; typedef enum _MAC_DISASSOCIATION_REASON { MAC_COORDINATOR_FORCED_LEAVE=0x01, MAC_DEVICE_LEAVE=0x02 } MAC_DISASSOCIATION_REASON; //接收数据帧结构 typedef struct _MAC_RX_FRAME { BYTE packetSize; MAC_FRAME_CONTROL frameCON; BYTE sequenceNumber; NODE_INFO srcAddress; NODE_INFO dstAddress; BYTE pMsdu[ConstMacPayloadSize]; CRC_RESULT crcRes; BYTE rssi; BYTE crc; BOOL bReady; }MAC_RX_FRAME; //发送数据帧结构 typedef struct _MAC_TX_FRAME { BYTE packetSize; MAC_FRAME_CONTROL frameCON; BYTE sequenceNumber; NODE_INFO srcAddress; NODE_INFO dstAddress; union { BYTE cVal; struct { BYTE bFinishHeader:1; BYTE bReadyTransmit:1; BYTE bTransmitOver:1; BYTE :5; }bits; }Flags; }MAC_TX_FRAME; typedef struct _MAC_TX_QUEUE { BYTE cTxBuffer[ConstMacPacketSize];//存储数据 DWORD dwStartTime; BYTE cRetries;//重发次数 union { BYTE cVal; struct { BYTE bInUse:1; BYTE :7; }bits; }Flags; }MAC_TX_QUEUE; typedef struct _MAC_TX_BUFFER { BYTE cTxBuffer[ConstMacPacketSize]; BYTE cSize; }MAC_TX_BUFFER; //邻居节点之间关系结构体 typedef enum _RELATIONSHIP_TYPE { NEIGHBOR_IS_PARENT = 0x00,//父节点 NEIGHBOR_IS_CHILD = 0x01,//子节点 NEIGHBOR_IS_SIBLING= 0x02,//对等节点 NEIGHBOR_IS_NONE = 0x03,//普通节点 } RELATIONSHIP_TYPE; //MAC层的初始化 void MACInitSetup(void); //地址信息的初始化 void MACInitIEEEAddr(void); //设置地址信息,网络描述信息,状态信息 void MACSetAddrInfo(void); //读取地址信息,网络描述信息,状态信息 void MACGetAddrInfo(void); //地址辨识 BOOL MACCheckAddress(NODE_INFO *pAddr); //封装包头 BOOL MACPutHeader(NODE_INFO *pDestAddr, BYTE frameCON); //写入发送缓冲区 void MACPutTxBuffer(BYTE *ptr,BYTE cSize); //发送数据 BOOL MACTransmitPacket(void); //读取一个完整的数据包 BOOL MACGetPacket(void); //丢弃一定长度的数据 void MACDiscardRx(BYTE size); //处理信标帧 void MACProcessBeacon(void); //处理命令帧 void MACProcessCommand(void); //处理确认帧 void MACProcessAck(void); //封装地址信息 void MACFillSourAddr(BYTE *ptr); //发送确认帧 BOOL MACSendACK(BYTE dsn); //发送帧临时存储 WORD MACEnqueTxFrame(void); //清除临时发送队列里一个数据帧 WORD MACRemoveTxFrame(BYTE dsn); //从临时发送队列里找到一个数据帧 WORD MACSearchTxFrame(BYTE dsn); //重发处理 void MACRefreshTxFrame(void); //统计临时发送队列中数据帧个数 BYTE MACRecordTxFrame(void); /**************************************************** //通过对协调器队列的管理,来选择一个可靠的网络加入 ****************************************************/ //格式化列表 void MACFormatPANRecord(void); //增加一个协调器节点 WORD MACAddPANRecord(PAN_DESCRIPTOR *Record); //查找协调器节点 WORD MACSearchPANRecord(PAN_DESCRIPTOR *Record); //修改协调器节点的通信次数 void MACRefreshPANRecord(PAN_DESCRIPTOR *Record); //选择一个最好的网络 WORD MACSearchPrioPANRecord(PAN_DESCRIPTOR *Record); //根据网络地址查询 WORD MACSearchPANRecordByPAN(SHORT_ADDR PANId); //统计网络的数量 WORD MACCountPANRecord(void); //超时处理 void MACProccessPANRecordByTimeout(void); //建立网络 void MACEstablishPAN(void); //加入网络 void MACJoinPAN(void); //对射频接收缓冲区的操作 #define MACGet() PHYGet() #define MACGetArray(ptr,cSize) PHYGetArray(ptr,cSize) //射频发送 #define MACTransmitByCSMA() PHYTranmitByCSMA() //信标请求 BOOL MACSendBeaconReq(void); //入网请求 BOOL MACSendAssociationReq(NODE_INFO *macAddr,ASSOC_REQUEST_CAP CapInfo); //离开网络 BOOL MACSendDisassociationNotify(LONG_ADDR *LongAddr,MAC_DISASSOCIATION_REASON Reason); //API接口 #define MACGetDeviceType() (macPIB.DeviceInfo.bits.DeviceType) #define MACSetDeviceType(DeviceType) (macPIB.DeviceInfo.bits.DeviceType=DeviceType) #define MACIsNetworkEstablished() (macStatus.bits.bEstablishPAN) #define MACIsNetworkJoined() (macStatus.bits.isAssociated) #define MACGetAddrMode() (macStatus.bits.addrMode) #define MACGetPANId() (macPIB.macPANId) #define MACGetShortAddr() (macPIB.macShortAddr) #define MACGetLongAddr() (macPIB.macLongAddr) #define MACSetAddrMode(v) (macStatus.bits.addrMode=v) #define MACSetPANId(v) (macPIB.macPANId.nVal=v.nVal) #define MACSetShortAddr(v) (macPIB.macShortAddr.nVal=v.nVal) #define MACSetLongAddr(v) (memcpy((BYTE *)&macPIB.macLongAddr,(BYTE *)&v,sizeof(LONG_ADDR))) #define MACGetCoordAddrMode() (PANDescriptor.CoordAddrMode) #define MACGetCoordPANId() (PANDescriptor.CoordPANId) #define MACGetCoordShortAddr() (PANDescriptor.CoordShortAddr) #define MACGetCoordLongAddr() (PANDescriptor.CoordLongAddr) #define MACSetCoordAddrMode(v) (PANDescriptor.CoordAddrMode=v) #define MACSetCoordPANId(v) (PANDescriptor.CoordPANId.nVal=v.nVal) #define MACSetCoordShortAddr(v) (PANDescriptor.CoordShortAddr.nVal=v.nVal) #define MACSetCoordLongAddr(v) (memcpy((BYTE *)&PANDescriptor.CoordLongAddr,(BYTE *)&v,sizeof(LONG_ADDR))) void MACFlushTxFrame(void); void MACTask(void); void MACProcessData(void); extern RTIME CurrentSysTime; extern DWORD mSeconds; extern RTIME CurrentSysTime; extern RTIME ServerTime; extern TICK StartmSeconds; extern TICK GetmSecinds(void); extern PAN_DESCRIPTOR PANDescriptor; extern MAC_PIB macPIB; //用于记录mac层的PIB属性 extern MAC_STATUS macStatus; //记录MAC状态 extern MAC_RX_FRAME macCurrentRxFrame; //接收包的帧格式 #endif <file_sep>#include "timeds.h" #include "p24FJ64GA002.h" #include "tick.h" /****************************************************************** 此时已经可以AD转换了,转换后将得到的数据进行一一校正,进而再进行传递 调用方法:只需要调用ADgetData()就可以了。 ******************************************************************/ #include "common.h" BYTE Second; BYTE Minute; BYTE Hour; BYTE Day; BYTE Month; BYTE Year; extern DWORD mSeconds; TICK StartmSeconds; RTIME ServerTime; RTIME CurrentSysTime; /********************时间初始化,防防止动作*************************/ void CurSysTimeInit(void) { CurrentSysTime.year = 0xff; CurrentSysTime.month = 0x07; CurrentSysTime.day = 0x07; CurrentSysTime.hour = 0x12; CurrentSysTime.minute = 0x01; CurrentSysTime.second = 0x01; } /****************计算当前时间******************************/ void CalCurSysTime(DWORD time_sys , RTIME *p)//当前的系统时间 { WORD hour,minute,second; time_sys /= 100; //将毫秒换成秒 hour = (WORD)(time_sys / 3600);//计算小时数 minute = (WORD)(time_sys / 60);//计算分钟数 minute = minute % 60;//计算显示的分钟数即去掉了小时 second = (WORD)(time_sys % 60); //计算显示的秒数 p->day = ServerTime.day; p->hour = ServerTime.hour + (BYTE)hour; p->minute = ServerTime.minute + (BYTE)minute; p->second = ServerTime.second + (BYTE)second; if(p->second >= 60) { p->second %= 60; p->minute += 1; } if (p->minute >= 60) { p->minute %= 60; p->hour += 1; } if(p->hour >= 24) { p->hour %= 24; p->day += 1; } } /********************系统真实时间**************************/ void SysRealTime(void) { if(CurrentSysTime.year!=0xFF) { CalCurSysTime((mSeconds-StartmSeconds) , &CurrentSysTime); } } TICK GetmSecinds(void) { return mSeconds; } <file_sep>#ifndef _FLASH_H #define _FLASH_H #include "common.h" #include "mcu.h" typedef union flashtuReg32 { DWORD dwVal; struct { WORD LW; WORD HW; }byte; BYTE cVal[4]; } uReg32; /********************************************************************* * 函数名: FLASHErasePage(uReg32 addr); * 前提条件: 无 * 输入参数: uReg32 addr,要擦除的页地址,也就是512条指令的起始地址, * 输出参数: 无 * 注意事项: addr,要能够被512整除 * 功能描述: 擦除内部FLASH的一页 ********************************************************************/ void FLASHErasePage(uReg32 addr); /********************************************************************* * 函数名: void FLASHReadValue(uReg32 addr,WORD *pRxBuf, WORD size); * 前提条件: 无 * 输入参数: uReg32 addr,要读取的地址;WORD *pRxBuf,读取数据存储指针;WORD size,读取数据长度 * 输出参数: 无 * 注意事项: 内部FLASH只存储在低字中,高字不存储数据 * 功能描述: 从内部FLASH中读取一定长度的数据 ********************************************************************/ void FLASHGetArray(uReg32 addr,WORD *pRxBuf, WORD size); /********************************************************************* * 函数名: void FLASHWriteValue(uReg32 addr,WORD *pTxBuf, WORD size); * 前提条件: 无 * 输入参数: uReg32 addr,要读取的地址;WORD *pTxBuf,写入数据存储指针;WORD size,数据长度 * 输出参数: 无 * 注意事项: 内部FLASH只存储在低字中,高字不存储数据 * 功能描述: 往从内部FLASH中读取写入一定长度的数据 ********************************************************************/ void FLASHPutArray(uReg32 addr,const WORD *pTxBuf, WORD size); void FLASHReadBytes(uReg32 addr,BYTE *pRxBuf, WORD size); void FLASHWriteBytes(uReg32 addr,const BYTE *pTxBuf,WORD size); #endif <file_sep>#include "FlashMM.h" /* 修改日期:2016年8月8日 修改者:李延超 特别说明: 一个是向FLASH中写入函数。FlashWriteMem(WORD LogSector,WORD OffSet,WORD *Ptr,WORD Number) 该函数实现流程是自己写的。 首先向设定的页中写数据,当换页时,首先将上一次写的页置为Dirty页,然后再写下一页。Dirty 作为换页的一个标志。所以,存在的一个bug是如果你写完这一页,然后写另一页,再回来写这一页的 时候会无法写入。另外,需要修改初始化函数FlashCreateMapInfo()。当是dirty页时,也要增加逻辑页 和物理页之间的对应,否则读取不正确。 */ //定位要进行定位的地址,备份页开始的地方,为了进行擦除。 WORD LctionAddr = 296; //对应的地址为0X9400,实际上是从第三块开始的,作为备份块使用。 //定义FLASH属性信息 FLASH_INFO MemInfo; //定义映射表,映射表物理扇区从数据区开始,不包含管理区 MEM_MAP_INFO MemMapInfo; //擦除 void FlashEraseMem(WORD LogicBlockNum) //输入为逻辑块号 { uReg32 addr; //地址=起始地址+块号*每块字节数 addr.dwVal=ConstPhyBeginAddr+LogicBlockNum*ConstBlockSize*ConstPageSize; FLASHErasePage(addr); //该函数中已经延时了 } //OffSet为字的开始 WORD FlashPutMem(WORD PhySector,WORD OffSet,WORD *Ptr,WORD Number) //输入为物理页 { WORD Size; uReg32 addr; //地址=起始地址页号*每页字节数,起始地址包含了管理部分 addr.dwVal=PhySector*ConstPageSize+2*OffSet; // if(Number<=ConstDataPageSize) //每页去掉8个字节状态位和逻辑单元 Size=Number; else Size=ConstDataPageSize; //这是字 FLASHPutArray(addr,Ptr,Size); CLR_WDT(); return Size; } WORD FlashGetMem(WORD PhySector,WORD OffSet,WORD *Ptr,WORD Number) //输入为物理页 { WORD Size; uReg32 addr; //地址=起始地址页号*每页字节数,起始地址包含了 addr.dwVal=PhySector*ConstPageSize+2*OffSet; if(Number<=ConstDataPageSize) //需要去掉几个状态字节 Size=Number; else Size=ConstDataPageSize;//这是字的大小 FLASHGetArray(addr,Ptr,Size); CLR_WDT(); return Size; } //写入每页的状态 void FlashPutStatus(WORD PhySector,WORD Status) //输入为物理页 { FlashPutMem(PhySector,ConstStatusOffSet,(WORD *)&Status,lengthof(WORD)); } WORD FlashGetStatus(WORD PhySector) //输入为物理页 { WORD Status; FlashGetMem(PhySector,ConstStatusOffSet,(WORD *)&Status,lengthof(WORD)); return Status; } //写入每页的CRC校验和 void FlashPutCheckSum(WORD PhySector,WORD CheckSum) { FlashPutMem(PhySector,ConstCheckSumOffSet,(WORD *)&CheckSum,lengthof(WORD)); } WORD FlashGetCheckSum(WORD PhySector) //输入为物理页 { WORD CheckSum; FlashGetMem(PhySector,ConstStatusOffSet,(WORD *)&CheckSum,lengthof(WORD)); return CheckSum; } //写入每页的逻辑号 void FlashPutLogicSector(WORD PhySector,WORD LogicSector) { FlashPutMem(PhySector,ConstLogicOffSet,(WORD *)&LogicSector,lengthof(WORD)); } WORD FlashGetLogicSector(WORD PhySector) //输入为物理页 { WORD LogicSector; FlashGetMem(PhySector,ConstLogicOffSet,(WORD *)&LogicSector,lengthof(WORD)); return LogicSector; } //坏块标志设定 void FlashSetBadSector(WORD PhySector) //根据物理页 { WORD i,j; WORD Index; WORD OffSet; WORD Status; //首先把物理页转换成坏区表中的位置,按照顺序排第几个扇区 Index=PhySector-ConstDataBeginSector; //去掉开始,去掉管理区 i=Index/16;//计算出数组坐标 j=Index%16; //计算出是一个自己的第几位 OffSet=4+i; //去掉四个字,因为偏移量是按照字来进行的 Status=~(0x01<<j); //0表示坏区 Nop(); //找到管理区存储位置,ConstBeginSector FlashPutMem(ConstPhyBeginSector,OffSet,(WORD *)&Status,lengthof(WORD)); Nop(); } //增加映射表的一条记录 WORD AddMemMapRecord(WORD LogicSector,WORD PageNum) { //if((LogicSector<ConstDataSectorSize) && (MemMapInfo.PhySector[LogicSector]==MEM_NULL)) if(LogicSector<ConstDataSectorSize) //修改的数据要覆盖上次写的数据,所以不能加空的判断 { MemMapInfo.PhySector[LogicSector]=PageNum; return LogicSector; } return MEM_NULL; } //删除映射表的一条记录 WORD RemoveMemMapRecord(WORD LogicSector) { if(LogicSector<ConstDataSectorSize) { MemMapInfo.PhySector[LogicSector]=MEM_NULL; return LogicSector; } return MEM_NULL; } //修改映射表记录 WORD RefreshMemMapRecord(WORD LogicSector,WORD PageNum) { if(LogicSector<ConstDataSectorSize) { if(MemMapInfo.PhySector[LogicSector]!=MEM_NULL) { MemMapInfo.PhySector[LogicSector]=PageNum; return LogicSector; } } return MEM_NULL; } //根据逻辑扇区得到物理扇区 WORD GetMemMapRecord(WORD LogSector) { if(LogSector<ConstDataSectorSize) { return MemMapInfo.PhySector[LogSector]; } return MEM_NULL; } //查询一个为空闲的物理扇区 WORD SearchFreePhySector(void) { WORD Status,i; WORD PhySector; for(i=0;i<ConstDataSectorSize;i++) //数据扇区范围内搜索 { PhySector=ConstDataBeginSector+i; //从数据扇区开始查找,从288页开始,也就是从物理地址0X9000开始。 Status=FlashGetStatus(PhySector); if(Status != DIRTY) { FlashPutStatus(PhySector,FREE); //将该页修改为空闲,其实只有第一次可以写入,其它的时候不起作用。 return PhySector; //返回物理页号 } } return MEM_NULL; } void FlashSearchMemStatus(void) { WORD i; WORD PhySector; //定义每页状态表 WORD MemStatus[ConstDataSectorSize]; for(i=0;i<ConstDataSectorSize;i++) //数据扇区范围内搜索 { PhySector=ConstDataBeginSector+i; //从数据扇区开始查找 MemStatus[i]=FlashGetStatus(PhySector); } Nop(); } //创建映射表 void FlashCreateMapInfo(void) { WORD i; WORD PhySector,LogSector; WORD Status,Number; //首先把空闲扇区数量清空 MemMapInfo.FreeNumber=0; //把需要擦除的数量清空 MemMapInfo.DirtyNumber=0; //从数据物理扇区开始依次检索 Number=ConstDataSectorSize; for(i=0;i<Number;i++) { PhySector=ConstDataBeginSector+i;//从数据扇区开始查找,跳过管理部分//ConstDataBeginSector81 //存储状态的偏移量 FlashGetMem(PhySector,ConstStatusOffSet,(WORD *)&Status,lengthof(WORD));//ConstStatusOffSet62 //存储逻辑扇区的偏移量 FlashGetMem(PhySector,ConstLogicOffSet,(WORD *)&LogSector,lengthof(WORD)); //读取逻辑地址 if(Status==INUSE) { AddMemMapRecord(LogSector,PhySector); } else if(Status==MEM_NULL) { MemMapInfo.FreeNumber++; //记录空闲的扇区数量 } else if(Status==DIRTY) { MemMapInfo.DirtyNumber++;//仍然要读取地址的对应关系 AddMemMapRecord(LogSector,PhySector); } } } void FlashFormatMem(void) //格式化存储区 { WORD i; MemInfo.EraseNumber++; //擦除次数增加 //擦除所有的块 for(i=0;i<ConstTotalPhyPages/ConstBlockSize;i++) FlashEraseMem(i); //管理区存储位置是ConstBeginSector,写入FLASH信息 FlashPutMem(ConstPhyBeginSector,0,(WORD *)&MemInfo,lengthof(FLASH_INFO)); //修改映射表,都置为空,表明存储区空间是空的 for(i=0;i<ConstDataSectorSize;i++) MemMapInfo.PhySector[i]=MEM_NULL; //i表示逻辑扇区 MemMapInfo.FreeNumber=ConstDataSectorSize; //记录空闲扇区数量 MemMapInfo.DirtyNumber=0; //需要擦除的数量为0 } //初始化 void FlashInitSetup(void) { WORD i; //初始化MemInfo MemInfo.Version=0; MemInfo.EraseNumber=0; MemInfo.Identifier=0; for(i=0;i<ConstBadSectorSize;i++) MemInfo.BadSector[i]=MEM_NULL; //初始化MemMapInfo MemMapInfo.FreeNumber=0; MemMapInfo.DirtyNumber=0; for(i=0;i<ConstDataSectorSize;i++) MemMapInfo.PhySector[i]=MEM_NULL; //i表示逻辑扇区 //读取ID扇区 FlashCreateMemInfo(); //如果是未使用,那么格式化 if((MemInfo.Version==MEM_NULL) && (MemInfo.Identifier==MEM_NULL)) { MemInfo.Version=0x01; MemInfo.EraseNumber=1; MemInfo.Identifier=0x9999; //每位代表一个扇区,0为坏扇区,1为正常 for(i=0;i<ConstBadSectorSize;i++) MemInfo.BadSector[i]=MEM_NULL; //管理区存储位置是ConstBeginSector,写入信息 FlashPutMem(ConstPhyBeginSector,0,(WORD *)&MemInfo,lengthof(FLASH_INFO)); } else { //创建映射表 FlashCreateMapInfo(); } } //存储区整理,把Dirty的擦除,输入是逻辑块号 BOOL FlashCleanMem(WORD nBlkNum) { WORD i; WORD BlockNumber; WORD Status; WORD LogSector; WORD PhySector,PageNum; WORD PtrRd[ConstWordPageSize]; for(i=0;i<ConstBlockSize;i++) { PhySector=ConstDataBeginSector+nBlkNum*ConstBlockSize+i; //找到物理页号 Status=FlashGetStatus(PhySector); if(Status!=INUSE) continue; //说明本页没有使用,跳出本次循环 //找到一个使用的页,把该页呢绒读出来写到另一个块的空闲页 FlashGetMem(PhySector,0,(WORD *)PtrRd,ConstWordPageSize); //按照字来读 //读出对应的逻辑页面 LogSector=FlashGetLogicSector(PhySector); //找到一个空闲页,保证不要再次写入本块 while(1) { //找到一个空闲页 PageNum=SearchFreePhySector(); //再找到一个空闲页,保证不要再次写入本块 //如果为空,则说明已经没有空闲页了,整理得太晚了 if(PageNum==MEM_NULL) return FALSE; //计算空闲页所属的逻辑块号 BlockNumber=(PageNum-ConstDataBeginSector)/ConstBlockSize; if(BlockNumber==nBlkNum) continue; //跳出本次循环,重新开始 //写到另一块的新空闲页 FlashPutMem(PageNum,0,(WORD *)PtrRd,ConstWordPageSize); //并将页置成使用 FlashPutStatus(PageNum,INUSE); //写入逻辑扇区号 FlashPutLogicSector(PageNum,LogSector); //将原来的页置成DIRTY FlashPutStatus(PhySector,DIRTY); //修改映射表 RefreshMemMapRecord(LogSector,PageNum); CLR_WDT(); break; //成功就跳出循环 } } //开始擦除 FlashEraseMem(nBlkNum+1); //将逻辑块转成物理块,要抛去管理块 #ifdef I_NEED_DEBUG DebugPrintf("FlashErase!",11); #endif return TRUE; } void FlashManageMem(void) { WORD i,j; WORD Number=0; float Percent; WORD PhySector,nBlockNum; WORD Status; Percent=((float)MemMapInfo.FreeNumber)/(float)ConstDataSectorSize; //共有5块,最多剩一块时候,开始整理存储区 if((Percent>=0) && (Percent<=0.2)) { //所有的块都要查询 for(i=0;i<ConstDataSectorSize/ConstBlockSize;i++) { //将数据逻辑块,转成物理块号 nBlockNum=ConstDataBeginSector/ConstBlockSize+i; //检索每块内状态为Dirty的页数量 for(j=0;j<ConstBlockSize;j++) { //计算物理页 PhySector=nBlockNum*ConstBlockSize+j; Status=FlashGetStatus(PhySector); if(Status==DIRTY) Number++; } //如果每块内,DIRTY的数量超过一半,则进行整理 if(Number>=(ConstBlockSize/2)) { Number=0; //重新清零,再次计数 FlashCleanMem(i); } CLR_WDT(); } //整理完毕,重新创建一下映射表 FlashCreateMapInfo(); } } //写存储器是按照逻辑扇区来进行写的,偏移量则是按照字来进行 WORD FlashWriteMem(WORD LogSector,WORD OffSet,WORD *Ptr,WORD Number) { WORD Size=0; WORD MaxSector; WORD NowLogicSector; WORD PhySector,PageNum; WORD CntNodeBackInfo = 18;//备份区域,从第18页开始,在删除的时候使用。 WORD Status,i; //从映射表中查找物理扇区,如果为空表明该逻辑扇区空闲 PhySector=GetMemMapRecord(LogSector); MaxSector=ConstDataBeginSector+ConstDataSectorSize;//值是328. //如果逻辑扇区对应物理扇区为空,或者已经使用 if((PhySector==MEM_NULL) || (PhySector<MaxSector)) { //进行整理内存 //FlashManageMem(); FlashManageMem(); //如果是往备份块中写信息 if(LogSector >= CntNodeBackInfo) { for(i=0;i<8;i++) //在第二块中搜索,从308页开始 { PageNum = LctionAddr + i; Status=FlashGetStatus(PageNum); if(Status != DIRTY) { FlashPutStatus(PhySector,FREE); //将该页修改为空闲,其实只有第一次可以写入,其它的时候不起作用。 break; } } } //如果不是往备份快中写信息,直接从头开始查找,与逻辑页的大小无关,都是从空闲的Flash区域最开始查找。 else { PageNum=SearchFreePhySector(); } NowLogicSector = FlashGetLogicSector(PageNum); //得到该扇区对应的逻辑页号 if((NowLogicSector != LogSector) && (NowLogicSector != MEM_NULL)) { MemMapInfo.FreeNumber--; FlashPutStatus(PageNum,DIRTY); MemMapInfo.DirtyNumber++; if(LogSector > CntNodeBackInfo) { PageNum = LctionAddr+(LogSector - CntNodeBackInfo); } else { PageNum = SearchFreePhySector(); } } //如果没有空闲的物理扇区,那么写失败 if(PageNum==MEM_NULL) { return 0; } //向该扇区中写入数据 Size=FlashPutMem(PageNum,OffSet,Ptr,Number); //空闲的扇区减少一个 //MemMapInfo.FreeNumber--; MemMapInfo.FreeNumber--; //修改当前扇区的状态 //FlashPutStatus(PageNum,INVALID); //如果本逻辑扇区是一个空的,直接加入映射表 if(PhySector==MEM_NULL) { //修改映射表中的对应值 AddMemMapRecord(LogSector,PageNum);//把逻辑扇区和物理扇区进行对应。 //再把刚写的物理页面的状态修改成InUSe FlashPutStatus(PageNum,INUSE); //写入逻辑扇区号 FlashPutLogicSector(PageNum,LogSector); } else { //修改映射表原来对应物理扇区成Dirty //FlashPutStatus(PhySector,DIRTY); FlashPutStatus(PhySector,DIRTY); //Dirty状态的页又多了一个 //MemMapInfo.DirtyNumber++; MemMapInfo.DirtyNumber++; //修改逻辑扇区对应的物理扇区值 RefreshMemMapRecord(LogSector,PageNum); //再把刚写的物理页面的状态修改成InUSe FlashPutStatus(PageNum,INUSE); //写入逻辑扇区号 FlashPutLogicSector(PageNum,LogSector); } } return Size; } WORD FlashReadMem(WORD LogSector,WORD OffSet,WORD *Ptr,WORD Number) { WORD Size,i; WORD PhySector; //由逻辑扇区得到物理扇区 PhySector=GetMemMapRecord(LogSector); //如果该扇区还没有使用,那么全部为0xFFFF if(PhySector==MEM_NULL) { Size=Number; for(i=0;i<Number;i++) *Ptr++=0xFFFF; #ifdef I_NEED_DEBUG DebugPrintf("FlashRead is error!",17); #endif } else { Size=FlashGetMem(PhySector,OffSet,Ptr,Number); } return Size; } <file_sep>#ifndef _DRIVER_H #define _DRIVER_H #include "cc2500.h" #include "common.h" #include "spi.h" #include "zigbee.h" #include "Interface.h" #include "Tick.h" #define RSSI_OFFSET 71 typedef enum _RF_TRX_STATE //射频芯片的状态 { RF_TRX_RX, RF_TRX_OFF, RF_TRX_IDLE, RF_TRX_TX } RF_TRX_STATE; /************************************************************ driver.h 文件描述:本文件主要是用来实现对CC2500的基本操作,也是硬件驱动部分之一 版本信息:v1.0 修改时间:2008/03/ *************************************************************/ /********************************************************************* * 函数名: void RFReset(void) * 前提条件: SPIInit()已经调用 * 输入参数: 无 * 输出参数: 无 * 注意事项: 无 * 功能描述: 初始化变量 ********************************************************************/ void RFReset(void); /********************************************************************* * 函数名: void RFWriteStrobe(BYTE cmd) * 前提条件: SPIInit()已经调用 * 输入参数: BYTE cmd,需要写入的命令 * 输出参数: 无 * 注意事项: 无。 * 功能描述: 对CC2500设置射命令 ********************************************************************/ void RFWriteStrobe(BYTE cmd);//写CC2500命令 /********************************************************************* * 函数名: void RFWriteReg(BYTE addr, BYTE value); * 前提条件: SPIInit()已经调用 * 输入参数: BYTE addr,寄存器地址,BYTE addr,需要配置的值 * 输出参数: 无 * 注意事项: 无 * 功能描述: 对CC2500配置寄存器 ********************************************************************/ void RFWriteReg(BYTE addr, BYTE value);//写寄存器值 /********************************************************************* * 函数名: BYTE RFReadReg(BYTE addr); * 前提条件: SPIInit()已经调用 * 输入参数: BYTE addr,寄存器地址 * 输出参数: 返回寄存器的值 * 注意事项: 无 * 功能描述: 读取CC2500配置寄存器 ********************************************************************/ BYTE RFReadReg(BYTE addr);//读寄存器的值 /********************************************************************* * 函数名: BYTE RFGetStatus(BYTE addr); * 前提条件: SPIInit()已经调用 * 输入参数: BYTE addr,寄存器地址 * 输出参数: 返回CC2500当前的状态 * 注意事项: 无 * 功能描述: 读取CC2500状态 ********************************************************************/ BYTE RFGetStatus(BYTE addr); /********************************************************************* * 函数名: void RFWriteBurstReg(BYTE addr,BYTE *pWriteValue,BYTE size); * 前提条件: SPIInit()已经调用 * 输入参数: BYTE addr,寄存器的初始地址;BYTE *pWriteValue存储写入数据值指针, * BYTE size,是写入寄存器的个数 * 输出参数: 无 * 注意事项: 无 * 功能描述: 连续写入CC2500配置寄存器 ********************************************************************/ void RFWriteBurstReg(BYTE addr,BYTE *pWriteValue,BYTE size);//连续写几个寄存器的值 /********************************************************************* * 函数名: void RFReadBurstReg(BYTE addr,BYTE *pReadValue,BYTE size); * 前提条件: SPIInit()已经调用 * 输入参数: BYTE addr,寄存器的初始地址;BYTE *pWriteValue存储读取的值指针, * BYTE size,是读取寄存器的个数 * 输出参数: 无 * 注意事项: 无 * 功能描述: 连续读取CC2500配置寄存器 ********************************************************************/ void RFReadBurstReg(BYTE addr,BYTE *pReadValue,BYTE size);//连续读几个寄存器的值 /********************************************************************* * 函数名: BYTE RFReadRxFIFO(void) * 前提条件: SPIInit()已经调用 * 输入参数: 无 * 输出参数: BYTE,从RXFIFO中读取一个字节 * 注意事项: 无 * 功能描述: 从RXFIFO寄存器中读取一个字节 ********************************************************************/ BYTE RFReadRxFIFO(void);//把接收到的数据读入接收缓冲区 /********************************************************************* * 函数名: void RFWriteTxFIFO(BYTE *pTxBuffer,BYTE size) * 前提条件: SPIInit()已经调用 * 输入参数: BYTE *pTxBuffer,写入值的指针,BYTE size写入的字节数 * 输出参数: 无 * 注意事项: 无 * 功能描述: 往TXFIFO寄存器中写入数据 ********************************************************************/ void RFWriteTxFIFO(BYTE *pTxBuffer,BYTE size); void RFClearTxBuffer(void); //清空接收缓冲区 void RFClearRxBuffer(void); //清空发送缓冲区 void RFInitSetup(void); //寄存器设置 BYTE RFDetectEnergy(void); //能量检测 void RFSetChannel(BYTE channel); //设置信道 void RFSetTxPower(BYTE power); //设置发射功率 void RFSetBaudRate(BYTE BaudRate); void RFSetTRxState(RF_TRX_STATE state); //设置RF状态 RF_TRX_STATE RFGetTRxState(void); void RFDetectStatus(void); //RF状态检测 BOOL RFTranmitByCSMA(void); //利用CSMA发送数据 #endif <file_sep>#ifndef _TICK_H #define _TICK_H #include "common.h" //定义时间结构 typedef DWORD TICK; //获取当前时间 TICK GetTicks(void); //计算时间间隔 TICK DiffTicks(TICK start,TICK end); //同步时间 void SynTicks(TICK tick); #endif <file_sep>#include "led.h" #include "mac.h" #include "common.h" #include "bootloader.h" #include "Mac.H" #include <math.h> extern BYTE Loc_Buffer[20]; extern WORD distance_Buffer[20]; extern BYTE Loc_i,Loc_j; extern BYTE Loc_Times; extern BYTE Type; //系统查询到系统消息TEM_SENT_REQ时,根据全局变量Type进行数据的回复 extern BYTE infrared_correct; unsigned int register2distance (float reg) { // 默认参数 从bootloader.c里的数组加载 // rssi_offset 71 // rssi_standard 45 // rssi_factor 4.0 float dbm = 0.0; float distance = 0.0; dbm = reg >= 128 ? (reg-256)/2-Parameter[_rssi_offset] :reg/2-Parameter[_rssi_offset] ; WORD mid2; distance = (float)pow(10,(-dbm-Parameter[_rssi_standard])/(10*Parameter[_rssi_factor])); mid2 = distance * 100;//debug观察寄存器用 return distance*100; } void LocTask(void) { BYTE i; BYTE cSize = 0; BYTE cPtrTx[50]; NODE_INFO macAddr; i=emWaitMesg(LOC_HEART_REQ,RealTimeMesg,0,0); if(i==1) { Delay(0x3000); macAddr.AddrMode = MAC_DST_SHORT_ADDR; macAddr.PANId.nVal = PANDescriptor.CoordPANId.nVal; macAddr.ShortAddr.nVal = PANDescriptor.CoordShortAddr.nVal; MACPutHeader(&macAddr,MAC_FRAME_DATA | MAC_INTRA_PAN_YES | MAC_ACK_NO); cPtrTx[cSize++]=0x02; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x01; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=30; //数据总长度30=0x1E cPtrTx[cSize++]=macPIB.macPANId.nVal>>8; cPtrTx[cSize++]=macPIB.macPANId.nVal; cPtrTx[cSize++]=macPIB.macShortAddr.nVal>>8; cPtrTx[cSize++]=macPIB.macShortAddr.nVal; cPtrTx[cSize++]=0x85; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x01; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x40; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x43; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x00; MACPutTxBuffer(cPtrTx,cSize); MACTransmitPacket(); } i=emWaitMesg(LOC_RSSI_REQ,RealTimeMesg,0,0); if(i==1) { Delay(0x3000); macAddr.AddrMode = MAC_DST_SHORT_ADDR; macAddr.PANId.nVal = PANDescriptor.CoordPANId.nVal; macAddr.ShortAddr.nVal = PANDescriptor.CoordShortAddr.nVal; MACPutHeader(&macAddr,MAC_FRAME_DATA | MAC_INTRA_PAN_YES | MAC_ACK_NO); cPtrTx[cSize++]=0x02; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x01; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=16; //数据总长度30=0x1E cPtrTx[cSize++]=macPIB.macPANId.nVal>>8; cPtrTx[cSize++]=macPIB.macPANId.nVal; cPtrTx[cSize++]=macPIB.macShortAddr.nVal>>8; cPtrTx[cSize++]=macPIB.macShortAddr.nVal; cPtrTx[cSize++]=0x40; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=macCurrentRxFrame.rssi;//记录的是锚节点 接收协调器的 RF信号强度 cPtrTx[cSize++]=macCurrentRxFrame.crc; MACPutTxBuffer(cPtrTx,cSize); MACTransmitPacket(); } i=emWaitMesg(LOC_DIS_REQ,RealTimeMesg,0,0); if(i==1) { Delay(0x3000); macAddr.AddrMode = MAC_DST_SHORT_ADDR; macAddr.PANId.nVal = PANDescriptor.CoordPANId.nVal; macAddr.ShortAddr.nVal = PANDescriptor.CoordShortAddr.nVal; MACPutHeader(&macAddr,MAC_FRAME_DATA | MAC_INTRA_PAN_YES | MAC_ACK_NO); cPtrTx[cSize++]=0x02; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x01; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=37; cPtrTx[cSize++]=macPIB.macPANId.nVal>>8; cPtrTx[cSize++]=macPIB.macPANId.nVal; cPtrTx[cSize++]=macPIB.macShortAddr.nVal>>8; cPtrTx[cSize++]=macPIB.macShortAddr.nVal; /* * BYTE dSize = cSize - 9; while(dSize <= 20) //减去9个字节的头 { cPtrTx[cSize++]=Loc_Buffer[dSize]>>8; cPtrTx[cSize++]=Loc_Buffer[dSize++]; } cPtrTx[9]=0x40; //按端口号将数据分段,每段7个数据 cPtrTx[10]=0x01; cPtrTx[11]=0x00; cPtrTx[16]=0x40; cPtrTx[17]=0x02; cPtrTx[18]=0x00; cPtrTx[23]=0x40; cPtrTx[24]=0x03; cPtrTx[25]=0x00; cPtrTx[cSize++]=0x40; cPtrTx[cSize++]=0x04; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=infrared_correct; cPtrTx[cSize++]=register2distance(0xc8)>>8; cPtrTx[cSize++]=register2distance(0xc8); memset(Loc_Buffer,0,30*sizeof(unsigned char)); memset(distance_Buffer,0,30*sizeof(unsigned int)); infrared_correct = 0; * */ cPtrTx[cSize++]=0x40; cPtrTx[cSize++]=0x01; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0; cPtrTx[cSize++]=0; cPtrTx[cSize++]=register2distance(Loc_Buffer[0])>>8; // = distance_Buffer[0]>>8; cPtrTx[cSize++]=register2distance(Loc_Buffer[0]); cPtrTx[cSize++]=0x40; cPtrTx[cSize++]=0x02; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0; cPtrTx[cSize++]=0; cPtrTx[cSize++]=register2distance(Loc_Buffer[1])>>8; // = distance_Buffer[0]>>8; cPtrTx[cSize++]=register2distance(Loc_Buffer[1]); cPtrTx[cSize++]=0x40; cPtrTx[cSize++]=0x03; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0; cPtrTx[cSize++]=0; cPtrTx[cSize++]=register2distance(Loc_Buffer[2])>>8; // = distance_Buffer[0]>>8; cPtrTx[cSize++]=register2distance(Loc_Buffer[2]); cPtrTx[cSize++]=0x40; cPtrTx[cSize++]=0x04; cPtrTx[cSize++]=0x00; cPtrTx[cSize++]=0; cPtrTx[cSize++]=0; cPtrTx[cSize++]=register2distance(Loc_Buffer[3])>>8; // = distance_Buffer[0]>>8; cPtrTx[cSize++]=register2distance(Loc_Buffer[3]); memset(Loc_Buffer,0,20*sizeof(unsigned char)); memset(distance_Buffer,0,20*sizeof(unsigned int)); MACPutTxBuffer(cPtrTx,cSize); MACTransmitPacket(); } CurrentTaskWait(); SchedTask(); }<file_sep>/***************************************************************************** * * Simple SRAM Dynamic Memory Allocation * ***************************************************************************** * This is a simple dynamic memory allocation module. The following are the * supported services: * * BYTE * NEAR SRAMalloc(NEAR BYTE nBytes) * void SRAMfree(BYTE * NEAR pSRAM) * void SRAMInitHeap(void) * * This version of the dynamic memory allocation limits the segment size * to 126 bytes. This is specifically designed such to enable better * performance by limiting pointer manipulation. * * * How it works: * The model is based on a simple form of a linked list. A block of memory * refered to as the dynamic heap is split into segments. Each segment * has a single byte header that references the next segment in the list * as well as indicating whether the segment is allocated. Consiquently * the reference implicitly identifies the length of the segment. * * This method also enables the possibility of allowing a large number * of memory allocations. The maximum is limited by the defined heap size. * * SRAMalloc() is used to split or merge segments to be allocated. * SRAMfree() is used to release segments. * * Example: * ---------- * | 0x7F | 0x200 Header Seg1 * | | * | | * | | * | | * | | * | | * | 0x89 | 0x27F Header Seg2 (allocated) * | | * | | * | 0x77 | 0x288 Header Seg3 * | | * | | * | | * | | * | | * | | * | | * | 0x00 | 0x2FF Tail * ---------- * * * Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 * * Alloc ------------- reference to next Header -------------- *****************************************************************************/ #ifndef _SRAM_H #define _SRAM_H #include "common.h" /********************************************************************* * Segment header data type ********************************************************************/ typedef union _SALLOC { WORD byte; //由于PIC24F单片机是16位的,RAM也是16位的,故内存分区用16位代替 struct _BITS { WORD count:7; //是内存块的大小,包含管理信息 WORD alloc:1; //表明该内存块是否已经分配 WORD :8; }bits; }SALLOC; /********************************************************************* * Function: BYTE * SRAMalloc(BYTE length) * * PreCondition: A memory block must be allocated in the linker, * and the memory headers and tail must already be * set via the function SRAMInitHeap(). * * Input: BYTE nBytes - Number of bytes to allocate. * * Output: BYTE * - A pointer to the requested block * of memory. * * Side Effects: * * Overview: This functions allocates a chunk of memory from * the heap. The maximum segment size for this * version is 126 bytes. If the heap does not have * an available segment of sufficient size it will * attempt to create a segment; otherwise a NULL * pointer is returned. If allocation is succeessful * then a pointer to the requested block is returned. * * Note: The calling function must maintain the pointer * to correctly free memory at runtime. ********************************************************************/ void *SRAMalloc(BYTE nSize); /********************************************************************* * Function: void SRAMfree(WORD * pSRAM) * * PreCondition: The pointer must have been returned from a * previously allocation via SRAMalloc(). * * Input: WORD * pSRAM - pointer to the allocated * * Output: void * * Side Effects: * * Overview: This function de-allocates a previously allocated * segment of memory. * * Note: The pointer must be a valid pointer returned from * SRAMalloc(); otherwise, the segment may not be * successfully de-allocated, and the heap may be * corrupted. ********************************************************************/ void SRAMfree(void * pSRAM); /********************************************************************* * Function: void SRAMInitHeap(void) * * PreCondition: * * Input: void * * Output: void * * Side Effects: * * Overview: This function initializes the dynamic heap. It * inserts segment headers to maximize segment space. * * Note: This function must be called at least one time. * And it could be called more times to reset the * heap. ********************************************************************/ void SRAMInitHeap(void); BOOL SRAMmerge(SALLOC *pSegA); #endif
5385fef5d0c5a76d90662c9e6b225a85cb04f6fd
[ "C" ]
44
C
dzlyxzy/Mao_door
b5cd1d0697a94bf22ac1eeb9bd4d2b7773364d9b
8decf391eb2742d8420369fa72ec9c4dd1e39b8d
refs/heads/master
<repo_name>dima74/mipt-meta-programming<file_sep>/tasks/1_20180926/base.h #ifndef META_PROGRAMMING_BASE_H #define META_PROGRAMMING_BASE_H enum class ComplexClassType { PROXY, MEDIATOR, OBSERVER, }; template<ComplexClassType classType> class ComplexClass; #endif <file_sep>/bonuses/1_10102018/README.md Бонусные задания с семинара 10.10.2018: * Изменить код семинарского TypeList так, чтобы Length<EmptyList> = 0 * Реализовать метод удаления типа из TypeList Компилировал clang++ версии 7.0.0: clang++ -std=c++17 main.cpp<file_sep>/bonuses/2_20181024/hierarchy_scatter_recursive.h #ifndef META_PROGRAMMING_HIERARCHY_SCATTER_H #define META_PROGRAMMING_HIERARCHY_SCATTER_H #include "../1_10102018/type_list.h" template<typename TypeList, template<typename AtomicType> typename Unit> struct GenScatterHierarchy; template<typename T1, typename ... T2, template<typename> typename Unit> struct GenScatterHierarchy<TypeList<T1, T2...>, Unit> : public Unit<T1>, public GenScatterHierarchy<TypeList<T2...>, Unit> { }; template<template<typename> typename Unit> struct GenScatterHierarchy<TypeList<>, Unit> {}; #endif <file_sep>/seminars/20180912/Singleton/SingletonMy.cpp #include <iostream> class Singleton { private: static Singleton *instance; Singleton() = default; public: Singleton(Singleton &) = delete; Singleton(Singleton &&) = delete; static Singleton &getInstance() { return *instance; } void printMessage() { std::cout << "hello" << std::endl; } }; Singleton *Singleton::instance = new Singleton(); int main() { Singleton &instance = Singleton::getInstance(); instance.printMessage(); return 0; }<file_sep>/tasks/1_20180926/observer.h #ifndef META_PROGRAMMING_OBSERVER_H #define META_PROGRAMMING_OBSERVER_H #include "base.h" #include <vector> using std::vector; struct ISubscriber { virtual void update() = 0; virtual ~ISubscriber() {} }; struct ExampleSubscriber : public ISubscriber { void update() { // handle update } }; template<> class ComplexClass<ComplexClassType::OBSERVER> { private: vector<ISubscriber *> subscribers; int state = 0; void notifySubscribers() { for (ISubscriber *subscriber : subscribers) { subscriber->update(); } } public: ComplexClass(ISubscriber *subscriber1, ISubscriber *subscriber2) : subscribers({subscriber1, subscriber2}) {} void changeState() { ++state; notifySubscribers(); } }; #endif <file_sep>/bonuses/3_20181107/abstract_factory.h #ifndef META_PROGRAMMING_ABSTRACT_FACTORY_H #define META_PROGRAMMING_ABSTRACT_FACTORY_H #include "../2_20181024/hierarchy_scatter.h" #include "./hierarchy_linear.h" #include "./allocator.h" // интерфейс template<typename T> struct TypeDescriptor {}; template<typename T> struct IAbstractFactoryUnit { virtual T *create(TypeDescriptor<T>) = 0; virtual ~IAbstractFactoryUnit() {} }; template<typename TypeList> struct IAbstractFactory : GenScatterHierarchy<TypeList, IAbstractFactoryUnit> { template<typename T> T *create() { return static_cast<IAbstractFactoryUnit<T> *>(this)->create(TypeDescriptor<T>()); } }; // реализация template< template<typename T, template<typename> typename Allocator> typename FactoryUnit, template<typename> typename Allocator, typename T, typename Base > struct FactoryUnitWrapper : FactoryUnit<T, Allocator>, Base { virtual T *create(TypeDescriptor<T>) { return FactoryUnit<T, Allocator>::create(allocator); } private: Allocator<T> allocator; }; template< template<typename T, template<typename> typename Allocator> typename FactoryUnit, template<typename> typename Allocator > struct GetFactoryUnitWrapper { template<typename T, typename Base> using FactoryUnitWrapperAlias = FactoryUnitWrapper<FactoryUnit, Allocator, T, Base>; }; template< typename TypeList, template<typename, template<typename> typename> typename FactoryUnit, template<typename> typename Allocator > using CAbstractFactory = GenLinearHierarchy< TypeList, GetFactoryUnitWrapper<FactoryUnit, Allocator>::template FactoryUnitWrapperAlias, IAbstractFactory<TypeList> >; #endif <file_sep>/tasks/3/main.cpp #include "../../bonuses/base.h" #include "../../bonuses/1_10102018/type_list.h" #include "../../bonuses/1_10102018/length.h" #include <iostream> #include <fstream> #include <vector> #include <cstring> #include <sstream> #include <iomanip> #include <cassert> using namespace std; struct NoneType {}; // очень грустно что нет constexpr тернарного оператора, либо частичной специализации для шаблонной функции template<typename T1, typename T2, typename TypeInFile> T1 decompressStage1(TypeInFile &valueFromFile) { if constexpr (is_same_v<T2, NoneType>) { static_assert(is_same_v<TypeInFile, T1>); return valueFromFile; } else { static_assert(is_same_v<TypeInFile, T2>); return valueFromFile.decompress(); } } template<typename T1, typename T2> static void readOneValue(istream &input, vector<byte> &data, void (*decompressFunction)(T1 &)) { constexpr bool hasT2 = !is_same_v<T2, NoneType>; using TypeInFile = conditional_t<hasT2, T2, T1>; TypeInFile valueFromFile; input >> valueFromFile; if (!input) throw runtime_error(string("Error while reading type: ") + getTypeName<TypeInFile>()); T1 valueAfterStage1 = decompressStage1<T1, T2, TypeInFile>(valueFromFile); if (decompressFunction != nullptr) { decompressFunction(valueAfterStage1); } data.resize(data.size() + sizeof(T1)); memcpy(&data[data.size() - sizeof(T1)], &valueAfterStage1, sizeof(T1)); } template<size_t i, typename TypeList1, typename TypeList2> struct ReaderForOneType; template<size_t i, typename ...Types1, typename ...Types2> struct ReaderForOneType<i, TypeList<Types1...>, TypeList<Types2...>> { static void read(istream &input, vector<byte> &data, const vector<void *> &decompressFunctionPointers) { // https://stackoverflow.com/a/15953673/5812238 using T1 = tuple_element_t<i, tuple<Types1...>>; using T2 = tuple_element_t<i, tuple<Types2...>>; void (*decompressFunction)(T1 &) = (void (*)(T1 &)) decompressFunctionPointers[i]; readOneValue<T1, T2>(input, data, decompressFunction); } }; template<typename TypeList1, typename TypeList2, size_t ...I> void readNextLineImpl(istream &input, vector<byte> &data, const vector<void *> &decompressFunctionPointers, index_sequence<I...>) { (ReaderForOneType<I, TypeList1, TypeList2>::read(input, data, decompressFunctionPointers), ...); } template<typename TypeList1, typename ... FunctionsExceptFirst> void addFunctionPointersToVector(vector<void *> &decompressFunctionPointers, void (*function)(typename TypeList1::head &), FunctionsExceptFirst... functionsExceptFirst) { decompressFunctionPointers.push_back((void *) function); if constexpr (sizeof...(FunctionsExceptFirst) > 0) { addFunctionPointersToVector<typename TypeList1::tail>(decompressFunctionPointers, functionsExceptFirst...); } } template<typename TypeList1, typename TypeList2> class Reader { private: ifstream input{"input.txt"}; // список указателей на функции vector<void *> decompressFunctionPointers; public: template<typename ... Functions> Reader(Functions... functions) { static_assert(Length<TypeList1>::value == Length<TypeList2>::value, "Lengths of TypeList1 and TypeList2 must match"); static_assert(sizeof...(functions) == Length<TypeList1>::value, "number of Reader constructor arguments should match length of TypeList1"); addFunctionPointersToVector<TypeList1>(decompressFunctionPointers, functions...); } void *readNextLine() { string line; getline(input, line); if (!input) throw runtime_error("End of file or IO error"); vector<byte> data; istringstream input_stream(line); readNextLineImpl<TypeList1, TypeList2>(input_stream, data, decompressFunctionPointers, make_index_sequence<Length<TypeList1>::value>()); byte *result = (byte *) operator new(data.size()); copy(data.begin(), data.end(), result); return result; } }; // тип элемента после распаковки struct T1 { int x; int y; }; // сжатый тип T1 (предполагается, что строка s состоит из цифр и всегда имеет длину 2, первая цифра --- x, вторая цифра --- y) struct T2 { string s; T1 decompress() { assert(s.length() == 2); return {s[0] - '0', s[1] - '0'}; } }; istream &operator>>(istream &in, T1 &value) { return in >> value.x >> value.y; } istream &operator>>(istream &in, T2 &value) { return in >> value.s; } void T1Decompress(T1 &value) { value.x += 16; value.y += 16; } int main() { Reader< TypeList<int,/* */ char,/* */ T1,/* */ T1,/* */ T1,/* */ T1>, TypeList<NoneType,/**/ NoneType,/**/ NoneType,/**/ NoneType,/**/ T2,/* */ T2> > reader(/* */nullptr,/* */ nullptr,/* */ nullptr,/* */ T1Decompress, nullptr, T1Decompress); vector<size_t> sizes = {sizeof(int), sizeof(char), sizeof(T1), sizeof(T1), sizeof(T1), sizeof(T1)}; for (int line = 0; line < 2; ++line) { byte *data = (byte *) reader.readNextLine(); for (size_t size : sizes) { for (int i = 0; i < size; ++i) { cout << setw(2) << hex << (int) data[i] << " "; } data += size; cout << " "; } cout << endl; } return 0; }<file_sep>/tasks/1_20180926/proxy.h #ifndef META_PROGRAMMING_PROXY_H #define META_PROGRAMMING_PROXY_H #include "base.h" #include <string> using std::string; struct IDataBase { virtual int getData() = 0; virtual void setData(int data) = 0; virtual ~IDataBase() {} }; class DataBase : public IDataBase { private: int data = -1; public: int getData() { return data; } void setData(int data) { this->data = data; } }; template<> class ComplexClass<ComplexClassType::PROXY> : public IDataBase { private: IDataBase *database = nullptr; void log(string message) { // log message } public: ComplexClass(IDataBase *database) : database(database) {} int getData() { log("getData"); return database->getData(); } void setData(int data) { log("setData"); database->setData(data); } }; #endif <file_sep>/bonuses/1_10102018/erase.h #ifndef META_PROGRAMMING_ERASE_H #define META_PROGRAMMING_ERASE_H #include "type_list.h" #include "append_front.h" template<typename List, typename R> struct EraseImpl; // удаление типа, не совпадающего с первым элементом списка template<typename First, typename ... Rest, typename Deleted> struct EraseImpl<TypeList<First, Rest...>, Deleted> { private: using ResultWithoutFirst = typename EraseImpl<TypeList<Rest...>, Deleted>::Result; public: using Result = typename AppendFront<First, ResultWithoutFirst>::result; }; // удаление типа из пустого списка template<typename T> struct EraseImpl<NullType, T> { using Result = NullType; }; template<typename T> struct EraseImpl<EmptyList, T> { using Result = NullType; }; // удаление типа, совпадающего с первым элементом списка template<typename T, typename ... U> struct EraseImpl<TypeList<T, U...>, T> { using Result = TypeList<U...>; }; template<typename List, typename T> struct Erase { private: using TypeListNormalized = typename Normalized<List>::type; using ResultInternal = typename EraseImpl<TypeListNormalized, T>::Result; public: using Result = typename Denormalized<ResultInternal>::type; }; #endif <file_sep>/bonuses/3_20181107/hierarchy_linear.h #ifndef META_PROGRAMMING_HIERARCHY_LINEAR_H #define META_PROGRAMMING_HIERARCHY_LINEAR_H #include "../1_10102018/type_list.h" template<typename TypeList, template<typename AtomicType, typename BaseType> typename Unit, typename Root = NullType> struct GenLinearHierarchy; template<typename T1, typename ... T2, template<typename AtomicType, typename BaseType> typename Unit, typename Root> struct GenLinearHierarchy<TypeList<T1, T2...>, Unit, Root> : public Unit<T1, GenLinearHierarchy<TypeList<T2...>, Unit, Root>> { }; template<typename T, template<typename, typename> typename Unit, typename Root> struct GenLinearHierarchy<TypeList<T>, Unit, Root> : public Unit<T, Root> {}; #endif <file_sep>/bonuses/3_20181107/allocator.h #ifndef META_PROGRAMMING_ALLOCATOR_H #define META_PROGRAMMING_ALLOCATOR_H template<typename T> struct IAllocator { virtual T *allocate() = 0; virtual ~IAllocator() {} }; template<typename T> struct AllocatorUsingNew : public IAllocator<T> { virtual T *allocate() { return new T(); } }; #endif <file_sep>/seminars/20180919/Compound/Compound.cpp #include <iostream> #include <vector> using namespace std; struct Entity { virtual int getTotalPrice() = 0; virtual ~Entity() = default; }; struct Item : public Entity { int price; explicit Item(int price) : price(price) {} int getTotalPrice() override { return price; } }; struct Package : public Entity { vector<Entity *> entities; Package(const initializer_list<Entity *> &entities) : entities(entities) {} int getTotalPrice() override { int totalPrice = 0; for (Entity *entity : entities) { totalPrice += entity->getTotalPrice(); } return totalPrice; } }; int main() { Item *item1 = new Item(1); Item *item2 = new Item(2); Item *item3 = new Item(3); Package *package1 = new Package({item1, item2}); Package *package2 = new Package({package1, item3}); cout << package1->getTotalPrice() << endl; cout << package2->getTotalPrice() << endl; return 0; }<file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 3.12) project(meta_programming) set(CMAKE_CXX_COMPILER /usr/bin/clang++) set(CMAKE_CXX_STANDARD 17) #add_executable(seminars_20180912_singleton seminars/20180912/Singleton/SingletonMayer.cpp) #add_executable(seminars_20180912_compound seminars/20180919/Compound/Compound.cpp) #add_executable(seminars_20180912_flyweight seminars/20180919/Flyweight/Flyweight.cpp) add_executable(bonus1 bonuses/1_10102018/main.cpp) add_executable(bonus2 bonuses/2_20181024/main.cpp) add_executable(bonus3 bonuses/3_20181107/main.cpp) add_executable(task1 tasks/1_20180926/main.cpp) add_executable(task2 tasks/2_20181128/main.cpp) add_executable(task3 tasks/3/main.cpp) add_executable(temp temp/main.cpp)<file_sep>/bonuses/base.h #ifndef META_PROGRAMMING_BASE_H #define META_PROGRAMMING_BASE_H #include <iostream> #include <cstring> using std::cout; using std::endl; using std::string; using std::strlen; template<typename T> void printType() { cout << "\n" << __PRETTY_FUNCTION__ << endl; } template<typename T> string getTypeName() { // something like "std::__cxx11::string getTypeName() [T = int]" string function_signature = __PRETTY_FUNCTION__; size_t i = function_signature.find("getTypeName"); return string(function_signature.begin() + i + strlen("getTypeName() [T = "), function_signature.end() - 1); } // type detector (works by generating error in compile-time) template<typename T> class TD; #endif <file_sep>/tasks/1_20180926/README.md # Задание 1. > Нужно написать шаблонный класс, который в зависимости от переданного параметра будет выполнять роль либо прокси, либо медиатора, либо наблюдателя для двух других классов. Компилировал clang++ версии 7.0.0: clang++ -std=c++17 main.cpp<file_sep>/tasks/2_20181128/main.cpp #include "../../bonuses/1_10102018/type_list.h" #include "../../bonuses/base.h" #include "./hierarchy_complex.h" // stub type template<int> struct T; template<typename T, typename Base> struct Unit : Base { T *create() { return new T(); } }; using Example0 = GenComplexHierarchy<TypeList<>, Unit>; using Example1 = GenComplexHierarchy<TypeList<T<1>>, Unit>; using Example2 = GenComplexHierarchy<TypeList<T<1>, T<2>>, Unit>; using Example3 = GenComplexHierarchy<TypeList<T<1>, T<2>, T<3>>, Unit>; using Example4 = GenComplexHierarchy<TypeList<T<1>, T<2>, T<3>, T<4>>, Unit>; using Example5 = GenComplexHierarchy<TypeList<T<1>, T<2>, T<3>, T<4>, T<5>>, Unit>; using Example6 = GenComplexHierarchy<TypeList<T<1>, T<2>, T<3>, T<4>, T<5>, T<6>>, Unit>; using Example7 = GenComplexHierarchy<TypeList<T<1>, T<2>, T<3>, T<4>, T<5>, T<6>, T<7>>, Unit>; int main() { Example0 example0; Example1 example1; Example2 example2; Example3 example3; Example4 example4; Example5 example5; Example6 example6; Example7 example7; return 0; }<file_sep>/seminars/20180912/AbstractFactory/AbstractFactory.cpp #include <iostream> using namespace std; struct Unit { virtual void attack() = 0; virtual ~Unit() {} }; struct Soldier : public Unit { int power; Soldier(int power) : power(power) {} void attack() { cout << "solder attack, power = " << power << endl; } }; struct Archer : public Unit { int range; Archer(int range) : range(range) {} void attack() { cout << "archer attack, range = " << range << endl; } }; struct AbstractFactory { virtual Soldier createSoldier() = 0; virtual Archer createArcher() = 0; }; struct EasyFactory : public AbstractFactory { Soldier createSoldier() { return Soldier(10); } Archer createArcher() { return Archer(10); } }; struct DifficultFactory : public AbstractFactory { Soldier createSoldier() { return Soldier(100); } Archer createArcher() { return Archer(100); } }; struct Game { AbstractFactory *factory; Game(string difficulty) { if (difficulty == "easy") { factory = new EasyFactory(); } else { factory = new DifficultFactory(); } } void createUnitsAndAttack() { Soldier soldier = factory->createSoldier(); Archer archer = factory->createArcher(); soldier.attack(); archer.attack(); } }; int main() { Game gameEasy("easy"); gameEasy.createUnitsAndAttack(); Game gameDifficult("difficult"); gameDifficult.createUnitsAndAttack(); return 0; }<file_sep>/bonuses/3_20181107/main.cpp #include "./abstract_factory.h" #include "../base.h" struct Infantry {}; struct Archer {}; struct Cavalry {}; using UnitsList = TypeList<Infantry, Archer, Cavalry>; template<typename T, template<typename> typename Allocator> struct FactoryUnit { T *create(Allocator<T> &allocator) { return allocator.allocate(); } }; using IArmyFactory = IAbstractFactory<UnitsList>; using CArmyFactory = CAbstractFactory<UnitsList, FactoryUnit, AllocatorUsingNew>; int main() { IArmyFactory *factory = new CArmyFactory(); Archer *archer = factory->create<Archer>(); Cavalry *cavalry = factory->create<Cavalry>(); return 0; }<file_sep>/seminars/20180912/Singleton/SingletonMayer.cpp #include <iostream> using namespace std; class Singleton { private: Singleton() = default; public: Singleton(Singleton &) = delete; Singleton(Singleton &&) = delete; static Singleton &getInstance() { static Singleton instance; return instance; } void printMessage() { cout << "hello" << endl; } }; int main() { Singleton &instance = Singleton::getInstance(); instance.printMessage(); return 0; }<file_sep>/tasks/1_20180926/main.cpp #include "base.h" #include "proxy.h" #include "mediator.h" #include "observer.h" void exampleProxyUsage() { DataBase *databaseOriginal = new DataBase(); IDataBase *database = new ComplexClass<ComplexClassType::PROXY>(databaseOriginal); database->setData(7); int data = database->getData(); } void exampleMediatorUsage() { IButtonComponent *buttonComponent = new ButtonComponent(); IDialogComponent *dialogComponent = new DialogComponent(); IMediator *mediator = new ComplexClass<ComplexClassType::MEDIATOR>(buttonComponent, dialogComponent); buttonComponent->click(); } void exampleObserverUsage() { ISubscriber *subscriber1 = new ExampleSubscriber(); ISubscriber *subscriber2 = new ExampleSubscriber(); auto *observer = new ComplexClass<ComplexClassType::OBSERVER>(subscriber1, subscriber2); observer->changeState(); } int main() { exampleProxyUsage(); exampleMediatorUsage(); exampleObserverUsage(); } <file_sep>/seminars/20180919/Flyweight/Flyweight.cpp #include <bits/stdc++.h> using namespace std; struct UnitType { string name; int attack; UnitType(string name, int attack) : name(std::move(name)), attack(attack) {} }; struct Unit { UnitType *type; explicit Unit(UnitType *type) : type(type) {} void attack() { cout << type->name << " attack: " << type->attack << endl; } }; int main() { UnitType soldierType("soldier", 7); Unit soldier(&soldierType); soldier.attack(); }<file_sep>/bonuses/2_20181024/main.cpp #include "hierarchy_scatter.h" #include <string> #include <cassert> using std::string; template<typename T> struct Holder { T value; }; struct Value { int x; int y; }; using Hierarchy = GenScatterHierarchy<TypeList<int, string, Value>, Holder>; template<typename T, typename Hierarchy> T get_value(Hierarchy hierarchy) { return (static_cast<Holder<T> &>(hierarchy)).value; } int main() { Hierarchy hierarchy; (static_cast<Holder<int> &>(hierarchy)).value = 7; assert(get_value<int>(hierarchy) == 7); (static_cast<Holder<int> &>(hierarchy)).value = 77; assert(get_value<int>(hierarchy) == 77); (static_cast<Holder<string> &>(hierarchy)).value = "foo"; assert(get_value<string>(hierarchy) == "foo"); (static_cast<Holder<string> &>(hierarchy)).value = "bar"; assert(get_value<string>(hierarchy) == "bar"); (static_cast<Holder<Value> &>(hierarchy)).value = {3, 4}; assert(get_value<Value>(hierarchy).x == 3); assert(get_value<Value>(hierarchy).y == 4); return 0; }<file_sep>/tasks/2_20181128/fibonacci.h #ifndef META_PROGRAMMING_FIBONACCI_H #define META_PROGRAMMING_FIBONACCI_H template<int n> struct Fibonacci { static constexpr int result = Fibonacci<n - 1>::result + Fibonacci<n - 2>::result; }; template<> struct Fibonacci<0> { static constexpr int result = 1; }; template<> struct Fibonacci<1> { static constexpr int result = 1; }; #endif <file_sep>/bonuses/2_20181024/hierarchy_scatter.h #ifndef META_PROGRAMMING_HIERARCHY_SCATTER_H #define META_PROGRAMMING_HIERARCHY_SCATTER_H #include "../1_10102018/type_list.h" template<typename TypeList, template<typename AtomicType> typename Unit> struct GenScatterHierarchy; template<typename ... Types, template<typename> typename Unit> struct GenScatterHierarchy<TypeList<Types...>, Unit> : public Unit<Types> ... {}; #endif <file_sep>/bonuses/1_10102018/main.cpp #include <type_traits> #include <cassert> #include "length.h" #include "erase.h" using std::is_same; void testLength() { static_assert(0 == Length<EmptyList>::value); static_assert(1 == Length<TypeList<int>>::value); static_assert(2 == Length<TypeList<int, int>>::value); static_assert(3 == Length<TypeList<int, int, int>>::value); } void testErase() { // length = 1 using Int = TypeList<int>; using Char = TypeList<char>; // length = 2 using IntInt = TypeList<int, int>; using IntChar = TypeList<int, char>; using CharInt = TypeList<char, int>; using CharChar = TypeList<char, char>; // length = 3 using IntIntChar = TypeList<int, int, char>; using IntBoolChar = TypeList<int, bool, char>; // length = 0 static_assert(is_same<Erase<EmptyList, int>::Result, EmptyList>::value); // length = 1 static_assert(is_same<Erase<Int, int>::Result, EmptyList>::value); static_assert(is_same<Erase<Int, char>::Result, Int>::value); // length = 2 static_assert(is_same<Erase<IntInt, int>::Result, Int>::value); static_assert(is_same<Erase<IntChar, int>::Result, Char>::value); static_assert(is_same<Erase<CharInt, int>::Result, Char>::value); static_assert(is_same<Erase<CharChar, int>::Result, CharChar>::value); // length = 3 static_assert(is_same<Erase<IntIntChar, int>::Result, IntChar>::value); static_assert(is_same<Erase<IntIntChar, char>::Result, IntInt>::value); static_assert(is_same<Erase<IntBoolChar, int>::Result, TypeList<bool, char>>::value); static_assert(is_same<Erase<IntBoolChar, bool>::Result, IntChar>::value); static_assert(is_same<Erase<IntBoolChar, char>::Result, TypeList<int, bool>>::value); } int main() { testLength(); testErase(); return 0; }<file_sep>/tasks/1_20180926/mediator.h #ifndef META_PROGRAMMING_MEDIATOR_H #define META_PROGRAMMING_MEDIATOR_H #include "base.h" enum class EventType { BUTTON_CLICK, }; // definition 0 struct IMediator { virtual void notify(EventType eventType) = 0; virtual ~IMediator() {} }; class IComponent { private: void attachToMediator(IMediator *mediator) { this->mediator = mediator; } friend ComplexClass<ComplexClassType::MEDIATOR>; protected: IMediator *mediator; public: virtual ~IComponent() {} }; struct IButtonComponent : public IComponent { virtual void click() = 0; virtual ~IButtonComponent() {} }; struct IDialogComponent : public IComponent { virtual void show() = 0; virtual ~IDialogComponent() {} }; // definition 1 class ButtonComponent : public IButtonComponent { public: void click() { this->mediator->notify(EventType::BUTTON_CLICK); } }; class DialogComponent : public IDialogComponent { public: void show() { // код показывающий диалог } }; template<> class ComplexClass<ComplexClassType::MEDIATOR> : public IMediator { private: IButtonComponent *showDialogButton; IDialogComponent *dialogComponent; public: ComplexClass(IButtonComponent *showDialogButton, IDialogComponent *dialogComponent) : showDialogButton(showDialogButton), dialogComponent(dialogComponent) { showDialogButton->attachToMediator(this); dialogComponent->attachToMediator(this); } void notify(EventType eventType) { if (eventType == EventType::BUTTON_CLICK) { dialogComponent->show(); } } }; #endif <file_sep>/bonuses/1_10102018/length.h #ifndef META_PROGRAMMING_LENGTH_H #define META_PROGRAMMING_LENGTH_H #include "type_list.h" template<typename List> struct Length { static constexpr int value = Length<typename List::tail>::value + 1; }; template<> struct Length<NullType> { static constexpr int value = 0; }; template<> struct Length<EmptyList> { static constexpr int value = 0; }; #endif <file_sep>/bonuses/1_10102018/append_front.h #ifndef META_PROGRAMMING_APPEND_FRONT_H #define META_PROGRAMMING_APPEND_FRONT_H #include "type_list.h" template<typename T, typename List> struct AppendFront; template<typename T, typename ... U> struct AppendFront<T, TypeList<U...>> { using result = TypeList<T, U...>; }; template<typename T> struct AppendFront<T, NullType> { using result = TypeList<T>; }; #endif <file_sep>/bonuses/1_10102018/type_list.h #ifndef META_PROGRAMMING_TYPE_LIST_H #define META_PROGRAMMING_TYPE_LIST_H struct NullType {}; template<typename ... Types> struct TypeList; template<typename First, typename ... Rest> struct TypeList<First, Rest...> { using head = First; using tail = TypeList<Rest...>; }; template<typename T> struct TypeList<T> { using head = T; using tail = NullType; }; template<> struct TypeList<> { using head = NullType; using tail = NullType; }; using EmptyList = TypeList<>; // у нас есть проблема, что EmptyList это TypeList { head = tail = NullType }, хотя было гораздо лучше, если EmptyList был бы NullType // поэтому нужна данная функция template<typename List> struct Normalized { using type = List; }; template<> struct Normalized<EmptyList> { using type = NullType; }; template<typename List> struct Denormalized { using type = List; }; template<> struct Denormalized<NullType> { using type = EmptyList; }; #endif <file_sep>/tasks/2_20181128/hierarchy_complex.h #ifndef META_PROGRAMMING_HIERARCHY_COMPLEX_H #define META_PROGRAMMING_HIERARCHY_COMPLEX_H #include "../../bonuses/3_20181107/hierarchy_linear.h" #include "../../bonuses/1_10102018/append_front.h" #include "./fibonacci.h" #include <cstddef> #include <variant> using std::enable_if_t; using std::is_same_v; template<typename List, size_t n, typename EnableFlag = void> struct Split { // part0 --- первые n типов из List (меньше если Length<List> < n) using part0 = typename AppendFront< typename List::head, typename Split<typename List::tail, n - 1>::part0 >::result; // part1 --- все остальные типы из List using part1 = typename Denormalized<typename Split<List, n - 1>::part1::tail>::type; }; template<typename List> struct Split<List, 0, enable_if_t<!is_same_v<List, NullType>>> { using part0 = TypeList<>; using part1 = List; }; template<size_t n> struct Split<NullType, n> { using part0 = TypeList<>; using part1 = TypeList<>; }; template<typename TypeList, template<typename, typename> typename Unit, int i> struct GenComplexHierarchyImpl : GenLinearHierarchy<typename Split<TypeList, Fibonacci<i>::result + 1>::part0, Unit>, GenComplexHierarchyImpl<typename Split<TypeList, Fibonacci<i>::result + 1>::part1, Unit, i + 1> { }; template<template<typename, typename> typename Unit, int i> struct GenComplexHierarchyImpl<TypeList<>, Unit, i> {}; template<typename TypeList, template<typename AtomicType, typename BaseType> typename Unit> using GenComplexHierarchy = GenComplexHierarchyImpl<TypeList, Unit, 0>; #endif <file_sep>/README.md # Правила отправки заданий Все задания присылать семинаристу Почта и тема письма: ``` <EMAIL> Метапрограммирование, задание ? (Д<NAME>) ``` # Задания с лекции ## 1 Два независимых задания, одно дали на лекции, второе на семинаре. Можно сделать любое из двух. ### 1. 26.09.2018 (лекция) Нужно написать шаблонный класс, который в зависимости от переданного параметра будет выполнять роль либо * Proxy * Mediator * Observer Срок выполнения: две недели ### 1. 26.09.2018 (семинар) Написать мини-проект, использовав как минимум по одному паттерну из каждой группы (порождающие, структурные, поведенческие) ## 2 Есть TypeList с классами T0...Tn. Нужно сгенерировать сложную иерархию: * Корневая вершина наследуется от классов T_{k_1} ... T_{k_K} * Вершина T_{k_i} линейно наследуется от классов T_{k_{i+1}}}, ..., T_{k_{i+j-1}} * Где j = i-ое число Фибоначчи Дедлайн: 28.11.2018 # Задания с семинаров (бонусы) ### 1. 10.10.2018 (подробное описание в лекции #5) * Изменить код семинарского `TypeList` так, чтобы `Length<EmptyList> = 0` * Реализовать метод удаления типа из `TypeList` Срок выполнения: две недели ### 2. 24.10.2018 (подробное описание в лекции #6) Написать функцию, которая позволяет получить доступ к члену класса по его типу ### 3. 07.11.2018 (подробное описание в лекции #7) * Сделать удобный вызов метода создания конкретного Unit'а для абстрактной фабрики (интерфейса) * Добавить возможность задавать стратеги выделения памяти для абстрактной фабрики (реализации)
f4f87af75788e67d6cb9c9eff48cc147ec231bca
[ "Markdown", "CMake", "C++" ]
31
C++
dima74/mipt-meta-programming
480fec1afd7698c114fa8b5997d68acd181b810c
4e4740264bd70d439c9be986c509561b3b65dab7
refs/heads/master
<repo_name>OakLabsInc/component-filesync<file_sep>/README.md # Filesync - Google Cloud Storage Syncing [![Dockerhub](https://img.shields.io/static/v1.svg?label=Docker%20Hub&message=latest&color=green)](https://hub.docker.com/r/oaklabs/component-filesync) This service will periodically, atomically sync a Google Cloud Storage directory to this container and server the contents over http. Requirements for use: * `CONTROL_PORT` env var - port that the control gRPC interface listens on. {DEFAULT: 9102} * `DATA_PORT` env var - port that the files are served on {DEFAULT: 9103} * `GS_URL` env var - gs:// url to the Google Cloud Storage directory where the files are downloaded from * `SYNC_DIR` env var - absolute path to the directory in the container the files should be stored it; this should be a persistent volume and will need to have at least 2x the amount of space that the GCS directory uses * `SYNC_PERIOD` env var - how often in seconds syncing should begin; if syncing is ongoing then the period just restarts * GCP service account credentails mounted at `/gcloud-credentials.json` This service can be signaled to wait before downloading by placing an empty file called `WAIT` in the top of the SYNC_DIR: ``` # Turn waiting on gsutil cp /dev/null gs://path/to/sync_dir/WAIT # Turn waiting off gsutil rm gs://path/to/sync_dir/WAIT ``` # Dev Notes The script `tryit.py` can be used to test the control interface. You can use `curl` to view the files. Here's a quick way to test the whole flow: ``` echo 'GS_URL=gs://your/gcs/directory/' > .env pip install grpcio grpcio-tools python -m grpc_tools.protoc -I . --python_out=. --grpc_python_out=. *.proto docker-compose up --build -d python tryit.py localhost:9102 curl http://localhost:9103/ ``` <file_sep>/bin/sync.sh #!/bin/bash GS_URL="$1" WAIT_INTERVAL_SECONDS=10 swap_idle_and_live () { # Moving a symlink is not an atomic operation. # Instead, we do this dance. # See http://blog.moertel.com/posts/2005-08-22-how-to-change-symlinks-atomically.html cp -P live tmp mv -Tf idle live mv -Tf tmp idle } echo "=== Verifying credentials" if ! (gsutil ls "$GS_URL" >/dev/null 2>/dev/null); then echo "Credentials are invalid. Make sure /gcloud-credentials.json is present and grants read access to $GS_URL" exit 1 fi echo "=== Checking for WAIT file" while gsutil -q stat "$GS_URL/WAIT"; do echo "=== $GS_URL/WAIT exists. Waiting until it's gone..." sleep $WAIT_INTERVAL_SECONDS done echo "=== Downloading $GS_URL" gsutil $GSUTIL_OPT -m rsync -d -r "$GS_URL" idle/ echo "=== Download complete, making it live" swap_idle_and_live echo "=== Copying live back to idle" gsutil $GSUTIL_OPT rsync -d -r live/ idle/ <file_sep>/examples/nodejs/docker-compose.yml --- version: '3' volumes: app-persistent-storage: services: server: image: index.docker.io/oaklabs/component-filesync:${VERSION-latest} volumes: - /dev/shm:/dev/shm - app-persistent-storage:/persistent - ./gcloud-credentials.json:/gcloud-credentials.json:ro environment: - CONTROL_PORT=9102 - DATA_PORT=9103 - GS_URL=gs://oak-test/onefile - SYNC_DIR=/persistent/files - SYNC_PERIOD=600 ports: - "9102:9102" - "9103:9103" <file_sep>/filesync/manager.py import logging import os import sh import threading import time OUTPUT_FILE_NAME = 'sync-output.log' log = logging.getLogger('filesync') class Filesync(object): def __init__(self, gs_url, workdir, period): self.gs_url = gs_url self.period = int(period) self.workdir = workdir self.outfile = os.path.join(workdir, OUTPUT_FILE_NAME) self.setup_cmd = sh.Command('bin/setup.sh').bake( _cwd=workdir, ) self.sync_cmd = sh.Command('bin/sync.sh').bake( gs_url, _cwd=workdir, _iter=True, _done=self.proc_done, _err_to_out=True, _no_pipe=True, _bg=True, ) self.lock = threading.RLock() self.runs_complete = 0 self.proc = None self.timer = None self.time_last_start = None self.time_last_done = None self.time_current_start = None self.time_next_start = None def get_state(self): with self.lock: now = time.time() t_next = t_last = t_ldur = t_cdur = None if self.time_next_start: t_next = int(self.time_next_start - now) if self.time_last_done: t_last = int(now - self.time_last_done) if self.time_last_start and self.time_last_done: t_ldur = int(self.time_last_done - self.time_last_start) if self.time_current_start: t_cdur = int(now - self.time_current_start) return { 'runsComplete': self.runs_complete, 'runningNow': self.proc is not None, 'secondsUntilNextStart': t_next, 'secondsSinceLastComplete': t_last, 'secondsLastDuration': t_ldur, 'secondsCurrentDuration': t_cdur, } def begin(self): log.info('Starting Filesync management') if not os.path.exists(self.workdir): log.info('Creating working directory %r', self.workdir) os.makedirs(self.workdir) self.setup_cmd() self.start_process() def wait_until_next_complete(self): current_run = self.runs_complete while self.runs_complete == current_run: time.sleep(0.25) def stream(self): current_run = self.runs_complete while not os.path.exists(self.outfile): time.sleep(0.25) with open(self.outfile, 'r') as f: while True: if self.runs_complete != current_run: break line = f.readline() if line: yield line else: time.sleep(0.25) yield '<END OF STREAM>\n' def start_process(self): log.info('Starting sync of %s', self.gs_url) with self.lock: self.time_current_start = time.time() self.proc = self.sync_cmd() def proc_done(self, _cmd, _success, _exit_code): log.info('Sync complete') with self.lock: self.time_last_done = time.time() self.time_last_start = self.time_current_start self.time_current_start = None self.runs_complete += 1 self.proc = None os.remove(self.outfile) self.start_timer() def start_timer(self): now = time.time() time_to_next_sync = self.period - (now % self.period) log.info('Starting timer for %s seconds', int(time_to_next_sync)) with self.lock: self.timer = threading.Timer(time_to_next_sync, self.timer_done) self.timer.start() self.time_next_start = now + time_to_next_sync def timer_done(self): log.info('Timer done') with self.lock: self.timer = None self.time_next_start = None self.start_process() def abort_process(self): with self.lock: if self.proc is not None: log.info('Aborting sync') self.proc.kill() log.warning( "There may now be a stacktrace for" " SignalException_SIGKILL. This is fine, there's" " just no way easy to hide it. Move along.") def abort_timer(self): with self.lock: if self.timer is not None: log.info('Aborting timer') self.timer.cancel() self.timer = None <file_sep>/bin/setup.sh #!/bin/bash mkdir -p green blue if [ ! -L live ] || [ ! -L idle ]; then ln -snf green live ln -snf blue idle fi <file_sep>/tryit.py import grpc import sys import filesync_pb2 import filesync_pb2_grpc EMPTY = filesync_pb2.Empty() def main(): target = sys.argv[1] channel = grpc.insecure_channel(target) stub = filesync_pb2_grpc.FilesyncStub(channel) print(stub.Info(EMPTY)) for line in stub.Watch(EMPTY): print(line.line) if __name__ == '__main__': main() <file_sep>/scripts/attach #!/bin/bash # attach a bash terminal to the running filesync container for debugging docker exec -i -t filesync_app_1 /bin/bash <file_sep>/filesync/server.py import concurrent.futures import grpc import logging import os import sys import time from manager import Filesync import filesync_pb2 import filesync_pb2_grpc FILES_DIR = os.getenv('SYNC_DIR') GS_URL = os.getenv('GS_URL') PORT = os.getenv('CONTROL_PORT') SYNC_PERIOD = os.getenv('SYNC_PERIOD') EMPTY = filesync_pb2.Empty() def main(): logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) logging.getLogger('sh').setLevel(logging.WARNING) if not (FILES_DIR and GS_URL and PORT and SYNC_PERIOD): print('These ENV vars must be set: FILES_DIR GS_URL PORT SYNC_PERIOD') sys.exit(1) address = '0.0.0.0:10000' server = make_server(address) server.start() print('filesync component serving on 0.0.0.0:%s' % PORT) try: while True: time.sleep(60 * 60 * 24) except KeyboardInterrupt: server.stop(0) def make_server(address): server = grpc.server(concurrent.futures.ThreadPoolExecutor(max_workers=10)) filesync_pb2_grpc.add_FilesyncServicer_to_server( FilesyncServicer(), server) server.add_insecure_port(address) return server class FilesyncServicer(filesync_pb2_grpc.FilesyncServicer): def __init__(self): self.fs = Filesync(GS_URL, FILES_DIR, SYNC_PERIOD) super(filesync_pb2_grpc.FilesyncServicer, self).__init__() self.fs.begin() def Info(self, request, context): return state_to_pb(self.fs.get_state()) def Restart(self, request, context): self.fs.abort_timer() self.fs.abort_process() self.fs.start_process() return state_to_pb(self.fs.get_state()) def Start(self, request, context): if self.fs.proc is None: self.fs.abort_timer() self.fs.start_process() return state_to_pb(self.fs.get_state()) def Abort(self, request, context): if self.fs.proc is not None: self.fs.abort_process() return state_to_pb(self.fs.get_state()) def Wait(self, request, context): self.fs.wait_until_next_complete() return state_to_pb(self.fs.get_state()) def Watch(self, request, context): for line in self.fs.stream(): yield filesync_pb2.Line(line=line.rstrip()) def state_to_pb(state): return filesync_pb2.FilesyncInformation( syncing_now=state['runningNow'], syncs_completed=state['runsComplete'], seconds_since_last_complete=state['secondsSinceLastComplete'], seconds_until_next_start=state['secondsUntilNextStart'], seconds_last_duration=state['secondsLastDuration'], seconds_current_duration=state['secondsCurrentDuration'], ) if __name__ == '__main__': main() <file_sep>/scripts/log #!/bin/bash docker logs filesync_app_1 <file_sep>/filesync/requirements.txt futures==3.0.5 grpcio==1.15.0 gunicorn==19.7.1 protobuf==3.6.1 sh==1.12.13
dade74f7aa5b9f95ae33f1d4942e7a17805d93ee
[ "YAML", "Markdown", "Python", "Text", "Shell" ]
10
Markdown
OakLabsInc/component-filesync
1c39a1904db93bbef26d5d587db9e2a7d2e7a615
75c738050ea2770189342cb140bd37d473fc8692
refs/heads/master
<file_sep>#!/bin/bash #install required packages sudo apt-get install nasm libwxgtk2.8-dev libfuse-dev libgtk2.0-dev ntfs-3g exfat-fuse exfat-utils -y WORKDIR=$(pwd) export PKCS11_INC="$WORKDIR/pkcs/" export WX_ROOT=$WORKDIR/wxWidgets-2.8.12 cd $WORKDIR/truecrypt-7.1a-source time make NOGUI=1 WXSTATIC=1 WX_ROOT=$WORKDIR/wxWidgets-2.8.12 wxbuild time make NOGUI=1 WXSTATIC=1 sudo cp $WORKDIR/truecrypt-7.1a-source/Main/truecrypt $WORKDIR/out sudo cp $WORKDIR/truecrypt-7.1a-source/Main/truecrypt /usr/bin/ sudo chmod a+x /usr/bin/truecrypt
0f59d70007a287b96fb797ada4ea1a869508c7a5
[ "Shell" ]
1
Shell
RickBahague/truecrypt-rpi
d2f83f673f05da666e45f71fdd437c6732fc79a7
0ab05b65372ee19cb6c556e1ae88116234120a73
refs/heads/master
<file_sep>//Written by <NAME> (GeoLiang90) //Defining Constants //Digital pins const int triggPin = 11; const int echoPin = 13; long travelTime; int distance; //Ground is GND and Vcc was connected to 5V void setup() { //changing pinMode pinMode(triggPin, OUTPUT); pinMode(echoPin, INPUT); //Mostly for display board Serial.begin(9600); } void loop() { //Toggle pin with digitalWrite //Low is off digitalWrite(triggPin, LOW); delayMicroseconds(3); //Generate a pulse by setting pin to HIGH digitalWrite(triggPin, HIGH); delayMicroseconds(10); digitalWrite(triggPin, LOW); //pulseIn will wait for a Pin to go high and times how long it takes to go low travelTime = pulseIn(echoPin, HIGH); //Speed of sound wave in microseconds //Sound wave also travels forward and bounces backwards distance = travelTime * 0.034/2; //Print result on serial Serial.print("Distance: "); Serial.print(distance); Serial.println(" cm"); //Test was accurate starting at about 5cm } <file_sep># Arduino Sensor Testing Arduino Leonardo tests will be posted to this repo as more are conducted. # Current Sensor Tests Available * Ultrasonic Sensor (HC-SR04)
cfc782f1b226a3ca404c83146a586d8aa822cc61
[ "Markdown", "C++" ]
2
C++
GeoLiang90/arduino-sensor-testing
265d1df431755c050c5dfc683f20d7d3f0977732
d1d9036e66b71cf7cf2683ab0c3d99c4853fed0b
refs/heads/master
<repo_name>kiseleq/lessons_main<file_sep>/script/hello.js 'use strict'; const money = prompt('Ваш месячный доход?'); const addExpenses = prompt('Перечислите возможные расходы за рассчитываемый период через запятую'); const mission = 6305; let deposit = prompt('Есть ли у вас дпозит в банке?'); switch (deposit) { case 'Да': deposit = true; break; case 'Нет': deposit = false; break; } console.log(typeof deposit); console.log(deposit); const expenses1 = prompt('Введите обязательную статью расходов'); const expenses2 = prompt('Введите обязательную статью расходов'); const amount1 = prompt ('Во сколько это обойдется?'); const amount2 = prompt ('Во сколько это обойдется?'); const budgetMonth = money - amount1 - amount2; console.log('Миссия будет достигнута за ' + Math.ceil(mission / budgetMonth) + ' месяцев'); const income = 'Макдональдс', period = 5, budgetDay = budgetMonth / 30; console.log('Бюджет на день ' + Math.floor(budgetDay)); /*switch (budgetMonth) { case budgetMonth >= 1200: console.log('У вас высокий уровень дохода'); break; case (budgetMonth < 1200 && budgetMonth >= 600): console.log('У вас средний уровень дохода'); break; case (budgetMonth < 600) && (budgetMonth >= 0): console.log('К сожалению, у вас уровень дохода ниже среднего'); break; default: console.log('Что-то пошло не так'); } */ // А так вообще можно использовать switch? В результате всегда выдаёт Что-то пошло не так if (budgetDay >= 1200) { console.log('У вас высокий уровень дохода'); } else if ((budgetDay < 1200) && (budgetDay >= 600)) { console.log('У вас средний уровень дохода'); } else if ((budgetDay < 600) && (budgetDay >= 0)) { console.log('К сожалению, у вас уровень дохода ниже среднего'); } else if (budgetDay < 0) { console.log('Что-то пошло не так'); } console.log(typeof money); console.log(typeof income); console.log(typeof deposit); console.log(income.length); console.log('Период равен ' + period + ' месяцев'); console.log('Цель заработать ' + mission + ' рублей'); console.log(addExpenses.toLowerCase().split(', ')); console.log(budgetDay);
bfceff788f8753c993328f92c34e8acc9ee27f61
[ "JavaScript" ]
1
JavaScript
kiseleq/lessons_main
40cb9ca787a68febf67f12491564414ae81bc753
1de80de1e9d0ffc5ee9503201343415821a1f8a8
refs/heads/main
<file_sep>#!/bin/bash instance=app1 echo "Creating CA key and certs" openssl genrsa -out appserver-ca-root.key openssl req -new -key appserver-ca-root.key -out appserver-ca-root.csr -subj "/CN=app-server-ca-root" openssl x509 -req -in appserver-ca-root.csr -signkey appserver-ca-root.key -out appserver-ca-root.crt openssl x509 -in appserver-ca-root.crt -subject -issuer -dates -noout echo "Creating ${instance} key and cert" openssl genrsa -out ${instance}.key openssl req -new -key ${instance}.key -out ${instance}.csr -subj "/CN=${instance}.local" openssl x509 -req -in ${instance}.csr -CA appserver-ca-root.crt -CAkey appserver-ca-root.key -out ${instance}.crt -CAcreateserial -CAserial serial openssl x509 -in ${instance}.crt -noout -subject -dates -issuer echo "Converting the certs in pem to jks" cat ${instance}.key ${instance}.crt >${instance}.pem openssl pkcs12 -export -out ${instance}.p12 -in ${instance}.pem -password <PASSWORD> keytool -importkeystore -srckeystore ${instance}.p12 -destkeystore ${instance}.jks -destalias ${instance}-alias -srcstoretype pkcs12 -deststorepass <PASSWORD> -srcstorepass <PASSWORD> -srcalias 1 echo "yes" | keytool -importcert -alias ca-cert -file appserver-ca-root.crt -keystore ${instance}.jks -storepass admin123 <file_sep># tomcat-configs This repo contains reference configurations and sample scripts for the following 1. Reference configuration files (production standards) for server.xml , catalina.properties and context.xml 2. Script to create a Tomcat instance 3. Script to create a CA and a certificate signed by the CA, and converted to JKS.<file_sep>#!/bin/bash TC_VERSION=9.0.50 JAVA_VERSION=jdk8u292-b10 INSTALL_DIR=/usr/mware INSTANCE_NAME=app1 INSTANCE_BASE_PATH=/usr/mware/tomcatApps/${INSTANCE_NAME} INSTANCE_APPBASE_PATH=/usr/mware/tomcatAppDetails/${INSTANCE_NAME} CATALINA_HOME=${INSTALL_DIR}/apache-tomcat-${TC_VERSION} wget https://downloads.apache.org/tomcat/tomcat-9/v${TC_VERSION}/bin/apache-tomcat-${TC_VERSION}.tar.gz wget https://github.com/AdoptOpenJDK/openjdk8-binaries/releases/download/jdk8u292-b10/OpenJDK8U-jdk_x64_linux_hotspot_8u292b10.tar.gz mkdir -p $INSTALL_DIR && cd $INSTALL_DIR tar -xzf apache-tomcat-${TC_VERSION}.tar.gz tar -xzf OpenJDK8U-jdk_x64_linux_hotspot_8u292b10.tar.gz ln -s ${INSTALL_DIR}/${JAVA_VERSION} java ${CATALINA_HOME}/bin/makebase.sh $INSTANCE_BASE_PATH cd $INSTANCE_BASE_PATH cp ${CATALINA_HOME}/bin/* $INSTANCE_BASE_PATH/bin/ rm -f ${INSTANCE_BASE_PATH}/bin/*.bat rm -fr ${INSTANCE_BASE_PATH}/lib && ln -s ${CATALINA_HOME}/lib rm -fr ${INSTANCE_BASE_PATH}/webapp mkdir -p $INSTANCE_APPBASE_PATH/lib $INSTANCE_APPBASE_PATH/webapps $INSTANCE_APPBASE_PATH/xmlbase $INSTANCE_APPBASE_PATH/work tee -a ${INSTANCE_BASE_PATH}/bin/setenv.sh << EOF JAVA_HOME=${INSTALL_DIR}/java CATALINA_PID=$INSTANCE_BASE_PATH/logs/${INSTANCE_NAME}.pid CATALINA_OPTS="-Xms128M -Xmx1024M -server" JAVA_OPTS="-Djava.awt.headless=true -Djava.security.egd=file:/dev/./urandom" EOF
a175464ffdca24f21bfa518bf33fe9a8017b6c22
[ "Markdown", "Shell" ]
3
Shell
dennisjacob/tomcat-configs
7b0da2690dd04e26ed9eec7f79f19417146e6bd1
c82b2070d607e68fe29e66f4eb898518cc67b371
refs/heads/main
<repo_name>avevlad/playground<file_sep>/constants/products.ts export interface Product { key: string; title: string; price: number; } export const products: Product[] = [ { key: "Bananas", title: "Bananas, each", price: 0.22, }, { key: "Cilantro", title: "Cilantro, bunch", price: 0.48, }, { key: "RomaTomatoes", title: "Roma Tomatoes, each", price: 0.29, }, { key: "WhiteEggs", title: "Great Value Large White Eggs, 18 Count", price: 1.6, }, ]; <file_sep>/pages/api/products.ts import { products } from "constants/products"; import { NextApiRequest, NextApiResponse } from "next"; export default (_: NextApiRequest, res: NextApiResponse) => { res.status(200).json(products); };
983202ff17f89786ff1a66540b10dbf325da7efb
[ "TypeScript" ]
2
TypeScript
avevlad/playground
abde0996e6e8e120c9213fff46ef9ee9b0fa9b29
97e636f75640de5c098c830da91951bed7cb19a0
refs/heads/main
<repo_name>45ewertton/Aula_Python_Turma2<file_sep>/aula_AE.py ''' Conversões: str, int, float, bool, list, tuple e ... n = str(5) print(type(n)) print(n) ''' ####################################################################### ''' Entrada de dados: input(): nome = input("Diga seu nome: ") print(type(nome)) print("Meu nome é : " + nome) ''' ######################################################################## ''' Estruturas condicionais if, else e elif. numero = 10 if numero > 10: print('Estou dentro do if') print('Estou fora do if') -------------------------------------------------------- idade = 18 if idade >= 18: print(f'Tenho {idade} anos, sou maior de idade.') else: print(f'Tenho {idade} anos, sou menor de idade.') --------------------------------------------------------- idade = -1 if idade < 0: print('Digite um valor válido...') elif idade >= 0 and idade < 16: print('Não pode votar!') elif idade <= 17 or idade > 70: print('Voto não é obrigatório') else: print('Voto obrigatório') ''' ################################################################################ ''' Estruturas de repetições while e for. Possível passar o continue e break i = 1 while i <= 6: print(i) i = i + 1 ------------------------------------------------------------- for i in 'banana': print(i) lista = ['banana', 'maçã', 22, ['melancia', 99.23]] for item in lista: print(item) for i in range (2, 30, 2): print(i) ''' ########################################################################################## ''' Estruturas de dados, lista, pilha e fila. lista = [1, 'Maria', True] print(lista) --------------------------------------------------------------------- pilha = [1, 2] pilha.append(3) pilha.pop() print(pilha) --------------------------------------------------------------------- '''<file_sep>/ex_verificacao.py verificacao = False #Não utilizado neste exemplo, apenas utilizado quando não tem break while True: n1 = input('Informe o primeiro valor: ') if n1.isnumeric(): n2 = input('Informe o segundo valor: ') if n2.isnumeric(): n1 = float(n1) n2 = float(n2) resultado = (n1+n2)/2 break print('Por favor informe um valor numerico...') print(f'A média entre os números {n1} e {n2} é igual a {resultado}!')
cf7399a00f780a9db02a8a2626634d3b29629902
[ "Python" ]
2
Python
45ewertton/Aula_Python_Turma2
5f4ba6f74fb9fd2fccc9f19dd5b503325fdbf66a
c48c75f8e804af16b282b5565661ffadaea20ac5
refs/heads/main
<file_sep># laravel-aliyun-sls ## Using ```shell composer require islenbo/laravel-aliyun-sls ``` add service provider to app.php ```PHP <?php use \Islenbo\LaravelAliyunSls\Providers\LaravelAliyunSlsProvider; return [ // ... 'providers' => [ /* * Package Service Providers... */ LaravelAliyunSlsProvider::class, ], // ... ]; ``` add config to logging.php ```PHP <?php return [ // ... // Aliyun SLS config 'aliyun-sls' => [ 'endpoint' => env('ALIYUN_LOG_ENDPOINT'), 'accessKeyId' => env('ALIYUN_LOG_ACCESSKEYID'), 'accessKey' => env('ALIYUN_LOG_ACCESSKEY'), 'project' => env('ALIYUN_LOG_PROJECT'), 'logstore' => env('ALIYUN_LOG_LOGSTORE'), 'bufferLimit' => env('ALIYUN_LOG_BUFFER_LIMIT', 5), 'formatter' => \Islenbo\LaravelAliyunSls\Formatters\AliyunSlsFormatter::class ], // ... 'channels' => [ 'stack' => [ 'driver' => 'stack', // assign aliyun-sls 'channels' => ['aliyun-sls'], 'ignore_exceptions' => false, 'tap' => [ ] ], // ... ], ]; ``` <file_sep><?php namespace Islenbo\LaravelAliyunSls\Handlers; use Aliyun_Log_Client; use Aliyun_Log_Models_PutLogsRequest; use Monolog\Handler\AbstractHandler; use Monolog\Handler\FormattableHandlerInterface; use Monolog\Handler\FormattableHandlerTrait; use Monolog\Handler\ProcessableHandlerTrait; use Monolog\Logger; class AliyunSlsHandler extends AbstractHandler implements FormattableHandlerInterface { use ProcessableHandlerTrait, FormattableHandlerTrait; /** @var string */ private $project; /** @var string */ private $logstore; /** @var Aliyun_Log_Client */ private $slsClient; private $topic = ''; public function __construct(string $endpoint, string $accessKeyId, string $accessKey, string $project, string $logstore, int $level = Logger::DEBUG, bool $bubble = true) { parent::__construct($level, $bubble); $this->project = $project; $this->logstore = $logstore; $this->slsClient = new Aliyun_Log_Client($endpoint, $accessKeyId, $accessKey); } public function handleBatch(array $records): void { $logItems = []; foreach ($records as $record) { if (!$this->isHandling($record)) { continue; } if ($this->processors) { $record = $this->processRecord($record); } $logItems[] = $this->getFormatter()->format($record); } $this->putLogs($logItems); } public function handle(array $record): bool { $this->handleBatch([$record]); return false === $this->bubble; } private function putLogs(array $logItems): void { $this->slsClient->putLogs( new Aliyun_Log_Models_PutLogsRequest($this->project, $this->logstore, $this->topic, gethostname(), $logItems) ); } } <file_sep><?php namespace Islenbo\LaravelAliyunSls\Formatters; use Aliyun_Log_Models_LogItem; use Illuminate\Support\Arr; use Monolog\DateTimeImmutable; use Monolog\Formatter\FormatterInterface; use Throwable; class AliyunSlsFormatter implements FormatterInterface { public function format(array $record) { /** @var DateTimeImmutable $datetime */ $datetime = $record['datetime']; $uid = Arr::pull($record, 'extra.uid', ''); $result = new Aliyun_Log_Models_LogItem(); $result->setTime($datetime->getTimestamp()); $result->setContents([ 'message' => $record['message'], 'level' => $record['level_name'], 'env' => $record['channel'], 'uid' => $uid, 'context' => $this->convert($record['context']), 'extra' => $this->convert($record['extra']), ]); return $result; } public function formatBatch(array $records) { $result = []; foreach ($records as $record) { $result[] = $this->format($record); } return $result; } private function convert(array $data): string { $result = []; foreach ($data as $k => $v) { if ($v instanceof Throwable) { $result[] = $k . ':'. $this->formatException($v); } else { $result[] = $k . ':' . json_encode($v, JSON_UNESCAPED_UNICODE); } } return implode(PHP_EOL, $result); } private function formatException(Throwable $e): string { return "[{$e->getCode()}] {$e->getMessage()}\n{$e->getFile()}:{$e->getLine()}\n{$e->getTraceAsString()}"; } } <file_sep><?php namespace Islenbo\LaravelAliyunSls; use Illuminate\Log\LogManager; use Monolog\Handler\HandlerInterface; class Manager extends LogManager { public function makeHandler(array $config): HandlerInterface { return $this->prepareHandler( $this->app->make($config['handler'], $config['handler_with']), $config ); } } <file_sep><?php namespace Islenbo\LaravelAliyunSls\Providers; use Illuminate\Config\Repository; use Illuminate\Support\ServiceProvider; use Islenbo\LaravelAliyunSls\Formatters\AliyunSlsFormatter; use Islenbo\LaravelAliyunSls\Handlers\AliyunSlsBufferHandler; use Islenbo\LaravelAliyunSls\Handlers\AliyunSlsHandler; class LaravelAliyunSlsProvider extends ServiceProvider { /** @var Repository */ private $config; public function __construct($app) { parent::__construct($app); $this->config = $this->app->get('config'); } /** * Register services. * * @return void */ public function register() { $this->config->set('logging.channels.aliyun-sls', $this->getChannel()); } /** * Bootstrap services. * * @return void */ public function boot() { } private function getChannel(): array { $slsConfig = $this->config->get('logging.aliyun-sls'); return [ 'driver' => 'monolog', 'handler' => AliyunSlsBufferHandler::class, 'handler_with' => [ 'handlerConfig' => [ 'handler' => AliyunSlsHandler::class, 'handler_with' => [ 'endpoint' => $slsConfig['endpoint'], 'accessKeyId' => $slsConfig['accessKeyId'], 'accessKey' => $slsConfig['accessKey'], 'project' => $slsConfig['project'], 'logstore' => $slsConfig['logstore'], ], ], 'bufferLimit' => $slsConfig['bufferLimit'], ], 'formatter' => class_exists($slsConfig['formatter']) ? $slsConfig['formatter'] : AliyunSlsFormatter::class, ]; } } <file_sep><?php namespace Islenbo\LaravelAliyunSls\Handlers; use Islenbo\LaravelAliyunSls\Manager; use Monolog\Handler\BufferHandler; use Monolog\Handler\HandlerInterface; use Monolog\Logger; class AliyunSlsBufferHandler extends BufferHandler { public function __construct(array $handlerConfig, int $bufferLimit = 0, $level = Logger::DEBUG, bool $bubble = true) { parent::__construct($this->makeHandler($handlerConfig), $bufferLimit, $level, $bubble, true); } private function makeHandler(array $config): HandlerInterface { $manager = new Manager(app()); return $manager->makeHandler($config); } }
4519577f598ebfe0c6aeb52a67915f8c59e9ed56
[ "Markdown", "PHP" ]
6
Markdown
wwc29/laravel-aliyun-sls
dea4d9da97bface97a4151792193426a552f5e4d
4b66cffcf413e638e5ab90ceba09ef6276574319
refs/heads/master
<repo_name>ultimatecoder/ultimatecoder.github.io<file_sep>/_posts/2018-09-29-analyzing-the-behaviour-of-python-function-splice.md --- layout: post title: "Analyzing the behaviour of Python function slice" date: "2018-09-29 10:17:46 +0530" tag: - python - slice - python trick questions --- ![Title Image](/assets/images/python_slice_function/title_image.jpg) Last Friday, I was sitting in one of the good coffee shops in Bangalore with my friend. Coffee and discussion is the best combination to release stress. It was looking like a perfect Friday evening until my friend was struck by an idea of asking me a question. “Let me conduct a quiz.” he said, interrupting our conversation. “A quiz? Quiz on what?”, I asked. “On programming”, he said “What is the level of difficulty then?” I said. Asking the level of difficulty is important. I never invest my efforts in solving something easy. If he had said easy, I would have ignored to answer, but he said “It is a bit difficult, but not that difficult. I gave a wrong answer to this question in my last interview.” There was no reason to go back from here. Taking some deep breaths I said, “Please go ahead.” He stood up, took a tissue paper from a nearby counter and scratched below code on it. [^1] And he asked me by pointing towards that code, “What will be the output of this code?” ```python def my_function(): l = [0, 1, 2] print(l[30:]) my_function() ``` Now it was my turn to give the answer. I looked at the code and tried parsing it in my head --- line by line. In my mind, I observed the first line. It was defining a function which seems to be correct. I moved my eyes to the next line. It was defining a variable `l` of type `list` and assigning values ranging from `0` to `2`. Even this wasn’t looking problematic. So I forwarded to the next line where it was trying to print that variable `l` by slicing it from starting value `30` to the infinity. “Well, the start value is `30` which is greater than the length of the list. This should raise an `IndexError`” I said in my mind. I was about to speak an answer, but suddenly Devil of me flashed. “It is less than [a banana job][4] my dear,” the Devil said to me, “You should take a little advantage of this opportunity my boy.” Because things were looking in my control, I shook my hands with the Devil. I said to my friend, “How about betting for some real values?” Going closer I spoke, “If I answer correctly, You will pay the bill and If I am wrong, This will be a treat from my side.” He thought for a while and nodded. Now it was my turn to unveil the cards. I said in a strong voice, “It will raise an `IndexError`.” And shifted my focus towards the chocolate. He starred my face for a second and spoke, “Okay. Are you sure about this?”. This was the hint he gave. I should have taken another shot here. What happens next become a lesson for me. I said with a flat face, “Yes I am.” With my answer, he instantly opened his backpack, took his Laptop out and typed the code which he wrote on that tissue. When I stopped hearing a sound of typing I yelled, “So did I win?” He turned his laptop towards me and exclaimed, “Not at all!” When I focused on the screen, the interpreter was printing `[]`. Damn! I lost the bet. Why the hell `slice` is returning an empty `list` even when we are trying to slice it with a value which is greater than the length of it! It was surely looking unpythonic behavior. I paid whatever the bill amount was. Entire evening this question was all roaming my mind. After coming home, I decided to justify reasons for returning an empty list instead of raising an `IndexError` from a `slice`. Below are a few reasons justifying such behavior of slice function. I am sharing this with you so that you don’t lose a bet with your friend :) For those who haven’t used slice anytime in their life, I advise to read [this][1] tutorial. Reading [this][2] guide for understanding how a slice function converts the input values. Especially rule number 3 and 4 referenced there. * **Reason number one:** Python lists are more commonly used in iterations. Consider below example: ```python numbers = [0, 1, 2, 3] for number in numbers[30:]: print(number) ``` If `slice` was raising an `IndexError`, then the above code would have to written like this written like like this ```python numbers = [0, 1, 2, 3] try: for number in numbers[30:]: print(numbers) except IndexError: pass ``` Or in another way below is also looking reasonable ```python numbers = [0, 1, 2, 3] start = 30 if start < len(numbers): for number in numbers[start:]: print(number) ``` Both the approaches are looking little lengthy by an obvious reason. And that reason is to prevent executing loop if there are no elements in it. When we observe the behavior of `slice` called at `for in`, it makes sense to return an empty list instead of raising an `IndexError`. I am not able to find further reasons to return an empty list instead of raising the `IndexError`. But I am sure, there will be. If you know any other potential reasons for such behavior of `slice`, please drop me a mail at **jaysinhp** at **gmail** dot **com** or contact me over Twitter [@jaysinhp][3]. I will update the reasons at this post and give credits to you. Thanks for reading this post. ###### Proofreaders: [<NAME>](https://github.com/gsnedders), [Elijah](https://mailto:<EMAIL>), [<NAME>](mailto:<EMAIL>.com), [<NAME>](http://codingquark.com/), [1]: https://docs.python.org/3.7/tutorial/introduction.html#lists [2]: https://docs.python.org/3.7/library/stdtypes.html#sequence-types-list-tuple-range [3]: https://twitter.com/jaysinhp [4]: http://catb.org/jargon/html/O/one-banana-problem.html [^1]: I am using the word "Scratch" because that tissue paper was such a thin that writing by a ballpen torn it. <file_sep>/_posts/2016-12-30-book-review-i-want-2-do-project-tell-me-wat-2-do.md --- layout: post categories: book review title: Book review 'i want 2 do project tell me wat 2 do' tag: books excerpt: Inspirational book for students who are at a fresher level. --- ![i_want_2_do_project_tell_me_wat_2_do]({{ site.url}}/assets/images/book_image_i_want_2_do_project_tell_me_wat_2_do.jpg) ## tl;dr Inspirational book for students who are at a fresher level. ## Detailed review The book is small and you can read it in a day or two. The author has mentioned important points for a newcomer with plenty of quotations. I believe these words are good advice for students. Some guidelines are very realistic. Even I have faced them during my academic years. The book depicts the wise experience of the writer. Your confusions with FOSS will mostly be resolved after reading this book. Following are a few of my observations: * Giving away email access to social networking sites * The importance of sending plain text emails * Not responding to email digest * Time management of project * Avoiding last minute changes in the code * Habit of daily committing the development work * Difference between shallow and fast vs deep and slow learning * Taking project decisions without informing mentors due to overconfidence * Selecting the programming language for your project * Not to fall for market trends * Ways of reporting a bug * Importance of automated build and deployment systems * Diverse types of documentation and their usage * The value of reading and writing and how to amend them * Benefits of going to conferences, hackathons etc. I would like to suggest following improvements to this book. Some references are repeatedly cited, I think they can be referenced commonly without repeating them at the end of chapter. Examples of source code is not written with a different font. It is good to have syntax highlighting for keywords of programming language used. While informing students on mailing list etiquette, it will be good to guide them about mail encryption technologies (GnuPG, etc) too. As a reader, I would have preferred to have one common section of coding related guidelines rather than small section in many chapters. Overall this book deserves “must read” if you are a student or you are an experienced professional who don’t have much exposure to FOSS. The book is “worth reading” even if you are a contributor of any project. It clearly explains the initial steps of FOSS mentorship. The book is an independent piece of work and is not specific to any FOSS project or community. The guidelines given in the book are applicable for any FOSS community or project. I congratulate Shakthi for his inspirational writing. Such efforts are required to inspire upcoming generation. [Buy Amazon.in](http://www.amazon.in/want-project-tell-wat-do/dp/9351741877) ###### Proofreaders: [<NAME>](http://shakthimaan.com/), [<NAME>](http://codingquark.com/) <file_sep>/_posts/2019-01-13-python-3-7-feature-walkthrough.md --- layout: post title: "Python 3.7 feature walkthrough" date: "2019-01-13 01:23:12 +0530" tag: - Python - CorePython - Python3.7 --- In this post, I will explain improvements done in Core Python version 3.7. Below is the outline of features covered in this post. * Breakpoints * Subprocess * Dataclass * Namedtuples * Hash-based Python object file ### breakpoint() Breakpoint is an extremely important tool for debugging. Since I started learning Python, I am using the same API for putting breakpoints. With this release, ```breakpoint()``` is introduced as a built-in function. Because it is in a built-in scope, you don't have to import it from any module. You can call this function to put breakpoints in your code. This approach is handier than importing ```pdb.set_trace()```. ![Breakpoint function in Python 3.7](/assets/images/walkthrough_python_3_7/breakpoint_example.gif) Code used in above example ```python for i in range(100): if i == 10: breakpoint() else: print(i) ``` ### PYTHONBREAKPOINT There wasn't any handy option to disable or enable existing breakpoints with a single flag. But with this release, you can certainly reduce your pain by using ```PYTHONBREAKPOINT``` environment variable. You can disable all breakpoints in your code by setting the environment variable ```PYTHONBREAKPOINT``` to ```0```. ![Breakpoint environment variable in Python 3.7](/assets/images/walkthrough_python_3_7/breakpoint_environment_variable_example.gif) ##### I advise putting "PYTHONBREAKPOINT=0" in your production environment to avoid unwanted pausing at forgotten breakpoints ### Subprocess.run(capture_output=True) You can pipe the output of Standard Output Stream (stdout) and Standard Error Stream (stderr) by enabling ```capture_output``` parameter of ```subprocess.run()``` function. ![subprocess.run got capture_output parameter](/assets/images/walkthrough_python_3_7/subprocess_run_capture_output.gif) You should note that it is an improvement over piping the stream manually. For example, ```subprocess.run(["ls", "-l", "/var"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)``` was the previous approach to capture the output of ```stdout``` and ```stderr```. ### Dataclasses The new class level decorator ```@dataclass``` introduced with the ```dataclasses``` module. Python is well-known for achieving more by writing less. It seems that this module will receive more updates in future which can be applied to reduce significant line of code. Basic understanding of Typehints is expected to understand this feature. When you wrap your class with the ```@dataclass``` decorator, the decorator will put obvious constructor code for you. Additionally, it defines a behaviour for dander methods ```__repr__()```, ```__eq__()``` and ```__hash__()```. ![Dataclasses.dataclass](/assets/images/walkthrough_python_3_7/dataclasses_dataclass.gif) Below is the code before introducing a ```dataclasses.dataclass``` decorator. ```python class Point: def __init__(self, x, y): self.x = x self.y = y ``` After wrapping with ```@dataclass``` decorator it reduces to below code ```python from dataclasses import dataclass @dataclass class Point: x: float y: float ``` ### Namedtuples The namedtuples are a very helpful data structure, yet I found it is less known amongst developers. With this release, you can set default values to argument variables. ![Namedtuples with default arguments](/assets/images/walkthrough_python_3_7/namedtuple_example.gif) ##### Note: Default arguments will be assigned from left to right. In the above example, default value ``2`` will be assigned to variable ``y`` Below is the code used in the example ```python from collections import namedtuple Point = namedtuple("Point", ["x", "y"], defaults=[2,]) p = Point(1) print(p) ``` ### .pyc **.pyc** are object files generated everytime you change your code file (.py). It is a collection of meta-data created by an interpreter for an executed code. The interpreter will use this data when you re-execute this code next time. Present approach to identify an outdated object file is done by comparing meta fields of source code file like last edited date. With this release, that identification process is improved by comparing files using a hash-based approach. The hash-based approach is quick and consistent across various platforms than comparing last edited dates. This improvement is considered unstable. Core python will continue with the metadata approach and slowly migrate to the hash-based approach. ### Summary * Calling ```breakpoint()``` will put a breakpoint in your code. * Disable all breakpoints in your code by setting an environment variable ```PYTHONBREAKPOINT=0```. * ```subprocess.run([...], capture_output=True)``` will capture the output of ```stdout``` and ```stderr```. * Class level decorator ```@dataclass``` will define default logic for constructor function. It will implement default logic for dunder methods ```__repr__()```, ```___eq__()``` and ```__hash__()```. * Namedtuple data structure supports default values to its arguments using ```defaults```. * Outdated Python object files (.pyc) are compared using the hash-based approach. I hope you were able to learn something new by reading this post. If you want to read an in-depth discussion on each feature introduced in Python 3.7, then please read [this](https://docs.python.org/3.7/whatsnew/changelog.html#python-3-7-0-final) official post. Happy hacking! ###### Proofreaders: [<NAME>](https://janusworx.com/), Ninpo, basen_ from #python at Freenode, Ultron from #python-offtopic at Freenode, up|ime from ##English at Freenode <file_sep>/_posts/2017-04-10-goyo-doc-vim-helpfile-for-goyo-plugin.md --- layout: post title: "goyo-doc: Vim helpfile for goyo.vim plugin" date: "2017-04-10 17:51:48 +0530" tags: - vim - goyo_doc excerpt: > Goyo is the vim plugin which allows writers to focus on their writing while they are writing. The plugin deactivates not required fancy windows which are not useful at the time of using vim for writing. It provides certain --- ![goyo_doc_plugin]({{site.url}}/assets/images/goyo_doc_plugin.png) ### What is Goyo? [Goyo][goyo] is the vim plugin which allows writers to focus on their writing while they are writing. The plugin deactivates not required fancy windows which are not useful at the time of using vim for writing. It provides certain customizations too. ### What is missing in Goyo? The main problem with [Goyo][goyo] plugin is that it carries very weak vim specific helpfile. A vimmer is habituated to find help at vim specific helpfile first. After few attempts, I have decided to write a good helpfile for the [Goyo][goyo] plugin. I am happy to maintain the documentation I have started with the ongoing development of the plugin until the author of [Goyo][goyo] is providing any concise helpfile for it. The [goyo-doc][goyo-doc] is not carrying any source of [Goyo][goyo] plugin, but only contains documentation for the plugin. I am inviting you to propose improvements if you find any. ### Why I decided to write a separate plugin for documentation? > "Documentation is essential. There needs to be something for people to read, > even if it's rudimentary and incomplete." > > -- <cite>K.Fogel, Producing Open source software</cite> I believe the documentation is the most important part of any software. While I was using [Goyo][goyo] plugin, I found it is missing the vim specific helpfile. I discussed this issue with the author and offered the help for improving on this. You can read further about early discussions [here](https://github.com/junegunn/goyo.vim/issues/144). I didn't get any positive response from the author so I decided to write and launch vim specific helpfile for this plugin. With this plugin, I am expecting to provide the solution to those users who are more familiar with vim specific helpfile than a Github wiki or README file of any project. Below are the links for downloading and using the plugin. ### Download links * [Vimscript](http://www.vim.org/scripts/script.php?script_id=5546) * [Github][goyo-doc] ###### Proofreader: [<NAME>](https://farhaanbukhsh.wordpress.com/) [goyo]: https://github.com/junegunn/goyo.vim [goyo-doc]: https://github.com/ultimatecoder/goyo-doc <file_sep>/_posts/2017-01-22-visit-to-linux-user-group-chennai.md --- layout: post title: Visit to Indian Linux User Group, Chennai tag: ILUG-C excerpt: > Lately I was travelling to Chennai for some personal work. I was very clear on meeting Mr. <NAME>. While travelling to Chennai I dropped a mail --- ![Indian Linux User Group Chennai]({{site.url}}/assets/images/ilugc.jpg) Lately I was travelling to [Chennai](https://en.wikipedia.org/wiki/Chennai) for some personal work. I was very clear on meeting [Mr. <NAME>](http://shakthimaan.com/). While travelling to Chennai I dropped a mail inquiring about his availability. He replied with an invitation to attend the Meetup of [Indian Linux Users Group, Chennai](https://www.meetup.com/ILUG-C/events/234086665/) scheduled at IIT Madras. I happily accepted the invitation and decided to attend the Meetup. The Meetup was happening in the AeroSpace Engineering department, IIT Madras. The campus is so huge that it took 15 minute bus journey to get to the department. Because I was late, I missed the initial talk on Emacs Org mode by Shakthi. I was lucky enough to attend lightning talk section. When I entered one young boy was demonstrating [BeFF](http://tools.kali.org/exploitation-tools/beef-xss). I was not aware about this tool before his talk. After his words I realized BeFF is a penetration testing tool and now I am confident for switching to its documentation and start going through it. His talk ended with little discussion on doubts. Nearly one hour was still remaining Shakthi came forward and invited interested people to present a lightning talk. That sure rang a bell! I was not sure about attending Meetup and presenting something instantly was looking tough. Mohan moved forward and demonstrated How memory mapping works in GNU/Linux system. During his talk I quickly skimmed on a list of topics I was aware about and I decided to speak on [JSON Web Token](https://en.wikipedia.org/wiki/JSON_Web_Token). I introduced myself and demonstrated ways to generate a secure token. Discussed about architecture a bit and gave few guidelines, points to remember. I ended my talk with comparing [Oauth 2.0](https://oauth.net/2/) with JWT. Few interested people asked questions and I was lucky enough to solve their confusions. I realized it is good to have small and interested audience than having large and distracted audience. This group has nice experienced people in the GNU/Linux domain. If Chennai is your town, I will promote you to join this group and get involved. ###### Proofreaders: [<NAME>](http://shakthimaan.com/), [<NAME>](https://github.com/vharsh) <file_sep>/README.md ![Travis build](https://travis-ci.org/ultimatecoder/Blog.svg?branch=master) # Blog - [Jaysinh's own heed](http://blog.jaysinh.com) This repository contains backend tool I use to write and publish my blog. Since begining, I have invested more time in identifying proper flow than writing blog post. * Framework: Jekyll * URL: http://blog.jaysinh.com <file_sep>/_posts/2017-01-08-2016-a-year-dedicated-to-python-workshops.md --- layout: post title: 2016 A year dedicated to Python Workshops tag: - python - workshop - pythonexpress excerpt: > Beautiful 2017 has already started. While everybody is busy with preparing resolutions for their new year I decided to look back and share my journey here. --- Beautiful 2017 has already started. While everybody is busy with preparing resolutions for their new year I decided to look back and share my journey here. After attending [PyCon India 2015](https://in.pycon.org/2015/) India 2015 I took an oath to spread the word of Python. It was looking simple at first glance with a guess of getting less invitations. But the estimate went wrong. Below is the summary of yearly progress highlight with word of experience. ![Python workshop piechart]({{site.url}}/assets/images/python_workshop_piechart.png) During my last year I conducted 13 workshops at various colleges of state Gujarat and Rajasthan. 10 workshops were conducted targeting college students and 3 were presented for professionals. Gandhinagar and Ahmedabad received 4 number of workshops individually. Did single workshop at Bhuj, Ajmer, Vadodara and New delhi. One over Google Hangouts on Air. Facilities I received while conducting workshops ------------------------------------------------ The colleges which were settled far from my town provided travelling allowance for me. I accepted because I felt there is nothing wrong in taking such help. Some colleges arranged an afternoon meal for me. I happily accepted that because finding another option during short breaks at unknown place is quite time consuming. There were few colleges which gave cash covers as a good will. I have decided to not accept such cash because sometimes it comes from the pocket of students and I don’t feel good to take money from the pocket of any student. Still some colleges claimed that the money belongs to their grants and not raised from students. I took that money at that time and donated each to [<NAME>](http://www.krishnavriddhashram.org/) located at Gandhinagar, Gujarat. Python Express -------------- Such contributions would have not possible without [Python Express][python_express]. Python Express is a platform to collaborate colleges, students with Python tutors across India. It is supervised and funded by the [Python Software Society of India](https://pssi.org.in/). ### Python Express Ahmedabad At present, we have a Python Express Ahmedabad group whose motive is to teach Python to nearby colleges. We are linked up with [Telegram Messenger](https://telegram.org/). During this PyCon, I got a large bunch of Python Express stickers from Vijay sir. The stickers will be a lot to motivate pupils. We also received Python Express volunteer T-shirts. If you are living nearby Ahmedabad and want to contribute to this movement, please get in touch over email. ![Python Express Ahmedabad]({{site.url}}/assets/images/python_express_ahmedabad.jpg) **"Teaching is the best way to learn."** ---------------------------------------- I am inspired from curious questions raised by scholars. They forced me to plunge deep into the subject. It was little difficult to afford such a huge hours with having a full time job, but after observing my personal improvements I consider this as a good investment. In summary, I took 1 workshop every month during the year 2016 which is nearly 90% more than what I did in the year 2015. You can download [Slides here](https://goo.gl/vTBhTh) and [Python Kit here](https://drive.google.com/file/d/0B_TmiicGbqjHb2ZGcE5QYmtXRHc/view?usp=sharing). Photos ----------------- ![PG GTU Gandhinagar]({{site.url}}/assets/images/pg_gtu.jpg) <p class="center"> At <a href="http://pgschool.gtu.ac.in/moodle/">PG GTU Gandhinagar</a> </p> **- - -** ![kskv_kachchh_university]({{site.url}}/assets/images/kskvku_photo.jpg) <p class="center"> At <a href="http://cs.kskvku.ac.in/">K.S.K.V. Kachchh University</a> </p> **- - -** ![Polytechnic Gandhinagar]({{site.url}}/assets/images/polytechnic_gandhinagar.jpg) <p class="center"> At <a href="http://www.gpgandhinagar.edu.in/">Gujarat Polytechnic College, Gandhinagar</a> </p> **- - -** ![Parul University]({{site.url}}/assets/images/parul_university.jpg) <p class="center"> At <a href="http://paruluniversity.ac.in/home/">Parul University, Waghodia, Vadodara</a> </p> **- - -** ![Nirma University]({{site.url}}/assets/images/nirma_university.jpg) <p class="center"> At <a href="http://www.nirmauni.ac.in/">Nirma Technology University, Ahmedabad</a> </p> **- - -** ![Startup Gujarat]({{site.url}}/assets/images/startup_gujarat.jpg) <p class="center"> At <a href="http://the1947.com/">Startup Gujarat, Gandhinagar</a> </p> **- - -** ![Ahmedabad Meetup]({{site.url}}/assets/images/ahmedabad_meetup.jpg) <p class="center"> At <a href="https://www.meetup.com/Ahmedabad-Web-and-Mobile-Developers-Meetup/events/232699917/"> Ahmedabad Web and Mobile developers meetup </a> </p> **- - -** ![DAIICT]({{site.url}}/assets/images/daiict.jpg) <p class="center"> At <a href="http://www.daiict.ac.in/">Dhirubhai Ambani Institute of Information and Communication Technology GandhinagarStartup Gujarat, Gandhinagar</a> </p> **- - -** ![Engineering college Ajmer]({{site.url}}/assets/images/engineering_college_ajmer.jpg) <p class="center"> At <a href="http://www.gweca.ac.in">Government Women Engineering College Ajmer</a> </p> **- - -** ![Ahmedabad University]({{site.url}}/assets/images/aeg_ahmedabad.jpg) <p class="center"> At <a href="https://www.ahduni.edu.in/">Ahmedabad University</a> </p> **- - -** ![Pycon India]({{site.url}}/assets/images/pycon_india.jpg) <p class="center"> At <a href="https://in.pycon.org/2016/">PyCon India, New Delhi</a> </p> **- - -** ![Macker Party]({{site.url}}/assets/images/macker_party.jpg) <p class="center"> At <a href="https://reps.mozilla.org/e/maker-party-gujarat/">Mozilla Maker Party Ahmedabad</a> </p> ### Do you want to invite me for your college? First step is to brief your college administration with Python Express to get the permission. Once they agree register your college at [Python Express][python_express] and create the workshop request that’s it! I will advice to schedule workshop on weekends. Saturday is usually the best day for me. Facilities like Projector, Microphone and speakers if number of attendees are more than 60. College Computer Labs, the auditorium is the best place for such events. Waiting for nice invitations :) ###### Proofreader: [<NAME>](https://farhaanbukhsh.wordpress.com/) [python_express]: https://pythonexpress.in/ [pydelhi_conf]: https://conference.pydelhi.org/ <file_sep>/_posts/2017-02-28-book-review-introduction-to-the-commandline.md --- layout: post categories: book review title: Book review 'Introduction to the Command Line' tag: - books - linux - programming excerpt: > Every chapter will introduce a bunch of comands and will point to its respective documentation for further learning. You should expect chapters describing from the grep command to GNU Octave which is a scientific programming language. The chapters are independent of each other. --- ![introduction_to_command_line]({{ site.url }}/assets/images/book_image_introduction_to_the_commandline.jpg) ## tl;dr Every chapter will introduce a bunch of comands and will point to its respective documentation for further learning. You should expect chapters describing from the [grep](https://www.gnu.org/software/grep/manual/grep.html) command to [GNU Octave](https://www.gnu.org/software/octave/) which is a scientific programming language. The chapters are independent of each other. The book is must read if you are new to the [GNU/Linux](https://en.wikipedia.org/wiki/Linux) command line. If you are at the intermediate level, then too investing time in reading this book will unveil a few surprises for you. ## Detailed review The book is community driven and published under [FLOSS Manual](http://flossmanuals.net). It is a collaborative effort of the [FSF](http://www.fsf.org/) community. The fun part is you can contribute to this book by adding new chapters or by improving an existing one. I fixed one typo in this book after reading. The best introduction is crafted comparing GUI based image editing tools with the most unknown command [convert](https://linux.die.net/man/1/convert). It conveys the importance of command line well to the reader. Initial chapters will present the overview of various [GNU/bash](https://www.gnu.org/software/bash/) commands. From my personal experience, you have to use mentioned commands in this chapter daily. The chapter of Command history shortcuts depicts geeky shell patterns. I will advise not to skip that chapter and read through once. The advanced section was not much advance for me. It demonstrates [ssh](https://linux.die.net/man/1/ssh) and related commands like [scp](https://linux.die.net/man/1/scp) and more. I appreciated the preference of using [GNU Screen](https://www.gnu.org/software/screen/) though I use [tmux](https://tmux.github.io/) over it. If you are possessed by moving around on multiple directories simultaneously, then **directory stacks** under **Moving Again** section is worth scanning. This functionality is saving dozens of my keystrokes now. There is one entire division dedicated to various editors. That section is not limited to [GNU Emacs](https://www.gnu.org/software/emacs/) or [vim][vim], but also briefs [GNU NANO](https://www.nano-editor.org/), [Kedit](http://www.kedit.com/) and [Gedit](https://wiki.gnome.org/Apps/Gedit). This section does not compare the pros and cons of several editors, but describes basics of each which should be counted as a good part. I skipped this part because I am comfortable with [vim][vim] editor at present and don’t want to invest much in others. The scripting section turned out to be the most interesting division for me. Though I was aware about the tools like [sed](https://www.gnu.org/software/sed/manual/sed.html) and language [awk](https://linux.die.net/man/1/awk) I was not using them often. Reading their chapters and implementing mentioned examples built little confidence in me. Now I am much comfortable in utilizing them. The irregular **Regular expressions** are everywhere. You should not pass over this section and pay careful attention to various examples. It is worth to invest your time in this segment. This is not the ending. This book presents a glimpse of various scripting level programming languages like [Perl](https://www.perl.org/), [Python](http://python.org) and [Ruby](https://www.ruby-lang.org/en/). Because I am a python developer for a few years and I was not much interested in other languages, I skipped this section. A shallow introduction to [GNU Octave](https://www.gnu.org/software/octave/) is nice to study if you are interested in knowing a little about this scientific programming language. ### How to read this book? Do not read to read. This book contains nice shell examples. By merely reading, you will end up without bringing about anything meaningful. I will advise you to interpret the description first, observe the examples and then implement them on your own. If you have any confusions, read the example and description again or obtain help from `man` or `info` are the best options. To remember, I revised the important chapters more than once in a week. It helped me to refresh what I learned before. I will attempt to re-read the important sections once again after a few days to refresh my memory. ### What is missing? Considerably, the book is nicely written, equally distributed and largely acceptable, but I would prefer to have a small set exercises section at the end of each topic. Exercise might help the reader to identify their weak points early and refer on them again if they desire to. ### Typo / Mistakes I didn't encounter any sever mistakes except one typo. The section of **Userful customizations** on page number 80 of my printed version, contains following example: ``` function manyargs { $arg=$1 shift ... } ``` Here, **$arg** is a misprint. A shell variable is never assigned with **$**. It should be `args=$1`. I myself has corrected the typographical error in the book. This change will be published maybe in the next release of this book. If you are encountering any mistakes while reading, I request you to fix the change [here](http://write.flossmanuals.net/command-line/introduction/). The interface for editing the book is beginner friendly. It took less than 5 minutes to drive the change. ### Where to buy/download? * [Buy printed version](https://shop.fsf.org/books-docs/introduction-command-line). * [Read Online](http://write.flossmanuals.net/command-line/introduction/). * [Download PDF](http://archive.flossmanuals.net/_booki/command-line/command-line.pdf) ###### Proofreader: [<NAME>](http://codingquark.com/) [vim]: http://www.vim.org/ <file_sep>/_plugins/tags_folder.rb module Jekyll class TagList < Page def initialize(site, base, dir) @site = site @base = base @dir = dir @name = 'index.html' self.process(@name) self.read_yaml(File.join(base, '_layouts'), 'tags_folder_index.html') end end class TagListGenerator < Generator safe true def generate(site) if site.layouts.key? 'tags_folder_index' site.pages << TagList.new(site, site.source, 'tags') end end end end <file_sep>/scripts/deploy #!/bin/bash rsync -avr --rsh="ssh -i keypair.pem -o StrictHostKeyChecking=no" --delete-after --delete-excluded _site/ <EMAIL>:/blog/ || exit <file_sep>/about.md --- layout: page title: About permalink: /about/ --- ![my_image]({{ site.url}}/assets/images/my_profile_picture.jpg) Hi, I am Full-stack developer by profession, Computer scientist by heart and Actor by gene. I speak at local events, meetup or any technical conferences. I love to conduct lectures on any specific topic for college students. I am organizer of PyKutch. You can consider innovative programming as one of my hobby. In my free time I try to digest top rated programming books recommended by goodreads. I prefer to communicate via electronic mail, IRC over physical. I support The Free Software Foundation and always insist the point of user’s Freedom. I am astonished by the contribution of the GNU community and openly thank them for giving us such a useful things. <file_sep>/_posts/2017-07-21-pydelhi-conf-2017-a-beautiful-conference-happend-at-new-delhi-india.md --- layout: post title: "PyDelhi Conf 2017: A beautiful conference happened in New Delhi, India" date: "2017-07-21 18:14:03 +0530" tag: - python - conference - django - talks excerpts: > PyDelhi conf 2017 was a two-day conference which featured workshops, dev sprints, both full-length and lightning talks on Python programming language. --- ![PyDelhi Conf 2017]({{site.url}}/assets/images/pydelhi_conf_2017/group_photo.jpg) ## TL;DR [PyDelhi conf 2017][pydelhi_conf_2017] was a two-day conference which featured workshops, dev sprints, both full-length and lightning talks. There were workshop sessions without any extra charges. Delhiites should not miss the chance to attend this conference in future. I conducted a workshop titled **“Tango with Django”** helping beginners to understand the Django web framework. ## Detailed Review ### About the [PyDelhi community][pydelhi_community] ![PyDelhi Community]({{site.url}}/assets/images/pydelhi_conf_2017/pydelhi_community.jpg) <p class="center"> PyDelhi conf 2017 volunteers </p> The [PyDelhi community][pydelhi_community] was known as NCR Python Users Group before few years. This community is performing a role of an umbrella organization for other FLOSS communities across New Delhi, India. They are actively arranging monthly [meetups][pydelhi_meetup] on interesting topics. Last [PyCon India](https://in.pycon.org/2016/) which is a national level conference of Python programming language was impressively organized by this community. This year too they took the responsibility of managing it. I am very thankful to this community for their immense contribution to this society. If you are around New Delhi, India then you should not miss the chance to attend their [meetups][pydelhi_meetup]. This community has great people who are always happy to mentor. ### [PyDelhi conf 2017][pydelhi_conf_2017] ![Conference T-shirt]({{site.url}}/assets/images/pydelhi_conf_2017/t_shirt.jpg) <p class="center"> Conference T-shirt </p> PyDelhi conf is a regional level conference of Python programming language organized by PyDelhi community. It is their second year organizing this conference. Last year it was located at [JNU University](http://www.jnu.ac.in). This year it happened at [IIM, Lucknow](https://www.iiml.ac.in/) campus based in Noida, New Delhi, India. I enjoyed various talks which I will mention later here, a workshops section because I was conducting one and some panel discussions because people involved were having a good level of experience. 80% of the time slot was divided equally between 30 minutes talk and 2-hour workshop section. 10% were given to panel discussions and 10% was reserved for lightning talks. The dev sprints were happening in parallel with the conference. The early slot was given to workshops for both the days. One large conference hall was located on a 2nd floor of the building and two halls at the ground floor. Food and beverages were served on the base floor. ![Panel discussion]({{site.url}}/assets/images/pydelhi_conf_2017/pannel_disussion.jpg) <p class="center"> Panel Discussion </p> ![Desk]({{site.url}}/assets/images/pydelhi_conf_2017/desk.jpg) <p class="center"> Registration desk </p> ![Lunch]({{site.url}}/assets/images/pydelhi_conf_2017/lunch.jpg) <p class="center"> Tea break </p> ### Keynote speakers ![Mr. <NAME>]({{site.url}}/assets/images/pydelhi_conf_2017/ricardo.jpg) * [**Mr. <NAME>:**]( https://www.linkedin.com/in/ricardo-rocha-739aa718/?ppe=1) Mr. Rocha is a software engineer at [CERN][cern]. I got some time to talk with him post-conference. We discussed his responsibilities at [CERN][cern]. I was impressed when he explained how he is managing infrastructure with his team. On inquiring opportunities available at [CERN][cern] he mentioned that the organization is always looking for the talented developers. New grads can keep an eye on various Summer Internship Programs which are very similar to Google Summer of Code program. ![Mr. <NAME>]({{site.url}}/assets/images/pydelhi_conf_2017/chris.jpg) * [**Mr. <NAME>:**](https://www.chrisstucchio.com/) Mr. Stucchio is director of Data Science at [Wingify/ VWO](https://vwo.com/). I found him physically fit compared to other software developers (mostly of India). I didn’t get much time to have a word with him. ### Interesting Talks Because I took the wrong metro train, I was late for the inaugural ceremony. I also missed a keynote given by Mr. Rocha. Below talks were impressively presented at the conference. * [**Let’s talk about GIL by Mr. <NAME>:**]( https://youtu.be/CwTnUvHo6d8?list=PL3Aq1JLV2oFZFzSGsDUcc6BieBEvUDzJg) [Mr. Kumar](http://iamit.in/) discussed various ways to trace threads first and then moved the track towards Global Interpreter Lock. He described why the GIL is important in [CPython][cpython]. * [**Concurrency in Python 3.0 world - Oh my! by Mr. <NAME>illai:**]( https://youtu.be/QCZ31d9dqF4?list=PL3Aq1JLV2oFZFzSGsDUcc6BieBEvUDzJg) [Mr. Pillai][mr_anand] is well experienced in programming using Python language. I like getting his advices on various programming topics. He explained how [async][async] IO can be leveraged to boost your programs. I got few correct references on understanding latest API of the [async][async] library. * [**Property based testing 101 by <NAME>:**](https://youtu.be/n5xUTcsrRns) I always enjoy chit chatting with [Mr. Maithani](http://www.aniketmaithani.net/) during conferences. He has jolly nature and always prepared with one liner. He discussed various strategies for generating demo data for test cases. I was amazed by his references, tips and tricks for generating test data. I love discussing with people rather than sit in on sessions. With that ace-reason, I always lose some important talks presented at the conference. I do not forget to watch them once they are publicly available. This year I missed following talks. * [**Optimizing Django for building high-performance systems by Mr. Sanyam Khurana**](https://youtu.be/I41LTEWzluU) * [**Mocking in Python by Mr. <NAME>**](https://youtu.be/xo9QhfaefzY) ### Volunteer Party I got a warm invitation by the organizers to join the volunteer party, but I was little tensed about my session happening on the next day. So, I decided to go home and improve the slides. I heard from friends that the party was awesome! ### My workshop session ![Tango with Django]({{site.url}}/assets/images/pydelhi_conf_2017/talk_2.jpg) <p class="center"> Me conducting workshop </p> I conducted a workshop on Django web framework. “Tango with Django” was chosen as a title with a thought of attracting beginners. I believe this title is already a name of famous book solving the same purpose. * [Slides](https://www.slideshare.net/jaysinhp/tango-with-django-78119081) * [Video Youtube](https://youtu.be/jr6LWM7Yquk) ### Dev sprints ![Dev sprints]({{site.url}}/assets/images/pydelhi_conf_2017/devsprint.jpg) <p class="center"> Me hacking at dev sprints section </p> The dev sprints were happening parallel with the conference. [Mr. Pillai][mr_anand] was representing [Junction](https://github.com/pythonindia/junction). I decided to test few issues of [CPython][cpython] but didn’t do much. There were a bunch of people hacking but didn’t find anything interesting. The quality of chairs was so an impressive that I have decided to buy the same for my home office. ### Why attend this conference? * **Free Workshops:** The conference has great slot of talks and workshops. Workshops are being conducted by field experts without expecting any other fees. This can be one of the great advantages you leverage from this conference. * **Student discounts:** If you are a student then you will receive a discount on the conference ticket. * **Beginner friendly platform:** If you are novice speaker than you will get mentorship from this community. You can conduct a session for beginners. * **Networking:** You will find senior employees of tech giants, owner of innovative start-ups and professors from well-known universities participating in this conference. It can be a good opportunity for you to network with them. ### What was missing? * **Lecture hall arrangement:** It was difficult to frequently travel to the second floor and come back to the ground floor. I found most people were spending their time on the ground floor rather than attending talks going on upstairs. * **No corporate stalls:** Despite having corporate sponsors like Microsoft I didn’t find any stall of any company. * **The venue for dev sprints:** The rooms were designed for teleconference containing circularly arranged wooden tables. This was not creating a collaborative environment. Involved projects were not frequently promoted during the conference. ### Thank you PyDelhi community! I would like to thank all the known, unknown volunteers who performed their best in arranging this conference. I am encouraging [PyDelhi][pydelhi_community] community for keep organizing such an affable conference. * [Conference Photos](https://www.flickr.com/groups/pydelhi/) * [Talk videos](https://www.youtube.com/playlist?list=PL3Aq1JLV2oFZFzSGsDUcc6BieBEvUDzJg) ###### Proofreaders: [Mr. <NAME>](https://github.com/pydsigner), [Mr. <NAME>](http://codingquark.com/), [Mr. <NAME>](https://sayanchowdhury.dgplug.org/), [Mr. <NAME>](https://www.emacswiki.org/emacs/TrentBuck) [pydelhi_conf_2017]:https://conference.pydelhi.org [pydelhi_community]:https://pydelhi.org/ [pydelhi_meetup]:http://www.meetup.com/pydelhi [cern]:https://home.cern/ [mr_anand]:https://youtu.be/I41LTEWzluU [cpython]:https://github.com/python/cpython [async]:https://docs.python.org/3/library/asyncio.html <file_sep>/_posts/2017-12-05-book-review-docker-up-running.md --- layout: post title: "Book review 'Docker Up & Running'" date: "2017-12-05 11:26:32 +0530" tags: - books - docker - linux --- ![book image docker up and running]({{ site.url}}/assets/images/book_review_docker_up_and_running/main.jpg) In the modern era of software engineering, terms are coined with a new wrapper. Such wrappers are required to make bread-and-butter out of it. Sometimes good marketed terms are adopted as best practices. I was having a lot of confusion about this Docker technology. Even I was unfamiliar with the concept of containers. My certain goal was to get a higher level overview first and then come to a conclusion. I started reading about the Docker from its official getting started guide. It helped me to host this blog using Docker, but I was expecting some more in-depth overview. With that reason, I decided to look for better resources. By reading some Quora posts and Goodreads reviews, I decided to read “Docker Up & Running by <NAME> and <NAME>”. I am sharing my reading experience here. ## TL;DR The book provides a nice overview of Docker toolchain. It is not a reference book. Even though few options are deprecated, I will advise you to read this book and then refer the [official documentation](https://docs.docker.com/) to get familiar with the latest development. ## Detailed overview I got a printed copy at nearly 450 INR (roughly rounding to 7 USD, where 1 USD = 65 INR) from [Amazon](https://www.amazon.in/). The prize is fairly acceptable with respect to the print quality. The book begins with a little history of containers (Docker is an implementation of the container). Initial chapters give a higher level overview of Docker tools combining Docker engine, Docker image, Docker registry, Docker compose and Docker container. Authors have pointed out situations where Docker is not suitable. I insist you do not skip that topic. I skipped the dedicated chapter on installing Docker. I will advise you to skip irrelevant topics because the chapters are not interlinked. You should read chapter 5 discussing the behavior of the container. That chapter cleared many of my confusions. Somehow I got lost in between, but re-reading helped. Such chapters are enough to get a general idea about Docker containers and images. Next chapters are focused more on best practices to setup the Docker engine. Frankly, I was not aware of possible ways to debug, log or monitor containers at runtime. This book points few expected production glitches that you should keep in mind. I didn't like the depicted testing workflow by authors. I will look for some other references which highlight more strategies to construct your test workflow. If you are aware of any, please share them with me via e-mail. I know about achieving auto-scaling using various orchestration tools. This book provides step by step guidance on configuring and using them. Mentioned tools are [Docker Swarm](https://github.com/docker/swarm), [Centurion](https://github.com/newrelic/centurion) and [Amazon EC2 container service](https://aws.amazon.com/ecs/). Unfortunately, the book is missing [Kubernets](https://kubernetes.io/) and [Helios](https://github.com/spotify/helios) here. As a part of advanced topics, you will find a comparison of various filesystems with a shallow overview of how Docker engine interacts with them. The same chapter is discussing available execution drivers and introduces [LXC](https://linuxcontainers.org/) as another container technology. This API option is deprecated by [Docker version 1.8](https://github.com/moby/moby/blob/master/CHANGELOG.md#180-2015-08-11) which makes [libcontainer](https://github.com/docker/libcontainer) the only dependency. I learned how Docker containers provide the virtualization layer using [Namespaces][namespaces]. Docker limits the execution of container using [CGroups (Control Groups)][cgroups]. [Namespaces][namespaces] and [CGroups][cgroups] are GNU/Linux level dependencies used by Docker under the hood. If you are an API developer, then you should not skip Chapter 11. This chapter discusses two well-followed patterns [Twelve-Factor App](https://12factor.net/) and [The Reactive manifesto](https://www.reactivemanifesto.org/). These guidelines are helpful while designing the architecture of your services. The book concludes with further challenges of using Docker as a container tool. One typo I found at page number 123, second last line. ``` expore some of the tools... ``` Here, `expore` is a typo and it should be ``` explore some of the tools... ``` I have submitted it to the [official errata](http://www.oreilly.com/catalog/errataunconfirmed.csp?isbn=0636920036142). At the time of writing this post, it has not confirmed by authors. Hope they will confirm it soon. ### Who should read this book? * Developers who want to get an in-depth overview of the Docker technology. * If you set up deployment clusters using Docker, then this book will help you to get an overview of Docker engine internals. You will find security and performance guidelines. * This is not a reference book. If you are well familiar with Docker, then this book will not be useful. In that case, the Docker documentation is the best reference. * I assume Docker was not supporting Windows platform natively when the book was written. The book focuses on GNU/Linux platform. It highlights ways to run Docker on Windows using VMs and [Boot2Docker](http://boot2docker.io/) for Non-Linux VM-based servers. ### What to keep in mind? * Docker is changing rapidly. There will be situations where mentioned options are deprecated. In such situation, you have to browse the latest Docker documentation and try to follow them. * You will be able to understand the official documentation better after reading this book. ## Conclusion * Your GNU/Linux skills are your Docker skills. Once you understand what the Docker is, then your decisions will become more mature. ###### Proofreaders: [<NAME>](http://codingquark.com/), [Polprog](https://www.youtube.com/channel/UCsxonLIUu9tB8QWNuFIXCwg/featured) ## Printed Copy * [Amazon](https://www.amazon.in/Docker-Up-Running-Karl-Matthias/dp/9352131320) * [Flipkart](https://www.flipkart.com/docker-up-running/p/itme8n74nhfg2wnm?pid=9789352131327) * [O'REILLY](http://shop.oreilly.com/product/0636920036142.do) [namespaces]: https://en.wikipedia.org/wiki/Linux_namespaces [cgroups]: https://en.wikipedia.org/wiki/Cgroups <file_sep>/_posts/2017-08-28-how_to_repair_a_broken_grub_in_ubuntu.md --- layout: post title: "How to repair a broken GRUB in Ubuntu?" date: "2017-08-28 13:35:42 +0530" tag: - Ubuntu - GRUB - How-to excerpt: Steps to restore your GRUB if you have formatted boot partition mistakenly --- ![How to repair a broken GRUB]({{ site.url}}/assets/images/how_to_fix_broken_grub/grub_title.png) ## Background story Yesterday, I was having some free time after lunch. I decided to complete a long term plan of checking the compatibility of few [Freedom Operating Systems][freedom] with my workstation. From [this list][freedom_oses], I decided to check [Trisquel][trisquel] OS first. [Trisquel][trisquel] is freedom clone of world-famous OS Ubuntu. The simplest option was to prepare a live USB drive and boot the [Trisquel][trisquel] from it. I inserted the USB drive and instructed the [Gparted][gparted] to format it. Bang! That simple step ruined my entire Sunday evening. Instead of formatting my USB drive, I mistakenly formatted the boot partition! Without putting any extra measures, I formatted my root partition which is also a type [FAT][fat]. I was lucky enough to identify that I have formatted the partition from my SSD and not the USB drive. After taking advice from the people of [##linux][linux_irc_channel] I found, I will not be able to re-boot because the [GRUB][GRUB] is lost. In this post, I will describe the steps I followed to restore the [GRUB][GRUB]. ## Procedure of restoring the GRUB You can restore your [GRUB][GRUB] using three methods: * Using GUI utility [“Boot-repair”][boot_repair]. This is the simplest step to follow first. Unfortunately, I was not able to fix my [GRUB][GRUB] using this method. * Boot from a live operating system, mount the infected boot partition and perform the steps of restoring the [GRUB][GRUB]. Since I identified the problem at an early stage, I didn’t restart my system until I was sure that nothing is broken. * Last is to run the steps of restoring the [GRUB][GRUB] from the command line if you haven’t reboot your system after formatting the boot partition. I will describe the steps of restoring your [GRUB][GRUB] using this method in this post. If you had rebooted and are unable to start the system then I will request to follow the steps described at [How to geek][how_to_geek] post rather than continuing here. If you are using Legacy BIOS rather than UEFI type then this post might not work for you. To identify which type your system has booted with, [follow this steps][bios_or_uefi]. ## So let’s start! * **Identify the type of your boot partition:** You can use GUI utilities like [GParted][gparted] or any other of your choice. The boot partition is the very first partition of the drive you are using for booting your operating system. ![Identify boot partition using gparted]({{ site.url}}/assets/images/how_to_fix_broken_grub/gparted_identification_parition.png) In my case, it is `/dev/sda1`. This partition should be either [FAT32][fat32] or [FAT16][fat16]. If it is anything other than that you should format it to [FAT][fat] version of your choice. * **Assert `/boot/efi` is mounted:** Run below command at your terminal. ``` sudo mount /boot/efi ``` Sample output ``` $sudo mount /boot/efi/ mount: /dev/sda1 is already mounted or /boot/efi busy /dev/sda1 is already mounted on /boot/efi ``` If it is mounted, it will throw a warning indicating that the partition is already mounted. If it isn’t mounted, then the prompt will come back without any warning message. * **Next, restore and update the [GRUB][GRUB]:** Run below command at your terminal. ``` sudo grub-install && update-grub ``` Sample output ``` $ sudo grub-install && update-grub Installing for x86_64-efi platform. Installation finished. No error reported. ``` If there is any error, I will advise to not move further and try other options I mentioned above for restoring your [GRUB][GRUB]. * **Finally, replace the UUID of the formatted partition:** Find the **UUID** of your boot partition. Once you format the partition, the **UUID** of the partition is changed. You have to update the new **UUID** value at `/etc/fstab` file. Use below command to get the latest **UUID** of your boot partition. ```sudo blkid /dev/sda1``` ![Identifying UUID of boot efi]({{ site.url}}/assets/images/how_to_fix_broken_grub/uuid_blkid_shell.png) Copy the value of **UUID** which is between the double quotes. Open the `/etc/fstab` file with your desired editor and update the value with the existing **UUID** of `/dev/sda1`. I am doing this procedure using the [vim][vim] editor. You can choose any editor of your choice. ```sudo vim /etc/fstab``` ![Updating the UUID to the etc fstab file]({{ site.url}}/assets/images/how_to_fix_broken_grub/vim_etc_fstab.png) You will require the root privileges for writing to this file. We are done! Now when you will run `sudo ls -l /boot/efi`, you should able to identify the files beneath that directory. It is time to confirm by rebooting your system. ## Vote of Thanks! I would like to thank [ioria][ioria] and [ducasse][ducasse], member of [#ubuntu][ubuntu_irc_channel] at Freenode, who invested a great amount of time to guide me in fixing this problem. [#ubutu][ubuntu_irc_channel] has great members who are always willing to help you. *Note: While mentioning the GRUB in this post, I actually mean the GRUB2.* ###### Proofreaders: [<NAME>](http://codingquark.com/), Pentode@##linux(Freenode), parsnip@#emacs (Freenode) [GRUB]: https://www.gnu.org/software/grub/ [trisquel]: https://trisquel.info/ [gparted]: http://gparted.org/ [fat]: https://en.wikipedia.org/wiki/File_Allocation_Table [fat32]: https://en.wikipedia.org/wiki/File_Allocation_Table#FAT32 [fat16]: https://en.wikipedia.org/wiki/File_Allocation_Table#FAT16 [linux_irc_channel]: https://freenode.linux.community/ [boot_repair]: https://help.ubuntu.com/community/Boot-Repair [vim]: http://www.vim.org [ubuntu_irc_channel]: irc://irc.freenode.net/ubuntu [ioria]: https://launchpad.net/~di-iorio [ducasse]: https://launchpad.net/~ducasse [freedom_oses]: https://www.gnu.org/distros/free-distros.en.html [freedom]: https://www.gnu.org/philosophy/free-sw.en.html [how_to_geek]: https://www.howtogeek.com/114884/how-to-repair-grub2-when-ubuntu-wont-boot/ [bios_or_uefi]: https://askubuntu.com/a/162896 <file_sep>/_posts/2017-03-14-pycon-pune-2017-a-wonderful-python-conference.md --- layout: post title: "Pycon Pune 2017: A wonderful Python conference" date: "2017-03-14 18:18:02 +0530" tag: - python - conference excerpt: > The conference is worth attending if you are a student, programmer or a hobbyist. If you are a swag-hungry then don't expect much as a swag from this conference. If you are a Devsprint lover, then this conference has the coolest Devsprint. A great number of keynote speakers are invited for this conference. --- ![pycon_pune_group_photo]({{ site.url}}/assets/images/pycon_pune_group_photo.jpg) ## tl;dr The conference is worth attending if you are a student, programmer or a hobbyist. If you are a swag-hungry then don't expect much as a swag from this conference. If you are a Devsprint lover, then this conference has the coolest Devsprint. A great number of keynote speakers are invited for this conference. ## Detailed Experience Because I was volunteering for this conference I reached Pune one day earlier than the conference days. The volunteer meeting was happening at Reserved-bit. ### Volunteer #### Reserved-bit [Reserved-bit][reservedbit] is the best hackerspace I have ever come across. It has a large collection of programmable boards. You will find boards like [Raspberry Pi](https://en.wikipedia.org/wiki/Raspberry_Pi), [Bana Pi](https://en.wikipedia.org/wiki/Banana_Pi), [Dragonboard](https://developer.qualcomm.com/hardware/dragonboard-410c), [Bigalbon](https://beagleboard.org), [BBC-microbit](https://en.wikipedia.org/wiki/Micro_Bit) and the 3D printer. Furthermore, this space has a great collection of books on Compilers and Embedded programming. I managed to found few on open-source too. The owners are great hackers. You will love to interact with hacker [<NAME>](https://siddhesh.in/). Hacker [<NAME>](https://twitter.com/nisha_poyarekar) is volunteering the [PyLadies community](https://www.meetup.com/PyLadies-Pune/) at Pune. #### Pune to Mumbai I spent my half day in this space. I got the responsibility of receiving one of the keynote speakers who was landing at Mumbai airport midnight. To be frank, estimation of Google Maps between Pune to Mumbai is wrong. It showed nearly 2 hours but it took almost 4.5 hours to reach Mumbai. It took few more minutes to reach the airport. The road is impressively smooth. You will encounter the beautiful mountains of [Lonavla](https://en.wikipedia.org/wiki/Lonavla). The task of moving from Pune to Mumbai airport, receive Katie and come back to Pune was completed in almost 13 hours. I left from Pune around 4.30 PM and came back at nearly 5 AM next day early morning. #### Illness during conference Because I did a huge amount of traveling at that night, I was unable to get enough sleep. Such tiredness resulted in an eye infection. I managed to attend the first day of the conference, but I was not in a condition to attend the second day. Treatment from local doctor healed me in two days and then I was able to take part into Devsprint. ### Conference The conference was a total of 4 days where the initial two days were for the talks and the end was assigned for a Devsprint. It didn't overwhelmed me with many tracks but gave the quality talks presented in a single track. The talks were set from 9 AM to 5 PM which was taken little lightly by the attendees. I was pretty impressed with the keynote speakers of this conference. #### [<NAME>](https://twitter.com/kcunning) Katie is the O'Reilly author. Her [book](http://shop.oreilly.com/product/0636920024514.do) on Accessibility depicts her area of expertise. She is fun to talk to. She likes to listen about developer communities, writing and most importantly computer games. Her broad vision on product development is amazing. She is an avid reader. I enjoyed listening to her experience of being in India for the very first time. #### [<NAME>](https://twitter.com/honzakral) Honza is the dude who loves contributing to [Django](https://www.djangoproject.com/). He is a core contributor of Django too. He hacks on Python drivers at [Elastic](https://www.elastic.co/). I was impressed with his suggestions on a code design problem I was trying to solve from the past few months. His suggestions on code design are worth noticing. He is a vimmer and maintains little [vim](http://www.vim.org) plugins as a part of his interest. #### [<NAME>](https://twitter.com/yasegumi) Stephen professes the Dismal Science of Economics. His knowledge is deep-rooted just like his beard. You will enjoy discussing computer science, books and his experience of programming. He is authoring few books written in the Japanese language. Stephen is [Emacsite](https://www.gnu.org/s/emacs/). ![stephen_turnbull]({{ site.url}}/assets/images/stephen_turnbull.jpg) #### [<NAME>](https://twitter.com/terriko) Terri is a security nerd. She spent most of her time exploring tools at Intel. Terri knows how to hide from the spying of the U.S. Government. She is leading [Google Summer of Code](https://summerofcode.withgoogle.com/) section from [Python Software Foundation](https://www.python.org/psf/). Terri is PSF community service award winner. If you are a student and want to take part in GSoC choosing PSF as your organization then she is the right person to talk to. #### [<NAME>](https://github.com/flofuchs) His knowledge on [ReST API](https://en.wikipedia.org/wiki/Representational_state_transfer) construction is the best. He is a [Falcon](https://falconframework.org/) nerd too. I enjoyed discussing various authentication mechanisms for ReST API with him. He is a Red Hatter. ![gnu_mailman_team]({{ site.url}}/assets/images/gnu_mailman_team.jpg) #### [<NAME>](https://twitter.com/ncoghlan_dev) Nick listens more than he speaks. I will advise you to not disturb him if he is coding. He enjoys concentrating while coding. Getting his mentorship was a great experience. He has been contributing to [Core Python](https://github.com/python/cpython) for a decade now. You will enjoy discussing on interesting code compositions with him. He is a Red Hatter. #### [<NAME>](https://twitter.com/_gnovi) Unfortunately, I didn't get much time to talk with Praveen during this conference. He is a math teacher who teaches concepts of mathematics using Python programming language. You should feel confident to speak with him on Python in education and mathematics with him. #### [<NAME>](https://github.com/warthog9) John is the wittiest person that I know. His lines always end with humor. He hacks mostly on hardware and GNU/Linux. Micro Python and GNU/Linux should be considered as part of his interests. I am sad to declare that I was unable to attend any keynote speeches because of the illness. Mostly I rested at the hotel or talked with people during the conference days. ![pycon_pune_2017_keynote_speakers]({{ site.url}}/assets/images/pycon_pune_2017_keynote_speakers.jpg) #### Volunteer Party If you are volunteering for this conference, then you will be invited to a volunteer dinner party. We enjoyed party colored disco lights dancing on the bits of the DJ. Punjabi food was served, and if you were above 25 than you were allowed to take a sip of a beer. #### Devsprint Devsprint happen at the [Red Hat Headquarters, Pune](https://goo.gl/maps/mXeirzQhPFz). I found the building has tight security. You will find an individual pantry section dedicated to each department. We were instructed to hack at a huge cafeteria section. I myself contributed to Core Python. <NAME> was mentoring for Core Python. I reviewed one PR, found one broken test case and wrote a fix of an existing issue with his help. Honza was leading the development of Django web framework. A team of [<NAME>](http://anandology.com/) mentored for [Web2py](http://www.web2py.com/). [<NAME>](https://twitter.com/fhackdroid) mentored for [Pagure](https://github.com/pypingou/pagure). <NAME> encouraged contributing to [MicroPython](https://micropython.org/). <NAME>, <NAME> and <NAME> mentored for [GNU/Mailman](https://en.wikipedia.org/wiki/GNU_Mailman). ![cpython_devsprint]({{ site.url}}/assets/images/cpython_devsprint.jpg) #### Why attend this conference? * This conference has the coolest Devsprint. The organizers understand the value of the Devsprint in a conference. I have never observed such an importance of Devsprint at any other Python conference happening in India. * If you are a student, then this is a beginner friendly conference. Don't be afraid to attend if you are a Python noob. You will receive a student concession for the tickets too. * If you are a developer, coming to this conference will inspire you to grow from your present level. You will meet core contributors, lead programmers, owners of startups and project managers. You will find a huge scope of opportunities to network with people. * The conference is single track event. This decision helped me to not miss the interesting talks. In my previous experience, parallel tracks forced me to choose between talks when I was interested in both, which killed me. * I have never seen such a huge amount of keynote speakers at any conference happening in India. Keynote speakers were the main attraction of this conference. #### What was missing? * If you are a swag-hungry fellow than attending this conference won't be worth it. The conference attendees have to be satisfied with the conference T-shirt. * I observed there were fewer corporate stalls than at other Python conferences. A stole from Reserved-bit, Red Hat and PSF community stall was there. * A workshop section was completely missing. In my opinion, the workshop helps the beginners to start. There were a few topics which can be better represented as workshop rather than a talk. * I was unable to observe any dedicated section for an open space discussion. This section is helpful for communities and contributors to discuss interesting problems and think together. ###### Proofreader: [<NAME>][benaiah], [Chameleon][chameleon] [reservedbit]: https://reserved-bit.com [benaiah]: https://benaiah.me/ [chameleon]: https://chameleon.kingdomofmysteries.xyz/ <file_sep>/_posts/2017-11-14-django-girls-bangalore-2017.md --- layout: post title: "My experience of mentoring at Django Girls Bangalore 2017" date: "2017-11-14 08:01:25 +0530" tag: - django - python - djangogirls --- ![group_photo]({{ site.url}}/assets/images/django_girls_blr_2018/group_photo.jpg) ## TL;DR Last Sunday, [Django Girls Bangalore][django_girls_bangalore] organized a hands-on session of web programming. This is a small event report from my side. ## Detailed overview [Django Girls][django_girls] is not for a profit initiative led by [O<NAME>](http://ola.sitarska.com/) and [Ola Sendecka](http://blog.sendecka.me/). Such movement helps women to learn the skills of website development using the well-known web-framework [Django][django]. This community is backed by organizers from many countries. Organizations like The [Python Software Foundation](https://www.python.org/psf/), [Github](https://github.com), [DjangoProject][django] and many [more](https://djangogirls.org/#supporters) are funding [Django Girls][django_girls]. [Django Girls Bangalore][django_girls_bangalore] chapter was organized by [<NAME>](https://twitter.com/MrSouravSingh) and [<NAME>](https://anirudha.org/). This was my second time mentoring for the [Django Girls][django_girls] event. First was for the [Ahmedabad chapter](https://djangogirls.org/ahmedabad/). The venue was sponsored by [HackerEarth](https://www.hackerearth.com). 8 male and 2 female mentored 21 women during this event. Each mentor was assigned more or less 3 participants. Introducing participants with web development becomes easy with the help of [Django Girls handbook][handbook]. The [Django Girls handbook][handbook] is a combination of beginner-friendly hands-on tutorials described in a simple language. The [handbook][handbook] contains tutorials on basics of Python programming language to deploying your web application. Pupils under me were already ready by pre-configuring Python with their workstation. We started by introducing our selves. We took some time browsing the [website](http://submarinecablemap.com/) of undersea cables. One of the amusing questions I got is, “Isn't the world connected with Satellites?”. My team was comfortable with the Python, so we quickly skimmed to the part where I introduced them to the basics of web and then [Django][django]. I noticed mentors were progressing according to the convenience of participants. Nice amount of time was invested in discussing raised queries. During illumination, we heard a loud call for the lunch. A decent meal was served to all the members. I networked with other mentors and participants during the break. Post-lunch we created a blog app and configured it with our existing project. Overview of [Django][django] models topped with the concept of [ORM](https://en.wikipedia.org/wiki/Object-relational_mapping) became the arduous task to explain. With the time as a constraint, I focused on admin panel and taught girls about deploying their websites to [PythonAnywhere](https://www.pythonanywhere.com/). I am happy with the hard work done by my team. They were able to demonstrate what they did to the world. I was more joyful than them for such achievement. The closing ceremony turned amusing event for us. 10 copies of [Two scoops of Django](https://www.twoscoopspress.com) book were distributed to the participants chosen by random draw strategy. I solemnly thank the authors of the book and [Pothi.com](https://pothi.com/) for gifting such a nice reference. Participants shared their experiences of the day. Mentors pinpointed helpful resources to look after. They insisted girls would not stop at this point and open their wings by developing websites using skills they learned. T-shirts, stickers and badges were distributed as event swags. You can find the list of all [Django Girls][django_girls] chapters [here](https://djangogirls.org/events/map/). Djangonauts are encouraged to become a mentor for [Django Girls][django_girls] events in your town. If you can't finding any in your town, I encourage you to take the responsibility and organize one for your town. If you are already a part of [Django Girls][django_girls] community, Why are you not sharing your experience with others? ###### Proofreaders: [<NAME>](https://kushaldas.in), [<NAME>](http://codingquark.com/), [<NAME>](https://github.com/Dude-X) [django_girls_bangalore]: https://djangogirls.org/bangalore/ [django_girls]: https://djangogirls.org/ [django]: https://www.djangoproject.com/ [handbook]: https://tutorial.djangogirls.org/en/
cdfd1e5fcb972ff4cf06a8d66e1051650334ae13
[ "Markdown", "Ruby", "Shell" ]
16
Markdown
ultimatecoder/ultimatecoder.github.io
13f91cfa84265705c9a04ea6c754b59f77c257a3
a23e2c109b83fc6b298758e0798e933e3b278714
refs/heads/master
<file_sep>#pragma once namespace Lab04GabrielSam1037420 { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; using namespace System::IO; /// <summary> /// Resumen de MyForm /// </summary> public ref class MyForm : public System::Windows::Forms::Form { public: MyForm(void) { InitializeComponent(); // //TODO: agregar código de constructor aquí // } protected: /// <summary> /// Limpiar los recursos que se estén usando. /// </summary> ~MyForm() { if (components) { delete components; } } private: System::Windows::Forms::TabControl^ tabControl1; protected: private: System::Windows::Forms::TabPage^ tabPage1; private: System::Windows::Forms::Button^ button1; private: System::Windows::Forms::DataGridView^ dgvMatriz; private: System::Windows::Forms::TabPage^ tabPage2; private: System::Windows::Forms::OpenFileDialog^ ofdImportar; private: System::Windows::Forms::SaveFileDialog^ sfdExportar; private: System::Windows::Forms::TextBox^ txtpa; private: System::Windows::Forms::Button^ button4; private: System::Windows::Forms::Button^ button3; private: System::Windows::Forms::Button^ button2; private: System::Windows::Forms::DataGridViewTextBoxColumn^ Column1; private: System::Windows::Forms::DataGridViewTextBoxColumn^ Column2; private: System::Windows::Forms::DataGridViewTextBoxColumn^ Column3; private: System::Windows::Forms::Button^ button5; private: System::Windows::Forms::DataGridView^ dgvMatriz2; private: System::Windows::Forms::Button^ button7; private: System::Windows::Forms::Button^ button6; private: /// <summary> /// Variable del diseñador necesaria. /// </summary> System::ComponentModel::Container ^components; #pragma region Windows Form Designer generated code /// <summary> /// Método necesario para admitir el Diseñador. No se puede modificar /// el contenido de este método con el editor de código. /// </summary> void InitializeComponent(void) { this->ofdImportar = (gcnew System::Windows::Forms::OpenFileDialog()); this->sfdExportar = (gcnew System::Windows::Forms::SaveFileDialog()); this->tabControl1 = (gcnew System::Windows::Forms::TabControl()); this->tabPage1 = (gcnew System::Windows::Forms::TabPage()); this->button4 = (gcnew System::Windows::Forms::Button()); this->button3 = (gcnew System::Windows::Forms::Button()); this->button2 = (gcnew System::Windows::Forms::Button()); this->txtpa = (gcnew System::Windows::Forms::TextBox()); this->button1 = (gcnew System::Windows::Forms::Button()); this->dgvMatriz = (gcnew System::Windows::Forms::DataGridView()); this->Column1 = (gcnew System::Windows::Forms::DataGridViewTextBoxColumn()); this->Column2 = (gcnew System::Windows::Forms::DataGridViewTextBoxColumn()); this->Column3 = (gcnew System::Windows::Forms::DataGridViewTextBoxColumn()); this->tabPage2 = (gcnew System::Windows::Forms::TabPage()); this->button5 = (gcnew System::Windows::Forms::Button()); this->dgvMatriz2 = (gcnew System::Windows::Forms::DataGridView()); this->button6 = (gcnew System::Windows::Forms::Button()); this->button7 = (gcnew System::Windows::Forms::Button()); this->tabControl1->SuspendLayout(); this->tabPage1->SuspendLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->dgvMatriz))->BeginInit(); this->tabPage2->SuspendLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->dgvMatriz2))->BeginInit(); this->SuspendLayout(); // // ofdImportar // this->ofdImportar->FileName = L"openFileDialog1"; // // tabControl1 // this->tabControl1->Controls->Add(this->tabPage1); this->tabControl1->Controls->Add(this->tabPage2); this->tabControl1->Location = System::Drawing::Point(27, 32); this->tabControl1->Name = L"tabControl1"; this->tabControl1->SelectedIndex = 0; this->tabControl1->Size = System::Drawing::Size(827, 506); this->tabControl1->TabIndex = 0; // // tabPage1 // this->tabPage1->Controls->Add(this->button4); this->tabPage1->Controls->Add(this->button3); this->tabPage1->Controls->Add(this->button2); this->tabPage1->Controls->Add(this->txtpa); this->tabPage1->Controls->Add(this->button1); this->tabPage1->Controls->Add(this->dgvMatriz); this->tabPage1->Location = System::Drawing::Point(4, 25); this->tabPage1->Name = L"tabPage1"; this->tabPage1->Padding = System::Windows::Forms::Padding(3); this->tabPage1->Size = System::Drawing::Size(819, 477); this->tabPage1->TabIndex = 0; this->tabPage1->Text = L"Problema 1"; this->tabPage1->UseVisualStyleBackColor = true; // // button4 // this->button4->Location = System::Drawing::Point(521, 263); this->button4->Name = L"button4"; this->button4->Size = System::Drawing::Size(234, 37); this->button4->TabIndex = 4; this->button4->Text = L"Quick"; this->button4->UseVisualStyleBackColor = true; // // button3 // this->button3->Location = System::Drawing::Point(521, 201); this->button3->Name = L"button3"; this->button3->Size = System::Drawing::Size(234, 37); this->button3->TabIndex = 3; this->button3->Text = L"Bubble"; this->button3->UseVisualStyleBackColor = true; this->button3->Click += gcnew System::EventHandler(this, &MyForm::button3_Click); // // button2 // this->button2->Location = System::Drawing::Point(521, 333); this->button2->Name = L"button2"; this->button2->Size = System::Drawing::Size(234, 37); this->button2->TabIndex = 3; this->button2->Text = L"Merge"; this->button2->UseVisualStyleBackColor = true; // // txtpa // this->txtpa->Location = System::Drawing::Point(498, 37); this->txtpa->Name = L"txtpa"; this->txtpa->Size = System::Drawing::Size(147, 22); this->txtpa->TabIndex = 2; // // button1 // this->button1->Location = System::Drawing::Point(679, 37); this->button1->Name = L"button1"; this->button1->Size = System::Drawing::Size(103, 37); this->button1->TabIndex = 1; this->button1->Text = L"Importar"; this->button1->UseVisualStyleBackColor = true; this->button1->Click += gcnew System::EventHandler(this, &MyForm::button1_Click); // // dgvMatriz // this->dgvMatriz->AllowUserToAddRows = false; this->dgvMatriz->ColumnHeadersHeightSizeMode = System::Windows::Forms::DataGridViewColumnHeadersHeightSizeMode::AutoSize; this->dgvMatriz->Columns->AddRange(gcnew cli::array< System::Windows::Forms::DataGridViewColumn^ >(3) { this->Column1, this->Column2, this->Column3 }); this->dgvMatriz->Location = System::Drawing::Point(22, 25); this->dgvMatriz->Name = L"dgvMatriz"; this->dgvMatriz->ReadOnly = true; this->dgvMatriz->RowHeadersWidth = 51; this->dgvMatriz->RowTemplate->Height = 24; this->dgvMatriz->Size = System::Drawing::Size(437, 435); this->dgvMatriz->TabIndex = 0; // // Column1 // this->Column1->HeaderText = L"Departamento"; this->Column1->MinimumWidth = 6; this->Column1->Name = L"Column1"; this->Column1->ReadOnly = true; this->Column1->Visible = false; this->Column1->Width = 125; // // Column2 // this->Column2->HeaderText = L"Año"; this->Column2->MinimumWidth = 6; this->Column2->Name = L"Column2"; this->Column2->ReadOnly = true; this->Column2->Visible = false; this->Column2->Width = 125; // // Column3 // this->Column3->HeaderText = L"Denuncias"; this->Column3->MinimumWidth = 6; this->Column3->Name = L"Column3"; this->Column3->ReadOnly = true; this->Column3->Visible = false; this->Column3->Width = 125; // // tabPage2 // this->tabPage2->Controls->Add(this->button7); this->tabPage2->Controls->Add(this->button6); this->tabPage2->Controls->Add(this->button5); this->tabPage2->Controls->Add(this->dgvMatriz2); this->tabPage2->Location = System::Drawing::Point(4, 25); this->tabPage2->Name = L"tabPage2"; this->tabPage2->Padding = System::Windows::Forms::Padding(3); this->tabPage2->Size = System::Drawing::Size(819, 477); this->tabPage2->TabIndex = 1; this->tabPage2->Text = L"Problema 2"; this->tabPage2->UseVisualStyleBackColor = true; // // button5 // this->button5->Location = System::Drawing::Point(675, 66); this->button5->Name = L"button5"; this->button5->Size = System::Drawing::Size(105, 29); this->button5->TabIndex = 1; this->button5->Text = L"Importar"; this->button5->UseVisualStyleBackColor = true; this->button5->Click += gcnew System::EventHandler(this, &MyForm::button5_Click); // // dgvMatriz2 // this->dgvMatriz2->ColumnHeadersHeightSizeMode = System::Windows::Forms::DataGridViewColumnHeadersHeightSizeMode::AutoSize; this->dgvMatriz2->Location = System::Drawing::Point(36, 32); this->dgvMatriz2->Name = L"dgvMatriz2"; this->dgvMatriz2->ReadOnly = true; this->dgvMatriz2->RowHeadersWidth = 51; this->dgvMatriz2->RowTemplate->Height = 24; this->dgvMatriz2->Size = System::Drawing::Size(594, 432); this->dgvMatriz2->TabIndex = 0; // // button6 // this->button6->Location = System::Drawing::Point(675, 171); this->button6->Name = L"button6"; this->button6->Size = System::Drawing::Size(105, 29); this->button6->TabIndex = 2; this->button6->Text = L"Bubble sort"; this->button6->UseVisualStyleBackColor = true; // // button7 // this->button7->Location = System::Drawing::Point(675, 234); this->button7->Name = L"button7"; this->button7->Size = System::Drawing::Size(105, 29); this->button7->TabIndex = 3; this->button7->Text = L"Quick sort"; this->button7->UseVisualStyleBackColor = true; // // MyForm // this->AutoScaleDimensions = System::Drawing::SizeF(8, 16); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->ClientSize = System::Drawing::Size(881, 550); this->Controls->Add(this->tabControl1); this->Name = L"MyForm"; this->Text = L"MyForm"; this->tabControl1->ResumeLayout(false); this->tabPage1->ResumeLayout(false); this->tabPage1->PerformLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->dgvMatriz))->EndInit(); this->tabPage2->ResumeLayout(false); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->dgvMatriz2))->EndInit(); this->ResumeLayout(false); } #pragma endregion private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) { ofdImportar->Filter = "Archivos separados por coma (csv) | *.csv"; ofdImportar->FileName = ""; if (ofdImportar->ShowDialog() == System::Windows::Forms::DialogResult::OK) { ReestablecerMatriz(); //Se elimina cualquier contenido de la matriz txtpa->Text = ofdImportar->FileName; //Se utiliza el objeto File para leer el archivo solo cuando el FileName es correcto //Importante haber llamado al namespace System::IO antes de usar File array<String^>^ archivoLineas = File::ReadAllLines(ofdImportar->FileName); if (archivoLineas->Length > 0) { //Obtiene la cantidad de elementos de la primer linea y ese toma como cantidad de columnas array<String^>^ archivoColumna = archivoLineas[0]->Split(';'); if (archivoColumna->Length > 0) { int cantidadColumnas = archivoColumna->Length; //Agrega las columnas for (int i = 0; i < cantidadColumnas; i++) { //Crea una columna DataGridViewColumn^ nuevacolumna = gcnew DataGridViewColumn(); nuevacolumna->Width = 100; //Le agrega el tipo de columna que será DataGridViewCell^ cellTemplate = gcnew DataGridViewTextBoxCell(); nuevacolumna->CellTemplate = cellTemplate; //Inserta la columna dgvMatriz->Columns->Add(nuevacolumna); } //Agrega las filas de manera dinámica for (int i = 0; i < archivoLineas->Length; i++) { dgvMatriz->Rows->Add(); } //Llena el DatagridView for (int i = 0; i < archivoLineas->Length; i++) { array<String^>^ fila = archivoLineas[i]->Split(';'); int j = 0; //Si alguna fila tiene más o menos objetos no afecta al funcionamiento ya que utiliza la cantidad de elementos de la primer fila while ((j < cantidadColumnas) && (j < fila->Length)) { dgvMatriz->Rows[i]->Cells[j]->Value = fila[j]; j++; } } } } } else { // Si no se selecciona correctamente un elemento entonces falla MessageBox::Show("No se seleccionó ningún archivo" , "Archivo no seleccionado" , MessageBoxButtons::OK , MessageBoxIcon::Exclamation); } } private: void ReestablecerMatriz() { dgvMatriz->Rows->Clear(); dgvMatriz->Columns->Clear(); dgvMatriz->ColumnHeadersVisible = false; dgvMatriz->RowHeadersVisible = false; }; private: System::Void button3_Click(System::Object^ sender, System::EventArgs^ e) { array<String^>^ archivoLineas = File::ReadAllLines(ofdImportar->FileName); array<String^>^ fila; int aux; for (int i = 0; i < 240; i++) { fila = archivoLineas[i]->Split(';'); for (int j = 0; j < 240; j++) { if (Convert::ToInt32(fila[j]) > Convert::ToInt32(fila[j + 1])) { aux = Convert::ToInt32(fila[j]); fila[j] = fila[j + 1]; fila[j + 1] = Convert::ToString(aux); } } } ReestablecerMatriz(); for (int i = 0; i < archivoLineas->Length; i++) { int j = 0; //Si alguna fila tiene más o menos objetos no afecta al funcionamiento ya que utiliza la cantidad de elementos de la primer fila while ((j < 3) && (j < fila->Length)) { dgvMatriz->Rows[i]->Cells[j]->Value = fila[j]; j++; } } } private: System::Void button5_Click(System::Object^ sender, System::EventArgs^ e) { ofdImportar->Filter = "Archivos separados por coma (csv) | *.csv"; ofdImportar->FileName = ""; if (ofdImportar->ShowDialog() == System::Windows::Forms::DialogResult::OK) { ReestablecerMatriz(); //Se elimina cualquier contenido de la matriz txtpa->Text = ofdImportar->FileName; //Se utiliza el objeto File para leer el archivo solo cuando el FileName es correcto //Importante haber llamado al namespace System::IO antes de usar File array<String^>^ archivoLineas = File::ReadAllLines(ofdImportar->FileName); if (archivoLineas->Length > 0) { //Obtiene la cantidad de elementos de la primer linea y ese toma como cantidad de columnas array<String^>^ archivoColumna = archivoLineas[0]->Split(';'); if (archivoColumna->Length > 0) { int cantidadColumnas = archivoColumna->Length; //Agrega las columnas for (int i = 0; i < cantidadColumnas; i++) { //Crea una columna DataGridViewColumn^ nuevacolumna = gcnew DataGridViewColumn(); nuevacolumna->Width = 100; //Le agrega el tipo de columna que será DataGridViewCell^ cellTemplate = gcnew DataGridViewTextBoxCell(); nuevacolumna->CellTemplate = cellTemplate; //Inserta la columna dgvMatriz2->Columns->Add(nuevacolumna); } //Agrega las filas de manera dinámica for (int i = 0; i < archivoLineas->Length; i++) { dgvMatriz2->Rows->Add(); } //Llena el DatagridView for (int i = 0; i < archivoLineas->Length; i++) { array<String^>^ fila = archivoLineas[i]->Split(';'); int j = 0; //Si alguna fila tiene más o menos objetos no afecta al funcionamiento ya que utiliza la cantidad de elementos de la primer fila while ((j < cantidadColumnas) && (j < fila->Length)) { dgvMatriz2->Rows[i]->Cells[j]->Value = fila[j]; j++; } } } } } else { // Si no se selecciona correctamente un elemento entonces falla MessageBox::Show("No se seleccionó ningún archivo" , "Archivo no seleccionado" , MessageBoxButtons::OK , MessageBoxIcon::Exclamation); } } }; }
99a2b11ebf827d5b8c51afec3991cc9a3d14f1b9
[ "C++" ]
1
C++
Gaboseb5/Lab04_Gabriel_Sam_1037420
50822bd49687d88a57ed79a26daf6abb5a9cbcd4
3d869849edfcdbf8b74d754297d6d75f38a9f1d3
refs/heads/master
<repo_name>manish-verma0/Fragment<file_sep>/app/src/main/java/com/example/fragment/BlankFragment3.java package com.example.fragment; import android.content.Context; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class BlankFragment3 extends Fragment { public BlankFragment3() { } @Override public void onStart() { Log.d("abc", "onStart frag 3 "); super.onStart(); } @Override public void onResume() { Log.d("abc", "onResume frag 3 "); super.onResume(); } @Override public void onPause() { Log.d("abc", "onPause frag 3 "); super.onPause(); } @Override public void onStop() { Log.d("abc", "onStop frag 3 "); super.onStop(); } @Override public void onAttach(@NonNull Context context) { Log.d("abc", "onAttach frag 3 "); super.onAttach(context); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { Log.d("abc", "onCreate frag 3 "); super.onCreate(savedInstanceState); } @Override public void onDestroyView() { Log.d("abc", "onDestroyView frag 3: "); super.onDestroyView(); } @Override public void onDestroy() { Log.d("abc", "onDestroy frag 3"); super.onDestroy(); } @Override public void onDetach() { Log.d("abc", "onDetach frag 3 "); super.onDetach(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.d("abc", "onCreateView frag 3 "); return inflater.inflate(R.layout.fragment_blank3, container, false); } }
db9506bd1ed5976683c88ecfb4869e3fb92a1974
[ "Java" ]
1
Java
manish-verma0/Fragment
2506ff184ce4a86682a2ce884b1eb25377e5e22f
1b9ef12df3882b191eb846dd0854cf646cd4b16c
refs/heads/master
<repo_name>buha/util<file_sep>/README.md # util Useful and reusable bits of code <file_sep>/control/pid/pid.h #include <stdlib.h> #include <stdio.h> #include <stdint.h> struct pid_range { int high; int low; }; struct pid_config { unsigned int Kp; // proportional gain (micro-units) unsigned int Ki; // integral gain (micro-units) unsigned int Kd; // derivative gain (micro-units) unsigned int hysteresis; // control supressed when process variable is within set point +/- hysteresis struct pid_range i_clip; // boundary limits for integral component struct pid_range output_clip; // boundary limits for the output int initial; // initial output }; struct pid; void pid_init(struct pid **pid, struct pid_config config); int pid_control(struct pid *pid, int SP, int PV); <file_sep>/control/pid/pid.c #include "pid.h" #include <stdlib.h> struct pid { int iacc; // integral accumulator int dacc; // derivative accumulator int64_t output; struct pid_config config; }; void pid_init(struct pid **pid, struct pid_config config) { if (!pid) return; if (config.output_clip.high < config.output_clip.low) return; *pid = calloc(1, sizeof(struct pid)); if (!*pid) return; (*pid)->config = config; (*pid)->output = config.initial; (*pid)->iacc = 0; (*pid)->dacc = 0; } int pid_control(struct pid *pid, int SP, int PV) { int ERR; // error int64_t P; // proportional component int64_t I; // integral component int64_t D; // derivative component struct pid_range *i_clip = &pid->config.i_clip; struct pid_range *output_clip = &pid->config.output_clip; // error is the difference between the set point and process variable ERR = SP - PV; // don't control (maintain output) if within hysteresis range if (abs(ERR) < pid->config.hysteresis) { printf("SP: %d PV: %d --> output: %lu for ERR=%d\n", SP, PV, pid->output, ERR); return pid->output; } // compute proportional component P = (int64_t)pid->config.Kp * ERR; // clip integrator accumulator if enabled and if needed if (i_clip->high > i_clip->low) { if (pid->iacc > i_clip->high) pid->iacc = i_clip->high; else if (pid->iacc < i_clip->low) pid->iacc = i_clip->low; } // compute integral component I = (int64_t)pid->config.Ki * pid->iacc; // compute the derivative component D = (int64_t)pid->config.Kd * (pid->dacc - ERR); // compute the output pid->output = (pid->output * 1000000 - (P + I + D)) / 1000000; printf("SP: %d PV: %d --> output: %ld for P %ld I %ld D %ld ERR=%d\n", SP, PV, pid->output, P, I, D, ERR); // clip the output if enabled and if needed if (output_clip->high > output_clip->low) { if (pid->output > output_clip->high) pid->output = output_clip->high; else if (pid->output < output_clip->low) pid->output = output_clip->low; } // keep track of error history in the integrator accumulator pid->iacc += ERR; // keep track of process variable change rate in the derivative accumulator pid->dacc = ERR; return pid->output; } <file_sep>/filter/ema/ema.c /* Exponential moving average The formula for the calculation is: y[n] = alpha * x[n] + (1 - alpha) * y[n-1] Where: y[n] - current output y[n-1] - previous output x[n] - current input alpha - number in range [0...1] This is a natural (readable, not optimized) floating point implementation. MIT License Copyright (c) 2020 <NAME> (<EMAIL>) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdlib.h> #include "ema.h" int ema_init(ema_t ** emah, float alpha) { if(emah == NULL) return -1; *emah = calloc(1, sizeof(ema_t)); if(*emah == NULL) return -2; (*emah)->alpha = alpha; (*emah)->last = 0.0; return 0; } float ema(ema_t * emah, float sample) { if(emah == NULL) return -1; float ema = emah->alpha * sample + (1.0 - emah->alpha) * emah->last; emah->last = ema; return ema; } int ema_deinit(ema_t * emah) { if(emah == NULL) return -1; free(emah); return 0; } <file_sep>/control/pid/main.c #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include "ema.h" #include "pid.h" #define SAMPLES 100 #define ARRAY_SIZE(x) sizeof(x) / sizeof(x[0]) int main() { char * commandsForGnuplot[] = { "set grid", "set lmargin at screen 0.1", "set multiplot layout 2, 1 ;" "set yrange [0:31];", "plot 'attn.data' with lines", "set yrange [0:1000];", "plot 'adc.data' with lines", "unset multiplot", }; FILE * fattn = fopen("attn.data", "w"); FILE * fadc = fopen("adc.data", "w"); FILE * gnuplotPipe = popen ("gnuplot -persistent", "w"); int attn[SAMPLES]; // RF ATTN int adc[SAMPLES]; // ADC int i; ema_t *model; ema_init(&model, 0.99); struct pid_config config = { .Kp = 15000, .Ki = 5000, .Kd = 0, .initial = 31, .hysteresis = 20, .i_clip = { .high = 100, .low = -100 }, .output_clip = { .high = 31, .low = 0 } }; struct pid *controller; pid_init(&controller, config); for (i = 0; i <= SAMPLES; i++) { if (i == 0) { adc[i] = ema(model, (31 - config.initial) * 1000 / 32); attn[i] = config.initial; } else { // simulate the device behavior based on what pid previously output adc[i] = ema(model, (31 - attn[i - 1]) * 1000 / 32); // simulate disturbances if (i==40) adc[i] = 0; if (i==60) adc[i] = 1000; // run the pid control algorithm attn[i] = pid_control(controller, 359, adc[i]); } fprintf(fadc, "%lu %ld \n", i, adc[i]); fprintf(fattn, "%lu %lu \n", i, attn[i]); } // feed commands to gnuplot for (i=0; i < ARRAY_SIZE(commandsForGnuplot); i++) { fprintf(gnuplotPipe, "%s \n", commandsForGnuplot[i]); } return 0; }
a9a87b48869018c3fdae37a77a2d473e18f7c06f
[ "Markdown", "C" ]
5
Markdown
buha/util
adb16d5d1a2062f1746cec86fec7de18ad2f7c99
6973abbf8f52728f3be952caf7f471ffcd2b58bd
refs/heads/master
<repo_name>vmonestel/CarND-Kidnapped-Vehicle-Project<file_sep>/src/particle_filter.cpp /* * particle_filter.cpp * * Created on: Dec 12, 2016 * Author: <NAME> */ #include <random> #include <algorithm> #include <iostream> #include <numeric> #include <math.h> #include <iostream> #include <sstream> #include <string> #include <iterator> #include "particle_filter.h" #define NUM_PARTICLES 50 using namespace std; void ParticleFilter::init(double x, double y, double theta, double std[]) { // Check is_initialized flag if (is_initialized) { return; } // Create the class to generate random numbers default_random_engine generator; // Set the number of particles num_particles = NUM_PARTICLES; // Get the standard deviations from input double std_x = std[0]; double std_y = std[1]; double std_theta = std[2]; // Create normal distributions for x,y,theta based on GPS input normal_distribution<double> dist_x(x, std_x); normal_distribution<double> dist_y(y, std_y); normal_distribution<double> dist_theta(theta, std_theta); // Initialize all the particles with the normal distribution with mean on GPS values. for (int i = 0; i < num_particles; i++) { // Create a new particle instance Particle new_particle; // Assign particle values (id,x,y,theta,weight) new_particle.id = i; new_particle.x = dist_x(generator); new_particle.y = dist_y(generator); new_particle.theta = dist_theta(generator); new_particle.weight = 1.0; // Add the new particle to the vector particles.push_back(new_particle); // Add the particle weight to the vector weights.push_back(new_particle.weight); } // Set initialized flag to true is_initialized = true; } void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate) { // Create the class to generate random numbers default_random_engine generator; // Theta to predict the state double theta; // Create normal distributions for x,y,theta based on GPS input normal_distribution<double> dist_x(0, std_pos[0]); normal_distribution<double> dist_y(0, std_pos[1]); normal_distribution<double> dist_theta(0, std_pos[2]); // Calculate the new state (x,y,theta) for (int i = 0; i < num_particles; i++) { theta = particles[i].theta; if (fabs(yaw_rate) < 0.0001 ) { // yaw is not changing (yaw rate is very near to 0) particles[i].x += velocity * delta_t * cos(theta); particles[i].y += velocity * delta_t * sin(theta); } else { // yaw rate is different than 0 particles[i].x += velocity / yaw_rate * (sin(theta + yaw_rate * delta_t) - sin(theta)); particles[i].y += velocity / yaw_rate * (-cos(theta + yaw_rate * delta_t) + cos(theta)); particles[i].theta += yaw_rate * delta_t; } // Add random Noise particles[i].x += dist_x(generator); particles[i].y += dist_y(generator); particles[i].theta += dist_theta(generator); } } void ParticleFilter::dataAssociation(std::vector<LandmarkObs> predicted, std::vector<LandmarkObs>& observations) { /* * Associate observations in map co-ordinates to predicted landmarks using nearest neighbor algorithm. * Here, the number of observations may be less than the total number of landmarks as some of the landmarks * may be outside the range of vehicle's sensor. * */ for (unsigned int observation_idx = 0; observation_idx < observations.size(); observation_idx++) { // Initialize the minimum distance to a big number. double min_distance = numeric_limits<double>::max(); // Initialize the landmark id to something invalid int landmark_id = -1; double observation_x = observations[observation_idx].x; double observation_y = observations[observation_idx].y; for (unsigned int prediction_idx = 0; prediction_idx < predicted.size(); prediction_idx++) { // Compute the distance between the oservation and the prediction double distance = dist(observation_x, observation_y, predicted[prediction_idx].x, predicted[prediction_idx].y); // Check if distance is less than the previous min_distance if (distance < min_distance) { min_distance = distance; landmark_id = predicted[prediction_idx].id; } } // Update the observation identifier. observations[observation_idx].id = landmark_id; } } void ParticleFilter::updateWeights(double sensor_range, double std_landmark[], const std::vector<LandmarkObs> &observations, const Map &map_landmarks) { double weight_normalizer = 0.0; for (int particle_index = 0; particle_index < num_particles; particle_index++) { // Get particle data double particle_x = particles[particle_index].x; double particle_y = particles[particle_index].y; double particle_theta = particles[particle_index].theta; // Map the observations from vehicle to map coordinates. vector<LandmarkObs> transformed_observations; for (unsigned int observation_idx = 0; observation_idx < observations.size(); observation_idx++) { LandmarkObs transformed_obs; transformed_obs.id = observation_idx; transformed_obs.x = particle_x + (cos(particle_theta) * observations[observation_idx].x) - (sin(particle_theta) * observations[observation_idx].y); transformed_obs.y = particle_y + (sin(particle_theta) * observations[observation_idx].x) + (cos(particle_theta) * observations[observation_idx].y); transformed_observations.push_back(transformed_obs); } // Filter map landmarks vector<LandmarkObs> predicted_landmarks; for (unsigned int landmark_idx = 0; landmark_idx < map_landmarks.landmark_list.size(); landmark_idx++) { Map::single_landmark_s current_landmark = map_landmarks.landmark_list[landmark_idx]; if ((fabs((particle_x - current_landmark.x_f)) <= sensor_range) && (fabs((particle_y - current_landmark.y_f)) <= sensor_range)) { predicted_landmarks.push_back(LandmarkObs {current_landmark.id_i, current_landmark.x_f, current_landmark.y_f}); } } // Associate data observation to predicted landmarks by calling dataAssociation dataAssociation(predicted_landmarks, transformed_observations); // Compute the new weight of each particle particles[particle_index].weight = 1.0; double sigma_x = std_landmark[0]; double sigma_y = std_landmark[1]; double sigma_x_square = pow(sigma_x, 2); double sigma_y_square = pow(sigma_y, 2); double normalizer = (1.0 / (2.0 * M_PI * sigma_x * sigma_y)); // Calculate the weight of each particle based on the multivariate Gaussian probability function for (unsigned int observation_idx = 0; observation_idx < transformed_observations.size(); observation_idx++) { double trans_obs_x = transformed_observations[observation_idx].x; double trans_obs_y = transformed_observations[observation_idx].y; double trans_obs_id = transformed_observations[observation_idx].id; double multi_prob = 1.0; for (unsigned int landmark_idx = 0; landmark_idx < predicted_landmarks.size(); landmark_idx++) { double pred_landmark_x = predicted_landmarks[landmark_idx].x; double pred_landmark_y = predicted_landmarks[landmark_idx].y; double pred_landmark_id = predicted_landmarks[landmark_idx].id; if (trans_obs_id == pred_landmark_id) { multi_prob = normalizer * exp(-1.0 * ((pow((trans_obs_x - pred_landmark_x), 2)/ (2.0 * sigma_x_square)) + (pow((trans_obs_y - pred_landmark_y), 2)/(2.0 * sigma_y_square)))); particles[particle_index].weight *= multi_prob; } } } weight_normalizer += particles[particle_index].weight; } // Normalize the weights of all particles for (unsigned int particle_index = 0; particle_index < particles.size(); particle_index++) { particles[particle_index].weight /= weight_normalizer; weights[particle_index] = particles[particle_index].weight; } } void ParticleFilter::resample() { /* * Re-sample particles with replacement with probability proportional to their weight. */ vector<Particle> resampled_particles; // Create the class to generate random numbers default_random_engine gen; // Generate random particle index uniform_int_distribution<int> particle_index(0, num_particles - 1); int current_index = particle_index(gen); double beta = 0.0; double max_weight_2 = 2.0 * *max_element(weights.begin(), weights.end()); for (unsigned int i = 0; i < particles.size(); i++) { uniform_real_distribution<double> random_weight(0.0, max_weight_2); beta += random_weight(gen); while (beta > weights[current_index]) { beta -= weights[current_index]; current_index = (current_index + 1) % num_particles; } resampled_particles.push_back(particles[current_index]); } particles = resampled_particles; } Particle ParticleFilter::SetAssociations(Particle& particle, const std::vector<int>& associations, const std::vector<double>& sense_x, const std::vector<double>& sense_y) { //particle: the particle to assign each listed association, and association's (x,y) world coordinates mapping to // associations: The landmark id that goes along with each listed association // sense_x: the associations x mapping already converted to world coordinates // sense_y: the associations y mapping already converted to world coordinates particle.associations= associations; particle.sense_x = sense_x; particle.sense_y = sense_y; return particle; } string ParticleFilter::getAssociations(Particle best) { vector<int> v = best.associations; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<int>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; } string ParticleFilter::getSenseX(Particle best) { vector<double> v = best.sense_x; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; } string ParticleFilter::getSenseY(Particle best) { vector<double> v = best.sense_y; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; }
341885e10596a70c9e3ed4a4bc1718e1b3707f4e
[ "C++" ]
1
C++
vmonestel/CarND-Kidnapped-Vehicle-Project
698556eb60eaedfec45a40ee1b47eb01b8dfb5aa
3a60495afa09c8bed2e7d214a541fbd27615fe60
refs/heads/master
<file_sep>def find_space(x): return { 1 : " ", 2 : " ", 3 : " " }[x] for number in range(1,13): output_string = "" for multiple in range(1,13): the_space = find_space(len(str(multiple*number))) output_string += str(number*multiple) + the_space output_string = output_string.strip() print(output_string)
520818f4477da673f98404109a171798328bbf5a
[ "Python" ]
1
Python
peterleh/code-eval-multiplication-table
4738c8876aa621b62225af2371d58e30d56b407a
0cf3ccd7520bebcc8bc5ddba7d1ac8f528ab8c17
refs/heads/master
<file_sep>// @flow import moment from 'moment'; import DateFormat from './DateFormat'; export default class DateUtils { /** * Given a JavaScript Date object, return a formatted date in the specified * locale using the format specified. */ static formatDate(date: Date, format: DateFormat, locale: string = 'en'): string { const m = moment(date).locale(locale); switch (format) { case DateFormat.ATTIVIO: return m.format(); case DateFormat.SHORT_DATE: return m.format('L'); case DateFormat.MEDIUM_DATE: return m.format('ll'); case DateFormat.LONG_DATE: return m.format('dddd, LL'); case DateFormat.SHORT_TIME: return m.format('LT'); case DateFormat.LONG_TIME: return m.format('LTS'); case DateFormat.SHORT_MONTH: return m.format('MMM. YYYY'); case DateFormat.LONG_MONTH: return m.format('MMMM YYYY'); case DateFormat.SHORT_YEAR: return m.format('’YY'); case DateFormat.LONG_YEAR: return m.format('YYYY'); case DateFormat.SHORT: return m.format('L LT'); case DateFormat.MEDIUM: return m.format('lll'); case DateFormat.LONG: return m.format('LLLL'); case DateFormat.AGO: return m.fromNow(); case DateFormat.IN: return m.toNow(); case DateFormat.ISO_8601: default: return m.format(); } } /** * Given a string, return a Date object created by parsing it. */ static stringToDate(dateString: string): Date { return moment(dateString).toDate(); } /** * Given a string, return a formatted date in the specified locale using * the format specified. */ static formatDateString(dateString: string | null, format: DateFormat, locale: string = 'en'): string { if (dateString) { const date = DateUtils.stringToDate(dateString); return DateUtils.formatDate(date, format, locale); } return ''; } } <file_sep>// @flow import FacetFilter from './FacetFilter'; import AuthUtils from '../util/AuthUtils'; /** * An object that embodies the various parameters needed to * make a query of the Attivio index. */ export default class SimpleQueryRequest { constructor( q: string = '*:*', wf: string = 'search', ql: 'simple' | 'advanced' = 'simple', l: string = 'en', r: number = 10, flt: Array<string> = [], f: Array<string> = [], s: Array<string> = [], fds: Array<string> = [], un: string | null = null, rlm: string | null = null, ff: Array<FacetFilter> = [], rp: Map<string, Array<string>> = new Map(), ) { this.query = q; this.workflow = wf; this.queryLanguage = ql; this.locale = l; this.rows = r; this.filters = flt; this.facets = f; this.sort = s; this.fields = fds; this.facetFilters = ff; this.restParams = rp; if (un === null) { this.username = AuthUtils.getConfig().ALL.defaultUsername; } else { this.username = un; } if (rlm === null) { this.realm = AuthUtils.getConfig().ALL.defaultRealm; } else { this.realm = rlm; } } /** The workflow to use when processing the query */ workflow: string; /** The query string */ query: string; /** Whether the query is in Simple Query Language or Advanced Query Language */ queryLanguage: 'simple' | 'advanced'; /** The locale to use when performing the query */ locale: string; /** The number of documents to return with the query results */ rows: number; /** Any filters to apply to the query */ filters: Array<string>; /** Which facets you want to have returned with the resuls */ facets: Array<string>; /** How you want the query results sorted */ sort: Array<string>; /** The fields to return for each document */ fields: Array<string>; /** The name of the user peroforming the query */ username: string; /** The user's realm */ realm: string; /** Any facet filters to apply to the query */ facetFilters: Array<FacetFilter>; /** Any additional REST parameters to pass. Note that the values MUST be arrays, even if there's only one instance. */ restParams: Map<string, Array<string>>; } <file_sep>// @flow export default class StringUtils { /** * Simply format a string/number combination based on the * value of the number. The format parameter is a string * containing multiple formatting templates separated by * a pipe character (|). If there are two parts, then the * first part is used if the value is 1 and the second part * is used if the value is not 1 (e.g., 0 or > 1). If there * are three parts, then the first is used if the value is * 0, the second if the value is 1 and the third if the * value is > 1. (If there is only one part, then it's used * in all cases.) * * In any case, if the part of the string being used contains * the charaters '{}', that is substituted with the number * itself, as a string. * * @param {*} format the format string * @param {*} value the numeric value to switch on/replace with */ static fmt(format: string, value: number) { let pieceForValue; const pieces = format.split('|'); if (pieces.length === 1) { pieceForValue = pieces[0]; } else if (pieces.length === 2) { if (value === 1) { pieceForValue = pieces[0]; } else { pieceForValue = pieces[1]; } } else if (value === 0) { pieceForValue = pieces[0]; } else if (value === 1) { pieceForValue = pieces[1]; } else { pieceForValue = pieces[2]; } const valueString = value.toString(); return pieceForValue.replace('{}', valueString); } static regexLastIndexOf(s: string, regex: RegExp, startPos: number | null = null) { const sp = startPos !== null ? startPos : s.length; let re; if (regex.global) { re = regex; } else { let flags; // (this rigamarole is required to make Flow happy) if (regex.ignoreCase && regex.multiline) { flags = 'gim'; } else if (regex.ignoreCase) { flags = 'gi'; } else if (regex.multiline) { flags = 'gm'; } else { flags = 'g'; } re = new RegExp(regex.source, flags); } const stringToWorkWith = s.substring(0, sp + 1); let lastIndexOf = -1; let nextStop = 0; let result = 1; while (result !== null) { result = re.exec(stringToWorkWith); if (result !== null) { lastIndexOf = result.index; nextStop += 1; re.lastIndex = nextStop; } } return lastIndexOf; } static stripSimpleHtml(orig: string): string { const div = document.createElement('div'); div.innerHTML = orig; const text = div.textContent || div.innerText || ''; return text; } /** * Truncate the passed-in string so it is no longer than the number of * characters specified by maxLen. The truncation will happen at a word * boundary, if possible. Unless otherwise specified, an ellipsis * is appended to the resulting string. */ static smartTruncate(orig: string, maxLen: number, ellipsis: boolean = true):string { if (orig.length < maxLen) { return orig; } // We check the first maxLen + 1 characters in case maxLen is the end of a word. const firstChunk = orig.substring(0, maxLen + 1); const lastWS = StringUtils.regexLastIndexOf(firstChunk, /\s/g); let result; if (lastWS >= 0) { // We found a whitespace character, so we'll break there. result = orig.substring(0, lastWS).trim(); } else { result = orig.substring(0, maxLen).trim(); } if (ellipsis) { result = `${result}…`; } return result; } /** * Split the string onto multiple lines, separated with the * given character, if the given limit is reached. */ static wrapLabel(orig: string, newLine: string = '\n', limit: number = 50): string { const s = String(orig); if (s.length < limit) { return s; } const firstChunk = s.substring(0, limit); const lastWS = StringUtils.regexLastIndexOf(firstChunk, /\s/g); let firstLine; let remainder; if (lastWS >= 0) { // We found a whitespace character, so we'll break there. firstLine = s.substring(0, lastWS).trim(); remainder = s.substring(lastWS).trim(); } else { firstLine = firstChunk; remainder = s.substring(limit).trim(); } if (remainder.length === 0) { // If the trimmed remainder is empty, then just return the part we found. return firstLine; } return `${firstLine}\n${StringUtils.wrapLabel(remainder, newLine, limit)}`; } /** * Returns true if the value is a string and it is has a length greater than 0. */ static notEmpty(value: any): boolean { return value && (typeof value === 'string' || value instanceof String) && value.length > 0; } } <file_sep>// @flow import React from 'react'; /** * Header for the Experts page. */ export default class ExpertsHeader extends React.Component<void, {}, void> { render() { return ( <div className="attivio-expert-hed"> <h2 className="attivio-expert-hed-title pull-left">Top Experts:</h2> <a className="attivio-expert-hed-link pull-right"><strong>All Experts…</strong></a> </div> ); } } <file_sep>// @flow import React from 'react'; import PropTypes from 'prop-types'; import SearchFacet from '../api/SearchFacet'; import SearchFacetBucket from '../api/SearchFacetBucket'; import DateUtils from '../util/DateUtils'; import DateFormat from '../util/DateFormat'; import Card from './Card'; import CollapsiblePanel from './CollapsiblePanel'; import BarChartFacetContents from './BarChartFacetContents'; import PieChartFacetContents from './PieChartFacetContents'; import MoreListFacetContents from './MoreListFacetContents'; import ListWithBarsFacetContents from './ListWithBarsFacetContents'; import TagCloudFacetContents from './TagCloudFacetContents'; import TimeSeriesFacetContents from './TimeSeriesFacetContents'; import SentimentFacetContents from './SentimentFacetContents'; import MapFacetContents from './MapFacetContents'; import FacetSearchBar from './FacetSearchBar'; type FacetProps = { /** The facet to display. */ facet: SearchFacet; /** The way the facet information should be displayed. Defaults to 'list' */ type: 'barchart' | 'columnchart' | 'piechart' | 'barlist' | 'tagcloud' | 'timeseries' | 'list' | 'sentiment' | 'geomap'; /** * The maximum number of items to show in a facet. If there * are more than this many buckets for the facet, only this many, with * the highest counts, will be shown. Defaults to 15. */ maxBuckets: number; /** * If set, then the facet will be displayed in a collapsible component. If * the facet is collapsible and has no buckets, it will be collapsed initially. */ collapse: boolean; /** If set, then the facet will be displayed in a card which has a border around it */ bordered: boolean; /** Controls the colors used to show various entity types (the value can be any valid CSS color) */ entityColors: Map<string, string>; } type FacetDefaultProps = { type: 'barchart' | 'columnchart' | 'piechart' | 'barlist' | 'tagcloud' | 'timeseries' | 'list' | 'sentiment' | 'geomap'; maxBuckets: number; collapse: boolean; bordered: boolean; entityColors: Map<string, string>; }; /** * Display a single facet from the search results. */ export default class Facet extends React.Component<FacetDefaultProps, FacetProps, void> { static defaultProps = { type: 'list', maxBuckets: 15, collapse: false, bordered: false, entityColors: new Map(), }; static contextTypes = { searcher: PropTypes.any, }; constructor(props: FacetProps) { super(props); (this: any).addFacetFilter = this.addFacetFilter.bind(this); (this: any).addTimeSeriesFilter = this.addTimeSeriesFilter.bind(this); } addFacetFilter(bucket: SearchFacetBucket, customBucketLabel: ?string) { const bucketLabel = customBucketLabel || bucket.displayLabel(); this.context.searcher.addFacetFilter(this.props.facet.findLabel(), bucketLabel, bucket.filter); } /** * Create a facet filter for the starting and ending dates... * If start is set but end is not, filters on the specific time * set by start, otherwises filters on the range. (If start is not * set, this simply returns). */ addTimeSeriesFilter(start: Date | null, end: Date | null) { if (start !== null) { let facetFilterString; let labelString; const startFacetFilterString = DateUtils.formatDate(start, DateFormat.ATTIVIO); const startLabelString = DateUtils.formatDate(start, DateFormat.MEDIUM); if (end !== null) { const endFacetFilterString = DateUtils.formatDate(end, DateFormat.ATTIVIO); const endLabelString = DateUtils.formatDate(end, DateFormat.MEDIUM); labelString = `${startLabelString} to ${endLabelString}`; facetFilterString = `${this.props.facet.name}:FACET(RANGE("${startFacetFilterString}", "${endFacetFilterString}", upper=inclusive))`; // eslint-disable-line max-len } else { labelString = startLabelString; facetFilterString = `${this.props.facet.name}:FACET(RANGE("${startFacetFilterString}", ${startFacetFilterString}, upper=inclusive))`; // eslint-disable-line max-len } this.context.searcher.addFacetFilter(this.props.facet.findLabel(), labelString, facetFilterString); } } render() { const facetColors = this.props.entityColors; const facetColor = facetColors.has(this.props.facet.field) ? facetColors.get(this.props.facet.field) : null; let facetContents; if (this.props.facet.buckets && this.props.facet.buckets.length > 0) { switch (this.props.type) { case 'barchart': facetContents = facetColor ? ( <BarChartFacetContents buckets={this.props.facet.buckets} addFacetFilter={this.addFacetFilter} color={facetColor} /> ) : ( <BarChartFacetContents buckets={this.props.facet.buckets} addFacetFilter={this.addFacetFilter} /> ); break; case 'columnchart': facetContents = facetColor ? ( <BarChartFacetContents buckets={this.props.facet.buckets} addFacetFilter={this.addFacetFilter} columns color={facetColor} /> ) : ( <BarChartFacetContents buckets={this.props.facet.buckets} addFacetFilter={this.addFacetFilter} columns /> ); break; case 'piechart': facetContents = ( <PieChartFacetContents buckets={this.props.facet.buckets} addFacetFilter={this.addFacetFilter} entityColors={this.props.entityColors} /> ); break; case 'barlist': facetContents = facetColor ? ( <ListWithBarsFacetContents buckets={this.props.facet.buckets} addFacetFilter={this.addFacetFilter} color={facetColor} /> ) : ( <ListWithBarsFacetContents buckets={this.props.facet.buckets} addFacetFilter={this.addFacetFilter} /> ); break; case 'tagcloud': facetContents = ( <TagCloudFacetContents buckets={this.props.facet.buckets} maxBuckets={this.props.maxBuckets} addFacetFilter={this.addFacetFilter} /> ); break; case 'timeseries': facetContents = <TimeSeriesFacetContents buckets={this.props.facet.buckets} addFacetFilter={this.addTimeSeriesFilter} />; break; case 'sentiment': facetContents = <SentimentFacetContents buckets={this.props.facet.buckets} addFacetFilter={this.addFacetFilter} />; break; case 'geomap': facetContents = <MapFacetContents buckets={this.props.facet.buckets} addFacetFilter={this.addFacetFilter} />; break; case 'list': default: facetContents = <div> <FacetSearchBar name={this.props.facet.field} label={this.props.facet.label} addFacetFilter={this.addFacetFilter} maxValues={5}/> <MoreListFacetContents buckets={this.props.facet.buckets} addFacetFilter={this.addFacetFilter} /></div>; break; } } else { facetContents = <span className="none">No values for this facet.</span>; } // Prefer the display name but fall back to the name field (note special case for geomaps // where we always use the label "Map"). const label = this.props.type === 'geomap' ? 'Map' : this.props.facet.findLabel(); if (this.props.collapse) { const collapsed = this.props.facet.buckets.length === 0; return ( <CollapsiblePanel title={label} id={`facet-${this.props.facet.field}`} collapsed={collapsed}> {facetContents} </CollapsiblePanel> ); } return ( <Card title={label} borderless={!this.props.bordered} className="attivio-facet"> {facetContents} </Card> ); } }
84b8e214889bf8344ada5751e5fd94d6ea115f35
[ "JavaScript" ]
5
JavaScript
brandon-bogan/support-demo-suit
83f90391b75adce289787688dac42d3387418d17
f44e5f569ab6cf750b4d61f80515f524264712ee
refs/heads/master
<repo_name>shubhamaryan001/Deplay-node<file_sep>/routes/coupon.js const express = require('express') const router = express.Router() const { create, deactivate, remove, list, find } = require('../controllers/coupon') const { requireSignin, isAuth, isAdmin } = require('../controllers/auth') router.post('/coupon/create', requireSignin, create) router.put('/coupon/deactivate/:code', requireSignin, deactivate) router.delete('/coupon/:code', requireSignin, remove) router.get('/coupon/:code', find) router.get('/coupon', list) module.exports = router <file_sep>/controllers/order.js const { Order, CartItem } = require("../models/order"); const { errorHandler } = require("../helpers/dbErrorHandler"); const nodemailer = require("nodemailer"); const defaultEmailData = { from: "<EMAIL>" }; const sgMail = require('@sendgrid/mail'); const sgTransport = require('nodemailer-sendgrid-transport'); const accountSid = 'AC8641b461a07dfa36d3b840ca8f6b8917'; const authToken = '<KEY>'; const unirest = require("unirest"); const twilio = require('twilio'); const clientwhat = require('twilio')(accountSid, authToken); // const trasporter = nodemailer.createTransport({ // host: "smtp.gmail.com", // port: 465, // secure: false, // requireTLS: true, // // auth: { // user: "<EMAIL>", // pass: "<PASSWORD>" // } // }); const fast2sms = unirest("POST", "https://www.fast2sms.com/dev/bulk"); fast2sms.headers({ "content-type": "application/x-www-form-urlencoded", "cache-control": "no-cache", "authorization": "<KEY>" }); const fast2cus = unirest("POST", "https://www.fast2sms.com/dev/bulk"); fast2cus.headers({ "authorization": "<KEY>" }); const options = { auth: { api_user: 'saurabharyan', api_key: 'Saurabh@001' } } const client = nodemailer.createTransport(sgTransport(options)); exports.orderById = (req, res, next, id) => { Order.findById(id) .populate("products.product", "name price") .exec((err, order) => { if (err || !order) { return res.status(400).json({ error: errorHandler(err) }); } req.order = order; next(); }); }; exports.create = (req, res) => { // console.log("CREATE ORDER: ", req.body); req.body.order.user = req.profile; const order = new Order(req.body.order); order.save((error, data) => { console.log(req.body.order.transaction_id); if (error) { return res.status(400).json({ error: errorHandler(error) }); } const emailData = { to: "<EMAIL>", from: "<EMAIL>", subject: `A new order is received`, html: ` <div> <p>Customer name:${order.user.name}</p> <p>Total products: ${order.products.length}</p> <p>Total cost: ${order.amount},${order.user.email}</p> <p>Login to dashboard to the order in detail.</p> </div> ` }; const userEmailData = { to: `${order.user.email}`, from: "<EMAIL>", subject: `A new order is received`, html: ` <p>Customer name:${order.user.name}</p> <p>Total products: ${order.products.length}</p> <p>Total cost: ${order.amount}</p> <p>Thank For Trusting Us</p> ` }; client.sendMail(emailData, function(err, info){ if (err ){ console.log(error); } else { console.log('Message sent:'); } }); client.sendMail(userEmailData, function(err, info){ if (err ){ console.log(error); } else { console.log('Message sent:'); } }); // trasporter.sendMail(emailData); // trasporter.sendMail(userEmailData); res.json(data); }); }; exports.listOrders = (req, res) => { Order.find() .populate("user", "_id name mobile email") .sort("-created") .exec((err, orders) => { if (err) { return res.status(400).json({ error: errorHandler(error) }); } res.json(orders); }); }; exports.getStatusValues = (req, res) => { res.json(Order.schema.path("status").enumValues); }; exports.updateOrderStatus = (req, res) =>{ Order.update( { _id: req.body.orderId }, { $set: { status: req.body.status } }, (err, order) => { if (err) { return res.status(400).json({ error: errorHandler(err) }); } const userOrderUpdate = { to: `${req.body.orderEmail}`, from: "<EMAIL>", subject: `Order Live Update`, html: ` <div> <p>Order Status:${req.body.status}</p> <p>Thank For Trusting Us</p> </div> ` }; clientwhat.messages .create({ from:'whatsapp:+14155238886', to:'whatsapp:+917011944204', body:`hello sir You update the order to ${req.body.status} with Order Id ${req.body.orderId}` }).then(message=>{ console.log(message.sid); }); fast2cus.form({ "sender_id": "FSTSMS", "language": "english", "route": "qt", "numbers": `${req.body.orderMobile}`, "message": "17920", "variables": "{#BB#}|{#EE#}", "variables_values": `${req.body.status}|${req.body.orderId}` }); fast2cus.end(function (res) { if (res.error) throw new Error(res.error); console.log(res.body); }); // fast2sms.form({ // "sender_id": "FSTSMS", // "language": "english", // "route": "p", // "numbers": "7011944204", // "message": `hello sir You update the order to ${req.body.status} with Order Id ${req.body.orderId} ` // }); // // fast2sms.end(function (res) { // if (res.error) throw new Error(res.error); // console.log(res.body); // }); res.json(order); } ); }; exports.ordersByUser = (req, res) => { Order.find({ user: req.profile._id }) .populate("user", "_id name") .sort("-created") .exec((err, orders) => { if (err) { return res.status(400).json({ error: err }); } res.json(orders); }); }; <file_sep>/helpers/helpers.js const User = require('../models/user'); module.exports = { updateChatList: async (req, message) => { await User.update( { _id: req.params.sender_Id }, { $pull: { chatList: { receiverId: req.params.receiver_Id } } } ); await User.update( { _id: req.params.receiver_Id }, { $pull: { chatList: { receiverId: req.params.sender_Id } } } ); await User.update( { _id: req.params.sender_Id }, { $push: { chatList: { $each: [ { receiverId: req.params.receiver_Id, msgId: message._id } ], $position: 0 } } } ); await User.update( { _id: req.params.receiver_Id }, { $push: { chatList: { $each: [ { receiverId: req.params.sender_Id, msgId: message._id } ], $position: 0 } } } ); } }; <file_sep>/models/coupon.js const mongoose = require('mongoose') const couponSchema = new mongoose.Schema( { code: { type: String, trim: true, required: true, maxlength: 32, unique: true }, isActive: { type: Boolean, default: true }, discount: { type: Number, required: true, max: 90, min: 10 }, isFlat: { type: Boolean, default: false // Just like flat Rs.500 off // if flat discount, deduct the discount from total amount else calculate the percentage from discount } }, { timestamps: true } ) module.exports = mongoose.model('Coupons', couponSchema) <file_sep>/controllers/wallet.js const User = require('../models/user') const { errorHandler } = require('../helpers/dbErrorHandler') // Add Balance // Body Required - // 1. amount type { Number } // 2. Description type { Object } // 3. Type type { String - 'Debit || Credit' } exports.addBalance = async (req, res) => { try { const userWallet = await User.findById(req.params.userId) if (req.body.amount) { userWallet.wallet_balance += parseInt(req.body.amount) } else { throw new Error('Enter a valid Amount!') } // details are not mandatory! if (req.body.details) { userWallet.wallet_history.push(req.body.details) } userWallet.save() res.json({ success: true, message: 'Wallet updated!' }) } catch (err) { return res.status(400).json({ success: false, error: err.message ? err.message : 'Something went wrong' }) } } exports.getBalance = async (req, res) => { try { const user = await User.findById(req.params.userId, { wallet_balance: 1 }) res.json(user ? { user, success: true } : { success: false, message: 'Something went wrong' }) } catch (err) { return res.status(400).json({ success: false, error: err.message ? err.message : 'Something went wrong' }) } } // Deduct Balance // Body Required - // 1. amount type { Number } // 2. Description type { Object } // 3. Type type { String - 'Debit || Credit' } exports.deductBalance = async (req, res) => { try { const userWallet = await User.findById(req.params.userId) if (req.body.amount) { userWallet.wallet_balance -= parseInt(req.body.amount) } else { throw new Error('Enter a valid Amount!') } // details are not mandatory! if (req.body.details) { userWallet.wallet_history.push(req.body.details) } userWallet.save() res.json({ success: true, message: 'Wallet updated!' }) } catch (err) { return res.status(400).json({ success: false, error: err.message ? err.message : 'Something went wrong' }) } } <file_sep>/controllers/coupon.js const Coupon = require('../models/coupon') const { errorHandler } = require('../helpers/dbErrorHandler') // Create Coupon // Body Required - // 1. code // 2. isActive // 3. discount // 4. isFlat exports.create = async (req, res) => { try { const coupon = await Coupon.create(req.body) res.json(coupon) } catch (err) { console.log(err.message) return res.status(400).json({ error: errorHandler(err) }) } } exports.find = async (req, res) => { try { const coupon = await Coupon.findOne({ code: req.params.code }) res.json(coupon ? { coupon, success: true } : { success: false, message: 'Invalid Coupon' }) } catch (err) { console.log(err.message) return res.status(400).json({ error: errorHandler(err) }) } } exports.deactivate = async (req, res) => { try { const coupon = await Coupon.findOneAndUpdate( { code: req.params.code }, { $set: { isActive: false } }, { new: true } ) res.json(coupon) } catch (err) { res.status(400).json({ error: errorHandler(err) }) } } // Remove Coupon - code required exports.remove = async (req, res) => { try { await Coupon.remove({ code: req.params.code }) res.json({ message: 'Coupon Removed' }) } catch (error) { return res.status(400).json({ error: errorHandler(err) }) } } exports.list = (req, res) => { Coupon.find().exec((err, coupons) => { if (err) { return res.status(400).json({ error: errorHandler(err) }) } res.json(coupons.length ? coupons : 'NO active coupons!') }) } <file_sep>/routes/message.js const express = require("express"); const router = express.Router(); const MessageCtrl = require('../controllers/message'); const { requireSignin, isAuth, isAdmin } = require("../controllers/auth"); router.get( '/chat-messages/:sender_Id/:receiver_Id', requireSignin, MessageCtrl.GetAllMessages); router.post( '/chat-messages/:sender_Id/:receiver_Id', requireSignin, MessageCtrl.SendMessage ); module.exports = router; <file_sep>/routes/wallet.js const express = require('express') const router = express.Router() const { addBalance, getBalance, deductBalance } = require('../controllers/wallet') const { requireSignin, isAuth, isAdmin } = require('../controllers/auth') router.post('/wallet/add/:userId', requireSignin, addBalance) router.post('/wallet/deduct/:userId', requireSignin, deductBalance) router.get('/wallet/balance/:userId', getBalance) module.exports = router <file_sep>/controllers/payment.js const User = require("../models/user"); require("dotenv").config(); const Razorpay = require("razorpay"); const { Order } = require("../models/order"); var instance = new Razorpay({ key_id: "<KEY>", key_secret: "<KEY>" }); exports.processPayment = (req, res) => { const razorPayId = req.body.razorpay_payment_id; const currentCharges = Math.round(req.body.amount * 100); instance.payments .capture(razorPayId, currentCharges) .then(captureResponse => { if (captureResponse.status === "captured") { res.json({ success: true }); console.log(`Payment #${captureResponse.id} Captured`); } }) .catch(error => { console.log(`Error capturing payment #${razorPayId}`); console.log(error); res.status(400).json({ success: false, message: `Order Failed. Error processing payment #${razorPayId}`, error }); }); }; <file_sep>/controllers/user.js const User = require("../models/user"); const { Order } = require("../models/order"); const httpStatus = require('http-status-codes'); const { errorHandler } = require("../helpers/dbErrorHandler"); const formidable = require("formidable"); const _ = require("lodash"); const fs = require("fs"); exports.GetAllUsers=(req, res)=> { User.find({"role": 0}) .then(result => { res.status(httpStatus.OK).json({ message: 'All Customers', result }); }) .catch(err => { res .status(httpStatus.INTERNAL_SERVER_ERROR) .json({ message: 'Error occured' }); }); } exports.GetUserByName=(req, res)=> { User.findOne({name:req.params.name}) .then(result => { res.status(httpStatus.OK).json({ message: 'User By Name', result }); }) .catch(err => { res .status(httpStatus.INTERNAL_SERVER_ERROR) .json({ message: 'Error occured' }); }); } exports.AdminUsers = (req, res) => { User.find({"role": 1}) .then(result => { res.status(httpStatus.OK).json({ message: 'All Admins', result }); }) .catch(err => { res.status(httpStatus.INTERNAL_SERVER_ERROR).json({ message: err }); }); }, // exports.list = (req, res) => { // let order = req.query.order ? req.query.order : "asc"; // let sortBy = req.query.sortBy ? req.query.sortBy : "_id"; // let limit = req.query.limit ? parseInt(req.query.limit) : 6; // Product.find() // .select("-photo") // .populate("category") // .sort([[sortBy, order]]) // .limit(limit) // .exec((err, products) => { // if (err) { // return res.status(400).json({ // error: "Products not found" // }); // } // res.json(products); // }); // }; exports.userById = (req, res, next, id) => { User.findById(id).exec((err, user) => { if (err || !user) { return res.status(400).json({ error: "User not found" }); } req.profile = user; next(); }); }; exports.read = (req, res) => { req.profile.hashed_password = <PASSWORD>; req.profile.salt = <PASSWORD>; return res.json(req.profile); }; exports.update = (req, res) => { User.findOneAndUpdate( { _id: req.profile._id }, { $set: req.body }, { new: true }, (err, user) => { if (err) { return res.status(400).json({ error: "You are not authorized to perform this action" }); } user.hashed_password = <PASSWORD>; user.salt = <PASSWORD>; res.json(user); } ); }; exports.updateUser = (req, res, next) => { let form = new formidable.IncomingForm(); // console.log("incoming form data: ", form); form.keepExtensions = true; form.parse(req, (err, fields, files) => { if (err) { return res.status(400).json({ error: 'Photo could not be uploaded' }); } // save user let user = req.profile; // console.log("user in update: ", user); user = _.extend(user, fields); user.updated = Date.now(); // console.log("USER FORM DATA UPDATE: ", user); if (files.photo) { user.photo.data = fs.readFileSync(files.photo.path); user.photo.contentType = files.photo.type; } user.save((err, result) => { if (err) { return res.status(400).json({ error: err }); } user.hashed_password = <PASSWORD>; user.salt = <PASSWORD>; // console.log("user after update with formdata: ", user); res.json(user); }); }); }; exports.userPhoto = (req, res, next) => { if (req.profile.photo.data) { res.set(('Content-Type', req.profile.photo.contentType)); return res.send(req.profile.photo.data); } next(); }; exports.addOrderToUserHistory = (req, res, next) => { let history = []; req.body.order.products.forEach(item => { history.push({ _id: item._id, name: item.name, description: item.description, category: item.category, quantity: item.count, transaction_id: req.body.order.transaction_id, order_status: req.body.order.status, amount: req.body.order.amount }); }); User.findOneAndUpdate( { _id: req.profile._id }, { $push: { history: history } }, { new: true }, (error, data) => { if (error) { return res.status(400).json({ error: "Could not update user purchase history" }); } next(); } ); }; exports.purchaseHistory = (req, res) => { Order.find({ user: req.profile._id }) .populate("user", "_id name") .sort("-created") .exec((err, orders) => { if (err) { return res.status(400).json({ error: errorHandler(err) }); } res.json(orders); }); };
4b91cc0001a4ac133306211b128a81cc1ab3fe94
[ "JavaScript" ]
10
JavaScript
shubhamaryan001/Deplay-node
3aa874047d9cccaeff645e7fa17d77ac8002e26a
c9dfa71366594c72340c0e879149aa88e652a64d
refs/heads/master
<file_sep>""" This file is the place to write solutions for the skills assignment called skills-sqlalchemy. Remember to consult the exercise instructions for more complete explanations of the assignment. All classes from model.py are being imported for you here, so feel free to refer to classes without the [model.]User prefix. """ from model import * init_app() # ------------------------------------------------------------------- # Part 2: Discussion Questions # 1. What is the datatype of the returned value of # ``Brand.query.filter_by(name='Ford')``? # # flask_sqlalchemy.BaseQuery object # 2. In your own words, what is an association table, and what type of # relationship (many to one, many to many, one to one, etc.) does an # association table manage? # # Association table manages two, many to many, tables. It # links those tables through foriegn keys. Association table # has a one to many relationship # to the tables. # ------------------------------------------------------------------- # Part 3: SQLAlchemy Queries # Get the brand with the ``id`` of "ram." q1 = "Brand.query.filter_by(brand_id='ram').all()" # Get all models with the name "Corvette" and the brand_id "che." q2 = "Model.query.filter(Model.name=='Corvette', Model.brand_id=='che').all()" # Get all models that are older than 1960. q3 = "Model.query.filter(Model.year < 1960).all()" # Get all brands that were founded after 1920. q4 = "Brand.query.filter(Brand.founded > 1920).all()" # Get all models with names that begin with "Cor." q5 = "Model.query.filter(Model.name.like('Cor%')).all()" # Get all brands that were founded in 1903 and that are not yet discontinued. q6 = "Brand.query.filter(Brand.founded=='1903', Brand.discontinued==None).all()" # Get all brands that are either 1) discontinued (at any time) or 2) founded # before 1950. q7 = "Brand.query.filter((Brand.founded < '1950') | (Brand.discontinued!=None)).all()" # Get any model whose brand_id is not "for." q8 = "Model.query.filter(Model.brand_id!='for').all()" # ------------------------------------------------------------------- # Part 4: Write Functions def get_model_info(year): """Takes in a year and prints out each model name, brand name, and brand headquarters for that year using only ONE database query.""" car_list = db.session.query(Model.name, Brand.brand_id, Brand.name, Brand.headquarters).filter(Model.year==year).\ join(Brand).all() for car in car_list: print "%s \t %s \t %s \t %s \n" % (car[0], car[1], car[2], car[3]) def get_brands_summary(): """Prints out each brand name and each model name with year for that brand using only ONE database query.""" car_list = db.session.query(Brand.name, Model.name).filter(Model.year).join(Brand).all() def search_brands_by_name(mystr): """Returns all Brand objects corresponding to brands whose names include the given string.""" brand_objs = Brand.query.filter(Brand.name.like('%mystr%')).all() return brand_objs def get_models_between(start_year, end_year): """Returns all Model objects corresponding to models made between start_year (inclusive) and end_year (exclusive).""" cars_in_range = Model.query.filter(Model.year > start_year, Model.year < end_year).all() return cars_in_range
370ef4712d31285cab584196e1603ccf0f2ae2af
[ "Python" ]
1
Python
KC2004/sqlAlchemy-hw
1b2c65e0847c7283610221b6eb8da72d6e96b458
8663b46558c8c09f4150aa4386131d967e617384
refs/heads/main
<file_sep> <!DOCTYPE html> <meta charset="utf-8" /> <title>Compute Pressure Level 1</title> <script src="https://www.w3.org/Tools/respec/respec-w3c" class="remove" defer></script> <script class="remove"> // All config options at https://respec.org/docs/ const respecConfig = { shortName: "compute-pressure", group: "das", specStatus: "ED", xref: "web-platform", github: "https://github.com/w3c/compute-pressure", formerEditors: [ { name: "<NAME>", company: "Google Inc.", companyURL: "https://google.com", w3cid: 81110, }, { name: "<NAME>", company: "Google Inc.", companyURL: "https://google.com", w3cid: 72312, } ], editors: [ { name: "<NAME>", company: "Intel Corporation", companyURL: "https://intel.com", w3cid: 57705, }, { name: "<NAME>", company: "Intel Corporation", companyURL: "https://intel.com", w3cid: 126342, } ], testSuiteURI: "https://github.com/web-platform-tests/wpt/labels/compute-pressure", xref: { profile: "web-platform", specs: [ "permissions-policy", "hr-time", "picture-in-picture", "mediacapture-streams" ] } }; </script> <style> @counter-style pressure-states-emoji { system: cyclic; symbols: "\026AA" "\01F7E2" "\01F7E1" "\01F534"; suffix: " "; } .pressure-states { list-style-type: pressure-states-emoji; } @counter-style pressure-source-emoji { system: cyclic; symbols: "\1F321" "\1F4A1"; suffix: " "; } .pressure-source { list-style-type: pressure-source-emoji; } ul li::marker { font-family: "Segoe UI Emoji", "Noto Color Emoji"; } </style> <section id="abstract"> <p> The <cite>Compute Pressure API</cite> provides a way for websites to react to changes in the CPU pressure of the target device, such that websites can trade off resources for an improved user experience. </p> </section> <section id="sotd"></section> <section class="informative"> <h2>Introduction</h2> <p> Modern applications often need to balance the trade offs and advantages of fully utilizing the system's computing resources, in order to provide a modern and delightful user experience. </p> <p> As an example, many applications can render video effects with varying degrees of sophistication. These applications aim to provide the best user experience, while avoiding driving the user's device into a high pressure regime. </p> <p> Utilization of [=processing units=] close to and often reaching 100% can lead to a bad user experience, as different tasks are fighting for the processing time. This can lead to slowless, which is especially noticeable with input delay. Further, a prolonged utilization close 100% can cause the [=processing units=] to heat up due to prolonged boosting, which can lead to throttling, resulting in an even worse user experience. </p> <p> As a result of thermal limits, many smartphones, tablets and laptops can become uncomfortably hot to the touch. The fans in laptops and desktops can become so loud that they disrupt conversations or the users’ ability to focus. </p> <p> In many cases, a device under high pressure appears to be unresponsive, as the operating system may fail to schedule the threads advancing the task that the user is waiting for. See also <a href="https://github.com/wicg/compute-pressure/#goals--motivating-use-cases">Use Cases</a>. </p> </section> <section> <h2>A Note on Feature Detection</h2> <p><i>This section is non-normative.</i></p> <p> Feature detection is an established web development best practice. Resources on the topic are plentiful on- and offline and the purpose of this section is not to discuss it further, but rather to put it in the context of detecting hardware-dependent features. </p> <p> Consider the below feature detection examples: </p> <aside class="example" title="Checking existence of PressureObserver interface"> <p> This simple example illustrates how to check whether the [=User Agent=] exposes the {{PressureObserver}} interface </p> <pre class="js"> if ("PressureObserver" in globalThis) { // Use PressureObserver interface } </pre> </aside> <aside class="note"> <p> Checking against {{globalThis/globalThis}} will work on any [=ECMAScript/agent=] as defined by [[ECMAScript]], thus also in workers. </p> <p> It does however not tell you whether that API is actually connected to a real [=platform collector=], whether the [=platform collector=] is collecting real telemetry readings, or whether the user is going to allow you to access it. </p> </aside> </section> <section> <h2>Concepts</h2> <p> This specification defines the following concepts: </p> <section> <h3>Processing Units</h3> <p> Computing devices consist of a multitude of different <dfn>processing units</dfn> such as the Central Processing Unit (CPU), the Graphics Processing Unit (GPU) and many specialized processing units. The latter are becoming popular such as ones designed to accelerate specific tasks like machine learning or computer vision. </p> </section> <section> <h3>Supported sources</h3> <p> The specification currently defines the <dfn>supported source types</dfn> as <em>global system thermals</em> and the <em>central [=processing unit=]</em>, also know as the CPU. Future levels of this specification MAY introduce additional [=source types=]. </p> <pre class="idl"> enum PressureSource { "thermals", "cpu" }; </pre> <p> The <dfn>PressureSource</dfn> enum represents the [=supported source types=]: </p> <p> <ul class="pressure-source"> <li> {{PressureSource/"thermals"}} represents the global thermal state of the system. </li> <li> {{PressureSource/"cpu"}} represents the average pressure of the central [=processing unit=] across all its cores. </li> </ul> </p> <aside class="note"> <p> If a user calls {{PressureObserver/observe()}} with a [=source type=] not part of {{PressureSource}}, at the level of this specification the [=user agent=] supports, the method will throw a {{TypeError}}. </p> <p> If the [=source type=] is part of {{PressureSource}}, but not supported by the [=user agent=], host OS or underlying hardware, the method will instead throw {{NotSupportedError}}. </p> <p> To check what [=source types=] are supported, a user can call the static method {{PressureObserver/supportedSources()}}. </p> </aside> </section> <section> <h3>Sampling and Reporting Rate</h3> <p> The <dfn>sampling rate</dfn> for a [=platform collector=] is defined as a rate at which the [=user agent=] obtains telemetry readings from the underlying platform, and it might differ from the pressure observers' [=requested sampling rates=]. </p> <p> The <dfn>reporting rate</dfn> for a pressure observer is the rate at which it runs the [=data delivery=] steps. </p> <p> The [=sampling rate=] differs from the [=requested sampling rate=] when the [=requested sampling rate=] exceeds upper or lower sampling rate bounds supported or accepted by the underlying platform and [=user agent=]<sup>†</sup>. </p> <p> <sup>†</sup>It is recommended that the [=user agent=] limits the [=reporting rate=] as outlined in [[[#rate-limiting-change-notifications]]]. </p> <p> In case the user didn't request a [=sampling rate=], the [=sampling rate=] is [=implementation-defined=]. </p> <aside class="note"> In case there are multiple instances of {{PressureObserver}} active with different [=requested sampling rates=], it is up to the [=user agent=] to set a [=platform collector=] level [=sampling rate=] that best fulfills these requests, while making sure that the [=reporting rate=] of all {{PressureObserver}}s does not exceed their respective [=requested sampling rates=]. </aside> </section> </section> <section> <h2>Platform primitives</h2> <p> The [=platform collector=] refers to a platform interface, with which the [=user agent=] interacts to obtain the telemetry readings required by this specification. </p> <p> A [=platform collector=] can be defined by the underlying platform (e.g. in a native telemetry framework) or by the [=user agent=], if it has a direct access to hardware counters. </p> <p> A [=platform collector=] can support telemetry for different <dfn>source types</dfn> of computing devices defined by {{PressureSource}}, or there can be multiple [=platform collectors=]. </p> <p> From the implementation perspective [=platform collector=] can be treated as a software proxy for the corresponding hardware counters. It is possible to have multiple [=platform collector=] simultaneously interacting with the same underlying hardware if the underlying platform supports it. </p> <p> In simple cases, a [=platform collector=] represents individual hardware counters, but if the provided counter readings are a product of data fusion performed in software, the [=platform collector=] represents the results of the data fusion process. This may happen in user space or in kernel space. </p> <p> As collecting telemetry data often means polling hardware counters, it is not a free operation and thus, it should not happen if there are no one observing the data. See [[[#life-cycle]]] for more information. </p> <p> A [=platform collector=] samples data at a specific rate. A [=user agent=] may modify this rate (if possible) for privacy reasons, or ignore and fuse certain readings. </p> </section> <section> <h3> User notifications </h3> <p> It is RECOMMENDED that a [=user agent=] show some form of unobtrusive notification that informs the user when a pressure observer is active, as well as provides the user with the means to block the ongoing operation, or simply dismiss the notification. </p> </section> <section> <h3> Policy control </h3> <p> The Compute Pressure API defines a [=policy-controlled feature=] identified by the token "compute-pressure". Its [=policy-controlled feature/default allowlist=] is `["self"]`. </p> <aside class="note"> <p> The [=policy-controlled feature/default allowlist=] of `["self"]` allows usage in same-origin nested frames but prevents third-party content from using the feature. </p> <p> Third-party usage can be selectively enabled by adding `allow="compute-pressure"` attribute to the frame container element: </p> <pre class="example html" title= "Enabling compute pressure on remote content"> &lt;iframe src="https://third-party.com" allow="compute-pressure"/&gt;&lt;/iframe&gt; </pre> <p> Alternatively, the Compute Pressure API can be disabled completely by specifying the permissions policy in a HTTP response header: </p> <pre class="example http" title="Feature Policy over HTTP"> Permissions-Policy: {"compute-pressure": []} </pre> <p> See [[[PERMISSIONS-POLICY]]] for more details. </p> </aside> </section> <section> <h3> Internal Slot Definitions </h3> <p> Each [=global object=] has: <ul> <li> a <dfn>current pressure state</dfn> (a string), initialized to the empty string. </li> <li> a <dfn>pressure observer task queued</dfn> (a boolean), which is initially false. </li> <li> a <dfn>registered observer list</dfn> per supported [=source type=], which is initially empty. </li> <li> a reference to an underlying <dfn>platform collector</dfn> as detailed in [[[#platform-primitives]]]. </li> </ul> A <dfn>registered observer</dfn> consists of an <dfn>observer</dfn> (a {{PressureObserver}} object). </p> <p> A constructed {{PressureObserver}} object has the following internal slots: </p> <ul data-dfn-for="PressureObserver"> <li> a <dfn>[[\Callback]]</dfn> of type {{PressureUpdateCallback}} set on creation. </li> <li> a <dfn>[[\SampleRate]]</dfn> double set on creation. </li> <li> a <dfn>[[\PendingObservePromises]]</dfn> [=list=] of zero or more source-promise [=tuples=], initially empty, where source holds a {{PressureSource}} string and promise holds a {{Promise}} object. </li> <li> a <dfn>[[\QueuedRecords]]</dfn> [=queue=] of zero or more {{PressureRecord}} objects, which is initially empty. </li> <li> a <dfn>[[\LastRecordMap]]</dfn> [=ordered map=], [=map/keyed=] on a {{PressureSource}}, representing the [=source type=] to which the last record belongs. The [=ordered map=]'s [=map/value=] is a {{PressureRecord}}. </li> </ul> <p> The [=user agent=] additionally has a <dfn>max queued records</dfn> integer, which is set to an [=implementation-defined=] value, greater than 0. </li> </p> </section> <section> <h2>Pressure States</h2> <p> <dfn>Pressure states</dfn> represents the minimal set of useful states that allows websites to react to changes in compute and system pressure with minimal degration in quality or service, or user experience. </p> <pre class="idl"> enum PressureState { "nominal", "fair", "serious", "critical" }; </pre> <p> The <dfn>PressureState</dfn> enum represents the [=pressure state=] with the following states: </p> <p> <ul class="pressure-states"> <li> {{PressureState/"nominal"}}: The conditions of the target device are at an acceptable level with no noticeable adverse effects on the user. </li> <li> {{PressureState/"fair"}}: Target device pressure, temperature and/or energy usage are slightly elevated, potentially resulting in reduced battery-life, as well as fans (or systems with fans) becoming active and audible. Apart from that the target device is running flawlessly and can take on additional work. </li> <li> {{PressureState/"serious"}}: Target device pressure, temperature and/or energy usage is consistently highly elevated. The system may be throttling as a countermeasure to reduce thermals. </li> <li> {{PressureState/"critical"}}: The temperature of the target device or system is significantly elevated and it requires cooling down to avoid any potential issues. </li> </ul> </p> </section> <section> <h2>Contributing Factors</h2> <p> Contributing factors represent the underlying hardware metrics contributing to the [=current pressure state=] and can be [=implementation-defined=]. </p> <p> The <dfn>change in contributing factors is substantial</dfn> steps are as follows: <ol> <li> If [=implementation-defined=] low-level hardware metrics that contribute to the [=current pressure state=] drop below or exceed an, per metric, [=implementation-defined=] threshold for the [=current pressure state=], return true. </li> <li> Return false. </li> </ol> <aside class="note"> <p> The [=change in contributing factors is substantial=] algorithm allows [=user agents=] to avoid flip- flopping between states in certain circumstances. For example, a state might otherwise change too rapidly in response to a certain system metric that fluctuates around a boundary condition that triggers a state change. </p> <p> This specification does not define the precise algorithm to allow implementations optimize this algorithm to match the underlying hardware platform's behavior. One possible implementation of this algorithm is to use a <a href="https://en.wikipedia.org/wiki/Preisach_model_of_hysteresis#Nonideal_relay">nonideal relay</a> as a model and identify appropriate lower threshold &#945; and upper threshold &#946; for each [=pressure state=] taking special characteristics of each contributing factors into consideration. </p> </aside> </p> </section> <section> <h2>Pressure Observer</h2> The Compute Pressure API enables developers to understand the pressure of system resources such as the CPU. <section data-dfn-for="PressureObserverCallback"> <h3>The <a>PressureUpdateCallback</a> callback</h3> <pre class="idl"> callback PressureUpdateCallback = undefined ( sequence&lt;PressureRecord&gt; changes, PressureObserver observer ); </pre> This callback will be invoked when the [=pressure state=] changes. </section> <section data-dfn-for="PressureObserver"> <h2>The <a>PressureObserver</a> object</h2> <p> The {{PressureObserver}} can be used to observe changes in the [=pressure states=]. </p> <pre class="idl"> [Exposed=(DedicatedWorker,SharedWorker,Window), SecureContext] interface PressureObserver { constructor(PressureUpdateCallback callback, optional PressureObserverOptions options = {}); Promise&lt;undefined&gt; observe(PressureSource source); undefined unobserve(PressureSource source); undefined disconnect(); sequence&lt;PressureRecord&gt; takeRecords(); [SameObject] static readonly attribute FrozenArray&lt;PressureSource&gt; supportedSources; }; </pre> <p>The <dfn>PressureObserver</dfn> interface represents a {{PressureObserver}}.</p> <section> <h3>The <dfn>constructor()</dfn> method</h3> <p> The `new` {{PressureObserver(callback, options)}} constructor steps are: <ol class="algorithm"> <li> Set |this|.{{PressureObserver/[[Callback]]}} to |callback:PressureUpdateCallback|. </li> <li> If |options|["sampleRate"] is less than or equal to 0, throw a {{RangeError}}. </li> <li> Set |this:PressureObserver|.{{PressureObserver/[[SampleRate]]}} to |options|["sampleRate"]. </li> </ol> </p> </section> <section> <h3>The <dfn>observe()</dfn> method</h3> <p> The {{PressureObserver/observe(source)}} method steps are: <ol class="algorithm"> <li> Let |document:Document| be [=this=]'s [=relevant settings object=]'s [=associated Document=]. </li> <li> If |document| is not null and is not [=allowed to use=] the [=policy-controlled feature=] token "compute-pressure", return [=a promise rejected with=] {{NotAllowedError}}. <aside class="issue"> <a href="https://github.com/wicg/compute-pressure/issues/110"> Permission policy doesn't support workers yet #110 </a> </aside> </li> <li> Let |promise:Promise| be [=a new promise=]. </li> <li> Let |pendingPromiseTuple| be (|source|, |promise|). </li> <li> [=list/Append=] |pendingPromiseTuple| to [=this=].{{PressureObserver/[[PendingObservePromises]]}}. </li> <li> [=promise/React=] to |promise|: <ul> <li> If |promise| was [=resolved|fulfilled=] or [=rejected=], then: <ol> <li> [=list/Remove=] |tuple| from [=this=].{{PressureObserver/[[PendingObservePromises]]}}. </li> </ol> </li> </ul> </li> <li> Run the following steps [=in parallel=]: <ol> <li> If |source:PressureSource| is not a [=supported source type=], [=queue a global task=] on the [=PressureObserver task source=] given |document|'s [=relevant global object=] |relevantGlobal| to reject |promise| {{NotSupportedError}} and abort these steps. </li> <li> Activate [=data delivery=] of |source| data to |relevantGlobal|. </li> <li> [=Queue a global task=] on the [=PressureObserver task source=] given |document|'s [=relevant global object=] |relevantGlobal| to run these steps: <ol> <li> If |promise| was rejected, run the following substeps: <ol> <li> If |relevantGlobal|'s [=registered observer list=] for |source| is [=list/empty=], deactivate [=data delivery=] of |source| data to |relevantGlobal|. </li> <li> Return. </li> </ol> </li> <li> [=list/Append=] a new [=registered observer=] whose [=observer=] is [=this=] to |relevantGlobal|'s [=registered observer list=] for |source|. </li> <li> Resolve |promise|. </li> </ol> </li> </ol> </li> <li> Return |promise|. </li> </ol> </p> </section> <section> <h3>The <dfn>unobserve()</dfn> method</h3> <p> The {{PressureObserver/unobserve(source)}} method steps are: <ol class="algorithm"> <li> If |source:PressureSource| is not a [=supported source type=], throw {{"NotSupportedError"}}. </li> <li> [=list/Remove=] from |this|.{{PressureObserver/[[QueuedRecords]]}} all |records| associated with |source|. </li> <li> [=map/Remove=] |this|.{{PressureObserver/[[LastRecordMap]]}}[|source|]. </li> <li> [=list/For each=] (|promiseSource|, |pendingPromise|) of [=this=].{{PressureObserver/[[PendingObservePromises]]}}, if |source| is equal to |promiseSource|, [=reject=] |pendingPromise| with an {{AbortError}}. </li> <li> Let |relevantGlobal| be [=this=]'s [=relevant global object=]. </li> <li> Remove any [=registered observer=] from |relevantGlobal|'s [=registered observer list=] for |source| for which [=this=] is the [=registered observer=]. </li> <li> If the above [=registered observer list=] is [=list/empty=], deactivate [=data delivery=] of |source| data to |relevantGlobal|. </li> </ol> </p> </section> <section> <h3>The <dfn>disconnect()</dfn> method</h3> <p> The {{PressureObserver/disconnect()}} method steps are: <ol class="algorithm"> <li> [=list/Empty=] |observer|.{{PressureObserver/[[QueuedRecords]]}}. </li> <li> [=map/Clear=] |this|.{{PressureObserver/[[LastRecordMap]]}}. </li> <li> [=list/For each=] (|promiseSource|, |pendingPromise|) of [=this=].{{PressureObserver/[[PendingObservePromises]]}}, [=reject=] |pendingPromise| with an {{AbortError}}. </li> <li> Let |relevantGlobal| be [=this=]'s [=relevant global object=]. </li> <li> Remove any [=registered observer=] from |relevantGlobal|'s' [=registered observer list=] for all supported [=source types=] for which [=this=] is the [=observer=]. </li> <li> If the above [=registered observer list=] is [=list/empty=], deactivate [=data delivery=] of |source| data to |relevantGlobal|. </li> </ol> </p> </section> <section> <h3>The <dfn>takeRecords()</dfn> method</h3> <aside class="note"> <p> A common use case for this is to immediately fetch all pending state change records immediately prior to disconnecting the observer, so that any pending state changes can be processed when shutting down the observer. </p> <p> Another use case is the ability to receive any pending, already-generated states changes without waiting for the callbacks to be invoked. Callbacks are invoked from a task queue as part of the event loop cycle, so this allows for conferring the current state outside of the event loop cycle. </p> </aside> <p> The {{PressureObserver/takeRecords()}} method steps are: <ol class="algorithm"> <li> Let |records| be a [=list/clone=] of |observer|.{{PressureObserver/[[QueuedRecords]]}}. </li> <li> [=list/Empty=] |observer|.{{PressureObserver/[[QueuedRecords]]}}. </li> <li> Return |records|. </li> </ol> </p> </section> <section> <h3>The <dfn>supportedSources</dfn> attribute</h3> <p> The {{PressureObserver/supportedSources}} attribute is informing on the [=supported source type=] by the [=platform collector=]. </p> <p> The {{PressureObserver/supportedSources}} getter steps are: <ol class="algorithm"> <li> Let |sources| be a [=list=] of |source:PressureSource|. </li> <li> Return |observer|'s frozen array of supported [=source types=]. </li> </ol> </p> <aside class="note"> <p> This attribute allows web developers to easily know which [=source types=] are supported by the user agent. </p> </aside> </section> </section> <section data-dfn-for="PressureRecord"> <h3>The <dfn>PressureRecord</dfn> interface</h3> <pre class="idl"> [Exposed=(DedicatedWorker,SharedWorker,Window), SecureContext] interface PressureRecord { readonly attribute PressureSource source; readonly attribute PressureState state; readonly attribute DOMHighResTimeStamp time; [Default] object toJSON(); }; </pre> <p> A constructed {{PressureRecord}} object has the following internal slots: </p> <ul data-dfn-for="PressureRecord"> <li> a <dfn>[[\Source]]</dfn> value of type {{PressureSource}}, which represents the current [=source type=]. </li> <li> a <dfn>[[\State]]</dfn> value of type {{PressureState}}, which represents the [=current pressure state=]. </li> <li> a <dfn>[[\Time]]</dfn> value of type {{DOMHighResTimeStamp}}, which corresponds to the time the data was obtained from the system, relative to the [=environment settings object/time origin=] of the global object associated with the {{PressureObserver}} instance that generated the notification. </li> </ul> <section> <h3>The <dfn>source</dfn> attribute</h3> <p> The {{PressureRecord/source}} [=getter steps=] are to return its {{PressureRecord/[[Source]]}} internal slot. </p> </section> <section> <h3>The <dfn>state</dfn> attribute</h3> <p> The {{PressureRecord/state}} [=getter steps=] are to return its {{PressureRecord/[[State]]}} internal slot. </p> </section> <section> <h3>The <dfn>time</dfn> attribute</h3> <p> The {{PressureRecord/time}} [=getter steps=] are to return its {{PressureRecord/[[Time]]}} internal slot. </p> </section> <section> <h3>The <dfn>toJSON</dfn> member</h3> <p> When {{PressureRecord.toJSON}} is called, run [[[WebIDL]]]'s [=default toJSON steps=]. </p> </section> </section> <section data-dfn-for="PressureObserverOptions"> <h3>The <dfn>PressureObserverOptions</dfn> dictionary</h3> <pre class="idl"> dictionary PressureObserverOptions { double sampleRate = 1.0; }; </pre> <section> <h3>The <dfn>sampleRate</dfn> member</h3> <p> The {{PressureObserverOptions/sampleRate}} member represents the <dfn>requested sampling rate</dfn> expressed in Hz, ie. it represents the number of samples requested to be obtained from the hardware per second. The [=reporting rate=] will never exceed the [=requested sampling rate=]. </p> <aside class="note"> <p> For slow sampling rates (less than 1hz), it is common to use seconds and talk about period instead of rate. Fortunately, it is easy to convert between the two, as hertz is rotations per second. If you want to request a sampling rate of 10 seconds, then just use the value of 0.1. </p> <p> A [=user agent=] might not be able to respect the requested sampling rate. For more information consult [[[#sampling-and-reporting-rate]]]. </p> </aside> </section> </section> <section id="life-cycle"> <h3>Life-cycle and garbage collection</h3> <p> Each [=global object=] has a strong reference to [=registered observers=] in their [=registered observer list=] (one per source). </p> <aside class="note"> <p> A {{PressureObserver}} is observing a |source:PressureSource| if it exists in the [=registered observer list=], modified by invocations of {{PressureObserver/observe()}}, {{PressureObserver/unobserve()}} and {{PressureObserver/disconnect()}}. </p> <p> This means that a {{PressureObserver}} object |observer:PressureObserver| will remain alive (thus not be garbage collection) until both of these conditions hold: <ul> <li> There are no scripting references to the |observer|. </li> <li> The |observer| is not observing any |source|. </li> </ul> </p> <p> [[[#cb-observer-example]]] contains an example of how to use the {{PressureObserver/disconnect()}} (or any other {{PressureObserver}} method) from the observer callback. </p> </aside> </section> <section id="processing-model"> <h3>Processing Model</h3> <p> This section outlines the steps the user agent must take when implementing the specification. </p> <section> <h3>Supporting algorithms</h3> <p> <aside class="note"> Readings are available for [=documents=] (incl. [=iframes=] and popup windows) and workers, matching the following criteria: <ul> <li> They are [=Document/fully active=] [=documents=], or they are <a href="https://html.spec.whatwg.org/multipage/workers.html#active-needed-worker">active needed workers</a>. </li> <li> Their [=origin=] is [=same origin-domain=] with the [=Node/node document|document=] containing the <a href="https://html.spec.whatwg.org/multipage/interaction.html#focused">focused</a> [=node=], or an <a href="https://w3c.github.io/picture-in-picture/#initiators-of-active-picture-in-picture-sessions"> initiator of an active Picture-in-Picture session</a>, or the browsing [=context is capturing=], including microphone, camera and display. </li> </ul> </aside> The <dfn>passes privacy test</dfn> steps given the argument |observer:PressureObserver| and its [=relevant global object=] |relevantGlobal|, are as follows: <ul> <li> If |relevantGlobal| is a {{WorkerGlobalScope}} object: <ol> <li> If |relevantGlobal|'s relevant worker is not a <a href="https://html.spec.whatwg.org/multipage/workers.html#active-needed-worker"> active needed worker</a>, return false. </li> <li> Otherwise, return true. </li> </ol> </li> <li> If |relevantGlobal| is a {{Window}} object: <ol> <li> If |relevantGlobal|'s [=associated document=] is not [=Document/fully active=], return false. </li> <li> [=list/For each=] |origin| in <a href="https://w3c.github.io/picture-in-picture/#initiators-of-active-picture-in-picture-sessions"> initiators of active Picture-in-Picture sessions</a>: <ol> <li> If |relevantGlobal|'s [=relevant settings object=]'s [=origin=] is [=same origin-domain=] with |origin|, return true. </li> </ol> </li> <li> If |relevantGlobal|'s [=browsing context=] is [=context is capturing|capturing=], return true. </li> <li> Let |topLevelBC| be |relevantGlobal|'s [=browsing context=]'s [=top-level browsing context=]. </li> <li> If |topLevelBC| does not have [=top-level traversable/system focus=], return false. </li> <li> Let |focusedDocument| be the |topLevelBC|'s <a href="https://html.spec.whatwg.org/multipage/interaction.html#currently-focused-area-of-a-top-level-browsing-context"> currently focused area</a>'s [=Node/node document=]. </li> <li> If |relevantGlobal|'s [=relevant settings object=]'s [=origin=] is [=same origin-domain=] with |focusedDocument|'s [=origin=], return true. </li> <li> Otherwise, return false. </li> </ol> </li> </ul> <aside class="note"> As there might be multiple observers, each with a different [=requested sampling rate=], the underlying [=platform collector=] will need to use a [=sampling rate=] that fulfills all these requirements. This also means that not every data sample from the [=platform collector=] needs to be delivered to each active observer. </aside> The <dfn>passes rate test</dfn> steps given the argument |observer:PressureObserver|, |source:PressureSource| and |timestamp:DOMHighResTimeStamp|, are as follows: <ol> <li> If |observer|.{{PressureObserver/[[LastRecordMap]]}}[|source|] does not [=map/exist=], return true. </li> <li> Let |record:PressureRecord| be |observer|.{{PressureObserver/[[LastRecordMap]]}}[|source|]. </li> <li> Let |sampleRate| be |observer|.{{PressureObserver/[[SampleRate]]}}. </li> <li> Let |timeDeltaMilliseconds:DOMHighResTimeStamp| = |timestamp| - |record|.{{PressureRecord/[[Time]]}}. </li> <li> Let |intervalSeconds| = 1 / |sampleRate|. </li> <li> If (|timeDeltaMilliseconds| / 1000) &ge; |intervalSeconds|, return true, otherwise return false. </li> </ol> The <dfn>has change in data</dfn> steps given the argument |observer:PressureObserver|, |source:PressureSource|, |state:PressureState|, are as follows: <ol> <li> If |observer|.{{PressureObserver/[[LastRecordMap]]}}[|source|] does not [=map/exist=], return true. </li> <li> Let |record:PressureRecord| be |observer|.{{PressureObserver/[[LastRecordMap]]}}[|source|]. </li> <li> If |record|.{{PressureRecord/[[State]]}} is not equal to |state| and [=change in contributing factors is substantial=] returns true, return true. </li> <li> Return false. </li> </ol> </p> </section> <section> <h3>Data delivery</h3> <p> [=Data delivery=] from a [=platform collector=] can be activate and deactivated in an [=implementation-defined=] manner per [=source type=] and [=global object=]. </p> <aside class="note"> It is recommended that the [=platform collector=] suspends low-level data polling when there is no active [=data delivery=] to any {{PressureObserver}} [=relevant global object=]. </aside> <p> The <dfn>data delivery</dfn> steps that are run when an [=implementation-defined=] |data| sample of [=source type=] |source:PressureSource| is obtained from [=global object=] |relevantGlobal|'s [=platform collector=], are as follows: <ol> <li> Let |source:PressureSource| be the [=source type=] of the |data| sample. </li> <li> Let |state:PressureState| be an [=implementation-defined=] state given |data| and |source|. </li> <li> Let |timestamp:DOMHighResTimeStamp| be a timestamp representing the time the |data| was obtained from the |relevantGlobal|'s [=platform collector=]. <aside class="note"> The |data| sample and mapping between |data| sample, and [=pressure states=], is [=implementation-defined=] and may use many different metrics. For instance, for CPU, it might consider processor frequency and utilization, as well as thermal conditions. </aside> </li> <li> [=list/For each=] |observer:PressureObserver| in |relevantGlobal|'s [=registered observer list=] for |source|: <ol> <li> If running [=passes privacy test=] with |observer| returns false, [=iteration/continue=]. </li> <li> If running [=passes rate test=] with |observer|, |source| and |timestamp| returns false, [=iteration/continue=]. </li> <li> If running [=has change in data=] with |observer|, |source| and |state| returns false, [=iteration/continue=]. </li> <li> Run [=queue a record=] with |observer|, |source|, |state| and |timestamp|. </li> </ol> </li> </ol> </p> </section> <section> <h3>Queue a PressureRecord</h3> <p> To <dfn>queue a record</dfn> given the arguments |observer:PressureObserver|, |source:PressureSource|, |state:PressureState| and |timestamp:DOMHighResTimeStamp|, run these steps: </p> <ol class="algorithm"> <li> Let |record:PressureRecord| be a new {{PressureRecord}} object with its {{PressureRecord/[[Source]]}} set to |source|, {{PressureRecord/[[State]]}} set to |state| and {{PressureRecord/[[Time]]}} set to |timestamp|. </li> <li> If [=list/size=] of |observer|.{{PressureObserver/[[QueuedRecords]]}} is greater than [=max queued records=], then [=list/remove=] the first [=list/item=]. <li> [=list/Append=] |record| to |observer|.{{PressureObserver/[[QueuedRecords]]}}. </li> <li> Set |observer|.{{PressureObserver/[[LastRecordMap]]}}[|source|] to |record|. </li> <li> [=Queue a pressure observer task=] with |observer|'s [=relevant global object=]. </li> </ol> </section> <section> <h3>Queue a Pressure Observer Task</h3> <p> The <dfn>PressureObserver task source</dfn> is a [=task source=] used for scheduling tasks to [[[#notify-observers]]]. </p> <p> To <dfn>queue a pressure observer task</dfn> given |relevantGlobal| as input, run these steps: </p> <ol class="algorithm"> <li> If the |relevantGlobal|'s [=pressure observer task queued=] is true, then return. </li> <li> Set the |relevantGlobal|'s [=pressure observer task queued=] to true. </li> <li> [=Queue a global task=] on [=PressureObserver task source=] with |relevantGlobal| to [=notify pressure observers=]. </li> </ol> </section> <section id="notify-observers"> <h3>Notify Pressure Observers</h3> <p> To <dfn>notify pressure observers</dfn> given |relevantGlobal| as input, run these steps: </p> <ol class="algorithm"> <li> Set |relevantGlobal|'s [=pressure observer task queued=] to false. </li> <li> Let |notifySet| be a new [=set=] of all [=observers=] in |relevantGlobal|’s [=registered observer lists=]. </li> <li> [=list/For each=] |observer:PressureObserver| of |notifySet|: <ol> <li> Let |records| be a [=list/clone=] of |observer|.{{PressureObserver/[[QueuedRecords]]}}. </li> <li> [=list/Empty=] |observer|.{{PressureObserver/[[QueuedRecords]]}}. </li> <li> If |records| is not [=list/empty=], then invoke |observer|.{{PressureObserver/[[Callback]]}} with |records| and |observer|. If this throws an exception, catch it, and [=report the exception=]. </li> </ol> </li> </ol> </section> <section> <h3>Handling change of fully active</h3> <p> When a {{Document}} |document| is no longer [=Document/fully active=], deactivate [=data delivery=] of data of all [=supported source types=] to |document|'s [=relevant global object=]. </p> <p> When a worker with associated {{WorkerGlobalScope}} |relevantGlobal| is no longer an <a href="https://html.spec.whatwg.org/multipage/workers.html#active-needed-worker"> active needed workers</a>, deactivate [=data delivery=] of data of all [=supported source types=] to |relevantGlobal|. </p> <p> When a {{Document}} |document| becomes [=Document/fully active=], for each non-[=list/empty=] [=registered observer list=] associated the [=source type=] |source|, activate [=data delivery=] of |source| data to |document|'s [=relevant global object=]. </p> <p> When a worker with associated {{WorkerGlobalScope}} |relevantGlobal| becomes an <a href="https://html.spec.whatwg.org/multipage/workers.html#active-needed-worker"> active needed workers</a>, for each non-[=list/empty=] [=registered observer list=] associated the [=source type=] |source|, activate [=data delivery=] of |source| data to |document|'s [=relevant global object=]. </p> <aside class="note"> When a document is no longer [=Document/fully active=] (or associated workers no longer <a href="https://html.spec.whatwg.org/multipage/workers.html#active-needed-worker"> active needed workers</a>), like when entering the back/forward cache, or "BFCache" for short, then no events are send to the pressure observers (see [=passes privacy test=]) in accordance with <a href="https://www.w3.org/TR/design-principles/#listen-fully-active"> Web Platform Design Principles: Listen for changes to fully active status</a>. This means that the system can safely deactivate [=data delivery=] from the associated [=platform collector=], but also that it needs to be re-activated when the opposite happens. </aside> </section> <section id="unload-observers"> <h3>Handle unloading document and closing of workers</h3> <p> When a worker with associated {{WorkerGlobalScope}} |relevantGlobal|, once |relevantGlobal|'s [=WorkerGlobalScope/closing=] flag is set to true, deactivate [=data delivery=] for all [=supported source types=] to |relevantGlobal|. </p> <p> As one of the [=unloading document cleanup steps=] given {{Document}} |document|, deactivate [=data delivery=] for all [=supported source types=] to |document|'s [=relevant global object=]. </p> </section> </section> </section> <!-- Pressure Observer --> <section> <h2> Security and privacy considerations </h2> <p> Please consult the <a href="security-privacy-self-assessment.html">Security and Privacy Self-Assessment</a> based upon the [[security-privacy-questionnaire]]. </p> <section> <h3>Minimizing information exposure</h3> <p> Exposing hardware related events related to low -level details such as exact CPU utilization or frequency <a href="https://w3ctag.github.io/design-principles/#device-ids"> increases the risk of harming the user's privacy</a>. </p> <p> To mitigate this risk, no such low level details are exposed. </p> <p> The subsections below describe the processing model. At a high level, the information exposed is reduced by the following steps: <ol> <li> <b>Rate-limiting</b> - The user agent notifies the application of changes in the information it can learn. Change notifications are rate-limited. </li> <li> <b>Same-origin context</b> - The feature is only available in same-origin contexts by default, but can be extended to third-party contexts such as iframes via a permission policy. </li> </ol> <section> <h4>Rate-limiting change notifications</h4> <p> We propose exposing the pressure state via rate-limited change notifications. This aims to remove the ability to observe the precise time when a value transitions between two states. </p> <p> More precisely, once the pressure observer is activated, it will be called once with initial values, and then be called when the values change. The subsequent calls will be rate-limited. When the callback is called, the most recent value is reported. </p> <p> The specification will recommend a rate limit of at most one call per second for the active window, and one call per 10 seconds for all other windows. We will also recommend that the call timings are jittered across origins. </p> <p> These measures benefit the user's privacy, by reducing the risk of identifying a device across multiple origins. The rate-limiting also benefits the user's security, by making it difficult to use this API for timing attacks. Last, rate-limiting change callbacks places an upper bound on the performance overhead of this API. </p> <p> Rate limiting can be implemented in the user agent, but it might also be possible to simply change the polling/sampling rate of the underlying hardware counters, if not accessed via a higher level framework. </p> </section> <section> <h4>No side-channels</h4> <p> It is possible to identify users across non-[=same origin=] sites if unique or very precise values can be accessed at the same time by sites not sharing origin. </p> <p> If the same [=pressure state=] and timestamp is observed by two origins, that would be a good indication that the origin is used by the same user on the same machine. For this reason, the API limits reporting [=pressure state=] changes to one origin at the time. </p> <p> A common way to do this, is only to report changes to the focused page, but one of the main users of this API are video conferencing sites. These sites want to make sure that the video streams and effects doesn't negatively affect the system and thus the conferencing experience - but there are two common cases where the site will usually not be focused: <ul> <li> The user is taking meeting notes and the site is in the background. Commonly the video stream is only visible via a picture-in-picture window. </li> <li> The user is sharing an external application window such as a presentation, or sharing the whole screen, unusually with some UI indicating sharing is happening. </li> </ul> For this reason, the API considers these two cases to have higher priority than whether the site is focused. </p> </section> <section> <h4>Same-origin contexts</h4> <p> By <em>default</em> data delivery is restricted to documents served from the same-origin as an <a href="https://w3c.github.io/picture-in-picture/#initiators-of-active-picture-in-picture-sessions"> initiator of an active picture-in-picture-session</a>, documents [=context is capturing|capturing=] or the document with [=top-level traversable/system focus=], if any. </p> <p> The documents qualifying for data delivery, under the above rules, can delegate it to documents in [=child navigables=]. </p> </section> </p> </section> </section> <section id="examples" class="informative"> <h2> Examples </h2> <pre class="example js" title="How to access observer from callback" id="cb-observer-example"> const samples = []; function pressureChange(records, observer) { for (const record of records) { samples.push(record.state); // We only want 20 samples. if (samples.length == 20) { observer.disconnect(); return; } } } const observer = new PressureObserver(pressureChange); observer.observe("cpu"); </pre> <p> In the following example we want to lower the number of concurrent video streams when the pressure becomes critical. For the sake of simplicity we only consider this one state. </p> <p> As lowering the amount of streams might not result in exiting the critical state, or at least not immediately, we use a strategy where we lower one stream at the time every 30 seconds while still in the critical state. </p> <p> We accomplish this by making sure the callback is called at least once every 30 seconds, or when the state actually changes. When the state changes we reset the interval timer. </p> <pre class="example js" title="How to adjust the number of video feeds based on CPU pressure"> let timerId = -1; function pressureChange(records) { // Clear timer every time we are called, either by an actual state change, // or when called by setTimeout (see below). if (timerId > 0) { clearTimeout(timerId); } // When entering critical state, we want to recheck every 30sec if we are // still in critical state and if so, further reduce our concurrent streams. // For this reason we create a timer for 30 seconds that will call us back // with the last result in there were no change. const lastRecordArray = [records.at(records.length - 1)]; timerId = setTimeout(pressureChange.bind(this, lastRecordArray), 30_000); for (const record of records) { if (record.state == "critical") { let streamsCount = getStreamsCount(); setStreamsCount(streamsCount--); } } } const observer = new PressureObserver(pressureChange); observer.observe("cpu"); </pre> <p> In the following example, we want to demonstrate the usage of {{PressureObserver/takeRecords()}}, by retrieving the remaining |records| accumulated since the the callback was last invoked. </p> <p> It is recommended to do so before {{PressureObserver/disconnect()}}, otherwise {{PressureObserver/disconnect()}} will clear them and they will be lost forever. </p> <p> For example, we might want to measure the pressure during a benchmarking workload, and thus want pressure telemetry for the exact duration of the workload. This means disconnecting all observers immediately when the task is completed, and manually requesting any pending pressure telemetry up to this point that might not have been delivered yet as part of the event loop cycle. </p> <pre class="example js" title="How to handle all state changes right up until disconnect"> function logWorkloadStatistics(records) { // do something with records. } const observer = new PressureObserver(logWorkloadStatistics); observer.observe("cpu"); // Read pending state change records, otherwise they will be cleared // when we disconnect. const records = observer.takeRecords(); logWorkloadStatistics(records); observer.disconnect(); </pre> <p> In the following example, we show how to tell the observer to stop watching a specific |source:PressureSource| by invoking {{PressureObserver/unobserve()}} with |source|. </p> <aside class="note"> The example uses 'gpu', which could be a potential future addition to the specification. It aims to show that the API is extentable to support other types of pressure in the future </aside> <pre class="example js" title="How to tell the observer to stop watching for state changes for a specific source"> const observer = new PressureObserver(records => { // do something with records. })); observer.observe("cpu"); observer.observe("gpu"); // Callback now gets called whenever the pressure state changes for 'cpu' or 'gpu'. observer.unobserve("gpu"); // Callback now only gets called whenever the pressure state changes for 'cpu'. </pre> <p> In the following example, we show how to tell the observer to stop watching for any state changes by calling {{PressureObserver/disconnect()}}. Calling {{PressureObserver/disconnect()}} will stop observing all sources observed by previous {{PressureObserver/observe()}} calls. </p> <p> Additionally it will clear all pending records collected since the last callback was invoked. </p> <pre class="example js" title="how to tell the observer to stop watching for any state changes"> const observer = new PressureObserver(records => { // do something with records. }); observer.observe("cpu"); observer.observe("gpu"); // some time later... observer.disconnect(); // records will be an empty array, because of the previous disconnect(). const records = observer.takeRecords(); </pre> </section> <section id="conformance"> <p> This specification defines conformance criteria for a single product: a <dfn>user agent</dfn> that implements the interfaces that it contains. </p> </section> <section class="appendix informative" id="acknowledgments"> <h2>Acknowledgments</h2> <p> Many thanks for valuable feedback and advice from <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME> </p> <p> Thanks to the W3C Privacy Interest Group (PING) and especially <NAME> for the privacy review and feedback. </p> <p> Special thanks to <NAME>, <NAME>, <NAME> and others from the Zoom engineering team for the feedback and hands-on experiments that have helped improve this API in real-world scenarios. </p> </section> <section id="idl-index" class="appendix"> <!-- All the Web IDL will magically appear here --> </section> <file_sep># Security and Privacy Questionnaire [Security and Privacy questionnaire](https://www.w3.org/TR/security-privacy-questionnaire/) responses for the Compute Pressure API ### 2.1. What information might this feature expose to Web sites or other parties, and for what purposes is that exposure necessary? This API exposes a high-level pressure state, consisting of four levels, used to indicate whether the system is under pressure and how serious that pressure is. This allows websites to react to increases in pressure to reduce it before it results in throttling or applications fighting over compute resources. Though generally having a nice smooth system is preferred from a user point of view, such throttling can be detrimental to certain application types such as e-sports, games and video conferencing. In e-sports and games, throttling can result in input lag making you lose the game, and in video conferencing systems, throttling can result in connection breakage - important words not coming across, or even making it impossible to type up minutes while listening to others talk. Earlier approach --- An earlier revision of this feature exposed CPU utilization and frequency (clock ticks) with certain modifications as the values being averaged across cores and normalized to a value between 0 and 1 (ignoring certain kinds of boost modes). The website could then configure a certain set of thresholds they were interested in, but the amount of thresholds would depend on the user agent. This resulted in lots of uncertainties and issues. Like some early adopters were uncertain why certain thresholds were never crossed due to having created one too many thresholds. Also, utilization and frequency are not the best metrics available. For instance, thermal conditions can easily affect throttling. Utilization might also be artificially high because certain processes are stalled on I/O. Additionally, CPU design is becoming heterogeneous with different kind of cores (e.g. performance core vs efficient core). There are even systems today with more than 3 different core types, where all cores are never active at the same time. This makes it very hard to look at aggregates and normalized utilization and frequency and base programming decisions upon that in a way that they make sense across a wide range of current and future devices. The new design allows the user agent or underlying system to provide much better pressure levels depending on the host system without the user needing to know what system the code is running on. ### 2.2. Is this specification exposing the minimum amount of information necessary to power the feature? The API design aggressively limits the amount of information exposed. The information is exposed as a series of change events, which makes it easy for user agents to rate-limit the amount of information revealed over time. The specification encourages user agents to rate-limit background windows more aggressively than the window the user is interacting with. ### 2.3. How does this specification deal with personal information or personally-identifiable information or information derived thereof? The information exposed by this API is not personal information or personally-identifiable information. ### 2.4. How does this specification deal with sensitive information? The information exposed by this API is not sensitive information. ### 2.5. Does this specification introduce new state for an origin that persists across browsing sessions? This API does not introduce any new persistent state. It exposes device data that is likely to change every second. ### 2.6. What information from the underlying platform, e.g. configuration data, is exposed by this specification to an origin? Aside from the data detailed in question 1, which is data about an instanteneous state of the device, no additional data is exposed. ### 2.7. Does this specification allow an origin access to sensors on a user’s device This specification does not allow direct access to sensors. However, the CPU clock speed may be used to make broad inferences about the device's temperature. ### 2.8. What data does this specification expose to an origin? Please also document what data is identical to data exposed by other features, in the same or different contexts. See answer to question 1. Some information about CPU utilization can be inferred from the timing of [requestAnimationFrame()](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)'s callbacks. ### 2.9. Does this specification enable new script execution/loading mechanisms? No. ### 2.10. Does this specification allow an origin to access other devices? No. ### 2.11. Does this specification allow an origin some measure of control over a user agent’s native UI? No. ### 2.12. What temporary identifiers might this specification create or expose to the web? The data obtained in step 1 could pose a cross-origin identification issue, however, we think our mitigations would prevent this risk. ### 2.13. How does this specification distinguish between behavior in first-party and third-party contexts? The specified API will not be available in third-party contexts. ### 2.14. How does this specification work in the context of a user agent’s Private Browsing or "incognito" mode? The API works the same way in Private Browsing / "incognito". We think that the cross-origin identification mitigations also prevent identification across normal and Private Browsing modes. ### 2.15. Does this specification have a "Security Considerations" and "Privacy Considerations" section? ### 2.16. Does this specification allow downgrading default security characteristics? No. ### 2.17. What should this questionnaire have asked? We think that the questions here accurately capture the API's security and privacy implications. <file_sep>Support for Power Pressure === This is what we need to do in order to create a Power Pressure Observer POC. The high level states map well to power pressure, though the contributing factors don’t. We could initially leave the factors array empty until we find some factors that would be useful to developers. Add another object or not? --- Power pressure could be supported by adding a new “power” value to the current PressureObserver and there is no real reason to create a PowerPressureObserver unless we would need different behavior or different API surface. So far that doesn’t look like the case, and adding new objects grows the size of the web engine, e.g., Chromium runtime. Also the string value allows us to specify more detailed sources in the future like e.g. power-package, power-memory etc if needed. Whether these need to be dash or dot separated is unclear, we need to check for prior art on the web platform and potentially consult with the W3C TAG By using the same object, there is also the advantage that all events of different sources will be handled by the same callback, and it is easy to split that out into multiple callbacks if needed by the developer, by just filtering the records array. CPU pressure per thread === Adding CPU pressure per thread, from an API standpoint boils down to the syntax for the enums. ```"cpu"``` today means global pressure. The bare minimum would be supporting the pressure for the app/tab/JS context itself, something like ```"cpu.self"```. We often call this the main thread but that name is not exposed in Web APIs. ```"cpu.self"``` could also work well for workers, but it’s a question whether we would allow a worker to get access to the telemetry for its owner/parent. We could add something like ```"cpu.owner"``` or ```"cpu.parent"```, but we would need to handle the owner being a worker itself. There are specific threads outside of the main thread and worker thread that developers are interested in, especially for video conferencing / game streaming. Web RTC is often used and though it uses two threads, we could probably expose this as ```"cpu.rtc"```. WebRTC and Chrome have separate threads for ```"cpu.camera"``` and ```"cpu.microphone"``` capture and it might make sense to expose compute pressure for these. Average pressure === Though polling frequently allows getting the most recent state, you can also be unlucky and get data at exactly the point when the system is under pressure, though that is the odd case and might not represent the state over time. Users can average values manually, though it costs JavaScript cycles and can be made more efficient lower down the stack. As averaging costs cycles it makes sense to make this an opt-in, by an option flag to the ```observe()``` method, e.g., ```observe(“cpu” { summarize: true })```. Looking at existing APIs it seems that a summarized average over the last 10 seconds, 30 seconds (half a minute) and 300 seconds (5 minutes) makes sense. This could be exposed as: ```webidl readonly attribute FrozenArray<PressureState> averages; ``` Or as individual attributes: ```webidl readonly attribute PressureState? average10s; readonly attribute PressureState? average30s; readonly attribute PressureState? average300s; ``` A step back === In reality there seems to be different kinds of use-cases for the CPU telemetry which can affect how we expose the data. One of our biggest issues has been that the data is high-level due to privacy considerations that makes it less useful for AB-testing of new code paths in live deployments. But a site interested in doing AB-testing is mostly interested in knowing the "utilization" of CPU resources (possible in addition with core type, boost modes, stalls etc.) in threads it's using (main thread, workers, camera thread etc) as well as a rough estimate of the global pressure on the system. Given it applies to its own threads, there shouldn't actually be privacy issues in exposing low level data if it is done in a platform abstracted manner, and the global pressure can still be consulted via the existing API. If we take this a step further, the use-cases for global CPU pressure really revolves around avoiding throttling and noisy fans, but there is only so much a site can do, as it might not be caused by the site itself. It is really mostly related to high thermals and consistent high global utilization. You could argue that setting frequency actually matters the most when looking at detailed data like low level utilization (as in percentage) and we could ignore frequency for the high-level states. Additionally, global CPU pressure is an important additional data point when looking at local thread utilization, as in the AB-testing case.<file_sep>/* -*- Mode: javascript; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 ; js-indent-level : 2 ; js-curly-indent-offset: 0 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ // Polyfill and alerts if (typeof Math.fround == 'undefined') { Math.fround = function(x) { return x }; } self.addEventListener ("message", computeFrame, false); // Asm.js module buffer. var buffer = new ArrayBuffer(16 * 1024 * 1024); var image = new Uint32Array(buffer); function computeFrame (e) { if (typeof e.data.terminate !== "undefined") { self.close (); return; } var message = e.data.message; // Draw the image to the local asm.js buffer. drawMandelbrot (message); // Copy the image for return. var msg_image = new Uint32Array (e.data.buffer); var width = message.width; var height = message.height; for (var i = 0; i < (width * height); i++) msg_image[i] = image[i]; self.postMessage ({worker_index: e.data.worker_index, message: message, buffer: e.data.buffer}, [e.data.buffer]); } function nonSimdAsmjsModule (global, imp, buffer) { "use asm" var b8 = new global.Uint8Array(buffer); var toF = global.Math.fround; var imul = global.Math.imul; const mk0 = 0x007fffff; function declareHeapLength() { b8[0x00ffffff] = 0; } function mandelPixelX1 (xf, yf, yd, max_iterations) { xf = toF(xf); yf = toF(yf); yd = toF(yd); max_iterations = max_iterations | 0; var z_re = toF(0), z_im = toF(0); var z_re2 = toF(0), z_im2 = toF(0); var new_re = toF(0), new_im = toF(0); var count = 0, i = 0, mi = 0; z_re = xf; z_im = yf; for (i = 0; (i | 0) < (max_iterations | 0); i = (i + 1) | 0) { z_re2 = toF(z_re * z_re); z_im2 = toF(z_im * z_im); if (toF(z_re2 + z_im2) > toF(4)) break; new_re = toF(z_re2 - z_im2); new_im = toF(toF(z_re * toF(2)) * z_im); z_re = toF(xf + new_re); z_im = toF(yf + new_im); count = (count + 1) | 0; } return count | 0; } function mapColorAndSetPixel (x, y, width, value, max_iterations) { x = x | 0; y = y | 0; width = width | 0; value = value | 0; max_iterations = max_iterations | 0; var rgb = 0, r = 0, g = 0, b = 0, index = 0; index = ((((imul((width >>> 0), (y >>> 0)) | 0) + x) | 0) * 4) | 0; if ((value | 0) == (max_iterations | 0)) { r = 0; g = 0; b = 0; } else { rgb = ~~toF(toF(toF(toF(value >>> 0) * toF(0xffff)) / toF(max_iterations >>> 0)) * toF(0xff)); r = rgb & 0xff; g = (rgb >>> 8) & 0xff; b = (rgb >>> 16) & 0xff; } b8[(index & mk0) >> 0] = r; b8[(index & mk0) + 1 >> 0] = g; b8[(index & mk0) + 2 >> 0] = b; b8[(index & mk0) + 3 >> 0] = 255; } function mandelColumnX1 (x, width, height, xf, yf, yd, max_iterations) { x = x | 0; width = width | 0; height = height | 0; xf = toF(xf); yf = toF(yf); yd = toF(yd); max_iterations = max_iterations | 0; var y = 0, m = 0; yd = toF(yd); for (y = 0; (y | 0) < (height | 0); y = (y + 1) | 0) { m = mandelPixelX1(toF(xf), toF(yf), toF(yd), max_iterations) | 0; mapColorAndSetPixel(x | 0, y | 0, width, m, max_iterations); yf = toF(yf + yd); } } function mandelX1 (width, height, xc, yc, scale, max_iterations) { width = width | 0; height = height | 0; xc = toF(xc); yc = toF(yc); scale = toF(scale); max_iterations = max_iterations | 0; var x0 = toF(0), y0 = toF(0), xd = toF(0), yd = toF(0), xf = toF(0); var x = 0; x0 = toF(xc - toF(scale * toF(1.5))); y0 = toF(yc - scale); xd = toF(toF(scale * toF(3)) / toF(width >>> 0)); yd = toF(toF(scale * toF(2)) / toF(height >>> 0)); xf = x0; for (x = 0; (x | 0) < (width | 0); x = (x + 1) | 0) { mandelColumnX1(x, width, height, xf, y0, yd, max_iterations); xf = toF(xf + xd); } } function mandel (width, height, xc, yc, scale, max_iterations) { width = width | 0; height = height | 0; xc = toF(xc); yc = toF(yc); scale = toF(scale); max_iterations = max_iterations | 0; var x0 = toF(0), y0 = toF(0); var xd = toF(0), yd = toF(0); var xf = toF(0); var x = 0; x0 = toF(xc - toF(scale * toF(1.5))); y0 = toF(yc - scale); xd = toF(toF(scale * toF(3)) / toF(width >>> 0)); yd = toF(toF(scale * toF(2)) / toF(height >>> 0)); xf = x0; for (x = 0; (x | 0) < (width | 0); x = (x + 1) | 0) { mandelColumnX1(x, width, height, xf, y0, yd, max_iterations); xf = toF(xf + xd); } } return mandel; } var mandelNonSimd = nonSimdAsmjsModule (this, {}, buffer); function drawMandelbrot (params) { var width = params.width; var height = params.height; var scale = params.scale; var xc = params.xc; var yc = params.yc; var max_iterations = params.max_iterations; mandelNonSimd(width, height, xc, yc, scale, max_iterations); }<file_sep># API Surface Changes This file describes API surface changes made during experimentation. A first Origin Trial was carried out between [M92–M94](https://chromestatus.com/feature/5597608644968448). No real feedback was shared by Google with other parties, incl. Intel. At the beginning of 2022, the ownership of the Compute Pressure API was transferred to Intel. ## Changes since last Origin Trial After research and discussions with interested parties (e.g., Google, Zoom, and others), we decided to make the following major changes to the API shape: - For better ergonomics, and due to security and fingerprinting [concerns](https://github.com/w3c/compute-pressure/issues/24), the API [interfaces](https://www.w3.org/TR/compute-pressure/#the-pressurerecord-interface) have been redesigned to not use developer-configurable buckets, but instead output pressure changes as [high level states](https://github.com/w3c/compute-pressure/blob/main/high-level-states.md). - Alignment with existing APIs: The Observer pattern used by the specification now more closely [follows](https://github.com/w3c/compute-pressure/issues/21) existing Observer based APIs on the web platform. - Partner requests: The APIs now work in iframes as well as [workers](https://github.com/w3c/compute-pressure/issues/15) (shared and dedicated) with proper security and privacy mitigations in place. In a few words, the Compute Pressure API proposed for the new OT is more mature, stable, and has been re-designed to address security and fingerprinting concerns. ## Examples of `PressureObserver` API basic usage ### Before (1st Origin Trial, Chrome M92–M94) [This explainer snapshot](https://github.com/w3c/compute-pressure/blob/aabc7dbd5d52a2c24c47edd7848a0fcb717a4a73/README.md) captures the older Compute Pressure API implemented in early experimentation. ```js function computePressureCallback(update) { // The CPU base clock speed is represented as 0.5. if (update.cpuSpeed >= 0.5 && update.cpuUtilization >= 0.9) { // Dramatically cut down compute requirements to avoid overheating. return; } // Options applied are returned with every update. if (update.options.testMode) { // The options applied may be different than those requested. // E.g. the user agent may have reduced the number of thresholds observed. console.log(`Utilization Thresholds: ${ JSON.stringify(update.options.cpuUtilizationThresholds)}`); console.log(`Speed Thresholds: ${ JSON.stringify(update.options.cpuSpeedThresholds)}`); } } const observer = new ComputePressureObserver(computePressureCallback, { // Thresholds divide the interval [0.0 .. 1.0] into ranges. cpuUtilizationThresholds: [0.75, 0.9, 0.5], // The minimum clock speed is 0, and the maximum speed is 1. 0.5 maps to // the base clock speed. cpuSpeedThresholds: [0.5], // Setting testMode to `true` will result in `computePressureCallback` to // be invoked regularly even if no thresholds have been crossed. The // computational data returned will not be informative, but this is useful // for testing if the requested options have been accepted. testMode: false, }); observer.start(); ``` ### After (Proposal for 2nd Origin Trial, Chrome M11x) [The explainer](https://github.com/w3c/compute-pressure/blob/main/README.md) and [specification](https://www.w3.org/TR/compute-pressure/) capture the latest vision for the API, implemented for further experimentation. ```js function pressureCallback(update) { if (update.status === "critical") { // Dramatically cut down compute requirements to avoid overheating. return; } } const observer = new PressureObserver(pressureCallback, { sampleRate : 1 }); observer.observe('cpu'); ``` <file_sep># How to experiment ComputePressure API with Chrome The [Compute Pressure API](https://www.w3.org/TR/compute-pressure/) is currently available in Chrome Canary and Edge Canary behind a flag. ## Own local Chromium repository (Linux): 1) Rebase to latest HEAD and compile the chromium project. 2) Launch Chrome with the command line flag --enable-features=ComputePressure. 3) Navigate to `about://flags` and enable `Experimental Web Platform features`. 4) Navigate to the demo page, https://w3c.github.io/compute-pressure/demo/. 5) Play with the demo. ## Chrome/Edge Canary (Windows Only): 1) Download a version of Chrome with ComputePressure implemented ([Chrome Canary](https://www.google.com/intl/en_ie/chrome/canary/)) ([Edge Canary](https://www.microsoftedgeinsider.com/en-us/download/canary)). 2) Find your Canary browser in the menu. <br /> <img src="pictures/win_menu_1.png" /> <br /> 3) Click right and select "properties". <br /> <img src="pictures/win_menu_2.png" /> <br /> 4) Add to the command line flags --enable-features=ComputePressure. (after the last ") <br /> <img src="pictures/win_menu_3.png" /> <br /> 5) Start your browser. 6) Navigate to `about://flags` and enable `Experimental Web Platform features`. 7) Navigate to the demo page, https://w3c.github.io/compute-pressure/demo/. 8) Play with the demo. ## Code Examples: ```javascript // Observer Callback. function pressureObserverCallback(updates) { console.log("cpu pressure state = " + updates[0].state); console.log("timestamp = " + updates[0].time); } // Create observer with 1s sample rate. observer = new PressureObserver(pressureObserverCallback, { sampleRate: 1 }); // Start observer. await observer.observe("cpu"); ``` You should see, everytime the state changes, the following: ``` cpu pressure state = nominal timestamp = 1671114838027.834 cpu pressure state = serious timestamp = 1671114914289.584 cpu pressure state = critical timestamp = 1671114926328.48 ``` Stopping observer: ``` // Stop observer. observer.unobserve('cpu'); ``` Other API calls and examples can be found in the specification. <file_sep># Compute Pressure ## Authors: * <NAME> (Intel) * <NAME> (Intel) * <NAME> (Google) * <NAME> (formerly Google) ## Participate * [Issue tracker](https://github.com/wicg/compute-pressure/issues) ## Table of Contents <!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> - [Introduction](#introduction) - [Goals / Motivating Use Cases](#goals--motivating-use-cases) - [Future Goals](#future-goals) - [Non-goals](#non-goals) - [Current approach - high-level states](#current-approach---high-level-states) - [Throttling](#throttling) - [Measuring pressure is complicated](#measuring-pressure-is-complicated) - [How to properly calculate pressure](#how-to-properly-calculate-pressure) - [Design considerations](#design-considerations) - [API flow illustrated](#api-flow-illustrated) - [Other considerations](#other-considerations) - [Observer API](#observer-api) - [Key scenarios](#key-scenarios) - [Adjusting the number of video feeds based on CPU usage](#adjusting-the-number-of-video-feeds-based-on-cpu-usage) - [Detailed design discussion](#detailed-design-discussion) - [Prevent instead of mitigate bad user experiences](#prevent-instead-of-mitigate-bad-user-experiences) - [Third-party contexts](#third-party-contexts) - [Considered alternatives](#considered-alternatives) - [Expose a thermal throttling indicator](#expose-a-thermal-throttling-indicator) - [Stakeholder Feedback / Opposition](#stakeholder-feedback--opposition) - [References & acknowledgments](#references--acknowledgments) <!-- END doctoc generated TOC please keep comment here to allow auto update --> ## Introduction >🆕✨ We propose a new API that conveys the utilization of system resources, initially focusing on CPU resources (v1) with the plan to add other resources such as GPU resources in the future (post v1). In a perfect world, a computing device is able to perform all the tasks assigned to it with guaranteed and consistent quality of service. In practice, the system is constantly balancing the needs of multiple tasks that compete for shared system resources. The underlying system software tries to minimize both the overall wait time and response time (time to interactive) and maximize throughput and fairness across multiple tasks running concurrently. This scheduling action is handled by an operating system module called scheduler whose work may also be assisted by hardware in modern systems. Notably, all this is transparent to web applications, and as a consequence, the user is only made aware the system is too busy when there's already a perceived degradation in quality of service. For example, a video conferencing application starts dropping video frames, or worse, the audio cuts out. As this is undesirable for the end-user, software developers would like to avoid such cases and balance the set of enabled features and their quality level against the resource pressure of the end-user device. ## Goals / Motivating Use Cases The primary use cases enhanced by v1 are video conferencing and video games. These popular [real-time applications](https://en.wikipedia.org/wiki/Real-time_computing#Criteria_for_real-time_computing) are classified as _soft_. That is, the quality of service degrades if the system is exercised beyond certain states, but does not lead to a total system failure. These _soft_ real-time applications greatly benefit from being able to adapt their workloads based on CPU consumption/pressure. Specifically, v1 aims to facilitate the following adaptation decisions for these use cases: * Video conferencing * Adjust the number of video feeds shown simultaneously during calls with many participants * Reduce the quality of video processing (video resolution, frames per second) * Skip non-essential video processing, such as some [camera filters](https://snapcamera.snapchat.com/) * Disable non-essential audio processing, such as [WebRTC noise suppression](https://w3c.github.io/mediacapture-main/#dom-mediatrackconstraintset-noisesuppression) * Turn quality-vs-speed and size-vs-speed knobs towards “speed” in video and audio encoding (in [WebRTC](https://webrtc.org/), [WebCodecs](https://wicg.github.io/web-codecs/), or software encoding) * Video games * Use lower-quality assets to compose the game’s video (3D models, textures, shaders) and audio (voices, sound effects) * Disable effects that result in less realistic non-essential details (water / cloth / fire animations, skin luminance, glare effects, physical simulations that don’t impact gameplay) * Tweak quality-vs-speed knobs in the game’s rendering engine (shadows quality, texture filtering, view distance) Technically these can be accomplished by knowing thermal states (e.g., is the system being passively cooled - throttled) as well as CPU pressure states for the threads the site is using such as main thread and workers. System thermal state is a global state and can be affected by other apps and sites than the observing site. ### Future Goals Post v1 we plan to explore support for other resource types, such as GPU resources. Additionally, we would like to investigate whether we can enable measurement of hardware resource consumption of different code paths in front end code. We aim to support the following decision processes: * Compare the CPU consumption of alternative implementations of the same feature, for the purpose of determining the most efficient implementation. We aim to support measuring CPU utilization in the field via A/B tests, because an implementation’s CPU utilization depends on the hardware it’s running on, and most developers cannot afford performance measurement labs covering all the devices owned by their users. * Estimate the impact of enabling a feature on CPU consumption. This cost estimate feeds into the decisions outlined in the primary use cases. ## Non-goals This proposal exposes a high-level abstraction that considers both CPU utilization and thermal throttling. This limitation leaves out some resource consumption decisions that Web applications could make to avoid bad the user experiences mentioned in the introduction. The following decisions will not be supported by this proposal: * Routing video processing, such as [background replacement](https://support.google.com/meet/answer/10058482), to the CPU (via [WebAssembly](https://webassembly.org/)) or to the GPU (via [WebGL](https://www.khronos.org/webgl/) / [WebGPU](https://gpuweb.github.io/gpuweb/)). * Routing video encoding or decoding to an accelerated hardware implementation (via [WebCodecs](https://wicg.github.io/web-codecs/)) or software (via WebAssembly). Video conferencing applications and games would require the following information to make the decisions enumerated above: * GPU utilization * CPU capabilities, such as number of cores, core speed, cache size * CPU vendor and model ## Current approach - high-level states The API defines a set of pressure states delivered to a web application to signal when adaptation of the workload is appropriate to ensure consistent quality of service. The signal is proactively delivered when the system pressure trend is rising to allow timely adaptation. And conversely, when the pressure eases, a signal is provided to allow the web application to adapt accordingly. Human-readable pressure states with semantics attached to them improve ergonomics for web developers and provide future-proofing against diversity of hardware. Furthermore, the high-level states abstract away complexities of system bottlenecks that cannot be adequately explained with low-level metrics such as processor clock speed and utilization. For instance, a processor might have additional cores that work can be distributed to in certain cases, and it might be able to adjust clock speed. The faster clock speed a processor runs at, the more power it consumes which can affect battery and the temperature of the processor. A processor that runs hot may become unstable and crash or even burn. For this reason processors adjust clock speed all the time based on factors such as the amount of work, whether the device is on battery power or not (AC vs DC power) and whether the cooling system can keep the processor cool. Work often comes in bursts. For example, when the user is performing a certain operation that requires the system to be both fast and responsive, modern processors use multiple boost modes to temporarily runs the processor at an extremely high clock rate in order to get work out of the way and return to normal operation faster. When this happens in short bursts it does not heat up the processor too much. This is more complex in real life because boost frequencies depend on how many cores are utilized among other factors. The high-level states proposal hides all this complexity from the web developer. Throttling --- A processor might be throttled, run slower than usual, resulting in a poorer user experience. This can happen for a number of reasons, for example: - The temperature of the processor is higher than what can be sustained for longer periods of time - Other bottlenecks exists in the system, e.g. work is blocked on memory access - System is battery-powered (DC), or its battery level is low - The user has explicitly set or the system is preconfigured with a preference for longer battery life over high performance, or better acoustic performance User's preferences affecting throttling may be configured by the user via operating system provided affordances while some may be preconfigured policies set by the hardware vendor. These factor are often dynamically adjusted taking user's preference into consideration. Measuring pressure is complicated --- Using utilization as a measurement for pressure is suboptimal. What you may think 90% CPU utilization means: ``` _____________________________________________________________________ | | | | Busy | Waiting | | | (idle) | |_________________________________________________________|___________| ``` What it might really mean is: ``` _____________________________________________________________________ | | | | | Busy | Waiting | Waiting | | | (Stalled) | (idle) | |__________|______________________________________________|___________| ``` Stalled means that the processor is not making forward progress with instructions, and this usually happens because it is waiting on memory I/O. Chances are, you're mostly stalled. This is even more complicated when the processor has multiple cores and the cores you are using are busy but your work cannot simply be distributed to other cores. The overall system processor utilization may be low for nonobvious reasons. An active core can be running slower waiting on memory I/O, or it may be busy but is throttled due to thermals. Furthermore, some modern systems have different kind of cores, such as performance cores and efficiency cores, or even multiple levels of such. You can imagine a system with just an efficiency core running when workload is nominal (background check of notifications etc.) and performance cores taking over to prioritize UX when an application is in active use. In this scenario, system will never reach 100% overall utilizations as the efficiency core will never run when other cores are in use. Clock frequency is likewise a misleading measurement as the frequency is impacted by factors such as which core is active, whether the system is on battery power or plugged in, boost mode being active or not, or other factors. How to properly calculate pressure --- Properly calculating pressure is architecture dependent and as such an implementation must consider multiple input signals that may vary by architecture, form factor, or other system characteristics. Possible signals could be, for example: * AC or DC power state * Thermals * Some weighted values of “utilization” including information about memory I/O A better metric than utilization could be CPI (clock ticks per instruction, retained) that reports the amount of clock ticks it takes on average to execute an instruction. If the processor is waiting on memory I/O, CPI is rising sharply. If CPI is around or below 1, the system is usually doing well. This is also architecture dependent as some complex instructions take up multiple instructions. A competent implementation will take this into consideration. Design considerations --- In order to enable web applications to react to changes in pressure with minimal degration in quality or service, or user experience, it is important to be notified while you can still adjust your workloads (temporal relevance), and not when the system is already being throttled. It is equally important to not notify too often for both privacy (data minimization) and developer ergonomics (conceptual weight minimization) reasons. In order to expose the minimum data necessary at the highest level of abstraction that satisfy the use cases, we suggest the following buckets: ⚪ **Nominal**: Work is minimal and the system is running on lower clock speed to preserve power. 🟢 **Fair**: The system is doing fine, everything is smooth and it can take on additional work without issues. 🟡 **Serious**: There is some serious pressure on the system, but it is sustainable and the system is doing well, but it is getting close to its limits: * Clock speed (depending on AC or DC power) is consistently high * Thermals are high but system can handle it At this point, if you add more work the system may move into critical. 🔴 **Critical**: The system is now about to reach its limits, but it hasn’t reached _the_ limit yet. Critical doesn’t mean that the system is being actively throttled, but this state is not sustainable for the long run and might result in throttling if the workload remains the same. This signal is the last call for the web application to lighten its workload. API flow illustrated --- As an example, a video conferencing app might have the following dialogue with the API: > **Developer**: *How is pressure?* > **System**: 🟢 *It's fair* > **Developer**: *OK, I'll use a better, more compute intensive audio codec* > **System**: 🟢 *Pressure is still fair* > **Developer**: *Show video stream for 8 instead of 4 people* > **System**: 🟡 *OK, pressure is now serious* > **Developer**: *Great, we are doing good and the user experience is optimal!* > **System**: 🔴 *The user turned on background blur, pressure is now critical. If you stay in this state for extended time, the system might start throttling* > **Developer**: *OK, let’s only show video stream for 4 people (instead of 8) and tell the users to turn off background blur for a better experience* > **System**: 🟡 *User still wants to keep background blur on, but pressure is now back to serious, so we are doing good* Other considerations --- There are a lot of advantages to using the above states. For once, it is easier for web developers to understand. What web developers care about is delivering the best user experience to their users given the available resources that vary depending on the system. This may mean taking the system to its limits as long as it provides a better experience, but avoiding taxing the system so much that it starts throttling work. Another advantage is that this high-level abstraction allows for considering multiple signals and adapts to constant innovation in software and hardware below the API layer. For instance, a CPU can consider memory pressure, thermal conditions and map them to these states. As the industry strives to make the fastest silicon that offers the best user experience, it is important that the API abstraction that developers will depend on is future-proof and stands the test of time. If we'd expose low-level raw values such as clock speed, a developer might hardcode in the application logic that everything above 90% the base clock is considered critical, which could be the case on some systems today, but wouldn't generalize well. For example, on a desktop form factor or on a properly cooled laptop with an advanced CPU, you might go way beyond the base clock with frequency boosting without negative impacting user experience, while a passively-cooled mobile device would likely behave differently. ## Observer API We propose a design similar to [Intersection Observer](https://w3c.github.io/IntersectionObserver/) to let applications be notified when the system's pressure changes. ```js function callback(entries) { const lastEntry = entries[entries.length - 1]; console.log(`Current pressure ${lastEntry.state}`); } const observer = new PressureObserver(callback, { sampleRate: 1 }); await observer.observe("cpu"); ``` ## Key scenarios ### Adjusting the number of video feeds based on CPU usage In this more advanced example we lower the number of concurrent video streams if pressure becomes critical. As lowering the amount of streams might not result in exiting the critical state, or at least not immediately, we use a strategy where we lower one stream at the time every 30 seconds while still in the critical state. The example accomplishes this by creating an async iterable that will end iterating as soon as the pressure exists critical state, or every 30 seconds until then. ```js // Utility: A Promise that is also an Iterable that will iterate // at a given interval until the promise resolves. class IteratablePromise extends Promise { #interval; #fallback; constructor(fn, interval, fallbackValue) { super(fn); this.#interval = interval; this.#fallback = fallback; } async* [Symbol.asyncIterator]() { let proceed = true; this.then(() => proceed = false); yield this.#fallback; while (proceed) { let value = await Promise.any([ this, new Promise(resolve => setTimeout(resolve, this.#interval)) ]); yield value || this.#fallback; } } }; ``` ```js // Allow to resolve a promise externally by calling resolveFn let resolveFn = null; function executor(resolve) { resolveFn = value => resolve(value) } async function lowerStreamCountWhileCritical() { let streamsCount = getStreamsCount(); let iter = new IteratablePromise(executor, 30_000, "critical"); for await (const state of iter) { if (state !== "critical" || streamsCount == 1) { break; } setStreamsCount(streamsCount--); } } function pressureChange(entries) { for (const entry of entries) { if (resolveFn) { resolveFn(entry.state); resolveFn = null; continue; } if (entry.state == "critical") { lowerStreamCountWhileCritical(); } } } const observer = new PressureObserver(pressureChange, { sampleRate: 1 }); await observer.observe("cpu"); ``` ## Detailed design discussion ### Prevent instead of mitigate bad user experiences A key goal for our proposal is to prevent, rather than mitigate, bad user experience. Mobile devices such as laptops, smartphones and tablets, when pushed into high CPU or GPU utilization may cause the device to become uncomfortably hot, cause the device’s fans to get disturbingly loud, or drain the battery at an unacceptable rate. The key goal above disqualifies solutions such as [requestAnimationFrame()](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame), which lead towards a feedback system where **bad user experience is mitigated, but not completely avoided**. Feedback systems have been successful on desktop computers, where the user is insulated from the device's temperature changes, the fan noise variation is not as significant, and DC power means stable power supply. ### Third-party contexts This API will only be available in frames served from the same origin as the top-level frame. This requirement is necessary for preserving the privacy benefits of the API's quantizing scheme. The same-origin requirement above implies that the API is only available in first-party contexts. ## Considered alternatives ### Expose a thermal throttling indicator On some operating systems and devices, applications can detect when thermal throttling occurs. Thermal throttling is a strong indicator of a bad user experience (high temperature, CPU cooling fans maxed out). This option was discarded because of concerns that the need to mitigate [some recent attacks](https://platypusattack.com/) may lead to significant changes in the APIs that this proposal was envisioning using. Theoretically, Chrome [can detect thermal throttling](https://source.chromium.org/chromium/chromium/src/+/master:base/power_monitor/) on Android, Chrome OS, and macOS. However, developer experience suggests that the macOS API is not reliable. ## Stakeholder Feedback / Opposition * Chrome: Positive * Gecko: Negative * WebKit: TODO * Web developers: Positive ## References & acknowledgments Many thanks for valuable feedback and advice from: * <NAME> * <NAME> * <NAME> * <NAME> * <NAME> * <NAME> * <NAME> * <NAME> * <NAME> * <NAME> * <NAME> * <NAME> * <NAME> * <NAME> * <NAME> * <NAME> * <NAME> * <NAME> * <NAME> Exposing CPU utilization information has been explored in the following places. * [WebPerf June 2019 discussion notes](https://docs.google.com/document/d/1uQ7pXwuBv-1jitYou7TALJxV0tllXLxTyEjA2n1mSzY/) * [Chrome extensions API for CPU metadata](https://developer.chrome.com/docs/extensions/reference/system_cpu/) * [Chrome extensions API for per-process CPU utilization](https://developer.chrome.com/docs/extensions/reference/processes/) * [IOPMCopyCPUPowerStatus](https://developer.apple.com/documentation/iokit/1557079-iopmcopycpupowerstatus?language=objc) in IOKit/[IOPMLib.h](https://opensource.apple.com/source/IOKitUser/IOKitUser-647.6/pwr_mgt.subproj/IOPMLib.h) * [user-land source](https://opensource.apple.com/source/IOKitUser/IOKitUser-388/pwr_mgt.subproj/IOPMPowerNotifications.c.auto.html) * [Windows 10 Task Manager screenshot](https://answers.microsoft.com/en-us/windows/forum/windows_10-other_settings-winpc/windows-10-only-use-half-of-max-cpu-speed/d97b219f-10ee-4a42-a0fc-d517c1b60be8) * [CPU usage exceeds 100% in Task Manager and Performance Monitor if Intel Turbo Boost is active](https://docs.microsoft.com/sv-SE/troubleshoot/windows-client/performance/cpu-usage-exceeds-100) This explainer is based on [the W3C TAG's template](https://w3ctag.github.io/explainers). <file_sep>A collection of Implementation notes Terminology === Utilization --- Processing Unit utilization refers to a device’s usage of the processing resources, or the amount of work handled by a processing unit. Not every task requires heavy utilization time as the task might depend on other resources, such as reading data from memory. Processing units often contain multiple execution units/cores, so utilization MAY refers to the average percentage of the total working time of all execution units. As an example, for a CPU, the utilization is the fraction of time that each core has been executing code belonging to a thread, as opposed to being in an idle state. Processing Units are designed to run safely at 100% utilization. However, it means they have reached their limit and cannot take on additional work and maybe not even handle the current work at hand, resulting in perceptible slowness. Load --- For CPUs, it is common to consider load in addition to utilization. Load is the number of processes (queue length) being executed or waiting to be by the CPU. When a system is heavily loaded, its CPU utilization is likely close to 100%, though a system with 2 processes in the queue and one with 10 are not comparable. For this reason it is common to look at load average (average system load over a period of time) as a set of three numbers, which represent the load during the last one-, five-, and fifteen-minute periods. Frequency --- Processing units run at a certain frequency, also known as clock rate, expressed in cycles per second (e.g. gigahertz). The base frequency is a measure that the CPU manufacturer guarantees the processing unit can run at with reasonable cooling. To avoid processing units running at 100% utilization for long, some processing units can use dynamic frequency scaling to temporarily boost the frequency of a certain execution unit and then assign the largest task to it, alleviating the poor user experience in many situations. The processing unit will try to increase the operating frequency in regular increments (steps) as required to meet demand. The increased frequency is limited by the processing unit's power, current, and thermal limits, the number of execution units currently in use, and the maximum frequency of the active ones. Dynamic Frequency Scaling can also be used to throttle the execution, by slowing down the frequency to use less energy and conserve battery, especially in laptops. Throttling can also happen as a result of an processing unit reaching its thermal limits. This thermal throttling helps cool the processing unit down when it gets too hot by lowering the frequency. Concepts === CPU frequency --- CPU cores may support a variety of complex dynamic frequency scaling technologies to raise the clock frequency beyond the base frequency (max frequency without boosting). The boosting max frequency can depend on the type of core in heterogeneous systems, but even the same cores can have different max frequency. In modern Intel CPUs, one or two P-cores (performance cores) are considered <em>favored cores</em> with even higher max frequency. Beyond this, Intel CPUs might support <em>Thermal Velocity Boost</em> (TVB), which allows an even higher frequency, going beyond the max frequency if the CPU's within temperature limits and turbo power budget is available. Overclocked CPUs can similarly go beyond the boosting max frequency. Frequencies beyond boosting max frequency are ignored by this specification and frequencies are clamped to the boosting max frequency. More information about Intel based boosting technologies <a href="https://www.intel.com/content/www/us/en/gaming/resources/how-intel-technologies-boost-cpu-performance.html"> here</a>. Aggregating CPU utilization --- CPU utilization can averaged over all enabled CPU cores. Under normal circumstances, all of a system's cores are enabled. However, mitigating some recent micro-architectural attacks on some devices may require completely disabling some CPU cores. For example, some Intel systems require disabling hyperthreading. We recommend that user agents aggregate CPU utilization over a time window of 1 second. Smaller windows increase the risk of facilitating a side-channel attack. Larger windows reduce the application's ability to make timely decisions that avoid bad user experiences. <file_sep>High-level states === What is compute pressure? --- In a perfect world, a computing device is able to perform all the tasks assigned to it with guaranteed and consistent quality of service. In practice, the system is constantly balancing the needs of multiple tasks that compete for shared system resources. The underlying system software tries to minimize both the overall wait time and response time (time to interactive) and maximize throughput and fairness across multiple tasks running concurrently. This scheduling action is handled by an operating system module called scheduler whose work may also be assisted by hardware in modern systems. Notably, all this is transparent to web applications, and as a consequence, the user is only made aware the system is too busy when there's already a perceived degradation in quality of service. For example, a video conferencing application starts dropping video frames, or worse, the audio cuts out. Compute Pressure specification defines a set of compute pressure states delivered to a web application to signal when adaptation of the workload is appropriate to ensure consistent quality of service. The signal is proactively delivered when the compute pressure trend is rising to allow timely adaptation. And conversely, when the pressure eases, a signal is provided to allow the web application to adapt accordingly. Human-readable compute pressure states with semantics attached to them improve ergonomics for web developers and provide future-proofing against diversity of hardware. Furthermore, the high-level states abstract away complexities of system bottlenecks that cannot be adequately explained with low-level metrics such as processor clock speed and utilization. For instance, a processor might have additional cores that work can be distributed to in certain cases, and it might be able to adjust clock speed. The faster clock speed a processor runs at, the more power it consumes which can affect battery and the temperature of the processor. A processor that runs hot becomes unstable and may crash or even burn. For this reason processors adjust clock speed all the time, given the amount of work and whether it's on battery power or not (AC vs DC power) and whether the cooling system can keep the processor cool. Work often comes in bursts, like when the user is performing a certain operation, and in order to keep the system fast and responsive, modern processors use multiple boost modes, where it temporarily runs at an extremely high clock rate in order to get work out of the way and return to normal operations. As this happens in short bursts that is possible without heating up the processor too much. This is even more complex as boost frequencies depend on how many cores are utilized etc. Throttling --- A processor might be throttled, run slower than usual, resulting in a poorer user experience. This can happen for a number of reasons, for example: - The temperature of the processor is hotter than that can be sustained - Other bottlenecks in the system, like work blocking on memory access - System is DC (battery) powered so longer battery life is preferred instead of high clock speed - To keep system more quiet (less fans) as a user preference Measuring compute pressure is quite complicated --- Using utilization as a measurement for compute pressure is suboptimal. What you may think 90% CPU utilization means: ``` _____________________________________________________________________ | | | | Busy | Waiting | | | (idle) | |_________________________________________________________|___________| ``` What it might really mean is: ``` _____________________________________________________________________ | | | | | Busy | Waiting | Waiting | | | (Stalled) | (idle) | |__________|______________________________________________|___________| ``` Stalled means that the processor is not making forward progress with instructions, and this usually happens because it is waiting on memory I/O. Chances are, you're mostly stalled. This is even more complicated when the processor has multiple cores and the cores you are using are busy but your work cannot simply be distributed to other cores. If you look at the overall system processor utilization it might be quite low, but your core can be running slower than usual as it is waiting on memory I/O, or it might even be actually busy but be throttled due to thermals. Furthermore, some modern systems have different kinds of cores, such as performance cores and efficiency cores, or even multiple levels of such. You can imagine a system with just an efficiency core running when workload is nominal (background check of notifications etc.) and performance cores taking over to prioritize UX when an application is in active use. In this scenario, system will never reach 100% overall utilizations as the efficiency core will never run when other cores are in use. Clock frequency is likewise a misleading measurement as the frequency is impacted by factors such as which core is active, whether the system is on battery power or plugged in, boost mode being active or not, or other factors. How to properly calculate pressure --- Properly calculating compute pressure is architecture dependent and as such an implementation must consider multiple input signals that may vary by architecure, form factor, or other system characteristics. Possible signals could be, for example: * AC or DC power state * Thermals * Some weighted values of “utilization” including information about memory I/O A better metric than utilization could be CPI (clock ticks per instruction, retained) that reports the amount of clock ticks it takes on average to execute an instruction. If the processor is waiting on memory I/O, CPI is rising sharply. If CPI is around or below 1, the system is usually doing well. This is also architecture dependent as some complex instructions take up multiple instructions. A competent implementation will take this into consideration. Design considerations --- In order to enable web applications to react to changes in compute pressure with minimal degration in quality or service, or user experience, it is important to be notified while you can still adjust your workloads (temporal relevance), and not when the system is already being throttled. It is equally important to not notify too often for both privacy (data minimization) and developer ergonomics (conceptual weight minimization) reasons. In order to expose the minimum data necessary at the highest level of abstraction that satisfy the use cases, we suggest the following buckets: ⚪ **Nominal**: Work is minimal and the system is running on lower clock speed to preserve power. 🟢 **Fair**: The system is doing fine, everything is smooth and it can take on additional work without issues. 🟡 **Serious**: There is some serious pressure on the system, but it is sustainable and the system is doing well, but it is getting close to its limits: * Clock speed (depending on AC or DC power) is consistently high * Thermals are high but system can handle it At this point, if you add more work the system may move into critical. 🔴 **Critical**: The system is now about to reach its limits, but it hasn’t reached _the_ limit yet. Critical doesn’t mean that the system is being actively throttled, but this state is not sustainable for the long run and might result in throttling if the workload remains the same. This signal is the last call for the web application to lighten its workload. API flow illustrated --- As an example, a video conferencing app might have the following dialogue with the API: > **Developer**: *How is pressure?* > **System**: 🟢 *It's fair* > **Developer**: *OK, I'll use a better, more compute intensive audio codec* > **System**: 🟢 *Pressure is still fair* > **Developer**: *Show video stream for 8 instead of 4 people* > **System**: 🟡 *OK, pressure is now serious* > **Developer**: *Great, we are doing good and the user experience is optimal!* > **System**: 🔴 *The user turned on background blur, pressure is now critical. If you stay in this state for extended time, the system might start throttling* > **Developer**: *OK, let’s only show video stream for 4 people (instead of 8) and tell the users to turn off background blur for a better experience* > **System**: 🟡 *User still wants to keep background blur on, but pressure is now back to serious, so we are doing good* Other considerations --- There are a lot of advantages to using the above states. For once, it is easier for web developers to understand. What web developers care about is delivering the best user experience to their users given the available resources that vary depending on the system. This may mean taking the system to its limits as long as it provides a better experience, but avoiding taxing the system so much that it starts throttling work. Another advantage is that this high-level abstraction allows for considering multiple signals and adapts to constant innovation in software and hardware below the API layer. For instance, a CPU can consider memory pressure, thermal conditions and map them to these states. As the industry strives to make the fastest silicon that offers the best user experience, it is important that the API abstraction that developers will depend on is future-proof and stands the test of time. If we'd expose low-level raw values such as clock speed, a developer might hardcode in the application logic that everything above 90% the base clock is considered critical, which could be the case on some systems today, but wouldn't generalize well. For example, on a desktop form factor or on a properly cooled laptop with an advanced CPU, you might go way beyond the base clock with frequency boosting without negative impacting user experience, while a passively-cooled mobile device would likely behave differently.
f7181daa948f96ec0296c1c090196858e8f80d2f
[ "Markdown", "JavaScript", "HTML" ]
9
HTML
oyiptong/compute-pressure
5ab53da9e280842a8964f9b1a088b27377e42e1d
c28bd08791b939b30860ae921ef574fbd5096863
refs/heads/master
<file_sep>// // findLoopWay.swift // ScenicSpotSystem // // Created by ffm on 16/11/24. // Copyright © 2016年 ITPanda. All rights reserved. // /* 4、输出导游路线图中的回路。 思路,跟深度遍历一样进行递归,然后另外定义一个数组,把每次走的点的名字记录下来(记录路径) 每走下一步,然后都往路径里面 思路有误。(无向) 1.先判断是否有回路 (计算度 ,把每个结点度都大于1那就肯定了,如果有存在1的,删掉,并相应结点扣1 如果都大于2 那就存在 2.当存在回路,就进行寻找 3.深度优先遍历,当遇到起始点的时候,标记,然后继续,遍历完,退栈,看有否更短的其他路径,(注意排除只有2个结点的环 胜利竣工✌️,思路主要是记录走过的路径,每准备走下一步的时候,对下一个点进行多重判断 如果没遍历过,则当前点设为它,如果遍历过,判断是否是起点,如果是起点,则判断长度,如果符合形成回路的长度,则证明发现了一个回路 代码再重构! 大量优化代码,极大缩小代码篇幅, 当遇到遍历过的点,其实也不用管他是不是顶点了 */ import Foundation public func findLoopWay(graph:Graph) { print("以下为图中所有的回路!") var path:[String] = [] resetAceNodes(arr: &graph.vertexArr) for vertex:ArcNode in graph.vertexArr { if !vertex.visited { moveToNext(graph: graph, path: &path ,vertex: vertex) } } resetAceNodes(arr: &graph.vertexArr) } func moveToNext(graph:Graph, path:inout [String] ,vertex:ArcNode) { vertex.visited = true path.append(vertex.name) for connectedEdge:Edge in vertex.connectedEdgeArr { let nextPointName:String = connectedEdge.endPoint.name let nextPoint:ArcNode = graph.getArcNode(vertexName: nextPointName)! if !nextPoint.visited { moveToNext(graph: graph, path:&path ,vertex: nextPoint) } else { //走过的点,判断是否满足产生回路的条件 let lastTimePointIndex:Int = findLastSamePointInPath(path: path, pointName: nextPointName) if path.count - lastTimePointIndex - 1 > 1 { let pathNSArray:NSArray = path as NSArray let range = NSMakeRange(lastTimePointIndex, path.count-lastTimePointIndex) let loop = pathNSArray.subarray(with: range) for str in loop { print("\(str)-->",terminator:"") } print(nextPointName) } } } path.removeLast() //要退一步的时候,模拟进行退栈,把最后一个元素移除 } func findVertexIndexInVertexArr(graph:Graph, vertex:ArcNode) -> Int { //这里假设传个Array,要有泛型[Arcnode] 还不如干脆整个graph传过来 for i in 0 ..< graph.vertexArr.count { let temp:ArcNode = graph.vertexArr[i] if temp.name == vertex.name { return i } } return 32676 } func findLastSamePointInPath(path:[String], pointName:String) -> Int { for i in 0 ..< path.count { let point:String = path[i] if pointName == point { return i } } return 32676 } func resetAceNodes(arr:inout [ArcNode]) { for vertex:ArcNode in arr { vertex.visited = false } } <file_sep>// // ScenicSpotDataModel.swift // ScenicSpotSystem // // Created by ffm on 16/11/23. // Copyright © 2016年 ITPanda. All rights reserved. // import Foundation public class ScenicSpotListModel : NSObject { var name:String? var introduction:String? var popularity:String? var isHaveRestArea:String? var isHaveWC:String? init(dict:[String : Any]) { super.init() setValuesForKeys(dict) } } public class EdgeListModel : NSObject { var startPoint:String? var endPoint:String? var weight:String? init(dict:[String : Any]) { super.init() setValuesForKeys(dict) } } <file_sep>// // CreateDistributionMap.swift // ScenicSpotSystem // // Created by ffm on 16/11/23. // Copyright © 2016年 ITPanda. All rights reserved. // /* 1.创建景区景点分布图 */ import Foundation let MAX_VERTEX_NUM = 15 let MAX_EDGE_NUM = 20 //初始化数组 public func initGraphSpotArr(graph:inout Graph) { let arrSpotPlist:NSArray = readPlist(plistNameStr: "ScenicSpotList.plist") for i in 0 ..< arrSpotPlist.count { let dict = arrSpotPlist[i] let model:ScenicSpotListModel = ScenicSpotListModel.init(dict: dict as! [String : Any]) let node:ArcNode = ArcNode(name: model.name!, introduction: model.introduction!, popularity: model.popularity!, haveRestArea: model.isHaveRestArea!, haveWC: model.isHaveWC!) if graph.insertArcNode(vertex: node) { print("插入第\(i+1)个结点成功") } } } public func initGraphEdgeArr(graph:inout Graph) { let arrEdgePlist:NSArray = readPlist(plistNameStr: "EdgeList.plist") for i in 0 ..< arrEdgePlist.count { let dict = arrEdgePlist[i] let model:EdgeListModel = EdgeListModel.init(dict: dict as! [String : Any]) // let newEdge:Edge = Edge(startVertex: graph.getArcNode(vertexName: model.startPoint!)!, endVertex: graph.getArcNode(vertexName: model.endPoint!)!, edgeWeight: Int(model.weight!)!) if graph.insertEdge(vertex: graph.getArcNode(vertexName: model.startPoint!)!, anotherVertex: graph.getArcNode(vertexName: model.endPoint!)!, weight: Int(model.weight!)!) { print("插入第\(i+1)条边成功") } } } func readPlist(plistNameStr:String) -> NSArray { let path = Bundle.main.path(forResource: plistNameStr, ofType: nil) //老师看这里! 这个路径很重要啊,因为swift更新了之后这个方法的路径去到其他目录了,请务必要把plist文件移动到这打印的路径下 print(Bundle.main) //main方法返回的路径贼奇怪,换了个地,为了测试方便,直接拷贝一份plist文件到其目录下了。就不过多纠结这些了。。 let arr:NSArray = NSArray.init(contentsOfFile: path!)! return arr } public func createDistributionMap(graph:inout Graph ) { print("开始创建景区景点分布图") initGraphSpotArr(graph: &graph) initGraphEdgeArr(graph: &graph) print("创建景区景点分布图成功!") } /* 初始版本是获取用户输入,这样用户输入太多,太多错误操作要考虑而且输入数据太大,所以把数据都写到plist文件里 //获取用户输入 public func getUserInput() -> [String] { let stdInput = FileHandle.standardInput let userInput = NSString(data: stdInput.availableData, encoding: String.Encoding.utf8.rawValue) var tempArr = userInput?.components(separatedBy: " ") let tempArr2 = tempArr?.last?.components(separatedBy: "\n") //把空格去掉归并到一个数组里 tempArr?.removeLast() tempArr?.append((tempArr2?.first)!) return tempArr! } public func createDistributionMap() { print("请输入顶点数和边数") let vertexAndEdgeNum = getUserInput() let maxVertexNum:Int = (Int)(vertexAndEdgeNum.first!)! let maxEdgeNum:Int = (Int)(vertexAndEdgeNum.last!)! let graph = Graph(maxVertexNum: maxVertexNum, maxEdgeNum: maxEdgeNum) print("\n 请输入各顶点的信息\n\n请输入各顶点的名字(空格隔开)") let ScenicSpotNameArr = getUserInput() print(ScenicSpotNameArr.count) for i in 0..<(ScenicSpotNameArr.count) { let spotName = ScenicSpotNameArr[i] let spot = ArcNode(name: spotName) if graph.insertArcNode(vertex: spot) { print("插入\(spotName)节点成功") } } for i in 0..<maxEdgeNum { print("请输入第\(i+1)条边的两个顶点以及该边的权值:(空格隔开)") let edgeSetArr = getUserInput() let startSpot = graph.getArcNode(vertexName: edgeSetArr[0]) let endSpot = graph.getArcNode(vertexName: edgeSetArr[1]) let weight:Int = (Int)(edgeSetArr.last!)! if graph.insertEdge(vertex: startSpot!, anotherVertex: endSpot!, weight: weight) { print("插入边\(startSpot?.name)到\(endSpot?.name)成功,权值为\(weight)") } else { print("插入失败") } } print(graph.edgeArr) print(graph.vertexArr) print(graph.getArcNode(vertexName: "hello")?.connectedEdgeArr[0].endPoint.name) } */ <file_sep>// // outputDistributionMap.swift // ScenicSpotSystem // // Created by ffm on 16/11/23. // Copyright © 2016年 ITPanda. All rights reserved. // /* 2.输出景区景点分布图 */ import Foundation public func outputDistributionMap(graph:Graph) { print("开始输出景区景点分布图") var nameStr:String = " " for vertex:ArcNode in graph.vertexArr { nameStr="\(nameStr)\t\(vertex.name)" } print(nameStr) for vertex:ArcNode in graph.vertexArr { let startPointName:String = vertex.name var outputStr:String = startPointName for anotherVertex:ArcNode in graph.vertexArr { let endPointName:String = anotherVertex.name outputStr = "\(outputStr)\t\(graph.getWeight(vertexName: startPointName, anotherName: endPointName))" } print(outputStr) } } <file_sep>// // FindAndSort.swift // ScenicSpotSystem // // Created by ffm on 16/11/25. // Copyright © 2016年 ITPanda. All rights reserved. // //6、查找排序 /* 可以根据用户输入的关键字进行景点的查找,关键字可以在景点名称也可以在景点介绍中。 查找成功则返回景点的相关简介,如果查找不成功请给予正确提示。 */ import Foundation public func SearchScenicSpot(graph: Graph) { print("请输入要查找的景点信息(景点名称或简介包含的关键字") let info = getUserInput() let userInPut:String = info.first! let search:Serach = Serach(userInput: userInPut, graph: graph) search.startSearch() } public class Serach : NSObject { let keyWord:String? let grapah:Graph var resultPointNams:[String] = [] var vertexDict:Dictionary<String, String> init(userInput:String, graph:Graph) { self.keyWord = userInput self.grapah = graph self.vertexDict = Dictionary() } public func startSearch() { dictInit() searchInName() searchInIntroduction() outputResults() } func dictInit() { for vertex:ArcNode in self.grapah.vertexArr { self.vertexDict[vertex.name] = vertex.introduction } } func searchInName() { for key in self.vertexDict.keys { if key == self.keyWord { self.resultPointNams.append(key) } } } func searchInIntroduction() { for (key, value) in self.vertexDict { if value.contains(self.keyWord!) { self.resultPointNams.append(key) } } } func outputResults() { if self.resultPointNams.count != 0 { for str in self.resultPointNams { let suitablePoint:ArcNode = self.grapah.getArcNode(vertexName: str)! print(suitablePoint.name) print(suitablePoint.introduction) print(suitablePoint.popularity) print("休息区:\(suitablePoint.isHaveRestArea)") print("厕所:\(suitablePoint.isHaveWC)") } } else { print("没有找到符合的结果") } } } <file_sep>// // ParkingLotManageSystem.swift // ScenicSpotSystem // // Created by ffm on 16/11/25. // Copyright © 2016年 ITPanda. All rights reserved. // /* 8、车辆进出管理系统 存在bug与不足: 时间只能输入整数 在等待队列里的车其实不应该计费的,进入排队队列应该不能算停车费。 在排队队列转移到停车场的时候,应该更新他们的arriveTime才对。 */ import Foundation let MAX_PARKING_CAR_COUNT = 5 //设置停车场停车位 let PRICE_PER_HOUR = 30 public func parkingLotManageSys() { print(" ** 停车场管理程序 **") print("==========================") print("** **") print("** 1. ---- 汽车 进 车场") print("** 2. ---- 汽车 出 车场") print("** 3. ---- 退出 程序") print("** **") print("==========================") let parkingSys:ParkingLotSystem = ParkingLotSystem() var value:Int = 1 while value != 0 { print("请输入你要执行的操作") value = parkingSys.start() } } class ParkingLotSystem: NSObject { var parkingLotStack:[Car] = [] var waitingQueue:[Car] = [] var tempPark:[Car] = [] func start() -> Int { let userInp = FileHandle.standardInput let inputData = NSString(data: userInp.availableData, encoding: String.Encoding.utf8.rawValue) let carAction:Int = Int(inputData!.intValue) switch carAction { case 1: carEnter() case 2: carLeave() case 3: return 0 default: print("输入有误") } return 1 } func carEnter() { let newInCar = getCarInfo() if isParkingLotFull() { //如果停车场满了 放入等待队列末尾 self.waitingQueue.append(newInCar) print("场停车已满,该车进入等待队列,队列前面还有\(self.waitingQueue.count-1)辆车") } else { self.parkingLotStack.append(newInCar) print("你的车停在了\(self.parkingLotStack.count-1)号车位") } } func carLeave() { print("请输入要离开的车辆的车牌号:") let carID:String? = getUserInput().first! print("请输入当前的时间 (0~24)") let currentTime:Int = Int((getUserInput().first! as NSString).intValue) for (index, value) in self.parkingLotStack.enumerated() { if carID == value.carID { print("你的车在\(index)号停车位") takeCharge(currentTime: currentTime, leavingCar: value) //开始退栈,进行让路 for i in index+1 ..< self.parkingLotStack.count { //把这辆车后面的都放到tempPark里 (让路) let moveWayCar = self.parkingLotStack[i] self.tempPark.append(moveWayCar) } self.parkingLotStack.removeSubrange(index...self.parkingLotStack.count-1) //把这辆车跟后面的都退掉 for moveCar in self.tempPark { self.parkingLotStack.append(moveCar) } self.tempPark.removeAll() //记得要清空一下临时队列 if isHaveCarWaiting() { let firstWaitCar = self.waitingQueue.first self.waitingQueue.removeFirst() //哈哈哈 调用removeFirst之后,后面的元素会自动补上来 self.parkingLotStack.append(firstWaitCar!) } } } } func isParkingLotFull() -> Bool { if self.parkingLotStack.count >= MAX_PARKING_CAR_COUNT { return true } else { return false } } func isHaveCarWaiting() -> Bool { return !self.waitingQueue.isEmpty } func getCarInfo() -> Car { //获取用户输入 print("车牌为:") let carID:String = getUserInput().first! print("当前的时刻为:(0~24)") let arrTime:Int = Int((getUserInput().first as! NSString).intValue) let currentCar:Car = Car(carID: carID, arriveTime: arrTime) return currentCar } func takeCharge(currentTime:Int ,leavingCar:Car) { //进行计费 并输出 let parkTime:Int = currentTime - leavingCar.arriveTime let parkFee:Int = parkTime * PRICE_PER_HOUR print("本次停车\(parkTime)个小时,收取\(parkFee)") } } struct Car { var carID:String var arriveTime:Int init(carID:String, arriveTime:Int) { self.carID = carID self.arriveTime = arriveTime } } <file_sep>// // outputGuideLineMap.swift // ScenicSpotSystem // // Created by ffm on 16/11/23. // Copyright © 2016年 ITPanda. All rights reserved. // /* 3、输出导游路线图 深度优先遍历 之前错了!不应该在整个数组里找啊!!应该找与点相连的边 /* bugs 北门-->狮子山-->一线天-->观云台-->飞流瀑-->红叶亭-->花卉园-->朝日峰-->碧水亭-->仙武湖-->仙云石-->九曲桥-->请输入你要选择的菜单项 1.飞流瀑-->红叶亭 32676 2.花卉园-->朝日峰 找到问题所在了,原来只是输出问题,因为到达该点之后就直接输出,当走到尽头的时候,而不能撤销输出,所以看起来就好像 飞流瀑-->红叶亭 有路一样,其实只是因为输出问题 解决:先不输出,先存数组里,直到最后才进行速出 */ */ import Foundation public func outputGuiLineMap(graph:Graph) { var path:[String] = [] var pathsArr:NSMutableArray = [] var connectedVectorCount:Int = 0 for vertex:ArcNode in graph.vertexArr { vertex.visited = false } for vertex:ArcNode in graph.vertexArr { if !vertex.visited { DFSTraverse(graph: graph, path: &path, pathsArr: &pathsArr ,vertex: vertex) connectedVectorCount += 1 //联通分量 } } //查找最大值 let maxCount:Int = findTheMaxCountArr(arr: pathsArr) path = pathsArr[maxCount] as! [String] print("为您推荐的最佳导游路线一条路走到底不走回头路!") for str:String in path { if str != path.last { print("\(str)-->",terminator:"") } else { print(str) } } print("联通分量一共有\(connectedVectorCount)个") //判断两个景点间是否有直接相连的边 let temp1:ArcNode = ArcNode(name: "狮子山") // let temp2:ArcNode = ArcNode(name: "碧水亭") let temp2:ArcNode = ArcNode(name: "北门") IsEdge(graph: graph, vertex1: temp1, vertex2: temp2) } func DFSTraverse(graph:Graph, path:inout [String], pathsArr:inout NSMutableArray,vertex:ArcNode) { vertex.visited = true path.append(vertex.name) for connectedEdge:Edge in vertex.connectedEdgeArr { let nextPointName:String = connectedEdge.endPoint.name let nextPoint:ArcNode = graph.getArcNode(vertexName: nextPointName)! if !nextPoint.visited { DFSTraverse(graph: graph, path:&path, pathsArr: &pathsArr ,vertex: nextPoint) } } pathsArr.add(path) path.removeLast() } // for nextPoint:ArcNode in graph.vertexArr { 警钟长鸣,找下一个点的时候要从与该点相连的那些点里去找 // if !nextPoint.visited { // DFSTraverse(graph: &graph, vertex: nextPoint) // } // } //判断要查的这两个顶点之间是否有直接相连的边: func IsEdge(graph:Graph, vertex1:ArcNode, vertex2:ArcNode) { let weight:Int = graph.getWeight(vertexName: vertex1.name, anotherName: vertex2.name) if weight != 32676 && weight != 0 { print("\(vertex1.name)与\(vertex2.name)之间有直接相连的边!"); } else { print("\(vertex1.name)与\(vertex2.name)之间没有直接相连的边") } } //查找路径数组里面的最大值 func findTheMaxCountArr(arr:NSMutableArray) -> Int { var maxCount = 0 var maxCountArr:[String] = arr[maxCount] as! [String] for i in 1 ..< arr.count { let temp:[String] = arr[i] as! [String] if temp.count > maxCountArr.count { maxCountArr = temp maxCount = i } } return maxCount } <file_sep>// // findBestWayAndShortestWay.swift // ScenicSpotSystem // // Created by ffm on 16/11/24. // Copyright © 2016年 ITPanda. All rights reserved. // 北门 狮子山 仙云石 一线天 飞流瀑 仙武湖 九曲桥 观云台 花卉园 红叶亭 朝日峰 碧水亭 /* 求两个景点间的最短路径和最短距离。 输出路径还是有点小问题 啥时候退栈的问题。 */ import Foundation let places:[String] = ["北门", "狮子山","仙云石","一线天","飞流瀑","仙武湖","九曲桥","观云台","花卉园","红叶亭","朝日峰","碧水亭"] public func findBestWayAndShortestWay (graph:inout Graph) { print("请输入要查询的两个距离的两个景点名称(空格隔开)") let places = getUserInput() let startPlace:String = places.first! let endPlaces:String = places.last! if !places.contains(startPlace) || !places.contains(endPlaces) { print("输入地址有误!") return } let dijkstra:DijkstraTofindShortestWay = DijkstraTofindShortestWay(graph: &graph, startPoint: startPlace) dijkstra.createDistanceDict() print("最短路径为\(dijkstra.getShortesetDistanceTo(destinPoint: endPlaces))") dijkstra.showPath(destin: endPlaces) } class DijkstraTofindShortestWay: NSObject { var graph:Graph? var startPoint:String? var distToOtherPointDict:Dictionary<String, Int> var currentPoint:ArcNode? var path:[String] = [] //不另外设计为结点设置一个bool值,直接利用之前深度遍历的时候设置的 isVisited:Bool 属性作为标记 init(graph:inout Graph, startPoint:String) { self.graph = graph self.startPoint = startPoint self.distToOtherPointDict = Dictionary<String, Int>() } public func createDistanceDict() { //初始化 resetAceNodes(graph: &self.graph!) for vertex:ArcNode in (self.graph?.vertexArr)! { self.distToOtherPointDict[vertex.name] = 32676 } let startVertex:ArcNode = (self.graph?.getArcNode(vertexName: self.startPoint!))! startVertex.visited = true self.distToOtherPointDict[startPoint!] = 0 currentPoint = self.graph?.getArcNode(vertexName: self.startPoint!) for i in 0 ..< (self.graph?.vertexArr.count)! { let sortedValueArr = getSortedValueArr() self.path.append((currentPoint?.name)!) //查找对应在邻接结点是哪个 let miniDistance = sortedValueArr[i] currentPoint = findFixPoint(miniDistance: miniDistance) //遍历周围的结点 for connectedEdge:Edge in (currentPoint?.connectedEdgeArr)! { let endVertex:ArcNode = (self.graph?.getArcNode(vertexName: connectedEdge.endPoint.name))! if endVertex.visited { //当为真,证明已经访问过,进行松弛操作 let fomerPointWeight:Int = self.distToOtherPointDict[endVertex.name]! if miniDistance + connectedEdge.weight < fomerPointWeight { //更新权值 self.distToOtherPointDict[endVertex.name] = miniDistance + connectedEdge.weight } } else { self.distToOtherPointDict[endVertex.name] = connectedEdge.weight + miniDistance endVertex.visited = true } } } } public func hasPathTo(endPoint:String) -> Bool { if self.distToOtherPointDict[endPoint] != 32676 { return true } else { return false } } public func showPath(destin:String) { //不能直接输出self.path 因为是一次深度遍历完全的回路,要截取 self.path.removeFirst() var index:Int = 0 for i in 0 ..< self.path.count { if destin == self.path[i] { index = i } } let pathNSArray:NSArray = self.path as NSArray let range = NSMakeRange(0, index) let subArr = pathNSArray.subarray(with: range) for str in subArr { print("\(str)-->",terminator:"") } print(destin) } func getShortesetDistanceTo(destinPoint:String) -> Int { return self.distToOtherPointDict[destinPoint]! } func findFixPoint(miniDistance:Int) -> ArcNode { var point:ArcNode? for (key, value) in self.distToOtherPointDict { if value == miniDistance { point = (self.graph?.getArcNode(vertexName: key))! break } } return point! } func getSortedValueArr() -> [Int] { //找出此时字典里最小的最近距离 let valueArr = self.distToOtherPointDict.values let sortedValueArr = valueArr.sorted() return sortedValueArr } func resetAceNodes(graph:inout Graph) { for vertex:ArcNode in graph.vertexArr { vertex.visited = false } } } <file_sep>// // Graph.swift // ScenicSpotSystem // // Created by ffm on 16/11/22. // Copyright © 2016年 ITPanda. All rights reserved. // import Foundation let MAX_WEIGHT:Int = 32676 public class ArcNode { var name:String = "" //景点名称 var introduction:String = "" //景点简介 var popularity:String = "AAAAA旅游景区" //景点欢迎度 var isHaveRestArea:String = "有" //是否有休息区 var isHaveWC:String = "有" //是否公厕 //与该顶点相连的所有边 var connectedEdgeArr:[Edge] = [] var visited:Bool = false init(name:String, introduction:String, popularity:String, haveRestArea:String, haveWC:String) { self.name = name self.introduction = introduction self.popularity = popularity self.isHaveRestArea = haveRestArea self.isHaveWC = haveWC } init(name:String) { self.name = name self.introduction = "\(name)真是个好地方呀风景如画啦啦啦" self.popularity = "AAAA旅游景区" self.isHaveRestArea = "有" self.isHaveWC = "有" } } public class Edge { var startPoint:ArcNode var endPoint:ArcNode var weight:Int = MAX_WEIGHT //权重 init(startVertex:ArcNode, endVertex:ArcNode, edgeWeight:Int) { self.startPoint = startVertex self.endPoint = endVertex self.weight = edgeWeight } } public class Graph { var numberOfVetex:Int = 0 var numberOfEdge:Int = 0 var vertexArr:[ArcNode] var edgeArr:[Edge] var isDirected:Bool = false var maxVertexNum:Int var maxEdgeNum:Int //建立空图; init() { vertexArr = [] edgeArr = [] self.maxEdgeNum = 0 self.maxVertexNum = 0 } init(maxVertexNum:Int, maxEdgeNum:Int) { self.maxVertexNum = maxVertexNum self.maxEdgeNum = maxEdgeNum vertexArr = [] edgeArr = [] } //插入一顶点vertex,顶点暂时没有边 public func insertArcNode(vertex:ArcNode) ->Bool { if self.vertexArr.count >= self.maxVertexNum { print("已达到最大顶点值!插入顶点失败!\n") return false } else if (self.getArcNode(vertexName: vertex.name) != nil) { print("该节点已经存在!") return false } self.numberOfVetex += 1 self.vertexArr.append(vertex) return true } //插入一条边 public func insertEdge(vertex: ArcNode, anotherVertex: ArcNode, weight:Int) ->Bool { if self.edgeArr.count >= self.maxEdgeNum { print("已达最大边界数,插入边失败") return false } else if vertex.name == anotherVertex.name { //注意此程序不考虑自环边 print("不考虑自环边!插入边失败") return false } for tempEdge in self.edgeArr { if (tempEdge.startPoint.name == vertex.name && tempEdge.endPoint.name == anotherVertex.name) || (tempEdge.endPoint.name == vertex.name && tempEdge.startPoint.name == anotherVertex.name) { print("该边已经存在!") return false } } /* 这里切不可以直接修改传进来的点的信息,一来 不是引用传递 ,改了对外部也没用 除非用inout关键字修饰 但是就算修改了,改的也只是在外部声明的这个结点,对内部数据没任何影响 正确的姿势应该是从self.vertexArr里面获取到对应点的点来修改才对 */ // vertex.next = anotherVertex // anotherVertex.pre = vertex let vertex1 = self.getArcNode(vertexName: vertex.name) let vertex2 = self.getArcNode(vertexName: anotherVertex.name) // vertex1?.next = vertex2 // vertex2?.pre = vertex1 let newEdge = Edge(startVertex: vertex1!, endVertex: vertex2!, edgeWeight: weight) vertex1?.connectedEdgeArr.append(newEdge) let reverseEdge = Edge(startVertex: vertex2!, endVertex: vertex1!, edgeWeight: weight) vertex2?.connectedEdgeArr.append(reverseEdge) self.edgeArr.append(newEdge) self.numberOfEdge += 1 return true } //判断图是否为空 func graphIsEmpty() -> Bool { if self.numberOfEdge == 0 { return true } else { return false } } //判断图满 func graphFull() -> Bool { if (self.numberOfVetex == self.maxVertexNum || self.numberOfEdge == self.maxVertexNum * (self.maxVertexNum - 1)/2) { return true } else { return false } } //返回当前顶点数 public func getNumberOfVetex() -> Int { return self.numberOfVetex } //返回当前边数 public func getNumberOfEdge() -> Int { return self.numberOfEdge } //获取某个顶点 不合理则返回0 public func getArcNode(vertexName:String) -> ArcNode? { for tempVertex in self.vertexArr { if vertexName == tempVertex.name { return tempVertex } } return nil } //获取某条边上的权值 public func getWeight(vertexName:String, anotherName:String) -> Int { for tempEdge in self.edgeArr { if vertexName == anotherName { return 0 } else if ((tempEdge.startPoint.name == vertexName && tempEdge.endPoint.name == anotherName) || (tempEdge.endPoint.name == vertexName && tempEdge.startPoint.name == anotherName)) { return tempEdge.weight } } return MAX_WEIGHT } //获取与结点相连的所有结点 public func getNeighbourVertex(vertex:ArcNode) -> [ArcNode] { var arr:[ArcNode] = [] for edge:Edge in edgeArr { let vertex:ArcNode = getArcNode(vertexName: edge.endPoint.name)! arr.append(vertex) } return arr } //获取相邻结点通过权重 public func getNeighbourByWeight(vertex:ArcNode, weight:Int) -> ArcNode? { for edge:Edge in vertex.connectedEdgeArr { if edge.weight == weight { return edge.endPoint } } return nil } } <file_sep>// // Sort.swift // ScenicSpotSystem // // Created by ffm on 16/11/25. // Copyright © 2016年 ITPanda. All rights reserved. // import Foundation public func SortScenicSpot(graph: Graph) { print("请输入要进行的排序方式\n1.冒泡排序 2.快速排序 3.插入排序") let sinInput = FileHandle.standardInput let cxData = NSString(data: sinInput.availableData, encoding: String.Encoding.utf8.rawValue) let sortWay:Int = Int(cxData!.intValue) let sortSpot:Sort = Sort(graph: graph) switch sortWay { case 1: sortSpot.sortPopularityByBubble() case 2: sortSpot.quickSort() case 3: sortSpot.selectSort() default: print("输入有误") } } public class Sort : NSObject { let graph:Graph var nodeArr:[ArcNode] = [] init(graph:Graph) { self.graph = graph self.nodeArr = graph.vertexArr } func sortPopularityByBubble() { for i in 0 ... self.nodeArr.count-1 { //n个数排序,只要进行n-1轮操作 for j in 0 ..< self.nodeArr.count-i-1 { if self.nodeArr[j].popularity > self.nodeArr[j+1].popularity { let temp = self.nodeArr[j] self.nodeArr[j] = self.nodeArr[j+1] self.nodeArr[j+1] = temp } } } ouputResult(sortWay: "冒泡") } func quickSort() { print("暂未开放...") } func selectSort() { for i in 0 ..< self.nodeArr.count { for j in i ..< self.nodeArr.count { if self.nodeArr[j].popularity < self.nodeArr[i].popularity { let temp = self.nodeArr[j] self.nodeArr[j] = self.nodeArr[i] self.nodeArr[i] = temp } } } ouputResult(sortWay: "选择") } func ouputResult(sortWay:String) { print("\(sortWay)排序结束,排序后:") for vertex in self.nodeArr { print("景点:\(vertex.name), 人气:\(vertex.popularity), 简介:\(vertex.introduction)") } } } <file_sep>// // main.swift // ScenicSpotSystem // // Created by ffm on 16/11/22. // Copyright © 2016年 ITPanda. All rights reserved. // // /* plist文件的路径,可能是由于运行在mac上,不同于运行在虚拟机,或者是swift语言的改版,在读取plist文件的时候,Bundle.main方法的读取路径不再是之前的在当前工程目录里查找读取,而是去到了一个debug的文件夹,具体还得通过print方法输出,通过finder前往文件夹才行。所以这里也恳请老师留个心眼,如果读取文件失败的话,麻烦把plist文件移动到Bundle.main方法所提供的路径。谢谢老师。 (其实我已经把输出路径的代码混在了第一个功能creatDistributionMap里面了,直接按的话应该可以输出 */ import Foundation print("============================"); print(" 欢迎使用景区信息管理系统"); print(" ***请选择菜单***"); print("============================"); print("\n1、创建景区景点分布图。\n2、输出景区景点分布图。\n3、输出导游路线图。\n4、输出导游路线图中的回路。\n5、求两个景点间的最短路径和最短距离。\n6、查找排序。\n7、景点热度排行榜。\n8、车辆进出管理系统。"); private var graph:Graph = Graph(maxVertexNum: MAX_VERTEX_NUM, maxEdgeNum: MAX_EDGE_NUM) while true { print("请输入你要选择的菜单项") var sin = FileHandle.standardInput var cx = NSString(data: sin.availableData, encoding: String.Encoding.utf8.rawValue) var choice:Int = Int(cx!.intValue) switch choice { case 1: createDistributionMap(graph: &graph) case 2: outputDistributionMap(graph: graph) case 3: outputGuiLineMap(graph: graph) case 4: findLoopWay(graph: graph) case 5: findBestWayAndShortestWay(graph: &graph) case 6: SearchScenicSpot(graph: graph) case 7: SortScenicSpot(graph: graph) case 8: parkingLotManageSys() default: print("输入有误,请重新输入") } } //都会用到的方法,获取用户输入的字符串 返回一个数组 func getUserInput() -> [String] { let stdInput = FileHandle.standardInput let userInput = NSString(data: stdInput.availableData, encoding: String.Encoding.utf8.rawValue) var tempArr = userInput?.components(separatedBy: " ") let tempArr2 = tempArr?.last?.components(separatedBy: "\n") //把空格去掉归并到一个数组里 tempArr?.removeLast() tempArr?.append((tempArr2?.first)!) return tempArr! }
f29dddf37b3ac87047c10030c4281b97edaa4e13
[ "Swift" ]
11
Swift
ITpandaffm/ScenicSpotSystem
76bedd8dd6df798de4780b99a712db721dddeaaa
ee2df3e54720d7a1e7e6ce6cc77cd26948bd902b
refs/heads/master
<repo_name>josh20130/SwingGui<file_sep>/src/application/Application.java package application; import javax.swing.JFrame; import javax.swing.SwingUtilities; public class Application { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run(){ //Initializes frame, takes care of basic needs like close button, makes window visible and sets the size JFrame frame = new MainFrame("Application"); frame.setSize(500,400); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } ); } }<file_sep>/README.md # SwingGui A simple Swing GUI
45168c3918a21dc82aec25a7d55949ba8e902386
[ "Markdown", "Java" ]
2
Java
josh20130/SwingGui
4f1a77242077b6929eb138d6f57be2ade5a3d73c
173d1f474e8e42c647e213974541bb612dd08b4f
refs/heads/master
<repo_name>fatalwall/BatMon<file_sep>/src/BatMon.ScheduledTasks/Config/ResultCodeElement.cs /* *Copyright (C) 2018 <NAME> - All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license, * * You should have received a copy of the MIT license with * this file. If not, visit : https://github.com/fatalwall/BatMon */ using System; using System.Configuration; namespace BatMon.ScheduledTasks.Config { public class ResultCodeElement : ConfigurationElement { public ResultCodeElement() {} public ResultCodeElement(String ExitCode, String AppDynamicsCode, String Description) { this.ExitCode = ExitCode; this.AppDynamicsCode = AppDynamicsCode; this.Description = Description; } [ConfigurationProperty("ExitCode", IsKey = true, IsRequired = false)] public String ExitCode { get { return base["ExitCode"] as string; } set { base["ExitCode"] = value; } } [ConfigurationProperty("AppDynamicsCode", IsKey = false, IsRequired = false)] public String AppDynamicsCode { get { return base["AppDynamicsCode"] as string; } set { base["AppDynamicsCode"] = value; } } [ConfigurationProperty("Description", IsKey = false, IsRequired = false)] public String Description { get { return base["Description"] as string; } set { base["Description"] = value; } } protected override void DeserializeElement(System.Xml.XmlReader reader, bool serializeCollectionKey) { //get Attributes (ID and User) for (int i = 0; i < reader.AttributeCount; i++) { reader.MoveToAttribute(i); try { this[reader.Name] = reader.Value; } catch (Exception e) { throw new ConfigurationErrorsException("XMLPart: ResultCodeElement" + ", Attribute: " + reader.Name + ", Error: Unable to read in Value", e); } } //Get Text Content (Password) reader.MoveToElement(); this.Description = reader.ReadElementContentAsString(); } public override bool Equals(object o) { if (o.GetType() == typeof(ResultCodeElement)) { return (ResultCodeElement)o == this; } else { return false; } } public override int GetHashCode() { return this.ExitCode.GetHashCode() * 17 + this.AppDynamicsCode.GetHashCode() * 17 + this.Description.GetHashCode(); } public static bool operator == (ResultCodeElement object1, ResultCodeElement object2) { return ((object1.ExitCode == object2.ExitCode) && (object1.AppDynamicsCode == object2.AppDynamicsCode) && (object1.Description == object2.Description)); } public static bool operator !=(ResultCodeElement object1, ResultCodeElement object2) { return !(object1 == object2); } } }<file_sep>/src/BatMon.Framework.Web/BootStrapper.cs  /* *Copyright (C) 2018 <NAME> - All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license, * * You should have received a copy of the MIT license with * this file. If not, visit : https://github.com/fatalwall/BatMon */ using Nancy; using Nancy.Conventions; namespace BatMon.Framework.Web { public class BootStrapper: DefaultNancyBootstrapper { protected override void ConfigureConventions(NancyConventions nancyConventions) { base.ConfigureConventions(nancyConventions); nancyConventions.StaticContentsConventions.Clear(); nancyConventions.StaticContentsConventions.Add (StaticContentConventionBuilder.AddDirectory("css", "/web/style")); nancyConventions.StaticContentsConventions.Add (StaticContentConventionBuilder.AddDirectory("js", "/web/js")); nancyConventions.StaticContentsConventions.Add (StaticContentConventionBuilder.AddDirectory("images", "/web/img")); nancyConventions.StaticContentsConventions.Add (StaticContentConventionBuilder.AddDirectory("fonts", "/web/fonts")); nancyConventions.StaticContentsConventions.Add (StaticContentConventionBuilder.AddDirectory("Static", @"Static")); } } } <file_sep>/src/BatMon.ScheduledTasks/ScheduledTasksPlugin.cs /* *Copyright (C) 2018 <NAME> - All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license, * * You should have received a copy of the MIT license with * this file. If not, visit : https://github.com/fatalwall/BatMon */ using System; using System.Collections.Generic; using System.Configuration; using BatMon.Framework; using BatMon.ScheduledTasks.Config; using Microsoft.Win32.TaskScheduler; using System.Text.RegularExpressions; using System.ComponentModel.Composition; using System.Linq; using System.Reflection; using System.IO; namespace BatMon.ScheduledTasks { [Export(typeof(IBatMonPlugin))] [ExportMetadata("Name", "ScheduledTasks")] [ExportMetadata("isAggregate", false)] public class ScheduledTasksPlugin : BatMonPlugin, IBatMonPlugin { private string DetermineApplication(Task task, ScheduledTasksSection settings) { string Application = settings.Application.Value; if (settings.ApplicationDynamicOverride != null & !String.IsNullOrEmpty(settings.ApplicationDynamicOverride.Value)) { Match m = Regex.Match(task.Folder.Path, settings.ApplicationDynamicOverride.Value); if (m.Success) { Application = string.IsNullOrWhiteSpace(m.Groups["Application"].Value) ? Application : m.Groups["Application"].Value; } else { m = Regex.Match(task.Path, settings.ApplicationDynamicOverride.Value); if (m.Success) { Application = string.IsNullOrWhiteSpace(m.Groups["Application"].Value) ? Application : m.Groups["Application"].Value; } } } return Application; } private string DetermineTier(Task task, ScheduledTasksSection settings) { string Tier = settings.Tier.Value; if (settings.TierDynamicOverride != null & !String.IsNullOrEmpty(settings.TierDynamicOverride.Value)) { Match m = Regex.Match(task.Folder.Path, settings.TierDynamicOverride.Value); if (m.Success) { Tier = string.IsNullOrWhiteSpace(m.Groups["Tier"].Value) ? Tier : m.Groups["Tier"].Value; } else { m = Regex.Match(task.Path, settings.TierDynamicOverride.Value); if (m.Success) { Tier = string.IsNullOrWhiteSpace(m.Groups["Tier"].Value) ? Tier : m.Groups["Tier"].Value; } } } return Tier; } protected Result[] InitialStageResultCodesResults(ScheduledTasksSection settings) { List<Result> r = new List<Result>(); using (TaskService ts = new TaskService()) { foreach (Task t in ts.AllTasks) { if (!settings.FolderFilters.Match(t.Folder.Path)) { //Determine Application and Tier string Application = DetermineApplication(t, settings); string Tier = DetermineTier(t, settings); //Loop to add all potential result codes foreach (ResultCodeElement rc in settings.ResultCodes) { r.Add(new Result(Application, Tier, t.Name, rc.AppDynamicsCode, rc.Description)); } } } } return r.ToArray(); } protected override Result[] fetchResults() { //create a fallback if no section exists in the app.config so that it will look for a ScheduledTasks.config ScheduledTasksSection settings; try { settings = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).Sections.OfType<ScheduledTasksSection>().FirstOrDefault() as ScheduledTasksSection ?? ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location).Sections.OfType<ScheduledTasksSection>().FirstOrDefault() as ScheduledTasksSection; } catch (ConfigurationException cEx) { logger.Error(cEx, string.Format("Unable to load configuration {0}", Assembly.GetExecutingAssembly().Location + ".config")); settings = new ScheduledTasksSection(); } if (settings is null) { logger.Error(string.Format("Unable to load configuration {0}", Assembly.GetExecutingAssembly().Location + ".config")); settings = new ScheduledTasksSection(); } logger.Trace(string.Format("ScheduledTasks Configuration loaded with {0} Result Codes and {1} Folder Filters", settings.ResultCodes.Count(), settings.FolderFilters.Count())); if (settings.InitialStageResultCodes.Enabled == true) { //If true output will be an initial load of all possible outputs. This is to help populate all cases within app dynamics return InitialStageResultCodesResults(settings); } List<Result> r = new List<Result>(); using (TaskService ts = new TaskService()) { logger.Trace(string.Format("ScheduledTasks has detected {0} Tasks", ts.AllTasks.Count())); //Initialize logging foreach (Task t in ts.AllTasks) { if (!settings.FolderFilters.Match(t.Folder.Path)) { //Determine Application and Tier string Application = DetermineApplication(t, settings); string Tier = DetermineTier(t, settings); //Determine Job state and add result if (t.Enabled == true) { if (t.LastRunTime == DateTime.MinValue) { //Task has never run r.Add(new Result(Application, Tier, t.Name, settings.ResultCodes["NeverRun"].AppDynamicsCode, settings.ResultCodes["NeverRun"].Description,t)); logger.Info(string.Format("Application: {0,-40}Tier: {1,-40}ProcessName: {2,-40}Exit Code: {3,-15}Error Code: {4,-20}Error Description: {5}" , Application , Tier , t.Name.Substring(0, Math.Min(39, t.Name.Length)) , "NeverRun" , settings.ResultCodes["NeverRun"].AppDynamicsCode , r.Last<Result>().ErrorDescription ) ); } else { //Base code off of the exit code r.Add(new Result(Application, Tier, t.Name, settings.ResultCodes[t.LastTaskResult.ToString()].AppDynamicsCode, settings.ResultCodes[t.LastTaskResult.ToString()].Description, t)); if (settings.ResultCodes[t.LastTaskResult.ToString()] == settings.ResultCodes.Default) { logger.Warn(string.Format("Application: {0,-40}Tier: {1,-40}ProcessName: {2,-40}Exit Code: {3,-15}Error Code: {4,-20}Error Description: {5}" , Application , Tier , t.Name.Substring(0, Math.Min(39, t.Name.Length)) , t.LastTaskResult.ToString() , settings.ResultCodes[t.LastTaskResult.ToString()].AppDynamicsCode , r.Last<Result>().ErrorDescription ) ); } else { logger.Info(string.Format("Application: {0,-40}Tier: {1,-40}ProcessName: {2,-40}Exit Code: {3,-15}Error Code: {4,-20}Error Description: {5}" , Application , Tier , t.Name.Substring(0, Math.Min(39, t.Name.Length)) , t.LastTaskResult.ToString() , settings.ResultCodes[t.LastTaskResult.ToString()].AppDynamicsCode , r.Last<Result>().ErrorDescription ) ); } } } else { //Job is disabled r.Add(new Result(Application, Tier, t.Name, settings.ResultCodes["Disabled"].AppDynamicsCode, settings.ResultCodes["Disabled"].Description,t)); logger.Info(string.Format("Application: {0,-40}Tier: {1,-40}ProcessName: {2,-40}Exit Code: {3,-15}Error Code: {4,-20}Error Description: {5}" , Application , Tier , t.Name.Substring(0, Math.Min(39, t.Name.Length)) , "Disabled" , settings.ResultCodes["Disabled"].AppDynamicsCode , r.Last<Result>().ErrorDescription ) ); } } } } return r.ToArray(); } } } <file_sep>/src/BatMon/Program.cs /* *Copyright (C) 2018 <NAME> - All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license, * * You should have received a copy of the MIT license with * this file. If not, visit : https://github.com/fatalwall/BatMon */ using Topshelf.Nancy; using Topshelf; using NLog; using System.Text; namespace BatMon { static class Program { /// <summary> /// The main entry point for the application. /// </summary> static void Main() { Logger logger = LogManager.GetCurrentClassLogger(); var host = HostFactory.New(x => { x.UseNLog(); x.EnableServiceRecovery(r => { r.RestartService(0); r.RestartService(1); r.RestartService(5); } ); x.Service<BatMonService>(s => { s.ConstructUsing(settings => new BatMonService()); s.WhenStarted(service => service.Start()); s.WhenStopped(service => service.Stop()); s.WithNancyEndpoint(x, c => { c.AddHost(port: BatMonPluginManager.Settings.Port); c.CreateUrlReservationsOnInstall(); c.OpenFirewallPortsOnInstall(firewallRuleName: "BatMon"); }); }); x.StartAutomatically(); x.SetServiceName("BatMon"); x.SetDisplayName("BatMon (System Monitor)"); x.SetDescription("Web Services providing JSON feeds for monitoring."); x.RunAsLocalSystem(); }); host.Run(); } } } <file_sep>/src/BatMon.Framework/BatMonPluginManager.cs /* *Copyright (C) 2018 <NAME> - All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license, * * You should have received a copy of the MIT license with * this file. If not, visit : https://github.com/fatalwall/BatMon */ using System; using System.IO; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.Collections.Generic; using System.Linq; using BatMon.Framework; using System.Configuration; using BatMon.Framework.Config; using NLog; using System.Reflection; namespace BatMon { public sealed class BatMonPluginManager { Logger logger = LogManager.GetCurrentClassLogger(); private static readonly BatMonPluginManager instance = new BatMonPluginManager(); public static BatMonPluginManager getCurrentInstance { get { return instance; } } private static readonly BatMonSection settings = (ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).Sections.OfType<BatMonSection>().FirstOrDefault() as BatMonSection) ?? new BatMonSection(); public static BatMonSection Settings { get { return settings; } } [ImportMany] private IEnumerable<Lazy<IBatMonPlugin, IMetadata>> modules; public IEnumerable<Lazy<IBatMonPlugin, IMetadata>> Plugins { get { return modules?.OrderBy(m => m.Value.About.dllName + "." + m.Value.About.className) ?? null; } } public Lazy<IBatMonPlugin, IMetadata> this[string NameOrClass] { get { foreach (Lazy<IBatMonPlugin, IMetadata> p in Plugins) { if (p.Metadata.Name == NameOrClass || p.Value.About.className == NameOrClass) return p; } return null; } } public BatMonPluginManager() { AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; } public void DoImport() { var catalog = new AggregateCatalog(); //Load from executing assemblies plugin subdirectory try { //Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) catalog.Catalogs.Add(new DirectoryCatalog(@".\Plugins")); foreach (var path in System.IO.Directory.EnumerateDirectories(@".\Plugins", "*", System.IO.SearchOption.TopDirectoryOnly)) { catalog.Catalogs.Add(new DirectoryCatalog(path)); } } catch { catalog.Catalogs.Add(new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory)); foreach (var path in System.IO.Directory.EnumerateDirectories(AppDomain.CurrentDomain.BaseDirectory, "*", System.IO.SearchOption.TopDirectoryOnly)) { catalog.Catalogs.Add(new DirectoryCatalog(path)); } } CompositionContainer container = new CompositionContainer(catalog); try { container.ComposeParts(this); } catch(System.Reflection.ReflectionTypeLoadException) { }//if no modules load oh well } public int Count { get { return modules != null ? modules.Count() : 0; } } public BatMonPluginAbout[] AboutAll() { var result = new List<BatMonPluginAbout>(); if (!(modules is null)) foreach (Lazy<IBatMonPlugin, IMetadata> com in Plugins) { result.Add(com.Value.About); } return result.ToArray(); } public List<Result> RunAll() { var result = new List<Result>(); if (!(modules is null)) foreach (Lazy<IBatMonPlugin, IMetadata> com in Plugins.Where(p => !p.Metadata.isAggregate)) { if (com.Value.Run()) { result.AddRange(com.Value.Results.Values); } } return result; } private static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { System.Reflection.Assembly a = null; //App Folder string exePath = System.IO.Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().GetName().CodeBase).LocalPath); if (a is null) { a = isAssemblyHere(exePath, args); } //App/Plugins Folder string pluginsPath = System.IO.Path.Combine(exePath, "Plugins"); if (a is null) { a = isAssemblyHere(pluginsPath, args); } //App/Plugins/PluginName Folder string pluginPath = System.IO.Path.Combine(pluginsPath, args.Name); if (a is null) { a = isAssemblyHere(pluginPath, args); } //System32 Folder if (a is null) { a = isAssemblyHere(Environment.SystemDirectory, args); } //Windows Folder if (a is null) { a = isAssemblyHere(Environment.GetFolderPath(Environment.SpecialFolder.Windows), args); } if (a is null) { LogManager.GetCurrentClassLogger().Error("{0} could not be found in any of the following locations:\r\n\t{1}\r\n\t{2}\r\n\t{3}\r\n\t{4}\r\n\t{5}\r\n", args.Name, exePath, pluginsPath, pluginPath, Environment.SystemDirectory, Environment.GetFolderPath(Environment.SpecialFolder.Windows)); } return a; } private static Assembly isAssemblyHere(string directory, ResolveEventArgs args) { string path = Path.Combine(directory, string.Format("{0}.dll", args.Name)); try { return File.Exists(path) ? Assembly.LoadFile(path) : null; } catch (Exception ex) { LogManager.GetCurrentClassLogger().Error(ex, string.Format("Failed to load assembly where it was found: {0}", path)); return null; } } } } <file_sep>/src/BatMon.UriMonitor/UriPlugin.cs /* *Copyright (C) 2019 <NAME> - All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license, * * You should have received a copy of the MIT license with * this file. If not, visit : https://github.com/fatalwall/BatMon */ using BatMon.Framework; using System.ComponentModel.Composition; using System.Collections.Generic; namespace BatMon.UriMonitor { [Export(typeof(IBatMonPlugin))] [ExportMetadata("Name", "UriMonitor")] [ExportMetadata("isAggregate", false)] public class UriPlugin : BatMonPlugin, IBatMonPlugin { protected override Result[] fetchResults() { List<Result> r = new List<Result>(); foreach (Config.EndPoint s in Config.UriEndPoints.getCurrentInstance.EndPoints) { try { r.Add(new Result(s.ApplicationName, s.TierName, s.ProcessName, s.TestResult() ? "Success" : "Error", s.TestResultMessage, s.Result)); } catch(System.Exception ex) { System.Console.WriteLine(ex.Message); } } return r.ToArray(); } } } <file_sep>/src/BatMon.WindowsShare/Config/FolderCollection.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Configuration; namespace BatMon.WindowsShare.Config { public class FolderCollection : ConfigurationElementCollection { public FolderElement this[int index] { get { return (FolderElement)BaseGet(index); } } public new FolderElement this[string Path] { get { return this.Cast<FolderElement>().Where(f => f.Path == Path).First(); } } public int IndexOf(FolderElement e) { return BaseIndexOf(e); } public override System.Configuration.ConfigurationElementCollectionType CollectionType { get { return System.Configuration.ConfigurationElementCollectionType.BasicMap; } } protected override ConfigurationElement CreateNewElement() { return new FolderElement(); } protected override object GetElementKey(ConfigurationElement element) { return ((FolderElement)element); } public void Add(FolderElement e) { BaseAdd(e); } public void Remove(FolderElement e) { if (BaseIndexOf(e) >= 0) BaseRemove(e); } public void RemoveAt(int index) { BaseRemoveAt(index); } public void Clear() { BaseClear(); } protected override string ElementName { get { return "Folder"; } } } } <file_sep>/src/BatMon.ActiveConnections/ActiveConnectionsPlugin.cs /* *Copyright (C) 2019 <NAME> - All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license, * * You should have received a copy of the MIT license with * this file. If not, visit : https://github.com/fatalwall/BatMon */ using BatMon.Framework; using System.ComponentModel.Composition; using System.Collections.Generic; using System.Net.NetworkInformation; namespace BatMon.ActiveConnections { [Export(typeof(IBatMonPlugin))] [ExportMetadata("Name", "ActiveConnections")] [ExportMetadata("isAggregate", false)] public class ActiveConnectionsPlugin : BatMonPlugin, IBatMonPlugin { protected override Result[] fetchResults() { IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections(); IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners(); IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners(); return null; } } } <file_sep>/src/BatMon.Framework/IBatMonPlugin.cs /* *Copyright (C) 2018 <NAME> - All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license, * * You should have received a copy of the MIT license with * this file. If not, visit : https://github.com/fatalwall/BatMon */ namespace BatMon.Framework { public interface IBatMonPlugin { MonitorResults Results { get; } BatMonPluginAbout About { get; } bool Run(); string htmlPieChart(); string htmlWidget(); } public interface IMetadata { string Name { get; } bool isAggregate { get; } } } <file_sep>/src/BatMon.Framework.Web/web/js/PageRefresh.js setTimeout(function () { location.reload(); }, 5 * 60 * 1000);<file_sep>/src/BatMon.AllPlugins/AllPlugins.cs /* *Copyright (C) 2018 <NAME> - All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license, * * You should have received a copy of the MIT license with * this file. If not, visit : https://github.com/fatalwall/BatMon */ using BatMon.Framework; using System.ComponentModel.Composition; using System.Linq; namespace BatMon.AllPlugins { [Export(typeof(IBatMonPlugin))] [ExportMetadata("Name", "AllPlugins")] [ExportMetadata("isAggregate", true)] public class AllPlugins : BatMonPlugin, IBatMonPlugin { public override MonitorResults Results { get { MonitorResults r = new MonitorResults(); foreach (var plugin in BatMonPluginManager.getCurrentInstance.Plugins.Where(p => p.Metadata.isAggregate == false).Where(p => p.Value.Results!=null && p.Value.Results.Values.Count > 0 )) { r.Values.AddRange(plugin.Value.Results.Values); } return r; } } public new bool Run() { return true; } } } <file_sep>/src/BatMon.Framework/Config/EmailElement.cs /* *Copyright (C) 2018 <NAME> - All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license, * * You should have received a copy of the MIT license with * this file. If not, visit : https://github.com/fatalwall/BatMon */ using System; using System.Collections.Generic; using System.Configuration; using System.Net.Mail; using System.Text.RegularExpressions; namespace BatMon.Framework.Config { public class EmailElement : ConfigurationElement { public void Send() { SmtpClient mail = new SmtpClient(); mail.Host = this.smtpServer; mail.Port = this.smtpPort; mail.EnableSsl = this.enableSsl; if (!string.IsNullOrWhiteSpace(this.smtpUserName)) { mail.Credentials = new System.Net.NetworkCredential(this.smtpUserName, this.smtpPassword); } MailMessage message = new MailMessage(); message.From = new MailAddress(this.From); foreach (string address in this.To.Split(new char[] { ';',','})) { if (!string.IsNullOrWhiteSpace(address)) { message.To.Add(address); } } foreach (string address in this.Cc.Split(new char[] { ';', ',' })) { if (!string.IsNullOrWhiteSpace(address)) { message.CC.Add(address); } } foreach (string address in this.Bcc.Split(new char[] { ';', ',' })) { if (!string.IsNullOrWhiteSpace(address)) { message.Bcc.Add(address); } } message.Subject = ApplyVariables(this.Subject); message.Body = ApplyVariables(this.BodyHeader) + ApplyVariables(this.Body) + ApplyVariables(this.BodyFooter); message.IsBodyHtml = this.Html; try { mail.Send(message); }catch(System.Net.Mail.SmtpException ex) { var logger = NLog.LogManager.GetCurrentClassLogger(); logger.Error(ex, String.Format("Failed to send email onErrorCode '{0}'\r\n Host: {1}\r\n Port: {2}\r\n EnableSsl: {3}\r\n Subject: {4}\r\n Body: {5}", this.onErrorCode ,mail.Host, mail.Port, mail.EnableSsl,message.Subject,message.Body.Replace("\r\n","\r\n\t"))); } } private String ApplyVariables(String Value) { foreach (KeyValuePair<String, String> var in Variables) { //Value = Value.Replace(var.Key, var.Value); var regex = new Regex(@"\" + var.Key, RegexOptions.IgnoreCase); Value = regex.Replace(Value, var.Value); } return Value; } public Dictionary<String,String> Variables = new Dictionary<string, string>(); public EmailElement() { Variables.Add("${newline}", Environment.NewLine); Variables.Add("${tab}", "\t"); Variables.Add("${machinename}", Environment.MachineName); Variables.Add("${longdate}", DateTime.Now.ToLongDateString()); Variables.Add("${longtime}", DateTime.Now.ToLongTimeString()); Variables.Add("${longdatetime}", DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString()); Variables.Add("${shortdate}", DateTime.Now.ToShortDateString()); Variables.Add("${shorttime}", DateTime.Now.ToShortTimeString()); Variables.Add("${shortdatetime}", DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString()); } [ConfigurationProperty("onErrorCode", IsKey = true, IsRequired = true)] public String onErrorCode { get { return (String)base["onErrorCode"]; } set { this["onErrorCode"] = value; } } #region SMTP Server Settings [ConfigurationProperty("smtpServer", IsKey = false, IsRequired = true)] public String smtpServer { get { return (String)base["smtpServer"]; } set { this["smtpServer"] = value; } } [ConfigurationProperty("smtpPort", IsKey = false, IsRequired = true)] public int smtpPort { get { return (int)base["smtpPort"]; } set { this["smtpPort"] = value; } } [ConfigurationProperty("smtpUserName", IsKey = false, IsRequired = false)] public String smtpUserName { get { if (!string.IsNullOrEmpty((String)base["smtpUserName"])) { return (String)base["smtpUserName"]; } else return null; } set { this["smtpUserName"] = value; } } [ConfigurationProperty("smtpPassword", IsKey = false, IsRequired = false)] public String smtpPassword { get { if (!string.IsNullOrEmpty((String)base["smtpPassword"])) { return (String)base["smtpPassword"]; } else return null; } set { this["smtpPassword"] = value; } } [ConfigurationProperty("enableSsl", IsKey = false, IsRequired = false)] public Boolean enableSsl { get { return (Boolean)base["enableSsl"]; } set { this["enableSsl"] = value; } } #endregion #region Email Header [ConfigurationProperty("To", IsKey = false, IsRequired = true)] public String To { get { if (!string.IsNullOrEmpty((String)base["To"])) { return (String)base["To"]; } else return ""; } set { this["To"] = value.Replace(" ", ""); } } [ConfigurationProperty("Bcc", IsKey = false, IsRequired = false)] public String Bcc { get { if (!string.IsNullOrEmpty((String)base["Bcc"])) { return (String)base["Bcc"]; } else return ""; } set { this["Bcc"] = value.Replace(" ", ""); } } [ConfigurationProperty("Cc", IsKey = false, IsRequired = false)] public String Cc { get { if (!string.IsNullOrEmpty((String)base["Cc"])) { return (String)base["Cc"]; } else return ""; } set { this["Cc"] = value.Replace(" ", ""); } } [ConfigurationProperty("From", IsKey = false, IsRequired = true)] public String From { get { return (String)base["From"]; } set { this["From"] = value.Replace(" ", ""); } } #endregion #region Email Content [ConfigurationProperty("Subject", IsKey = false, IsRequired = false)] public String Subject { get { return (String)base["Subject"]; } set { this["Subject"] = value; } } [ConfigurationProperty("BodyHeader", IsKey = false, IsRequired = false)] public String BodyHeader { get { return (String)base["BodyHeader"]; } set { this["BodyHeader"] = value; } } [ConfigurationProperty("Body", IsKey = false, IsRequired = false)] public String Body { get { return (String)base["Body"]; } set { this["Body"] = value; } } [ConfigurationProperty("BodyFooter", IsKey = false, IsRequired = false)] public String BodyFooter { get { return (String)base["BodyFooter"]; } set { this["BodyFooter"] = value; } } [ConfigurationProperty("Html", IsKey = false, IsRequired = false)] public Boolean Html { get { return (Boolean)base["Html"]; } set { this["Html"] = value; } } #endregion } } <file_sep>/src/BatMon.WindowsShare/Config/WindowsShareSection.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Configuration; using System.Reflection; namespace BatMon.WindowsShare.Config { public class WindowsShareSection : ConfigurationSection { private static readonly WindowsShareSection instance = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).Sections.OfType<WindowsShareSection>().FirstOrDefault() as WindowsShareSection ?? ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location).Sections.OfType<WindowsShareSection>().FirstOrDefault() as WindowsShareSection; public static WindowsShareSection getCurrentInstance { get { return instance; } } [ConfigurationProperty("", IsDefaultCollection = true)] public FolderCollection Folders { get { return ((FolderCollection)base[""]) ?? new FolderCollection(); } } } } <file_sep>/src/BatMon.Framework.Web/InterfaceWeb.cs /* *Copyright (C) 2018 <NAME> - All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license, * * You should have received a copy of the MIT license with * this file. If not, visit : https://github.com/fatalwall/BatMon */ using System; using System.Collections.Generic; using System.Linq; using Nancy; using System.Net.Sockets; using System.Net.NetworkInformation; using System.Net; using Newtonsoft.Json; using System.IO; using Microsoft.VisualBasic.Devices; using System.Reflection; namespace BatMon.Framework.Web { public class InterfaceWeb : NancyModule { public Uri[] GetUriBindings(int Port) { List<Uri> uriResults = new List<Uri>(); if (this.Request.UserHostAddress == "127.0.0.1" || this.Request.UserHostAddress == "::1") uriResults.Add(new Uri(string.Format("http://{0}:{1}", "localhost", Port))); uriResults.Add(new Uri(string.Format("http://{0}:{1}", Dns.GetHostName(), Port))); if (Dns.GetHostEntry("").HostName != Dns.GetHostName()) uriResults.Add(new Uri(string.Format("http://{0}:{1}", Dns.GetHostEntry("").HostName, Port))); foreach (string ip in NetworkInterface.GetAllNetworkInterfaces() .Where(i => i.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || i.NetworkInterfaceType == NetworkInterfaceType.Ethernet) .SelectMany(i => i.GetIPProperties().UnicastAddresses) .Where(i => i.Address.AddressFamily == AddressFamily.InterNetwork && i.SuffixOrigin != SuffixOrigin.LinkLayerAddress) .Select(i => i.Address.ToString())) { uriResults.Add(new Uri(string.Format("http://{0}:{1}", ip, Port))); } return uriResults.ToArray(); } private BatMonPluginManager pluginManager = BatMonPluginManager.getCurrentInstance; private string getFooter() { if(System.IO.File.Exists(@".\web\Views\footer.html")) return System.IO.File.ReadAllText(@".\web\Views\footer.html"); else return ""; } private string getHeader() { if (System.IO.File.Exists(@".\web\Views\header.html")) return System.IO.File.ReadAllText(@".\web\Views\header.html"); else return ""; } public InterfaceWeb() { Get["/"] = x => { string t = "<link rel='stylesheet' href='/css/home.css' />"; t = t + @"<script type='text/javascript' src='https://www.gstatic.com/charts/loader.js'></script>"; t = t + @"<div class='Body'>"; //bound uri t = t + @"<div class='WidgetWrapper'>"; t = t + @"<div class='Widget' id='BoundUri'>"; t = t + string.Format(@"<div class='header'>{0}</div>", "Addresses"); foreach (var uri in GetUriBindings(BatMonPluginManager.Settings.Port)) { t = t + string.Format(@"<div class='link'><a href='{0}'>{0}</a></div>", uri); } t = t + @"</div>"; t = t + @"</div>"; //Health Report t = t + @"<div class='WidgetWrapperFill'>"; t = t + @"<div class='Widget' id='HealthReport'>"; t = t + string.Format(@"<div class='header'>{0}</div>", "Health Report"); if (pluginManager.RunAll().Count > 0) { t = t + @"<script type='text/javascript'>"; t = t + @"google.charts.load('current', { 'packages':['corechart']});"; foreach (var p in pluginManager.Plugins.Where(i => i.Value.Results.Values.Count > 0)) { t = t + p.Value.htmlPieChart(); } t = t + @"</script>"; t = t + "<div class='PieChartWrapper'>"; foreach (var p in pluginManager.Plugins.Where(i => i.Value.Results.Values.Count > 0)) { t = t + string.Format("<div class='PieChart' id='{0}'></div>", p.Metadata.Name); } t = t + @"</div>"; } t = t + @"</div>"; t = t + @"</div>"; //Server Info t = t + @"<div class='WidgetWrapper'>"; t = t + @"<div class='Widget' id='ServerInfo'>"; t = t + string.Format(@"<div class='header'>{0}</div>", "Server Info"); t = t + string.Format(@"<div class='content'><b>{0}:</b> {1}</div>", "Host Name", System.Environment.MachineName); t = t + string.Format(@"<div class='content'><b>{0}:</b> {1}</div>", "OS", new ComputerInfo().OSFullName); t = t + string.Format(@"<div class='content'><b>{0}:</b> {1}</div>", "OS Platform", new ComputerInfo().OSPlatform); t = t + string.Format(@"<div class='content'><b>{0}:</b> {1}</div>", "OS Version", new ComputerInfo().OSVersion); t = t + string.Format(@"<div class='content'><b>{0}:</b> {1}</div>", "BatMon Version", Assembly.GetEntryAssembly().GetName().Version.ToString(BatMon.Framework.Diagnostics.isRelease() ? 3 : 4)); t = t + @"<div class='content'>"; t = t + @"<table class='System'>"; t = t + @"<thead>"; t = t + @"<tr>"; t = t + @"<th>Cores</th>"; t = t + @"<th>Memory</th>"; t = t + @"<th>Usage</th>"; t = t + @"</tr>"; t = t + @"</thead>"; t = t + @"<tbody>"; var TotalMem = new ComputerInfo().TotalPhysicalMemory; var AvailMem = new ComputerInfo().AvailablePhysicalMemory; int MemPercent = (int)(((double)(TotalMem - AvailMem) / TotalMem) * 100); t = t + string.Format(@"<tr class='{0}'>", MemPercent >= 95 ? "Critical" : MemPercent >= 85 ? "Warning" : "Good"); t = t + string.Format(@"<td>{0}</td>", Environment.ProcessorCount); t = t + string.Format(@"<td>{0:0.#} GB</td>", (decimal)TotalMem / 1024 / 1024 / 1024); t = t + string.Format(@"<td>{0}%</td>", MemPercent); t = t + @"</tr>"; t = t + @"</tbody>"; t = t + @"</table>"; t = t + @"</div>"; t = t + @"<div class='content'>"; t = t + @"<table class='DiskDrives'>"; t = t + @"<thead>"; t = t + @"<tr>"; t = t + @"<th>Drive</th>"; t = t + @"<th>Type</th>"; t = t + @"<th>Size</th>"; t = t + @"<th>Usage</th>"; t = t + @"</tr>"; t = t + @"</thead>"; t = t + @"<tbody>"; foreach (var drive in DriveInfo.GetDrives().Where(i => i.IsReady == true && i.DriveType != DriveType.CDRom)) { int percent = (int)(((double)(drive.TotalSize - drive.TotalFreeSpace) / drive.TotalSize) * 100); t = t + string.Format(@"<tr class='{1}' id='{0}'>", drive.Name, percent >= 95 ? "Critical" : percent >= 85 ? "Warning" : "Good"); t = t + string.Format(@"<td>{0}</td>", drive.Name); t = t + string.Format(@"<td>{0}</td>", drive.DriveType); t = t + string.Format(@"<td>{0} GB</td>", drive.TotalSize / 1024 / 1024 / 1024); t = t + string.Format(@"<td>{0}%</td>", percent); t = t + @"</tr>"; } t = t + @"</tbody>"; t = t + @"</table>"; t = t + @"</div>"; t = t + @"</div>"; t = t + @"</div>"; t = t + @"</div>"; return getHeader() + t + getFooter(); }; //Displays a list of all plugins registered Get["/plugin"] = x => { if (Request.Query["json"].HasValue) { var responce = (Response)JsonConvert.SerializeObject(pluginManager.AboutAll()); responce.ContentType = "application/json"; return responce; } else { string t = "<link rel='stylesheet' href='/css/table.css' />"; t = t + "<link rel='stylesheet' href='/css/plugin.css' />"; t = t + @"<table class='blueTable'>"; t = t + @"<thead>"; t = t + @"<tr>"; t = t + @"<th>dllName</th>"; t = t + @"<th>className</th>"; t = t + @"<th>Version</th>"; t = t + @"</tr>"; t = t + @"</thead>"; t = t + @"<tbody>"; foreach (BatMonPluginAbout a in pluginManager.AboutAll()) { t = t + @"<tr>"; t = t + string.Format(@"<td>{0}</td>", a.dllName); t = t + string.Format(@"<td><a href='/plugin/{1}'>{0}</a></td>", a.className, pluginManager[a.className].Metadata.Name); t = t + string.Format(@"<td>{0}</td>", a.Version); t = t + @"</tr>"; } t = t + @"</tbody>"; t = t + @"</table>"; return getHeader() + t + getFooter(); } }; //BatMonPlugin Dynamically added addresses if (!(pluginManager.Plugins is null)) { foreach (Lazy<IBatMonPlugin, IMetadata> p in pluginManager.Plugins) { Get[string.Format("/Plugin/{0}", p.Metadata.Name)] = x => { if (Request.Query["json"].HasValue) { p.Value.Run(); var responce = (Response)JsonConvert.SerializeObject(p.Value.Results.Values); responce.ContentType = "application/json"; return responce; } else if (Request.Query["appd"].HasValue) { p.Value.Run(); var responce = (Response)p.Value.Results.ToAppD(); responce.ContentType = "application/json"; return responce; } else { p.Value.Run(); string t = "<link rel='stylesheet' href='/css/table.css' />"; t = t + @"<table class='blueTable'>"; t = t + @"<thead>"; t = t + @"<tr>"; foreach (var field in p.Value.Results.Fields) { t = t + string.Format(@"<th>{0}</th>", field.Label); } t = t + @"</tr>"; t = t + @"</thead>"; t = t + @"<tbody>"; foreach (var value in p.Value.Results.Values) { t = t + string.Format(@"<tr class='{0}'>", value.ErrorCode); t = t + string.Format(@"<td>{0}</td>", value.ApplicationName); t = t + string.Format(@"<td>{0}</td>", value.TierName); t = t + string.Format(@"<td>{0}</td>", value.ProcessName); t = t + string.Format(@"<td>{0}</td>", value.ErrorCode); t = t + string.Format(@"<td>{0}</td>", value.ErrorDescription); t = t + @"</tr>"; } t = t + @"</tbody>"; t = t + @"</table>"; return getHeader() + t + getFooter(); } }; } } } } } <file_sep>/src/BatMon.WindowsShare/Config/FolderElement.cs using System.Configuration; namespace BatMon.WindowsShare.Config { public class FolderElement : ConfigurationElement { public override string ToString() { return string.Format("{0} ({1})", this.ProcessName, this.Path); } [ConfigurationProperty("ApplicationName", IsKey = false, IsRequired = true)] public string ApplicationName { get { return (string)base["ApplicationName"]; } set { this["ApplicationName"] = value; } } [ConfigurationProperty("TierName", IsKey = false, IsRequired = true)] public string TierName { get { return (string)base["TierName"]; } set { this["TierName"] = value; } } [ConfigurationProperty("ProcessName", IsKey = false, IsRequired = true)] public string ProcessName { get { return (string)base["ProcessName"]; } set { this["ProcessName"] = value; } } [ConfigurationProperty("Path", IsKey = false, IsRequired = true)] public string Path { get { return (string)base["Path"]; } set { this["Path"] = value; } } [ConfigurationProperty("User", IsKey = false, IsRequired = false)] public string User { get { return string.IsNullOrWhiteSpace((string)base["User"]) ? null : (string)base["User"]; } set { this["User"] = value; } } [ConfigurationProperty("Password", IsKey = false, IsRequired = false)] public string Password { get { return string.IsNullOrWhiteSpace((string)base["Password"]) ? null : (string)base["Password"]; } set { this["Password"] = value; } } [ConfigurationProperty("ContentCheck", IsKey = false, IsRequired = false, DefaultValue = true)] public bool ContentCheck { get { return (bool)base["ContentCheck"]; } set { this["ContentCheck"] = value; } } } } <file_sep>/src/BatMon.Framework/Field.cs /* *Copyright (C) 2018 <NAME> - All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license, * * You should have received a copy of the MIT license with * this file. If not, visit : https://github.com/fatalwall/BatMon */ using Newtonsoft.Json; namespace BatMon.Framework { public class Field { public Field(string Label) { this.Label = Label; } public string Label { get; set; } public string ToAppD() { return string.Format("{{\"label\": {0}}}", JsonConvert.SerializeObject(this.Label)); } } } <file_sep>/src/BatMon.Framework/Config/BatMonSection.cs /* *Copyright (C) 2018 <NAME> - All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license, * * You should have received a copy of the MIT license with * this file. If not, visit : https://github.com/fatalwall/BatMon */ using System.Configuration; namespace BatMon.Framework.Config { public class BatMonSection : ConfigurationSection { [ConfigurationProperty("", IsDefaultCollection = true)] public EmailCollection EmailEvents { get { EmailCollection emailCollection = (EmailCollection)base[""]; return emailCollection; } } [ConfigurationProperty("port", IsKey = false, IsRequired = false)] public int Port { get { return (int)base["port"] == 0 ? 7865 : (int)base["port"]; } set { this["port"] = value; } } } } <file_sep>/src/BatMon.ActiveDirectory/ADUserObject.cs /* *Copyright (C) 2019 <NAME> - All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license, * * You should have received a copy of the MIT license with * this file. If not, visit : https://github.com/fatalwall/BatMon */ using BatMon.Framework; using System.ComponentModel.Composition; using System.Collections.Generic; namespace BatMon.ActiveDirectory { public class ADUserObject : BatMonPlugin, IBatMonPlugin { protected override Result[] fetchResults() { return null; } } } <file_sep>/src/BatMon.ScheduledTasks/Config/InitialStageResultCodesElement.cs /* *Copyright (C) 2018 <NAME> - All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license, * * You should have received a copy of the MIT license with * this file. If not, visit : https://github.com/fatalwall/BatMon */ using System; using System.Configuration; namespace BatMon.ScheduledTasks.Config { public class InitialStageResultCodesElement : ConfigurationElement { public InitialStageResultCodesElement() { } public InitialStageResultCodesElement(Boolean Enabled) { this.Enabled = Enabled; } [ConfigurationProperty("Enabled", IsKey = false, IsRequired = true)] public Boolean Enabled { get { return (Boolean) base["Enabled"]; } set { base["Enabled"] = value; } } protected override void DeserializeElement(System.Xml.XmlReader reader, bool serializeCollectionKey) { for (int i = 0; i < reader.AttributeCount; i++) { reader.MoveToAttribute(i); try { switch (this[reader.Name].GetType().ToString()) { case "System.Boolean": this[reader.Name] = Boolean.Parse(reader.Value); //.Parse(reader.Value); break; default: this[reader.Name] = reader.Value; break; } } catch (Exception e) { throw new ConfigurationErrorsException("XMLPart: InitialStageResultCodesElement" + ", Attribute: " + reader.Name + ", Error: Unable to read in Value", e); } } } } }<file_sep>/src/BatMon.Framework/MonitorResults.cs /* *Copyright (C) 2018 <NAME> - All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license, * * You should have received a copy of the MIT license with * this file. If not, visit : https://github.com/fatalwall/BatMon */ using System.Collections.Generic; using System.Linq; namespace BatMon.Framework { public class MonitorResults { public MonitorResults() { Fields = new List<Field>(); Fields.Add(new Field("Application Name")); Fields.Add(new Field("Tier Name")); Fields.Add(new Field("Process Name")); Fields.Add(new Field("Error Code")); Fields.Add(new Field("Error Description")); Values = new List<Result>(); } public List<Field> Fields { get; private set; } public List<Result> Values { get; private set; } public string ToAppD() { string outputField = "\"fields\": ["; outputField += string.Join(",", Fields.Select(x => x.ToAppD()).ToArray()); outputField += "]"; string outputResult = "\"results\": ["; outputResult += string.Join(",", Values.Select(x => x.ToAppD()).ToArray()); outputResult += "]"; return string.Format("[{{{0},{1}}}]", outputField, outputResult); } } } <file_sep>/src/BatMon.ScheduledTasks/Config/ApplicationDynamicOverrideElement.cs /* *Copyright (C) 2018 <NAME> - All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license, * * You should have received a copy of the MIT license with * this file. If not, visit : https://github.com/fatalwall/BatMon */ using System.Configuration; namespace BatMon.ScheduledTasks.Config { public class ApplicationDynamicOverrideElement : ConfigurationElement { public ApplicationDynamicOverrideElement() { } public ApplicationDynamicOverrideElement(string Value) { this.Value = Value; } [ConfigurationProperty("Value", IsKey = false, IsRequired = true)] public string Value { get { return base["Value"] as string; } set { base["Value"] = value; } } protected override void DeserializeElement(System.Xml.XmlReader reader, bool serializeCollectionKey) { //Get Text Content reader.MoveToElement(); this.Value = reader.ReadElementContentAsString(); } } }<file_sep>/src/BatMon.Framework/Config/EmailCollection.cs /* *Copyright (C) 2018 <NAME> - All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license, * * You should have received a copy of the MIT license with * this file. If not, visit : https://github.com/fatalwall/BatMon */ using System; using System.Configuration; namespace BatMon.Framework.Config { public class EmailCollection : ConfigurationElementCollection { #region Generic Minor Edits public EmailCollection() { EmailElement e = (EmailElement)CreateNewElement(); if (e.onErrorCode != "") { Add(e); } } protected override ConfigurationElement CreateNewElement() { return new EmailElement(); } protected override Object GetElementKey(ConfigurationElement element) { return ((EmailElement)element).onErrorCode; } public EmailElement this[int index] { get { return (EmailElement)BaseGet(index); } set { if (BaseGet(index) != null) { BaseRemoveAt(index); } BaseAdd(index, value); } } new public EmailElement this[string Name] { get { return (EmailElement)BaseGet(Name); } } public int IndexOf(EmailElement e) { return BaseIndexOf(e); } public int IndexOf(String Name) { for (int idx = 0; idx < base.Count; idx++) { if (this[idx].onErrorCode.ToUpper() == Name.ToUpper()) return idx; } return -1; } public void Add(EmailElement e) { BaseAdd(e); } public void Remove(EmailElement e) { if (BaseIndexOf(e) >= 0) BaseRemove(e.onErrorCode); } protected override string ElementName { get { return "Email"; } } #endregion #region Generic No Edit public override ConfigurationElementCollectionType CollectionType { get { return ConfigurationElementCollectionType.BasicMap; } } protected override void BaseAdd(ConfigurationElement element) { BaseAdd(element, false); } public void RemoveAt(int index) { BaseRemoveAt(index); } public void Remove(string name) { BaseRemove(name); } public void Clear() { BaseClear(); } #endregion } } <file_sep>/src/BatMon.Framework/Diagnostics.cs using System.Diagnostics; namespace BatMon.Framework { public class Diagnostics { [Conditional("DEBUG")] private static void setDebug() { _isRelease = false; } private static bool _isRelease = true; public static bool isRelease() { setDebug(); return _isRelease; } public static bool isDebug() { return !isRelease(); } } } <file_sep>/src/BatMon.UriMonitor/Config/EndPoint.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Configuration; using System.Net; namespace BatMon.UriMonitor.Config { public class EndPoint : ConfigurationElement { public override string ToString() { return string.Format("{0} ({1})", this.ProcessName, this.Uri); } [ConfigurationProperty("ApplicationName", IsKey = false, IsRequired = true)] public string ApplicationName { get { return (string)base["ApplicationName"]; } set { this["ApplicationName"] = value; } } [ConfigurationProperty("TierName", IsKey = false, IsRequired = true)] public string TierName { get { return (string)base["TierName"]; } set { this["TierName"] = value; } } [ConfigurationProperty("ProcessName", IsKey = false, IsRequired = true)] public string ProcessName { get { return (string)base["ProcessName"]; } set { this["ProcessName"] = value; } } [ConfigurationProperty("Uri", IsKey = false, IsRequired = true)] public string Uri { get { return (string)base["Uri"]; } set { this["Uri"] = value; } } [ConfigurationProperty("User", IsKey = false, IsRequired = false)] public string User { get { return string.IsNullOrWhiteSpace((string)base["User"]) ? null : (string)base["User"]; } set { this["User"] = value; } } [ConfigurationProperty("Password", IsKey = false, IsRequired = false)] public string Password { get { return string.IsNullOrWhiteSpace((string)base["Password"]) ? null : (string)base["Password"]; } set { this["Password"] = value; } } [ConfigurationProperty("WindowsAuth", IsKey = false, IsRequired = false, DefaultValue = false)] public bool WindowsAuth { get { return (bool)base["WindowsAuth"]; } set { this["WindowsAuth"] = value; } } [ConfigurationProperty("StatusCode", IsKey = false, IsRequired = false, DefaultValue = 200)] public int StatusCode { get { return (int)base["StatusCode"]; } set { this["StatusCode"] = value; } } [ConfigurationProperty("ValidationRegex", IsKey = false, IsRequired = false)] public string ValidationRegex { get { return string.IsNullOrWhiteSpace((string)base["ValidationRegex"]) ? null : (string)base["ValidationRegex"]; } set { this["ValidationRegex"] = value; } } public UriResult Result { get; protected set; } public class UriResult { public string Content { get; set; } public Exception Exception { get; set; } public HttpStatusCode? StatusCode { get; set; } } public string TestResultMessage { get; private set; } public bool TestResult() { bool result = true; this.Result = new UriResult(); using (WebClient client = new WebClient()) { try { if (this.WindowsAuth == true && string.IsNullOrWhiteSpace(this.User)) client.UseDefaultCredentials = true; if (this.WindowsAuth == true && !string.IsNullOrWhiteSpace(this.User)) { CredentialCache cc = new CredentialCache(); cc.Add( new Uri(this.Uri), "NTLM", new NetworkCredential( this.User.Contains(@"\") ? this.User.Split('\\')[1] : this.User, this.Password, this.User.Contains(@"\") ? this.User.Split('\\')[0] : System.Environment.UserDomainName)); client.Credentials = cc; } this.Result.Content = client.DownloadString(this.Uri); this.Result.StatusCode = HttpStatusCode.OK; } catch (System.Net.WebException webEx) { if (webEx.Response is System.Net.HttpWebResponse) this.Result.StatusCode = ((System.Net.HttpWebResponse)webEx.Response).StatusCode; this.Result.Exception = webEx; } catch (ArgumentNullException argEx) { this.Result.Content = ""; this.Result.StatusCode = HttpStatusCode.BadRequest; this.Result.Exception = argEx; result = false; } catch (NotSupportedException notEx) { this.Result.Content = ""; this.Result.StatusCode = HttpStatusCode.BadRequest; this.Result.Exception = notEx; result = false; } catch (UriFormatException uriEx) { this.Result.Content = ""; this.Result.StatusCode = HttpStatusCode.BadRequest; this.Result.Exception = uriEx; result = false; } catch (Exception ex) { this.Result.Exception = ex; result = false; } } //Validation if (!string.IsNullOrEmpty(this.ValidationRegex)) if (!(new Regex(this.ValidationRegex)).Match(this.Result.Content).Success) { this.TestResultMessage = "HTTP Content failed to match validation Regular Expression"; result = false; } if ((int)this.Result.StatusCode != this.StatusCode) { this.TestResultMessage = string.Format("HTTP Status Code: {0}, Expected: {1}", (int)this.Result.StatusCode, this.StatusCode) ; result = false; } return result; } } } <file_sep>/src/BatMon/BatMonService.cs using NLog; using System.Text; namespace BatMon { class BatMonService { Logger logger = LogManager.GetCurrentClassLogger(); public bool Start() { var t = BatMonPluginManager.getCurrentInstance; t.DoImport(); StringBuilder pList = new StringBuilder(); pList.AppendLine("BatMon is starting with the following plugins:"); if (t.Plugins is null) { pList.AppendLine(" No plugins loaded"); } else { foreach (var a in t.Plugins) { pList.AppendFormat(" - {0}", a.Metadata.Name).AppendLine(); } } logger.Info(pList); return true; } public bool Stop() { return true; } } } <file_sep>/src/BatMon.Framework/BatMonPlugin.cs /* *Copyright (C) 2018 <NAME> - All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license, * * You should have received a copy of the MIT license with * this file. If not, visit : https://github.com/fatalwall/BatMon */ using System; using System.Linq; using System.Text; using System.ComponentModel.Composition; namespace BatMon.Framework { public class BatMonPlugin : IBatMonPlugin { private NLog.Logger _logger; protected NLog.Logger logger { get { if (_logger is null) _logger = NLog.LogManager.GetLogger(GetType().FullName); return _logger; } } public virtual MonitorResults Results { get; private set; } public BatMonPluginAbout About { get { return new BatMonPluginAbout(this.GetType().Assembly.GetName().Name, this.GetType().Name, this.GetType().Assembly.GetName().Version); } } /// <summary> /// Implemetation of Plugin initiator that kicks off overidable method getResults() with /// default error handling to insulate the plugin manager from uncaught exceptions within /// plugins. /// </summary> /// <returns>boolean value indicating if the plugin succeded or failed to run</returns> public bool Run() { try { Results = new MonitorResults(); Result[] r = fetchResults(); if (!(r is null)) Results.Values.AddRange(r); return true; } catch (Exception ex) { logger.Error(ex); return false; } } /// <summary> /// Overridable method that returns a result set back to the Run method. /// </summary> /// <returns></returns> protected virtual Result[] fetchResults() { throw new NotImplementedException("fetchResults has not been implemented"); } /// <summary> /// Implemetation of standard access method to Metadata Attributes /// </summary> /// <returns>Object value</returns> protected object MetadataAttribute(string Name) { foreach (var a in this.GetType().GetCustomAttributes(typeof(ExportMetadataAttribute), true).OfType<ExportMetadataAttribute>().Where(a => a.Name == Name)) { return a.Value; } return null; } /// <summary> /// Implemetation of standard pie chart for web page /// </summary> /// <returns>string value containing needed javascript, html, css, etc.</returns> public string htmlPieChart() { string output = ""; output = output + string.Format(@"google.charts.setOnLoadCallback(drawChart{0});", this.MetadataAttribute("Name").ToString()); output = output + string.Format("function drawChart{0}() {{ var data = google.visualization.arrayToDataTable([", this.MetadataAttribute("Name").ToString()); output = output + string.Format("['{0}', '{1}']", "ErrorCode", "Counts"); foreach (var g in this.Results.Values.GroupBy(i => i.ErrorCode)) { output = output + string.Format(",['{0}', {1}]", g.Key, g.Count()); } output = output + string.Format(@"]); var options = {{ pieSliceText: 'label', 'legend':'none', 'width':'100%', 'height':'100%', title: '{0}', titleTextStyle: {{ 'fontSize':14, 'bold':true }} }};", this.MetadataAttribute("Name").ToString()); output = output + string.Format(@"var chart = new google.visualization.PieChart(document.getElementById('{0}'));", this.MetadataAttribute("Name").ToString()); output = output + string.Format(@"chart.draw(data, options);}}", this.MetadataAttribute("Name").ToString()); return output; } public string htmlWidget() { return ""; } } } <file_sep>/README.md # BatMon Batch Job Monitor Dashboard and API [![GitHub release](https://img.shields.io/github/release/fatalwall/BatMon.svg?label=GitHub%20release)](https://github.com/fatalwall/BatMon/releases/latest) <file_sep>/src/BatMon.Framework/Result.cs /* *Copyright (C) 2018 <NAME> - All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license, * * You should have received a copy of the MIT license with * this file. If not, visit : https://github.com/fatalwall/BatMon */ using System.Linq; using BatMon.Framework.Config; using System.Configuration; using Newtonsoft.Json; using System.Text.RegularExpressions; using System; namespace BatMon.Framework { public class Result { public Result(string ApplicationName, string TierName, string ProcessName, string ErrorCode, string ErrorDescription, object obj = null) { this.Obj = obj; this.ApplicationName = ApplicationName; this.TierName = TierName; this.ProcessName = ProcessName; this.ErrorCode = ErrorCode; this.ErrorDescription = ExpandVariables(ErrorDescription); } public string ApplicationName { get; set; } public string TierName { get; set; } public string ProcessName { get; set; } public string ErrorCode { get; set; } public string ErrorDescription { get; set; } [JsonIgnore] public object Obj { get; private set; } public string ToAppD() { return string.Format("[{0},{1},{2},{3},{4}]", JsonConvert.SerializeObject(this.ApplicationName), JsonConvert.SerializeObject(this.TierName), JsonConvert.SerializeObject(this.ProcessName), JsonConvert.SerializeObject(this.ErrorCode), JsonConvert.SerializeObject(this.ErrorDescription)); } public string ExpandVariables(string s) { if (s is null) { return null; } MatchCollection mc = Regex.Matches(s, @"\${(?'Object'.*?)?(?:\:(?'Item'.*?))?(?:\[(?'ItemSub1'.*?)\](?:\[(?'ItemSub2'.*?)\])?)?(?:->[fF][oO][rR][mM][aA][tT]=(?'Format'.*?))?}"); /* Groups * Object - Returns the objects toString value * Item - Name of the Variable or Property you want * ItemSub1 - (Optional) Sub property of Item (Row if a dataset) * ItemSub2 - (Optional) for use with datasets as Column * Format - (Optional - can be used even without any of the previous options set) * For Supported formating go to https://docs.microsoft.com/en-us/dotnet/standard/base-types/formatting-types * * Example Matchs * ${Obj} = 1 * ${Obj->format=yyyy-MM-dd HH:mm:ss.fff} = 3 * ${Obj:ExitCode} = 5 * ${Obj:ExitCode->format=yyyy-MM-dd HH:mm:ss.fff} = 7 * ${Obj[BaudRate]} = 9 * ${Obj[BaudRate]->format=#.##} = 11 * ${Obj:Port[BaudRate]} = 13 * ${Obj:Port[BaudRate]->format=yyyy-MM-dd HH:mm:ss.fff} = 15 * ${Obj[Row][Column]} = 19 * ${Obj[Row][Column]->format=#.##} = 21 * ${Obj:DataSet[Row][Column]} = 23 * ${Obj:DataSet[Row][Column]->format=yyyy-MM-dd HH:mm:ss.fff} = 25 * */ foreach (Match m in mc) { //Substitute the variable ${Obj} with its objects value s = s.Replace(m.Value, ConfigVariable_ToValue(m)); } return Environment.ExpandEnvironmentVariables(s); } private string ConfigVariable_ToValue(Match m) { dynamic t_obj; dynamic t_item; dynamic t_itemSub1; dynamic t_itemSub2; string newValue= "[INVALID VARIABLE]"; switch (ConfigVariable_PartScore(m)) { case 1: //Object = 1 t_obj = this.GetType()?.GetProperty(m.Groups["Object"].Value)?.GetValue(this); newValue = t_obj?.ToString() ?? "[INVALID VARIABLE]"; break; case 3: //Object = 1 //Format = 2 t_obj = this.GetType()?.GetProperty(m.Groups["Object"].Value)?.GetValue(this); try { newValue = t_obj?.ToString(m.Groups["Format"].Value) ?? "[INVALID VARIABLE]"; } catch { newValue = t_obj?.ToString() ?? "[INVALID VARIABLE]"; } break; case 5: //Validated by Testing //Object = 1 //Item = 4 t_obj = this.GetType()?.GetProperty(m.Groups["Object"].Value)?.GetValue(this); t_item = t_obj.GetType()?.GetProperty(m.Groups["Item"].Value)?.GetValue(t_obj); newValue = t_item?.ToString() ?? "[INVALID VARIABLE]"; break; case 7: //DateTime Validated by testing //Object = 1 //Item = 4 //Format = 2 t_obj = this.GetType()?.GetProperty(m.Groups["Object"].Value)?.GetValue(this); t_item = t_obj.GetType()?.GetProperty(m.Groups["Item"].Value)?.GetValue(t_obj); try { newValue = t_item?.ToString(m.Groups["Format"].Value) ?? "[INVALID VARIABLE]"; } catch { newValue = t_item?.ToString() ?? "[INVALID VARIABLE]"; } break; case 9: // FIX ME //Object = 1 //ItemSub1 = 8 t_obj = this.GetType()?.GetProperty(m.Groups["Object"].Value)?.GetValue(this); t_itemSub1 = t_obj?[m.Groups["ItemSub1"].Value]; newValue = t_itemSub1?.ToString() ?? "[INVALID VARIABLE]"; break; case 11: // FIX ME //Object = 1 //ItemSub1 = 8 //Format = 2 t_obj = this.GetType()?.GetProperty(m.Groups["Object"].Value)?.GetValue(this); t_itemSub1 = t_obj?[m.Groups["ItemSub1"].Value]; try { newValue = t_itemSub1?.ToString(m.Groups["Format"].Value) ?? "[INVALID VARIABLE]"; } catch { newValue = t_itemSub1?.ToString() ?? "[INVALID VARIABLE]"; } break; case 13: //FIX ME //Object = 1 //Item = 4 //ItemSub1 = 8 t_obj = this.GetType()?.GetProperty(m.Groups["Object"].Value)?.GetValue(this); t_item = t_obj.GetType()?.GetProperty(m.Groups["Item"].Value)?.GetValue(t_obj); t_itemSub1 = t_item?[m.Groups["ItemSub1"].Value]; newValue = t_itemSub1?.ToString() ?? "[INVALID VARIABLE]"; break; case 15: // FIX ME //Object = 1 //Item = 4 //ItemSub1 = 8 //Format = 2 t_obj = this.GetType()?.GetProperty(m.Groups["Object"].Value)?.GetValue(this); t_item = t_obj.GetType()?.GetProperty(m.Groups["Item"].Value)?.GetValue(t_obj); t_itemSub1 = t_item?[m.Groups["ItemSub1"].Value]; try { newValue = t_itemSub1?.ToString(m.Groups["Format"].Value) ?? "[INVALID VARIABLE]"; } catch { newValue = t_itemSub1?.ToString() ?? "[INVALID VARIABLE]"; } break; case 19: // FIX ME //Object = 1 //ItemSub1 = 8 //ItemSub2 =10 t_obj = this.GetType()?.GetProperty(m.Groups["Object"].Value)?.GetValue(this); t_itemSub1 = t_obj?[m.Groups["ItemSub1"].Value]; t_itemSub2 = t_itemSub1?[m.Groups["ItemSub2"].Value]; newValue = t_itemSub2?.ToString() ?? "[INVALID VARIABLE]"; break; case 21: // FIX ME //Object = 1 //ItemSub1 = 8 //ItemSub2 =10 //Format = 2 t_obj = this.GetType()?.GetProperty(m.Groups["Object"].Value)?.GetValue(this); t_itemSub1 = t_obj?[m.Groups["ItemSub1"].Value]; t_itemSub2 = t_itemSub1?[m.Groups["ItemSub2"].Value]; try { newValue = t_itemSub2?.ToString(m.Groups["Format"].Value) ?? "[INVALID VARIABLE]"; } catch { newValue = t_itemSub2?.ToString() ?? "[INVALID VARIABLE]"; } break; case 23: // FIX ME //Object = 1 //Item = 4 //ItemSub1 = 8 //ItemSub2 =10 t_obj = this.GetType()?.GetProperty(m.Groups["Object"].Value)?.GetValue(this); t_item = t_obj.GetType()?.GetProperty(m.Groups["Item"].Value)?.GetValue(t_obj); t_itemSub1 = t_item?[m.Groups["ItemSub1"].Value]; t_itemSub2 = t_itemSub1?[m.Groups["ItemSub2"].Value]; newValue = t_itemSub2?.ToString() ?? "[INVALID VARIABLE]"; break; case 25: // FIX ME //Object = 1 //Item = 4 //ItemSub1 = 8 //ItemSub2 = 10 //Format = 2 t_obj = this.GetType()?.GetProperty(m.Groups["Object"].Value)?.GetValue(this); t_item = t_obj.GetType()?.GetProperty(m.Groups["Item"].Value)?.GetValue(t_obj); t_itemSub1 = t_item?[m.Groups["ItemSub1"].Value]; t_itemSub2 = t_itemSub1?[m.Groups["ItemSub2"].Value]; try { newValue = t_itemSub2?.ToString(m.Groups["Format"].Value) ?? "[INVALID VARIABLE]"; } catch { newValue = t_itemSub2?.ToString() ?? "[INVALID VARIABLE]"; } break; default: break; } return newValue; } private int ConfigVariable_PartScore(Match m) { int PartsValue = 0; foreach (var grpName in m.Groups.Cast<Group>() .Where(g => g.Value != "") .Select(g => g.Name) ) { switch (grpName) { case "Object": PartsValue += 1; break; case "Item": PartsValue += 4; break; case "ItemSub1": PartsValue += 8; break; case "ItemSub2": PartsValue += 10; break; case "Format": PartsValue += 2; break; default: //Do not add anything break; } } return PartsValue; } } } <file_sep>/src/BatMon.UriMonitor/Config/UriEndPoints.cs using System.Linq; using System.Configuration; using System.Reflection; namespace BatMon.UriMonitor.Config { public class UriEndPoints : ConfigurationSection { private static readonly UriEndPoints instance = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).Sections.OfType<UriEndPoints>().FirstOrDefault() as UriEndPoints ?? ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location).Sections.OfType<UriEndPoints>().FirstOrDefault() as UriEndPoints; public static UriEndPoints getCurrentInstance { get { return instance; } } [ConfigurationProperty("", IsDefaultCollection = true)] public EndPoints EndPoints { get { return ((EndPoints)base[""]) ?? new EndPoints(); } } } } <file_sep>/src/BatMon.WindowsShare/WindowsSharePlugin.cs /* *Copyright (C) 2018 <NAME> - All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license, * * You should have received a copy of the MIT license with * this file. If not, visit : https://github.com/fatalwall/BatMon */ using BatMon.Framework; using System.ComponentModel.Composition; using BatMon.WindowsShare.Config; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Net; using vshed.IO; namespace BatMon.WindowsShare { [Export(typeof(IBatMonPlugin))] [ExportMetadata("Name", "WindowsShare")] [ExportMetadata("isAggregate", false)] public class WindowsSharePlugin : BatMonPlugin, IBatMonPlugin { protected override Result[] fetchResults() { List<Result> r = new List<Result>(); WindowsShareSection settings = WindowsShareSection.getCurrentInstance; foreach (FolderElement f in settings.Folders) { logger.Trace(string.Format("Path: {0} User: {1}", f.Path, f.User??"")); UncShare Credentials = null; try { //Initialize Credentials if needed if (f.User != null) Credentials = new UncShare(f.Path, f.User, f.Password); //Run Filesystem Test if (!System.IO.Directory.Exists(f.Path)) { r.Add(new Result(f.ApplicationName, f.TierName, f.ProcessName, "Failure", string.Format("Path could not be found {0}", f.Path))); } else { if (f.ContentCheck & System.IO.Directory.GetFiles(f.Path).Length <= 0 & System.IO.Directory.GetDirectories(f.Path).Length <= 0) { r.Add(new Result(f.ApplicationName, f.TierName, f.ProcessName, "Error", string.Format("Path contains 0 files and directories {0}", f.Path))); } else { r.Add(new Result(f.ApplicationName, f.TierName, f.ProcessName, "Successful", "Folder or Network share is acessable")); } } } catch (System.ComponentModel.Win32Exception ex) { r.Add(new Result(f.ApplicationName, f.TierName, f.ProcessName, "Failure", ex.Message)); } finally { //Clean up credentials if needed if (Credentials != null) Credentials.Dispose(); } } return r.ToArray(); } } } <file_sep>/src/BatMon.ScheduledTasks/Config/ResultCodeCollection.cs /* *Copyright (C) 2018 <NAME> - All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license, * * You should have received a copy of the MIT license with * this file. If not, visit : https://github.com/fatalwall/BatMon */ using System; using System.Configuration; namespace BatMon.ScheduledTasks.Config { public class ResultCodeCollection : ConfigurationElementCollection { public ResultCodeCollection() { this.Add(new ResultCodeElement("", "Unconfigured", "No result code configuration could be found")); } public int IndexOf(String ExitCode) { for (int idx = 0; idx < base.Count; idx++) { if (this[idx].ExitCode.ToUpper() == ExitCode.ToUpper()) return idx; } return -1; } public ResultCodeElement this[int index] { get { return (ResultCodeElement)BaseGet(index); } } public new ResultCodeElement this[String ExitCode] { get { if (IndexOf(ExitCode) < 0) { return this.Default; } return (ResultCodeElement)BaseGet(ExitCode); } } public ResultCodeElement Default { get { if (IndexOf("") < 0) return null; return (ResultCodeElement)BaseGet(""); } } public void Add(ResultCodeElement c) { BaseAdd(c); } public void Remove(ResultCodeElement c) { if (BaseIndexOf(c) >= 0) BaseRemove(c.ExitCode); } public void RemoveAt(int index) { BaseRemoveAt(index); } public void Remove(String ID) { BaseRemove(ID); } public void Clear() { BaseClear(); } public new int Count() { return base.Count; } public override ConfigurationElementCollectionType CollectionType { get { return ConfigurationElementCollectionType.BasicMap; } } protected override ConfigurationElement CreateNewElement() { return new ResultCodeElement(); } protected override object GetElementKey(ConfigurationElement element) { return ((ResultCodeElement)element).ExitCode; } protected override string ElementName { get { return "ResultCode"; } } } }<file_sep>/src/BatMon.ScheduledTasks/Config/ScheduledTasksSection.cs /* *Copyright (C) 2018 <NAME> - All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license, * * You should have received a copy of the MIT license with * this file. If not, visit : https://github.com/fatalwall/BatMon */ using System.Configuration; namespace BatMon.ScheduledTasks.Config { public class ScheduledTasksSection : ConfigurationSection { [ConfigurationProperty("ResultCodes", IsDefaultCollection = false)] [ConfigurationCollection(typeof(ResultCodeCollection), AddItemName = "add", ClearItemsName = "Clear", RemoveItemName = "Remove")] public ResultCodeCollection ResultCodes { get { return ((ResultCodeCollection)base["ResultCodes"]) ?? new ResultCodeCollection(); } } [ConfigurationProperty("FolderFilters", IsDefaultCollection = false)] [ConfigurationCollection(typeof(FolderFilterCollection), AddItemName = "add", ClearItemsName = "Clear", RemoveItemName = "Remove")] public FolderFilterCollection FolderFilters { get { return ((FolderFilterCollection)base["FolderFilters"]) ?? new FolderFilterCollection(); } } [ConfigurationProperty("Application")] public ApplicationElement Application { get { return (ApplicationElement)base["Application"]; } } [ConfigurationProperty("Tier")] public TierElement Tier { get { return (TierElement)base["Tier"]; } } [ConfigurationProperty("ApplicationDynamicOverride")] public ApplicationDynamicOverrideElement ApplicationDynamicOverride { get { return (ApplicationDynamicOverrideElement)base["ApplicationDynamicOverride"]; } } [ConfigurationProperty("TierDynamicOverride")] public TierDynamicOverrideElement TierDynamicOverride { get { return (TierDynamicOverrideElement)base["TierDynamicOverride"]; } } [ConfigurationProperty("InitialStageResultCodes")] public InitialStageResultCodesElement InitialStageResultCodes { get { return ((InitialStageResultCodesElement)base["InitialStageResultCodes"]) ?? new InitialStageResultCodesElement(false); } } } }<file_sep>/img/ReadMe.txt All Icons are from Open-Iconic under the MIT Licence SVG files have bene sized, converted, colored, and merged as needed. More details and other icons can be found here https://useiconic.com/open https://github.com/iconic/open-iconic<file_sep>/src/BatMon.UriMonitor/Config/EndPoints.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Configuration; namespace BatMon.UriMonitor.Config { public class EndPoints : ConfigurationElementCollection { public EndPoint this[int index] { get { return (EndPoint)BaseGet(index); } } public int IndexOf(EndPoint e) { return BaseIndexOf(e); } public override System.Configuration.ConfigurationElementCollectionType CollectionType { get { return System.Configuration.ConfigurationElementCollectionType.BasicMap; } } protected override ConfigurationElement CreateNewElement() { return new EndPoint(); } protected override object GetElementKey(ConfigurationElement element) { return ((EndPoint)element); } public void Add(EndPoint e) { BaseAdd(e); } public void Remove(EndPoint e) { if (BaseIndexOf(e) >= 0) BaseRemove(e); } public void RemoveAt(int index) { BaseRemoveAt(index); } public void Clear() { BaseClear(); } protected override string ElementName { get { return "EndPoint"; } } } } <file_sep>/src/BatMon.Framework/BatMonPluginAbout.cs /* *Copyright (C) 2018 <NAME> - All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license, * * You should have received a copy of the MIT license with * this file. If not, visit : https://github.com/fatalwall/BatMon */ namespace BatMon.Framework { public class BatMonPluginAbout { public BatMonPluginAbout(string dllName, string className, System.Version version) { this.dllName = dllName; this.className = className; this.Version = version; } public string className { get; private set; } public string dllName { get; private set; } public System.Version Version { get; private set; } public override string ToString() { return string.Format("{0}.{1} ({2})", this.dllName,this.className, this.Version); } } }
81614f406bd1afcd9ec4490331384f7e9ed84b33
[ "JavaScript", "C#", "Text", "Markdown" ]
35
C#
fatalwall/BatMon
64f0edf34c503281add3652f9d58e7dcdc75bf1b
026e034357621b116c5222115fd3d019b9702c38
refs/heads/master
<file_sep># Pokemon-Game This is a simple 3-D pokemon game made using Unity. It uses Google's ARCore to detect planes and spawn objects. <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class Gamemanager : MonoBehaviour { public Text t; private void Start() { if(blast.scy != true) { t.text = "Scyther Won!!"; } if (blast.scy != false) { t.text = "Blastoise Won!!"; } } public void Restart() { blast.scy = true; blast.health1 = 100f; Button1.health2 = 100f; SceneManager.LoadScene(0); } public void Exit() { Application.Quit(); } } <file_sep>sdk.dir=C\:\\Users\\<NAME>\\AppData\\Local\\Android\\sdk <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class Button1 : MonoBehaviour { public Animator a; public Animator b; public Text t; public static float health2 = 100f; private float time = 0f; private bool set = true; public Transform obj; private void Start() { t.text = health2.ToString("0"); } private void Update() { time += Time.deltaTime; if (time >= 1.2f) { set = true; } if(health2 <= 0f) { blast.scy = false; SceneManager.LoadScene(1); } } public void Clicked() { if (set == true) { a.SetBool("Attack", true); b.SetBool("AttackB", true); Invoke("StopAnimation", 1.2f); time = 0f; set = false; } } private void StopAnimation() { a.SetBool("Attack", false); b.SetBool("AttackB", false); health2 -= Random.Range(20f, 40f); t.text = health2.ToString("0"); } public void Rotate() { obj.Rotate(0f, 10f, 0f); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class blast : MonoBehaviour { public Animator b; public Text t; public static float health1 = 100f; public ParticleSystem P; public ParticleSystem P1; public static bool scy = true; private float time = 0f; private bool set = true; public Transform obj; private void Start() { t.text = health1.ToString("0"); } private void Update() { time += Time.deltaTime; if (time >= 1.5f) { set = true; } if (health1 <= 0f) { SceneManager.LoadScene(1); } } public void Clicked() { if (set == true) { b.SetBool("AttackB", true); Invoke("StopAnimation", 2f); P.Play(); P1.Play(); time = 0f; set = false; } } private void StopAnimation() { b.SetBool("AttackB", false); health1 -= Random.Range(20f, 40f); t.text = health1.ToString("0"); } public void Rotate() { obj.Rotate(0f,10f,0f); } }
da2326ffeadff2b5e76b373ef4a224a69b182671
[ "Markdown", "C#", "INI" ]
5
Markdown
Surya-13/Simple-Pokemon-Game
fc1e20989f36a3e2bc5b5d27237d0a39fe3a4c5f
e02715707a43220335d8c66de516424a582f5ec5
refs/heads/master
<file_sep>package com.example.luongquockhang.weatherforecast.utils; /** * Created by <NAME> on 10/27/2017. */ public enum TypePrediction { ADDRESS_NAME, // TÌM THEO ĐỊA CHỈ LATITUDE_LONGITUDE // TÌM THEO VĨ ĐỘ VÀ KINH ĐỘ } <file_sep>package com.example.luongquockhang.weatherforecast.WeatherPrediction; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.Color; import android.location.Address; import android.location.Geocoder; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.example.luongquockhang.weatherforecast.Model.OpenWeatherJSON; import com.example.luongquockhang.weatherforecast.R; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.model.Marker; import java.io.IOException; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Date; import java.util.List; import java.util.Locale; /** * Created by <NAME> on 11/13/2017. */ public class InfoAdapter implements GoogleMap.InfoWindowAdapter { private Activity context; private Marker marker = null; private OpenWeatherJSON openWeatherJSON = null; Bitmap bitmap = null; NumberFormat format = new DecimalFormat("#0.0"); private double latitude; private double longitude; public InfoAdapter(Activity activity) { this.context = activity; } public InfoAdapter(Activity context, Marker marker, OpenWeatherJSON weather, Bitmap bitmap) { this.context = context; this.marker = marker; this.openWeatherJSON = weather; this.bitmap = bitmap; } public InfoAdapter(Activity context, Marker marker, OpenWeatherJSON weather, Bitmap bitmap, double latitude, double longitude) { this.context = context; this.marker = marker; this.openWeatherJSON = weather; this.bitmap = bitmap; this.latitude = latitude; this.longitude = longitude; } @Override public View getInfoWindow(Marker marker) { View view = this.context.getLayoutInflater().inflate(R.layout.info_window,null); TextView CurrentLocation,Temperature,Max_temp,Min_temp,Wind,Pressure,Humidity,Clouds,Sunrise,Description,SunSet; ImageView image = (ImageView)view.findViewById(R.id.imageView); CurrentLocation = (TextView)view.findViewById(R.id.textViewLocation); Temperature = (TextView)view.findViewById(R.id.textViewTemp); Max_temp = (TextView)view.findViewById(R.id.textViewMaxtemp); Min_temp = (TextView)view.findViewById(R.id.textViewMinTemp); Wind = (TextView)view.findViewById(R.id.textViewWind); Pressure = (TextView)view.findViewById(R.id.textViewPressure); Humidity = (TextView)view.findViewById(R.id.textViewHumidity); Clouds = (TextView)view.findViewById(R.id.textViewClouds); Sunrise = (TextView)view.findViewById(R.id.textViewSunrise); Description = (TextView)view.findViewById(R.id.textviewDescription); SunSet = (TextView)view.findViewById(R.id.txtSunset); CurrentLocation.setText(openWeatherJSON.getName()); Temperature.setText( String.valueOf(openWeatherJSON.getMain().getTemp()) + "°C"); Max_temp.setText(String.valueOf(openWeatherJSON.getMain().getTemp_max()) + "°C"); Min_temp.setText(String.valueOf(openWeatherJSON.getMain().getTemp_min()) + "°C"); Wind.setText(String.valueOf(openWeatherJSON.getWind().getSpeed()) + "m/s"); Pressure.setText(String.valueOf(openWeatherJSON.getMain().getPressure()) + "hpa"); Humidity .setText(String.valueOf(openWeatherJSON.getMain().getHumidity()) + "%"); Clouds.setText(openWeatherJSON.getListWeather().get(0).getMain()); Date TimeSunrise = new Date((long) (openWeatherJSON.getSys().getSunrise()*1000)); Sunrise.setText(TimeSunrise.getHours() + " : " + TimeSunrise.getMinutes()); Date TimeSunSet = new Date((long) openWeatherJSON.getSys().getSunset()*1000); String TimeSS = TimeSunSet.getHours() + " : " + TimeSunSet.getMinutes(); SunSet.setText(TimeSS); Description.setText(openWeatherJSON.getListWeather().get(0).getDesciption()); image.setImageBitmap(bitmap); try { Geocoder geocoder; List<Address> addresses; geocoder = new Geocoder(this.context, Locale.getDefault()); addresses = geocoder.getFromLocation(latitude,longitude,1); if ( addresses.size() > 0) { Address address = addresses.get(0); if ( address != null ) { CurrentLocation.setText(address.getAddressLine(0)); } } } catch (IOException e) { e.printStackTrace(); } view.setBackgroundColor(Color.WHITE); return view; } @Override public View getInfoContents(Marker marker) { return null; } } <file_sep>package com.example.luongquockhang.weatherforecast.WeatherPrediction; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import com.example.luongquockhang.weatherforecast.R; import com.example.luongquockhang.weatherforecast.utils.WeatherAsyncTask; public class weather_information extends AppCompatActivity { Button btnBack; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_weather_information); btnBack = (Button)findViewById(R.id.button); btnBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } @Override protected void onResume() { super.onResume(); Intent intent = getIntent(); String data = intent.getStringExtra("data"); WeatherAsyncTask Task = new WeatherAsyncTask(weather_information.this,data); Task.execute(); } } <file_sep>package com.example.luongquockhang.weatherforecast.Model; /** * Created by <NAME> on 10/27/2017. */ public class Clouds { public int getAll() { return all; } public void setAll(int all) { this.all = all; } private int all; // tỉ lệ có mây } <file_sep>package com.example.luongquockhang.weatherforecast.utils; import android.app.Activity; import android.app.ProgressDialog; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.location.Address; import android.location.Geocoder; import android.os.AsyncTask; import android.widget.ImageView; import android.widget.TextView; import com.example.luongquockhang.weatherforecast.Model.OpenWeatherJSON; import com.example.luongquockhang.weatherforecast.R; import com.example.luongquockhang.weatherforecast.WeatherPrediction.InfoAdapter; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.model.Marker; import org.json.JSONException; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Date; import java.util.List; import java.util.Locale; /** * Created by <NAME> on 10/27/2017. */ public class WeatherAsyncTask extends AsyncTask<Void,Void,OpenWeatherJSON> { private Activity activity; private Bitmap mybitmap; private ProgressDialog dialog; private TypePrediction prediction; private String location; private double latitude; private double longitude; private NumberFormat format = new DecimalFormat("#0.0"); Marker marker = null; GoogleMap googlemap = null; public WeatherAsyncTask(Activity activity, double latitude, double longitude, Marker marker, GoogleMap googlemap) { prediction = TypePrediction.LATITUDE_LONGITUDE; this.activity = activity; this.latitude = latitude; this.longitude = longitude; this.marker = marker; this.googlemap = googlemap; dialog = new ProgressDialog(activity); dialog.setTitle("Loading data ..."); dialog.setCancelable(true); } public WeatherAsyncTask(Activity activity , String location) { prediction = TypePrediction.ADDRESS_NAME; this.activity = activity; this.location = location; dialog = new ProgressDialog(activity); dialog.setTitle("Loading data ..."); dialog.setCancelable(true); } @Override protected void onPreExecute() { super.onPreExecute(); //dialog.show(); } @Override protected OpenWeatherJSON doInBackground(Void... params) { // kết nối , lấy thông tin String data = "'"; WeatherHttpClient http = new WeatherHttpClient(); if ( prediction == TypePrediction.LATITUDE_LONGITUDE) { data = http.getWeatherDataByCoord(latitude,longitude); } else { data = http.getCurrentWeatherData(location); } OpenWeatherJSON JObject = null; try { JObject = OpenWeatherMapAPI.getWeather(data); if (JObject != null) { String idIcon = JObject.getListWeather().get(0).getIcon().toString(); String urlicon = "http://openweathermap.org/img/w/" + idIcon + ".png"; InputStream is = null; HttpURLConnection connection = null; try { URL urlconnection = new URL(urlicon); connection = (HttpURLConnection) urlconnection.openConnection(); connection.setDoInput(true); connection.connect(); is = connection.getInputStream(); mybitmap = BitmapFactory.decodeStream(is); is.close(); connection.disconnect(); return JObject; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } catch (JSONException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(OpenWeatherJSON openWeatherJSON) { super.onPostExecute(openWeatherJSON); if ( googlemap != null && openWeatherJSON != null) { googlemap.setInfoWindowAdapter(new InfoAdapter(activity,marker,openWeatherJSON,mybitmap,latitude,longitude)); marker.showInfoWindow(); return; } if ( openWeatherJSON != null ) { // cập nhật thông tin lên giao diện TextView CurrentLocation, Temperature, Max_temp, Min_temp, Wind, Pressure, Humidity, Clouds, Sunrise, Description, SunSet; ImageView image = (ImageView) activity.findViewById(R.id.imageView); CurrentLocation = (TextView) activity.findViewById(R.id.textViewLocation); Temperature = (TextView) activity.findViewById(R.id.textViewTemp); Max_temp = (TextView) activity.findViewById(R.id.textViewMaxtemp); Min_temp = (TextView) activity.findViewById(R.id.textViewMinTemp); Wind = (TextView) activity.findViewById(R.id.textViewWind); Pressure = (TextView) activity.findViewById(R.id.textViewPressure); Humidity = (TextView) activity.findViewById(R.id.textViewHumidity); Clouds = (TextView) activity.findViewById(R.id.textViewClouds); Sunrise = (TextView) activity.findViewById(R.id.textViewSunrise); Description = (TextView) activity.findViewById(R.id.textviewDescription); SunSet = (TextView) activity.findViewById(R.id.txtSunset); CurrentLocation.setText(openWeatherJSON.getName()); Temperature.setText(String.valueOf(openWeatherJSON.getMain().getTemp()) + "°C"); Max_temp.setText(String.valueOf(openWeatherJSON.getMain().getTemp_max()) + "°C"); Min_temp.setText(String.valueOf(openWeatherJSON.getMain().getTemp_min()) + "°C"); Wind.setText(String.valueOf(openWeatherJSON.getWind().getSpeed()) + "m/s"); Pressure.setText(String.valueOf(openWeatherJSON.getMain().getPressure()) + "hpa"); Humidity.setText(String.valueOf(openWeatherJSON.getMain().getHumidity()) + "%"); Clouds.setText(openWeatherJSON.getListWeather().get(0).getMain()); Date TimeSunrise = new Date((long) (openWeatherJSON.getSys().getSunrise() * 1000)); Sunrise.setText(TimeSunrise.getHours() + " : " + TimeSunrise.getMinutes()); Date TimeSunSet = new Date((long) openWeatherJSON.getSys().getSunset() * 1000); String TimeSS = TimeSunSet.getHours() + " : " + TimeSunSet.getMinutes(); SunSet.setText(TimeSS); Description.setText(openWeatherJSON.getListWeather().get(0).getDesciption()); image.setImageBitmap(mybitmap); try { Geocoder geocoder; List<Address> addresses; geocoder = new Geocoder(this.activity, Locale.getDefault()); addresses = geocoder.getFromLocation(latitude,longitude,1); if ( addresses.size() > 0) { Address address = addresses.get(0); if ( address != null ) { CurrentLocation.setText(address.getAddressLine(0)); } } } catch (IOException e) { e.printStackTrace(); } } dialog.dismiss(); } }
e167124f7eb08089802dca8874b2c2cdcbe3dcb2
[ "Java" ]
5
Java
LuongQuocKhang/Weather-Forecast---android
86665de4f51220f08a04391d4cbd888f280a7abf
592a2d19dc6dcf7c10a56237add55f9c2c24d8db
refs/heads/master
<repo_name>mahi386/TestBean<file_sep>/src/com/utilities/BeanTester.java package com.objectpartners.pojodemo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.math.BigDecimal; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.function.Supplier; import org.junit.Test; /** * A utility class which allows for testing entity and transfer object classes. * This is mainly for code coverage since these types of objects are normally * nothing more than getters and setters. If any logic exists in the method, * then the get method name should be sent in as an ignored field and a custom * test function should be written. * * @param <T> * The object type to test. */ public class DomainModelTest{ final static HashMap<Class<?>, Supplier<?>> testData = new HashMap<Class<?>, Supplier<?>>(); /* * A utility class which allows for testing entity and transfer object * classes. This is mainly for code coverage since these types of objects * are normally getters and setters. */ static { /** * loading all Primitives data in testData map **/ testData.put(int.class, () -> 0); testData.put(double.class, () -> 0.0d); testData.put(float.class, () -> 0.0f); testData.put(long.class, () -> 0l); testData.put(boolean.class, () -> true); testData.put(short.class, () -> (short) 0); testData.put(byte.class, () -> (byte) 0); testData.put(char.class, () -> (char) 0); testData.put(Integer.class, () -> Integer.valueOf(0)); testData.put(Double.class, () -> Double.valueOf(0.0)); testData.put(Float.class, () -> Float.valueOf(0.0f)); testData.put(Long.class, () -> Long.valueOf(0)); testData.put(Boolean.class, () -> Boolean.TRUE); testData.put(Short.class, () -> Short.valueOf((short) 0)); testData.put(Byte.class, () -> Byte.valueOf((byte) 0)); testData.put(Character.class, () -> Character.valueOf((char) 0)); testData.put(BigDecimal.class, () -> BigDecimal.ONE); testData.put(Date.class, () -> new Date()); // loading all Collection Types data in testData map testData.put(Set.class, () -> Collections.emptySet()); testData.put(SortedSet.class, () -> Collections.emptySortedSet()); testData.put(List.class, () -> Collections.emptyList()); testData.put(Map.class, () -> Collections.emptyMap()); testData.put(SortedMap.class, () -> Collections.emptySortedMap()); } /** * Calls a getter and verifies the result is what is expected. * * @param fieldName * The field name (used for error messages). * @param getter * The get {@link Method}. * @param instance * The test instance. * @param expected * The expected result. * * @throws IllegalAccessException * if this Method object is enforcing Java language access * control and the underlying method is inaccessible. * @throws IllegalArgumentException * if the method is an instance method and the specified object * argument is not an instance of the class or interface * declaring the underlying method (or of a subclass or * implementor thereof); if the number of actual and formal * parameters differ; if an unwrapping conversion for primitive * arguments fails; or if, after possible unwrapping, a * parameter value cannot be converted to the corresponding * formal parameter type by a method invocation conversion. * @throws InvocationTargetException * if the underlying method throws an exception. */ // fieldName is variable in POJO class // getter method in POJO class // This method calls junit assertEquals method for Primitives and assertSame // method for non primitives private void callGetter(String fieldName, Method getter, Object instance, Object expected) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { final Object getResult = getter.invoke(instance); if (getter.getReturnType().isPrimitive()) { /* * Calling assetEquals() here due to autoboxing of primitive to * object type. */ assertEquals(fieldName + " is different", expected, getResult); } else { /* * This is a normal object. The object passed in should be the * exactly same object we get back. */ assertSame(fieldName + " is different", expected, getResult); } } private void callEnumValidator(Object newObject,Class<?> instance){ assertEquals( "Enum values are different or not ", newObject.toString(), instance.getEnumConstants()[0].toString()); } //This is the starting point for class private String packageName = "com.objectpartners.dtotester"; Class<?>[] objectArray; public ArrayList<Object> Setup() throws Exception { ArrayList<Object> classList=new ArrayList<Object>(); objectArray = getClasses(packageName); for(Class<?> clazz:objectArray){ System.out.println("class name :"+clazz.getClass()); Class<?> clazz1 = Class.forName(clazz.getName()); Object data = null; if(clazz.isEnum()){ testEnumclass(clazz1); continue; } data = clazz1.newInstance(); classList.add(data); } return classList; } public Class<?>[] getClasses(String packageName) throws ClassNotFoundException, IOException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); assert classLoader != null; String path = packageName.replace('.', '/'); Enumeration<URL> resources = classLoader.getResources(path); List<File> dirs = new ArrayList<File>(); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); dirs.add(new File(resource.getFile())); } ArrayList<Class<?>> classes = new ArrayList<Class<?>>(); for (File directory : dirs) { classes.addAll(findClasses(directory, packageName)); } //return classes.toArray(new Class[classes.size()]); return classes.toArray(new Class[classes.size()]); } public List<Class<?>> findClasses(File directory, String packageName) throws ClassNotFoundException { List<Class<?>> classes = new ArrayList<Class<?>>(); if (!directory.exists()) { return classes; } File[] files = directory.listFiles(); for (File file : files) { if (file.isDirectory()) { classes.addAll(findClasses(file, packageName + "." + file.getName())); } else if (file.getName().endsWith(".class")) { classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6))); } } return classes; } /** * Creates an object for the given {@link Class}. * * @param fieldName * The name of the field. * @param clazz * The {@link Class} type to create. * * @return A new instance for the given {@link Class}. * * @throws InstantiationException * If this Class represents an abstract class, an interface, an * array class, a primitive type, or void; or if the class has * no nullary constructor; or if the instantiation fails for * some other reason. * @throws IllegalAccessException * If the class or its nullary constructor is not accessible. * */ // method is returns the object this object is nothing but value inserted in // testData hash map private Object createObject(String fieldName, Class<?> instance) throws InstantiationException, IllegalAccessException { try { final Supplier<?> supplier = testData.get(instance); if (supplier != null) { return supplier.get(); } // Test the object is enum or not if (instance.isEnum()) { return instance.getEnumConstants()[0]; } return instance.newInstance(); } catch (IllegalAccessException | InstantiationException e) { throw new RuntimeException("Unable to create objects for field '"+ fieldName + "'.", e); } } /** * Returns an instance to use to test the get and set methods. * * @return An instance to use to test the get and set methods. */ /** * Tests all the getters and setters. Verifies that when a set method is * called, that the get method returns the same thing. This will also use * reflection to set the field if no setter exists * * @throws Exception * If an expected error occurs. */ // Test method is executed for each end every POJO test class is loaded in JUNIT @Test public void test() throws Exception{ ArrayList<Object> instance1 = Setup(); System.out.println(instance1.size()); Object instance = null; for(Object object: instance1){ instance=object; testGettersAndSetters(instance); } } void testEnumclass(Class<?> instance ) throws Exception{ /* Sort items for consistent test runs. */ final SortedMap<String, GetterSetterPair> getterSetterMapping = new TreeMap<>(); System.out.println(instance.getName()); // for loop is used to get the all the methods of pojo class for (final Method method : instance.getDeclaredMethods()) { final String methodName = method.getName(); System.out.println(" method name "+ methodName); // Ignoring the object class methods if (methodName.equalsIgnoreCase("wait") || methodName.equalsIgnoreCase("equals") || methodName.equalsIgnoreCase("toString") || methodName.equalsIgnoreCase("notify") || methodName.equalsIgnoreCase("notifyAll") || methodName.equalsIgnoreCase("toString") || methodName.equalsIgnoreCase("hashCode") || methodName.equalsIgnoreCase("getClass")) { continue; } if (testData.containsValue(methodName)) { continue; } String objectName; if (methodName.startsWith("get") && method.getParameters().length == 0) { /* Found the get method for pojo class . */ objectName = methodName.substring("get".length()); GetterSetterPair getterSettingPair = getterSetterMapping.get(objectName); if (getterSettingPair == null) { getterSettingPair = new GetterSetterPair(); getterSetterMapping.put(objectName, getterSettingPair); } getterSettingPair.setGetter(method); } else if (methodName.startsWith("set") && method.getParameters().length == 1) { /* Found the set method for pojo class . */ objectName = methodName.substring("set".length()); GetterSetterPair getterSettingPair = getterSetterMapping.get(objectName); if (getterSettingPair == null) { getterSettingPair = new GetterSetterPair(); getterSetterMapping.put(objectName, getterSettingPair); } getterSettingPair.setSetter(method); } else if (methodName.startsWith("is") && method.getParameters().length == 0) { /* Found the is method, which really is a get method. */ objectName = methodName.substring("is".length()); GetterSetterPair getterSettingPair = getterSetterMapping.get(objectName); if (getterSettingPair == null) { getterSettingPair = new GetterSetterPair(); getterSetterMapping.put(objectName, getterSettingPair); } getterSettingPair.setGetter(method); } } /* * Found all our mappings. Now call the getter and setter or set the * field via reflection and call the getting it doesn't have a setter. */ for (final Entry<String, GetterSetterPair> entry : getterSetterMapping.entrySet()) { final GetterSetterPair pair = entry.getValue(); final String objectName = entry.getKey(); final String fieldName = objectName.substring(0, 1).toLowerCase() + objectName.substring(1); if (pair.hasGetterAndSetter()) { /* Create an object. */ final Object newObject = createObject(fieldName, instance); callEnumValidator(newObject,instance); } else if (pair.getGetter() != null) { final Object newObject = createObject(fieldName, pair.getGetter().getReturnType()); final Field field = instance.getClass().getDeclaredField(fieldName); field.setAccessible(true); field.set(instance, newObject); callEnumValidator(newObject,instance); } } } public void testGettersAndSetters(Object instance) throws Exception { /* Sort items for consistent test runs. */ final SortedMap<String, GetterSetterPair> getterSetterMapping = new TreeMap<>(); // for loop is used to get the all the methods of pojo class for (final Method method : instance.getClass().getMethods()) { final String methodName = method.getName(); // Ignoring the object class methods if (methodName.equalsIgnoreCase("wait") || methodName.equalsIgnoreCase("equals") || methodName.equalsIgnoreCase("toString") || methodName.equalsIgnoreCase("notify") || methodName.equalsIgnoreCase("notifyAll") || methodName.equalsIgnoreCase("toString") || methodName.equalsIgnoreCase("hashCode") || methodName.equalsIgnoreCase("getClass")) { continue; } if (testData.containsValue(methodName)) { continue; } String objectName; if (methodName.startsWith("get") && method.getParameters().length == 0) { /* Found the get method for pojo class . */ objectName = methodName.substring("get".length()); GetterSetterPair getterSettingPair = getterSetterMapping.get(objectName); if (getterSettingPair == null) { getterSettingPair = new GetterSetterPair(); getterSetterMapping.put(objectName, getterSettingPair); } getterSettingPair.setGetter(method); } else if (methodName.startsWith("set") && method.getParameters().length == 1) { /* Found the set method for pojo class . */ objectName = methodName.substring("set".length()); GetterSetterPair getterSettingPair = getterSetterMapping.get(objectName); if (getterSettingPair == null) { getterSettingPair = new GetterSetterPair(); getterSetterMapping.put(objectName, getterSettingPair); } getterSettingPair.setSetter(method); } else if (methodName.startsWith("is") && method.getParameters().length == 0) { /* Found the is method, which really is a get method. */ objectName = methodName.substring("is".length()); GetterSetterPair getterSettingPair = getterSetterMapping.get(objectName); if (getterSettingPair == null) { getterSettingPair = new GetterSetterPair(); getterSetterMapping.put(objectName, getterSettingPair); } getterSettingPair.setGetter(method); } } /* * Found all our mappings. Now call the getter and setter or set the * field via reflection and call the getting it doesn't have a setter. */ for (final Entry<String, GetterSetterPair> entry : getterSetterMapping.entrySet()) { final GetterSetterPair pair = entry.getValue(); final String objectName = entry.getKey(); final String fieldName = objectName.substring(0, 1).toLowerCase() + objectName.substring(1); if (pair.hasGetterAndSetter()) { /* Create an object. */ final Class<?> parameterType = pair.getSetter() .getParameterTypes()[0]; final Object newObject = createObject(fieldName, parameterType); pair.getSetter().invoke(instance, newObject); callGetter(fieldName, pair.getGetter(), instance, newObject); } else if (pair.getGetter() != null) { final Object newObject = createObject(fieldName, pair.getGetter().getReturnType()); final Field field = instance.getClass().getDeclaredField(fieldName); field.setAccessible(true); field.set(instance, newObject); callGetter(fieldName, pair.getGetter(), instance, newObject); } } } }
ddd7edf26ce6ef189dc83a57a5d987718a5427ed
[ "Java" ]
1
Java
mahi386/TestBean
d3b96dc8fcd7fcc9b9bd215fa8de25f5b99c5c5c
28b77dd8863550975ddd1463508458e5117c0366
refs/heads/master
<file_sep>typedef struct SYS_Reg { SYS_Reg(uint8_t raw) { SYS_MON = (raw >> 5) & 0x07; CAL_SAMP = (raw >> 3) & 0x03; TIMEOUT = (raw >> 2) & 0x01; _CRC = (raw >> 1) & 0x01; SENDSTAT = (raw >> 0) & 0x01; } uint8_t get() { uint8_t retval = 0x00; retval |= (SENDSTAT << 0); retval |= (_CRC << 1); retval |= (TIMEOUT << 2); retval |= (CAL_SAMP << 3); retval |= (SYS_MON << 5); return retval; } uint8_t SYS_MON :3; /* * System monitor configuration(1) Enables a set of system monitor measurements using the ADC. 000 : Disabled (default) 001 : PGA inputs shorted to (AVDD + AVSS) / 2 and disconnected from AINx and the multiplexer; gain set by user 010 : Internal temperature sensor measurement; PGA must be enabled (PGA_EN[1:0] = 01); gain set by user(2) 011 : (AVDD – AVSS) / 4 measurement; gain set to 1 (3) 100 : DVDD / 4 measurement; gain set to 1 (3) 101 : Burn-out current sources enabled, 0.2-µA setting 110 : Burn-out current sources enabled, 1-µA setting 111 : Burn-out current sources enabled, 10-µA setting */ uint8_t CAL_SAMP :2; /* * Calibration sample size selection Configures the number of samples averaged for self and system offset and system gain calibration. 00 : 1 sample 01 : 4 samples 10 : 8 samples (default) 11 : 16 samples */ uint8_t TIMEOUT :1; /* * SPI timeout enable Enables the SPI timeout function. 0 : Disabled (default) 1 : Enabled */ uint8_t _CRC :1; /* * CRC enable Enables the CRC byte appended to the conversion result. When enabled, CRC is calculated across the 24-bit conversion result (plus the STATUS byte if enabled). 0 : Disabled (default) 1 : Enabled */ uint8_t SENDSTAT :1; /* * STATUS byte enable Enables the STATUS byte prepended to the conversion result. 0 : Disabled (default) 1 : Enabled */ } SYS_Reg; typedef struct ID_Reg { ID_Reg(uint8_t raw) { RESERVED = (raw >> 3); DEV_ID = raw & 0x7; } uint8_t get() { uint8_t retval = 0x00; retval |= (DEV_ID << 0); retval |= (RESERVED << 3); return retval; } uint8_t RESERVED :5; /* Values are subject to change without notice */ uint8_t DEV_ID :3; /* * Device identifier Identifies the model of the device. 000 : ADS124S08 (12 channels, 24 bits) 001 : ADS124S06 (6 channels, 24 bits) else: Reserved */ } ID_Reg; typedef struct STATUS_Reg { STATUS_Reg(uint8_t raw) { FL_POR = (raw >> 7) & 0x01; nRDY = (raw >> 6) & 0x01; FL_P_RAILP = (raw >> 5) & 0x01; FL_P_RAILN = (raw >> 4) & 0x01; FL_N_RAILP = (raw >> 3) & 0x01; FL_N_RAILN = (raw >> 2) & 0x01; FL_REF_L1 = (raw >> 1) & 0x01; FL_REF_L0 = (raw >> 0) & 0x01; } uint8_t get() { uint8_t retval = 0x00; retval |= (FL_REF_L0 << 0); retval |= (FL_REF_L1 << 1); retval |= (FL_N_RAILN << 2); retval |= (FL_N_RAILP << 3); retval |= (FL_P_RAILN << 4); retval |= (FL_P_RAILP << 5); retval |= (nRDY << 6); retval |= (FL_POR << 7); return retval; } uint8_t FL_POR :1; /* * POR flag Indicates a power-on reset (POR) event has occurred. 0 : Register has been cleared and no POR event has occurred. 1 : POR event occurred and has not been cleared. Flag must be cleared by user register write (default) */ uint8_t nRDY :1; /* * Device ready flag Indicates the device has started up and is ready for communication. 0 : ADC ready for communication (default) 1 : ADC not ready */ uint8_t FL_P_RAILP :1; /* * Positive PGA output at positive rail flag(1) Indicates the positive PGA output is within 150 mV of AVDD. 0 : No error (default) 1 : PGA positive output within 150 mV of AVDD */ uint8_t FL_P_RAILN :1; /* * Positive PGA output at negative rail flag(1) Indicates the positive PGA output is within 150 mV of AVSS. 0 : No error (default) 1 : PGA positive output within 150 mV of AVSS */ uint8_t FL_N_RAILP :1; /* * Negative PGA output at positive rail flag(1) Indicates the negative PGA output is within 150 mV of AVDD. 0 : No error (default) 1 : PGA negative output within 150 mV of AVDD */ uint8_t FL_N_RAILN :1; /* * Negative PGA output at negative rail flag(1) Indicates the negative PGA output is within 150 mV of AVSS. 0 : No error (default) 1 : PGA negative output within 150 mV of AVSS */ uint8_t FL_REF_L1 :1; /* * Reference voltage monitor flag, level 1 Indicates the external reference voltage is lower than 1/3 of the analog supply voltage. Can be used to detect an open-excitation lead in a 3-wire RTD application. 0 : Differential reference voltage ≥ 1/3 · (AVDD – AVSS) (default) 1 : Differential reference voltage < 1/3 · (AVDD – AVSS) */ uint8_t FL_REF_L0 :1; /* * Reference voltage monitor flag, level 0 Indicates the external reference voltage is lower than 0.3 V. Can be used to indicate a missing or floating external reference voltage. 0 : Differential reference voltage ≥ 0.3 V (default) 1 : Differential reference voltage < 0.3 V */ } STATUS_Reg; typedef struct INPMUX_Reg { INPMUX_Reg(uint8_t raw) { MUXP = (raw >> 4) & 0x07; MUXN = (raw >> 0) & 0x07; } uint8_t get() { uint8_t retval = 0x00; retval |= (MUXN << 0); retval |= (MUXP << 4); return retval; } uint8_t MUXP :4; /* * Positive ADC input selection Selects the ADC positive input channel. 0000 : AIN0 (default) 0001 : AIN1 0010 : AIN2 0011 : AIN3 0100 : AIN4 0101 : AIN5 0110 : AIN6 (ADS124S08 only) 0111 : AIN7 (ADS124S08 only) 1000 : AIN8 (ADS124S08 only) 1001 : AIN9 (ADS124S08 only) 1010 : AIN10 (ADS124S08 only) 1011 : AIN11 (ADS124S08 only) 1100 : AINCOM 1101 : Reserved 1110 : Reserved 1111 : Reserved */ uint8_t MUXN :4; /* * Negative ADC input selection Selects the ADC negative input channel. 0000 : AIN0 0001 : AIN1 (default) 0010 : AIN2 0011 : AIN3 0100 : AIN4 0101 : AIN5 0110 : AIN6 (ADS124S08 only) 0111 : AIN7 (ADS124S08 only) 1000 : AIN8 (ADS124S08 only) 1001 : AIN9 (ADS124S08 only) 1010 : AIN10 (ADS124S08 only) 1011 : AIN11 (ADS124S08 only) 1100 : AINCOM 1101 : Reserved 1110 : Reserved 1111 : Reserved */ } INPMUX_Reg; typedef struct PGA_Reg { PGA_Reg(uint8_t raw) { DELAY = (raw >> 5) & 0x07; PGA_EN = (raw >> 3) & 0x03; GAIN = (raw >> 0) & 0x07; } uint8_t get() { uint8_t retval = 0x00; retval |= (GAIN << 0); retval |= (PGA_EN << 3); retval |= (DELAY << 5); return retval; } uint8_t DELAY :3; /* * Programmable conversion delay selection Sets the programmable conversion delay time for the first conversion after a WREG when a configuration change resets of the digital filter and triggers a new conversion(1) . 000 : 14 · tMOD (default) 001 : 25 · tMOD 010 : 64 · tMOD 011 : 256 · tMOD 100 : 1024 · tMOD 101 : 2048 · tMOD 110 : 4096 · tMOD 111 : 1 · tMOD */ uint8_t PGA_EN :2; /* * PGA enable Enables or bypasses the PGA. 00 : PGA is powered down and bypassed. Enables single-ended measurements with unipolar supply (Set gain = 1 (2)) (default) 01 : PGA enabled (gain = 1 to 128) 10 : Reserved 11 : Reserved */ uint8_t GAIN :3; /* * PGA gain selection Configures the PGA gain. 000 : 1 (default) 001 : 2 010 : 4 011 : 8 100 : 16 101 : 32 110 : 64 111 : 128 */ } PGA_Reg; typedef struct DATARATE_Reg { DATARATE_Reg(uint8_t raw) { G_CHOP = (raw >> 7) & 0x01; CLK = (raw >> 6) & 0x01; MODE = (raw >> 5) & 0x01; FILTER = (raw >> 4) & 0x01; DR = raw & 0x07; } uint8_t get() { uint8_t retval = 0x00; retval |= (DR << 0); retval |= (FILTER << 4); retval |= (MODE << 5); retval |= (CLK << 6); retval |= (G_CHOP << 7); return retval; } uint8_t G_CHOP :1; /* * Global chop enable Enables the global chop function. When enabled, the device automatically swaps the inputs and takes the average of two consecutive readings to cancel the offset voltage. 0 : Disabled (default) 1 : Enabled */ uint8_t CLK :1; /* * Clock source selection Configures the clock source to use either the internal oscillator or an external clock. 0 : Internal 4.096-MHz oscillator (default) 1 : External clock */ uint8_t MODE :1; /* * Conversion mode selection Configures the ADC for either continuous conversion or single-shot conversion mode. 0 : Continuous conversion mode (default) 1 : Single-shot conversion mode */ uint8_t FILTER :1; /* * Digital filter selection Configures the ADC to use either the sinc3 or the low-latency filter. 0 : Sinc3 filter 1 : Low-latency filter (default) */ uint8_t DR :4; /* * Data rate selection Configures the output data rate(1) . 0000 : 2.5 SPS 0001 : 5 SPS 0010 : 10 SPS 0011 : 16.6 SPS 0100 : 20 SPS (default) 0101 : 50SPS 0110 : 60 SPS 0111 : 100 SPS 1000 : 200 SPS 1001 : 400 SPS 1010 : 800 SPS 1011 : 1000 SPS 1100 : 2000 SPS 1101 : 4000 SPS 1110 : 4000 SPS 1111 : Reserved */ } DATARATE_Reg; typedef struct REF_Reg { REF_Reg(uint8_t raw) { FL_REF_EN = (raw >> 6) & 0x03; nREFP_BUF = (raw >> 5) & 0x01; nREFN_BUF = (raw >> 4) & 0x01; REFSEL = (raw >> 2) & 0x03; REFCON = (raw >> 0) & 0x03; } uint8_t get() { uint8_t retval = 0x00; retval |= (REFCON << 0); retval |= (REFSEL << 2); retval |= (nREFN_BUF << 4); retval |= (nREFP_BUF << 5); retval |= (FL_REF_EN << 6); return retval; } uint8_t FL_REF_EN :2; /* * Reference monitor configuration Enables and configures the reference monitor. 00 : Disabled (default) 01 : FL_REF_L0 monitor enabled, threshold 0.3 V 10 : FL_REF_L0 and FL_REF_L1 monitors enabled, thresholds 0.3 V and 1/3 · (AVDD – AVSS) 11 : FL_REF_L0 monitor and 10-MΩ pull-together enabled, threshold 0.3 V */ uint8_t nREFP_BUF :1; /* * Positive reference buffer bypass Disables the positive reference buffer. Recommended when V(REFPx) is close to AVDD. 0 : Enabled (default) 1 : Disabled */ uint8_t nREFN_BUF :1; /* * Negative reference buffer bypass Disables the negative reference buffer. Recommended when V(REFNx) is close to AVSS. 0 : Enabled 1 : Disabled (default) */ uint8_t REFSEL :2; /* * Reference input selection Selects the reference input source for the ADC. 00 : REFP0, REFN0 (default) 01 : REFP1, REFN1 10 : Internal 2.5-V reference(1) 11 : Reserved */ uint8_t REFCON :2; /* * Internal voltage reference configuration(2) Configures the behavior of the internal voltage reference. 00 : Internal reference off (default) 01 : Internal reference on, but powers down in power-down mode 10 : Internal reference is always on, even in power-down mode 11 : Reserved */ } REF_Reg; typedef struct IDACMAG_Reg { IDACMAG_Reg(uint8_t raw) { FL_RAIL_EN = (raw >> 7) & 0x01; PSW = (raw >> 6) & 0x01; RESERVED = (raw >> 4) & 0x03; IMAG = (raw >> 0) & 0x0F; } uint8_t get() { uint8_t retval = 0x00; retval |= (IMAG << 0); retval |= (RESERVED << 4); retval |= (PSW << 6); retval |= (FL_RAIL_EN << 7); return retval; } uint8_t FL_RAIL_EN :1; /* * PGA output rail flag enable Enables the PGA output voltage rail monitor circuit. 0 : Disabled (default) 1 : Enabled */ uint8_t PSW :1; /* * Low-side power switch Controls the low-side power switch. The low-side power switch opens automatically in power-down mode. 0 : Open (default) 1 : Closed */ uint8_t RESERVED :2; // Always write 0h uint8_t IMAG :4; /* * IDAC magnitude selection Selects the value of the excitation current sources. Sets IDAC1 and IDAC2 to the same value. 0000 : Off (default) 0001 : 10 µA 0010 : 50 µA 0011 : 100 µA 0100 : 250 µA 0101 : 500 µA 0110 : 750 µA 0111 : 1000 µA 1000 : 1500 µA 1001 : 2000 µA 1010 - 1111 : Off */ } IDACMAG_Reg; typedef struct IDACMUX_Reg { IDACMUX_Reg(uint8_t raw) { I2MUX = (raw >> 4) & 0x0F; I1MUX = (raw >> 0) & 0x0F; } uint8_t get() { uint8_t retval = 0x00; retval |= (I1MUX << 0); retval |= (I2MUX << 4); return retval; } uint8_t I2MUX :4; /** * IDAC2 output channel selection Selects the output channel for IDAC2. 0000 : AIN0 0001 : AIN1 0010 : AIN2 0011 : AIN3 0100 : AIN4 0101 : AIN5 0110 : AIN6 (ADS124S08), REFP1 (ADS124S06) 0111 : AIN7 (ADS124S08), REFN1 (ADS124S06) 1000 : AIN8 (ADS124S08 only) 1001 : AIN9 (ADS124S08 only) 1010 : AIN10 (ADS124S08 only) 1011 : AIN11 (ADS124S08 only) 1100 : AINCOM 1101 - 1111 : Disconnected (default) */ uint8_t I1MUX :4; /* * IDAC1 output channel selection Selects the output channel for IDAC1. 0000 : AIN0 0001 : AIN1 0010 : AIN2 0011 : AIN3 0100 : AIN4 0101 : AIN5 0110 : AIN6 (ADS124S08 only), REFP1 (ADS124S06) 0111 : AIN7 (ADS124S08 only), REFN1 (ADS124S06) 1000 : AIN8 (ADS124S08 only) 1001 : AIN9 (ADS124S08 only) 1010 : AIN10 (ADS124S08 only) 1011 : AIN11 (ADS124S08 only) 1100 : AINCOM 1101 - 1111 : Disconnected (default) */ } IDACMUX_Reg; typedef struct VBIAS_Reg { VBIAS_Reg(uint8_t raw) { VB_LEVEL = (raw >> 7) & 0x01; VB_AINC = (raw >> 6) & 0x01; VB_AIN5 = (raw >> 5) & 0x01; VB_AIN4 = (raw >> 4) & 0x01; VB_AIN3 = (raw >> 3) & 0x01; VB_AIN2 = (raw >> 2) & 0x01; VB_AIN1 = (raw >> 1) & 0x01; VB_AIN0 = (raw >> 0) & 0x01; } uint8_t get() { uint8_t retval = 0x00; retval |= (VB_AIN0 << 0); retval |= (VB_AIN1 << 1); retval |= (VB_AIN2 << 2); retval |= (VB_AIN3 << 3); retval |= (VB_AIN4 << 4); retval |= (VB_AIN5 << 5); retval |= (VB_AINC << 6); retval |= (VB_LEVEL << 7); return retval; } uint8_t VB_LEVEL :1; /* * VBIAS level selection Sets the VBIAS output voltage level. VBIAS is disabled when not connected to any input. 0 : (AVDD + AVSS) / 2 (default) 1 : (AVDD + AVSS) / 12 */ uint8_t VB_AINC :1; /** * AINCOM VBIAS selection(1) Enables VBIAS on the AINCOM pin. 0 : VBIAS disconnected from AINCOM (default) 1 : VBIAS connected to AINCOM */ uint8_t VB_AIN5 :1; /* * AIN5 VBIAS selection(1) Enables VBIAS on the AIN5 pin. 0 : VBIAS disconnected from AIN5 (default) 1 : VBIAS connected to AIN5 */ uint8_t VB_AIN4 :1; /* * AIN4 VBIAS selection(1) Enables VBIAS on the AIN4 pin. 0 : VBIAS disconnected from AIN4 (default) 1 : VBIAS connected to AIN4 */ uint8_t VB_AIN3 :1; /* * AIN3 VBIAS selection(1) Enables VBIAS on the AIN3 pin. 0 : VBIAS disconnected from AIN3 (default) 1 : VBIAS connected to AIN3 */ uint8_t VB_AIN2 :1; /* * AIN2 VBIAS selection(1) Enables VBIAS on the AIN2 pin. 0 : VBIAS disconnected from AIN2 (default) 1 : VBIAS connected to AIN2 */ uint8_t VB_AIN1 :1; /* * AIN1 VBIAS selection(1) Enables VBIAS on the AIN1 pin. 0 : VBIAS disconnected from AIN1 (default) 1 : VBIAS connected to AIN1 */ uint8_t VB_AIN0 :1; /* * AIN0 VBIAS selection(1) Enables VBIAS on the AIN0 pin. 0 : VBIAS disconnected from AIN0 (default) 1 : VBIAS connected to AIN5 */ } VBIAS_Reg; typedef struct FSCAL_Reg { union FSCAL { uint32_t gain; uint8_t raw[3]; }; } FSCAL_Reg; typedef struct GPIODAT_Reg { GPIODAT_Reg(uint8_t raw) { DIR = (raw >> 4) & 0x0F; DAT = (raw >> 0) & 0x0F; } uint8_t get() { uint8_t retval = 0x00; retval |= (DAT << 0); retval |= (DIR << 4); return retval; } uint8_t DIR :4; /* * GPIO direction Configures the selected GPIO as an input or output. 0 : GPIO[x] configured as output (default) 1 : GPIO[x] configured as input */ uint8_t DAT :4; /* * GPIO data Contains the data of the GPIO inputs or outputs. 0 : GPIO[x] is low (default) 1 : GPIO[x] is high */ } GPIODAT_Reg; typedef struct GPIOCON_Reg { GPIOCON_Reg(uint8_t raw) { RESERVED = (raw >> 4) & 0x0F; CON = (raw >> 0) & 0x0F; } uint8_t get() { uint8_t retval = 0x00; retval |= (CON << 0); retval |= (RESERVED << 4); return retval; } uint8_t RESERVED :4; // Always write 0h uint8_t CON :4; /* * GPIO pin configuration Configures the GPIO[x] pin as an analog input or GPIO. CON[x] corresponds to the GPIO[x] pin. 0 : GPIO[x] configured as analog input (default)(1) 1 : GPIO[x] configured as GPIO */ } GPIOCON_Reg; typedef struct OFCAL_Reg { union OFCAL { uint32_t offset; uint8_t raw[3]; }; } OFCAL_Reg; <file_sep>/* * ADCads124S0.cpp * * Author: reed */ #include "../device_specific/ADC/ads124S0.h" #include "cmsis_os.h" ADS124S0::ADS124S0(SPI_HandleTypeDef *spi, uint16_t ResetPin, GPIO_TypeDef *resetPort, uint16_t CSPin, GPIO_TypeDef *CSPort, uint16_t DRDYPin, GPIO_TypeDef *DRDYPort, uint16_t STARTPin, GPIO_TypeDef *STARTPort): spi(spi), ResetPin(ResetPin), resetPort(resetPort), CSPin(CSPin), CSPort(CSPort), DRDYPin(DRDYPin), DRDYPort(DRDYPort), STARTPin(STARTPin), STARTPort(STARTPort) { HAL_GPIO_WritePin(resetPort, ResetPin, GPIO_PIN_SET); // Make sure its not in reset HAL_GPIO_WritePin(STARTPort, STARTPin, GPIO_PIN_RESET); // Don't start sampling yet HAL_GPIO_WritePin(CSPort, CSPin, GPIO_PIN_SET); // Not talking to it yet } bool ADS124S0::init() { // Reset reset(); // check ID adc_ID = ID_Reg(readReg8(REGISTER::ADS124S0_ID)); if(adc_ID.DEV_ID != DEVICE_ID::ADS124S06 && adc_ID.DEV_ID != DEVICE_ID::ADS124S08) { // Not a recognized device return false; } // set REFSEL to 00 Ref0: Pg35 // configure REFP_BUF/REFN_BUF ????? disable : pg36 adc_reference = REF_Reg(readReg8(REGISTER::ADS124S0_REF)); adc_reference.REFSEL = 0b00; adc_reference.REFCON = 0b10; // internal reference needs to be on for current excitation writeReg8(REGISTER::ADS124S0_REF, adc_reference.get()); // set CLK bit to ?? to choose internal oscillator // set FILTER bit to Sinc^3 or low-latency?? : pg37 // sinc is slower, but less noise, need to find timing requirements // set DATARATE reg to ???? decide on slowest possible // set GCHOP // On is twice as slow, but again more accurate // set Mode bit to 1 in datarate reg for single shot : Pg60 adc_datarate = DATARATE_Reg(readReg8(REGISTER::ADS124S0_DATARATE)); adc_datarate.CLK = 0b0; // internal clock adc_datarate.MODE = 0b1; // single shot adc_datarate.G_CHOP = 0b1; // enable chopping adc_datarate.FILTER = 0b0; // sinc3 filter adc_datarate.DR = 0b0111; // 100SPS writeReg8(REGISTER::ADS124S0_DATARATE, adc_datarate.get()); /* Timing analysis * Number of channels to sample total : (4 thermopile + 1 thermister)*2 = 10 channels * Max time per channel: 100 ms * Internal oscillator: 4.096 Mhz, or T = 244ns, * * Modulator runs at 4.096/16= 256Khz * * Max cycles per channel: 409,600 * * GCHOP doubles number of samples * sinc^3 filter triples number of samples * 6 samples total per reading total * * * */ // turn off current sources, IMAG to 0000 : Pg50 adc_excite_current_mag = IDACMAG_Reg(readReg8(REGISTER::ADS124S0_IDACMAG)); adc_excite_current_mag.FL_RAIL_EN = 0b0;//disabled adc_excite_current_mag.PSW = 0b0;//open adc_excite_current_mag.RESERVED = 0b00; adc_excite_current_mag.IMAG = EXCITATION_CURRENT::OFF; // disabled writeReg8(REGISTER::ADS124S0_IDACMAG, adc_excite_current_mag.get()); // I1MUX set to 1111 for no connect : Pg50 // I2MUX set to 1111 for no connect : Pg50 adc_excite_current_mux = IDACMUX_Reg(readReg8(REGISTER::ADS124S0_IDACMUX)); adc_excite_current_mux.I1MUX = 0b1111; // disabled adc_excite_current_mux.I2MUX = 0b1111; // disabled writeReg8(REGISTER::ADS124S0_IDACMUX, adc_excite_current_mux.get()); // turn on/off voltage bias(VB_AINx) : Pg51 adc_bias = VBIAS_Reg(0x00); // disable vbias writeReg8(REGISTER::ADS124S0_VBIAS, adc_bias.get()); // turn on CRC & status adc_settings = SYS_Reg(readReg8(REGISTER::ADS124S0_SYS)); adc_settings.SENDSTAT = 0b1; // send status adc_settings._CRC = 0b1; // send CRC adc_settings.TIMEOUT = 0b1; // spi timeout monitor writeReg8(REGISTER::ADS124S0_SYS, adc_settings.get()); // set DELAY for signals to settle? timing analysis required : Pg61 adc_prog_gain = PGA_Reg(readReg8(REGISTER::ADS124S0_PGA)); adc_prog_gain.DELAY = 0b010; adc_prog_gain.PGA_EN = 0b00; adc_prog_gain.GAIN = 0b000; writeReg8(REGISTER::ADS124S0_PGA, adc_prog_gain.get()); // set GPIO to analog input (should be default but make sure) : Pg85 adc_gpio_con.RESERVED = 0x0000; adc_gpio_con.CON = 0b0000; // all analog inputs writeReg8(REGISTER::ADS124S0_GPIOCON, adc_gpio_con.get()); adc_status = STATUS_Reg(readReg8(REGISTER::ADS124S0_STATUS)); adc_status.FL_POR = 0; // reset POR flag writeReg8(REGISTER::ADS124S0_STATUS, adc_status.get()); // Wait for the ADC to be ready (should just be good to go) // If not ready in 15ms, bail and report error for(int idx = 0; idx < 3; idx++) { if(!adc_status.nRDY) { return true; } adc_status = STATUS_Reg(readReg8(REGISTER::ADS124S0_STATUS)); osDelay(5); } return false; } void ADS124S0::reset() { HAL_GPIO_WritePin(resetPort, ResetPin, GPIO_PIN_RESET); // Make sure its not in reset osDelay(10); HAL_GPIO_WritePin(resetPort, ResetPin, GPIO_PIN_SET); // Make sure its not in reset osDelay(10); } uint32_t ADS124S0::readChannel(uint8_t channel) { adc_input_mux.MUXN = 0b1100; // common adc_input_mux.MUXP = channel & 0xF; writeReg8(REGISTER::ADS124S0_INPMUX, adc_input_mux.get()); osDelay(1); //HAL_GPIO_WritePin(STARTPort, STARTPin, GPIO_PIN_SET); issueCommand(COMMAND::START); osDelay(2); while(HAL_GPIO_ReadPin(DRDYPort, DRDYPin) == GPIO_PIN_SET)osThreadYield(); // wait for pin to go low //HAL_GPIO_WritePin(STARTPort, STARTPin, GPIO_PIN_RESET); return readData(); } ADS124S0::~ADS124S0() { // TODO Auto-generated destructor stub } uint8_t ADS124S0::readReg8(REGISTER address) { txBuff[0] = 0b00100000; txBuff[0] |= (((uint8_t)address) & 0x1F); txBuff[1] = 0x00; // only write one register at a time HAL_GPIO_WritePin(CSPort, CSPin, GPIO_PIN_RESET); HAL_SPI_Transmit(spi, txBuff, 2, 100); HAL_SPI_Receive(spi, rxBuff, 1, 100); HAL_GPIO_WritePin(CSPort, CSPin, GPIO_PIN_SET); return rxBuff[0]; } void ADS124S0::setExcitationMagnitude(EXCITATION_CURRENT current) { IDACMAG_Reg mag(readReg8(ADS124S0_IDACMAG)); mag.IMAG = ((uint8_t) current) & 0xF; writeReg8(ADS124S0_IDACMAG, mag.get()); } void ADS124S0::stopExcitation() { setExcitationMagnitude(EXCITATION_CURRENT::OFF); routeExcitation1(0xF); // disabled routeExcitation2(0xF); // disabled } void ADS124S0::routeExcitation1(uint8_t channel) { IDACMUX_Reg imux(readReg8(ADS124S0_IDACMUX)); imux.I1MUX = (uint8_t) channel & 0xF; writeReg8(ADS124S0_IDACMUX, imux.get()); } void ADS124S0::routeExcitation2(uint8_t channel) { IDACMUX_Reg imux(readReg8(ADS124S0_IDACMUX)); imux.I2MUX = (uint8_t) channel & 0xF; writeReg8(ADS124S0_IDACMUX, imux.get()); } uint32_t ADS124S0::readData() { txBuff[0] = (uint8_t) COMMAND::RDATA; HAL_GPIO_WritePin(CSPort, CSPin, GPIO_PIN_RESET); HAL_SPI_Transmit(spi, txBuff, 1, 100); bool sendStat = false; // Need to determine how many bytes to expect if(adc_settings.SENDSTAT) { sendStat = true; HAL_SPI_Receive(spi, rxBuff, 1, 100); // Read the status of the ADC } HAL_SPI_Receive(spi, rxBuff+1, 3, 100); // Read the adc sample bool okay = true; if(adc_settings._CRC) { HAL_SPI_Receive(spi, rxBuff+4, 1, 100); // Read the CRC of the transaction if(!checkCRC(rxBuff, 4, rxBuff[4])) { // data is bad okay = false; } } HAL_GPIO_WritePin(CSPort, CSPin, GPIO_PIN_SET); if(okay) { if(sendStat) { adc_status = STATUS_Reg(rxBuff[0]); } return rxBuff[1] << 16 | rxBuff[2] << 8 | rxBuff[3] << 0; } else { return 0xFFFFFFFF; // not a valid reading from a 24-bit adc, treat as an error; } } bool ADS124S0::checkCRC(uint8_t * data, uint8_t length, uint8_t checksum) { uint16_t i; uint16_t crc = 0x0; for(int idx = 0; idx < length; idx++) { i = (crc ^ data[idx]) & 0xFF; crc = (crc8x_table[i] ^ (crc << 8)) & 0xFF; } crc = crc & 0xFF; return checksum == crc; } void ADS124S0::writeReg8(REGISTER address, uint8_t data) { // Write nnnnn registers starting at address rrrrr // r rrrr = starting register address. // n nnnn = number of registers to read or write – 1. // 010r rrrr, 000n nnnn txBuff[0] = 0b01000000; txBuff[0] |= (((uint8_t)address) & 0x1F); txBuff[1] = 0x00; // only write one register at a time txBuff[2] = data; HAL_GPIO_WritePin(CSPort, CSPin, GPIO_PIN_RESET); HAL_SPI_Transmit(spi, txBuff, 3, 100); HAL_GPIO_WritePin(CSPort, CSPin, GPIO_PIN_SET); } void ADS124S0::issueCommand(COMMAND cmd) { switch(cmd) { case RREG: case WREG: case RDATA: // These should not be used with this method as they require // more steps than just sending the command Error_Handler(); break; default: break; } txBuff[0] = (uint8_t) cmd; HAL_GPIO_WritePin(CSPort, CSPin, GPIO_PIN_RESET); HAL_SPI_Transmit(spi, txBuff, 1, 100); HAL_GPIO_WritePin(CSPort, CSPin, GPIO_PIN_SET); } const uint8_t ADS124S0::crc8x_table[256] = { 0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15, 0x38, 0x3f, 0x36, 0x31, 0x24, 0x23, 0x2a, 0x2d, 0x70, 0x77, 0x7e, 0x79, 0x6c, 0x6b, 0x62, 0x65, 0x48, 0x4f, 0x46, 0x41, 0x54, 0x53, 0x5a, 0x5d, 0xe0, 0xe7, 0xee, 0xe9, 0xfc, 0xfb, 0xf2, 0xf5, 0xd8, 0xdf, 0xd6, 0xd1, 0xc4, 0xc3, 0xca, 0xcd, 0x90, 0x97, 0x9e, 0x99, 0x8c, 0x8b, 0x82, 0x85, 0xa8, 0xaf, 0xa6, 0xa1, 0xb4, 0xb3, 0xba, 0xbd, 0xc7, 0xc0, 0xc9, 0xce, 0xdb, 0xdc, 0xd5, 0xd2, 0xff, 0xf8, 0xf1, 0xf6, 0xe3, 0xe4, 0xed, 0xea, 0xb7, 0xb0, 0xb9, 0xbe, 0xab, 0xac, 0xa5, 0xa2, 0x8f, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9d, 0x9a, 0x27, 0x20, 0x29, 0x2e, 0x3b, 0x3c, 0x35, 0x32, 0x1f, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0d, 0x0a, 0x57, 0x50, 0x59, 0x5e, 0x4b, 0x4c, 0x45, 0x42, 0x6f, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7d, 0x7a, 0x89, 0x8e, 0x87, 0x80, 0x95, 0x92, 0x9b, 0x9c, 0xb1, 0xb6, 0xbf, 0xb8, 0xad, 0xaa, 0xa3, 0xa4, 0xf9, 0xfe, 0xf7, 0xf0, 0xe5, 0xe2, 0xeb, 0xec, 0xc1, 0xc6, 0xcf, 0xc8, 0xdd, 0xda, 0xd3, 0xd4, 0x69, 0x6e, 0x67, 0x60, 0x75, 0x72, 0x7b, 0x7c, 0x51, 0x56, 0x5f, 0x58, 0x4d, 0x4a, 0x43, 0x44, 0x19, 0x1e, 0x17, 0x10, 0x05, 0x02, 0x0b, 0x0c, 0x21, 0x26, 0x2f, 0x28, 0x3d, 0x3a, 0x33, 0x34, 0x4e, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5c, 0x5b, 0x76, 0x71, 0x78, 0x7f, 0x6a, 0x6d, 0x64, 0x63, 0x3e, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2c, 0x2b, 0x06, 0x01, 0x08, 0x0f, 0x1a, 0x1d, 0x14, 0x13, 0xae, 0xa9, 0xa0, 0xa7, 0xb2, 0xb5, 0xbc, 0xbb, 0x96, 0x91, 0x98, 0x9f, 0x8a, 0x8d, 0x84, 0x83, 0xde, 0xd9, 0xd0, 0xd7, 0xc2, 0xc5, 0xcc, 0xcb, 0xe6, 0xe1, 0xe8, 0xef, 0xfa, 0xfd, 0xf4, 0xf3 }; <file_sep>/* * CANOpenTask.cpp * * Created on: Oct 1, 2021 * Author: reedt */ #include "CANopenNode/CANopen.h" #include "CANopenNode/301/CO_ODinterface.h" #include "CANopenNode/305/CO_LSSslave.h" #include "bsp/DS28CM00ID/DS28CM00ID.h" #include "bsp/LEDs/LEDManager.h" #include "can.h" #include "tim.h" #include "CANOpenNode/OD.h" #include "Logging/Logger.h" #include "cmsis_os.h" #include <map> #include <set> #include <functional> #define NMT_CONTROL \ CO_NMT_ERR_ON_ERR_REG \ | CO_ERR_REG_GENERIC_ERR \ | CO_ERR_REG_COMMUNICATION #define FIRST_HB_TIME 500 #define SDO_SRV_TIMEOUT_TIME 1000 #define SDO_CLI_TIMEOUT_TIME 500 #define SDO_CLI_BLOCK false #define OD_STATUS_BITS NULL #define COMMSPC 1 #define SENSORSPC 2 #define BMEPC 3 CO_t *canOpenHandle; extern LEDManager leds; extern DS28CM00_ID id1; static uint8_t pendingID = CO_LSS_NODE_ID_ASSIGNMENT; static uint16_t pendingRate = 1000; void canopen_start(void) { CO_ReturnError_t err; auto co = CO_new( /*config*/nullptr, /*heap used*/nullptr); err = CO_CANinit(co, (void*) &hcan1, 1000); uint64_t serNum = id1.getID(); auto entry = OD_ENTRY_H1018_identity; OD_set_u32(entry, 4, serNum, true); // Set device serial number // @formatter:off CO_LSS_address_t lssAddress = { .identity = { .vendorID = OD_PERSIST_COMM.x1018_identity.vendor_ID, .productCode = OD_PERSIST_COMM.x1018_identity.productCode, .revisionNumber = OD_PERSIST_COMM.x1018_identity.revisionNumber, .serialNumber = OD_PERSIST_COMM.x1018_identity.serialNumber } }; // @formatter:on err = CO_LSSinit(co, &lssAddress, &pendingID, &pendingRate); uint32_t errInf = 0; // @formatter:off err = CO_CANopenInit(co, nullptr, /* alternate NMT */ nullptr, /* alternate em */ OD, /* Object dictionary */ OD_STATUS_BITS, /* Optional OD_statusBits */ (CO_NMT_control_t)(NMT_CONTROL), FIRST_HB_TIME, /* ??? firstHBTime_ms */ SDO_SRV_TIMEOUT_TIME, /*??? SDOserverTimeoutTime_ms */ SDO_CLI_TIMEOUT_TIME, /*??? SDOclientTimeoutTime_ms */ SDO_CLI_BLOCK, /*??? SDOclientBlockTransfer */ pendingID, /*??? CO_activeNodeId */ &errInf /*errInfo*/); // @formatter:on err = CO_CANopenInitPDO(co, co->em, OD, pendingID, &errInf); // Delay until after Node-ID assignment CO_CANsetNormalMode(co->CANmodule); canOpenHandle = co; HAL_TIM_Base_Start_IT(&htim15); HAL_TIM_Base_Start_IT(&htim16); __HAL_TIM_SET_COUNTER(&htim16, 0); } void canopen_oneMs(void) { uint32_t us = __HAL_TIM_GET_COUNTER(&htim16); auto reset = CO_RESET_NOT; uint32_t next = 0; reset = CO_process(canOpenHandle, false, us, &next); switch (reset) { /** 0, Normal return, no action */ case CO_RESET_NOT: break; /** 1, Application must provide communication reset. */ case CO_RESET_COMM: HAL_TIM_Base_Stop_IT(&htim15); CO_CANsetConfigurationMode((void*) &hcan1); CO_delete(canOpenHandle); canopen_start(); return; /** 2, Application must provide complete device reset */ case CO_RESET_APP: HAL_NVIC_SystemReset(); // DOES NOT RETURN break; /** 3, Application must quit, no reset of microcontroller (command is not * requested by the stack.) */ case CO_RESET_QUIT: CO_CANsetConfigurationMode((void*) &hcan1); CO_delete(canOpenHandle); HAL_TIM_Base_Stop_IT(&htim15); return; default: Error_Handler(); } bool syncWas = false; #if (CO_CONFIG_SYNC) & CO_CONFIG_SYNC_ENABLE syncWas = CO_process_SYNC(canOpenHandle, us, NULL); #endif #if (CO_CONFIG_PDO) & CO_CONFIG_RPDO_ENABLE CO_process_RPDO(canOpenHandle, syncWas, us, NULL); #endif #if (CO_CONFIG_PDO) & CO_CONFIG_TPDO_ENABLE CO_process_TPDO(canOpenHandle, syncWas, us, NULL); #endif auto LED_red = CO_LED_RED(canOpenHandle->LEDs, CO_LED_CANopen); auto LED_green = CO_LED_GREEN(canOpenHandle->LEDs, CO_LED_CANopen); if (LED_red != 0) { leds.turnOn(color::RED); } else { leds.turnOff(color::RED); } if (LED_green != 0) { leds.turnOn(color::GREEN); } else { leds.turnOff(color::GREEN); } __HAL_TIM_SET_COUNTER(&htim16, 0); } <file_sep>/* * ADCads124S0.h * * Author: reed */ #ifndef INC_ADS124S0_H_ #define INC_ADS124S0_H_ #include <cstdint> #include "main.h" class ADS124S0 { public: #include "../device_specific/ADC/ads123S0_enums.h" // Contains enums for this class #include "../device_specific/ADC/ads123S0_structs.h" // Contains structs for this class public: ADS124S0(SPI_HandleTypeDef *spi, uint16_t ResetPin, GPIO_TypeDef *resetPort, uint16_t CSPin, GPIO_TypeDef *CSPort, uint16_t DRDYPin, GPIO_TypeDef *DRDYPort, uint16_t STARTPin, GPIO_TypeDef *STARTPort); bool init(); void reset(); uint32_t readChannel(uint8_t channel); virtual ~ADS124S0(); ADS124S0(const ADS124S0 &other) = default; ADS124S0(ADS124S0 &&other) = default; ADS124S0& operator=(const ADS124S0 &other) = default; ADS124S0& operator=(ADS124S0 &&other) = default; void setExcitationMagnitude(EXCITATION_CURRENT current); void stopExcitation(); void routeExcitation1(uint8_t channel); void routeExcitation2(uint8_t channel); bool checkCRC(uint8_t *data, uint8_t length, uint8_t checksum); uint8_t readReg8(REGISTER address); uint32_t readData(); void writeReg8(REGISTER address, uint8_t data); void issueCommand(COMMAND cmd); private: SPI_HandleTypeDef *spi; uint16_t ResetPin; GPIO_TypeDef *resetPort; uint16_t CSPin; GPIO_TypeDef *CSPort; uint16_t DRDYPin; GPIO_TypeDef *DRDYPort; uint16_t STARTPin; GPIO_TypeDef *STARTPort; uint8_t txBuff[8]; uint8_t rxBuff[8]; SYS_Reg adc_settings = 0x10; // default from reset: PG72 ID_Reg adc_ID = 0xFF; // this is an invalid value, can use to see if it has been read yet STATUS_Reg adc_status = 0x80; // default value: PG72 INPMUX_Reg adc_input_mux = 0x01; // default PG:72 PGA_Reg adc_prog_gain = 0x00; // default PG:72 DATARATE_Reg adc_datarate = 0x14; // default PG:72 REF_Reg adc_reference = 0x10; // default PG:72 IDACMAG_Reg adc_excite_current_mag = 0x00; // default PG:72 IDACMUX_Reg adc_excite_current_mux = 0xFF; // default PG:72 VBIAS_Reg adc_bias = 0x00; // default PG:72 GPIOCON_Reg adc_gpio_con = 0x00; static const uint8_t crc8x_table[256]; }; #endif /* INC_ADS124S0_H_ */ <file_sep> enum EXCITATION_CURRENT : uint8_t { OFF = 0b0000, _10uA = 0b0001, _50uA = 0b0010, _100uA = 0b0011, _250uA = 0b0100, _500uA = 0b0101, _750uA = 0b0110, _1000uA = 0b0111, _1500uA = 0b1000, _2000uA = 0b1001 }; enum REGISTER : uint8_t { ADS124S0_ID = 0x00, ADS124S0_STATUS = 0x01, ADS124S0_INPMUX = 0x02, ADS124S0_PGA = 0x03, ADS124S0_DATARATE = 0x04, ADS124S0_REF = 0x05, ADS124S0_IDACMAG = 0x06, ADS124S0_IDACMUX = 0x07, ADS124S0_VBIAS = 0x08, ADS124S0_SYS = 0x09, ADS124S0_OFCAL0 = 0x0A, ADS124S0_OFCAL1 = 0x0B, ADS124S0_OFCAL2 = 0x0C, ADS124S0_FSCAL0 = 0x0D, ADS124S0_FSCAL1 = 0x0E, ADS124S0_FSCAL2 = 0x0F, ADS124S0_GPIODAT = 0x10, ADS124S0_GPIOCON = 0x11 }; enum COMMAND : uint8_t { // Control Commands NOP = 0x00, WAKEUP = 0x02, POWERDOWN = 0x04, _RESET = 0x06, START = 0x08, STOP = 0x0A, // Calibration Commands SYOCAL = 0x16, SYGCAL = 0x17, SFOCAL = 0x19, // Data Read Commands (cant be used with issue command) RDATA = 0x12, // Read/write Reg Masks (cant be used with issue command) RREG, WREG }; enum DEVICE_ID : uint8_t { ADS124S08 = 0x00, ADS124S06 = 0x01, }; <file_sep>/* USER CODE BEGIN Header */ /** ****************************************************************************** * @file : main.c * @brief : Main program body ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2021 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ /* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "cmsis_os.h" #include "can.h" #include "crc.h" #include "dma.h" #include "fatfs.h" #include "i2c.h" #include "rng.h" #include "sdmmc.h" #include "spi.h" #include "tim.h" #include "usart.h" #include "gpio.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include "bsp/DS28CM00ID/DS28CM00ID.h" #include "bsp/LEDs/LEDManager.h" #include "Logging/UARTLogHandler.h" #include "bsp/UART/UARTManager.h" /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN PTD */ /* USER CODE END PTD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ DS28CM00_ID id1(&hi2c1); LEDManager leds( { .port = GPIOD, .pin = LED_R_Pin }, { .port = GPIOD, .pin = LED_G_Pin }, { .port = GPIOD, .pin = LED_B_Pin }); UARTManager uartMan(&huart1); UARTLogHandler *handler(UARTLogHandler::configure(&uartMan, LOG_LEVEL_ALL)); Logger Log("app"); /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); void MX_FREERTOS_Init(void); /* USER CODE BEGIN PFP */ /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------*/ /* USER CODE BEGIN 0 */ void* operator new(std::size_t sz) { return pvPortMalloc(sz); } void operator delete(void* ptr) noexcept { vPortFree(ptr); } /* USER CODE END 0 */ /** * @brief The application entry point. * @retval int */ int main(void) { /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /* MCU Configuration--------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* USER CODE BEGIN Init */ /* USER CODE END Init */ /* Configure the system clock */ SystemClock_Config(); /* USER CODE BEGIN SysInit */ /* USER CODE END SysInit */ /* Initialize all configured peripherals */ MX_GPIO_Init(); MX_DMA_Init(); MX_CAN1_Init(); MX_I2C1_Init(); MX_SDMMC1_SD_Init(); MX_SPI1_Init(); MX_USART1_UART_Init(); MX_USART2_UART_Init(); MX_TIM2_Init(); MX_CRC_Init(); MX_RNG_Init(); MX_FATFS_Init(); MX_TIM15_Init(); MX_TIM16_Init(); /* USER CODE BEGIN 2 */ HAL_GPIO_WritePin(CAN_MODE_GPIO_Port, CAN_MODE_Pin, GPIO_PIN_RESET); /* USER CODE END 2 */ /* Init scheduler */ osKernelInitialize(); /* Call init function for freertos objects (in freertos.c) */ MX_FREERTOS_Init(); /* Start scheduler */ osKernelStart(); /* We should never get here as control is now taken by the scheduler */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ } /* USER CODE END 3 */ } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = { 0 }; RCC_ClkInitTypeDef RCC_ClkInitStruct = { 0 }; RCC_PeriphCLKInitTypeDef PeriphClkInit = { 0 }; /** Configure the main internal regulator output voltage */ if (HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1) != HAL_OK) { Error_Handler(); } /** Initializes the RCC Oscillators according to the specified parameters * in the RCC_OscInitTypeDef structure. */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI; RCC_OscInitStruct.MSIState = RCC_MSI_ON; RCC_OscInitStruct.MSICalibrationValue = 0; RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_6; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_MSI; RCC_OscInitStruct.PLL.PLLM = 1; RCC_OscInitStruct.PLL.PLLN = 40; RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV4; RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2; RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { Error_Handler(); } /** Initializes the CPU, AHB and APB buses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_3) != HAL_OK) { Error_Handler(); } PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_USART2 | RCC_PERIPHCLK_I2C1 | RCC_PERIPHCLK_SDMMC1 | RCC_PERIPHCLK_RNG; PeriphClkInit.Usart1ClockSelection = RCC_USART1CLKSOURCE_PCLK2; PeriphClkInit.Usart2ClockSelection = RCC_USART2CLKSOURCE_PCLK1; PeriphClkInit.I2c1ClockSelection = RCC_I2C1CLKSOURCE_PCLK1; PeriphClkInit.RngClockSelection = RCC_RNGCLKSOURCE_PLLSAI1; PeriphClkInit.Sdmmc1ClockSelection = RCC_SDMMC1CLKSOURCE_PLLP; PeriphClkInit.PLLSAI1.PLLSAI1Source = RCC_PLLSOURCE_MSI; PeriphClkInit.PLLSAI1.PLLSAI1M = 1; PeriphClkInit.PLLSAI1.PLLSAI1N = 16; PeriphClkInit.PLLSAI1.PLLSAI1P = RCC_PLLP_DIV2; PeriphClkInit.PLLSAI1.PLLSAI1Q = RCC_PLLQ_DIV2; PeriphClkInit.PLLSAI1.PLLSAI1R = RCC_PLLR_DIV2; PeriphClkInit.PLLSAI1.PLLSAI1ClockOut = RCC_PLLSAI1_48M2CLK; if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK) { Error_Handler(); } } /* USER CODE BEGIN 4 */ extern void canopen_oneMs(void); /* USER CODE END 4 */ /** * @brief Period elapsed callback in non blocking mode * @note This function is called when TIM1 interrupt took place, inside * HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment * a global variable "uwTick" used as application time base. * @param htim : TIM handle * @retval None */ void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { /* USER CODE BEGIN Callback 0 */ if (htim->Instance == TIM15) { canopen_oneMs(); } /* USER CODE END Callback 0 */ if (htim->Instance == TIM17) { HAL_IncTick(); } /* USER CODE BEGIN Callback 1 */ /* USER CODE END Callback 1 */ } /** * @brief This function is executed in case of error occurrence. * @retval None */ void Error_Handler(void) { /* USER CODE BEGIN Error_Handler_Debug */ /* User can add his own implementation to report the HAL error return state */ __disable_irq(); while (1) { } /* USER CODE END Error_Handler_Debug */ } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t *file, uint32_t line) { /* USER CODE BEGIN 6 */ /* User can add his own implementation to report the file name and line number, ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* USER CODE END 6 */ } #endif /* USE_FULL_ASSERT */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ <file_sep>/* USER CODE BEGIN Header */ /** ****************************************************************************** * File Name : freertos.c * Description : Code for freertos applications ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2021 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ /* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "FreeRTOS.h" #include "task.h" #include "main.h" #include "cmsis_os.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include "can.h" #include "i2c.h" #include "spi.h" #include "tim.h" #include "usart.h" #include "gpio.h" #include <string.h> #include <cstdint> #include <stdio.h> #include <cmath> #include <algorithm> #include "device_specific/ADC/ads123S0_enums.h" #include "device_specific/ADC/ads124S0.h" #include "bsp/DS28CM00ID/DS28CM00ID.h" #include "bsp/LEDs/LEDManager.h" #include "bsp/UART/UARTManager.h" #include "Logging/Logger.h" #include "CANOpenNode/OD.h" #include "301/CO_ODinterface.h" #include "sdmmc.h" #include "fatfs.h" /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN PTD */ /* USER CODE END PTD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN Variables */ extern DS28CM00_ID id1; extern LEDManager leds; extern UARTManager uartMan; extern Logger Log; /* Definitions for SysMonitor */ osThreadId_t SysMonitorHandle; osThreadAttr_t SysMonitor_attributes = { .name = "SysMonitor", }; /* Definitions for SerialID_lock */ osMutexId_t SerialID_lockHandle; const osMutexAttr_t SerialID_lock_attributes = { .name = "SerialID_lock" }; /* USER CODE END Variables */ /* Definitions for defaultTask */ /* Private function prototypes -----------------------------------------------*/ /* USER CODE BEGIN FunctionPrototypes */ void startMonitoring(void *argument); extern void canopen_start(void); void measurementTask(void*); /* USER CODE END FunctionPrototypes */ void MX_FREERTOS_Init(void); /* (MISRA C 2004 rule 8.1) */ /* Hook prototypes */ void vApplicationStackOverflowHook(xTaskHandle xTask, signed char *pcTaskName); void vApplicationMallocFailedHook(void); /* USER CODE BEGIN 4 */ void vApplicationStackOverflowHook(xTaskHandle xTask, signed char *pcTaskName) { /* Run time stack overflow checking is performed if configCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2. This hook function is called if a stack overflow is detected. */ } /* USER CODE END 4 */ /* USER CODE BEGIN 5 */ void vApplicationMallocFailedHook(void) { /* vApplicationMallocFailedHook() will only be called if configUSE_MALLOC_FAILED_HOOK is set to 1 in FreeRTOSConfig.h. It is a hook function that will get called if a call to pvPortMalloc() fails. pvPortMalloc() is called internally by the kernel whenever a task, queue, timer or semaphore is created. It is also called by various parts of the demo application. If heap_1.c or heap_2.c are used, then the size of the heap available to pvPortMalloc() is defined by configTOTAL_HEAP_SIZE in FreeRTOSConfig.h, and the xPortGetFreeHeapSize() API function can be used to query the size of free heap space that remains (although it does not provide information on how the remaining heap might be fragmented). */ } /* USER CODE END 5 */ /** * @brief FreeRTOS initialization * @param None * @retval None */ void MX_FREERTOS_Init(void) { /* USER CODE BEGIN Init */ SysMonitor_attributes.priority = (osPriority_t) osPriorityLow; SysMonitor_attributes.stack_size = 2048 * 4; /* USER CODE END Init */ /* USER CODE BEGIN RTOS_MUTEX */ /* add mutexes, ... */ SerialID_lockHandle = osMutexNew(&SerialID_lock_attributes); /* USER CODE END RTOS_MUTEX */ /* USER CODE BEGIN RTOS_SEMAPHORES */ /* add semaphores, ... */ /* USER CODE END RTOS_SEMAPHORES */ /* USER CODE BEGIN RTOS_TIMERS */ /* start timers, add new ones, ... */ /* USER CODE END RTOS_TIMERS */ /* USER CODE BEGIN RTOS_QUEUES */ /* add queues, ... */ /* USER CODE END RTOS_QUEUES */ /* Create the thread(s) */ /* creation of defaultTask */ /* USER CODE BEGIN RTOS_THREADS */ /* add threads, ... */ /* creation of SysMonitor */ // SysMonitorHandle = osThreadNew(startMonitoring, (void*) nullptr, // &SysMonitor_attributes); osThreadAttr_t Task_attributes{0}; Task_attributes.stack_size = 8096 * 4; Task_attributes.name = "measurementTask"; Task_attributes.priority = (osPriority_t) osPriorityNormal; osThreadNew(measurementTask, nullptr, &Task_attributes); /* USER CODE END RTOS_THREADS */ /* USER CODE BEGIN RTOS_EVENTS */ /* add events, ... */ uartMan.start(); leds.start(false); Log.info("Application Started"); canopen_start(); /* USER CODE END RTOS_EVENTS */ } /* Private application code --------------------------------------------------*/ /* USER CODE BEGIN Application */ double toVoltage(int32_t val) { return (val / 8388608.0) * 3.3; // divide by 2^23 and multiply by vref } double toTemp(double resistance) { double ln = log(resistance); double result = 0.000949801222; double inter = 0.000216475249 * ln; result = result + inter; inter = pow(ln, 2); inter = inter * 0.000000483296004; result = result + inter; inter = pow(ln, 3); inter = inter * 0.000000110644773; result = result + inter; result = pow(result, -1.0); result = result - 273.15; return result; } void measurementTask(void*) { Logger ilog("MeasureTask"); ilog.info("Starting measurements"); ADS124S0 adc(&hspi1, ADC_RST_Pin, ADC_RST_GPIO_Port, ADC_CS_Pin, ADC_CS_GPIO_Port, ADC_DRDY_Pin, ADC_DRDY_GPIO_Port, ADC_Start_Pin, ADC_Start_GPIO_Port); if (!adc.init()) { ilog.error("Could not initialize ADC"); for (;;) osDelay(1000); } adc.setExcitationMagnitude(ADS124S0::EXCITATION_CURRENT::_10uA); adc.routeExcitation1(10); // route the excitation current to the thermistor adc.routeExcitation2(11); double internals[2]; double externals[8]; auto thermEntry1 = OD_ENTRY_H6000_thermopile1; auto thermEntry2 = OD_ENTRY_H6001_thermopile2; // SD INIT START MX_FATFS_Init(); const char *path = "/"; const char *name = "sensor_log.csv"; FATFS fs; // file system FIL fil; // File FRESULT fresult; // result UINT bw; // File read/write count bool fsOK = false; char buffer[512]; int size; std::string fsbuffer; // Mount fresult = f_mount(&fs, path, 1); // mount partition if(fresult != FR_OK) goto endfs_init; // CSV log setup fresult = f_open(&fil, name, FA_OPEN_APPEND | FA_WRITE | FA_OPEN_ALWAYS | FA_READ); // Open (or create) file if(fresult != FR_OK) goto endfs_init; fresult = f_lseek(&fil, 0); // Go to beginning of file if(fresult != FR_OK) goto endfs_init; size = sprintf(buffer, "Time(ms),T1CA(v),T1CB(v),T1CC(v),T1CD(v),T1Therm(c),T2CA(v),T2CB(v),T2CC(v),T2CD(v),T2Therm(c)\n"); fresult = f_write(&fil, buffer, size, &bw); // Write CSV header if(fresult != FR_OK) goto endfs_init; fresult = f_lseek(&fil, f_size(&fil)); // Go to end of file for appending if(fresult != FR_OK) goto endfs_init; fsOK = true; fsbuffer.reserve(121 * 60 * 30); // save for 30 minutes endfs_init: // SD INIT END fsbuffer.clear(); for (;;) { internals[0] = toTemp((toVoltage(adc.readChannel(10)) - 1.25) / 0.00001); // get voltage then divide by excitation current to get resistance OD_set_f32(thermEntry1, 5, internals[0], true); internals[1] = toTemp((toVoltage(adc.readChannel(11)) - 1.25) / 0.00001); // get voltage then divide by excitation current to get resistance OD_set_f32(thermEntry2, 5, internals[1], true); for (int idx = 0; idx < 8; idx++) { externals[idx] = toVoltage(adc.readChannel(idx)); if(idx < 4) { OD_set_f32(thermEntry1, idx+1, externals[idx], true); } else { OD_set_f32(thermEntry2, idx-3, externals[idx], true); } osDelay(1); } if(fsOK) { // Filesystem should be active.... size = sprintf(buffer, "%ld," "%8.8f,%8.8f," "%8.8f,%8.8f,%8.8f,%8.8f," "%8.8f,%8.8f,%8.8f,%8.8f\n", HAL_GetTick(), externals[0], externals[1], externals[2], externals[3], internals[0], externals[4], externals[5], externals[6], externals[7], internals[1]); fsbuffer.append(buffer); if( (fsbuffer.capacity() - fsbuffer.size()) <= 121 ) { // No more space, flush to SD for(size_t idx = 0; idx < fsbuffer.size();) { auto sizeToWrite = std::min((uint32_t)512, (uint32_t)(fsbuffer.size() - idx)); fresult = f_write(&fil, fsbuffer.data() + idx, sizeToWrite, &bw); idx += sizeToWrite; } fresult = f_sync(&fil); fsbuffer.clear(); } } ilog.info( "Thermopile1- cA=%8.4fV, cB=%8.4fV, cC=%8.4fV, cD=%8.4fV, therm=%8.4f *C", externals[0], externals[1], externals[2], externals[3], internals[0]); ilog.info( "Thermopile2- cA=%8.4fV, cB=%8.4fV, cC=%8.4fV, cD=%8.4fV, therm=%8.4f *C", externals[4], externals[5], externals[6], externals[7], internals[1]); ilog.info( "=========================================================================================================================================="); osDelay(500); } } /* USER CODE BEGIN Header_startMonitoring */ /** * @brief Function implementing the SysMonitor thread. * @param argument: Not used * @retval None */ /* USER CODE END Header_startMonitoring */ void startMonitoring(void *argument) { /* USER CODE BEGIN startMonitoring */ Logger privLog("SystemMonitor"); auto retval = osMutexAcquire(SerialID_lockHandle, 1000); if (retval == osOK) { auto family = id1.getFamily(); auto id = id1.getID(); auto dev_mode = id1.getMode(); privLog.info("Family=%hhx, id=%llx, mode=%hhx", family, id, dev_mode); osMutexRelease(SerialID_lockHandle); } else { auto holder = osMutexGetOwner(SerialID_lockHandle); privLog.error("Could not acquire mutex on DS28CM00_ID, held by: %s", osThreadGetName(holder)); } // leds.slowFlash(WHITE); for (;;) { // osDelay(1000); // leds.fastFlash(RED); // privLog.debug("RED fast"); osDelay(1000); // leds.slowFlash(GREEN); // privLog.debug("GREEN slow"); // osDelay(1000); // leds.turnOn(BLUE); // privLog.debug("BLUE on"); // osDelay(1000); // leds.turnOff(WHITE); // privLog.debug("LEDs all off"); size_t freeHeap = xPortGetFreeHeapSize(); if (freeHeap < 2000) { privLog.error("LOW HEAP, %u bytes remaining", freeHeap); } } /* USER CODE END startMonitoring */ } /* USER CODE END Application */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ <file_sep>/* USER CODE BEGIN Header */ /** ****************************************************************************** * @file : main.h * @brief : Header for main.c file. * This file contains the common defines of the application. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2021 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ /* USER CODE END Header */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __MAIN_H #define __MAIN_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l4xx_hal.h" #include "stm32l4xx_hal.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ /* USER CODE END Includes */ /* Exported types ------------------------------------------------------------*/ /* USER CODE BEGIN ET */ /* USER CODE END ET */ /* Exported constants --------------------------------------------------------*/ /* USER CODE BEGIN EC */ /* USER CODE END EC */ /* Exported macro ------------------------------------------------------------*/ /* USER CODE BEGIN EM */ /* USER CODE END EM */ /* Exported functions prototypes ---------------------------------------------*/ void Error_Handler(void); /* USER CODE BEGIN EFP */ /* USER CODE END EFP */ /* Private defines -----------------------------------------------------------*/ #define TP13_Pin GPIO_PIN_13 #define TP13_GPIO_Port GPIOC #define CAL_2_Pin GPIO_PIN_0 #define CAL_2_GPIO_Port GPIOC #define CAL_1_Pin GPIO_PIN_1 #define CAL_1_GPIO_Port GPIOC #define CAL_0_Pin GPIO_PIN_2 #define CAL_0_GPIO_Port GPIOC #define CAL_CS_Pin GPIO_PIN_3 #define CAL_CS_GPIO_Port GPIOC #define HEAT_PWM_Pin GPIO_PIN_0 #define HEAT_PWM_GPIO_Port GPIOA #define CHILL_PWM_Pin GPIO_PIN_1 #define CHILL_PWM_GPIO_Port GPIOA #define TP9_Pin GPIO_PIN_4 #define TP9_GPIO_Port GPIOC #define ADC_CS_Pin GPIO_PIN_1 #define ADC_CS_GPIO_Port GPIOB #define ADC_Start_Pin GPIO_PIN_8 #define ADC_Start_GPIO_Port GPIOE #define ADC_RST_Pin GPIO_PIN_11 #define ADC_RST_GPIO_Port GPIOE #define ADC_DRDY_Pin GPIO_PIN_14 #define ADC_DRDY_GPIO_Port GPIOE #define TP33_Pin GPIO_PIN_15 #define TP33_GPIO_Port GPIOE #define SDMMC1_CD_Pin GPIO_PIN_10 #define SDMMC1_CD_GPIO_Port GPIOB #define TP22_Pin GPIO_PIN_12 #define TP22_GPIO_Port GPIOB #define CALIB_MODE_Pin GPIO_PIN_13 #define CALIB_MODE_GPIO_Port GPIOB #define TP23_Pin GPIO_PIN_15 #define TP23_GPIO_Port GPIOB #define LED_B_Pin GPIO_PIN_8 #define LED_B_GPIO_Port GPIOD #define LED_G_Pin GPIO_PIN_9 #define LED_G_GPIO_Port GPIOD #define LED_R_Pin GPIO_PIN_10 #define LED_R_GPIO_Port GPIOD #define CAN_MODE_Pin GPIO_PIN_8 #define CAN_MODE_GPIO_Port GPIOA /* USER CODE BEGIN Private defines */ /* USER CODE END Private defines */ #ifdef __cplusplus } #endif #endif /* __MAIN_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
a522ce0af5cbf87382ddf41bbd70fec7ec181a2f
[ "C", "C++" ]
8
C
RIT-Landsat-Field-Radiometers/Sensor-Board
68a832bb6974edd23a7044c4d67f225b7acb84e1
725662cc79e0350c60d98bbe20dd253f6c908491
refs/heads/master
<repo_name>pkukielka/ar.js<file_sep>/README.md # ar.js Augmented Reality with Scala.js <file_sep>/src/main/javascript/fireball.js // Source: http://matsu4512.jp/blog/works/javascript/fire-effect/ var balls = []; function drawFireball(canvas, mouseX, mouseY) { ctx=canvas.getContext("2d"); ctx.globalCompositeOperation = "lighter"; for(var i = 0; i < 10; i++){ var ball = {}; ball.x = mouseX; ball.y = mouseY; ball.vx = Math.random()*10-5; ball.vy = Math.random()*10-7; ball.size = Math.random()*35+10; ball.r = Math.floor(Math.random()*128+127); ball.g = Math.floor(0.4*Math.random()*255); ball.b = Math.floor(0.4*Math.random()*255); ball.cx = mouseX; balls.push(ball); } i = balls.length; while(i--){ ball = balls[i]; ball.x += ball.vx; ball.y += ball.vy; ball.vy -= 0.4; ball.vx += (ball.cx-ball.x)/ball.size/2; ball.size -= 1.3; if(ball.size < 1){ balls.splice(i,1); continue; } ctx.beginPath(); var edgecolor1 = "rgba(" + ball.r + "," + ball.g + "," + ball.b + ","+(ball.size/20)+")"; var edgecolor2 = "rgba(" + ball.r + "," + ball.g + "," + ball.b + ",0)"; var gradblur = ctx.createRadialGradient(ball.x, ball.y, 0, ball.x, ball.y, ball.size); gradblur.addColorStop(0,edgecolor1); gradblur.addColorStop(1,edgecolor2); ctx.fillStyle = gradblur; ctx.arc(ball.x, ball.y, ball.size, 0, Math.PI*2, false); ctx.fill(); } ctx.globalCompositeOperation = "source-over"; }
70bc072c5a1c979cffa8ba1c929dc1f7f5dae431
[ "Markdown", "JavaScript" ]
2
Markdown
pkukielka/ar.js
17c3876e2a8c4b16970d37811efa94f7cb6d25c8
d8354547221a634f895ede5fce2e8f976f47e636
refs/heads/master
<repo_name>ssamsonau/CourseraDDPCompareYourCar<file_sep>/server.R library(shiny) library(ggplot2) library(plyr) DFtemp <- DFs # make this variable available in every function of this file shinyServer( function(input, output) { output$oCyl <- renderPrint({input$iCyl}) output$oTr <- renderPrint({ input$iTr }) output$oCarMPG <- renderPrint({ input$iCarMPG }) G <-reactive({ DFtemp <- subset(DFs, Trans == {input$iTr} & X..Cyl == {input$iCyl}) if( dim(DFtemp)[1]==0 ) stop("There is no data for a given paramenters combinations") ; DFtemp <- ddply(DFtemp, "Mfr.Name", summarise, City.MPG=mean(City.MPG)) DFtemp$compare <- "better" DFtemp[DFtemp$City.MPG < {input$iCarMPG}, "compare"] <- "worse" ggplot(data=DFtemp, aes(x=reorder(Mfr.Name, City.MPG), y=City.MPG, col = compare)) + geom_bar(stat="identity") + coord_flip() + xlab("") + ylab("City MPG") }) output$mpgPlot <- renderPlot({ input$estimateButton isolate( G() ) }) } ) <file_sep>/README.md CourseraDDPCompareYourCar ========================= <file_sep>/ui.R library(shiny) shinyUI(pageWithSidebar( headerPanel("Compare your's car mpg to others"), sidebarPanel( selectInput("iTr", "Transmission", levels(DFs$Trans), selected="A" ), selectInput("iCyl", "Number of Cylinders", sort( unique(DFs$X..Cyl) ), selected=4), numericInput("iCarMPG", "Enter City mpg of your car", 15, 0, 230), actionButton('estimateButton', "Refresh Plot"), h3("_______"), h3("You entered:"), h4('Type of transmission'), verbatimTextOutput("oTr"), h4('Number of cylinders'), verbatimTextOutput("oCyl"), h4('City mpg of your car'), verbatimTextOutput("oCarMPG") ), mainPanel( h4("! How to use the app"), helpText(" Please choose on the left a transmisiion type of your car and a number of cylinders. After that please enter mpg of your car. Press 'Refresh button' to compare mpg to average mpg from other brands in the year 2014 with the same number of cylinders and transmission type. This application uses the data from http://www.fueleconomy.gov/feg/epadata/14data.zip ." ), helpText("On the plot color helps you to see which manufacturers make cars with a better mpg"), helpText("This model is oversimplified to keep algorithm small and clear for reviews."), plotOutput("mpgPlot") ) ))<file_sep>/global.R URL <- "http://www.fueleconomy.gov/feg/epadata/14data.zip" if(! file.exists("./data/14data.zip")) { dir.create("./data/") download.file(URL, "./data/14data.zip", method="wget") unzip("./data/14data.zip", exdir="./data") filePath=paste0("./data/", grep(".xlsx", list.files("./data/"), value=TRUE)) library(xlsx) DF <- read.xlsx2(filePath, sheetName="FE Guide") DFs <- subset(DF, select=c("Mfr.Name", "X..Cyl", "Trans", "City.FE..Guide....Conventional.Fuel") ) write.csv(DFs, paste(filePath, "_subset.csv")) rm(DF); rm(DFs); } filePathCSV=paste0("./data/", grep(".csv", list.files("./data/"), value=TRUE)) DFs <- read.csv(filePathCSV, header=TRUE) DFs <- transform(DFs, Trans <- as.factor(Trans)) names(DFs)[names(DFs)=="City.FE..Guide....Conventional.Fuel"] = c("City.MPG")
acc6c3579d4fee29761c204454ac1359205109ea
[ "Markdown", "R" ]
4
R
ssamsonau/CourseraDDPCompareYourCar
e1d8d16586cee3b975066636f0cbe66ea85aa6a9
cbf77121bf83060bb89c75a383812b5a1959e291
refs/heads/master
<repo_name>takashi-i5/crm_questions_tinoue<file_sep>/README.md 5/10 締め切り課題 CRM関連用語問題集 <file_sep>/app/View/Questions/index.ctp <?php $num_questions = 10; $num_selections = 4; $questions_keys = array_keys($questions); if ($num_questions == 1) { $rand_keys = [array_rand($questions_keys, $num_questions)]; } else { $rand_keys = array_rand($questions_keys, $num_questions); } echo $this->Form->create('Question', ['url' => ['action' => 'index2'], 'type' => 'get']); echo $this->Form->hidden('rand_keys', ['value'=>$rand_keys]) ; for ($i = 0; $i < count($rand_keys); $i++) { $selected_questions = $questions[$rand_keys[$i]]; $num_question = $i + 1; echo "<h2>問題 $num_question</h2>"; $question_name = $selected_questions['Question']['question_sentence']; echo "<h3>$question_name</h3>"; echo "<h4>正解と思う選択肢にチェックしてください</h4>"; echo "<br />"; $k = 1; if ($rand_keys[$i] > 0) { for ($j = ($rand_keys[$i] + 1) * $num_selections - $num_selections; $j < ($rand_keys[$i] + 1) * $num_selections; $j++) { $selected_choices = $questionschoicesreasons[$j]; $checkbox = $this->Form->checkbox($selected_choices['QuestionsChoicesReason']['id']); $selected_choice = $selected_choices['QuestionsChoicesReason']['choice']; echo "<h4>$checkbox $k . ". " $selected_choice</h4>"; echo "<br />"; $k += 1; } } else { for ($j = 0; $j < $num_selections; $j++) { $selected_choices = $questionschoicesreasons[$j]; $checkbox = $this->Form->checkbox($selected_choices['QuestionsChoicesReason']['id']); $selected_choice = $selected_choices['QuestionsChoicesReason']['choice']; echo "<h4>$checkbox $k . ". " $selected_choice</h4>"; echo "<br />"; $k += 1; } } echo '<br />'; } $next_page = $this->Form->submit('答え合わせをする'); echo "<h1>$next_page</h1>"; echo $this->Form->end(); ?> <!-- <!DOCTYPE html> <html> <head> <title>第一問</title> </head> <body> <a href="./questions/index2">次へ</a> </body> </html> --><file_sep>/app/View/Questions/index2.ctp <?php $num_questions = 10; $num_selections = 4; $result_sorted = array_values($result); $count = 1; for ($i = 0; $i < $num_questions * $num_selections; $i++) { if ($result_sorted[$i] == 1) { $usrs_ans[] = $count; } else { } if ($count < 4) { $count += 1; } else { $count = 1; } } for ($i = 0; $i < count($rand_keys); $i++) { $selected_questions = $questions[$rand_keys[$i]]; $correct_ans = $numberquestionsanswers[$rand_keys[$i]]; $num_question = $i + 1; echo "<h2>問題 $num_question</h2>"; $question_name = $selected_questions['Question']['question_sentence']; echo "<h3>$question_name</h3>"; echo '<br />'; echo "<h4>あなたの答え</h4>"; echo "<h4>$usrs_ans[$i]</h4>"; echo "<h4>解答</h4>"; $correct_num = $correct_ans['NumberQuestionsAnswer']['number_answer']; $correct_nums[] = $correct_num; echo "<h4>$correct_num</h4>"; echo "<h4>解説</h4>"; for ($j = 4 * $rand_keys[$i]; $j < 4 + 4 * $rand_keys[$i]; $j++) { $tmp = $questionschoicesreasons[$j]; $qcr = $tmp['QuestionsChoicesReason']['reason']; echo "<h4>$qcr</h4>"; } echo '<br />'; } $score = count(array_intersect_assoc($usrs_ans, $correct_nums)); echo "<b><font size='5' color='#ff0000'><p style='text-align: center'>あなたの正答数は $score でした!</p></font></b>"; echo '<br />'; ?> <?php if ($score > 0) { echo $this->Form->create(); echo "<font size='4' color='#000000'><p style='text-align: center'>おめでとうございます!殿堂入りです!氏名を入力してください!</p></font>"; $inputted_name = $this->Form->input('name', array( 'type' => 'text', 'placeholder' => '氏名を入力する', 'label' => '', 'style' => array( 'width:100px' ) )); echo "<h1>$inputted_name</h1>"; $register_name = $this->Form->submit('登録'); echo "<h1>$register_name</h1>"; echo $this->Form->end(); } ?> <?php if ($score == 10) { echo $this->Form->create(); echo "<font size='4' color='#000000'><p style='text-align: center'>よろしければさらに難しいCRM関連の問題をお教え願えますでしょうか?</p></font>"; $inputted_name = $this->Form->input('question', array( 'type' => 'textarea', 'placeholder' => '問題を入力する', 'label' => '', 'style' => array( 'width:600px' ) )); echo "<h1>$inputted_name</h1>"; $register_name = $this->Form->submit('登録'); echo "<h1>$register_name</h1>"; echo $this->Form->end(); } $crown = $this->Html->image('crown.png', array('alt' => 'crown', 'width' => '50', 'height' => '50')); echo "<b><font size='5' color='#000000'><p style='text-align: center'>$crown 高得点者一覧 $crown</p></font></b>"; for ($k = 0; $k < count($names); $k++) { $rankers = $names[$k]; $name_ranker = $rankers['Name']['name']; echo "<font size='4' color='#000000'><p style='text-align: center'>$name_ranker</p></font>"; } ?> <!-- <!DOCTYPE html> <html> <head> <title>第一問解答解説</title> </head> <body> <a href="./questions/index2">次の問題に進む</a> </body> </html> --><file_sep>/app/Controller/QuestionsController.php <?php class QuestionsController extends AppController { // public $autoLayout = false; public $helpers = array('Html', 'Form'); public $uses = array('Question', 'NumberQuestionsAnswer', 'QuestionsChoicesReason', 'Name', 'DifficultQuestion'); public function index() { $this->set('questions', $this->Question->find('all')); $this->set('questionschoicesreasons', $this->QuestionsChoicesReason->find('all')); $this->set('title_for_layout', 'CRM関連用語問題集'); } public function index2() { // debug($this->request->query()); $this->set('questions', $this->Question->find('all')); $this->set('names', $this->Name->find('all')); $this->set('questionschoicesreasons', $this->QuestionsChoicesReason->find('all')); $this->set('numberquestionsanswers', $this->NumberQuestionsAnswer->find('all')); $this->set('title_for_layout', 'CRM関連用語問題集'); // チェックされた情報を配列として渡す $result = $this->request->query(); unset($result['rand_keys']); $this->set('result', $result); // ランダムな問題番号インデックス $rand_keys = explode(" ", $this->request->query['rand_keys']); $this->set('rand_keys', $rand_keys); // フォームによる入力 $inputted_data = $this->request->data(); $form_name = current(array_keys($inputted_data['Question'])); if (isset($inputted_data) && $form_name == 'name') { $this->Name->save(array('name' => $inputted_data['Question']['name'])); } elseif (isset($inputted_data) && $form_name == 'question') { $this->DifficultQuestion->save(array('question' => $inputted_data['Question']['question'])); } } } <file_sep>/app/Model/Question.php <?php class Question extends AppModel { public $validate = array( 'name' => array( 'allowEmpty' => false ) ); }
05ca9d83cca690fb587b4ace93366beae3c3b5a9
[ "Markdown", "PHP" ]
5
Markdown
takashi-i5/crm_questions_tinoue
620a0510ffda1da574c43cc57b93325622012cba
da6da57e1534c8e8e7506a943f30cd9b47560a0c
refs/heads/master
<file_sep>import {combineReducers} from 'redux'; import {demoReducer} from "./demoReducer"; export const rootReducer = combineReducers({ demoReducer: demoReducer });<file_sep>const STORE_DATA = "Store_Data"; const GET_DATA = "Get_Data"; export interface storeData { data: string; } export const demoReducer = (state: storeData = {data: 'NOT_SET'}, action: any) => { switch(action.type){ case STORE_DATA: console.log("STORE: " + action.payload); return {data: 'ZAC Did'}; case GET_DATA: console.log("GET: " + action.payload); return action.payload; default: return state; } };
139dd8ef99759537320ea2137d9ee1ceba37e1ee
[ "TypeScript" ]
2
TypeScript
zcstr/reactdemo02
75e02e708811f0e0ab84ca959a78dd6325ebf7c9
2d0d355f2a0811409cb223ba69aa19bfb8d587c6
refs/heads/master
<repo_name>AnnaKuzina/Home_Work_1<file_sep>/README.md Home Work 25.02.2019 ![HomeWorkTask(25.02.2019)](https://github.com/AnnaKuzina/C_Sharp_HomeWork1_25.02.2019/blob/master/HomeWorkTask(25.02.2019).PNG) <file_sep>/Task1_NumbersMultiplicationBy10.cs using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AppMultiplicationBy10 { class NumbersMultiplicationBy10 { public int[] InputNumbers() { int[] input_numbers = new int[5]; Console.WriteLine("Please enter 5 numbers: "); for (int i = 0; i < input_numbers.Length; i++) { input_numbers[i] = Int32.Parse(Console.ReadLine()); } return input_numbers; } public void PrintsNumbersMultipliedBy10(int[] input_numbers) { Console.WriteLine("User input finished. Processing..."); for (int j = 0; j < input_numbers.Length; j++) { Console.Write(input_numbers[j] * 10 + " "); } } static void Main(string[] args) { NumbersMultiplicationBy10 n = new NumbersMultiplicationBy10(); n.PrintsNumbersMultipliedBy10(n.InputNumbers()); Console.ReadKey(); } } } <file_sep>/Task2_NUnitTestOpenLink.cs using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using System; namespace Tests { public class TestsWebDriver { IWebDriver driver = new ChromeDriver(@"C:\"); [SetUp] public void Setup() { driver.Manage().Window.Maximize(); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(20); } [Test] public void TestOpen() { driver.Navigate().GoToUrl("https://www.google.com/"); //open site Google driver.FindElement(By.XPath("//*[@id='tsf']/div[2]/div/div[1]/div/div[1]/input")).SendKeys("Wikipedia" + Keys.Enter); //enter "Wikipedia" and press Enter driver.FindElement(By.XPath("//*[@id='rso']/div[1]/div/div/div/div/div[1]/a/h3")).Click(); //click first link on the page } [TearDown] public void Cleanup() { driver.Quit(); } } }
1ea688e92de8f70d94141e807ffd8bc0b736db46
[ "Markdown", "C#" ]
3
Markdown
AnnaKuzina/Home_Work_1
53075523120d8cfebeb66b2afe4ec5eeebe49688
871e71fb06a1d6fc64f86517f6a7fa43d65476cc
refs/heads/master
<repo_name>noemoriwaki/original_hp<file_sep>/login.php <?php // セッションを開始 session_start(); // データーベースの読み込み require_once("database.php"); function findUserByEmail($dbh, $email){ $sql = "SELECT * FROM users WHERE email = ? "; $stmt = $dbh->prepare($sql); $data[] = $email; $stmt->execute($data); return $stmt->fetch(PDO::FETCH_ASSOC); } // Emailが合っているのか参照 if (!empty($_POST)) { // emailが合っている場合 $user = findUserByEmail($dbh, $_POST["email"]) ; //passwordも合っている場合 if(password_verify($_POST["password"], $user["password"])) { $_SESSION["login"] = true; // どのページでもログイン状態にする $_SESSION["user"] = $user; // ログインするとマイページへ飛ぶ header('Location: original.php'); exit; }else { echo 'Invalid password.'; } } // ログインしているのか表示 if ($_SESSION["login"]) { echo "ログインしています。"; } else { echo "ログインしていません。"; } ?> <!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>ログイン</title> </head> <body> <h1>ログイン</h1> <!-- 自分に戻ってくる --> <form action="./login.php" method="POST"> <div> メールアドレス <input type="Email" name="email" id="email"> </div> <div> パスワード <input type="<PASSWORD>" name="password" id="password"> </div> <div> <button type="submit">ログイン</button> </div> </form> </body> </html>
85d5e5368949f73849c48497f4090d2a11a28b8a
[ "PHP" ]
1
PHP
noemoriwaki/original_hp
ada7a42cd8e4e38645e65d6fc04f002b78f9bef4
a8f5904016f4a4727f45e75447af485ec2561884
refs/heads/master
<repo_name>TheBlueGamer55/Simple-Text-Encoder<file_sep>/index.js var data = require("sdk/self").data; var text_entry = require("sdk/panel").Panel({ width: 960, height: 320, contentURL: data.url("text-entry.html"), contentScriptFile: data.url("convert-text.js") }); require("sdk/ui/button/action").ActionButton({ id: "show-panel", label: "Show Panel", icon: { "16": "./icon-16.png", "32": "./icon-32.png", "64": "./icon-64.png" }, onClick: handleClick }); function handleClick(state){ text_entry.show(); } text_entry.on("show", function(){ text_entry.port.emit("show"); }); <file_sep>/data/convert-text.js var textArea = document.getElementById("plaintext-box"); var binaryArea = document.getElementById("binary-box"); var hexadecimalArea = document.getElementById("hexadecimal-box"); var textButton = document.getElementById("plaintext-button"); var binaryButton = document.getElementById("binary-button"); var hexadecimalButton = document.getElementById("hexadecimal-button");; function textToBinary(plaintext){ var output = ""; for(var i = 0; i < plaintext.length; i++){ var temp = plaintext[i].charCodeAt(0).toString(2); temp = "00000000".substr(temp.length) + temp; output += temp; } return output; } function textToHexadecimal(plaintext){ var output = ""; for(var i = 0; i < plaintext.length; i++){ var temp = plaintext[i].charCodeAt(0).toString(16); output += temp; } return output; } function binaryToText(binarytext){ binarytext = binarytext.trim(); var output = ""; for(var i = 0; i < binarytext.length; i+=8){ var temp = binarytext.substr(i, 8); temp = String.fromCharCode(parseInt(temp, 2)); output += temp; } return output; } function binaryToHexadecimal(binarytext){ binarytext = binarytext.trim(); var plaintext = binaryToText(binarytext); var hexadecimalText = textToHexadecimal(plaintext); return hexadecimalText; } function hexadecimalToText(hexadecimaltext){ hexadecimaltext = hexadecimaltext.trim(); var output = ""; for(var i = 0; i < hexadecimaltext.length; i+=2){ var temp = hexadecimaltext.substr(i, 2); temp = String.fromCharCode(parseInt(temp, 16)); output += temp; } return output; } function hexadecimalToBinary(hexadecimaltext){ hexadecimaltext = hexadecimaltext.trim(); var plaintext = hexadecimalToText(hexadecimaltext); var binaryText = textToBinary(plaintext); return binaryText; } textButton.addEventListener("click", function onClick(){ var text = textArea.value; binaryArea.value = textToBinary(text); hexadecimalArea.value = textToHexadecimal(text); }); binaryButton.addEventListener("click", function onClick(){ var binaryText = binaryArea.value; textArea.value = binaryToText(binaryText); hexadecimalArea.value = binaryToHexadecimal(binaryText); }); hexadecimalButton.addEventListener("click", function onClick(){ var hexadecimalText = hexadecimalArea.value; textArea.value = hexadecimalToText(hexadecimalText); binaryArea.value = hexadecimalToBinary(hexadecimalText); }); self.port.on("show", function onShow(){ textArea.focus(); }); <file_sep>/README.md # Simple Text Encoder A simple addon that converts plaintext into other forms such as binary and hexadecimal.
d324374a02f1b3d61527018bdb54c7753fa72185
[ "JavaScript", "Markdown" ]
3
JavaScript
TheBlueGamer55/Simple-Text-Encoder
e0ecd2e3c56d43e3e7d71ce3a6750a758d4386c4
dcb13e63e65d0f678f007de078e3134f6f056599
refs/heads/master
<file_sep>import { Pipe, PipeTransform } from '@angular/core'; import { Wine } from './classes/wine'; @Pipe({ name: 'tableFilter' }) export class TableFilterPipe implements PipeTransform { transform(wines: Wine[], searchText: string): any { if (!searchText) { return wines; } return wines.filter((wine: Wine) => this.applyFilter(wine, searchText)); } applyFilter(wine: Wine, searchText: string): boolean { for (const key in wine) { if (String(wine[key]).toLowerCase().indexOf(searchText.toLowerCase()) !== -1) { return true; } } return false; } } <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { ReactiveFormsModule, FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { WineDetailComponent } from './wine-detail/wine-detail.component'; import { AppRoutingModule } from './/app-routing.module'; import { WineListComponent } from './wine-list/wine-list.component'; import { WineNewComponent } from './wine-new/wine-new.component'; import { TableFilterPipe } from './table-filter.pipe'; import { WineCardComponent } from './wine-card/wine-card.component'; import { WineNavComponent } from './wine-nav/wine-nav.component'; import { WineCommentsFormComponent } from './wine-comments-form/wine-comments-form.component'; @NgModule({ declarations: [ AppComponent, WineDetailComponent, WineListComponent, WineNewComponent, TableFilterPipe, WineCardComponent, WineNavComponent, WineCommentsFormComponent ], imports: [ BrowserModule, HttpClientModule, AppRoutingModule, ReactiveFormsModule, FormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { Component, OnInit } from '@angular/core'; import { WineApiService } from '../wine-api.service'; import { Wine } from '../classes/wine'; import { WineCardComponent } from '../wine-card/wine-card.component'; @Component({ selector: 'app-wine-list', templateUrl: './wine-list.component.html', styleUrls: ['./wine-list.component.scss'] }) export class WineListComponent implements OnInit { public wines: Wine[]; searchText = ''; constructor(private _wineService: WineApiService) { } ngOnInit() { this.getWine(); } sortBy(column) { if (this.wines) { this.wines.sort((win1, win2) => win1[column] !== win2[column] ? win1[column] < win2[column] ? -1 : 1 : 0); } } getWine() { this._wineService.getWines().subscribe( res => this.wines = res, err => console.error(err), () => console.log('wine loaded') ); } } <file_sep>import { TestBed, inject } from '@angular/core/testing'; import { WineApiService } from './wine-api.service'; describe('WineApiService', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [WineApiService] }); }); it('should be created', inject([WineApiService], (service: WineApiService) => { expect(service).toBeTruthy(); })); }); <file_sep>export class Wine { constructor( public name: string, public vineyard?: string, public year?: number, public description?: string, public image?: string, ) {} } <file_sep>import { Component, OnInit } from '@angular/core'; import { FormControl, FormGroup } from '@angular/forms'; import { WineApiService } from './../wine-api.service'; import { Wine } from '../classes/wine'; @Component({ selector: 'app-wine-new', templateUrl: './wine-new.component.html', styleUrls: ['./wine-new.component.scss'] }) export class WineNewComponent implements OnInit { wineForm = new FormGroup({ name: new FormControl(), description: new FormControl(), vineyard: new FormControl(), year: new FormControl() }); constructor(private _wineService: WineApiService) { } submitWine() { const model = this.wineForm.value; const wine = new Wine( model.name, model.vineyard, model.year, model.description ); this._wineService.postWine(wine); } ngOnInit() { } } <file_sep>import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Wine } from './classes/wine'; @Injectable({ providedIn: 'root' }) export class WineApiService { public api = 'http://localhost:3000/'; constructor(private http: HttpClient) { } getWines() { return this.http.get( this.api + 'wines'); } getWine(id) { return this.http.get( this.api + 'wines/' + id); } postWine(newWine) { return this.http.post(this.api + 'wines', newWine).subscribe(res => console.log(res)); } } <file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-wine-nav', templateUrl: './wine-nav.component.html', styleUrls: ['./wine-nav.component.scss'] }) export class WineNavComponent implements OnInit { searchText = ''; constructor() { } ngOnInit() { } } <file_sep>import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { WineDetailComponent } from './wine-detail/wine-detail.component'; import { WineListComponent } from './wine-list/wine-list.component'; import { WineNewComponent } from './wine-new/wine-new.component'; const routes: Routes = [ { path: '', redirectTo: '/wine', pathMatch: 'full' }, { path: 'wine', component: WineListComponent }, { path: 'wine/:id', component: WineDetailComponent }, { path: 'newWine', component: WineNewComponent } ]; @NgModule({ imports: [ RouterModule.forRoot(routes) ], exports: [ RouterModule ] }) export class AppRoutingModule { } <file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { WineApiService } from './../wine-api.service'; @Component({ selector: 'app-wine-detail', templateUrl: './wine-detail.component.html', styleUrls: ['./wine-detail.component.scss'] }) export class WineDetailComponent implements OnInit { public wine; constructor( private _route: ActivatedRoute, private _wineService: WineApiService, ) { } ngOnInit() { this._route.params.subscribe(params => { this._wineService.getWine(params['id']).subscribe(res => { this.wine = res; }); }); } } <file_sep>import { Component, OnInit, Input } from '@angular/core'; import { Wine } from '../classes/wine'; @Component({ selector: 'app-wine-card', templateUrl: './wine-card.component.html', styleUrls: ['./wine-card.component.scss'] }) export class WineCardComponent implements OnInit { @Input() wine: Wine; constructor() { } ngOnInit() { } }
7382b26244fda0d7b26a8eb6a5b6497e6bc244e6
[ "TypeScript" ]
11
TypeScript
CptSpades/winery
dde6cb0559c8cfe39dc2cb02dfd91bdae6dd542a
178b7e1290aa0b38d8475a92c39b1775b7469d03
refs/heads/master
<repo_name>TylerGlorie/ringLED-AudioViz<file_sep>/The_Real_Analyzer_part1/The_Real_Analyzer_part1.ino /* Original Code written by by FischiMc and SupaStefe The original code used a 10x10 RGB LED-Matrix as a spectrum analyzer It uses a FTT Library to analyze an audio signal connected to the pin A7 of an Arduino nano. Everytime a column gets higher than 10 pixels the color of each column changes. This code has been modified to work on 6 concentric WS2812b ring LEDs. Also modified to raise the noise floor to prevent flickering. */ #define LOG_OUT 0 //set output of FFT library to linear not logarithmical #define LIN_OUT 1 #define FFT_N 256 //set to 256 point fft #include <FFT.h> //include the FFT library #include <FastLED.h> //include the FastLED Library #include <math.h> //include library for mathematic funcions #define DATA_PIN 5 //DATA PIN WHERE YOUR LEDS ARE CONNECTED #define NUM_LEDS 121 //amount of LEDs in your matrix CRGB leds[NUM_LEDS]; float faktoren[6] = {1, 1.1, 2.0, 2.6, 3.2, 4.8}; //factors to increase the height of each column unsigned char hs[6] = {0,0,0,0,0,0}; //height of each column float hue = 0; //hue value of the colors unsigned char ringLed[6] = {30,12,8,6,4,1}; unsigned char numLeds[6] = {0,60,84,100,112,120}; //sum of leds before it void setBalken(unsigned char column, unsigned char height){ //calculation of the height of each column unsigned char h = (unsigned char)map(height, 0, 255, 0, ringLed[(column)]); h = (unsigned char)(h * faktoren[column]); if (height < 24 && column == 0){ //testing to reduce stable flickering h = 0; } if (h < hs[column]){ hs[column]--; } else if (h > hs[column]){ hs[column] = h; } if (height > 250){ hue+=2; //CHANGE THIS VALUE IF YOU WANT THE DIFFERENCE BETWEEN THE COLORS TO BE BIGGER if(hue > 24) hue=0; } for(unsigned char y = 0; y < ringLed[column]; y++){ //set colors of pixels according to column and hue if(hs[column] > y){ float suby = y; float bright = (140 + (60*(suby/(ringLed[column])))); leds[y+numLeds[column]] = CHSV((hue*10)+(column*10), 255, bright ); ////may need to change second column to column+1 leds[(numLeds[column+1]) -y] = CHSV((hue*10)+(column*10), 255, bright); } else { leds[y+numLeds[column]] = CRGB::Black; leds[(numLeds[column+1]) -y] = CRGB::Black; } } } unsigned char grenzen[7] = {0,3,5,8,14,100,120}; //borders of the frequency areas void setup() { FastLED.addLeds<WS2812B, DATA_PIN, GRB> (leds, NUM_LEDS); Serial.begin(115200); //use the serial port TIMSK0 = 0; //turn off timer0 for lower jitter ADCSRA = 0xe5; //set the adc to free running mode ADMUX = 0b01000111; //use pin A7 DIDR0 = 0x01; //turn off the digital input for analogReference(EXTERNAL); //set aref to external } void loop() { while(1) { //reduces jitter cli(); //UDRE interrupt slows this way down on arduino1.0 for (int i = 0 ; i < 512 ; i += 2) { //save 256 samples while(!(ADCSRA & 0x10)); //wait for adc to be ready ADCSRA = 0xf5; //restart adc byte m = ADCL; //fetch adc data byte j = ADCH; int k = (j << 8) | m; //form into an int k -= 0x0200; //form into a signed int k <<= 6; //form into a 16b signed int fft_input[i] = k; //put real data into even bins } fft_window(); // window the data for better frequency response fft_reorder(); // reorder the data before doing the fft fft_run(); // process the data in the fft fft_mag_lin(); // take the output of the fft sei(); fft_lin_out[0] = 0; fft_lin_out[1] = 0; for(unsigned char i = 0; i < 6; i++){ unsigned char maxW = 0; for(unsigned char x = grenzen[i]; x < grenzen[i+1];x++){ if((unsigned char)fft_lin_out[x] > maxW){ maxW = (unsigned char)fft_lin_out[x]; } } setBalken(i, maxW); Serial.print(maxW); Serial.print(" "); } Serial.println(""); TIMSK0 = 1; FastLED.show(); TIMSK0 = 0; } } <file_sep>/README.md # ringLED-AudioViz
54330e786a57114878770d4fa5df7a1f5c15ed2d
[ "Markdown", "C++" ]
2
C++
TylerGlorie/ringLED-AudioViz
bfa868d3a00f7568bd46c417110fdf875768ac8f
dc5e05d5f0b1c5b741b923d776bc0d8f29466c7e
refs/heads/master
<file_sep>import matplotlib.pyplot as plt import numpy as np x = np.linspace(-5, 5, 100) y1 = 0.5 * x y2 = x * x plt.figure() plt.xlabel('X axis...') plt.ylabel('Y axis...') #设置坐标轴的文字标签 ax = plt.gca() # get current axis 获得坐标轴对象 ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') # 将右边 上边的两条边颜色设置为空 其实就相当于抹掉这两条边 ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') # 指定下边的边作为 x 轴 指定左边的边为 y 轴 ax.spines['bottom'].set_position(('data', 0)) #指定 data 设置的bottom(也就是指定的x轴)绑定到y轴的0这个点上 ax.spines['left'].set_position(('data', 0)) plt.plot(x, y1, linestyle='--') plt.plot(x, y2) plt.show()<file_sep># pygal 已经删除了i18n,需要导入pygal_maps_world from pygal_maps_world.i18n import COUNTRIES def get_country_code(country_name): """根据指定的国家,返回pygal使用的两个字母的国别码""" for code, name in COUNTRIES.items(): if name == country_name: return code if country_name == "Hong Kong SAR, China": return 'hk' if country_name == "Korea, Dem. People’s Rep.": return 'kp' if country_name == "Korea, Rep.": return 'kr' if country_name == 'Moldova': return 'md' if country_name == 'Yemen, Rep.': return 'ye' if country_name == 'Viet Nam': return 'vn' # 如果找到指定的国家,返回None return None <file_sep>import csv # pygal 已经删除了i18n,需要导入pygal_maps_world from pygal_maps_world.i18n import COUNTRIES from pygal.style import RotateStyle from pygal_maps_world.maps import World from pygal.style import Style def get_country_code(country_name): """根据指定的国家,返回pygal使用的两个字母的国别码""" for code, name in COUNTRIES.items(): if name == country_name: return code if country_name == "Hong Kong SAR, China": return 'hk' if country_name == "Korea, Dem. People’s Rep.": return 'kp' if country_name == "Korea, Rep.": return 'kr' if country_name == 'Moldova': return 'md' if country_name == 'Yemen, Rep.': return 'ye' if country_name == 'Viet Nam': return 'vn' # 如果找不到指定的国家,返回None return None # 载入csv filename = 'API_NY.GDP.PCAP.CD_DS2_en_csv_v2_713080.csv' with open(filename, encoding="UTF-8") as f: reader = csv.reader(f) # 建gdp字典 new_gdp_list = {} for i in range(5): ignore = next(reader) for row in reader: date = 63 # 当GDP不为空时 while not row[date]: date -= 1 if date == 4: break if date != 4: code = get_country_code(row[0]) # 如果code存在 if code != None: new_gdp_list[code] = float(row[date]) # 为国家分组 gdp_1, gdp_2, gdp_3, gdp_4 = {},{},{},{} for code, gdp in new_gdp_list.items(): if gdp > 50000: gdp_1[code] = gdp elif gdp > 10000: gdp_2[code] = gdp elif gdp > 1000: gdp_3[code] = gdp else: gdp_4[code] = gdp # 设置颜色 custom_style = Style(colors=('#000066', '#000099', '#0066ff', '#3399ff')) wm_style = RotateStyle('#000099') wm = World(style=custom_style) wm.title = 'GDP per capita (current US$)' wm.add("GDP > 50000", gdp_1) wm.add("GDP 50000-10000", gdp_2) wm.add("GDP 10000-1000", gdp_3) wm.add("GDP 1000-0", gdp_4) wm.render_to_file("result.svg") <file_sep>import csv import matplotlib.pyplot as plt import datetime import CaixinData.caixin_pneumonia_data as cpd # 更新数据 option = input("更新数据?y/n") if option == 'y': cpd.run() filename = 'CaixinData/data2.csv' with open(filename, encoding='utf-8') as f: # 计算多少行 lines = len(f.readlines()) # 返回第一行,因为readline()执行完后在文件末尾 f.seek(0) reader = csv.reader(f) header_row = next(reader) plt.rcParams['font.sans-serif'] = ['KaiTi'] plt.rcParams['font.serif'] = ['KaiTi'] """ enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列, 同时列出数据和数据下标,一般用在 for 循环当中。 """ # 获得全国数据 total = [] hubei = [] for row in reader: try: total.append(int(row[1])) hubei.append(int(row[2])) except ValueError: print('data missing') # 生成一个日期轴 day_list = ['2019-12-31', '2019-1-11'] begin = datetime.date(2020, 1, 16) for i in range(lines-3): day = begin + datetime.timedelta(days=i) day_list.append(str(day)) # 根据数据绘制图形 fig = plt.figure(dpi=200, figsize=(10,6)) plt.plot(day_list, total, c='black', linewidth=3) plt.plot(day_list, hubei, c='gray', linewidth=3) plt.fill_between(day_list, total, hubei, facecolor='blue', alpha=0.1) # 设置图形格式 plt.title("全国和湖北确诊人数", fontsize=24) plt.ylabel("Infection Toll", fontsize=16) plt.xticks(rotation=90) # 90为旋转的角度 plt.savefig("result.png", dpi=200, bbox_inches='tight') plt.show() <file_sep># LearnDataScienceOnTheWay 个人学习matplotlib、pandas、pygal <file_sep>import matplotlib.pyplot as plt squares = [1,4,9,16,25] plt.plot(squares,linewidth=5) plt.title("square Numbers", fontsize=24) plt.show()
fe3e4c503329201ee12d8c6e9898659105e9b91b
[ "Markdown", "Python" ]
6
Python
OhiyoX/LearnDataScienceOnTheWay
3882be0c58914445fbb4ad132bd99a8650243f15
f79f47825e925ec4095791c45bd2ece8770764b6
refs/heads/master
<file_sep>import re import time import string # For string.ascii_lowercase (detecting CAPS floods) import supybot.conf as conf import supybot.ircutils as ircutils import supybot.ircmsgs as ircmsgs import supybot.ircdb as ircdb from supybot.commands import * import supybot.callbacks as callbacks import supybot.schedule as schedule from supybot.i18n import PluginInternationalization, internationalizeDocstring _ = PluginInternationalization('FloodProtector') class FloodProtector(callbacks.Plugin): """Kicks/Bans users for flooding""" regexs = {} # Mass highlight offenses = {} # Users are immune for three secconds to prevent double kicks and bans immunities = {} repetitionRegex = re.compile(r"(.+?)\1+") def inFilter(self, irc, msg): if msg.command in ("PRIVMSG", "NOTICE", "JOIN", "PART", "QUIT"): channel = msg.args[0] if ircutils.isChannel(channel) and\ self.registryValue("enabled", channel): if msg.command in ("PRIVMSG", "NOTICE"): self.checkMessageFlood(irc, msg) elif msg.command in ("JOIN", "PART", "QUIT"): self.checkJoinFlood(irc, msg) return msg def generateRecent(self, irc, msg, commands, maxNeeded = 5): recent = [] # Sorted in order of arival for item in reversed(irc.state.history): if item.command in commands and\ item.nick == msg.nick and\ item.args[0] == msg.args[0]: recent.insert(0, item) if len(recent) >= maxNeeded: break return recent def checkJoinFlood(self, irc, msg): channel = msg.args[0] recentJoins = self.generateRecent(irc, msg, ("JOIN", "PART", "QUIT"), 6) # Flaping connection if len(recentJoins) >= 6 and\ recentJoins[-1].receivedAt - recentJoins[-6].receivedAt < 240: self.banForward(irc, msg, "#fix_your_connection") def checkMessageFlood(self, irc, msg): channel = msg.args[0] message = ircutils.stripFormatting(msg.args[1]) recentMessages = self.generateRecent(irc, msg, ("PRIVMSG", "NOTICE")) # Regular message flood if len(recentMessages) >= 5: if (recentMessages[-1].receivedAt -\ recentMessages[-5].receivedAt) <= 6: self.floodPunish(irc, msg, "Message", dummy = False) # Message repitition flood if len(recentMessages) >= 3: firstTime = recentMessages[-3].receivedAt curTime = recentMessages[-1].receivedAt if (recentMessages[-3].args[1] ==\ recentMessages[-2].args[1] ==\ recentMessages[-1].args[1]) and\ curTime - firstTime < 60: self.floodPunish(irc, msg, "Message repetition", dummy = False) return # Repitition #def repetitions(r, s): # for match in r.finditer(s): # yield((match.group(1), len(match.group(0)) / len(match.group(1)))) #repetitionList = list(repetitions(self.repetitionRegex, # recentMessages[-1].args[1])) #for rep in repetitionList: # if rep[1] > 10: # self.floodPunish(irc, msg, "Repetition", dummy = True) # return # Paste flood typedTooFast = lambda recent, old:\ len(recent.args[1]) > (recent.receivedAt - old.receivedAt) * 30 if len(recentMessages) >= 4 and\ typedTooFast(recentMessages[-1], recentMessages[-2]) and\ typedTooFast(recentMessages[-2], recentMessages[-3]) and\ typedTooFast(recentMessages[-3], recentMessages[-4]): self.floodPunish(irc, msg, "Paste", dummy = False) return # Slap flood isSlap = lambda x: ircmsgs.isAction(x) and x.args[1][8:13] == "slaps" if len(recentMessages) > 3 and\ isSlap(recentMessages[-1]) and\ isSlap(recentMessages[-2]) and\ isSlap(recentMessages[-3]) and\ (recentMessages[-1].receivedAt - recentMessages[-3].receivedAt) < 30: self.floodPunish(irc, msg, "Slap") return # Mass highlight if irc.network in self.regexs and\ channel in self.regexs[irc.network]: matches = self.regexs[irc.network][channel].findall(message) if len(matches) > 10: self.floodPunish(irc, msg, "Highlight") return # CAPS FLOOD #def tooManyCaps(s): # if len(s) == 0: return False # numNotCaps = 0 # for c in s: # if c in string.ascii_lowercase: # numNotCaps += 1 # return numNotCaps / len(s) < 0.25 #if len(recentMessages) >= 3: # if tooManyCaps(recentMessages[-1].args[1]) and\ # tooManyCaps(recentMessages[-2].args[1]) and\ # tooManyCaps(recentMessages[-3].args[1]): # self.floodPunish(irc, msg, "CAPS", dummy = True) # return def banForward(self, irc, msg, channel): hostmask = irc.state.nickToHostmask(msg.nick) banmaskstyle = conf.supybot.protocols.irc.banmask banmask = banmaskstyle.makeBanmask(hostmask) irc.queueMsg(ircmsgs.mode(msg.args[0], ("+b", banmask + "$" + channel))) self.log.warning("Ban-forwarded %s (%s) from %s to %s.", banmask, msg.nick, msg.args[0], channel) def floodPunish(self, irc, msg, floodType, dummy = False): channel = msg.args[0] if (not irc.nick in irc.state.channels[channel].ops) and\ (not irc.nick in irc.state.channels[channel].halfops): self.log.warning("%s flooded in %s, but not opped.",\ msg.nick, channel) return if msg.nick in self.immunities: self.log.debug("Not punnishing %s, they are immune.", msg.nick) return if msg.nick in irc.state.channels[channel].ops or\ msg.nick in irc.state.channels[channel].halfops or\ msg.nick in irc.state.channels[channel].voices: self.log.debug("%s flooded in %s. But"\ + " I will not punish them because they have"\ + " special access.", msg.nick, channel) return if ircdb.checkCapability(msg.prefix, 'trusted') or\ ircdb.checkCapability(msg.prefix, 'admin') or\ ircdb.checkCapability(msg.prefix, channel + ',op'): self.log.debug("%s flooded in %s. But"\ + " I will not punish them because they are"\ + " trusted.", msg.nick, channel) return if msg.host in self.offenses and self.offenses[msg.host] > 2: hostmask = irc.state.nickToHostmask(msg.nick) banmaskstyle = conf.supybot.protocols.irc.banmask banmask = banmaskstyle.makeBanmask(hostmask) if not dummy: irc.queueMsg(ircmsgs.ban(channel, banmask)) self.log.warning("Banned %s (%s) from %s for repeated"\ + " flooding.", banmask, msg.nick, channel) reason = floodType + " flood detected." if floodType == "Paste": reason += " Use a pastebin like pastebin.ubuntu.com or gist.github.com." if not dummy: irc.queueMsg(ircmsgs.kick(channel, msg.nick, reason)) self.log.warning("Kicked %s from %s for %s flooding.",\ msg.nick, channel, floodType) # Don't schedule the same nick twice if not (msg.host in self.offenses): schedule.addEvent(self.clearOffenses, time.time()+300, args=[msg.host]) self.offenses[msg.host] = 0 # Incremented below self.offenses[msg.host] += 1 self.immunities[msg.nick] = True schedule.addEvent(self.unImmunify, time.time()+3, args=[msg.nick]) def clearOffenses(self, host): if self.offenses[host] > 1: self.offenses[host] -= 1 schedule.addEvent(self.clearOffenses, time.time()+300, args=[host]) else: del self.offenses[host] def unImmunify(self, nick): del self.immunities[nick] def makeRegexp(self, irc, channel): if channel is None: channels = irc.state.channels.keys() else: channels = [channel] for channelName in channels: longNicks = [x for x in\ irc.state.channels[channelName].users if len(x) > 3] s = r"|".join(map(re.escape, longNicks)) if not irc.network in self.regexs: self.regexs[irc.network] = {} self.regexs[irc.network][channel] =\ re.compile(s, re.IGNORECASE) def doJoin(self, irc, msg): for channel in msg.args[0].split(","): self.makeRegexp(irc, channel) def doPart(self, irc, msg): if msg.nick == irc.nick: return for channel in msg.args[0].split(","): self.makeRegexp(irc, channel) def doQuit(self, irc, msg): if msg.nick == irc.nick: return self.makeRegexp(irc, None) def doKick(self, irc, msg): if msg.nick == irc.nick: return self.makeRegexp(irc, msg.args[0]) def doNick(self, irc, msg): self.makeRegexp(irc, None) Class = FloodProtector <file_sep>from __future__ import division import time import supybot.conf as conf import supybot.registry as registry from supybot.i18n import PluginInternationalization, internationalizeDocstring _ = PluginInternationalization('FloodProtector') def configure(advanced): from supybot.questions import output, expect, anything, something, yn conf.registerPlugin('FloodProtector', True) FloodProtector = conf.registerPlugin('FloodProtector') conf.registerChannelValue(FloodProtector, "enabled", registry.Boolean(True, "Whether to check floods in the channel.")) # vim:set textwidth=79:
532da647bb7b737cae165da3938824c5c483541f
[ "Python" ]
2
Python
nanepiwo/Limnoria-plugins
dd6261ffea2d0064f33f89d763bccc0dc9709b5c
12b28919daa51a584fa4af3d50c6b8f3f0ae88d0
refs/heads/master
<repo_name>abdibus/Terraform-Cheatsheet<file_sep>/AWS-EBS-Attach-Mount/code/run.sh #!/bin/bash sudo yum -y update sudo yum -y upgrade # The best way is to run that script after \resource "aws_volume_attachment"\ created sleep 120 # Format and mount an attached volume DEVICE=/dev/$(lsblk -rno NAME | awk 'FNR == 3 {print}') MOUNT_POINT=/data/ mkdir $MOUNT_POINT yum -y install xfsprogs mkfs -t xfs $DEVICE mount $DEVICE $MOUNT_POINT # Automatically mount an attached volume after reboot / For the current task it's not obligatory cp /etc/fstab /etc/fstab.orig UUID=$(blkid | grep $DEVICE | awk -F '\"' '{print $2}') echo -e "UUID=$UUID $MOUNT_POINT xfs defaults,nofail 0 2" >> /etc/fstab umount /data mount -a # Change user for data operations / Non mandatory chown -R ec2-user:ec2-user $MOUNT_POINT su ec2-user <file_sep>/AWS-VNP-WireGuard/code/user_data.sh #!/bin/bash git clone https://github.com/pprometey/wireguard_aws.git /home/ubuntu/wireguard_aws chown -R ubuntu:ubuntu /home/ubuntu/wireguard_aws # remove.sh cd /home/ubuntu/wireguard_aws && sh remove.sh # install.sh apt install software-properties-common -y add-apt-repository ppa:wireguard/wireguard -y apt update apt install wireguard-dkms wireguard-tools qrencode -y NET_FORWARD="net.ipv4.ip_forward=1" sysctl -w ${NET_FORWARD} sed -i "s:#${NET_FORWARD}:${NET_FORWARD}:" /etc/sysctl.conf cd /etc/wireguard umask 077 SERVER_PRIVKEY=$( wg genkey ) echo $SERVER_PRIVKEY > ./server_private.key SERVER_PUBKEY=$( echo $SERVER_PRIVKEY | wg pubkey ) echo $SERVER_PUBKEY > ./server_public.key ENDPOINT=$(host myip.opendns.com resolver1.opendns.com | grep "myip.opendns.com has" | awk '{print $4}') echo "$ENDPOINT:54321" > ./endpoint.var SERVER_IP="10.50.0.1" echo $SERVER_IP | grep -o -E '([0-9]+\.){3}' > ./vpn_subnet.var DNS="1.1.1.1" echo $DNS > ./dns.var echo 1 > ./last_used_ip.var WAN_INTERFACE_NAME="eth0" echo $WAN_INTERFACE_NAME > ./wan_interface_name.var cat ./endpoint.var | sed -e "s/:/ /" | while read SERVER_EXTERNAL_IP SERVER_EXTERNAL_PORT do cat > ./wg0.conf.def << EOF [Interface] Address = $SERVER_IP SaveConfig = false PrivateKey = $SERVER_PRIVKEY ListenPort = $SERVER_EXTERNAL_PORT PostUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -A FORWARD -o %i -j ACCEPT; iptables -t nat -A POSTROUTING -o $WAN_INTERFACE_NAME -j MASQUERADE; PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -D FORWARD -o %i -j ACCEPT; iptables -t nat -D POSTROUTING -o $WAN_INTERFACE_NAME -j MASQUERADE; EOF done cp -f ./wg0.conf.def ./wg0.conf systemctl enable wg-quick@wg0 <file_sep>/AWS-EBS-Attach-Mount/Readme.md ### Prerequisites How to launch an Instance with Attached and Mounted EBS volume in AWS Cloud? <br> Here's a simple Terraform template with a boot-strapping/user-data script you may use. It works for me and I find it useful for others. ### Commands to execute Create ssh-keys: ``` mkdir .ssh-keys ssh-keygen ``` Terraform commands: ``` terraform init terraform plan terraform apply terraform destroy ``` ### Commands to check the results To make ssh-connect: <br> `ssh -i .ssh-keys/ssh-key ec2-user@<server-ip>` To check the results: ``` lsblk cat /etc/fstab ls -la / | grep data df /data/ ``` If you haven't seen the results please wait for at least 2 minutes to check disk is mounted. #### Resulting screenshots ssh-connect && result confirmation: <img src="instance.png"><br> ### Links of used resources <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/volume_attachment">Resource: aws_volume_attachment</a> <br> <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-using-volumes.html">Make an Amazon EBS volume available for use on Linux</a> <br> <a href="https://github.com/adv4000/terraform-lessons">Terraform Lessons by <NAME></a> ### Issues 1. For now, the mounting process included in `run.sh` starts after 120 sec after the instance was added. It's more much better to run by the event of EBS-volume attachment. 2. In different regions, the value of AMI filter in `data.tf` may differ. 3. There's no elastic IP on the template. If you are going to stop the instance you created via template its IP address may be changed while starting. But it will work after the reboot of the instance. 4. I have Terraform version of `Terraform v0.15.0`. In earlier versions, especially in v0.12 and older ones, it won't work. <file_sep>/AWS-VNP-WireGuard/Readme.md ### Prerequisites How to Launch WireGuard VPN-Server on AWS Instance via Terraform. <br> Here's a simple Terraform template with a boot-strapping/user-data script you may use. It works for me and I find it useful for others. ### Commands to execute Create ssh-keys: ``` mkdir .ssh-keys ssh-keygen ``` Launch and stop VPN-Server via Terraform: ``` cd Terraform-Cheatsheet/AWS-VNP-WireGuard/ ./vpn-server apply ./vpn-server destroy ``` Add user on remote-server: ``` cd wireguard_aws/ sudo sh add-client.sh ``` ### Result Scan QR-code using WireGuard app from AppStore or Google Play on the phone/tablet or pass credentials to the app on Mac/PC. <br> <img src="instance.png"> ##### <center>Relax!</center> ### Links of used resources <a href="https://github.com/pprometey/wireguard_aws"><NAME>'s Github</a> <br> <a href="https://habr.com/ru/post/448528/">The article about manual deployment in Russian</a> ### Issues - It takes about extra 10 seconds for `user_data.sh` to be completed after ssh-connect. Please wait. - In different regions, the value of AMI filter in `data.tf` may differ. - I have Terraform version of `Terraform v0.15.0`. In earlier versions, especially in v0.12 and older ones, it will not work. <file_sep>/AWS-VNP-OpenVPN/Readme.md ### Prerequisites How to Launch OpenVPN-Server on AWS Instance via Terraform. Here's a simple Terraform template with a <a href="https://openvpn.net/vpn-software-packages/">user-data</a> applied to AWS Linux-2 instance. ### Commands to execute Create ssh-keys: ``` mkdir .ssh-keys ssh-keygen // choose ssh-key ``` Terraform commands: ``` terraform init terraform plan terraform apply terraform destroy ``` You have to set password for `openvpn` admin-user by ssh-connect: ``` ssh -i .ssh-keys/ssh-key ec2-user@<public-ip> // sudo passwd openvpn ``` ### Result - Go to admin consul - Configure Network, VPN-Server, users, and get VPN-Client - Relax <file_sep>/AWS-VNP-OpenVPN/code/run.sh #!/bin/bash sudo yum -y update sudo yum -y upgrade yum -y remove openvpn-as-yum yum -y install https://as-repository.openvpn.net/as-repo-amzn2.rpm yum -y install openvpn-as <file_sep>/Readme.md ### About Repository Here's a cheat sheet with notes about Terraform applied to AWS Cloud. <br> I hope you will find this useful. <file_sep>/AWS-VNP-WireGuard/vpn-server #!/bin/bash if [[ $1 = "apply" ]]; then cd ./code && terraform apply -auto-approve export HOST=`cat ./terraform.tfstate | grep '"public_ip"' | awk -F '"' '{print $4; exit}'` sleep 90 ssh -o StrictHostKeyChecking=no -i ./.ssh-keys/ssh-key $HOST -l ubuntu elif [[ $1 = "destroy" ]]; then cd ./code && terraform destroy -auto-approve elif [[ $1 = "plan" ]]; then cd ./code && terraform plan else echo "Please set one of:" echo " plan" echo " apply" echo " destroy" fi
c3aa87c8509a3ac7048ab4b2d9ae3342e254e482
[ "Markdown", "Shell" ]
8
Shell
abdibus/Terraform-Cheatsheet
5ddec3f65402fcac2377988544269df7e2a77ded
cf43ef9546592ab6dd8b9be7fd981dad569512ad
refs/heads/master
<repo_name>xpj624/node-practice<file_sep>/app.js var express = require('express'); var superagent = require('superagent'); var cheerio = require('cheerio'); var fs = require('fs'); var app = express(); app.get('/', function(req, res, next) { // 用 superagent 去抓取 https://cnodejs.org/ 的内容 superagent.get('https://cnodejs.org/') .end(function(err, sres) { // 常规的错误处理 if (err) { return next(err); } // sres.text 里面存储着网页的 html 内容,将它传给 cheerio.load 之后 // 就可以得到一个实现了 jquery 接口的变量,我们习惯性地将它命名为 `$` // 剩下就都是 jquery 的内容了 var $ = cheerio.load(sres.text); var items = []; $('#topic_list .topic_title, #topic_list .user_avatar').each(function(idx, element) { var $element = $(element); var pos = items.length; if ($element.hasClass('pull-left')) { items[pos] = {}; items[pos].user = $element.attr('href').slice(6); } else { items[pos - 1].title = $element.attr('title'); items[pos - 1].href = $element.attr('href'); } // items.push({ // title: $element.attr('title'), // href: $element.attr('href') // }); }); console.log('把数据写入访问的页面'); res.send(items); // 把数据写入访问的页面 // 向result.json文件写入内容,先将对象转换为json字符串 const buf = Buffer.alloc(1024); fs.writeFile('result.json', JSON.stringify(items), buf, function(err) { if (err) { return console.error(err); } console.log('数据写入成功'); }); }); }); app.listen(3000, function(req, res) { console.log('app is running at port 3000'); }); <file_sep>/README.md # 使用 superagent 与 cheerio 完成简单爬虫 当在浏览器中访问 ``http://localhost:3000/`` 时,输出 CNode(https://cnodejs.org/ ) 社区首页的所有帖子标题和链接,以 json 的形式。 输出示例: ``` [ { "title": "【公告】发招聘帖的同学留意一下这里", "href": "http://cnodejs.org/topic/541ed2d05e28155f24676a12" }, { "title": "发布一款 Sublime Text 下的 JavaScript 语法高亮插件", "href": "http://cnodejs.org/topic/54207e2efffeb6de3d61f68f" } ] ```
66e1f1fe14668b1549430315c17811dc297d53b0
[ "JavaScript", "Markdown" ]
2
JavaScript
xpj624/node-practice
e8c91375161c3f697b439abab917f9a7cb91fbc9
e832a7a5e66b4764570089dce5d41e5b0c4fa32f
refs/heads/master
<file_sep># Chord-P2P-Architecture Python implementation of chord p2p protocol <file_sep>import socket import os import sys from Server import Server,client_connection ip = raw_input("Ip of connecting Node: ") ip = str(ip) port = raw_input("Type port to use: ") port = int(port) mBit = raw_input("Power of size in your ring: ") mBit = int(mBit) total_node = 2**mBit threads = [] finger = [-1 for i in range(mBit)] predecessor = None active_server = Server(ip, port,total_node, predecessor,mBit,finger) active_server.start() threads.append(active_server) while True: x = raw_input("chord>> ") if x=="": continue x = x.strip() x = x.split() if x[0]=="print": print ip,port,active_server.predecessor print active_server.finger_table elif x[0]=="create_ring": active_server.create_ring() print "Ring created with only node in it",active_server.position elif x[0]=="join": active_server.joinNode(x[1],x[2]) print "Node joined succesfully" elif x[0]=="find": print active_server.find_succesor(x[1]) elif x[0]=="add_key": print active_server.add_key(x[1]) elif x[0]=="find_key": print "Required key is present on ", active_server.find_key(x[1]) elif x[0]=="print_table": active_server.print_key_table() elif x[0]=="close": active_server.take_my_keys() active_server.dead = True client_connection(ip,port,"close") # quit() break elif x[0]=="print_hb": print active_server.hb_ip print active_server.hb_port print active_server.suc_hb_ip print active_server.suc_hb_port # active_server.join()
2e6953907b812c7722fa1e136a1b7e9938cfee83
[ "Markdown", "Python" ]
2
Markdown
jainayush975/Chord-P2P-Architecture
bbee6c4a843da92f51518795da0246f148ee56f7
4ed25b1fcab65aaf706db74ac7d3fa1623ddc464
refs/heads/master
<repo_name>j90115j/farm4.0<file_sep>/mainsite/fmqtt2.py import paho.mqtt.client as mqtt from .models import tlight, thumi, ttemp, tsoil import time import decimal # import pandas as pd # import numpy as np read_photocell=False read_temp=False read_humi=False read_tempf=False read_soil=False light=[] temp=[] humi=[] soil=[] # a=np.array([1,2,3,4,5]) # df = pd.DataFrame(a) # df.columns=["photocell","temp","humi","tempf","soil"] # 當地端程式連線伺服器得到回應時,要做的動作 def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) # 將訂閱主題寫在on_connet中 # 如果我們失去連線或重新連線時 # 地端程式將會重新訂閱 client.subscribe("command") # 當接收到從伺服器發送的訊息時要進行的動作 def on_message(client, userdata, msg): # 轉換編碼utf-8才看得懂中文 #print(msg.topic+" "+ msg.payload.decode('utf-8')) global read_photocell,read_temp,read_humi,read_tempf,read_soil if msg.payload.decode('utf-8')=='photocellVal': read_photocell=True elif msg.payload.decode('utf-8')=='temp': read_temp=True elif msg.payload.decode('utf-8')=='humi': read_humi=True elif msg.payload.decode('utf-8')=='tempf': read_tempf=True elif msg.payload.decode('utf-8')=='soil_sensorValue': read_soil=True elif msg.payload.decode('utf-8')=='photo': print("") else: if read_photocell: read_photocell=False # print("photocell="+msg.payload.decode('utf-8')) tmp = str(msg.payload.decode('utf-8')) tmp = decimal.Decimal(tmp).quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_DOWN) light.append(tmp) tlight(light=tmp).save() elif read_temp: read_temp=False tmp = str(msg.payload.decode('utf-8')) tmp = decimal.Decimal(tmp).quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_DOWN) temp.append(tmp) ttemp(temp=tmp).save() elif read_humi: read_humi=False tmp = str(msg.payload.decode('utf-8')) tmp = decimal.Decimal(tmp).quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_DOWN) humi.append(tmp) thumi(humi=tmp).save() elif read_tempf: read_tempf=False tempf = msg.payload.decode('utf-8') elif read_soil: read_soil=False tmp = str(msg.payload.decode('utf-8')) tmp = decimal.Decimal(tmp).quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_DOWN) soil.append(tmp) tsoil(soil=tmp).save() # 連線設定 # 初始化地端程式 client = mqtt.Client() # 設定連線的動作 client.on_connect = on_connect # 設定接收訊息的動作 client.on_message = on_message # 設定登入帳號密碼 # client.username_pw_set("1234","123") # 設定連線資訊(IP, Port, 連線時間) client.connect("127.0.0.1", 1883, 60) # client.connect("172.16.58.3", 1883, 60) # client.connect("192.168.50.246", 1883, 60) # 開始連線,執行設定的動作和處理重新連線問題 # 也可以手動使用其他loop函式來進行連接 # client.loop_forever()<file_sep>/mainsite/models.py from django.db import models from django.utils import timezone # Create your models here. # class Post(models.Model): # title = models.CharField(max_length=200) # slug = models.CharField(max_length=200) # body = models.TextField() # pub_date = models.DateTimeField(default=timezone.now) # class Meta: # ordering = ('-pub_date',) # def __str__(self): # return self.title class IMG(models.Model): # upload_to為圖片上傳的路徑,不存在就創建一個新的。 img_url = models.ImageField(upload_to='img') class tlight(models.Model): time = models.DateTimeField(auto_now_add=True) light = models.FloatField() def __str__(self): return self.title class ttemp(models.Model): time = models.DateTimeField(auto_now_add=True) temp = models.FloatField() def __str__(self): return self.title class thumi(models.Model): time = models.DateTimeField(auto_now_add=True) humi = models.FloatField() def __str__(self): return self.title class tsoil(models.Model): time = models.DateTimeField(auto_now_add=True) soil = models.FloatField() def __str__(self): return self.title<file_sep>/mainsite/views.py from django.shortcuts import render, redirect from django.http import HttpResponse from .models import IMG, tlight, thumi, ttemp, tsoil from datetime import datetime from DrPlant.settings import BASE_DIR from tensorflow.keras.models import load_model from PIL import Image from skimage import transform import os import numpy as np import tensorflow as tf from . import fmqtt2 fmqtt2.client.loop_start() fpath = os.path.join(BASE_DIR, 'static')+'/' config = tf.compat.v1.ConfigProto( device_count={'CPU': 2}, intra_op_parallelism_threads=1, allow_soft_placement=True ) session = tf.compat.v1.Session(config=config) tf.compat.v1.keras.backend.set_session(session) model = load_model(filepath=fpath+'98%.hdfS') # import pymysql # Create your views here. def showindex(request): now = datetime.now() # # 打开数据库连接 # db = pymysql.connect("localhost","test123","test123","aiotdb" ) # # 使用 cursor() 方法创建一个游标对象 cursor # cursor = db.cursor() # # 使用 execute() 方法执行 SQL 查询 # cursor.execute("select * from sensors") # # 使用 fetchone() 方法获取单条数据. # data = cursor.fetchall() # time = [str(rows[1]) for rows in data] # light = [rows[2] for rows in data] # now_light = data[-1][2] # temp = [rows[3] for rows in data] # now_temp = data[-1][3] # humid = [rows[4] for rows in data] # now_humid = data[-1][4] # soil_moisture = [rows[5] for rows in data] # now_soil_moisture = data[-1][5] # # 关闭数据库连接 # cursor.close() # db.close() light = [] temp = [] humid = [] soil_moisture = [] time_light = [] time_temp = [] time_humid = [] time_soil_moisture = [] for i in (tlight.objects.values_list('time', flat=True)[::-1])[:10]: time_light.append(i) now_light_time = time_light[0] time_light = time_light[::-1] for i in (tlight.objects.values_list('light', flat=True)[::-1])[:10]: light.append(i) now_light = light[0] light = light[::-1] for i in (ttemp.objects.values_list('time', flat=True)[::-1])[:10]: time_temp.append(i) now_temp_time = time_temp[0] time_temp = time_temp[::-1] for i in (ttemp.objects.values_list('temp', flat=True)[::-1])[:10]: temp.append(i) now_temp = temp[0] temp = temp[::-1] for i in (thumi.objects.values_list('time', flat=True)[::-1])[:10]: time_humid.append(i) now_humid_time = time_humid[0] time_humid = time_humid[::-1] for i in (thumi.objects.values_list('humi', flat=True)[::-1])[:10]: humid.append(i) now_humid = humid[0] humid = humid[::-1] for i in (tsoil.objects.values_list('time', flat=True)[::-1])[:10]: time_soil_moisture.append(i) now_soil_moisture_time = time_soil_moisture[0] time_soil_moisture = time_soil_moisture[::-1] for i in (tsoil.objects.values_list('soil', flat=True)[::-1])[:10]: soil_moisture.append(i) now_soil_moisture = soil_moisture[0] soil_moisture = soil_moisture[::-1] if request.method == 'POST': img = IMG(img_url=request.FILES.get('img')) img.save() imgs = IMG.objects.all() last = imgs[len(imgs)-1] tt = last return render(request, 'index.html', locals()) return render(request, 'index.html', locals()) # 清除圖片 def imgShow(request): imgs = IMG.objects.all() for i in imgs: os.remove(BASE_DIR+i.img_url.url) i.delete() # os.remove(BASE_DIR+imgs[len(imgs)-1].img_url.url) # imgs.delete() context = { 'imgs' : imgs } return render(request, 'imgShow.html', locals()) def detect(request): if request.method == 'POST': img = IMG(img_url=request.FILES.get('img')) img.save() imgs = IMG.objects.all()[::-1][0].img_url.url # file= fpath+'Septoria_leaf_spot.JPG' file = BASE_DIR+imgs # msgfmqtt = fmqtt.get_msg() np_image = Image.open(file) np_image = np.array(np_image).astype('float32')/255 np_image = transform.resize(np_image, (299,299,3)) image = np.expand_dims(np_image, axis=0) with session.as_default(): with session.graph.as_default(): pred = model.predict(image) labels={0: 'Bacterial_spot', 1: 'Early_blight', 2: 'Late_blight', 3: 'Leaf_Mold', 4: 'Septoria_leaf_spot', 5: 'Spider_mites Two-spotted_spider_mite', 6: 'Target_Spot', 7: 'Yellow_Leaf_Curl_Virus', 8: 'Mosaic_virus', 9: 'Healthy'} predt=np.sort(-pred.reshape(-1)) tmp=[] for i in predt[:3]: for j, k in zip(range(10), pred.reshape(-1)): if -i==k: tmp.append(labels[j]) tmp.append(k) break t0 = tmp[0] t1 = tmp[1] t2 = tmp[2] t3 = tmp[3] t4 = tmp[4] t5 = tmp[5] return render(request, 'detect.html', locals()) def dbtest(request): light = [] for i in tlight.objects.values_list('light', flat=True): light.append(i) now_light = light[-1] # light = list(tlight.objects.all()) # light = tlight.objects.all().values # light = tlight.objects.values_list('light', flat=True) # n_light= light[-1] # tlight(light=342).save() # tlight(light=12).save() return render(request, 'dbtest.html', locals()) <file_sep>/mainsite/migrations/0004_auto_20200620_1427.py # Generated by Django 3.0.7 on 2020-06-20 06:27 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mainsite', '0003_auto_20200620_1126'), ] operations = [ migrations.CreateModel( name='thumi', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('time', models.DateTimeField(auto_now_add=True)), ('humi', models.FloatField()), ], ), migrations.CreateModel( name='tlight', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('time', models.DateTimeField(auto_now_add=True)), ('light', models.FloatField()), ], ), migrations.CreateModel( name='tsoil', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('time', models.DateTimeField(auto_now_add=True)), ('soil', models.FloatField()), ], ), migrations.CreateModel( name='ttemp', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('time', models.DateTimeField(auto_now_add=True)), ('temp', models.FloatField()), ], ), migrations.DeleteModel( name='Sensors', ), ] <file_sep>/mainsite/migrations/0003_auto_20200620_1126.py # Generated by Django 3.0.7 on 2020-06-20 03:26 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mainsite', '0002_img'), ] operations = [ migrations.CreateModel( name='Sensors', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('time', models.DateTimeField(auto_now_add=True)), ('light', models.FloatField()), ('temp', models.FloatField()), ('humid', models.FloatField()), ('soil_moisture', models.FloatField()), ], ), migrations.DeleteModel( name='Post', ), ]
64b88196c2f334a3ae90ff6e7876109d43e99c3a
[ "Python" ]
5
Python
j90115j/farm4.0
9f22d4312e1c07563ec2293b6330d72612bf00fa
8defd7ea7b696e9b6ec5b50749801d5a83301bf6
refs/heads/master
<repo_name>terminusdb/terminus-dashboard<file_sep>/public_pages.sh #!/bin/bash echo "___SONO IN SCRIPT____" PUBLICATION_BRANCH=gh-pages # Checkout the branch REPO_PATH=$PWD echo "$REPO_PATH" pushd "$HOME" || exit git clone --branch=$PUBLICATION_BRANCH "https://${GITHUB_TOKEN}@github.com/$TRAVIS_REPO_SLUG" tmp_pages 2>&1 > /dev/null cd tmp_pages || exit rm -rf ./1.1.10 echo 'package=$PACKAGE_VERSION' # Update pages cp -r $REPO_PATH/public_pages/. . rm -rf ./dist/* cp -r $REPO_PATH/public_pages/$PACKAGE_VERSION/dist/* ./dist # Commit and push latest version git add . git config user.name "Travis" git config user.email "<EMAIL>" git commit -m "Updated version." git push -fq origin $PUBLICATION_BRANCH 2>&1 > /dev/null popd || exit <file_sep>/src/ApiExplorer.js /** * @file Javascript Api explorer tool * @author <NAME> * @license Copyright 2018-2019 Data Chemist Limited, All Rights Reserved. See LICENSE file for more * * @summary Displays a demo and description of api calls from WOQLCLient and what happens under the hood of api calls */ const TerminusPluginManager = require('./plugins/TerminusPlugin'); const UTILS = require('./Utils'); const TerminusClient = require('@terminusdb/terminus-client'); const HTMLHelper = require('./html/HTMLHelper'); let apiNavConfig = { mainNav: { connect: { navText: 'Connect API', action : 'connect', icon : 'link', defaultSelected: true }, database: { navText: 'Database API', action : 'create', icon : 'database' }, schema: { navText: 'Schema API', action : 'schema', icon : 'cog' }, document: { navText: 'Document API', action : 'document', icon : 'file' }, query: { navText: 'Query API', action : 'query', icon : 'search' } }, subNav: { database: { createDatabase: { navText: 'Create database', action : 'create', icon : 'plus', defaultSelected: true }, deleteDatabase: { navText: 'Delete database', action : 'delete', icon : 'trash-alt' } }, schema: { getSchema: { navText: 'View Schema', action : 'getSchema', icon : 'eye', defaultSelected: true }, updateSchema: { navText: 'Update Schema', action : 'updateSchema', icon : 'arrow-up' }, getClassFrames: { navText: 'Get Class Frames', action : 'getClassFrames', icon : 'share-alt' } }, document: { viewDocument: { navText: 'View Document', action : 'viewDocument', icon : 'eye', defaultSelected: true }, createDocument: { navText: 'Create Document', action : 'createDocument', icon : 'plus' }, updateDocument: { navText: 'Update Document', action : 'updateDocument', icon : 'arrow-up' }, deleteDocument:{ navText: 'Delete Document', action : 'deleteDocument', icon : 'trash-alt' } }, query: { select: { navText: 'Select', action : 'select', icon : 'mouse-pointer', defaultSelected: true }, update: { navText: 'Update', action : 'update', icon : 'arrow-up' } } } } function ApiExplorer(ui){ this.ui = ui; this.viewer = ui.mainDOM; this.client = new TerminusClient.WOQLClient(); this.client.use_fetch = true; this.client.return_full_response = true; this.pman = new TerminusPluginManager(); } // Controller provides access to Api explorer functions ApiExplorer.prototype.getAsDOM = function(){ var aec = document.createElement("div"); aec.setAttribute("class", "terminus-db-controller"); if(this.ui){ this.getApiNav(aec, this.viewer); // nav this.getApiExplorerDom('connect', this.viewer); // content dom } // if this.ui return aec; } /***** Api Nav bar *****/ // Toggle selected nav bars ApiExplorer.prototype.setSelectedNavMenu = function(a){ UTILS.removeSelectedNavClass("terminus-selected"); a.classList.add("terminus-selected"); } ApiExplorer.prototype.navOnSelect = function(action, nav, viewer){ UTILS.removeSelectedNavClass("terminus-selected"); nav.classList.add("terminus-selected"); this.getApiExplorerDom(action, viewer); } // create nav bars ApiExplorer.prototype.createNavs = function(navConfig, viewer, ul){ var a = document.createElement('a'); a.setAttribute('class', 'terminus-a terminus-list-group-a terminus-list-group-a-action terminus-nav-width terminus-pointer'); if(navConfig.defaultSelected) a.classList.add('terminus-selected'); var self = this; a.addEventListener("click", function(){ self.navOnSelect(navConfig.action, this, viewer); }) var icon = document.createElement('i'); icon.setAttribute('class', 'terminus-menu-icon fa fa-' + navConfig.icon); a.appendChild(icon); var txt = document.createTextNode(navConfig.navText); a.appendChild(txt); ul.appendChild(a); } // gets api nav bar ApiExplorer.prototype.getApiNav = function(navDom, viewer){ // list view of apis var nav = document.createElement('div'); navDom.appendChild(nav); // connect to server api var ul = document.createElement('ul'); ul.setAttribute('class', 'terminus-ul'); nav.appendChild(ul); // loop over apiNavConfig for (var key in apiNavConfig.mainNav){ if (apiNavConfig.mainNav.hasOwnProperty(key)) { this.createNavs(apiNavConfig.mainNav[key], viewer, ul); } } // for apiNavConfig return navDom; } // getApiNav() /***** Api sub navs *****/ // get schema api explorer - nav bar, alert msg, headers ... ApiExplorer.prototype.getApiExplorerDom = function(view, viewer){ // clear of viewer HTMLHelper.removeChildren(viewer); // wrapper var wrap = document.createElement('div'); //wrap.setAttribute('class', 'terminus-wrapper terminus-wrapper-height'); viewer.appendChild(wrap); var cont = document.createElement('div'); cont.setAttribute('class', 'container-fluid'); wrap.appendChild(cont); var row = document.createElement('div'); row.setAttribute('class', 'row-fluid'); cont.appendChild(row); var body = document.createElement('div'); body.setAttribute('class', 'terminus-module-body'); row.appendChild(body); var api = document.createElement('div'); api.setAttribute('class', 'terminus-module-body terminus-module-body-white-bg terminus-module-body-width'); body.appendChild(api); // body var cont = document.createElement('div'); var self = this; switch(view){ case 'connect': var apiCont = self.getConnectExplorer(cont); api.appendChild(apiCont); break; case 'create': var apiCont = self.getDatabaseExplorer(cont); api.appendChild(apiCont); break; case 'schema': var apiCont = self.getSchemaApi(cont); api.appendChild(apiCont); break; case 'document': var apiCont = self.getDocumentApi(cont); api.appendChild(apiCont); break; case 'query': var apiCont = self.getQueryApi(cont); api.appendChild(apiCont); break; }// switch(api) return wrap; } // getApiExplorerDom // on trigger of click event - change dom ApiExplorer.prototype.changeSubApiDom = function(curSubMenu, action, cont, body){ HTMLHelper.removeChildren(body); switch(curSubMenu){ case 'database': var dom = this.getDatabaseDom(action, body); break; case 'schema': // getShowApiDom() deals with schema and document var dom = this.getShowApiDom(action, body); break; case 'document': // getShowApiDom() deals with schema and document var dom = this.getShowApiDom(action, body); break; case 'query': var dom = this.getQueryApiDom(action, body); break; default: console.log('Invalid Api Config'); break; } cont.appendChild(dom); } ApiExplorer.prototype.subNavOnSelect = function(curSubMenu, subMenuConfig, subNav, cont, body){ UTILS.setSelectedSubMenu(subNav); this.changeSubApiDom(curSubMenu, subMenuConfig.action, cont, body); } // create sub nav bars ApiExplorer.prototype.createSubNavs = function(curSubMenu, subMenuConfig, cont, body, ul){ // comment getclassframes for api explorer time being if(subMenuConfig.action == 'getClassFrames') return; var a = document.createElement('a'); a.setAttribute('class', 'terminus-a terminus-hz-list-group-a terminus-list-group-a-action terminus-nav-width terminus-pointer'); if(subMenuConfig.defaultSelected) a.classList.add('terminus-submenu-selected'); var self = this; a.addEventListener("click", function() { self.subNavOnSelect(curSubMenu, subMenuConfig, this, cont, body); }) var icon = document.createElement('i'); icon.setAttribute('class', 'terminus-menu-icon fa fa-' + subMenuConfig.icon); a.appendChild(icon); var txt = document.createTextNode(subMenuConfig.navText); a.appendChild(txt); ul.appendChild(a); } // get connect to server api calls - on click of connectAPI nav bar ApiExplorer.prototype.getConnectExplorer = function(body){ var self = this; var br = document.createElement('BR'); body.appendChild(br); // get signature var b = this.getSignature('connect'); body.appendChild(b); // get header Parameter body.appendChild(UTILS.getHeaderDom('Parameters')); var br = document.createElement('BR'); body.appendChild(br); //form to get server url this.getForm( '', body, true, 'connect', 'URL : server_url'); //body.appendChild(form); return body; } // getConnectExplorer // get database api calls - on click of databaseAPI nav bar - submenus of database Api defined here ApiExplorer.prototype.getDatabaseExplorer = function(cont){ var body = document.createElement('div'); // list view of Databse tools var ul = document.createElement('ul'); ul.setAttribute('class','terminus-ul-horizontal'); // loop over apiNavConfig for (var key in apiNavConfig.subNav.database){ if (apiNavConfig.subNav.database.hasOwnProperty(key)) this.createSubNavs('database', apiNavConfig.subNav.database[key], cont, body, ul); } // for apiNavConfig cont.appendChild(ul); // landing page var dom = this.getDatabaseDom(apiNavConfig.subNav.database.createDatabase.action, body); cont.appendChild(dom); return cont; } // getDatabaseExplorer // get schema api calls - on click of SchemaAPI nav bar - submenus of schema Api defined here ApiExplorer.prototype.getSchemaApi = function(cont){ var body = document.createElement('div'); // list view of Databse tools var ul = document.createElement('ul'); ul.setAttribute('class','terminus-ul-horizontal'); // loop over apiNavConfig for (var key in apiNavConfig.subNav.schema){ if (apiNavConfig.subNav.schema.hasOwnProperty(key)) { this.createSubNavs('schema', apiNavConfig.subNav.schema[key], cont, body, ul); } } // for apiNavConfig cont.appendChild(ul); var dom = this.getShowApiDom(apiNavConfig.subNav.schema.getSchema.action, body); cont.appendChild(dom); return cont; } // getSchemaApi // get document api calls - on click of DocumentAPI nav bar ApiExplorer.prototype.getDocumentApi = function(cont){ var body = document.createElement('div'); // list view of Databse tools var ul = document.createElement('ul'); ul.setAttribute('class','terminus-ul-horizontal'); // loop over apiNavConfig for (var key in apiNavConfig.subNav.document){ if (apiNavConfig.subNav.document.hasOwnProperty(key)) { this.createSubNavs('document', apiNavConfig.subNav.document[key], cont, body, ul); } } // for apiNavConfig cont.appendChild(ul); var dom = this.getShowApiDom(apiNavConfig.subNav.document.viewDocument.action, body); cont.appendChild(dom); return cont; } // getDocumentApi // get query api calls - on click of QueryAPI nav bar - submenus of Query Api defined here ApiExplorer.prototype.getQueryApi = function(cont){ var body = document.createElement('div'); // list view of Databse tools var ul = document.createElement('ul'); ul.setAttribute('class','terminus-ul-horizontal'); // loop over apiNavConfig for (var key in apiNavConfig.subNav.query){ if (apiNavConfig.subNav.query.hasOwnProperty(key)) { this.createSubNavs('query', apiNavConfig.subNav.query[key], cont, body, ul); } } // for apiNavConfig cont.appendChild(ul); var dom = this.getQueryApiDom(apiNavConfig.subNav.query.select.action, body); cont.appendChild(dom); return cont; } //getQueryApi /***** Api Content view *****/ // get database dom ApiExplorer.prototype.getDatabaseDom = function(mode, body){ var self = this; var br = document.createElement('BR'); body.appendChild(br); // get signature var b = this.getSignature(mode); body.appendChild(b); // get header Parameter body.appendChild(UTILS.getHeaderDom('Parameters')); var br = document.createElement('BR'); body.appendChild(br); //form to get database id if(mode == 'create') this.getForm( null, body, false, mode, 'URL : server/database_id'); else this.getForm( null, body, true, mode, 'URL : server/database_id'); return body; } // getConnectExplorer //get create & delete db form ApiExplorer.prototype.getServerForm = function(){ // form var form = document.createElement('form'); form.setAttribute('class', 'terminus-form-horizontal row-fluid'); var fd = document.createElement('div'); fd.setAttribute('class', 'terminus-control-group'); form.appendChild(fd); var inpLabel = document.createElement('label'); inpLabel.setAttribute('class', 'terminus-control-label'); inpLabel.setAttribute('for', 'basicinput'); inpLabel.innerHTML = 'Url:'; fd.appendChild(inpLabel); var cd = document.createElement('div'); cd.setAttribute('class', 'terminus-controls'); fd.appendChild(cd); var inpId = document.createElement('input'); inpId.setAttribute('type', 'text'); inpId.setAttribute('id', 'basicinput'); inpId.setAttribute('class', 'terminus-input-text'); inpId.setAttribute('placeholder', 'URL : server_url'); if(this.val) inpId.value = this.val; cd.appendChild(inpId); var fd = document.createElement('div'); fd.setAttribute('class', 'terminus-control-group'); form.appendChild(fd); var keyLabel = document.createElement('label'); keyLabel.setAttribute('class', 'terminus-control-label'); keyLabel.setAttribute('for', 'basicinput'); keyLabel.innerHTML = 'Key:'; fd.appendChild(keyLabel); var cd = document.createElement('div'); cd.setAttribute('class', 'terminus-controls'); fd.appendChild(cd); var key = document.createElement('input'); key.setAttribute('type', 'text'); key.setAttribute('id', 'basicinput'); key.setAttribute('class', 'span8 terminus-input-text'); key.setAttribute('placeholder', 'Key : key'); if(this.val) key.value = this.val; cd.appendChild(key); var button = document.createElement('button'); button.setAttribute('class', 'terminus-btn terminus-send-api-btn'); button.setAttribute('type', 'button'); button.innerHTML = 'Send Api'; var gatherips = function(){ var input = {}; input.url = inpId.value; input.key = key.value; return input; } var resd = document.createElement('div'); form.appendChild(button); form.appendChild(resd); var self = this; button.addEventListener("click", function(){ var buttonSelf = this; //opts = {}; var input = gatherips(); self.client.connect(input.url, input.key) .then(function(response){ HTMLHelper.removeChildren(resd); var resultDom = UTILS.showHttpResult(response, 'connect', resd, self.ui); }); }) // button click return form; } // getServerForm() // get database api calls - on click of databaseAPI nav bar - submenus of database Api defined here ApiExplorer.prototype.getDatabaseExplorer = function(cont){ var body = document.createElement('div'); // list view of Databse tools var ul = document.createElement('ul'); ul.setAttribute('class','terminus-ul-horizontal'); // loop over apiNavConfig for (var key in apiNavConfig.subNav.database){ if (apiNavConfig.subNav.database.hasOwnProperty(key)) { this.createSubNavs('database', apiNavConfig.subNav.database[key], cont, body, ul); } } // for apiNavConfig cont.appendChild(ul); // landing page var dom = this.getDatabaseDom(apiNavConfig.subNav.database.createDatabase.action, body); cont.appendChild(dom); return cont; } // getDatabaseExplorer // get schema & document dom ApiExplorer.prototype.getShowApiDom = function(action, body){ var self = this; var br = document.createElement('BR'); body.appendChild(br); // signature var b = this.getSignature(action); body.appendChild(b); // get header Parameter body.appendChild(UTILS.getHeaderDom('Parameters')); var br = document.createElement('BR'); body.appendChild(br); // get input switch(action){ case 'getSchema': this.getForm( 'schema', body, true, action, 'URL : server/database_id'); break; case 'getClassFrames': this.getForm( 'getClassFrames', body, true, action, 'URL : server/database_id'); break; case 'updateSchema': this.getForm( 'schema', body, false, action, 'URL : server/database_id'); break; case 'viewDocument': this.getForm('document', body, true, action, 'URL : server/database_id/document/document_id'); break; case 'deleteDocument': this.getForm('document', body, true, action, 'URL : server/database_id/document/document_id'); break; case 'createDocument': this.getForm('document', body, false, action, 'URL : server/database_id/document/document_id'); break; case 'updateDocument': this.getForm('document', body, false, action, 'URL : server/database_id/document/document_id'); break; default: console.log('Invalid Api Call on form'); break; }// switch(action) return body; } // getShowApiDom() // get query api dom ApiExplorer.prototype.getQueryApiDom = function(action, body){ var br = document.createElement('BR'); body.appendChild(br); // signature var b = this.getSignature(action); body.appendChild(b); // get header Parameter body.appendChild(UTILS.getHeaderDom('Parameters')); var br = document.createElement('BR'); body.appendChild(br); this.getForm( 'query', body, false, action, 'URL : server/database_id'); return body; } // getQueryApiDom /*ApiExplorer.prototype.getClassFramesForm = function(){ // form var form = document.createElement('form'); form.setAttribute('class', 'terminus-form-horizontal row-fluid'); var fd = document.createElement('div'); fd.setAttribute('class', 'terminus-control-group'); form.appendChild(fd); var inpLabel = document.createElement('label'); inpLabel.setAttribute('class', 'terminus-control-label'); inpLabel.setAttribute('for', 'basicinput'); inpLabel.innerHTML = 'Url:'; fd.appendChild(inpLabel); var cd = document.createElement('div'); cd.setAttribute('class', 'terminus-controls'); fd.appendChild(cd); var inpUrl = document.createElement('input'); inpUrl.setAttribute('type', 'text'); inpUrl.setAttribute('id', 'basicinput'); inpUrl.setAttribute('class', 'span8 terminus-input-text'); inpUrl.setAttribute('placeholder', 'URL : database_url'); if(this.val) inpUrl.value = this.val; cd.appendChild(inpUrl); var fd = document.createElement('div'); fd.setAttribute('class', 'terminus-control-group'); form.appendChild(fd); var inpLabel = document.createElement('label'); inpLabel.setAttribute('class', 'terminus-control-label'); inpLabel.setAttribute('for', 'basicinput'); inpLabel.innerHTML = 'Url/ ID:'; fd.appendChild(inpLabel); var cd = document.createElement('div'); cd.setAttribute('class', 'terminus-controls'); fd.appendChild(cd); var inpDocUrl = document.createElement('input'); inpDocUrl.setAttribute('type', 'text'); inpDocUrl.setAttribute('id', 'basicinput'); inpDocUrl.setAttribute('class', 'span8 terminus-input-text'); inpDocUrl.setAttribute('placeholder', 'Url or ID of document class'); cd.appendChild(inpDocUrl); var fd = document.createElement('div'); fd.setAttribute('class', 'terminus-control-group'); form.appendChild(fd); var optLabel = document.createElement('label'); optLabel.setAttribute('class', 'terminus-control-label'); optLabel.setAttribute('for', 'basicinput'); optLabel.innerHTML = 'Options:'; fd.appendChild(optLabel); var cd = document.createElement('div'); cd.setAttribute('class', 'terminus-controls'); fd.appendChild(cd); var optInp = document.createElement('input'); optInp.setAttribute('type', 'text'); optInp.setAttribute('id', 'basicinput'); optInp.setAttribute('class', 'span8 terminus-input-text'); optInp.setAttribute('placeholder', 'options'); cd.appendChild(optInp); var button = document.createElement('button'); button.setAttribute('class', 'terminus-btn terminus-send-api-btn'); button.setAttribute('type', 'button'); button.innerHTML = 'Send Api'; var gatherips = function(){ var input = {}; input.url = inpUrl.value; input.docUrl = inpDocUrl.value; input.options = optInp.value; return input; } var self = this; button.addEventListener("click", function(form){ var input = gatherips(); var buttonSelf = this; opts = {}; opts.explorer = true; self.client.getClassFrame(input.url, input.docUrl, opts) .then(function(response){ var currForm = buttonSelf.parentNode; var resultDom = UTILS.showHttpResult(response, 'getClassFrames', currForm, self.ui); }); }) // button click form.appendChild(button); return form; } */ // get form for all Apis ApiExplorer.prototype.getForm = function(curApi, body, view, action, urlPlaceholder){ // form var formDoc = document.createElement('form'); formDoc.setAttribute('class', 'terminus-form-horizontal row-fluid'); var fd = document.createElement('div'); fd.setAttribute('class', 'terminus-control-group'); formDoc.appendChild(fd); var urlLabel = document.createElement('label'); urlLabel.setAttribute('class', 'terminus-control-label'); urlLabel.setAttribute('for', 'basicinput'); urlLabel.innerHTML = 'Url:'; fd.appendChild(urlLabel); var cd = document.createElement('div'); cd.setAttribute('class', 'terminus-controls'); fd.appendChild(cd); var inpUrl = document.createElement('input'); inpUrl.setAttribute('type', 'text'); inpUrl.setAttribute('id', 'basicinput'); inpUrl.setAttribute('class', 'span8 terminus-input-text'); inpUrl.setAttribute('placeholder', urlPlaceholder); cd.appendChild(inpUrl); // add extra form fields based on current api chosen switch(curApi){ case 'getClassFrames': var fd = document.createElement('div'); fd.setAttribute('class', 'terminus-control-group'); formDoc.appendChild(fd); var docUrlLabel = document.createElement('label'); docUrlLabel.setAttribute('class', 'terminus-control-label'); docUrlLabel.setAttribute('for', 'basicinput'); docUrlLabel.innerHTML = 'Url/ ID:'; fd.appendChild(docUrlLabel); var cd = document.createElement('div'); cd.setAttribute('class', 'terminus-controls'); fd.appendChild(cd); var inpDocUrl = document.createElement('input'); inpDocUrl.setAttribute('type', 'text'); inpDocUrl.setAttribute('id', 'basicinput'); inpDocUrl.setAttribute('class', 'span8 terminus-input-text'); inpDocUrl.setAttribute('placeholder', 'Url or ID of document class'); cd.appendChild(inpDocUrl); break; case 'schema': //encoding /* var fd = document.createElement('div'); fd.setAttribute('class', 'terminus-control-group'); formDoc.appendChild(fd); var encLabel = document.createElement('label'); encLabel.setAttribute('class', 'terminus-control-label'); encLabel.setAttribute('for', 'basicinput'); encLabel.innerHTML = 'Encoding:'; fd.appendChild(encLabel); var cd = document.createElement('div'); cd.setAttribute('class', 'terminus-controls'); fd.appendChild(cd); var inpEnc = document.createElement('select'); inpEnc.setAttribute('style', 'height: 50px;width: 300px;padding: 10px;'); inpEnc.setAttribute('placeholder', 'turtle'); var optTurt = document.createElement('option'); optTurt.setAttribute('value', 'terminus:turtle'); optTurt.appendChild(document.createTextNode('turtle')); inpEnc.appendChild(optTurt); var optJld = document.createElement('option'); optJld.setAttribute('value', 'terminus:jsonld'); optJld.appendChild(document.createTextNode('jsonLD')); inpEnc.appendChild(optJld); cd.appendChild(inpEnc); */ break; } var fd = document.createElement('div'); fd.setAttribute('class', 'terminus-control-group'); formDoc.appendChild(fd); var keyLabel = document.createElement('label'); keyLabel.setAttribute('class', 'terminus-control-label'); keyLabel.setAttribute('for', 'basicinput'); keyLabel.innerHTML = 'Key:'; fd.appendChild(keyLabel); var cd = document.createElement('div'); cd.setAttribute('class', 'terminus-controls'); fd.appendChild(cd); var inpKey = document.createElement('input'); inpKey.setAttribute('type', 'text'); inpKey.setAttribute('id', 'basicinput'); inpKey.setAttribute('class', 'span8 terminus-input-text'); inpKey.setAttribute('placeholder', 'Key'); cd.appendChild(inpKey); if(!view){ // include text area only if call is type post var fd = document.createElement('div'); fd.setAttribute('class', 'terminus-control-group'); formDoc.appendChild(fd); var docLabel = document.createElement('label'); docLabel.setAttribute('class', 'terminus-control-label'); docLabel.setAttribute('for', 'basicinput'); if(curApi == 'query') docLabel.innerHTML = 'Query:'; docLabel.innerHTML = 'Document:'; fd.appendChild(docLabel); var cd = document.createElement('div'); cd.setAttribute('class', 'terminus-controls'); fd.appendChild(cd); var inpDoc = document.createElement('textarea'); cd.appendChild(inpDoc); inpDoc.setAttribute('class', 'terminus-api-explorer-text-area'); UTILS.stylizeEditor(this.ui, inpDoc, 'api-doc', 'javascript'); } body.appendChild(formDoc); // gather inputs var inp ={}; inp.url = inpUrl; inp.key = inpKey; if(curApi == 'getClassFrames') inp.docUrl = inpDocUrl; //if(curApi == 'schema') inp.enc = inpEnc; if(!view) inp.doc = inpDoc; var form = this.getApiSendButton(action, inp); body.appendChild(form); } // define event listeners on send api of schema & documents ApiExplorer.prototype.getApiForm = function(action, input){ // form var form = document.createElement('form'); form.setAttribute('class', 'terminus-form-horizontal row-fluid'); var button = document.createElement('button'); button.setAttribute('class', 'terminus-btn terminus-send-api-btn'); button.setAttribute('type', 'button'); button.innerHTML = 'Send Api'; form.appendChild(button); var resd = document.createElement('div'); form.appendChild(resd); var self = this; switch(action){ case 'getSchema': button.addEventListener("click", function(){ var opts = {}; opts['terminus:encoding'] = input.enc.value; opts['terminus:user_key'] = 'terminus:turtle'; var schurl = input.url.value; var buttonSelf = this; self.client.getSchema(schurl, opts) .then(function(response){ HTMLHelper.removeChildren(resd); var resultDom = UTILS.showHttpResult(response, 'getSchema', resd, self.ui); }); }) // button click break; case 'updateSchema': button.addEventListener("click", function(){ var buttonSelf = this; opts = {}; opts['terminus:encoding'] = input.enc.value; opts['terminus:user_key'] = 'terminus:turtle'; var schurl = input.url.value; self.client.connectionConfig.connected_mode = false; self.client.updateSchema(schurl, input.doc.value, opts) .then(function(response){ var gtxtar = document.createElement('textarea'); gtxtar.setAttribute('readonly', true); gtxtar.innerHTML = response; var currForm = buttonSelf.parentNode; currForm.appendChild(gtxtar); UTILS.stylizeEditor(this.ui, txtar, 'schema', 'turtle'); }); }) // button click break; case 'viewDocument': button.addEventListener("click", function(){ var dcurl = input.value; var buttonSelf = this; var opts = {}; opts.format = 'turtle'; self.client.getDocument(dcurl, opts) .then(function(response){ HTMLHelper.removeChildren(resd); var resultDom = UTILS.showHttpResult(response, action, resd, self.ui); }); }) // button click break; case 'deleteDocument': button.addEventListener("click", function(){ var dcurl = input.value; var buttonSelf = this; var opts = {}; self.client.deleteDocument(dcurl, opts) .then(function(response){ HTMLHelper.removeChildren(resd); var resultDom = UTILS.showHttpResult(response, action, resd, self.ui); }); }) // button click break; case 'createDocument': button.addEventListener("click", function(){ var dcurl = input.schemaUrlDom.value; var payload = input.htmlEditor.getValue(); var buttonSelf = this; opts = {}; self.client.createDocument(dcurl, payload, opts) .then(function(response){ HTMLHelper.removeChildren(resd); var resultDom = UTILS.showHttpResult(response, action, resd, self.ui); }); }) // button click break; case 'updateDocument': button.addEventListener("click", function(){ var dcurl = input.schemaUrlDom.value; var payload = input.htmlEditor.getValue(); var buttonSelf = this; opts = {}; opts.editmode = 'replace'; opts.format = 'json'; self.client.updateDocument(dcurl, payload, opts) .then(function(response){ HTMLHelper.removeChildren(resd); var resultDom = UTILS.showHttpResult(response, action, resd, self.ui); }); }) // button click break; } // switch(action) var br = document.createElement('BR'); form.appendChild(br); var br = document.createElement('BR'); form.appendChild(br); return form; } // getApiForm() // define event listeners on send api of schema & documents ApiExplorer.prototype.getApiSendButton = function(action, input){ // form var form = document.createElement('form'); form.setAttribute('class', 'terminus-form-horizontal row-fluid'); var button = document.createElement('button'); button.setAttribute('class', 'terminus-btn terminus-send-api-btn'); button.setAttribute('type', 'button'); button.innerHTML = 'Send Api'; form.appendChild(button); var resd = document.createElement('div'); form.appendChild(resd); var self = this; switch(action){ case 'connect': button.addEventListener("click", function(){ self.client.connect(input.url.value, input.key.value) .then(function(response){ HTMLHelper.removeChildren(resd); var resultDom = UTILS.showHttpResult(response, action, resd, self.ui); }); }) // button click break; case 'create': button.addEventListener("click", function(form){ self.client.createDatabase(input.url.value, JSON.parse(input.doc.value), input.key.value) .then(function(response){ HTMLHelper.removeChildren(resd); var resultDom = UTILS.showHttpResult(response, action, resd, self.ui); }); }) // button click break; case 'delete': button.addEventListener("click", function(){ var opts ={} self.client.deleteDatabase(input.url.value, input.key.value) .then(function(response){ HTMLHelper.removeChildren(resd); var resultDom = UTILS.showHttpResult(response, action, resd, self.ui); }); }) // button click break case 'getSchema': button.addEventListener("click", function(){ var opts = {}; opts['terminus:encoding'] = 'terminus:turtle'; opts['terminus:user_key'] = input.key.value; var schurl = input.url.value; self.client.getSchema(schurl, opts) .then(function(response){ HTMLHelper.removeChildren(resd); var resultDom = UTILS.showHttpResult(response, action, resd, self.ui); }); }) // button click break; case 'updateSchema': button.addEventListener("click", function(){ opts = {}; opts['terminus:encoding'] = 'terminus:turtle'; opts['terminus:user_key'] = input.key.value; var payload = input.doc.value; var schurl = input.url.value; self.client.connectionConfig.connected_mode = false; self.client.updateSchema(schurl, input.doc.value, opts) //self.client.updateSchema(schurl, input.doc.value, opts) .then(function(response){ HTMLHelper.removeChildren(resd); var resultDom = UTILS.showHttpResult(response, action, resd, self.ui); }); }) // button click break; case 'getClassFrames': button.addEventListener("click", function(form){ var schurl = input.url.value; opts = {}; opts.explorer = true; self.client.getClassFrame(input.url, JSON.parse(input.docUrl.value), opts) .then(function(response){ var currForm = buttonSelf.parentNode; var resultDom = UTILS.showHttpResult(response, action, currForm, self.ui); }); }) // button click break; case 'viewDocument': button.addEventListener("click", function(){ var dcurl = input.url.value; var opts = {}; opts['terminus:encoding'] = "jsonld"; opts['terminus:user_key'] = input.key.value; self.client.getDocument(dcurl, opts) .then(function(response){ HTMLHelper.removeChildren(resd); var resultDom = UTILS.showHttpResult(response, action, resd, self.ui); }); }) // button click break; case 'deleteDocument': button.addEventListener("click", function(){ var dcurl = input.url.value; var opts = {}; opts.key = input.key.value; self.client.deleteDocument(dcurl, opts) .then(function(response){ HTMLHelper.removeChildren(resd); var resultDom = UTILS.showHttpResult(response, action, resd, self.ui); }); }) // button click break; case 'createDocument': button.addEventListener("click", function(){ var dcurl = input.url.value; var payload = input.doc.value; opts = {}; opts['terminus:encoding'] = "jsonld"; opts['terminus:user_key'] = input.key.value; self.client.createDocument(dcurl, JSON.parse(payload), opts) .then(function(response){ HTMLHelper.removeChildren(resd); var resultDom = UTILS.showHttpResult(response, action, resd, self.ui); }); }) // button click break; case 'updateDocument': button.addEventListener("click", function(){ var dcurl = input.url.value; var payload = input.doc.value; var buttonSelf = this; opts = {}; opts['terminus:encoding'] = "jsonld"; opts['terminus:user_key'] = input.key.value; self.client.updateDocument(dcurl, JSON.parse(payload), opts) .then(function(response){ HTMLHelper.removeChildren(resd); var resultDom = UTILS.showHttpResult(response, action, resd, self.ui); }); }) // button click break; case 'select': button.addEventListener("click", function(){ var opts = {}; opts.key = input.key.value; var doc = JSON.parse(input.doc.value); self.client.select(input.url.value, doc, opts) .then(function(response){ HTMLHelper.removeChildren(resd); var resultDom = UTILS.showHttpResult(response, action, resd, self.ui); }); }) // button click break; case 'update': button.addEventListener("click", function(){ var opts = {}; opts.key = input.key.value; var doc = JSON.parse(input.doc.value); self.client.update(input.url.value, doc, opts) .then(function(response){ HTMLHelper.removeChildren(resd); var resultDom = UTILS.showHttpResult(response, action, resd, self.ui); }); }) // button click break; default: console.log('Invalid Api call on button'); break; } // switch(action) var br = document.createElement('BR'); form.appendChild(br); var br = document.createElement('BR'); form.appendChild(br); return form; } // getApiSendButton() // get signature of api calls ApiExplorer.prototype.getSignature = function(action){ var api = document.createElement('div'); // get header signature var sg = document.createElement('button'); sg.appendChild(document.createTextNode('Click to read API Signature')); sg.setAttribute('class', 'terminus-collapsible'); ic = document.createElement('i'); ic.setAttribute('class', 'terminus-cheveron-float fa fa-chevron-down'); sg.appendChild(ic); api.appendChild(sg); var br = document.createElement('BR'); api.appendChild(br); var cl = document.createElement('div'); cl.setAttribute('class', 'terminus-collapsible-content content'); var sig = UTILS.getFunctionSignature(action); var txt = document.createTextNode(sig.spec); var pre = document.createElement('pre'); pre.setAttribute('class', 'terminus-api-signature-pre'); pre.appendChild(txt); var txt = document.createTextNode(sig.descr); pre.appendChild(txt); var br = document.createElement('BR'); pre.appendChild(br); var br = document.createElement('BR'); pre.appendChild(br); var txt = document.createTextNode(sig.result); pre.appendChild(txt); cl.appendChild(pre); api.appendChild(cl); var br = document.createElement('BR'); api.appendChild(br); sg.addEventListener('click', function(){ UTILS.tolggleContent(ic, cl); }); return api; } // getSignature() // displays signature only on click function tolggleSignatureContent(content){ if (content.style.display === "block") content.style.display = "none"; else content.style.display = "block"; } module.exports=ApiExplorer <file_sep>/src/plugins/TerminusPlugin.js const HTMLHelper = require('../html/HTMLHelper'); function TerminusPluginManager(){ this.preloaded = []; this.loaded = []; this.loading = []; this.precluded = []; this.plugins = {}; this.css_base = window.css_base; this.plugins["font-awesome"] = { label: "Font Awesome", css: ["https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0-11/css/all.css"] }; this.plugins["quill"] = { label: "Quill", js: ["https://cdn.quilljs.com/1.3.6/quill.min.js"], css: ["https://cdn.quilljs.com/1.3.6/quill.snow.css"], }; this.plugins["codemirror"] = { label : "Code Mirror", js: ["https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.48.2/codemirror.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.48.2/mode/xml/xml.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.48.2/mode/css/css.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.48.2/mode/turtle/turtle.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.48.2/mode/javascript/javascript.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.48.2/addon/hint/anyword-hint.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.48.2/addon/hint/show-hint.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.48.4/addon/runmode/runmode.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.48.4/mode/http/http.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.48.4/addon/edit/closebrackets.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.48.4/addon/edit/matchbrackets.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.48.4/addon/display/placeholder.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.48.4/addon/fold/foldgutter.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.48.4/addon/fold/foldcode.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.48.4/addon/fold/indent-fold.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.48.4/addon/fold/markdown-fold.js" ], css: [ "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.48.2/codemirror.css", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.48.2/addon/hint/show-hint.css", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.48.4/theme/neo.css", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.48.4/theme/erlang-dark.css", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.48.4/addon/fold/foldgutter.css", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.48.4/theme/eclipse.css" ] }; this.plugins["jquery"] = { label: "jQuery", js: ["https://code.jquery.com/jquery-2.2.4.min.js"] }; this.plugins["jqueryui"] = { label: "jQuery UI", css: ["https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css"], js: ["https://code.jquery.com/ui/1.12.0/jquery-ui.js"], requires: ['jquery'] }; this.plugins["datatables"] = { label: "Data Tables", js: ["https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js", "https://cdn.datatables.net/v/dt/jszip-2.5.0/dt-1.10.16/b-1.5.1/b-html5-1.5.1/datatables.min.js"], css: ["https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"], requires: ['jquery'] }; /*this.plugins["prettify"] = { label: "Prettify", js: ["https://cdnjs.cloudflare.com/ajax/libs/prettify/r298/prettify.js"], css: ["https://cdnjs.cloudflare.com/ajax/libs/prettify/r298/prettify.css"], requires: ['jquery'] };*/ this.plugins["gmaps"] = { label: "Google Maps", js: ["https://maps.googleapis.com/maps/api/js"], //plugin: "gmaps.terminus.js" }; this.plugins["d3"] = { label: "d3", js: ["https://code.jquery.com/jquery-2.2.4.min.js"], requires: ['jquery'] }; this.plugins["select2"] = { label: "Select 2", js: ["https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.min.js"], css: ["https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.min.css"], requires: ['jquery'] }; /*this.plugins["jsoneditor"] = { label: "JSON Editor", js: ["https://cdnjs.cloudflare.com/ajax/libs/jsoneditor/7.0.4/jsoneditor.min.js"], css: ["https://cdnjs.cloudflare.com/ajax/libs/jsoneditor/7.0.4/jsoneditor.min.css"], //plugin: "jsoneditor.terminus.js" }; this.plugins["bootstrap"] = { label: "Bootstrap", js: ["https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"], css: ["https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.2.2/css/bootstrap.min.css", "https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.2.2/css/bootstrap-responsive.min.css"] }; this.plugins["flot"] = { label: "Flot", js: ["https://cdnjs.cloudflare.com/ajax/libs/flot/0.8.3/jquery.flot.min.js", "https://cdnjs.cloudflare.com/ajax/libs/flot/0.8.3/jquery.flot.resize.min.js"], requires: ["jquery"] };*/ } TerminusPluginManager.prototype.setPluginOptions = function(opts){ for(var p in opts){ if(!this.plugins[p]) continue; for(var k in opts[p]){ this.plugins[p][k] = opts[p][k]; } } } TerminusPluginManager.prototype.init = function(opts, then){ if(opts) this.setPluginOptions(opts); this.calculatePreloaded(); var toload = this.calculateRequiredInitPlugins(opts); if(toload && toload[0].length) { if(toload[1].length){ var self = this; var nthen = function(){ self.loadPlugins(toload[1], then); } this.loadPlugins(toload[0], nthen); } else { this.loadPlugins(toload[0], then); } } else if(then){ then(); } } TerminusPluginManager.prototype.calculateRequiredInitPlugins = function(opts){ if(opts){ var pins = []; for(var pid in opts){ if(opts[pid] && pins.indexOf(pid) == -1){ if(typeof opts[pid] != "object" && opts[pid]){ pins.push(pid); } else if(typeof opts[pid] == "object"){ if(!(typeof opts[pid].loaded != "undefined" && !opts[pid].loaded)){ pins.push(pid); } } } } } else { var pins = this.getDefaultPlugins(); } var needed_pins = []; for(var i = 0; i<pins.length; i++){ if(this.loaded.indexOf(pins[i]) == -1 && this.preloaded.indexOf(pins[i]) == -1 ){ needed_pins.push(pins[i]) } } var loading_order = [[], []]; for(var i = 0; i<needed_pins.length; i++){ if(this.plugins[needed_pins[i]]){ if(this.plugins[needed_pins[i]].requires && this.plugins[needed_pins[i]].requires.length){ loading_order[1].push(needed_pins[i]); } else { loading_order[0].push(needed_pins[i]); } } } return loading_order; } TerminusPluginManager.prototype.getAvailablePlugins = function(){ return this.plugins; } TerminusPluginManager.prototype.calculatePreloaded = function(){ for(var pl in this.plugins){ if(this.pluginAvailable(pl)){ this.preloaded.push(pl); } } } TerminusPluginManager.prototype.pluginAvailable = function(plugin, version_check){ if(typeof this.plugins[plugin] == "object"){ var pluginmeta = this.plugins[plugin]; if(pluginmeta.requires && pluginmeta.requires.length){ for(var i =0 ; i < pluginmeta.requires.length; i++){ if(!this.pluginAvailable(pluginmeta.requires[i], version_check)) { return false; } } } var required_version = (pluginmeta.version ? pluginmeta.version : false); switch(plugin){ case "jquery": { if(typeof jQuery == "undefined") return false; if(version_check && required_version){} return true; break; } case "jqueryui": { try{ if(typeof jQuery != "undefined" && jQuery.isFunction( jQuery.fn.slider )) return true; } catch(e){} return false; break; } case "quill": { if(typeof Quill == "undefined") return false; return true; break; } case "jsoneditor": { if(typeof JSONEditor == "undefined") return false; return true; break; } case "codemirror": { if(typeof CodeMirror == "undefined") return false; return this.plugins[plugin]; // sent plugin config with darkmode true/ false } case "font-awesome": { //if(typeof CodeMirror != "undefined") return true; return this.fontAwesomeCheck(); } case "datatables": { if(typeof jQuery != "undefined" && jQuery.isFunction( jQuery.fn.dataTable)) return true; return false; } case "select2": { if(typeof jQuery != "undefined" && jQuery.isFunction( jQuery.fn.select2 )) return true; return false; } case "gmaps": { if(typeof google == "undefined" || typeof google.maps == "undefined") return false; return true; } case "openlayers": { if(typeof ol == "undefined" || typeof ol.Map == "undefined") return false; return true; } case "d3": { if(typeof d3 == "undefined") return false; return true; } } } else { console.log(new Error(plugin + " is not a supported plugin ID")); } return false; }; TerminusPluginManager.prototype.fontAwesomeCheck = function(){ var span = document.createElement('span'); span.className = 'fa'; span.style.display = 'none'; if(document.body){ document.body.insertBefore(span, document.body.firstChild); function css(element, property) { return window.getComputedStyle(element, null).getPropertyValue(property); } var loaded = false; var fontAwsm = css(span, 'font-family'); if (fontAwsm.replace(/"/g, "") == 'Font Awesome 5 Free') { // remove double quotes loaded = true; } document.body.removeChild(span); return loaded; } return false; } TerminusPluginManager.prototype.getDefaultPlugins = function(){ var defplugs = ["font-awesome"]; return defplugs; } TerminusPluginManager.prototype.loadPlugins = function(plugins, then){ var ticker = plugins.length; var cback = function(){ if(--ticker <= 1 && then){ then(); } }; for(var i = 0; i < plugins.length; i++){ this.loadPlugin(plugins[i], cback); } } TerminusPluginManager.prototype.loadPlugin = function(plugin, then){ var pug = this.plugins[plugin]; if(pug.css){ for(var i=0; i<pug.css.length; i++){ var cssid = plugin + "_css_" + i; HTMLHelper.loadDynamicCSS(cssid, pug.css[i]); } } var scripts = (pug.js ? pug.js : []); if(plugin == "gmaps" && pug.key){ scripts[0] += "?key=" + pug.key; } if(pug.plugin){ //scripts.push("plugins/" + pug.plugin); } if(plugin == "codemirror"){ var cm = scripts[0]; var sid = plugin + "_js_" + (scripts.length -1); scripts.splice(0, 1); var self = this; var cback = function(){ self.loadPluginScripts(plugin, scripts, then); } HTMLHelper.loadDynamicScript(sid, cm, cback); } else { this.loadPluginScripts(plugin, scripts, then); } } TerminusPluginManager.prototype.loadPluginScripts = function(plugin, scripts, then){ var ticker = scripts.length - 1; var self = this; var cback = function(){ if(ticker == 0) { if(self.loaded.indexOf(plugin) == -1){ self.loaded.push(plugin); } if(self.loading.indexOf(plugin) != -1){ self.loading.splice(self.loading.indexOf(plugin), 1); } then(); } ticker--; }; if(scripts.length == 0){ this.loaded.push(plugin); } else { this.loading.push(plugin); } for(var i = 0; i<scripts.length; i++){ var sid = plugin + "_js_" + i; HTMLHelper.loadDynamicScript(sid, scripts[i], cback); } } TerminusPluginManager.prototype.loadPageCSS = function(css){ cssfid = "terminus_client_css"; var cssdom = document.getElementById(cssfid); if(cssdom){ cssdom.parentNode.removeChild(cssdom); } if(css){ cssurl = this.css_base + "css/" + css + ".css"; HTMLHelper.loadDynamicCSS(cssfid, cssurl); } } TerminusPluginManager.prototype.pluginLoadable = function(pid){ return (this.precluded.indexOf(pid) !== -1 || this.pluginLoadedOrLoading(pid)); } TerminusPluginManager.prototype.pluginLoadedOrLoading = function(pid){ if(this.loaded.indexOf(pid) != -1) return true; if(this.preloaded.indexOf(pid) != -1) return true; if(this.loading.indexOf(pid) != -1) return true; return false; } TerminusPluginManager.prototype.disabled = function(pid, obj){ if(this.precluded.indexOf(pid) != -1) return true; if(obj.requires){ for(var i = 0; i<obj.requires.length; i++){ if(!this.pluginLoadedOrLoading(obj.requires[i])) return true; } } return false; } TerminusPluginManager.prototype.getPluginDOM = function(plugid, obj, ui){ var a = document.createElement("a"); var cl = document.createElement("span"); a.appendChild(cl); cl.setAttribute("class", "terminus-plugin-control"); var cbox = document.createElement("input"); cbox.id = "terminus-plugin-control-" + plugid; cbox.type = "checkbox"; if(this.preloaded.indexOf(plugid) != -1){ cbox.checked = true; cbox.disabled = true; } else if(this.loaded.indexOf(plugid) != -1){ cbox.checked = true; } else if(this.loading.indexOf(plugid) != -1){ cbox.checked = true; } else if(this.disabled(plugid, obj)){ cbox.disabled = true; } var clab = document.createElement("label"); clab.setAttribute("class", "terminus-plugin-label terminus-pointer"); clab.setAttribute("for", cbox.id); clab.appendChild(document.createTextNode(obj.label)); cl.appendChild(clab); cl.appendChild(cbox); var self = this; cbox.addEventListener("change", function(){ self.togglePlugin(plugid, ui); }); return a; } TerminusPluginManager.prototype.togglePlugin = function(plugid, ui){ if(this.loaded.indexOf(plugid) == -1){ var then = function(){ ui.redraw(); } this.loadPlugin(plugid, then); } else { this.unloadPlugin(plugid); } HTMLHelper.removeChildren(ui.plugins); ui.drawPlugins(); } TerminusPluginManager.prototype.unloadPlugin = function(plugid){ if(!this.plugins[plugid] || this.loaded.indexOf(plugid) == -1) { console.log(new Error(plugid + " plugin unload request when it is not loaded")); return false; } var pug = this.plugins[plugid]; var num = (pug.js) ? pug.js.length : 0; if(pug.plugin) num++; for(var i=0; i< num; i++){ var cssfid = plugid + "_js_" + i; var cssdom = document.getElementById(cssfid); if(cssdom){ cssdom.parentNode.removeChild(cssdom); } } num = (pug.css ? pug.css.length : 0); for(var i=0; i< num; i++){ var cssfid = plugid + "_css_" + i; var cssdom = document.getElementById(cssfid); if(cssdom){ cssdom.parentNode.removeChild(cssdom); } } this.loaded.splice(this.loaded.indexOf(plugid), 1); } TerminusPluginManager.prototype.getAsDOM = function(ui){ var dm = document.createElement("span"); dm.setAttribute("class", "terminus-plugin-manager"); var clh = document.createElement("span"); clh.setAttribute("class", "terminus-plugin-control-header terminus-plugin-nav terminus-pointer"); clh.appendChild(document.createTextNode("Plugins")); dm.appendChild(clh); var a = document.createElement('a'); this.showPlugins(a, ui); clh.appendChild(a); a.style.display = 'none'; clh.addEventListener('click', function(){ if(a.style.display == 'none') a.style.display = 'block'; else a.style.display = 'none'; }) return dm; } TerminusPluginManager.prototype.showPlugins = function(a, ui){ a.setAttribute('style', 'background-color: #111;'); for(var pid in this.plugins){ a.appendChild(this.getPluginDOM(pid, this.plugins[pid], ui)); } } module.exports=TerminusPluginManager <file_sep>/README.md # terminus-dashboard Management Dashboard for TerminusDB The Terminus Dashboard is a simple javascript client application that provides users with an interface for managing and querying TerminusDB. It ships with TerminusDB and is available by default at the /dashboard URL of an installed TerminusDB server (default is http://localhost:6363/dashboard The dashboard requires terminus-client to be available. To install the manually dashboard, you have 3 choices: * Include the mininfied javascript libraries (in the /dist directory) in a web page * Download the package and use npm to manage the dependencies * For developors, the npm package includes a development server 1. Minified Javascript libraries For simple HTML use, you can just add the following scripts to any HTML page ```<script src="https://terminusdb.com/t/terminus-client.min.js"></script> <script src="https://terminusdb.com/t/terminus-dashboard.min.js"></script> ``` 2. npm Clone this repo, then cd into the root dir and run: `npm install` And all of the dependencies should be automatically installed 3. developers As above and then type `npm run start:dev` <file_sep>/src/TerminusServer.js /* User interface elements that relate to server context * * TerminusServerController is a control widget that invokes server actions * TerminusServerViewer is a window that displays server actions and server screens * */ const Datatables = require('./plugins/datatables.terminus'); const UTILS =require('./Utils'); const HTMLHelper = require('./html/HTMLHelper'); function TerminusServerController(ui){ this.ui = ui; } TerminusServerController.prototype.getAsDOM = function(){ var rsc = document.createElement("div"); rsc.setAttribute("class", "terminus-server-controller"); var self = this; if(this.ui && this.ui.server()){ var scd = document.createElement("div"); scd.setAttribute("class", "terminus-server-connection"); var nav = document.createElement('div'); nav.setAttribute('class', 'span3'); var ul = document.createElement('ul'); ul.setAttribute('class', 'terminus-ul'); nav.appendChild(ul); rsc.appendChild(nav); // connected to server // change server if(this.ui.showControl("change-server")){ var a = document.createElement('a'); a.setAttribute('class', 'terminus-a terminus-list-group-a terminus-list-group-a-action terminus-nav-width terminus-pointer'); var self = this; a.addEventListener("click", function(){ UTILS.activateSelectedNav(this, self); self.ui.clearMessages(); self.ui.showLoadURLPage(); }) var icon = document.createElement('i'); icon.setAttribute('class', 'terminus-menu-icon fa fa-link'); a.appendChild(icon); var txt = document.createTextNode('Change Server'); a.appendChild(txt); ul.appendChild(a); } // view databases if(this.ui.showControl("db")){ var a = document.createElement('a'); a.setAttribute('class', 'terminus-a terminus-list-group-a terminus-list-group-a-action terminus-nav-width terminus-pointer'); var self = this; a.addEventListener("click", function(){ UTILS.activateSelectedNav(this, self); if(self.ui.db()){ self.ui.clearDB(); self.ui.redrawControls(); } self.ui.clearMessages(); self.ui.showServerMainPage(); }) var icon = document.createElement('i'); icon.setAttribute('class', 'terminus-menu-icon fa fa-home'); a.appendChild(icon); var txt = document.createTextNode('Home'); a.appendChild(txt); ul.appendChild(a); } if(this.ui.showControl("create_database")){ var a = document.createElement('a'); a.setAttribute('class', 'terminus-a terminus-list-group-a terminus-list-group-a-action terminus-nav-width terminus-pointer'); var self = this; a.addEventListener("click", function(){ UTILS.activateSelectedNav(this, self); if(self.ui.db()){ self.ui.clearDB(); self.ui.redrawControls(); } self.ui.clearMessages(); self.ui.showCreateDBPage(); }) var icon = document.createElement('i'); icon.setAttribute('class', 'terminus-menu-icon fa fa-plus'); a.appendChild(icon); var txt = document.createTextNode('Create Database'); a.appendChild(txt); ul.appendChild(a); } if(this.ui.showControl("collaborate")){ var a = document.createElement('a'); a.setAttribute('class', 'terminus-a terminus-list-group-a terminus-list-group-a-action terminus-nav-width terminus-pointer'); var self = this; a.addEventListener("click", function(){ UTILS.activateSelectedNav(this, self); if(self.ui.db()){ self.ui.clearDB(); self.ui.redrawControls(); } self.ui.clearMessages(); self.ui.showCollaboratePage(); }) var icon = document.createElement('i'); icon.setAttribute('class', 'terminus-menu-icon fa fa-share-alt'); a.appendChild(icon); var txt = document.createTextNode('Collaborate'); a.appendChild(txt); ul.appendChild(a); } if(this.ui.showControl("tutorials")){ var a = document.createElement('a'); a.setAttribute('class', 'terminus-a terminus-list-group-a terminus-list-group-a-action terminus-nav-width terminus-pointer'); var self = this; a.addEventListener("click", function(){ UTILS.activateSelectedNav(this, self); if(self.ui.db()){ self.ui.clearDB(); self.ui.redrawControls(); } self.ui.clearMessages(); self.ui.showTutorialPage(); }) var icon = document.createElement('i'); icon.setAttribute('class', 'terminus-menu-icon fa fa-university'); a.appendChild(icon); var txt = document.createTextNode('Tutorials'); a.appendChild(txt); ul.appendChild(a); } } return rsc; } TerminusServerController.prototype.getServerLabelDOM = function(){ var srec = this.ui.client.connection.getServerRecord(); var lab = (srec && srec['rdfs:label'] && srec['rdfs:label']["@value"] ? srec['rdfs:label']["@value"] : this.ui.server()); var desc = (srec && srec['rdfs:comment'] && srec['rdfs:comment']["@value"] ? srec['rdfs:comment']["@value"] : ""); desc += " Server URL: "+ this.ui.server(); var val = document.createElement("span"); val.setAttribute("class", "terminus-server-value"); val.setAttribute("title", desc); val.appendChild(document.createTextNode(lab)); val = document.createElement('div'); return val; } function TerminusServerViewer(ui){ this.ui = ui; this.server = this.ui.server(); this.max_cell_size = 500; this.max_word_size = 40; this.css_base = window.css_base || '';//"https://terminusdb.github.io/terminus-dashboard/dist/"; } TerminusServerViewer.prototype.getAsDOM = function(selected){ var self = this; var pd = document.createElement("span"); pd.setAttribute("class", "terminus-server-home-page"); if(this.ui.server()){ var scd = document.createElement("span"); scd.setAttribute("class", "terminus-server-home"); if(this.ui.showView("server")){ scd.appendChild(this.getServerDetailsDOM()); } if(this.ui.showView("change-server")){ var csbut = document.createElement("button"); csbut.setAttribute("class", "terminus-control-button terminus-change-server-button terminus-btn") csbut.appendChild(document.createTextNode("Disconnect")); csbut.addEventListener("click", function(){ if(self.ui.db()){ self.ui.clearDB(); } self.ui.showLoadURLPage(); }) // 11092019 scd.appendChild(csbut); } if(this.ui.showView("create_database")){ var crbut = document.createElement("button"); crbut.setAttribute("class", "terminus-control-button terminus-create-db-button terminus-btn") crbut.appendChild(document.createTextNode("Create New Database")); crbut.addEventListener("click", function(){ if(self.ui.db()){ self.ui.clearDB(); } self.ui.clearMessages(); self.ui.showCreateDBPage(); }) } if(this.ui.showView("db")){ scd.appendChild(this.getDBListDOM()); } pd.appendChild(scd); } else { self.ui.showLoadURLPage(); } return pd; } TerminusServerViewer.prototype.getServerDetailsDOM = function(){ var scd = document.createElement("div"); scd.setAttribute("class", "terminus-server-details terminus-welcome-box terminus-no-res-alert"); var icon = document.createElement("img"); icon.setAttribute("class", "terminus-server-main-logo") var url = this.css_base + "css/img/TerminusDB_Logo_Original.png" icon.setAttribute("src", url); scd.appendChild(icon); var scl = document.createElement("p"); scl.setAttribute("class", "terminus-server-running") scl.appendChild(document.createTextNode("Terminus Server running at ")) scl.appendChild(document.createTextNode(this.ui.server())) scd.appendChild(scl); return scd; } TerminusServerViewer.prototype.wrapTableLinkCell = function(tdElement,dbid, text){ var self = this; var wrap = document.createElement("p"); // wrap.setAttribute("href", "#"); wrap.setAttribute("class", "terminus-table-content"); HTMLHelper.wrapShortenedText(wrap, text, this.max_cell_size, this.max_word_size); tdElement.addEventListener("click", function(){ self.ui.connectToDB(dbid); self.ui.showDBMainPage(); }); return wrap; } TerminusServerViewer.prototype.getDBListDOM = function(){ //var self = this; var sec = document.createElement("div"); sec.setAttribute("class", "terminus-db-list"); //sec.appendChild(UTILS.getHeaderDom('Databases')); var scd = document.createElement("table"); scd.setAttribute("class", "terminus-db-list terminus-db-size terminus-hover-table terminus-margin-top"); var thead = document.createElement("thead"); var thr = document.createElement("tr"); var th1 = document.createElement("th"); th1.appendChild(document.createTextNode("Database ID")); th1.setAttribute("class", "terminus-db-id terminus-table-header-full-css"); th1.style.width = "20%"; var th2 = document.createElement("th"); th2.appendChild(document.createTextNode("Title")); th2.setAttribute("class", "terminus-db-title terminus-table-header-full-css"); th2.style.width = "30%"; var th3 = document.createElement("th"); th3.appendChild(document.createTextNode("Description")); th3.setAttribute("class", "terminus-db-description terminus-table-header-full-css"); th3.style.width = "50%"; var th4 = document.createElement("th"); th4.setAttribute("class", "terminus-db-size terminus-table-header-full-css"); th4.appendChild(document.createTextNode("Size")); var th5 = document.createElement("th"); th5.setAttribute("class", "terminus-db-created terminus-table-header-full-css"); th5.appendChild(document.createTextNode("Created")); var th6 = document.createElement("th"); th6.appendChild(document.createTextNode("Delete")); th6.setAttribute("class", "terminus-db-delete terminus-table-header-full-css"); thr.appendChild(th1); thr.appendChild(th2); thr.appendChild(th3); //thr.appendChild(th4); //thr.appendChild(th5); //thr.appendChild(th6); thead.appendChild(thr); scd.appendChild(thead); var tbody = document.createElement("tbody"); var dbrecs = this.ui.client.connection.getServerDBRecords(); for(let fullid in dbrecs){ let dbrec = dbrecs[fullid]; const dbid = fullid.split(":")[1]; let tr = document.createElement("tr"); var td1 = document.createElement("td"); td1.appendChild(this.wrapTableLinkCell(td1,dbid, dbid)); td1.setAttribute("class", "terminus-db-id terminus-db-pointer"); var td2 = document.createElement("td"); td2.setAttribute("class", "terminus-db-title terminus-db-pointer"); var txt = (dbrec && dbrec['rdfs:label'] && dbrec['rdfs:label']['@value'] ? dbrec['rdfs:label']['@value'] : ""); td2.appendChild(this.wrapTableLinkCell(td2,dbid, txt)); var td3 = document.createElement("td"); td3.setAttribute("class", "terminus-db-description terminus-db-pointer"); var txt = (dbrec && dbrec['rdfs:comment'] && dbrec['rdfs:comment']['@value'] ? dbrec['rdfs:comment']['@value'] : ""); td3.appendChild(this.wrapTableLinkCell(td3,dbid, txt)); var td4 = document.createElement("td"); td4.setAttribute("class", "terminus-db-size terminus-db-pointer"); var txt = (dbrec && dbrec['terminus:size'] && dbrec['terminus:size']['@value'] ? dbrec['terminus:size']['@value'] : ""); td4.appendChild(this.wrapTableLinkCell(td4,dbid, txt)); var td5 = document.createElement("td"); td5.setAttribute("class", "terminus-db-created terminus-db-pointer"); var txt = (dbrec && dbrec['terminus:last_updated'] && dbrec['terminus:last_updated']['@value'] ? dbrec['terminus:last_updated']['@value'] : ""); td5.appendChild(this.wrapTableLinkCell(td5,dbid, txt)); var td6 = document.createElement("td"); td6.setAttribute("class", "db-delete"); var delbut = this.ui.getDeleteDBButton(dbid); if(delbut) td6.appendChild(delbut); tr.appendChild(td1); tr.appendChild(td2); tr.appendChild(td3); //tr.appendChild(td4); //tr.appendChild(td5); //tr.appendChild(td6); tbody.appendChild(tr); } scd.appendChild(tbody); sec.appendChild(scd); if(this.ui.pluginAvailable("datatables")){ var dt = new Datatables.CspDatatables(this.ui); var tab = dt.draw(scd); } return sec; } module.exports = {TerminusServerViewer,TerminusServerController} <file_sep>/src/html/datatypes/RangeEditor.js const TerminusClient = require('@terminusdb/terminus-client'); const HTMLHelper = require('../HTMLHelper'); function HTMLRangeEditor(options){ this.options(options); } HTMLRangeEditor.prototype.options = function(options){ this.commas = (options && options.commas ? options.commas : true); this.css = "terminus-literal-value terminus-literal-value-range " + ((options && options.css) ? options.css : ""); this.delimiter = (options && options.delimiter ? options.delimiter : false); } HTMLRangeEditor.prototype.renderFrame = function(frame, dataviewer){ var value = frame.get(); var vals = TerminusClient.UTILS.TypeHelper.parseRangeValue(value, this.delimiter); var d = document.createElement("span"); d.setAttribute("class", this.css); var rvals = document.createElement("span"); var svals = document.createElement("span"); var data1 = (vals.length > 0 ? vals[0] : ""); var data2 = (vals.length > 1 ? vals[1] : ""); var firstip = document.createElement("input"); firstip.setAttribute('type', "text"); firstip.setAttribute('size', 16); if(data1){ firstip.value = data1; } var secondip = document.createElement("input"); secondip.setAttribute('type', "text"); secondip.setAttribute('size', 16); if(data2){ this.showing_range = true; secondip.value = data2; } rvals.appendChild(firstip); d.appendChild(rvals); if(this.showing_range){ svals.appendChild(getRangeSymbolDOM()); svals.appendChild(secondip); } d.appendChild(svals); var but = document.createElement("button"); but.setAttribute("class", "terminus-change-range"); var txt = this.showing_range ? "Change to Simple Value" : "Change to Uncertain Range"; but.appendChild(document.createTextNode(txt)); d.appendChild(but); var self = this; but.addEventListener("click", function(){ if(self.showing_range){ self.showing_range = false; secondip.value = ""; HTMLHelper.removeChildren(svals); } else { self.showing_range = true; secondip.value = ""; svals.appendChild(getRangeSymbolDOM()); svals.appendChild(secondip); } var txt = self.showing_range ? "Change to Simple Value" : "Change to Uncertain Range"; but.innerText = txt; changeHandler(); }); var changeHandler = function(){ if(self.showing_range && secondip.value){ if(firstip.value) frame.set("[" + firstip.value + "," + secondip.value + "]"); else frame.set(secondip.value); } else { frame.set(firstip.value); } } firstip.addEventListener("change", changeHandler); secondip.addEventListener("change", changeHandler); return d; } function getRangeSymbolDOM(){ var d = document.createElement("span"); d.setAttribute("class", "terminus-range-indicator"); d.setAttribute("title", "The value is uncertain, it lies somewhere in this range"); d.appendChild(document.createTextNode(" ... ")); return d; } module.exports={HTMLRangeEditor} <file_sep>/src/html/TerminusViolation.js function TerminusViolations(vios, ui){ this.ui = ui; this.vios = []; var nvios = []; for(var i = 0; i<vios.length; i++){ nvios.push(vios[i]); } for(var i = 0; i<nvios.length; i++){ this.vios.push(new TerminusViolation(nvios[i], this.ui)); } } TerminusViolations.prototype.getAsDOM = function(context_msg){ var vdom = document.createElement("div"); vdom.setAttribute("class", "terminus-violations terminus-show-msg-vio"); var vioHeading = document.createElement("div"); vioHeading.setAttribute('class', 'terminus-violations-heading'); vdom.appendChild(vioHeading); var msg = this.vios.length + (this.vios.length > 1 ? " Violations Detected" : " Violation Detected"); if(context_msg) msg += " " + context_msg; vioHeading.appendChild(document.createTextNode(msg)); for(var i = 0; i<this.vios.length; i++){ vdom.appendChild(this.vios[i].getAsDOM()); } return vdom; } /* * Class for displaying violation reports as HTML */ function TerminusViolation(vio, ui){ this.ui = ui; this.vio = vio; } TerminusViolation.prototype.getAsDOM = function(){ var vdom = document.createElement("div"); vdom.setAttribute("class", "terminus-violation"); if(this.vio['@type']){ var msg = this.vio['vio:message'] || {"@value": ""}; vdom.appendChild(this.getPropertyAsDOM(this.vio["@type"], msg)); } for(var prop in this.vio){ if(prop != "vio:message" && prop != "@type"){ vdom.appendChild(this.getPropertyAsDOM(prop, this.vio[prop])); } } return vdom; } TerminusViolation.prototype.getPropertyAsDOM = function(prop, val){ var pdom = document.createElement("div"); pdom.setAttribute("class", "terminus-violation-property"); var ldom = document.createElement("span"); ldom.setAttribute("class", "terminus-label terminus-violation-property-label"); ldom.appendChild(document.createTextNode(prop)); var vdom = document.createElement("span"); vdom.setAttribute("class", "terminus-violation-property-value"); var mval = val["@value"] || val; if(mval && typeof mval != "object") vdom.appendChild(document.createTextNode(mval)); pdom.appendChild(ldom); pdom.appendChild(vdom); return pdom; } module.exports=TerminusViolations <file_sep>/src/TerminusDB.js /* * User Interface elements dealing with database level functions - view, delete, create, db * view document etc */ const UTILS=require('./Utils'); const TerminusClient = require('@terminusdb/terminus-client'); const HTMLHelper = require('./html/HTMLHelper'); const TerminusViewer = require("./html/TerminusViewer"); /** * DB home page main function * @param {TerminusUI} ui */ function TerminusDBViewer(ui){ this.ui = ui; this.tv = new TerminusViewer(ui.client); this.container = document.createElement("span"); this.container.setAttribute("class", "terminus-main-page"); this.pages = ["home"]; } //Document configuration for DB meta-data listing on DB home page TerminusDBViewer.prototype.getDatabaseDocumentConfig = function(){ var property_style = "display: block; padding: 0.3em 1em;" var box_style = "padding: 8px; border: 1px solid #afafaf; background-color: #efefef;" var label_style = "display: inline-block; min-width: 100px; font-weight: 600; color: #446ba0;"; var value_style = "font-weight: 400; color: #002856;"; var config = TerminusClient.View.document(); config.show_all("SimpleFrameViewer"); config.object().style(box_style); config.object().headerFeatures("id").style(property_style).args({headerStyle: label_style + " padding-right: 10px;", bodyStyle: value_style, label: "Database ID", removePrefixes: true}); config.object().headerFeatures("type").style(property_style).args({headerStyle: label_style + " padding-right: 10px;", bodyStyle: value_style}) config.object().features("value").style(property_style); config.property().features("label").style(label_style); config.property().features("label", "value"); config.property().property("terminus:id").hidden(true); config.data().features("value").style(value_style); return config; } /** * Query Pane Configurations */ //documents home page table TerminusDBViewer.prototype.getDocumentsQueryPane = function(docs, docClasses){ var table = TerminusClient.View.table(); //table.pager(true); table.column('ID').header('Document ID'); table.column('Label').header('Name'); table.column('Comment').header('Description'); table.column_order("ID", "Label", "Type", "Comment"); var self = this; var x = function(row){ self.showDocumentPage(row["v:ID"], docClasses, false, docs); } table.row().click(x); var qp = this.tv.getResult(docs.query, table, docs); return qp; } //Create document page pane configuration TerminusDBViewer.prototype.getCreateDataPaneConfig = function(){ const pc = { showQuery: false, editQuery: false }; return pc; } //Document configuration for create document page TerminusDBViewer.prototype.getCreateDocumentConfig = function(){ var property_style = "display: block; padding: 0.3em 1em;" var box_style = "padding: 8px; border: 1px solid #afafaf; background-color: #efefef;" var label_style = "display: inline-block; min-width: 100px; font-weight: 600; color: #446ba0;"; var value_style = "font-weight: 400; color: #002856;"; var config = TerminusClient.View.document().load_schema(true); config.all().mode("edit"); config.show_all("SimpleFrameViewer"); config.object().style(box_style); config.object().depth(0).headerFeatures("id").style(property_style).args({headerStyle: label_style + " padding-right: 10px;", bodyStyle: value_style, label: "Document ID", removePrefixes: true}); config.object().headerFeatures("type").style(property_style).args({headerStyle: label_style + " padding-right: 10px;", bodyStyle: value_style}) config.object().features("value").style(property_style); config.property().features("label").style(label_style); config.property().features("label", "value"); config.property().property("terminus:id").hidden(true); config.data().features("value").style(value_style); return config; } //Document configuration for view / edit document page TerminusDBViewer.prototype.getShowDocumentConfig = function(){ var property_style = "display: block; padding: 1.5em 1em 0.8em 1em; position: relative;" var config = TerminusClient.View.document().load_schema(true); config.show_all("SimpleFrameViewer"); config.object().depth(0).style("border: 1px solid #aaa; background-color: #fafafd").headerStyle("background-color: #002856; color: white; padding: 8px; display: block; "); config.object().headerFeatures("id", "type").args({headerStyle: "text-align: right; display: inline-block; width: 200px; padding-right: 10px; text-weight: 600px; color: white"}); //config.object().headerFeatures("mode").style("float: right"); config.object().features("value").style(property_style); config.property().features("label", "value"); config.property().features("label").style("text-align: right; display: inline-block; width: 200px; padding-right: 10px; font-weight: 600; color: #002856"); config.property().features("value").style("display: inline-block; vertical-align: top"); config.data().features("value").style("color: #002856; display: block; margin-bottom: 1em;"); return config; }; TerminusDBViewer.prototype.getDocumentsGraphConfig = function(res){ var graph = TerminusClient.View.graph(); graph.literals(false); graph.height(800).width(1250); graph.edges(["v:doc1", "v:doc2"], ["v:doc1", "v:Enttype"], ["v:doc2", "v:Enttype2"]); graph.node("v:Label", "v:Label2", "v:Predicate").hidden(true); graph.edge("v:doc1", "v:doc2").distance(100).text("v:Predicate"); graph.edge("v:doc1", "v:Enttype").distance(100).text("Class"); graph.edge("v:doc2", "v:Enttype2").distance(100).text("Class"); graph.node("v:Enttype").text("v:Enttype").color([200, 250, 200]).icon({label: true, color: [15, 50, 10]}).collisionRadius(80); graph.node("v:Enttype2").text("v:Enttype2").color([200, 250, 200]).icon({label: true, color: [15, 50, 10]}).collisionRadius(80); graph.node("v:doc1").size(24).text("v:Label1").icon({label: true, color: [15, 50, 10]}).collisionRadius(80) graph.node("v:doc2").size(24).text("v:Label2").icon({label: true, color: [15, 50, 10]}).collisionRadius(80) return graph; } TerminusDBViewer.prototype.showDocumentGraph = function(insertDOM){ var dburl = this.ui.client.connectionConfig.dbURL(); var q = TerminusClient.WOQL.limit(200).getAllDocumentConnections(); var qp = this.tv.getResult(q, this.getDocumentsGraphConfig()); var dloader = this.getLoaderDOM("Terminus Server is generating the document graph"); insertDOM.appendChild(dloader) insertDOM.appendChild(qp.getAsDOM()); this.graph_query_pane = qp; qp.load().finally(() => insertDOM.removeChild(dloader)); } TerminusDBViewer.prototype.showDocumentConnections = function(docid, targetDOM, docClasses, docs){ var q = TerminusClient.WOQL.limit(50).getDocumentConnections(docid); var viewer = TerminusClient.View.table().column_order("Outgoing", "Incoming", "Entid", "Label", "Enttype", "Class_Label" ); viewer.column("Entid").hidden(true); viewer.column("Enttype").hidden(true); viewer.column("Label").header("Document Name"); viewer.column("Class_Label").header("Type"); viewer.column("Incoming").header("Incoming Link"); viewer.column("Outgoing").header("Outgoing Link"); var self = this; var x = function(row){ self.showDocumentPage(row["v:Entid"], docClasses, false, docs); } viewer.row().click(x); var graph = TerminusClient.View.graph(); graph.literals(false); graph.height(800).width(1250); graph.edges(["v:Docid", "v:Entid"], ["v:Entid", "v:Docid"]); graph.node("Outgoing", "Incoming", "Label", "Enttype", "Class_Label").hidden(true); //graph.edge("v:Entid", "v:Docid").distance(200).text("v:Incoming"); graph.edge("v:Entid", "v:Docid").v("v:Incoming").in("unknown").hidden(true); graph.edge("v:Entid", "v:Docid").distance(200).text("v:Incoming").color([255, 0, 0]); graph.edge("v:Docid", "v:Entid").v("v:Outgoing").in("unknown").hidden(true); graph.edge("v:Docid", "v:Entid").distance(200).text("v:Outgoing").color([0, 0, 255]); graph.node("v:Docid").text("v:Docid").icon({label: true}); graph.node("v:Entid").text("v:Label"); var introdom = document.createElement("h3"); introdom.style = "margin-top: 1.5em; margin-bottom: -32px; color: #224488;" introdom.appendChild(document.createTextNode("Links from other documents")); var rpc = { intro: introdom, viewers: [graph] } var qp = this.tv.getQueryPane(q, [viewer], false, [rpc]); var dloader = this.getLoaderDOM("Fetching document relationship table"); targetDOM.appendChild(dloader) targetDOM.appendChild(qp.getAsDOM()); qp.load().finally(() => targetDOM.removeChild(dloader)); } TerminusDBViewer.prototype.createFullDocumentPane = function(docid, result_options, target, docClasses, docs){ var self = this; var func = function(v){ self.showDocumentPage(v, docClasses, false, docs); }; var dpoptions = {"HTMLEntityViewer": { "onclick": func}}; var dp = this.tv.getDocumentPane(docid, result_options, dpoptions); return dp; } /** * HTML Page drawing functions */ /** * Called first - runs set-up queries to seed UI elements * before drawing the page body */ TerminusDBViewer.prototype.getAsDOM = function(){ HTMLHelper.removeChildren(this.container); var limit = 20; var WOQL = TerminusClient.WOQL; var q = WOQL.limit(limit).documentMetadata(); q.execute(this.ui.client).then( (result) => { var docs = new TerminusClient.WOQLResult(result, q); var q2 = WOQL.query().concreteDocumentClasses(); q2.execute(this.ui.client).then( (result2) => { var docClasses = new TerminusClient.WOQLResult(result2, q2); var bdom = this.getBodyAsDOM(docs, docClasses); if(bdom) this.container.appendChild(bdom); }); }).catch((e) => { this.ui.showError(e); }); return this.container; } /** * Two main pages - DB home page and documents section */ TerminusDBViewer.prototype.getBodyAsDOM = function(docs, docClasses){ if(this.body){ HTMLHelper.removeChildren(this.body); } else { this.body = document.createElement("div"); this.body.setAttribute("class", "terminus-home-body terminus-document-view"); } if(this.ui.page == "docs"){ (this.docid ? this.showDocumentPage(this.docid, docClasses, this.body, docs) : this.getDocumentsDOM(docs, docClasses, this.body)); } else { this.getHomeDOM(docs, docClasses, this.body); } return this.body } /** * DB home page */ TerminusDBViewer.prototype.getHomeDOM = function(docs, docClasses, body){ var intro = this.showHappyBox("dbhome", "demo"); body.appendChild(intro); var config = this.getDatabaseDocumentConfig(); var cont = document.createElement("span"); intro.appendChild(cont); var mydb = this.ui.db(); this.ui.connectToDB("terminus"); this.insertDocument("doc:" + mydb, cont, config); this.ui.connectToDB(mydb); if(docs.count() > 0){ body.appendChild(this.showHappyBox("dbhome", "intro")); body.appendChild(this.showHappyBox("happy", "query")); } else if(docClasses.count() > 0) { var dchooser = this.getCreateDataChooser(docClasses, docs); if(docClasses.count() <= 3){ body.appendChild(this.showHappyBox("empty", "schema")); body.appendChild(this.showHappyBox("empty", "query")); } else { body.appendChild(this.showHappyBox("happy", "docs", dchooser)); body.appendChild(this.showHappyBox("happy", "query")); } } else { body.appendChild(this.showHappyBox("empty", "schema")); body.appendChild(this.showHappyBox("empty", "query")); } var delw = this.getDeleteDatabaseWidget("fa-2x"); if(delw) body.appendChild(this.showHappyBox("happy", "delete", delw)); return body; } /** * Main Document Listing Page */ TerminusDBViewer.prototype.getDocumentsDOM = function(docs, docClasses, body){ var mactions = this.getDocumentsMenu(docs, docClasses, body); if(mactions) body.appendChild(mactions); this.tableDOM = document.createElement("span"); body.appendChild(this.tableDOM); this.graphDOM = document.createElement("span"); this.graphDOM.setAttribute("class", "terminus-documents-graph"); this.graphDOM.style.display = "none"; body.appendChild(this.graphDOM); if(docs.count() > 0){ if(!this.document_table) this.document_table = this.getDocumentsQueryPane(docs, docClasses); this.tableDOM.appendChild(this.document_table.getAsDOM()); this.showDocumentGraph(this.graphDOM); } else { var dchooser = this.getCreateDataChooser(docClasses, docs); if(docClasses.count() <= 3){ this.ui.showWarning("The database must have a schema before you can add documents to it") body.appendChild(this.showHappyBox("empty", "schema")); body.appendChild(this.showHappyBox("empty", "query")); } else { this.ui.showWarning("No documents have been added to the database"); body.appendChild(this.showHappyBox("happy", "docs", dchooser)); body.appendChild(this.showHappyBox("happy", "query")); } } return body; } /** * Document View / Edit Page */ TerminusDBViewer.prototype.showDocumentPage = function(docid, docClasses, target, docs){ this.ui.clearMessages(); HTMLHelper.removeChildren(target); this.ui.page = "docs"; this.ui.redrawControls(); var start = docid.substring(0, 4); if(start != "doc:" && start != "http") docid = "doc:" + docid; var config = this.getShowDocumentConfig(); var dp = this.createFullDocumentPane(docid, config, target, docClasses, docs); this.docid = docid; this.pages.push(docid); var dcDOM = document.createElement("span"); var vc = this.showDocumentConnections(docid, dcDOM, docClasses, docs); return dp.load().then(() => { HTMLHelper.removeChildren(this.container); var nav = this.getNavigationDOM(docClasses, docs); this.container.appendChild(nav); var mactions = this.getDocumentsMenu(docs, docClasses, this.container, docid); if(mactions) this.container.appendChild(mactions); var dx = dp.getAsDOM(); this.container.appendChild(dx); this.container.appendChild(dcDOM); }) .catch((e) => { this.ui.showError(e) }); } /** * Main Create New Document Page */ TerminusDBViewer.prototype.loadCreateDocumentPage = function(cls, docClasses, docs){ this.ui.page = "docs"; this.ui.redrawControls(); var WOQL = TerminusClient.WOQL; var dburl = this.ui.client.connectionConfig.dbURL(); var config = this.getCreateDocumentConfig(); var dp = this.tv.getNewDocumentPane(cls, config); dp.documentLoader = this.getShowDocumentControl(docClasses, docs); /*var df = new DocumentPane(this.ui.client).options({ showQuery: true, editQuery: true, showConfig: false, editConfig: false, loadDocument: this.getShowDocumentControl(docClasses, docs) });*/ if(docClasses && docClasses.count() > 0){ var dchooser = this.getCreateDataChooser(docClasses, docs ); dp.setClassLoader(dchooser); } else { var q2 = WOQL.query().concreteDocumentClasses(); q2.execute(this.ui.client).then( (result2) => { docClasses = (docClasses ? docClasses : new TerminusClient.WOQLResult(result2, q2)); var dchooser = this.getCreateDataChooser(docClasses, docs ); dp.setClassLoader(dchooser); }); } this.container.appendChild(dp.getAsDOM()); dp.load().then(() => { HTMLHelper.removeChildren(this.container); var nav = this.getNavigationDOM(docClasses, docs); this.container.appendChild(nav); this.container.appendChild(dp.getAsDOM()); }); } /** * Toolbox Menu on top of the page on the documents home page */ TerminusDBViewer.prototype.getDocumentsMenu = function(docs, docClasses, target, docid){ var self = this; var page_actions = document.createElement("div"); page_actions.setAttribute("class", "terminus-home-actions"); var span = document.createElement('span'); page_actions.appendChild(span); if(docs.count() > 0){ var show_doc_action = this.getShowDocumentControl(docClasses, docs, target); span.appendChild(show_doc_action); if(!docid){ var tgtd = this.getToggleGraphTableDOM(); if(tgtd) page_actions.appendChild(tgtd); } } return page_actions;//turned off create document stuff if(docClasses.count() > 0){ var ch = function(cls){ if(cls) self.loadCreateDocumentPage(cls, docClasses, docs); } var dchooser = this.getCreateDataChooser(docClasses, docs, ch); if(docs.count() > 1) span.appendChild(dchooser); } else { this.ui.showError("No document classes found in schema - you must define a document, entity or relationship class before you can create documents"); } return page_actions; } TerminusDBViewer.prototype.getLoaderDOM = function(msg){ var cont = document.createElement('div'); cont.setAttribute('class', 'terminus-busy-msg') cont.appendChild(document.createTextNode(msg)); this.ui.getBusyLoader(cont, msg); return cont; } /** * Switches between graph and table display modes on documents home page */ TerminusDBViewer.prototype.redrawDocumentPage = function(){ if(this.docview == "graph"){ this.tableDOM.style.display = "none"; this.graphDOM.style.display = "inline"; } else { this.tableDOM.style.display = "inline"; this.graphDOM.style.display = "none"; } } TerminusDBViewer.prototype.getToggleGraphTableDOM = function(){ // delete database var isp = document.createElement('span'); isp.setAttribute("class", "terminus-toggle-documents"); var tisp = document.createElement('span'); var gisp = document.createElement('span'); isp.appendChild(tisp); isp.appendChild(gisp); var ticon = document.createElement("i"); ticon.setAttribute("class", "fa fa-table"); ticon.classList.add('terminus-result-view-icon'); var gicon = document.createElement("i"); tisp.appendChild(ticon); gisp.appendChild(gicon); gisp.setAttribute("title", "Click to view a graph of the links between the documents in the database"); tisp.setAttribute("title", "Switch back to a regular table of documents"); gicon.setAttribute("class", "fas fa-code-branch"); gicon.classList.add('terminus-result-view-icon'); if(this.docview && this.docview == "graph"){ gisp.style.display = "none"; } else { tisp.style.display = "none"; } var hov = function(ticon){ tisp.addEventListener('mouseover', function(){ this.style.cursor = "pointer"; }); } hov(gisp); hov(tisp); gisp.addEventListener("click", () => { if(this.docview && this.docview == "graph") return; if(!this.graph_query_pane){ this.showDocumentGraph(this.graphDOM); } this.docview = "graph"; gisp.style.display = "none"; this.graphDOM.style.display = "inline"; tisp.style.display = "inline"; this.tableDOM.style.display = "none"; }); ticon.addEventListener("click", () => { if(!this.docview || this.docview == "table") return; this.docview = "table"; tisp.style.display = "none"; gisp.style.display = "inline"; this.graphDOM.style.display = "none"; this.tableDOM.style.display = "inline"; }); isp.appendChild(tisp); isp.appendChild(gisp); return isp; } TerminusDBViewer.prototype.getDeleteDatabaseWidget = function(css){ // delete database if(this.ui.db() == "terminus") return; var d = document.createElement("span"); d.setAttribute("class", "terminus-db-widget"); HTMLHelper.removeChildren(this.container); var del = document.createElement('button'); del.setAttribute('class', 'terminus-btn terminus-btn-float-right terminus-home-del'); del.setAttribute('type', 'button'); del.appendChild(document.createTextNode('Delete Database')); var di = document.createElement("i"); var icss = "fa fa-trash fa-2x terminus-icon-padding" + (css ? " " + css : ""); di.setAttribute("class", icss); del.appendChild(di); var dbrec = this.ui.getDBRecord(); if(dbrec) var nm = (dbrec["rdfs:label"] && dbrec["rdfs:label"]["@value"] ? dbrec["rdfs:label"]["@value"] : this.ui.db()); else var nm = this.ui.db(); var self = this; var dbdel = this.ui.db(); var delbut = this.ui.getDeleteDBButton(dbdel); if(delbut){ d.appendChild(delbut); } return d; } TerminusDBViewer.prototype.styleCreateDocumentChooser = function(){ var select = document.getElementsByClassName('woql-chooser'); for(i=0; i<select.length; i++){ if(select[i].type == 'select'){ select[i].classList.add('terminus-form-doc-value'); var self = this; select[i].addEventListener('change', function(){ self.showCreateDocument(this.value); }) } } } TerminusDBViewer.prototype.getCreateDataChooser = function(docClasses, docs, change, pholder){ pholder = (pholder ? pholder : "Create a New Document"); //qopts = (qopts ? qopts : {}); //var dp = new QueryPane(this.ui.client, docClasses.query, docClasses).options(qopts); var chooser = TerminusClient.View.chooser().values("Class").labels("Label").titles("Comment").show_empty(pholder); var self = this; chooser.change = (change ? change : function(cls){ if(cls) self.loadCreateDocumentPage(cls, docClasses, docs); }); var dp = this.tv.getResult(docClasses.query, chooser, docClasses); var dchooser = dp.getAsDOM(); return dchooser; } TerminusDBViewer.prototype.showHappyBox = function(happy, type, chooser){ var hbox = document.createElement("div"); hbox.setAttribute("class", "terminus-welcome-box terminus-no-res-alert"); var self = this; var sets = {}; if(type == "schema"){ sets.title = (happy == "happy") ? "Document Classes Created" : "Create Schema from OWL"; sets.text = (happy == "happy") ? "You have successfully created a schema with valid document classes!" : "You can create a schema for your database from an OWL document"; sets.css = "fa fa-cog fa-2x terminus-welcome-icons"; } else if(type == "docs"){ sets.css = "fa fa-book fa-2x terminus-welcome-icons"; sets.title = "Create Documents"; sets.text = (happy == "happy") ? "Add data to the system through easy to use automatically generated forms for each document type" : "You should create a schema and add at least one document classes before you add data to the system"; } else if(type == "intro"){ sets.css = "fa fa-book fa-2x terminus-welcome-icons"; sets.title = "View Documents"; sets.text = "View the documents in the database and add new ones"; } else if(type == "query"){ sets.css = "fa fa-search fa-2x terminus-welcome-icons"; sets.title = (happy == "happy") ? "Run Queries" : "Create Schema with Queries"; sets.text = (happy == "happy") ? "You can add data to the system with queries and scripts, and import data directly from CSVs and URLs" : "You can write WOQL queries to create a schema through our query interface"; } else if(type == "demo"){ sets.css = "fa fa-database fa-2x terminus-welcome-icons"; var dbrec = this.ui.getDBRecord(); if(dbrec) var nm = (dbrec["rdfs:label"] && dbrec["rdfs:label"]["@value"] ? dbrec["rdfs:label"]["@value"] : this.ui.db()); else var nm = this.ui.db(); sets.title = nm ; sets.text = ""; } else if(type == "delete"){ sets.css = "fa fa-trash fa-2x terminus-welcome-icons terminus-db-list-del-icon"; sets.title = "Delete Database"; sets.text = "This will delete all data and permanently remove all record of this database from the system"; } var ispan = document.createElement("span"); ispan.setAttribute("class", "terminus-db-widget"); var ic = document.createElement("i"); ic.setAttribute("class", sets.css); ispan.appendChild(ic); hbox.appendChild(ispan); var htit = document.createElement("span"); htit.appendChild(document.createElement("strong").appendChild(document.createTextNode(sets.title))); htit.classList.add('terminus-welcome-title'); hbox.appendChild(htit); var body = document.createElement("p"); body.setAttribute('class', 'terminus-welcome-body'); body.appendChild(document.createTextNode(sets.text)); hbox.appendChild(body); if(type == "schema"){ hbox.addEventListener("click", function(){ self.ui.page = "schema"; self.ui.showSchemaPage(); self.ui.clearMessages(); self.ui.redrawControls(); }); }; if(type == "delete"){ ispan.addEventListener("click", function(){ self.ui.clearMessages(); let db = self.ui.db(); let deleteConfirm = confirm(`This action is irreversible, it will remove the database from the system permanently. Are you sure you want to delete ${db} Database?`); if (deleteConfirm == true) { self.ui.deleteDatabase(); self.ui.client.connectionConfig.dbid = false; self.ui.redrawControls(); } }); } if(type == "intro" || (type == "docs" && false && !chooser)){ hbox.addEventListener("click", function(){ self.ui.page = "docs"; self.ui.showDocumentPage(); self.ui.clearMessages(); self.ui.redrawControls(); }); }; if(type == "query"){ hbox.addEventListener("click", function(){ self.ui.page = "query"; self.ui.showQueryPage(); self.ui.clearMessages(); self.ui.redrawControls(); }); }; if(type == "query" || type == "schema" || type == "intro"){ hbox.addEventListener('mouseover', function(){ this.style.cursor = "pointer"; }); } if(type == "docs" && false && chooser){ var sp = document.createElement('span'); sp.setAttribute('class', 'terminus-welcome-chooser'); sp.appendChild(chooser); hbox.appendChild(sp); } return hbox; } TerminusDBViewer.prototype.getNavigationDOM = function(docClasses, docs){ var s = document.createElement("span"); s.setAttribute('class', 'terminus-back-to-home terminus-backtohome-span'); var i = document.createElement("span"); i.setAttribute("class", "fa fas fa-arrow-left"); s.appendChild(i); var p = this.pages[this.pages.length-2]; if(p){ var msg = (p == "home" ? "document list" : p) s.appendChild(document.createTextNode(" back to " + msg)); } else { this.pages.push("home"); s.appendChild(document.createTextNode(" back to document list ")); } s.addEventListener("click", () => { var pp = this.pages.pop(); p = this.pages[this.pages.length-1]; if(p == "home"){ delete(this["docid"]); this.getAsDOM(); } else { pp = this.pages.pop(); this.docid = pp; this.showDocumentPage(pp, docClasses, false, docs); } }); s.addEventListener('mouseover', function(){ this.style.cursor = "pointer"; }); return s; } TerminusDBViewer.prototype.insertDocument = function(docid, insertDOM, config, nuke){ var dp = this.tv.getDocument(docid, config); dp.load().then(() => { if(nuke) HTMLHelper.removeChildren(insertDOM); insertDOM.appendChild(dp.getAsDOM()); }) .catch((e) => this.ui.showError(e)); } TerminusDBViewer.prototype.getShowDocumentControl = function(docClasses, docs, target){ var scd = document.createElement("span"); scd.setAttribute("class", "terminus-get-doc terminus-document-chooser terminus-form-horizontal terminus-control-group"); var lab = document.createElement("span"); lab.setAttribute("class", "terminus-document-chooser-label terminus-doc-control-label terminus-control-label-padding"); var dcip = document.createElement("input"); dcip.setAttribute("class", "terminus-form-doc-value terminus-document-chooser terminus-doc-input-text"); dcip.setAttribute("placeholder", "Enter Document ID to view ..."); var nbut = document.createElement("button"); nbut.setAttribute('class', "terminus-control-button terminus-document-button terminus-btn"); nbut.setAttribute('title', 'Enter Document ID to view'); var is = document.createElement('i'); is.setAttribute('class', 'fa fa-caret-left'); nbut.appendChild(is); nbut.appendChild(document.createTextNode(" Load ")); var i = document.createElement('i'); i.setAttribute('class', 'fa fa-caret-right'); nbut.appendChild(i); var self = this; nbut.addEventListener("click", function(){ if(dcip.value) { self.showDocumentPage(dcip.value, docClasses, target, docs); } }) dcip.addEventListener("keyup", function(event) { event.preventDefault(); if (event.keyCode === 13 && dcip.value) { self.showDocumentPage(dcip.value, docClasses, target, docs); } }); scd.appendChild(lab); scd.appendChild(dcip); scd.appendChild(nbut); return scd; } /** * Class Representing the create Database form * @param {TerminusUI} ui */ function TerminusDBCreator(ui){ this.ui = ui; } TerminusDBCreator.prototype.getAsDOM = function(selected){ var scd = document.createElement("div"); scd.setAttribute("class", "terminus-db-creator"); var sct = document.createElement("h3"); sct.setAttribute("class", "terminus-db-creator-title terminus-module-head"); sct.appendChild(UTILS.getHeaderDom("Create Database")); scd.appendChild(sct); var mfd = document.createElement('div'); mfd.setAttribute('class', 'terminus-form-border '); scd.appendChild(mfd); var dht = document.createElement('div'); dht.setAttribute('class', 'terminus-form-margin-top'); mfd.appendChild(dht); var sci = document.createElement("div"); sci.setAttribute("class", "terminus-form-field terminus-form-field-spacing terminus-form-horizontal terminus-control-group"); var slab = document.createElement("span"); slab.setAttribute("class", "terminus-id-label terminus-form-label terminus-control-label"); slab.appendChild(document.createTextNode("ID")); sci.appendChild(slab); var idip = document.createElement("input"); idip.setAttribute("type", "text"); idip.setAttribute("class", "terminus-form-value terminus-input-text"); idip.setAttribute("placeholder", "No spaces or special characters allowed in IDs"); sci.appendChild(idip); mfd.appendChild(sci); var sci = document.createElement("div"); sci.setAttribute("class", "terminus-form-field terminus-form-field-spacing terminus-form-horizontal terminus-control-group"); var slab = document.createElement("span"); slab.setAttribute("class", "terminus-title-label terminus-form-label terminus-control-label"); slab.appendChild(document.createTextNode("Title")); var titip = document.createElement("input"); titip.setAttribute("type", "text"); titip.setAttribute("placeholder", "A brief title for the Database"); titip.setAttribute("class", "terminus-form-value terminus-input-text"); sci.appendChild(slab); sci.appendChild(titip); mfd.appendChild(sci); var sci = document.createElement("div"); sci.setAttribute("class", "terminus-form-field terminus-form-field-spacing terminus-form-horizontal terminus-control-group"); var slab = document.createElement("span"); slab.setAttribute("class", "terminus-title-label terminus-form-label terminus-control-label"); slab.appendChild(document.createTextNode("Description")); sci.appendChild(slab); var descip = document.createElement("textarea"); descip.setAttribute("class", "terminus-textarea terminus-db-description terminus-textarea "); descip.setAttribute("placeholder", "A short text describing the database and its purpose"); sci.appendChild(descip); mfd.appendChild(sci); var butfield = document.createElement("div"); butfield.setAttribute("class", "terminus-control-buttons"); var cancbut = document.createElement("button"); cancbut.setAttribute("class", "terminus-control-button terminus-cancel-db-button terminus-btn terminus-btn-float-right"); cancbut.appendChild(document.createTextNode("Cancel")); var loadbut = document.createElement("button"); loadbut.setAttribute("class", "terminus-control-button terminus-create-db-button terminus-btn terminus-btn-float-right"); loadbut.appendChild(document.createTextNode("Create")); var self = this; var gatherips = function(){ var input = {}; input.id = idip.value; input.title = titip.value; input.description = descip.value; //input.schema = schem.value; //input.key = kip.value; //input.data = datip.value; return input; } var self = this; loadbut.addEventListener("click", function(){ var input = gatherips(); self.ui.createDatabase(input); }) cancbut.addEventListener("click", function(){ self.ui.showServerMainPage(); }) butfield.appendChild(cancbut); butfield.appendChild(loadbut); mfd.appendChild(butfield); return scd; } /* * User Interface elements dealing with database level functions - view, delete, create, db * view document etc */ function TerminusDBController(ui){ this.ui = ui; } /* * Controller provides access to the server level functions (create/delete db) and db-level functions (schema, query, document) * Populates left hand column on dashboard page */ TerminusDBController.prototype.getAsDOM = function(){ var self = this; var dbc = document.createElement("div"); dbc.setAttribute("class", "terminus-db-controller"); if(this.ui && this.ui.db()){ var scd = document.createElement("div"); scd.setAttribute("class", "terminus-field terminus-db-connection"); var dbrec = this.ui.client.connection.getDBRecord(); var nm = (dbrec && dbrec["rdfs:label"] && dbrec["rdfs:label"]["@value"] ? dbrec["rdfs:label"]["@value"] : this.ui.db()); //dbc.appendChild(scd); var nav = document.createElement('div'); nav.setAttribute('class', 'span3'); dbc.appendChild(nav); var ul = document.createElement('ul'); ul.setAttribute('class','terminus-ul' ); nav.appendChild(ul); // connected to db var a = document.createElement('a'); a.setAttribute('class', 'terminus-dashboard-info terminus-a terminus-list-group-a terminus-list-group-a-action terminus-nav-width terminus-pointer"'); a.appendChild(document.createTextNode(nm)); ul.appendChild(a); var p = this.ui.page ? this.ui.page : "db"; if(this.ui.showControl("db")){ if(p == "db") { a.classList.add("terminus-selected"); self.ui.page = "db"; } a.addEventListener("click", function(event){ event.stopPropagation(); self.ui.showDBMainPage(); self.ui.page = "db"; self.ui.clearMessages(); self.ui.redrawControls(); }); } if(this.ui.showControl("get_document")){ var item = this.getControlHTML("Documents", "fas fa fa-book"); if(p == "docs") item.classList.add("terminus-selected"); item.addEventListener("click", function(event){ event.stopPropagation(); self.ui.showDocumentPage(); self.ui.clearMessages(); self.ui.page = "docs"; self.ui.redrawControls(); }); ul.appendChild(item); } if(this.ui.showControl("delete_database")){ var item = this.getControlHTML("Delete Database", "fa-trash-alt"); item.addEventListener("click", function(event){ UTILS.activateSelectedNav(this, self); self.ui.clearMessages(); self.ui.deleteDatabase(); }); ul.appendChild(item); } if(this.ui.showControl("woql_select")){ var item = this.getControlHTML("Query", "fa-search"); if(p == "query") item.classList.add("terminus-selected"); item.addEventListener("click", function(event){ UTILS.activateSelectedNav(this, self); event.stopPropagation(); self.ui.page = "query"; self.ui.showQueryPage(); self.ui.clearMessages(); self.ui.redrawControls(); }); ul.appendChild(item); } if(this.ui.showControl("get_schema")){ var item = this.getControlHTML("Schema", "fa-cog"); if(p == "schema") item.classList.add("terminus-selected"); item.addEventListener("click", function(){ UTILS.activateSelectedNav(this, self); self.ui.page = "schema"; self.ui.showSchemaPage(); self.ui.clearMessages(); self.ui.redrawControls(); }) ul.appendChild(item); } } return dbc; } TerminusDBController.prototype.getControlHTML = function(text, ic, css){ var self = this; var a = document.createElement('a'); a.setAttribute('class', 'terminus-a terminus-list-group-a terminus-list-group-a-action terminus-nav-width terminus-pointer'); var icon = document.createElement('i'); icon.setAttribute('class', 'terminus-menu-icon fa ' + ic); a.appendChild(icon); var txt = document.createTextNode(text); a.appendChild(txt); return a; } module.exports={TerminusDBViewer:TerminusDBViewer, TerminusDBController:TerminusDBController, TerminusDBCreator:TerminusDBCreator} <file_sep>/src/html/document/SimpleFrameViewer.js const HTMLHelper = require("../HTMLHelper"); function SimpleFrameViewer(){} SimpleFrameViewer.prototype.getScope = function(frame){ if(frame.isProperty()) return "property"; if(frame.isObject()) return "object"; if(frame.isData()) return "data"; } SimpleFrameViewer.prototype.setDatatypeViewers = function(datatypes){ this.datatypes = datatypes; } SimpleFrameViewer.prototype.getDatatypeViewer = function(frame, mode){ var dv = frame.display_options.dataviewer; if(!dv){ if(frame.isChoice()) var t = "oneOf"; else if(frame.isDocument()) var t = "document"; else t = frame.getType(); if(mode && mode == "edit"){ var r = this.datatypes.getEditor(t); } else { var r = this.datatypes.getRenderer(t); } dv = r.name; } if(frame.display_options.args){ var args = frame.display_options.args ; } else { if(r && r.args){ args = r.args; } else args = false; } var rend = this.datatypes.createRenderer(dv, args); rend.type = frame.getType(); return rend; } SimpleFrameViewer.prototype.render = function(frame){ if(!frame) frame = this.frame; if(!frame) return; var scope = this.getScope(frame); if(frame.display_options.header_features && frame.display_options.header_features.length){ var hfeatures = this.getFeaturesDOM(frame.display_options.header_features, scope, frame, frame.display_options.mode); } else var hfeatures = false; if(frame.display_options.features && frame.display_options.features.length){ var features = this.getFeaturesDOM(frame.display_options.features, scope, frame, frame.display_options.mode); } else var features = false; var orient = (scope == "object" || scope == "property") ? "page" : "line"; var ndom = HTMLHelper.getFrameDOM(scope, frame, orient, hfeatures, features); if(!ndom) return false; if(this.framedom){ this.framedom.replaceWith(ndom); } this.framedom = ndom; if(frame.display_options.style){ this.framedom.setAttribute("style", frame.display_options.style); } return this.framedom; } SimpleFrameViewer.prototype.getFeaturesDOM = function(flist, scope, frame, mode){ var features = document.createElement("span"); features.setAttribute("class", "terminus-features terminus-" + scope + "-features features-" + featuresToCSS(flist)); for(var i = 0; i<flist.length; i++){ let render = false; let style = false; let args = false; let fid = flist[i]; if(typeof fid == "object"){ fid = Object.keys(flist[i])[0]; if(flist[i][fid].hidden) continue; if(flist[i][fid].style) style = flist[i][fid].style; if(flist[i][fid].render) render = flist[i][fid].render; if(flist[i][fid].args){ args = flist[i][fid].args; } } else if(typeof fid != "string") continue; if(render){ var dom = render(frame, fid, scope, mode, args); if(style) dom.setAttribute("style", style); if(dom) features.appendChild(dom); } else if(fid == "value"){ if(scope == "data"){ var dv = this.getDatatypeViewer(frame, mode, args); if(dv) { var dom = dv.renderFrame(frame, this); } else { var dom = document.createTextNode(frame.get()); } if(dom){ if(style) dom.setAttribute("style", style); features.appendChild(dom); } } else { if(scope == 'object'){ var vals = frame.renderProperties(); for(var j = 0; j<vals.length; j++){ if(style) vals[j].setAttribute("style", style); features.appendChild(vals[j]); } } else { var vals = frame.renderValues(); var cont = document.createElement("span"); if(style) cont.setAttribute("style", style); for(var j = 0; j<vals.length; j++){ cont.appendChild(vals[j]); } features.appendChild(cont); } } } else { if(fid == "id" && mode == "edit" && scope == "object" && frame.isNew()){ var rend = this.datatypes.createRenderer("HTMLStringEditor", args); var dom = rend.renderFrame(frame, this); } else var dom = false; var dom = HTMLHelper.getFeatureDOM(frame, fid, scope, mode, args, dom); if(dom){ if(style) dom.setAttribute("style", style); features.appendChild(dom); } } } return features; } function featuresToCSS(flist){ var s = ""; for(var i = 0; i<flist.length; i++){ if(typeof flist[i] == "object"){ s += Object.keys(flist[i])[0] + "-"; } else { s += flist[i] + "-"; } } return s.substring(0, s.length-1); } module.exports = SimpleFrameViewer;<file_sep>/src/test.js var TerminusDashboard = require('./index.js'); var TerminusUI= TerminusDashboard.WOQL; console.log(TerminusDashboard.WOQL.limit(10).json()) <file_sep>/src/html/datatypes/Image.js function HTMLImageViewer(options){} HTMLImageViewer.prototype.options = function(options){} HTMLImageViewer.prototype.renderFrame = function(frame, dataviewer){ return this.render(frame.get()); } HTMLImageViewer.prototype.renderValue = function(dataviewer){ return this.render(dataviewer.value()); } HTMLImageViewer.prototype.render = function(value){ var input = document.createElement("span"); input.setAttribute('class', "terminus-literal-value terminus-literal-image-value"); input.setAttribute('data-value', value); if(value){ var img = document.createElement("a"); img.setAttribute('src', value); input.appendChild(img); } return input; } module.exports={HTMLImageViewer} <file_sep>/src/html/datatypes/Range.js const TerminusClient = require('@terminusdb/terminus-client'); function HTMLRangeViewer(options){ this.options(options); } HTMLRangeViewer.prototype.options = function(options){ this.commas = (options && options.commas ? options.commas : true); this.css = "terminus-literal-value terminus-literal-value-range " + ((options && options.css) ? options.css : ""); this.delimiter = (options && options.delimiter ? options.delimiter : false); } HTMLRangeViewer.prototype.renderFrame = function(frame, dataviewer){ return this.render(frame.get()); } HTMLRangeViewer.prototype.renderValue = function(dataviewer){ return this.render(dataviewer.value()); } HTMLRangeViewer.prototype.render = function(value){ var vals = TerminusClient.UTILS.TypeHelper.parseRangeValue(value, this.delimiter); var d = document.createElement("span"); d.setAttribute("class", this.css); var rvals = document.createElement("span"); rvals.setAttribute("class", "terminus-range-value-left"); var svals = document.createElement("span"); svals.setAttribute("class", "terminus-range-value-right"); var x = (this.useCommas() ? TerminusClient.UTILS.TypeHelper.numberWithCommas(vals[0]) : vals[0]); var tnode = document.createTextNode(x); rvals.appendChild(tnode); d.appendChild(rvals); if(vals.length == 2){ d.appendChild(getRangeSymbolDOM()); var x2 = (this.useCommas() ? TerminusClient.UTILS.TypeHelper.numberWithCommas(vals[1]) : vals[1]); var t2node = document.createTextNode(x2); svals.appendChild(t2node); d.appendChild(svals); } return d; } HTMLRangeViewer.prototype.useCommas = function(){ if(["xdd:gYearRange", "xdd:dateRange"].indexOf(this.type) != -1) return false; return this.commas; } function getRangeSymbolDOM(){ var d = document.createElement("span"); d.setAttribute("class", "terminus-range-indicator"); d.setAttribute("title", "The value is uncertain, it lies somewhere in this range"); d.appendChild(document.createTextNode(" ... ")); return d; } module.exports={HTMLRangeViewer} <file_sep>/src/html/DocumentPane.js const TerminusCodeSnippet = require('./query/TerminusCodeSnippet'); const UTILS = require('../Utils'); const HTMLHelper = require('./HTMLHelper'); //const TerminusFrame = require("../old/viewer/TerminusFrame"); const TerminusClient = require('@terminusdb/terminus-client'); const SimpleFrameViewer = require("./document/SimpleFrameViewer"); const Datatypes = require("./Datatypes"); const DatatypeRenderers = require("./DatatypeRenderers"); function DocumentPane(client, docid, clsid){ this.client = client; this.container = document.createElement('span'); this.container.setAttribute('class', 'terminus-document-cont'); this.defaultPaneView = { showConfig: false, editConfig: false, intro: false, loadSchema: false }; this.docid = (docid ? docid : false); this.clsid = (clsid ? clsid : false); this.datatypes = new DatatypeRenderers(); //Datatypes.initialiseDataRenderers(this.datatypes); } DocumentPane.prototype.load = function(){ if(this.docid || this.clsid){ this.frame = new TerminusClient.DocumentFrame(this.client, this.view); this.frame.owner = this; } if(this.docid){ return this.frame.load(this.docid, this.clsid) .then(() => this.filterFrame()); } if(this.clsid){ return this.frame.load(false, this.clsid).then(() => { this.frame.document.fillFromSchema("_:"); this.filterFrame(); }); } return Promise.reject("Either document id or class id must be specified before loading a document"); } DocumentPane.prototype.options = function(opts){ this.showQuery = (opts && typeof opts.showQuery != "undefined" ? opts.showQuery : false); this.showConfig = (opts && typeof opts.showConfig != "undefined" ? opts.showConfig : false); this.editConfig = (opts && typeof opts.editConfig != "undefined" ? opts.editConfig : false); this.intro = (opts && typeof opts.intro != "undefined" ? opts.intro : false); this.documentLoader = (opts && typeof opts.loadDocument != "undefined" ? opts.loadDocument : false); this.loadSchema = (opts && typeof opts.loadSchema != "undefined" ? opts.loadSchema : false); this.viewers = (opts && typeof opts.viewers != "undefined" ? opts.viewers : false); Datatypes.initialiseDataRenderers(this.datatypes, false, opts); return this; } DocumentPane.prototype.filterFrame = function(){ var self = this; var myfilt = function(frame, rule){ if(typeof rule.render() != "undefined"){ frame.render = rule.render(); } else { if(rule.renderer()){ var renderer = self.loadRenderer(rule.renderer(), frame, rule.args); } if(renderer && renderer.render){ frame.render = function(fframe){ return renderer.render(fframe); } } } if(rule.compare()){ frame.compare = rule.compare(); } } this.frame.applyRules(false, false, myfilt); } DocumentPane.prototype.loadDocument = function(docid, config){ this.docid = docid; this.view = config; return this.load(); } DocumentPane.prototype.loadClass = function(cls, config){ this.clsid = cls; this.docid = false; this.view = config; return this.load(); } DocumentPane.prototype.setClassLoader = function(cloader){ this.classLoader = cloader; if(this.queryPane){ this.queryPane.appendChild(this.classLoader); } return this; } DocumentPane.prototype.getQueryPane = function(){ var pane = document.createElement("div"); pane.setAttribute("class", "terminus-document-query"); if(this.documentLoader){ pane.appendChild(this.documentLoader); } if(this.classLoader){ pane.appendChild(this.classLoader); } return pane; } DocumentPane.prototype.getAsDOM = function(){ if(this.intro){ this.container.appendChild(UTILS.getHeaderDom(this.intro)); } var configspan = document.createElement("span"); configspan.setAttribute("class", "pane-config-icons"); this.container.appendChild(configspan); if(this.showQuery && (this.documentLoader || this.classLoader)){ var ipdom = this.getQueryPane(); var ispan = document.createElement("span"); ispan.setAttribute("class", "document-pane-config"); var ic = document.createElement("i"); ispan.appendChild(ic); if(this.showQuery != "always") configspan.appendChild(ispan); var self = this; function showQueryConfig(){ ispan.title="Click to Hide Query"; ic.setAttribute("class", "fas fa fa-times-circle"); if(configspan.nextSibling) self.container.insertBefore(ipdom, configspan.nextSibling); else self.container.appendChild(ipdom); } function hideQueryConfig(){ ispan.title="Click to View Query"; ic.setAttribute("class", "fas fa fa-search"); self.container.removeChild(ipdom); } ispan.addEventListener("click", () => { if(this.showingQuery) hideQueryConfig(); else showQueryConfig(); this.showingQuery = !this.showingQuery; }); showQueryConfig(); if(this.showQuery == "icon") hideQueryConfig(); this.queryPane = ipdom; } if(this.showConfig){ this.showingConfig = (this.showConfig != "icon"); var mode = (this.editConfig ? "edit" : "view"); this.input = this.createInput(mode); var ndom = this.input.getAsDOM(); var nspan = document.createElement("span"); nspan.addEventListener('mouseover', function(){ this.style.cursor = "pointer"; }); nspan.setAttribute("class", "result-pane-config"); var nc = document.createElement("i"); nspan.appendChild(nc); configspan.appendChild(nspan); var self = this; function showDocConfig(){ nspan.title="Click to Hide View Configuration"; nc.setAttribute("class", "fas fa fa-times-circle"); if(configspan.nextSibling) self.container.insertBefore(ndom, configspan.nextSibling); else self.container.appendChild(ndom); //stylize only after ta or pre have been appended if((self.input.snippet.value) || (self.input.snippet.innerHTML)) self.input.stylizeSnippet(); } function hideDocConfig(){ nspan.title="Click to View Configuration"; nc.setAttribute("class", "fas fa fa-vial"); self.container.removeChild(ndom); } nspan.addEventListener("click", () => { if(this.showingConfig) hideDocConfig(); else showDocConfig(); this.showingConfig = !this.showingConfig; }); showDocConfig(); if(this.showConfig == "icon") hideDocConfig(); } this.resultDOM = document.createElement("span"); this.resultDOM.setAttribute("class", "terminus-document-results"); //var form = (this.input.format == "js" ? "javascript" : "json"); //UTILS.stylizeEditor(ui, this.input.snippet, {width: this.input.width, height: this.input.height}, form); this.container.appendChild(this.resultDOM); this.renderResult(); return this.container; } DocumentPane.prototype.renderResult = function(){ if(this.resultDOM){ HTMLHelper.removeChildren(this.resultDOM); } else { this.resultDOM = document.createElement("span"); this.resultDOM.setAttribute("class", "terminus-document-results"); //var form = (this.input.format == "js" ? "javascript" : "json"); //UTILS.stylizeEditor(ui, this.input.snippet, {width: this.input.width, height: this.input.height}, form); this.container.appendChild(this.resultDOM); } if(this.frame && this.frame.document.render){ var fpt = this.frame.document.render(); if(fpt){ this.resultDOM.appendChild(fpt); } } } DocumentPane.prototype.loadRenderer = function(rendname, frame, args, termframe){ var evalstr = "new " + rendname + "("; if(args) evalstr += JSON.stringify(args); evalstr += ");"; try { var nr = eval(evalstr); nr.frame = frame; nr.datatypes = this.datatypes; return nr; } catch(e){ console.log("Failed to load " + rendname + e.toString()); return false; } } DocumentPane.prototype.createInput = function(mode){ let input = new TerminusCodeSnippet("rule", mode); if(this.view){ input.setQuery(this.view); } var self = this; input.submit = function(qObj){ self.updateView(qObj); }; return input; } DocumentPane.prototype.updateView = function(docview){ this.view = docview; this.frame.options(this.view); if(this.input) this.input.setQuery(this.view); this.frame.applyRulesToDocument(this.frame.document, this.frame.config); this.frame.renderer = this.frame.document; this.renderResult(); } DocumentPane.prototype.updateResult = function(result){ this.result = result; this.updateQuery(result.query); this.refreshViews(); } DocumentPane.prototype.empty = function(){ return (typeof this.view == "undefined"); } DocumentPane.prototype.clearMessages = function(){} DocumentPane.prototype.showError = function(){} DocumentPane.prototype.submitQuery = function(qObj){ this.clearMessages(); tdv.owner = this; tdv.setDatatypes(Datatypes.initialiseDataRenderers); tdv.loadDocument(id).then(() => { let dom = tdv.render(); if(dom) holder.appendChild(dom); }); return holder; } module.exports = DocumentPane; <file_sep>/src/html/datatypes/DateEditor.js const DateHelper = require('./DateHelper'); const TerminusClient = require('@terminusdb/terminus-client'); function HTMLDateEditor(options){ this.options(options); } HTMLDateEditor.prototype.options = function(options){ this.max = (options && options.max ? options.max : false); this.min = (options && options.min ? options.min : false); this.allowbce = (options && options.allowbce ? options.allowbce : false); this.date_spacer = "/"; this.time_spacer = ":"; this.datetime_separator = ", "; this.helper = new DateHelper.HTMLDateHelper(); } HTMLDateEditor.prototype.renderFrame = function(frame, dataviewer){ var value = frame.get(); var input = document.createElement("span"); input.setAttribute('class', "terminus-literal-value terminus-literal-date"); input.setAttribute('data-value', value); if(value){ this.parsed = TerminusClient.UTILS.DateHelper.parseDate(this.type, value); } else this.parsed = {}; var datepart = this.getDateComponentDOM(this.parsed, this.type, frame); var timepart = this.getTimeComponentDOM(this.parsed, this.type, frame); if(timepart) input.appendChild(timepart); if(timepart && datepart) input.appendChild(document.createTextNode(this.datetime_separator)); if(datepart) input.appendChild(datepart); return input; } HTMLDateEditor.prototype.set = function(part, val, frame, ty){ this.parsed[part] = val; var xsd = TerminusClient.UTILS.DateHelper.xsdFromParsed(this.parsed, ty); if(xsd){ frame.set(xsd); } } HTMLDateEditor.prototype.getTimeComponentDOM = function(parsed, ty, frame){ if(["xsd:dateTime", "xsd:dateTimeStamp", "xsd:time"].indexOf(ty) == -1){ return false; } var self = this; var hdom = document.createElement("input"); hdom.setAttribute("class", "terminus-hour-input terminus-hour-"+ty); hdom.setAttribute("size", 2); hdom.setAttribute("placeholder", "HH"); hdom.value = (parsed.hour ? parsed.hour : ""); hdom.addEventListener("input", function(){ self.set("hour", this.value, frame, ty); }); var mdom = document.createElement("input"); mdom.setAttribute("class", "terminus-minute-input terminus-minute-"+ty); mdom.setAttribute("size", 2); mdom.setAttribute("placeholder", "MM"); mdom.value = (parsed.minute ? parsed.minute: ""); mdom.addEventListener("input", function(){ self.set("minute", this.value, frame, ty); }); var sdom = document.createElement("input"); sdom.setAttribute("class", "terminus-second-input terminus-second-"+ty); sdom.setAttribute("size", 8); sdom.setAttribute("placeholder", "SS.sss..."); sdom.value = (parsed.second ? parsed.second: ""); sdom.addEventListener("input", function(){ self.set("second", this.value, frame, ty); }) var tdom = document.createElement("span"); tdom.appendChild(hdom); tdom.appendChild(document.createTextNode(this.time_spacer)); tdom.appendChild(mdom); tdom.appendChild(document.createTextNode(this.time_spacer)); tdom.appendChild(sdom); return tdom; } HTMLDateEditor.prototype.getDateComponentDOM = function(parsed, ty, frame){ var self = this; if(["xsd:date", "xsd:dateTime", "xsd:gYear", "xsd:gYearMonth", "xsd:dateTimeStamp"].indexOf(ty) != -1){ var ydom = document.createElement("input"); ydom.setAttribute("class", "terminus-year-input terminus-year-"+ty); ydom.setAttribute("size", 6); ydom.setAttribute("placeholder", "YYYY"); ydom.value = (parsed.year ? parsed.year : ""); ydom.addEventListener("input", function(){ self.set("year", this.value, frame, ty); }) } if(["xsd:date", "xsd:dateTime", "xsd:gYearMonth", "xsd:dateTimeStamp", "xsd:gMonth", "xsd:gMonthDay"].indexOf(ty) != -1){ var mdom = document.createElement("select"); mdom.setAttribute("class", "terminus-month-input terminus-month-"+ty); for(var i = 0; i<this.helper.months.length; i++){ var opdom = document.createElement("option"); opdom.value = i+1; opdom.appendChild(document.createTextNode(this.helper.months[i])); if(parsed.month && parsed.month == i+1){ opdom.selected = true; } mdom.appendChild(opdom); } mdom.addEventListener("change", function(){ self.set("month", this.value, frame, ty); }) } if(["xsd:date", "xsd:dateTime", "xsd:dateTimeStamp", "xsd:gDay", "xsd:gMonthDay"].indexOf(ty) != -1){ var ddom = document.createElement("input"); ddom.setAttribute("class", "terminus-day-input terminus-day-"+ty); ddom.setAttribute("size", 2); ddom.setAttribute("placeholder", "DD"); ddom.value = (parsed.day ? parsed.day : ""); ddom.addEventListener("input", function(){ self.set("day", this.value, frame, ty); }) } if(ydom || mdom || ddom){ var dadom = document.createElement("span"); if(ddom) dadom.appendChild(ddom); if(mdom) { if(ddom) dadom.appendChild(document.createTextNode(this.date_spacer)); dadom.appendChild(mdom); } if(ydom) { if(mdom || ddom) dadom.appendChild(document.createTextNode(this.date_spacer)); dadom.appendChild(ydom); } return dadom; } return false; } module.exports={HTMLDateEditor}<file_sep>/cypress/integration/tests/test_5.spec.js // update document // on clicking on a doc getDocument is also tested context('update document <NAME>', () => { beforeEach(() => { //connect to server and db cy.visit('http://localhost:6363/dashboard'); cy.get('#terminus-content-viewer') .find('table tbody tr td p') .contains('database_e2e_test') .click().then(() => { cy.wait(1000); cy.get('#terminus-content-viewer') .find('a') .contains('doc:JackieChan') .click(); cy.wait(1000); }) }) it('update documents', () => { cy.wait(1000); cy.get('#terminus-content-viewer') .find('div[class="terminus-document-controller"]') .find('select') .select('Edit Document').then(() => { cy.wait(1000); // update comment cy.get('#terminus-content-viewer') .find('div[data-property="rdfs:comment"]') .find('textarea') .focus().clear().type('Updating <NAME> info'); cy.wait(1000); // make <NAME> friends with <NAME> cy.get('#terminus-content-viewer') .find('span[class="terminus-object-add-property"]:first') // the first obj header .find('select') .select('Friend').then(() => { cy.wait(1000); // input friend cy.get('#terminus-content-viewer') .find('div[data-property="tcs:friend"]') .find('input[type="text"]') .focus().type('doc:BruceLee'); cy.wait(1000); }) // add property // add fb a/c cy.get('#terminus-content-viewer') .find('div[data-property="tcs:facebook_page"]') .find('button') .contains('Add') .click().then(() => { cy.wait(1000); cy.get('#terminus-content-viewer') .find('div[data-property="tcs:facebook_page"]') .find('input[type="text"]:eq(1)') .focus().type('https://facebook.secondProfileForJackie'); }) }); // hit save cy.get('#terminus-content-viewer') .find('button') .contains('Save') .click().then(() => { alert('updatedDocument for Person <NAME> success'); }) }) // update document }) <file_sep>/src/TerminusURL.js const UTILS = require("./Utils.js"); function TerminusURLLoader(ui, val){ this.ui = ui; this.val = val; this.url_input = false; this.key_input = false; } TerminusURLLoader.prototype.getLabelDOM = function(){ return document.createTextNode("Connect"); } TerminusURLLoader.prototype.getFormFieldDOM = function(ip, fname, ltxt, pholder){ var sci = document.createElement("div"); sci.setAttribute("class", "terminus-form-horizontal terminus-control-group terminus-form-field-spacing terminus-display-flex terminus-field-"+fname); var lab = document.createElement("span"); lab.setAttribute("class", "terminus-control-label terminus-form-label terminus-form-field-label terminus-label-"+fname); lab.appendChild(document.createTextNode(ltxt)) ip.setAttribute("type", "text"); ip.setAttribute("placeholder", pholder); sci.appendChild(lab); sci.appendChild(ip); return sci; } TerminusURLLoader.prototype.getAsDOM = function(){ var scd = document.createElement("div"); scd.setAttribute("class", "terminus-form terminus-url-loader"); scd.appendChild(UTILS.getHeaderDom('Connect To Terminus Server')); var mfd = document.createElement('div'); mfd.setAttribute('class', 'terminus-form-border terminus-margin-top'); scd.appendChild(mfd); this.url_input = document.createElement("input"); this.url_input.setAttribute("class", "terminus-form-value terminus-form-url terminus-form-field-input terminus-input-text"); if(this.val){ this.url_input.value = this.val; } var dht = document.createElement('div'); dht.setAttribute('class', 'terminus-form-margin-top'); mfd.appendChild(dht); if(!this.ui.attachedServer()){ mfd.appendChild(this.getFormFieldDOM(this.url_input, "connect", "URL", "Terminus DB URL")); } this.key_input = document.createElement("input"); this.key_input.setAttribute("class", "terminus-form-value terminus-value terminus-input-text"); mfd.appendChild(this.getFormFieldDOM(this.key_input, "connect", "Key", "Server API Key")); var loadbuts = document.createElement("div"); loadbuts.setAttribute("class", "terminus-control-buttons"); var loadbut = document.createElement("button"); loadbut.setAttribute("class", "terminus-control-button terminus-url-load terminus-btn terminus-btn-float-right"); loadbut.appendChild(document.createTextNode("Connect")); var self = this; loadbut.addEventListener("click", function(){ let keyval = self.key_input.value; let url = (self.ui.attachedServer() ? self.ui.attachedServer() : self.url_input.value); if(url){ self.ui.load(url, keyval); } }); loadbuts.appendChild(loadbut); mfd.appendChild(loadbuts); return scd; } module.exports=TerminusURLLoader <file_sep>/cypress/integration/tests/test_1.spec.js // test to create a new database context('create database', () => { beforeEach(() => { cy.visit('http://localhost:6363/dashboard'); }) // generate random db info const dbId = 'database_e2e_test'; const dbTitle = "Test db"; const dbCommment = "Test db comment"; it('create database', () => { cy.get('#terminus-control-panel') .find('a') .contains('Create New Database') .click().then(() => { cy.wait(1000) // enter id cy.get('#terminus-content-viewer') .find('input[placeholder="No spaces or special characters allowed in IDs"]') .focus().type(dbId); // enter db name cy.get('#terminus-content-viewer') .find('input[placeholder="A brief title for the Database"]') .focus().type(dbTitle); cy.wait(1000); // enter db comment cy.get('#terminus-content-viewer') .find('textarea[placeholder="A short text describing the database and its purpose"]') .focus().type(dbCommment); cy.wait(1000); // click on create cy.get('#terminus-content-viewer') .find('button').contains('Create').click().then(() => { alert('createDatabase success'); }) cy.wait(2000); }) }) // create database }) <file_sep>/src/html/query/TerminusCodeSnippet.js const TerminusClient = require('@terminusdb/terminus-client'); const UTILS = require('../../Utils'); const HTMLHelper = require("../HTMLHelper") /* qObj: WOQL object width: width of snippet in px height: height of snippet in px */ function TerminusCodeSnippet(language, mode, format, width, height, placeholder){ this.language = (language ? language : "woql");//woql / rule this.mode = (mode ? mode : "view"); this.width = (width ? width : 1200); this.height = (height ? height : 300); this.placeholder = (placeholder ? placeholder : ""); this.format = (format ? format : "js"); this.formats = {'js': "WOQL.js", 'jsonld': "JSON-LD"}; if(this.mode == 'view') this.snippet = document.createElement('pre'); else { this.snippet = document.createElement('textarea'); this.snippet.setAttribute("spellcheck", "false"); this.snippet.setAttribute("class", "terminus-code-snippet"); } } TerminusCodeSnippet.prototype.setQuery = function(q){ this.qObj = q; this.refreshContents(); } TerminusCodeSnippet.prototype.setInput = function(q){ if(this.mode == "edit"){ this.snippet.value = q; } else { HTMLHelper.removeChildren(this.snippet); this.snippet.appendChild(document.createTextNode(q)); } this.refreshCodeMirror(); return this.readInput(); } TerminusCodeSnippet.prototype.serialise = function(query, format){ if(format == "js"){ return query.prettyPrint(4); } else { return JSON.stringify(query.json(), undefined, 2); } } //parses a string encoding a woql in either json or js notation TerminusCodeSnippet.prototype.parseText = function(text, format){ try { var WOQL = TerminusClient.WOQL; var View = TerminusClient.View; if(format == "js"){ var nw = eval(text); if(this.language == "rule"){ this.view = view; return view; } return nw; } else { var qval = JSON.parse(text); if(this.language == "woql"){ return WOQL.json(qval); } else { return View.loadConfig(qval); } } } catch(e){ this.error = "Failed to parse Query " + e.toString() + " " + text; return this.error; //return false; } } TerminusCodeSnippet.prototype.getInputElement = function(){ return this.snippet; } TerminusCodeSnippet.prototype.readInput = function(){ if(this.mode == "edit") { this.qObj = this.parseText(this.snippet.value, this.format); } else { this.qObj = this.parseText(this.snippet.innerText, this.format); } return this.qObj; } TerminusCodeSnippet.prototype.get = function(){ return this.readInput(); } TerminusCodeSnippet.prototype.getAsDOM = function(with_buttons){ var scont = document.createElement('div'); scont.setAttribute('class', 'terminus-snippet-container') // query var snpc = document.createElement('div'); if(this.placeholder){ this.snippet.setAttribute("placeholder", this.placeholder); } snpc.appendChild(this.getFormatButtons()); if(this.qObj){ var serial = this.serialise(this.qObj, this.format); if(this.mode == "edit"){ this.snippet.value = serial; } else { HTMLHelper.removeChildren(this.snippet); this.snippet.appendChild(document.createTextNode(serial)); } } else { this.snippet.value = ""; } snpc.appendChild(this.snippet); if(this.mode == "edit"){ var ssb = document.createElement("span"); ssb.setAttribute("class", "terminus-query-submit-buttons"); var actbtn = this.getSubmitButton(); ssb.appendChild(actbtn); snpc.appendChild(ssb); } scont.appendChild(snpc); return scont; } TerminusCodeSnippet.prototype.changeRuleView = function(nview){ this.snippet.value = "view = WOQL."+ nview + "()"; this.readInput(); this.submit(this.qObj); } TerminusCodeSnippet.prototype.getIconsDOM = function(){ var bsp = document.createElement('span'); bsp.setAttribute('class', 'terminus-snippet-icons'); for(var i = 0; i<this.view_types.length; i++){ var isp = document.createElement('span'); var icon = document.createElement("i"); icon.title = this.view_types[i].label; icon.setAttribute("class", this.view_types[i].icon); isp.appendChild(icon); isp.name = this.view_types[i].id; var self = this; isp.addEventListener('click', function(){ if(!(self.view && self.view.type == this.name)){ self.changeRuleView(this.name); } }); isp.addEventListener('mouseover', function(){ if(!(self.view && self.view.type == this.name)){ this.style.cursor = "pointer"; } }); bsp.appendChild(isp); } return bsp; } TerminusCodeSnippet.prototype.getFormatButtons = function(){ var bsp = document.createElement('span'); bsp.setAttribute('class', 'terminus-snippet-panel'); //if(this.width) bsp.setAttribute("style", "width: "+ this.width +"px;"); for(f in this.formats){ var btn = document.createElement('button'); btn.setAttribute('value', f); btn.setAttribute('class', 'terminus-snippet-button'); if(f == 'js') btn.classList.add('terminus-snippet-format-selected'); btn.appendChild(document.createTextNode(this.formats[f])); var self = this; btn.addEventListener('click', function(){ UTILS.setSelected(this, 'terminus-snippet-format-selected'); var src = (self.mode == "edit" ? self.snippet.value : self.snippet.innerText) var qobj = self.parseText(src, self.format); self.format = this.value; if(qobj) self.qObj = qobj; self.refreshContents(); }) bsp.appendChild(btn); } return bsp; } TerminusCodeSnippet.prototype.getSubmitButton = function(){ var actbtn = document.createElement('button'); actbtn.setAttribute('class', 'terminus-btn'); actbtn.setAttribute('type', 'submit'); var txt = "Submit"; if(this.language == "WOQL"){ txt = "Submit Query"; } else if(this.language == "rule") { txt = "Update View"; } else if(this.language == "code"){ txt = "Run Script"; } actbtn.appendChild(document.createTextNode(txt)); actbtn.addEventListener('click', () => { this.readInput(); this.submit(this.qObj); }); return actbtn; } TerminusCodeSnippet.prototype.submit = function(){ alert("Submitted " + JSON.stringify(this.qObj)); } TerminusCodeSnippet.prototype.removeCodeMirror = function(){ var cm = this.snippet.nextSibling; if(!cm) return; if(cm.classList.contains('CodeMirror')) // remove code mirror HTMLHelper.removeElement(cm); } TerminusCodeSnippet.prototype.stylizeSnippet = function(){ var dimensions = "query"; //dimensions.width = "1000";//this.width; //dimensions.height = "1000";//this.height; this.removeCodeMirror(); if(this.mode == 'view') UTILS.stylizeCodeDisplay(null, this.snippet, null, 'javascript'); else UTILS.stylizeEditor(null, this.snippet, dimensions, 'javascript'); // default view is js } TerminusCodeSnippet.prototype.refreshContents = function(qObj){ qObj = qObj || this.qObj; HTMLHelper.removeChildren(this.snippet); if(this.mode == "edit") this.snippet.value == ""; if(!qObj) return; var serial = this.serialise(this.qObj, this.format); if(this.mode == "edit"){ this.snippet.value = serial; if(this.snippet.nextSibling){ this.removeCodeMirror(); if(this.format == 'js') var mode = 'javascript'; else var mode = 'application/ld+json'; UTILS.stylizeEditor(null, this.snippet, {width: this.width, height: this.height}, mode); } } else { this.snippet.appendChild(document.createTextNode(serial)); UTILS.stylizeCodeDisplay(null, this.snippet, null, mode); } } TerminusCodeSnippet.prototype.refreshCodeMirror = function(){ if(this.snippet.nextSibling){ this.removeCodeMirror(); } if(this.format == 'js') var mode = 'javascript'; else var mode = 'application/ld+json'; if(this.mode == "edit"){ UTILS.stylizeEditor(null, this.snippet, {width: this.width, height: this.height}, mode); } else { UTILS.stylizeCodeDisplay(null, this.snippet, null, mode); } } module.exports = TerminusCodeSnippet; <file_sep>/src/html/datatypes/Link.js function HTMLLinkViewer(options){ this.options(options); } HTMLLinkViewer.prototype.options = function(options){ this.css = "terminus-literal-value terminus-literal-value-range " + ((options && options.css) ? options.css : ""); } HTMLLinkViewer.prototype.renderFrame = function(frame, dataviewer){ return this.render(frame.get()); } HTMLLinkViewer.prototype.renderValue = function(dataviewer){ return this.render(dataviewer.value()); } HTMLLinkViewer.prototype.render = function(value){ var input = document.createElement("span"); input.setAttribute('class', this.css); input.setAttribute('size', 80); input.setAttribute('data-value', value); if(value){ var a = document.createElement("a"); a.setAttribute('href', value); a.appendChild(document.createTextNode(value)); input.appendChild(a); } return input; } module.exports={HTMLLinkViewer} <file_sep>/src/TerminusQuery.js const TerminusClient = require('@terminusdb/terminus-client'); const ScriptPane = require("./html/ScriptPane"); const HTMLHelper = require('./html/HTMLHelper'); const TerminusViewer = require("./html/TerminusViewer"); function TerminusQueryViewer(ui, options){ this.ui = ui; this.tv = new TerminusViewer(ui.client); this.options = options; this.panes = []; this.new_pane = false; this.new_pane_type = false; this.meta = {}; this.container = document.createElement("div"); this.container.setAttribute("class", "terminus-query-page"); } TerminusQueryViewer.prototype.newPaneOptions = function(){ var opts = { showQuery: "always", editQuery: true, showHeader: true, css: "terminus-full-query-pane" }; return opts; } TerminusQueryViewer.prototype.defaultResultOptions = function(){ var opts = { showConfig: "icon", editConfig: true, showHeader: false, viewers: [new TerminusClient.View.graph()], }; return opts; } TerminusQueryViewer.prototype.getNewQueryPane = function(){ let table = TerminusClient.View.table(); let qpane = this.tv.getQueryPane(false, [table], false, [this.defaultResultOptions()], this.newPaneOptions()); return qpane; } TerminusQueryViewer.prototype.addQueryPane = function(){ var qpane = this.getNewQueryPane(); this.panes.push(qpane); return qpane; } TerminusQueryViewer.prototype.addScriptPane = function(q){ let qpane = new ScriptPane(this.ui.client, q); this.panes.push(qpane); return qpane; } TerminusQueryViewer.prototype.addScriptPaneDOM = function(){ let qpane = new ScriptPane(this.ui.client); this.addNewPaneDOM(qpane); } TerminusQueryViewer.prototype.addQueryPaneDOM = function(){ let qpane = this.addQueryPane(); this.addNewPaneDOM(qpane); } TerminusQueryViewer.prototype.setNewDocumentPaneDOM = function(){ this.new_pane = this.tv.getDocumentPane(); //this.new_pane = new DocumentPane(this.ui.client).options({showQuery: true, editQuery: true}); this.new_pane_type = "document"; } TerminusQueryViewer.prototype.addNewPaneDOM = function(qpane){ var lpane = this.panes[this.panes.length-1]; //if(lpane && lpane.empty()){ // this.panes[this.panes.length-1] = qpane; // this.paneDOM.removeChild(this.paneDOM.lastChild) //} //else { this.panes.push(qpane); //} var qdom = qpane.getAsDOM(); var qhdr = this.getPaneHeader(); qdom.prepend(qhdr); this.paneDOM.appendChild(qdom); } TerminusQueryViewer.prototype.getAsDOM = function(q){ HTMLHelper.removeChildren(this.container); if(!this.paneDOM) this.paneDOM = this.getPanesDOM(); this.container.appendChild(this.paneDOM); this.controlDOM = this.getControlsDOM(); //this.container.appendChild(this.controlDOM); var cont = document.createElement("span"); cont.setAttribute("class", "terminus-new-query-pane"); var newPaneButton = document.createElement('button'); newPaneButton.setAttribute('class', 'terminus-btn terminus-query-btn'); newPaneButton.appendChild(document.createTextNode('Add New Query')); newPaneButton.addEventListener('click', () => this.addQueryPaneDOM()); cont.appendChild(newPaneButton); this.container.appendChild(cont); return this.container; } TerminusQueryViewer.prototype.getPanesDOM = function(q){ this.panesDOM = document.createElement("div"); this.panesDOM.setAttribute("class", "terminus-query-panes"); for(var i = 0; i<this.panes.length; i++){ var pd = this.panes[i].getAsDOM(); var qhdr = this.getPaneHeader(); pd.prepend(qhdr); this.panesDOM.appendChild(pd); } if(!this.new_pane){ this.new_pane = this.getNewQueryPane(); } var npd = this.new_pane.getAsDOM(); var nqhdr = this.getNewPaneHeader(); this.new_pane.headerDOM = nqhdr; this.new_pane.paneDOM = npd; npd.prepend(nqhdr); this.panesDOM.appendChild(npd); return this.panesDOM; } TerminusQueryViewer.prototype.removePane = function(pane, index){ HTMLHelper.removeChildren(pane.paneDOM); pane.paneDOM.appendChild(pane.headerDOM); if(this.panes[i]){ this.panes.splice(i, 1); } } TerminusQueryViewer.prototype.showPane = function(pane){ //HTMLHelper.removeChildren(pane.paneDOM); //var pd = pane.getAsDOM(); //var qhdr = this.getPaneHeader(); //pd.prepend(qhdr); //pane.headerDOM = qhdr; } TerminusQueryViewer.prototype.hidePane = function(pane){ } TerminusQueryViewer.prototype.getPaneHeader = function(){ var hdr = document.createElement("div"); //hdr.appendChild(this.getControlsDOM()); return hdr; } TerminusQueryViewer.prototype.getNewPaneHeader = function(){ var hdr = document.createElement("div"); //hdr.appendChild(this.getControlsDOM("new")); return hdr; } TerminusQueryViewer.prototype.getControlsDOM = function(isnew){ var c = document.createElement("div"); c.setAttribute("class", "terminus-query-page-controls"); if(isnew == "new"){ var newPaneButton = document.createElement('button'); newPaneButton.setAttribute('class', 'terminus-btn terminus-query-btn'); newPaneButton.appendChild(document.createTextNode('WOQL Query')); //newPaneButton.addEventListener('click', () => this.addQueryPaneDOM()); c.appendChild(newPaneButton); var newScriptButton = document.createElement('button'); newScriptButton.setAttribute('class', 'terminus-btn terminus-query-btn'); newScriptButton.appendChild(document.createTextNode('Script')); //newScriptButton.addEventListener('click', () => this.addScriptPaneDOM()); c.appendChild(newScriptButton); var newDocButton = document.createElement('button'); newDocButton.setAttribute('class', 'terminus-btn terminus-query-btn'); newDocButton.appendChild(document.createTextNode('Document Query')); newDocButton.addEventListener('click', () => this.setNewDocumentPaneDOM()); c.appendChild(newDocButton); } else { var savePaneButton = document.createElement('button'); savePaneButton.setAttribute('class', 'terminus-btn terminus-query-btn'); savePaneButton.appendChild(document.createTextNode('Save')); c.appendChild(savePaneButton); var closePaneButton = document.createElement('button'); closePaneButton.setAttribute('class', 'terminus-btn terminus-query-btn'); closePaneButton.appendChild(document.createTextNode('Close')); c.appendChild(closePaneButton); var collapsePaneButton = document.createElement('button'); collapsePaneButton.setAttribute('class', 'terminus-btn terminus-query-btn'); collapsePaneButton.appendChild(document.createTextNode('Collapse')); c.appendChild(collapsePaneButton); } return c; } module.exports=TerminusQueryViewer <file_sep>/src/html/HTMLHelper.js const TerminusClient = require('@terminusdb/terminus-client'); let HTMLHelper = {}; HTMLHelper.getSettingsControl = function(view){ var icon = document.createElement('icon'); if(view == 'property') icon.setAttribute('class', 'fa fa-cog terminus-pointer'); else if(view == 'data') icon.setAttribute('class', 'fa fa-edit terminus-pointer'); icon.setAttribute('style', 'margin: 10px;') return icon; } HTMLHelper.getControlIcon = function(control){ var icon; switch(control){ case 'delete': icon = '-alt-delete'; break; case 'add': icon = '-plus'; break; case 'reset': icon = '-undo'; break; case 'save': icon = '-save'; break; case 'hide': icon = '-eye-slash'; break; } return icon; } HTMLHelper.getSelectionControl = function(type, options, selected, callback){ var sel = document.createElement("select"); sel.setAttribute("class", "terminus-frame-selector frame-control-selection " + type); for(var i = 0; i < options.length; i++){ var opt = document.createElement("option"); if(typeof options[i] == "object"){ opt.value = options[i].value; var label = (options[i].label ? document.createTextNode(options[i].label) : document.createTextNode(TerminusClient.UTILS.labelFromURL(options[i].value))); opt.appendChild(label); } else { opt.value = options[i]; label = TerminusClient.UTILS.labelFromURL(opt.value); opt.appendChild(document.createTextNode(label)); } if(selected == opt.value){ opt.setAttribute("selected", "selected"); } sel.appendChild(opt); } sel.addEventListener("change", function(){ callback(this.value); }); return sel; } HTMLHelper.getModeSelectorDOM = function(which, renderer){ var viewsDOM = document.createElement("span"); viewsDOM.setAttribute("class", "terminus-mode terminus-"+which+"-mode"); if(renderer.mode == "view"){ var callback = function(){ renderer.setMode("edit");} viewsDOM.appendChild(HTMLHelper.getActionControl("terminus-mode terminus-"+which+"-mode", "edit", " Edit ", callback)); } else if(renderer.isNew()){ return false; } else { var callback = function(){ renderer.cancel();} viewsDOM.appendChild(HTMLHelper.getActionControl(which, "cancel", "Cancel", callback)); } return viewsDOM; } HTMLHelper.goToName = function(s, p, i){ var url = window.location.href; if(url){ var wbits = url.split("#"); var loc = wbits[0]; var sh = TerminusClient.UTILS.getShorthand(s); if(!sh) sh = s; var bits = sh.split(":"); if(bits.length > 1) sh = bits[1]; var htmlid = sh; if(p){ var prop = TerminusClient.UTILS.getShorthand(p); if(!prop ) prop = p; var bits = prop.split(":"); if(bits.length > 1) prop = bits[1]; htmlid += "_" + prop; if(i){ htmlid += "_" + i; } } window.location = loc + "#" + htmlid; } } HTMLHelper.wrapShortenedText = function(wrap, text, max_cell_size, max_word_size){ if(max_cell_size && (text.length > max_cell_size)){ wrap.setAttribute("title", text); text = text.substring(0, max_cell_size) + "..."; } if(text && text.length > max_word_size){ const replacements = {} const words = text.split(" "); for(var i = 0; i < words.length; i++){ var word = words[i]; if(word.length > max_word_size){ wrap.setAttribute("title", text); var newstr = word.substring(0, max_word_size) + "..."; replacements[word] = newstr; } } for(var k in replacements){ text = text.replace(k, replacements[k]); } } wrap.appendChild(document.createTextNode(text)); } HTMLHelper.getVariableValueFromBinding = function(varname, bind){ for(var key in bind){ var skey = key.substring(key.lastIndexOf("/")+1); if(skey == varname){ const obj = bind[key]; if(typeof obj == "object" && obj['@value']) return obj['@value']; return obj; } } return false; } /* * HTML drawing function for document rendering */ HTMLHelper.getFrameDOM = function(scope, frame, orientation, hfeatures, features){ if(frame.display_options.hidden) return false; var framedom = HTMLHelper.getFrameHolderDOM(scope, frame, orientation); if(typeof frame.display_options.header == "function"){ var hd = frame.display_options.header(hfeatures); framedom.appendChild(hd); } else { var hd = HTMLHelper.getFrameHeaderDOM(scope, frame, orientation, hfeatures); if(typeof frame.display_options.header_style != "undefined"){ hd.setAttribute("style", frame.display_options.header_style); } framedom.appendChild(hd); } framedom.appendChild(HTMLHelper.getFrameBodyDOM(scope, frame, orientation, features)); return framedom; } HTMLHelper.getFrameHolderDOM = function(scope, frame, orientation){ var pcls = "terminus-" + scope + "-frame"; if(orientation == "page"){ var sp = document.createElement("div"); } else { var sp = document.createElement("span"); } var css = pcls + " " + pcls + "-" + orientation + (scope == "object" && frame.parent ? "" : " terminus-root-frame") + " " + pcls + "-" + frame.display_options.mode; sp.setAttribute("class", css); if(scope == "object"){ sp.setAttribute("data-class", frame.subjectClass()); sp.setAttribute("data-id", frame.subject()); var hid = this.hash(frame.subject()); } else if(scope == "property"){ sp.setAttribute('data-property', frame.property()); var hid = this.hash(frame.subject()+frame.property()); } else if(scope == "data"){ sp.setAttribute('data-value', frame.get()); var hid = this.hash(frame.subject() + frame.property() + frame.index); } var idm = document.createElement("a"); idm.setAttribute("class", "terminus-" + scope + "-idmarker"); idm.setAttribute("name", hid); sp.appendChild(idm); return sp; } HTMLHelper.getFrameHeaderDOM = function(scope, frame, orientation, features){ var css = "terminus-" + scope + "-header"; if(orientation == "page"){ var objDOM = document.createElement("div"); } else { var objDOM = document.createElement("span"); } objDOM.setAttribute("class", css + " " + css + "-" + orientation); if(features) objDOM.appendChild(features); return objDOM; } HTMLHelper.getFrameBodyDOM = function(scope, frame, orientation, features){ var css = "terminus-" + scope + "-properties"; if(orientation == "page"){ var vholder = document.createElement("div"); } else { var vholder = document.createElement("span"); } vholder.setAttribute('class', css + " " + css + "-" + orientation); if(features) vholder.appendChild(features); return vholder; } HTMLHelper.hash = function(s) { var hash = 0, i, chr; if (s.length === 0) return hash; for (i = 0; i < s.length; i++) { chr = s.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; HTMLHelper.getFeatureDOM = function(frame, feature, scope, mode, args, rend){ if(feature == "id"){ if(scope == "object") var val = frame.subject(); else if(scope == "property") var val = frame.property(); if(val == "_:") var val = "New Document"; return HTMLHelper.getInfoboxDOM("object-id", "ID", val, "The ID that identifies this document", mode, args, rend); } else if(feature == "summary"){ var sum = frame.getSummary(); return HTMLHelper.getInfoboxDOM(scope + "-summary", false, sum.long, sum.status, mode, args); } else if(feature == "label"){ var lab = frame.getLabel(); if(lab){ return HTMLHelper.getInfoboxDOM(scope + "-type", false, lab, false, mode, args); } return false; } else if(feature == "status"){ var sum = frame.getSummary(); return HTMLHelper.getInfoboxDOM(scope + "-status-"+sum.status, false, sum.status, sum.status, mode, args); } else if(feature == "comment"){ var lab = frame.getComment(); return HTMLHelper.getInfoboxDOM("property-comment", false, lab, false, mode, args); } else if(feature == "type"){ if(scope == "property" && mode == "edit" && frame.parent && frame.parent.isClassChoice() && frame.isNew()){ return this.getClassChoiceTypeSelector(frame, mode, args); } if(scope == "object") var lab = frame.subjectClass(); else if(scope == "property") var lab = frame.range(); else if(scope == "data") var lab = frame.getType(); if(lab){ return HTMLHelper.getInfoboxDOM(scope + "-type", "Type", lab, false, mode, args); } return false; } else if(feature == "delete"){ var callback = function(){frame.delete()}; var disabled = false; if(!frame.cardControlAllows("delete", scope)){ if(!frame.display_options.show_disabled_buttons){ return false; } disabled = "Cardinality rules prevent deleting this element"; } return HTMLHelper.getActionControl(scope, "delete", "Delete", callback, disabled, mode, args); } else if(feature == "clone"){ var callback = function(){frame.clone()}; var disabled = false; if(!frame.cardControlAllows("clone", scope)){ if(!frame.display_options.show_disabled_buttons){ return false; } disabled = "Cardinality rules prevent cloning this element"; } return HTMLHelper.getActionControl(scope, "clone", "Clone", callback, disabled, mode, args); } else if(feature == "reset"){ var callback = function(){frame.reset()}; var disabled = false; if(!frame.isUpdated()){ if(!frame.display_options.show_disabled_buttons){ return false; } disabled = "No changes have been made to this element"; } return HTMLHelper.getActionControl(scope, "reset", "Reset", callback, disabled, mode, args); } else if(feature == "mode"){ var callback = function(){frame.mode("edit")}; return HTMLHelper.getActionControl(scope, "mode", "Edit", callback, mode, args); } else if(feature == "hide"){ var callback = function(){frame.show()}; return HTMLHelper.getActionControl(scope, "hide", "Hide", callback, mode, args); } else if(feature == "update"){ var callback = function(){frame.save()}; if(!frame.isUpdated() && !frame.display_options.show_disabled_buttons, mode, args){ return false; } var disabled = frame.isUpdated() ? false : "No changes have been made to this element"; return HTMLHelper.getActionControl(scope, "save", "Save", callback, disabled, mode, args); } else if(feature == "viewer"){ return false;//this.getViewerSelectorDOM(scope, frame, mode, args); } else if(feature == "view"){ return this.getViewEntryDOM(scope, frame, mode, args); } else if(feature == "cardinality"){ return this.getCardinalityDOM(scope, frame, mode, args); } else if(feature == "add"){ return this.getAddDOM(scope, frame, mode, args); } } HTMLHelper.getViewerSelectorDOM = function(scope, frame, mode, args){ //var viewers = frame.datatypes.getAvailableViewers(); //var r = frame.datatypes.getRenderer(t); if(viewers && viewers.length){ var mpropDOM = document.createElement("span"); mpropDOM.setAttribute("class", "terminus-" + scope + "-viewer"); var callback = function(viewer){ if(viewer){ frame.setViewer(viewer); } } var selected = frame.currentViewer(); var sel = HTMLHelper.getSelectionControl(scope + '-viewer', viewers, selected, callback, mode, args); mpropDOM.appendChild(sel); return mpropDOM; } return false; } /* needs html viewer context for goto */ HTMLHelper.getViewEntryDOM = function(scope, frame, mode, args){ if(scope == "object"){ var viewables = frame.getFilledPropertyList(); } else if(scope == "property"){ } var self = this; if(viewables && viewables.length){ var mpropDOM = document.createElement("span"); mpropDOM.setAttribute("class", "terminus-"+scope + "-view-entry"); viewables.unshift({ value: "", label: "View " + scope}); var callback = function(add){ if(add){ frame.goToEntry(add); } } var sel = HTMLHelper.getSelectionControl(scope + "-view-entry", viewables, "", callback, mode, args); mpropDOM.appendChild(sel); return mpropDOM; } return false; } HTMLHelper.getCardinalityDOM = function(scope, frame, mode, args){ var restriction = frame.getRestriction(); if(restriction.min && restriction.max){ if(restriction.min == restriction.max){ var lab = restriction.min; var help = "Cardinality: " + restriction.min; } else { var lab = restriction.min + "-" + restriction.max; var help = "Minimum Cardinality: " + restriction.min; help += ", Maximum Cardinality: " + restriction.max; } } else if(restriction.min){ var lab = ">"+(restriction.min-1); var help = "Minimum Cardinality: " + restriction.min; } else if(restriction.max){ var lab = "<"+(restriction.max+1); var help = "Maximum Cardinality: " + restriction.max; } else { return false; } return HTMLHelper.getInfoboxDOM("property-cardinality", "Cardinality", lab, help, mode, args); } HTMLHelper.getClassChoiceTypeSelector = function(frame, mode, args){ var cs = frame.parent.getAvailableClassChoices(); if(cs && cs.length){ var mpropDOM = document.createElement("span"); mpropDOM.setAttribute("class", "terminus-property-change-class"); var mlabDOM = document.createElement("span"); mlabDOM.setAttribute("class", "terminus-property-change-label"); mlabDOM.appendChild(document.createTextNode("Type")); mpropDOM.appendChild(mlabDOM); var callback = function(cls){ if(cls){ frame.changeClass(cls); } } var sel = HTMLHelper.getSelectionControl("change-class", cs, frame.subjectClass(), callback, mode, args); mpropDOM.appendChild(sel); return mpropDOM; } return false; } HTMLHelper.getAddDOM = function(scope, frame, mode, args){ if(scope == "property"){ if(frame.isClassChoice()){ var cs = frame.getAvailableClassChoices(); if(cs && cs.length){ var mpropDOM = document.createElement("span"); mpropDOM.setAttribute("class", "terminus-property-add-class"); cs.unshift({ value: "", label: "Add Type"}); var callback = function(cls){ if(cls){ frame.addClass(cls); } } var sel = HTMLHelper.getSelectionControl("add-property", cs, "", callback, mode, args); mpropDOM.appendChild(sel); return mpropDOM; } } if(frame.cardControlAllows("add") || frame.display_options.show_disabled_buttons){ var callback = function(){frame.add("edit")}; var disabled = (frame.cardControlAllows("add") ? false : "Cardinality Rules Forbid Add"); return HTMLHelper.getActionControl(scope + "-add-entry", "add", "Add", callback, disabled, mode, args); } } else { var addables = frame.getMissingPropertyList(); if(addables && addables.length){ var mpropDOM = document.createElement("span"); mpropDOM.setAttribute("class", "terminus-" + scope + "-add-entry"); addables.unshift({ value: "", label: "Add new " + scope}); var callback = function(add){ if(add){ if(scope == "object") frame.addNewProperty(add); else if(scope == "property") frame.addNewValue(add); } } if(frame.cardControlAllows("add") || frame.display_options.show_disabled_buttons){ var disabled = (frame.cardControlAllows("add") ? false : "Cardinality rules forbid adding element"); var sel = HTMLHelper.getSelectionControl(scope + "-add-entry", addables, "", callback, disabled, mode, args); mpropDOM.appendChild(sel); return mpropDOM; } } } return false; } HTMLHelper.getInfoboxDOM = function(type, label, value, help, mode, args, input){ /*var frow = this.getFrameRow(); var fgroup = this.getFrameGroup(frow);*/ var infoDOM = document.createElement("span"); infoDOM.setAttribute("class", "terminus-frame-infobox-box " + "terminus-" +type ); //fgroup.appendChild(infoDOM); if(help){ infoDOM.setAttribute("title", help); } if(args && typeof args.label != "undefined") label = args.label; if(label !== false){ label = (args && args.label ? args.label : label); var linfo = document.createElement("span"); linfo.setAttribute("class", "terminus-frame-infobox-label " + "terminus-" +type + "-label"); linfo.appendChild(document.createTextNode(label)); if(args && args.headerStyle){ linfo.setAttribute("style", args.headerStyle); } infoDOM.appendChild(linfo); } var lval = document.createElement("span"); lval.setAttribute("class", "terminus-frame-infobox-value " + "terminus-" +type + "-value"); if(input){ input.value = value; lval.appendChild(input); } else if(args && args.removePrefixes && value && value.split(":").length == 2) { var bits = value.split(":"); sh = bits[1]; lval.setAttribute("title", value); lval.appendChild(document.createTextNode(sh)); } else { lval.appendChild(document.createTextNode(value)); } if(args && args.bodyStyle){ lval.setAttribute("style", args.bodyStyle); } infoDOM.appendChild(lval); if(args && args.style){ infoDOM.setAttribute("style", args.style) } return infoDOM; } HTMLHelper.getActionControl = function(type, control, label, callback, disabled, mode, args){ //var pman = new TerminusPluginManager(); var dpropDOM = document.createElement("span"); //dpropDOM.setAttribute("class", "terminus-action-control terminus-save-btn " + type + "-" + control); label = (args && typeof args.label != "undefined" ? args.label : label); icon = (args && args.icon ? args.icon : false); if(icon){ var i = document.createElement("i"); i.setAttribute("class", "fa " + icon); icon = i; } var tag = (args && args.tag ? args.tag : "button"); var button = document.createElement(tag); if(icon){ button.appendChild(icon); } if(label) button.appendChild(document.createTextNode(" " + label + " ")); if(args && args.title){ button.setAttribute("title", args.title); } if(disabled){ //button.setAttribute("class", "terminus-frame-control terminus-frame-btn frame-control-action action-disabled " + type + "-" + control + "-disabled"); button.setAttribute("title", disabled); } else { //button.setAttribute("class", "terminus-frame-control terminus-frame-btn frame-control-action " + type + "-" + control); } dpropDOM.appendChild(button); return dpropDOM; } HTMLHelper.removeChildren = function (node) { if (node) { while (node.hasChildNodes()) { node.removeChild(node.childNodes[0]); } } }; HTMLHelper.loadDynamicScript = function (scriptid, src, callback) { const existingScript = document.getElementById(scriptid); if (!existingScript) { const script = document.createElement('script'); script.src = src; // URL for the third-party library being loaded. document.body.appendChild(script); script.onload = function () { script.id = scriptid; // do it here so it doesn't trigger the callback below on multiple calls if (callback) callback(scriptid); }; } if (existingScript && callback) { callback(scriptid); } }; HTMLHelper.loadDynamicCSS = function (cssid, src, callback) { const existingScript = document.getElementById(cssid); if (!existingScript) { const link = document.createElement('link'); link.href = src; // URL for the third-party library being loaded. link.id = cssid; // e.g., googleMaps or stripe link.rel = 'stylesheet'; document.body.appendChild(link); link.onload = function () { if (callback) callback(cssid); }; } if (existingScript && callback) callback(cssid); }; HTMLHelper.removeElement = function (node) { if (node) { node.parentNode.removeChild(node); } } module.exports=HTMLHelper <file_sep>/src/html/datatypes/GoogleMapHelper.js function GoogleMapHelper(options){ this.polygon = false; this.polyline = false; this.markers = []; this.init(options); } GoogleMapHelper.prototype.init = function(config){ this.type = ((config && config.type) ? config.type: 'Shape'); this.width = ((config && config.width) ? config.width : '400px'); this.height = ((config && config.height ) ? config.height : '400px'); this.mapLat = ((config && config.mapLat) ? config.mapLat : '41.9010004'); this.mapLong = ((config && config.mapLong ) ? config.mapLong : '12.500061500000015'); this.zoom = ((config && config.zoom) ? config.zoom : 3); this.stroke = ((config && config.stroke) ? config.stroke : { color: '#FF0000', opacity: 0.3, weight: 3}); this.fill = ((config && config.fill) ? config.fill : { color: '#FF0000', opacity: 0.1}); this.line = ((config && config.line) ? config.line : { color: '#000000', opacity: 0.9, weight: 3}); } GoogleMapHelper.prototype.destroy = function(){ this.clear(); } GoogleMapHelper.prototype.translatePolygonToArray = function(polygon){ var data = "["; var vertices = polygon.getPath(); var seenValue = false; for (var j=0; j<vertices.getLength(); j++){ if(seenValue){ data = data + ","; } var xy = vertices.getAt(j); data = data + "[" + xy.lat() + "," + xy.lng() + "]" seenValue = true; } data = data + "]"; return data; }; GoogleMapHelper.prototype.translateArrayToPolygon = function(array){ var jsonified = JSON.parse(array); var output = []; for(var i=0;i<jsonified.length;i++){ var latlong = {} latlong.lat = jsonified[i][0]; latlong.lng = jsonified[i][1]; output.push(latlong); } return output; } GoogleMapHelper.prototype.createPolygon = function(coords, map) { var polygon = new google.maps.Polygon({ paths: coords, strokeColor: this.stroke.color, strokeOpacity: this.stroke.opacity, strokeWeight: this.stroke.weight, fillColor: this.fill.color, fillOpacity: this.fill.opacity }); polygon.setMap(map); return polygon; } GoogleMapHelper.prototype.createPolyline = function(coords){ var init = { strokeColor: this.line.color, strokeOpacity: this.line.opacity, strokeWeight: this.line.weight }; if(coords){ init.paths = coords; } var poly = new google.maps.Polyline(init); return poly; } GoogleMapHelper.prototype.clearMarkers = function() { for (var i = 0; i < this.markers.length; i++ ) { this.markers[i].setMap(null); } this.markers.length = 0; } GoogleMapHelper.prototype.addMarker = function(position, map, frame, title, ty) { var init = { position: position, map: map } if(title){ init.title = title; } var marker = new google.maps.Marker(init); var self = this; if(this.markers.length == 0 && ty == "xdd:coordinatePolygon"){ marker.addListener('click', function() { var coords = self.getCoordsFromMarkers(); self.polygon = self.createPolygon(coords, map); self.clearMarkers(); self.polyline.setMap(null); frame.set(self.translatePolygonToArray(self.polygon)); }); } this.markers.push(marker); if(ty == "xdd:coordinatePolyline"){ var x = this.translatePolygonToArray(this.polyline); frame.set(x); } return marker; } GoogleMapHelper.prototype.getCoordsFromMarkers = function(){ return this.polyline.getPath(); } GoogleMapHelper.prototype.clear = function(){ if(this.polygon) { this.polygon.setMap(null); this.polygon = false; } if(this.polyline) { this.clearMarkers(); this.polyline.setMap(null); } } GoogleMapHelper.prototype.initMap = function(mapContainer, value, type){ mapContainer.style.width = this.width; mapContainer.style.height = this.height; if(typeof google == "undefined"){ alert("google is not effing loaded"); return false; } var map = new google.maps.Map(mapContainer, { zoom: this.zoom, center: {lat: parseFloat(this.mapLat), lng: parseFloat(this.mapLong)} }); if(type == "xdd:coordinatePolygon"){ this.polyline = this.createPolyline(); this.polyline.setMap(map); var coords = (value ? this.translateArrayToPolygon(value) : []); if(value){ this.polygon = this.createPolygon(coords, map); } } else if(type == "xdd:coordinatePolyline"){ var coords = (value ? this.translateArrayToPolygon(value) : []); this.polyline = this.createPolyline(); this.polyline.setMap(map); if(value){ this.polyline.setPath(coords); } } else if(type == "xdd:coordinate"){ if(value){ this.clearMarkers(); var lat = parseFloat(value.substring(1, value.indexOf(","))); var long = parseFloat(value.substring(value.indexOf(",")+1, value.length-1)); var init = { position: {lat: lat, lng: long}, map: map } var marker = new google.maps.Marker(init); this.markers.push(marker); } } google.maps.event.trigger(map, 'resize'); return map; } module.exports=GoogleMapHelper;<file_sep>/src/html/datatypes/Number.js const TerminusClient = require('@terminusdb/terminus-client'); function HTMLNumberViewer(options){ this.options(options); } HTMLNumberViewer.prototype.options = function(options){ this.commas = (options && options.commas ? options.commas : true); } HTMLNumberViewer.prototype.renderFrame = function(frame, dataviewer){ return this.render(frame.get()); } HTMLNumberViewer.prototype.renderValue = function(dataviewer){ return this.render(dataviewer.value()); } HTMLNumberViewer.prototype.render = function(value){ if(value === 0) value = "0"; var input = document.createElement("span"); input.setAttribute('class', 'terminus-number-value terminus-literal-value'); input.setAttribute('data-value', value); value = (this.commas ? TerminusClient.UTILS.TypeHelper.numberWithCommas(value) : value); input.appendChild(document.createTextNode(value)); return input; } module.exports={HTMLNumberViewer} <file_sep>/src/TerminusTutorial.js const UTILS = require("./Utils.js"); const HTMLHelper = require('./html/HTMLHelper'); function TerminusTutorialLoader(ui){ this.ui = ui; this.tutorial_server = "https://terminusdb.github.io/terminus-tutorials/"; this.fetchOptions(); this.container = document.createElement("span"); this.container.setAttribute("class", "terminus-main-page"); } TerminusTutorialLoader.prototype.fetchOptions = function(){ let self = this; let cback = function(){ self.showTutorialChoices() } HTMLHelper.loadDynamicScript("tutorials", this.tutorial_server + "tutorials.js", cback); } TerminusTutorialLoader.prototype.drawChoices = function(){ if(this.choices){ for(var i = 0 ; i < this.choices.length; i++){ this.showChoice(this.choices[i]); } } } TerminusTutorialLoader.prototype.showTutorialChoices = function(){ this.choices = getTutorialOptions(); this.drawChoices(); } TerminusTutorialLoader.prototype.showChoice = function(choice){ var hbox = document.createElement("div"); hbox.setAttribute("class", "terminus-welcome-box terminus-no-res-alert"); var ispan = document.createElement("span"); ispan.setAttribute("class", "terminus-db-widget"); if(choice.css){ var ic = document.createElement("i"); ic.setAttribute("class", choice.css); ispan.appendChild(ic); } hbox.appendChild(ispan); var htit = document.createElement("span"); htit.appendChild(document.createElement("strong").appendChild(document.createTextNode(choice.title))); htit.classList.add('terminus-welcome-title'); hbox.appendChild(htit); var body = document.createElement("p"); body.setAttribute('class', 'terminus-welcome-body'); body.appendChild(document.createTextNode(choice.text)); hbox.appendChild(body); let self = this hbox.addEventListener("click", function(){ self.prepareDatabase(choice) }); this.container.appendChild(hbox); } TerminusTutorialLoader.prototype.getAsDOM = function(){ HTMLHelper.removeChildren(this.container); this.drawChoices(); return this.container; } TerminusTutorialLoader.prototype.prepareDatabase = function(choice){ this.client.deleteDatabase(choice.id) .finally(()=>{ this.ui.CreateDatabase(choice) .finally(()=>{ this.loadTutorial(choice) }) }) } //also need to update the UI screen TerminusTutorialLoader.prototype.loadTutorial = function(choice){ let self = this; let cback = function(){ self.startTutorial(choice, TerminusTutorial); } HTMLHelper.loadDynamicScript(choice.id, this.tutorial_server + choice.id + "/tutorial.js", cback); } TerminusTutorialLoader.prototype.showTutorialLaunchPage = function(choice, tutorialConfig){ HTMLHelper.removeChildren(this.container); //alert(tid) return this.container; } TerminusTutorialLoader.prototype.startTutorial = function(choice, tutorialConfig) { this.showTutorialLaunchPage(choice, tutorialConfig) } TerminusTutorialLoader.prototype.createSchema = function(OWLSchema){ return this.client.updateSchema(OWLSchema) } TerminusTutorialLoader.prototype.insert = function(insertJSON){ return this.client.woql(insertJSON) } TerminusTutorialLoader.prototype.query = function(selectWOQL){ return this.client.woql(selectWOQL) } TerminusTutorialLoader.prototype.showTutorialStages = function(stages){ // this.stages = []; return this.client.woql(InsertJSON) } TerminusTutorialLoader.prototype.loadTutorialStage = function(stage){ // return this.client.woql(InsertJSON) } function getNextStageButton(func){ let but = document.createElement("button"); but.appendChild(document.createTextNode("Next Step")) but.addEventListener("click", function(){ func(); }) return but; } TerminusTutorialLoader.prototype.executeStage = function(func){ let but = document.createElement("button"); but.appendChild(document.createTextNode("Run Query")) but.addEventListener("click", function(){ func(); }) return but; } TerminusTutorialLoader.prototype.showStageResult = function(q, v, complete){ let vu = v || `let view = View.table()`; var rq = Viewer.getQueryPane(eval(q), eval(vu), false, false, {showQuery: false}); let rd = rq.getAsDOM(); rq.load(); return rd; } /** * * @param {WOQLClient} client * @param {String} id * @param {String} title * @param {String} description function createDatabase(id, title, description){ title = title || "Seshat"; description = description || "Seshat global history databank"; const dbdetails = { "@context" : { rdfs: "http://www.w3.org/2000/01/rdf-schema#", terminus: "http://terminusdb.com/schema/terminus#" }, "@type": "terminus:Database", 'rdfs:label' : { "@language": "en", "@value": title }, 'rdfs:comment': { "@language": "en", "@value": description}, 'terminus:allow_origin': { "@type" : "xsd:string", "@value" : "*" } }; return WOQLclient.createDatabase(id, dbdetails); } */ module.exports=TerminusTutorialLoader <file_sep>/src/html/datatypes/EntityEditor.js function HTMLEntityEditor(options){} HTMLEntityEditor.prototype.renderFrame = function(frame, dataviewer){ var value = frame.get(); var input = document.createElement("input"); input.setAttribute("class", "terminus-literal-value terminus-entity-reference-value"); input.setAttribute("type", "text"); input.setAttribute('size', 80); input.value = value; var self = this; input.addEventListener("change", function(){ var url = this.value; if(url.indexOf("/") == -1 && url.indexOf(":") == -1){ url = "doc:" + url; } frame.set(url); }); return input; } module.exports={HTMLEntityEditor}<file_sep>/cypress/integration/tests/test_3.spec.js // update schema // on click of import button we make sure getSchema works as well context('update schema', () => { beforeEach(() => { //connect to server and db cy.visit('http://localhost:6363/dashboard'); cy.get('#terminus-content-viewer') .find('table tbody tr td p') .contains('database_e2e_test') .click(); }) it('update schema', () => { cy.get('.terminus-db-controller') .find('a') .contains('Schema') .click().then(() => { cy.wait(1000); cy.get('#terminus-content-viewer') .find('button') .contains('Edit') .click().then(() => { cy.wait(1000); // use force: true below because the textarea is hidden // and by default Cypress won't interact with hidden elements cy.get('.CodeMirror textarea') .type('test test test test ... \n updating something here ....\n', {force: true}) cy.wait(1000); // click on save cy.get('#terminus-content-viewer') .find('button').contains('Save').click().then(() => { alert('updateSchema success'); cy.wait(3000);}) }) }) }) // import schema }) <file_sep>/src/Utils.js /** * @file Javascript Api explorer tool * @author <NAME> * @license Copyright 2018-2019 Data Chemist Limited, All Rights Reserved. See LICENSE file for more * * @summary Set of functions used across scripts */ const Codemirror= require('./plugins/codemirror.terminus'); const TerminusClient = require('@terminusdb/terminus-client'); const HTMLHelper = require('./html/HTMLHelper'); // function to read Files function readFile(file){ if (window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else{ // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.open("GET",file,false); xmlhttp.send(); xmlDoc=xmlhttp.responseText; return xmlDoc; } // readFile() // function to write api call signatures from woql client function getFunctionSignature(which){ var sigs = {}; sigs.connect = { spec : "WOQLClient.connect(surl, key)", descr : "\n\nConnect to a Terminus server at the given URI with an API key" + "Stores the terminus:ServerCapability document returned in the connection register" + "which stores, the url, key, capabilities, and database meta-data for the connected server" + "If the curl argument is false or null, the this.server will be used if present," + " or the promise will be rejected." + "\n1)The first (surl) argument: {string} argument it is the Server Url" + "\n2)The second(key) argument: {string} argument contains an API key", result : "HTTP 200 on success, 409 for already existing database, otherwise error code", args : {server_url : 'url', key: 'Api key'}, options: { title: "", description: "" } }; sigs.create = { spec : "WOQLClient.createDatabase(dburl, details, key)", descr : "\n\nCreate a Terminus Database" + "\n1)The first (dburl) argument:{string}, it is a terminusDB Url or a terminusDB Id " + "\n2)The second(details) argument:{object}, details which is the payload" + "\n which included information of the new database to be created" + "\n3)The third (key) argument:{string}, contains an API key ", result : "HTTP 200 on success, 409 for already existing database, otherwise error code", args : {database_url : 'url', details: '', key: ' Api key'}, options: { title: "", description: "" } }; sigs.delete = { spec : "WOQLClient.deleteDatabase(dburl, key)", descr : "\n\nDeletes a Database" + "\n1)The first (dburl) argument: {string}, it is a terminusDB Url or a terminusDB Id " + "\n2)The second(key) argument: {string}, contains an API key", result: "HTTP 200 on success, otherwise error code", }; sigs.getSchema = { spec : "WOQLClient.getSchema(surl, options)", descr : "\n\nGets the schema of a database." +"\n1)The first (surl) argument: {string}, it is a dbUrl/schema" + "\n2)The second(key) argument: {string}, contains an API key", result : "Ontology Document on success (HTTP 200), 409 for already existing database, otherwise error code", options: { format: "turtle" } }; sigs.getClassFrames = { spec : "WOQLClient.getClassFrame = function(cfurl, cls, opts)", descr : "\n\nRetrieves a WOQL query on the specified database which updates the state and returns the results" + "\nThe first (cfurl) argument can be" + "\n1) a valid URL of a terminus database or" + "\n2) omitted - the current database will be used" + "\nthe second argument (cls) is the URL / ID of a document class that exists in the database schema" + "\nthe third argument (opts) is an options json - opts.key is an optional API key", result : "Ontology Document on success (HTTP 200), 409 for already existing database, otherwise error code", options: { format: "turtle" } }; sigs.updateSchema = { spec : "WOQLClient.updateSchema(schurl, docs, options)", descr : "\n\nUpdates the Schema of the specified database" +"\n1)The first (surl) argument :{string}, is a dbUrl/schema" + "\n2)The second(docs) argument:{object}, is a valid owl ontology (new schema to be updated) in turtle format" + "\n3)The third (key) argument:{string}, contains an API key", result : "Ontology Document on success (HTTP 200), 409 for already existing database, otherwise error code", args : {document : 'doc'}, options: { format: "turtle", editmode: "replace"} }; sigs.createDocument = { spec : "WOQLClient.createDocument(docurl, document, options)", descr : "\n\nCreates a new document in the specified database" + "\n1)The first (docurl) argument: {string}, is a dbUrl/document/document_id" + "\n2)The second(document) argument: {object}, is a valid document in json-ld" + "\n3)The third (key) argument:{string}, contains an API key", result : "Created Document on success (HTTP 200), Violation Report Otherwise (HTTP 400+)", args : {document_url : 'url', document: "doc"}, options: { format: "turtle", fail_on_id_denied: false} }; sigs.viewDocument = { spec : "WOQLClient.getDocument(docurl, options)", descr : "\n\nRetrieves a document from the specified database" + "\n1)The first (docurl) argument: {string}, is a dbUrl/document/document_id" + "\n2)The second (key) argument: {string}, contains an API key", result : "Document (HTTP 200), Violation Report Otherwise (HTTP 400+)", args : {document_url : 'url'}, options: { format: "turtle"} }; sigs.updateDocument = { spec : "WOQLClient.updateDocument(docurl, document, options)", descr : "\n\nUpdates a document in the specified database with a new version" + "\n1)The first (docurl) argument: {string}, is a dbUrl/document/document_id" + "\n2)The second(document) argument: {object}, is a valid document in json-ld" + "\n3)The third (key) argument:{string} argument contains an API key", result : "Ontology Document on success (HTTP 200), 409 for already existing database, otherwise error code", args : {document_url : 'url', document: "doc"}, options: { format: "turtle", editmode: "replace"} }; sigs.deleteDocument = { spec : "WOQLClient.deleteDocument(docurl, key)", descr : "\n\nDeletes a document from the specified database" + "\n1)The first (docurl) argument: {string},is a dbUrl/document/document_id" + "\n2)The second (key) argument: {string}, contains an API key", result: "Ontology Document on success (HTTP 200), 409 for already existing database, otherwise error code", args : {document_url : 'url'}, }; sigs.select = { spec: "WOQLClient.select(dburl, query, options)", descr: "\n\nExecutes a read-only WOQL query on the specified database and returns the results" + "\n1)The first (docurl) argument: {string}, is a terminusDB Url or a terminusDB Id" + "\n2)The second (query) argument: {object}, a valid query in json-ld format " + "\n3)The third (key) argument:{string}, contains an API key", result: "WOQL Result (HTTP 200), otherwise error code", args: {woql: 'woql'}, }; sigs.update = { spec : "WOQLClient.update(dburl, query, options)", descr : "\n\nExecutes a WOQL query on the specified database which updates the state and returns the results" + "\n1)The first (dburl) argument: {string}, is a terminusDB Url or a terminusDB Id" + "\n2)The second (query) argument: {object}, a valid query in json-ld format " + "\n3)The third (key) argument:{string}, contains an API key", result: "WOQL Result (HTTP 200), otherwise error code", args : {woql: 'woql'}, }; sigs.lookup = { spec: "WOQLClient.lookup(database_url, woql, options)", result: "WOQL Result (HTTP 200), otherwise error code", args: {class: 'url', term: 'string'}, }; sigs.map = { spec: "WOQLClient.lookup(source, target, woql, options)", result: "WOQL Result (HTTP 200), otherwise error code", args: {source: 'json', target: "json", woql: 'json'}, }; sigs.getClassFrame = { spec: "WOQLClient.getClassFrame(class, options)", result: "WOQL Result (HTTP 200), otherwise error code", args: {class: 'url'}, }; sigs.getPropertyFrame = { spec: "WOQLClient.getPropertyFrame(class, property, options)", result: "WOQL Result (HTTP 200), otherwise error code", args: {class: 'url', property: 'url'}, }; sigs.getFilledPropertyFrame = { spec: "WOQLClient.getPropertyFrame(document_url, property, options)", result: "WOQL Result (HTTP 200), otherwise error code", args: {document_url: 'url', property: 'url'}, }; sigs.getSubClasses = { spec: "WOQLClient.getSubClasses(class, options)", result: "WOQL Result (HTTP 200), otherwise error code", args: {class: 'url'}, }; return sigs[which]; }//getFunctionSignature // returns dom element for header text function getHeaderDom(text){ var hd = document.createElement('div'); hd.setAttribute('class', 'terminus-module-head'); var h = document.createElement('h3'); h.innerHTML = text; hd.appendChild(h); return hd; } // getHeaderTextDom function getButton(text){ var button = document.createElement('button'); button.setAttribute('class', 'terminus-btn'); button.setAttribute('value', text); button.appendChild(document.createTextNode(text)); return button; } // returns dom for alert banner function getInfoAlertDom(type, label, msg){ var ald = document.createElement('div'); if(type == 'info') ald.setAttribute('class', 'terminus-alert terminus-alert-success'); else ald.setAttribute('class', 'alert'); var str = document.createElement('STRONG'); str.innerHTML = label; ald.appendChild(str); var txt = document.createTextNode(msg); ald.appendChild(txt); return ald; } // getInfoAlertDom() // formats response results from platform function getResponse(currForm, action, response, terminator){ var rd = document.createElement('div'); // get header result rd.appendChild(getHeaderDom('Result')); var br = document.createElement('BR'); rd.appendChild(br); var data = JSON.stringify(response, 0, 4); var pre = document.createElement('pre'); pre.setAttribute('class', 'terminus-api-view terminus-scheme-pre'); pre.innerHTML = data; var cm = stylizeCodeDisplay(terminator, pre, rd, 'javascript'); if(!cm) rd.appendChild(pre); var br = document.createElement('BR'); rd.appendChild(br); currForm.appendChild(rd); return currForm; } // formats the response from fetch call and spits out Http header and result function showHttpResult(response, action, currForm, terminator){ //var currForm = document.createElement('div'); var br = document.createElement('BR'); currForm.appendChild(br); var br = document.createElement('BR'); currForm.appendChild(br); // get header result currForm.appendChild(getHeaderDom('HTTP Header')); var br = document.createElement('BR'); currForm.appendChild(br); var retHttpHeaders = ''; // iterate over all headers for (let [key, value] of response.headers) { retHttpHeaders = retHttpHeaders + `${key} = ${value}` + '\n'; } // http header result var hdres = document.createElement('pre'); hdres.setAttribute('class', 'terminus-api-signature-pre'); var txt = document.createTextNode(retHttpHeaders); hdres.appendChild(txt); var cm = stylizeCodeDisplay(terminator, hdres, currForm, 'message/http'); if(!cm) currForm.appendChild(hdres); return response.json() .then(function(response){ getResponse(currForm, action, response, terminator); // get return response }) } // UTILS.showHttpResult() function deleteStylizedEditor(ui, qip){ if(ui.pluginAvailable("codemirror")){ var cm = qip.nextElementSibling; cm.setAttribute('class', 'terminus-hide'); HTMLHelper.removeChildren(cm); } } /* ui: terminus ui reference txt: text area to be stylized view: defines the size of editor to appear in pages (schema/ query) mode: format to be displayed in */ function stylizeEditor(ui, txt, view, mode){ if(ui){ var cmConfig = ui.pluginAvailable("codemirror"); if(!(cmConfig)) return; var cm = new Codemirror(txt, mode, cmConfig); } else{ var cm = new Codemirror(txt, mode, {}); } var ar = cm.colorizeTextArea(view); cm.updateTextArea(ar); } /* ui: terminus ui reference txt: text area to be stylized dom: stylized pre area is appended to dom mode: format to be displayed in */ function stylizeCodeDisplay(ui, txt, dom, mode){ if(ui){ var cmConfig = ui.pluginAvailable("codemirror"); if(!(cmConfig)) return false; var cm = new Codemirror(txt, mode, cmConfig); } else var cm = new Codemirror(txt, mode, {}); var pr = cm.colorizePre(); if(dom) dom.appendChild(pr); return true; } /* name: classname to find and remove classes from elements */ function removeSelectedNavClass(name){ var el = document.getElementsByClassName(name); if (el.length < 1) return; for(var i=0; i<(el.length + 1); i++){ el[i].classList.remove(name); } } function setSelectedSubMenu(a){ removeSelectedNavClass("terminus-submenu-selected"); a.classList.add("terminus-submenu-selected"); } function setSelected(el, className){ var par = el.parentElement; for(var i=0; i<par.childNodes.length; i++){ if(par.childNodes[i].classList.contains(className)) par.childNodes[i].classList.remove(className); } el.classList.add(className); } // toggles between contents function tolggleContent(icon, content){ if (content.style.display === "block"){ removeSelectedNavClass("fa-chevron-up"); icon.classList.add("fa-chevron-down"); content.style.display = "none"; } else{ removeSelectedNavClass("fa-chevron-down"); icon.classList.add("fa-chevron-up"); content.style.display = "block"; } } // controls current selected nav bar function activateSelectedNav(nav, terminator){ removeSelectedNavClass("terminus-selected"); //checkDocumentSubMenus(terminator); nav.classList.add("terminus-selected"); } function hideDocumentSubMenus(el){ if(el.classList.contains('terminus-display')){ el.classList.remove('terminus-display'); el.classList.add('terminus-hide'); } } function checkDocumentSubMenus(terminator){ if(terminator.ui.showControl("get_document")) { var gd = document.getElementsByClassName('terminus-get-doc'); hideDocumentSubMenus(gd[0]); } if(terminator.ui.showControl("create_document")) { var cd = document.getElementsByClassName('terminus-create-doc'); hideDocumentSubMenus(cd[0]); } } function toggleVisibility(el){ if(el.classList.contains('terminus-display')){ el.classList.remove('terminus-display'); el.classList.add('terminus-hide'); } else if(el.classList.contains('terminus-hide')){ el.classList.remove('terminus-hide'); el.classList.add('terminus-display'); } } function extractValueFromCell(cellValue){ var ihtml = new DOMParser().parseFromString(cellValue, "text/xml"); return ihtml.firstChild.innerHTML; } function displayDocumentSubMenus(ui) { //display submenus on click of documents if(ui.showControl("get_document")) { var gd = document.getElementsByClassName('terminus-get-doc'); showSubMenus(gd[0]); } if(ui.showControl("create_document")) { var cd = document.getElementsByClassName('terminus-create-doc'); showSubMenus(cd[0]); } } function checkForMandatoryId(){ var objId = document.getElementsByClassName('terminus-object-id-input'); if(objId.length>0){ if(!objId[0].value){ objId[0].setAttribute('placeholder', 'Required field'); objId[0].style.background = '#f8d7da'; return false; } else return true; } } function showSubMenus (el){ el.classList.remove('terminus-hide'); el.classList.add('terminus-display'); } // function which generates query based on current settings from different screens of dashboard function getCurrentWoqlQueryObject(query, settings){ var qval; if(!query) query = settings.query; switch(query){ case 'Show_All_Schema_Elements': qval = TerminusClient.WOQL.limit(settings.pageLength) .start(settings.start) .elementMetadata(); break; case 'Show_All_Classes': qval = TerminusClient.WOQL.limit(settings.pageLength) .start(settings.start) .classMetadata(); break; case 'Show_All_Data': qval = TerminusClient.WOQL.limit(settings.pageLength) .start(settings.start) .getEverything(); break; case 'Show_All_Documents': qval = TerminusClient.WOQL.limit(settings.pageLength) .start(settings.start) .getAllDocuments(); break; case 'Show_All_Document_classes': qval = TerminusClient.WOQL.limit(settings.pageLength) .start(settings.start) .documentMetadata(); break; case 'Show_Document_Classes': qval = TerminusClient.WOQL.limit(settings.pageLength) .start(settings.start).and( TerminusClient.WOQL.quad("v:Element", "rdf:type", "owl:Class", "db:schema"), TerminusClient.WOQL.abstract("v:Element"), TerminusClient.WOQL.sub("v:Element", "tcs:Document"), TerminusClient.WOQL.opt().quad("v:Element", "rdfs:label", "v:Label", "db:schema"), TerminusClient.WOQL.opt().quad("v:Element", "rdfs:comment", "v:Comment", "db:schema")); break; case 'Show_All_Properties': qval = TerminusClient.WOQL.limit(settings.pageLength) .start(settings.start) .propertyMetadata(); break; default: console.log('Invalid query ' + query + ' passed in WOQLTextboxGenerator'); break; } return qval; } // removes spaces function trimValue(text){ (text).replace(/[\s\t\r\n\f]/g,''); return text; } // query string function getqObjFromInput(q){ const WOQL = TerminusClient.WOQL ; //var query = 'WOQL.' + q; var query = q; try { var qObj = eval(query); this.qObj = qObj; return qObj; } catch(e){ console.log('Error in getting woql object ',e.toString()); } } module.exports={tolggleContent, removeSelectedNavClass, stylizeCodeDisplay, stylizeEditor, deleteStylizedEditor, showHttpResult, getHeaderDom, getInfoAlertDom, getFunctionSignature, toggleVisibility, extractValueFromCell, displayDocumentSubMenus, setSelectedSubMenu, checkForMandatoryId, activateSelectedNav, getCurrentWoqlQueryObject, getButton, trimValue, setSelected, getqObjFromInput} <file_sep>/cypress/integration/tests/test_2.spec.js // import schema from 'http://172.16.31.10:6363/docs' context('import schema', () => { beforeEach(() => { //connect to server and db cy.visit('http://localhost:6363/dashboard'); cy.get('#terminus-content-viewer') .find('table tbody tr td p') .contains('database_e2e_test') .click(); }) it('import schema', () => { // populate import schema details const schurl = 'http://172.16.31.10:6363/myFirstTerminusDB'; const key = 'nooooooooooooooooooooooo'; cy.get('.terminus-db-controller') .find('a') .contains('Schema') .click().then(() => { cy.wait(1000); cy.get('#terminus-content-viewer') .find('button') .contains('Import New Schema') .click().then(() => { cy.wait(1000); // enter url cy.get('#terminus-content-viewer') .find('input[placeholder="Enter URL of DB to import from"]') .focus().type(schurl); cy.wait(1000); // enter api key cy.get('#terminus-content-viewer') .find('input[class="terminus-form-value terminus-input-text terminus-url-key"]') .focus().type(key); // click on create cy.get('#terminus-content-viewer') .find('button').contains('Import').click().then(() => { alert('import schema success'); cy.wait(3000); }) }); }) }) // import schema }) <file_sep>/src/html/QueryPane.js const TerminusClient = require('@terminusdb/terminus-client'); const TerminusCodeSnippet = require('./query/TerminusCodeSnippet'); const ResultPane = require("./ResultPane"); const UTILS = require('../Utils'); const HTMLHelper = require('./HTMLHelper'); const TerminusViolations = require('./TerminusViolation'); function QueryPane(client, query, result){ this.client = client; this.query = query; this.result = result; this.views = []; this.container = document.createElement('span'); this.messages = document.createElement('div'); this.messages.setAttribute('class', 'terminus-query-messages'); this.defaultResultView = { showConfig: false, editConfig: false }; this.defaultQueryView = { showQuery: false, editQuery: false }; } QueryPane.prototype.load = function(){ return this.query.execute(this.client).then( (result) => { let nresult = new TerminusClient.WOQLResult(result, this.query); this.updateResult(nresult); }); } QueryPane.prototype.fireDefaultQueries = function(){ let WOQL = TerminusClient.WOQL; var query = WOQL.query().classMetadata(); query.execute(this.client).then((results) => { let qcres = new TerminusClient.WOQLResult(results, query); this.classMetaDataRes = qcres; }) var query = WOQL.query().propertyMetadata(); query.execute(this.client).then((results) => { let qpres = new TerminusClient.WOQLResult(results, query); this.propertyMetaDataRes = qpres; }) } QueryPane.prototype.options = function(opts){ this.showQuery = (opts && typeof opts.showQuery != "undefined" ? opts.showQuery : false); this.editQuery = (opts && typeof opts.editQuery != "undefined" ? opts.editQuery : false); this.showHeader = (opts && typeof opts.showHeader != "undefined" ? opts.showHeader : false); this.addViews = (opts && typeof opts.addViews != "undefined" ? opts.addViews : false); this.intro = (opts && typeof opts.intro != "undefined" ? opts.intro : false); this.saved = (opts && typeof opts.saved != "undefined" ? opts.saved: true); var css = (opts && typeof opts.css != "undefined" ? opts.css : 'terminus-query-pane-cont'); this.container.setAttribute('class', css); return this; } QueryPane.prototype.getSection = function(sName){ var btn = document.createElement('button'); btn.setAttribute('class', 'terminus-query-section'); btn.appendChild(document.createTextNode(sName)); return btn; } QueryPane.prototype.clearSubMenus = function(btn){ var par = btn.parentElement.parentElement; var smenus = par.getElementsByClassName('terminus-queries-submenu'); for(var i=0; i<smenus.length; i++){ HTMLHelper.removeChildren(smenus[i]); } } QueryPane.prototype.getResults = function(query){ if(query) this.input.setQuery(query); HTMLHelper.removeChildren(this.sampleQueryDOM); this.sampleQueryDOM.appendChild(document.createTextNode(" Saved Queries ")) this.input.refreshContents(); } QueryPane.prototype.AddEvents = function(btn, aval){ var self = this; btn.addEventListener('click', function(){ let WOQL = TerminusClient.WOQL; self.clearSubMenus(this); var query; switch(this.value){ case 'Show All Schema Elements': query = WOQL.query().elementMetadata(); break; case 'Show All Classes': query = WOQL.query().classMetadata(); break; case 'Show All Properties': query = WOQL.query().propertyMetadata(); break; case 'Show Document Classes': query = WOQL.query().concreteDocumentClasses(); break; case 'Show All Data': query = WOQL.query().getEverything(); break; case 'Show all documents': query = WOQL.query().documentMetadata(); break; case 'Show data of chosen type': var choosen = aval || 'scm:' + this.innerText; query = WOQL.query().getDataOfClass(choosen); break; case 'Show data of chosen property': var choosen = aval || 'scm:' + this.innerText; query = WOQL.query().getDataOfProperty(choosen); break; case 'Show data of type': return; break; case 'Show data for property': return; break; default: console.log('Invalid Type of query'); break; } self.getResults(query); }) } QueryPane.prototype.getQueryMenu = function(qName){ var btn = document.createElement('button'); btn.setAttribute('class', 'terminus-load-queries'); btn.setAttribute('value', qName); btn.appendChild(document.createTextNode(qName)); this.AddEvents(btn); return btn; } QueryPane.prototype.getSubDataMenu = function(qName, val, aval){ var btn = document.createElement('button'); btn.setAttribute('class', 'terminus-load-queries'); btn.setAttribute('value', qName); btn.appendChild(document.createTextNode(val)); this.AddEvents(btn, aval); return btn; } // schema queries QueryPane.prototype.getSchemaSection = function(d){ var section = this.getSection('Schema Queries'); d.appendChild(section); var btn = this.getQueryMenu('Show All Schema Elements'); d.appendChild(btn); var btn = this.getQueryMenu('Show All Classes'); d.appendChild(btn); var btn = this.getQueryMenu('Show Document Classes'); d.appendChild(btn); var btn = this.getQueryMenu('Show All Properties'); d.appendChild(btn); } QueryPane.prototype.checkIfDataMenuOpen = function(btn){ var isOpen = false; if(btn.children.length){ for(var i=0; i<btn.children.length; i++){ //var child = btn.children[i].getElementsByClassName('terminus-queries-submenu'); var child = btn.getElementsByClassName('terminus-queries-submenu'); if(child.length){ for(var j=0; j<child.length; j++){ HTMLHelper.removeElement(child[j]); isOpen = true; } } } } return isOpen; } QueryPane.prototype.showDataOfTypeEvent = function(btn){ var self = this; btn.addEventListener('click', function(){ var isMenuOpen = self.checkIfDataMenuOpen(this); if(!isMenuOpen){ var subPar = document.createElement('div'); subPar.setAttribute('class', 'terminus-queries-submenu'); if(self.classMetaDataRes && self.classMetaDataRes.hasBindings()){ for(var i = 0; i<self.classMetaDataRes.bindings.length; i++){ var text = self.classMetaDataRes.bindings[i]['v:Label']['@value']; var val = self.classMetaDataRes.bindings[i]['v:Element']; subPar.appendChild(self.getSubDataMenu('Show data of chosen type', text, val)); } } btn.appendChild(subPar); } }) } QueryPane.prototype.showPropertyOfTypeEvent = function(btn){ var self = this; btn.addEventListener('click', function(){ var isMenuOpen = self.checkIfDataMenuOpen(this); if(!isMenuOpen){ var subPar = document.createElement('div'); subPar.setAttribute('class', 'terminus-queries-submenu'); if(self.propertyMetaDataRes && self.propertyMetaDataRes.hasBindings()){ for(var i = 0; i<self.propertyMetaDataRes.bindings.length; i++){ var text = self.propertyMetaDataRes.bindings[i]['v:Label']['@value']; var val = self.propertyMetaDataRes.bindings[i]['v:Property']; subPar.appendChild(self.getSubDataMenu('Show data of chosen property', text, val)); } } btn.appendChild(subPar); } }) } QueryPane.prototype.addCheveronIcon = function(btn){ var i = document.createElement('i'); i.setAttribute('class', 'fa fa-chevron-right terminus-query-section'); btn.appendChild(i); } // data queries QueryPane.prototype.getDataSection = function(d){ var section = this.getSection('Data Queries'); d.appendChild(section); // div to populate submenu on data of type var bd = document.createElement('div'); bd.setAttribute('class', 'terminus-query-submenu'); d.appendChild(bd); var btn = this.getQueryMenu('Show data of type'); bd.appendChild(btn); this.addCheveronIcon(btn); this.showDataOfTypeEvent(btn); // div to populate submenu on property of type var bd = document.createElement('div'); bd.setAttribute('class', 'terminus-query-submenu'); d.appendChild(bd); var btn = this.getQueryMenu('Show data for property'); bd.appendChild(btn); this.showPropertyOfTypeEvent(btn); this.addCheveronIcon(btn); var btn = this.getQueryMenu('Show All Data'); d.appendChild(btn); } QueryPane.prototype.fireDocumentEvent = function(document){ let WOQL = TerminusClient.WOQL; var query = WOQL.query().documentProperties(document); this.getResults(query); } QueryPane.prototype.getEnterDocumentIdDOM = function(){ var sp = document.createElement('span'); sp.setAttribute('class', 'terminus-display-flex'); var inp = document.createElement('input'); inp.setAttribute('class', 'terminus-doc-id-input'); inp.setAttribute('placeholder', 'doc:myDocId'); var sub = document.createElement('button'); sub.setAttribute('class', 'terminus-btn terminus-doc-id-input-submit'); sub.appendChild(document.createTextNode('Submit')); var self = this; sub.addEventListener('click', function(){ self.fireDocumentEvent(inp.value); }) sp.appendChild(inp); sp.appendChild(sub); return sp; } // document queries QueryPane.prototype.getDocumentSection = function(d){ var section = this.getSection('Document Queries'); d.appendChild(section); var btn = this.getQueryMenu('Show all documents'); d.appendChild(btn); d.appendChild(this.getEnterDocumentIdDOM()); } // bottom color transaprent QueryPane.prototype.getQueryMenuBlock = function(){ var d = document.createElement('div'); d.setAttribute('class', 'terminus-load-queries'); this.getSchemaSection(d); this.getDataSection(d); this.getDocumentSection(d); return d; } QueryPane.prototype.getSampleQueriesDOM = function(){ var i = document.createElement('icon'); i.setAttribute('class', 'fa fa-ellipsis-v terminus-ellipsis-icon'); i.setAttribute('title', 'Click to load sample Queries'); i.setAttribute('value', false); i.appendChild(document.createTextNode(" Saved Queries ")) this.sampleQueryDOM = i; var self = this; i.addEventListener('click', function(e){ if(e.target !== this) return; if(this.children.length) { HTMLHelper.removeChildren(this); this.appendChild(document.createTextNode(" Saved Queries ")) } else{ var d = self.getQueryMenuBlock(); this.appendChild(d); } }) return i; } QueryPane.prototype.getAsDOM = function(){ if(this.intro){ this.container.appendChild(UTILS.getHeaderDom(this.intro)); } if(this.showQuery) { if(this.saved) this.fireDefaultQueries(); var configspan = document.createElement("span"); configspan.setAttribute("class", "pane-config-icons"); this.querySnippet = configspan; this.container.appendChild(configspan); var mode = (this.editQuery ? "edit" : "view"); this.input = this.createInput(mode); var ipdom = this.input.getAsDOM(true); var ispan = document.createElement("span"); ispan.setAttribute("class", "query-pane-config"); var ic = document.createElement("i"); //ic.setAttribute('style', 'margin:10px;') configspan.appendChild(ic); var self = this; function showQueryConfig(){ if(self.showQuery != "always"){ configspan.title="Click to Hide Query"; ic.setAttribute("class", "fas fa fa-times-circle"); } configspan.classList.remove('terminus-click-to-view-query'); if(configspan.nextSibling){ self.container.insertBefore(ipdom, configspan.nextSibling); } else { self.container.appendChild(ipdom); } if(self.saved){ var qicon = self.getSampleQueriesDOM(); var sqd = document.createElement("span"); sqd.setAttribute("class", "sample-queries-pane"); sqd.appendChild(qicon); ipdom.appendChild(sqd); } self.input.stylizeSnippet(); } function hideQueryConfig(){ configspan.title="Click to View Query"; ic.setAttribute("class", "fas fa fa-search terminus-query-view-icon"); configspan.classList.add('terminus-click-to-view-query'); self.container.removeChild(ipdom); } configspan.addEventListener("click", () => { if(this.showingQuery) hideQueryConfig(); else showQueryConfig(); this.showingQuery = !this.showingQuery; }); showQueryConfig(); if(this.showQuery == "icon") hideQueryConfig(); } this.resultDOM = document.createElement("span"); if(this.showQuery){ this.resultDOM.setAttribute("class", "terminus-query-results-full"); } else { this.resultDOM.setAttribute("class", "terminus-query-results"); } this.resultDOM.appendChild(this.messages); if(this.views.length == 0){ this.addView(TerminusClient.View.table(), this.defaultResultView); } //this is where we want to put in the view headers in the case of the query page for(var i = 0; i<this.views.length; i++){ var vdom = this.views[i].getAsDOM(); if(vdom){ if(this.showHeader){ var closable = (this.views.length != 1); //var qhdr = this.getResultPaneHeader(closable); //vdom.prepend(qhdr); } this.resultDOM.appendChild(vdom); } } this.container.appendChild(this.resultDOM); if(this.addViews) this.container.appendChild(this.getAddViewControl()); return this.container; } QueryPane.prototype.getResultPaneHeader = function(closable){ var c = document.createElement('div'); var savePaneButton = document.createElement('button'); savePaneButton.setAttribute('class', 'terminus-btn terminus-query-btn'); savePaneButton.appendChild(document.createTextNode('Save')); c.appendChild(savePaneButton); if(closable){ var closePaneButton = document.createElement('button'); closePaneButton.setAttribute('class', 'terminus-btn terminus-query-btn'); closePaneButton.appendChild(document.createTextNode('Close')); c.appendChild(closePaneButton); } var collapsePaneButton = document.createElement('button'); collapsePaneButton.setAttribute('class', 'terminus-btn terminus-query-btn'); collapsePaneButton.appendChild(document.createTextNode('Collapse')); c.appendChild(collapsePaneButton); return c; } QueryPane.prototype.createInput = function(mode){ let input = new TerminusCodeSnippet("woql", mode, null, 800); if(this.query){ input.setQuery(this.query); } var self = this; input.submit = function(qObj){ self.submitQuery(qObj); }; return input; } QueryPane.prototype.updateQuery = function(qObj){ this.query = qObj; if(this.input) this.input.setQuery(this.query); } QueryPane.prototype.setInput = function(input){ if(this.input) { let qr = this.input.setInput(input); if(qr) this.query = qr; } } QueryPane.prototype.updateResult = function(result){ this.result = result; this.updateQuery(result.query); this.refreshViews(); } QueryPane.prototype.addView = function(config, options){ var nrp = new ResultPane(this.client, this, config).options(options); if(this.result){ nrp.setResult(this.result); } this.views.push(nrp); return nrp; } QueryPane.prototype.empty = function(){ return (typeof this.query == "undefined"); } QueryPane.prototype.clearMessages = function(){ if(this.messages.children.length) HTMLHelper.removeChildren(this.messages); } QueryPane.prototype.getBusyLoader = function(){ var pbc = document.createElement('div'); pbc.setAttribute('class', 'term-progress-bar-container'); var pbsa = document.createElement('div'); pbsa.setAttribute('class', 'term-progress-bar term-stripes animated reverse slower'); pbc.appendChild(pbsa); var pbia = document.createElement('span'); pbia.setAttribute('class', 'term-progress-bar-inner'); pbsa.appendChild(pbia); return pbc; } QueryPane.prototype.showBusy = function(msg){ var msgHolder = document.createElement('div'); msgHolder.setAttribute('class', 'terminus-busy-msg') msgHolder.appendChild(document.createTextNode(msg)); msgHolder.appendChild(this.getBusyLoader()); this.messages.appendChild(msgHolder); } QueryPane.prototype.showError = function(e){ this.showMessage(e, "error"); } QueryPane.prototype.showMessage = function(m, type){ var md = document.createElement('div'); md.setAttribute('class', 'terminus-show-msg-' + type); md.appendChild(document.createTextNode(m)); this.messages.appendChild(md); } QueryPane.prototype.showNoBindings = function(){ nor = document.createElement('div'); nor.setAttribute('class', 'terminus-show-msg-warning'); nor.appendChild(document.createTextNode("No results available for this query")); this.clearMessages(); this.messages.appendChild(nor); } QueryPane.prototype.submitQuery = function(qObj){ this.clearMessages(); if(!qObj){ this.showError("Query could not be extracted from input box - remember that the last element in the query must be a WOQL object") } if(typeof qObj == 'string'){ this.showError(qObj); return; } this.clearResults(); this.query = qObj; this.showBusy('Fetching results ...'); var self = this; var start = Date.now(); return qObj.execute(this.client).then((results) => { var r = new TerminusClient.WOQLResult(results, qObj); this.result = r; this.clearMessages(); if(this.result.hasBindings()){ var delta = Date.now() - start; this.showMessage("Query returned " + this.result.count() + " results in " + (delta/1000) + " seconds", "info"); this.refreshViews(); } else this.showNoBindings(); }).catch((error) => { this.clearMessages(); if(error.data && error.data['terminus:witnesses']){ this.showViolations(error.data['terminus:witnesses']); } else { this.showError(error); } }); } QueryPane.prototype.clearResults = function(){ for(var i = 0; i<this.views.length; i++){ this.views[i].clearResult(this.result); } } QueryPane.prototype.refreshViews = function(){ for(var i = 0; i<this.views.length; i++){ this.views[i].updateResult(this.result); } } QueryPane.prototype.showViolations = function(vios){ var nvios = new TerminusViolations(vios, this); this.messages.appendChild(nvios.getAsDOM("")); } QueryPane.prototype.getAddViewControl = function(){ var vd = document.createElement('div'); vd.setAttribute('class', 'terminus-add-view-selector'); var self = this; var WOQL = TerminusClient.WOQL; var newView = function(val){ self.selector.value = ""; var c= eval('WOQL.' + val + "()"); var nv = self.addView(c, self.defaultResultView); if(self.result){ nv.setResult(self.result); } var vdom = nv.getAsDOM(); if(vdom){ self.resultDOM.appendChild(vdom); } } var opts = [ { value: "", label: "Add another view of results"}, { value: "table", label: "Add Table View"}, { value: "stream", label: "Add Stream View"}, { value: "graph", label: "Add Graph View"}, { value: "chooser", label: "Add Drop-down View"}, { value: "map", label: "Add Map View"} ]; var sel = HTMLHelper.getSelectionControl("view", opts, false,newView); this.selector = sel; vd.appendChild(sel); return vd; } module.exports = QueryPane;<file_sep>/src/html/datatypes/Coordinate.js function HTMLCoordinateViewer(options){ this.inputs = []; } HTMLCoordinateViewer.prototype.parseValue = function(value){ try { var parsed = (value ? JSON.parse(value) : false); if(parsed && this.type == "xdd:coordinate"){ parsed = [parsed]; } return parsed; } catch(e){ this.error = this.type + " value " + value + " failed to parse as json", e.toString(); return []; } } HTMLCoordinateViewer.prototype.renderFrame = function(frame, dataviewer){ return this.render(frame.get()); } HTMLCoordinateViewer.prototype.renderValue = function(dataviewer){ return this.render(dataviewer.value()); } HTMLCoordinateViewer.prototype.render = function(value){ var input = document.createElement("span"); input.setAttribute('class', "terminus-literal-value terminus-literal-coordinate"); if(value){ input.setAttribute('data-value', value); var parsed = this.parseValue(value); if(parsed){ for(var i = 0; i < parsed.length; i++){ var lldom = document.createElement("span"); lldom.setAttribute("class", "latlong"); lldom.appendChild(document.createTextNode("Latitude: ")); lldom.appendChild(document.createTextNode(parsed[i][0] + " °" + " ")); lldom.appendChild(document.createTextNode("Longitude: ")); lldom.appendChild(document.createTextNode(parsed[i][1] + " °" )); input.appendChild(lldom); } } else { input.setAttribute("title", this.error); } } return input; } module.exports={HTMLCoordinateViewer} <file_sep>/src/html/datatypes/GoogleMapViewer.js const GoogleMapHelper = require("./GoogleMapHelper") function GoogleMapViewer(options){} GoogleMapViewer.prototype.renderFrame = function(frame, dataviewer){ return this.render(frame.get()); } GoogleMapViewer.prototype.renderValue = function(dataviewer){ return this.render(dataviewer.value()); } GoogleMapViewer.prototype.render = function(value){ var map = document.createElement("div"); map.setAttribute('class', "gmap-window gmap-viewer"); var self = this; var ghelper = new GoogleMapHelper(); ghelper.initMap(map, value, this.type); return map; } module.exports={GoogleMapViewer};<file_sep>/src/html/DatatypeRenderers.js /* * Maintains a list of renderers that are available for rendering * datatype values - also covers choice values and id values */ function DatatypeRenderers(options){ this.registeredDataViewers = {}, this.registeredDataEditors = {}, this.defaultViewers = {}; this.defaultEditors = {}; this.universalViewer = false; this.universalEditor = false; if(options) this.options(options); //links to other documents, choices, id field, id fields of contained objects, ids of structural elements: properties, etc this.specials = ['document', 'oneOf', 'id', 'contained', 'structural']; } DatatypeRenderers.prototype.options = function (options){ this.universalViewer = (options && options.universalViewer ? options.universalViewer : false); this.universalEditor = (options && options.universalEditor ? options.universalEditor : false); this.editor = (options && options.editor ? options.editor : false); } DatatypeRenderers.prototype.getValidDataViewerList = function(datatype){ let valids = []; if(datatype && typeof this.registeredDataViewers[datatype] != "undefined"){ valids = valids.concat(this.registeredDataViewers[datatype]); } if(this.universalViewer && valids.indexOf(this.universalViewer) == -1){ valids.push(this.universalViewer); } return valids; }; DatatypeRenderers.prototype.getValidDataEditorList = function(datatype){ let valids = []; if(datatype && typeof this.registeredDataEditors[datatype] != "undefined"){ var nftypes = this.registeredDataEditors[datatype]; if(nftypes){ for(var i = 0; i<nftypes.length; i++){ if(valids.indexOf(nftypes[i]) == -1) valids.push(nftypes[i]); } } } if(typeof this.registeredDataEditors[datatype] != "undefined"){ valids = valids.concat(this.registeredDataEditors[datatype]); } if(this.universalEditor && valids.indexOf(this.universalEditor) == -1){ valids.push(this.universalEditor); } return valids; } DatatypeRenderers.prototype.getEditorForDataFrame = function(datatype){ var vals = this.getValidDataEditorList(datatype); if(this.defaultEditors[datatype] && vals[this.defaultEditors[datatype]]){ return vals[this.defaultEditors[datatype]]; } //last added is default if no explicit default is set if(vals){ return vals[Object.keys(vals)[0]]; } else { if(this.universalEditor) return this.universalEditor; } } DatatypeRenderers.prototype.getViewerForDataFrame = function(datatype){ var vals = this.getValidDataViewerList(datatype); if(this.defaultViewers[datatype] && vals[this.defaultViewers[datatype]]){ return vals[this.defaultViewers[datatype]]; } if(vals){ return vals[Object.keys(vals)[0]]; } else { if(this.universalViewer) return this.universalViewer; } } DatatypeRenderers.prototype.registerViewerForTypes = function(viewer, record, types){ for(var i = 0; i < types.length; i++){ if(typeof this.registeredDataViewers[types[i]] == "undefined"){ this.registeredDataViewers[types[i]] = {}; } if(!this.registeredDataViewers[types[i]][viewer]){ this.registeredDataViewers[types[i]][viewer] = record; } } } DatatypeRenderers.prototype.registerEditorForTypes = function(viewer, record, types){ for(var i = 0; i < types.length; i++){ if(typeof this.registeredDataEditors[types[i]] == "undefined"){ this.registeredDataEditors[types[i]] = {}; } if(!this.registeredDataEditors[types[i]][viewer]){ this.registeredDataEditors[types[i]][viewer] = record; } } } DatatypeRenderers.prototype.getRenderer = function(type, value){ var r = {}; let v = this.getViewerForDataFrame(type); if(v){ if(typeof v == "object"){ r.name = Object.keys(v)[0]; if(v[r.name].label){ r.label = v[r.name].label; } if(v[r.name].args){ r.args = v[r.name].args; } } else { r.name = v; } return r; } return false; } DatatypeRenderers.prototype.getEditor = function(type, value){ var r = {}; let v = this.getEditorForDataFrame(type); if(v){ if(typeof v == "object"){ r.name = Object.keys(v)[0]; if(v[r.name].label){ r.label = v[r.name].label; } if(v[r.name].args){ r.args = v[r.name].args; } } else { r.name = v; } return r; } return false; } module.exports=DatatypeRenderers; <file_sep>/src/html/datatypes/StringEditor.js function HTMLStringEditor(options){ this.options(options); } HTMLStringEditor.prototype.options = function(options){ this.css = ((options && options.css) ? "terminus-literal-value " + options.css : "terminus-literal-value"); this.opts = options; } HTMLStringEditor.prototype.renderFrame = function(frame, dataviewer){ var value = frame.get(); var big = ((this.opts && typeof this.opts.big != "undefined") ? this.opts.big : this.isBigType(this.type, value)); if(big){ var input = document.createElement("textarea"); this.css += " terminus-literal-big-value"; } else { var size = ((this.opts && typeof this.opts.size != "undefined") ? this.opts.size : this.getTypeSize(this.type, value)); var input = document.createElement("input"); input.setAttribute('type', "text"); input.setAttribute('size', size); } input.setAttribute('class', this.css); input.setAttribute("data-value", value); input.value = value; var self = this; input.addEventListener("input", function(){ frame.set(this.value); }); return input; } HTMLStringEditor.prototype.isBigType = function(ty, value){ if(value && value.length && value.length > 100) return true; var longs = ["xdd:coordinatePolyline", "xdd:coordinatePolygon", "xsd:base64Binary", "xdd:html", "xdd:json", "rdf:XMLLiteral"]; if(longs.indexOf(ty) == -1) return false; return true; } HTMLStringEditor.prototype.getTypeSize = function(ty, value){ if(value && value.length && value.length > 40) return 80; var bigs = ["xdd:url", "xdd:coordinate", "xsd:anyURI"]; var smalls = ["xsd:gYearMonth", "xdd:gYearRange", "xsd:decimal", "xsd:float", "xsd:time", "xsd:date", "xsd:dateTimeStamp","xsd:gYearMonth", "xsd:gMonthDay", "xsd:duration", "xsd:yearMonthDuration", "xsd:dayTimeDuration", "xsd:nonNegativeInteger", "xsd:positiveInteger", "xsd:negativeInteger", "xsd:nonPositiveInteger", "xsd:integer","xsd:unsignedInt"]; var tinys = ["xsd:boolean", "xsd:gYear", "xsd:gMonth", "xsd:gDay", "xsd:byte", "xsd:short", "xsd:unsignedByte", "xsd:language"]; if(bigs.indexOf(ty) != -1) return 80; if(smalls.indexOf(ty) != -1) return 16; if(tinys.indexOf(ty) != -1) return 8; return 32; } module.exports={HTMLStringEditor} <file_sep>/src/html/datatypes/GoogleMapEditor.js const GoogleMapHelper = require("./GoogleMapHelper") function GoogleMapEditor(options){} GoogleMapEditor.prototype.renderFrame = function(frame, dataviewer){ var mapcontainer = document.createElement("div"); mapcontainer.setAttribute('class', "gmap-window gmap-editor"); var self = this; var ghelper = new GoogleMapHelper(); var map = ghelper.initMap(mapcontainer, value, this.type); if(ty == "xdd:coordinate"){ google.maps.event.addListener(map, 'click', function(event) { var position = event.latLng; var coo = "[" + position.lat() + "," + position.lng() + "]"; dataviewer.set(coo); ghelper.clearMarkers(); var init = { position: position, map: map } var marker = new google.maps.Marker(init); ghelper.markers.push(marker); }); } else { google.maps.event.addListener(map, 'click', function(event) { var path = ghelper.polyline.getPath(); path.push(event.latLng); var position = event.latLng; ghelper.addMarker(position, map, frame, '#' + path.getLength(), this.type); }); } return mapcontainer; } module.exports={GoogleMapEditor};<file_sep>/src/viewer/WOQLRule.js const TerminusClient = require('@terminusdb/terminus-client'); const WOQLChooser = require("./WOQLChooser"); const WOQLTable = require("./WOQLTable"); const WOQLQueryViewer = require("./WOQLQueryView"); const WOQLGraph = require("./WOQLGraph"); const WOQLStream = require("./WOQLStream"); const TerminusFrame = require("./TerminusFrame"); TerminusClient.WOQL.table = function(){ return new WOQLTableConfig(); } TerminusClient.WOQL.chart = function(){ return new WOQLChartConfig(); } TerminusClient.WOQL.graph = function(){ return new WOQLGraphConfig(); } TerminusClient.WOQL.chooser = function(){ return new WOQLChooserConfig(); } TerminusClient.WOQL.stream = function(){ return new WOQLStreamConfig(); } TerminusClient.WOQL.document = function(){ return new FrameConfig(); } TerminusClient.WOQL.loadConfig = function(config){ if(config.table){ var view = new WOQLTableConfig(); view.loadJSON(config.table, config.rules); } else if(config.chooser){ var view = new WOQLChooserConfig(); view.loadJSON(config.chooser, config.rules); } else if(config.graph){ var view = new WOQLGraphConfig(); view.loadJSON(config.graph, config.rules); } else if(config.stream){ var view = new WOQLStreamConfig(); view.loadJSON(config.stream, config.rules); } else if(config.frame){ var view = new FrameConfig(); view.loadJSON(config.frame, config.rules); } return view; } //the below are aspirational... //TerminusClient.WOQL.map = function(){ return new WOQLMapConfig(); } //TerminusClient.WOQL.chart = function(){ return new WOQLChartConfig(); } //Class for expressing and matching rules about WOQL results //especially for efficiently expressing rules about how they should be rendered //const TerminusClient = require('@terminusdb/terminus-client'); function FrameConfig(){ this.rules = []; this.type = "document"; } FrameConfig.prototype.prettyPrint = function(){ var str = "view = WOQL.document();\n"; if(this.renderer()){ str += "view.renderer('" + this.renderer() + "')\n"; } if(typeof this.load_schema() != "undefined"){ str += "view.load_schema(" + this.load_schema() + ")\n"; } for(var i = 0; i<this.rules.length ; i++){ str += "view." + this.rules[i].prettyPrint("frame") + "\n"; } return str; } FrameConfig.prototype.json = function(){ let jr = []; for(var i = 0; i<this.rules.length; i++){ jr.push(this.rules[i].json()); } var conf = {}; if(typeof this.renderer() != "undefined"){ conf['renderer'] = this.renderer(); } if(typeof this.load_schema() != "undefined"){ conf['load_schema'] = this.load_schema(); } let mj = {"frame" :conf, "rules": jr}; return mj; } FrameConfig.prototype.loadJSON = function(config, rules){ var jr = []; for(var i = 0; i<rules.length; i++){ var nr = new TerminusClient.WOQL.rule(); nr.json(rules[i]); jr.push(nr); } this.rules = jr; if(typeof config.renderer != "undefined"){ this.renderer(config.renderer); } if(typeof config.load_schema != "undefined"){ this.load_schema(config.load_schema); } } FrameConfig.prototype.create = function(client, renderers){ var tf = new TerminusFrame(client, this); if(this.trenderer) tf.setRenderer(this.trenderer); else if(renderers && renderers['frame']){ tf.setRenderer(renderers['frame']); } return tf; } FrameConfig.prototype.renderer = function(rend){ if(typeof rend == "undefined") return this.trenderer; this.trenderer = rend; return this; } FrameConfig.prototype.json_rules = function(){ let jr = []; for(var i = 0; i<this.rules.length; i++){ jr.push(this.rules[i].json()); } return jr; } FrameConfig.prototype.load_schema = function(tf){ if(typeof tf == "undefined") return this.get_schema; this.get_schema = tf; return this; } FrameConfig.prototype.show_all = function(r){ this.all().renderer(r); return this; } FrameConfig.prototype.show_parts = function(o, p, d){ this.object().renderer(o); this.property().renderer(p); this.data().renderer(d); return this; } FrameConfig.prototype.object = function(){ let fp = TerminusClient.WOQL.rule(); fp.scope("object") this.rules.push(fp); return fp; } FrameConfig.prototype.property = function(){ let fp = TerminusClient.WOQL.rule(); fp.scope("property"); this.rules.push(fp); return fp; } FrameConfig.prototype.data = function(){ let fp = TerminusClient.WOQL.rule(); fp.scope("data") this.rules.push(fp); return fp; } FrameConfig.prototype.all = function(){ let fp = TerminusClient.WOQL.rule(); fp.scope("*") this.rules.push(fp); return fp; } FrameConfig.prototype.setFrameDisplayOptions = function(frame, rule){ if(typeof frame.display_options == "undefined") frame.display_options = {}; if(typeof rule.mode() != "undefined") { frame.display_options.mode = rule.mode();} if(typeof rule.view() != "undefined") frame.display_options.view = rule.view(); //if(typeof rule.facets() != "undefined") frame.display_options.facets = rule.facets(); //if(typeof rule.facet() != "undefined") frame.display_options.facet = rule.facet(); if(typeof rule.showDisabledButtons() != "undefined") frame.display_options.show_disabled_buttons = rule.showDisabledButtons(); if(typeof rule.features() != "undefined") { frame.display_options.features = rule.features(); } if(typeof rule.header() != "undefined") frame.display_options.header = rule.header(); if(typeof rule.hidden() != "undefined") frame.display_options.hidden = rule.hidden(); if(typeof rule.collapse() != "undefined") frame.display_options.collapse = rule.collapse(); if(typeof rule.headerFeatures() != "undefined") frame.display_options.header_features = rule.headerFeatures(); if(typeof rule.showEmpty() != "undefined") frame.display_options.show_empty = rule.showEmpty(); if(typeof rule.featureRenderers() != "undefined") frame.display_options.feature_renderers = rule.featureRenderers(); if(typeof rule.dataviewer() != "undefined") { frame.display_options.dataviewer = rule.dataviewer(); if(typeof rule.args() != "undefined") frame.display_options.args = rule.args(); } } //WOQL.rule().renderer("object").json(), //WOQL.rule().renderer("property").json(), //WOQL.rule().renderer("data").json(), //WOQL.rule().renderer("data").property("rdfs:comment").render(false).json() function WOQLStreamConfig(){ this.rules = []; this.type = "stream"; } WOQLStreamConfig.prototype.prettyPrint = function(){ var str = "view = WOQL.stream();\n"; for(var i = 0; i<this.rules.length ; i++){ str += "view." + this.rules[i].prettyPrint("stream") + "\n"; } return str; } WOQLStreamConfig.prototype.loadJSON = function(config, rules){ var jr = []; for(var i = 0; i<rules.length; i++){ var nr = new WOQLRule(); nr.json(rules[i]); jr.push(nr); } this.rules = jr; } WOQLStreamConfig.prototype.json = function(){ let jr = []; for(var i = 0; i<this.rules.length; i++){ jr.push(this.rules[i].json()); } var conf = {}; let mj = {"stream" :conf, "rules": jr}; return mj; } WOQLStreamConfig.prototype.getMatchingRules = function(row, key, context, action){ return getMatchingRules(this.rules, row, key, context, action); } WOQLStreamConfig.prototype.create = function(client, renderers){ var wqt = new WOQLStream(client, this); if(this.trenderer) wqt.setRenderer(this.trenderer); else if(renderers && renderers['stream']){ wqt.setRenderer(renderers['stream']); } return wqt; } function WOQLChooserConfig(){ this.rules = []; this.type = "chooser"; } WOQLChooserConfig.prototype.getMatchingRules = function(row, key, context, action){ return getMatchingRules(this.rules, row, key, context, action); } WOQLChooserConfig.prototype.create = function(client, renderers){ var wqt = new WOQLChooser(client, this); if(this.trenderer) wqt.setRenderer(this.trenderer); else if(renderers && renderers['chooser']){ wqt.setRenderer(renderers['chooser']); } return wqt; } WOQLChooserConfig.prototype.prettyPrint = function(){ var str = "view = WOQL.chooser();\n"; if(typeof this.change() != "undefined"){ str += "view.change(" + this.change() + ")\n"; } if(typeof this.show_empty() != "undefined"){ str += "view.show_empty('" + this.show_empty() + "')\n"; } if(typeof this.values() != "undefined"){ str += "view.values('" + removeNamespaceFromVariable(this.values()) + "')\n"; } if(typeof this.labels() != "undefined"){ str += "view.labels('" + removeNamespaceFromVariable(this.labels()) + "')\n"; } if(typeof this.titles() != "undefined"){ str += "view.titles('" + removeNamespaceFromVariable(this.titles()) + "')\n"; } if(typeof this.sort() != "undefined"){ str += "view.sort(" + this.sort() + ")\n"; } if(typeof this.direction() != "undefined"){ str += "view.direction('" + this.direction() + "')\n"; } for(var i = 0; i<this.rules.length ; i++){ str += "view." + this.rules[i].prettyPrint("chooser") + "\n"; } return str; } WOQLChooserConfig.prototype.json = function(){ let jr = []; for(var i = 0; i<this.rules.length; i++){ jr.push(this.rules[i].json()); } var conf = {}; if(typeof this.change() != "undefined"){ conf['change'] = this.change(); } if(typeof this.show_empty() != "undefined"){ conf['show_empty'] = this.show_empty(); } if(typeof this.values() != "undefined"){ conf['values'] = this.values(); } if(typeof this.labels() != "undefined"){ conf['labels'] = this.labels(); } if(typeof this.titles() != "undefined"){ conf['titles'] = this.titles(); } if(typeof this.sort() != "undefined"){ conf['sort'] = this.sort(); } if(typeof this.direction() != "undefined"){ conf['direction'] = this.direction(); } let mj = {"chooser" :conf, "rules": jr}; return mj; } WOQLChooserConfig.prototype.loadJSON = function(config, rules){ var jr = []; for(var i = 0; i<rules.length; i++){ var nr = new WOQLRule(); nr.json(rules[i]); jr.push(nr); } this.rules = jr; if(typeof config.change != "undefined"){ this.change(config.change); } if(typeof config.show_empty != "undefined"){ this.show_empty(config.show_empty); } if(typeof config.values != "undefined"){ this.values(config.values); } if(typeof config.labels != "undefined"){ this.labels(config.labels); } if(typeof config.titles != "undefined"){ this.titles(config.titles); } if(typeof config.sort != "undefined"){ this.sort(config.sort); } if(typeof config.direction != "undefined"){ this.direction(config.direction); } } WOQLChooserConfig.prototype.change = function(v){ if(typeof v != "undefined"){ this.onChange = v; return this; } return this.onChange; } WOQLChooserConfig.prototype.show_empty = function(p){ if(typeof p != "undefined"){ this.placeholder = p; return this; } return this.placeholder; } WOQLChooserConfig.prototype.rule = function(v){ let nr = new WOQLRule("row"); this.rules.push(nr); return nr.v(v); } WOQLChooserConfig.prototype.values = function(v){ if(typeof v != "undefined"){ if(v.substring(0, 2) != "v:") v = "v:" + v; this.value_variable = v; return this; } return this.value_variable; } WOQLChooserConfig.prototype.labels = function(v){ if(v){ if(v.substring(0, 2) != "v:") v = "v:" + v; this.label_variable = v; return this; } return this.label_variable; } WOQLChooserConfig.prototype.titles = function(v){ if(v){ if(v.substring(0, 2) != "v:") v = "v:" + v; this.title_variable = v; return this; } return this.title_variable; } WOQLChooserConfig.prototype.sort = function(v){ if(v){ if(v.substring(0, 2) != "v:") v = "v:" + v; this.sort_variable = v; return this; } return this.sort_variable; } WOQLChooserConfig.prototype.direction = function(v){ if(v){ this.sort_direction = v; return this; } return this.sort_direction; } //this.choice = (config && config.choice ? config.choice : false); function WOQLTableConfig(){ this.rules = []; this.type = "table"; } WOQLTableConfig.prototype.getMatchingRules = function(row, key, context, action){ return getMatchingRules(this.rules, row, key, context, action); } WOQLTableConfig.prototype.create = function(client, renderers, dtypes){ var wqt = new WOQLTable(client, this); wqt.setDatatypes(dtypes); if(this.trenderer) wqt.setRenderer(this.trenderer); else if(renderers && renderers['table']){ wqt.setRenderer(renderers['table']); } return wqt; } WOQLTableConfig.prototype.json = function(){ let jr = []; for(var i = 0; i<this.rules.length; i++){ jr.push(this.rules[i].json()); } var conf = {}; if(typeof this.column_order() != "undefined"){ conf['column_order'] = this.column_order(); } if(typeof this.pagesize() != "undefined"){ conf['pagesize'] = this.pagesize(); } if(typeof this.renderer() != "undefined"){ conf['renderer'] = this.renderer(); } if(typeof this.pager() != "undefined"){ conf['pager'] = this.pager(); } if(typeof this.page() != "undefined"){ conf['page'] = this.page(); } let mj = {"table" :conf, "rules": jr}; return mj; } WOQLTableConfig.prototype.loadJSON = function(config, rules){ var jr = []; for(var i = 0; i<rules.length; i++){ var nr = new WOQLRule(); nr.json(rules[i]); jr.push(nr); } this.rules = jr; if(typeof config.column_order != "undefined"){ this.column_order(config.column_order); } if(typeof config.pagesize != "undefined"){ this.pagesize(config.pagesize); } if(typeof config.renderer != "undefined"){ this.renderer(config.renderer); } if(typeof config.pager != "undefined"){ this.pager(config.pager); } if(typeof config.page != "undefined"){ this.titles(config.page); } } WOQLTableConfig.prototype.prettyPrint = function(){ var str = "view = WOQL.table();\n"; if(typeof this.column_order() != "undefined"){ str += "view.column_order('" + this.column_order() + "')\n"; } if(typeof this.pagesize() != "undefined"){ str += "view.pagesize(" + this.pagesize() + ")\n"; } if(typeof this.renderer() != "undefined"){ str += "view.renderer('" + this.renderer() + "')\n"; } if(typeof this.pager() != "undefined"){ str += "view.pager(" + this.pager() + ")\n"; } if(typeof this.page() != "undefined"){ str += "view.page(" + this.page() + ")\n"; } for(var i = 0; i<this.rules.length ; i++){ str += "view." + this.rules[i].prettyPrint("table") + "\n"; } return str; } WOQLTableConfig.prototype.renderer = function(rend){ if(!rend) return this.trenderer; this.trenderer = rend; return this; } WOQLTableConfig.prototype.column_order = function(...val){ if(typeof val == "undefined" || val.length == 0){ return this.order; } this.order = addNamespacesToVariables(val); return this; } WOQLTableConfig.prototype.pager = function(val){ if(typeof val == "undefined"){ return this.show_pager; } this.show_pager = val; return this; } WOQLTableConfig.prototype.pagesize = function(val, editable){ if(typeof val == "undefined"){ return this.show_pagesize; } this.show_pagesize = val; this.change_pagesize = editable; return this; } WOQLTableConfig.prototype.page = function(val){ if(typeof val == "undefined"){ return this.show_pagenumber; } this.show_pagenumber = val; return this; } WOQLTableConfig.prototype.column = function(...cols){ let nr = new WOQLRule("column"); nr.setVariables(cols); this.rules.push(nr); return nr; } WOQLTableConfig.prototype.row = function(){ let nr = new WOQLRule("row"); this.rules.push(nr); return nr; } WOQLGraphConfig = function(){ this.rules = []; this.type = "graph"; } WOQLGraphConfig.prototype.create = function(client, renderers){ var wqt = new WOQLGraph(client, this); if(this.trenderer) wqt.setRenderer(this.trenderer); else if(renderers && renderers['graph']){ wqt.setRenderer(renderers['graph']); } return wqt; } WOQLGraphConfig.prototype.getMatchingRules = function(row, key, context, action){ return getMatchingRules(this.rules, row, key, context, action); } WOQLGraphConfig.prototype.literals = function(v){ if(typeof v != "undefined"){ this.show_literals = v; return this; } return this.show_literals; } WOQLGraphConfig.prototype.source = function(v){ if(v){ if(v.substring(0, 2) != "v:") v = "v:" + v; this.source_variable = v; return this; } return this.source_variable; } WOQLGraphConfig.prototype.fontfamily = function(v){ if(typeof v != "undefined"){ this.fontfam = v; return this; } //return 'Font Awesome 5 Free'; return this.fontfam; } WOQLGraphConfig.prototype.show_force = function(v){ if(typeof v != "undefined"){ this.force = v; return this; } return this.force; } WOQLGraphConfig.prototype.fix_nodes = function(v){ if(typeof v != "undefined"){ this.fixed = v; return this; } return this.fixed; } WOQLGraphConfig.prototype.explode_out = function(v){ if(typeof v != "undefined"){ this.explode = v; return this; } return this.explode; } WOQLGraphConfig.prototype.selected_grows = function(v){ if(typeof v != "undefined"){ this.bigsel = v; return this; } return this.bigsel; } WOQLGraphConfig.prototype.width = function(v){ if(typeof v != "undefined"){ this.gwidth = v; return this; } return this.gwidth; } WOQLGraphConfig.prototype.height = function(v){ if(typeof v != "undefined"){ this.gheight = v; return this; } return this.gheight; } WOQLGraphConfig.prototype.edges = function(...edges){ if(edges && edges.length){ var nedges = []; for(var i = 0; i<edges.length; i++){ nedges.push(addNamespacesToVariables(edges[i])); } this.show_edges = nedges; return this; } return this.show_edges; } WOQLGraphConfig.prototype.edge = function(source, target){ let nr = new WOQLRule("edge"); if(source && target) nr.setVariables([source, target]); else if(source) nr.setVariables([source]); else if(target) nr.setVariables([target]); if(source) nr.source = source; if(target) nr.target = target; this.rules.push(nr); return nr; } WOQLGraphConfig.prototype.node = function(...cols){ let nr = new WOQLRule("node"); nr.setVariables(cols); this.rules.push(nr); return nr; } WOQLGraphConfig.prototype.getConfigAsJSON = function(){ var json = {}; if(typeof this.literals() != "undefined"){ json['literals'] = this.literals(); } if(typeof this.source() != "undefined"){ json['source'] = this.source(); } if(typeof this.fontfamily() != "undefined"){ json['fontfamily'] = this.fontfamily(); } if(typeof this.show_force() != "undefined"){ json['show_force'] = this.show_force(); } if(typeof this.fix_nodes() != "undefined"){ json['fix_nodes'] = this.fix_nodes(); } if(typeof this.explode_out() != "undefined"){ json['explode_out'] = this.explode_out(); } if(typeof this.selected_grows() != "undefined"){ json['selected_grows'] = this.selected_grows(); } if(typeof this.width() != "undefined"){ json['width'] = this.width(); } if(typeof this.height() != "undefined"){ json['height'] = this.height(); } if(typeof this.edges() != "undefined"){ json['edges'] = this.edges(); } return json; } WOQLGraphConfig.prototype.loadJSON = function(config, rules){ var jr = []; for(var i = 0; i<rules.length; i++){ var nr = new WOQLRule(); nr.json(rules[i]); jr.push(nr); } this.rules = jr; if(typeof config.literals != "undefined"){ this.literals(config.literals); } if(typeof config.source != "undefined"){ this.source(config.source); } if(typeof config.fontfamily != "undefined"){ this.fontfamily(config.fontfamily); } if(typeof config.show_force != "undefined"){ this.show_force(config.show_force); } if(typeof config.fix_nodes != "undefined"){ this.fix_nodes(config.showfix_nodes_force); } if(typeof config.explode_out != "undefined"){ this.explode_out(config.explode_out); } if(typeof config.selected_grows != "undefined"){ this.selected_grows(config.selected_grows); } if(typeof config.width != "undefined"){ this.width(config.width); } if(typeof config.height != "undefined"){ this.height(config.height); } if(typeof config.edges != "undefined"){ this.edges(config.edges); } } WOQLGraphConfig.prototype.prettyPrint = function(){ var str = "view = WOQL.graph();\n"; if(typeof this.literals() != "undefined"){ str += "view.literals('" + this.literals() + "')\n"; } if(typeof this.source() != "undefined"){ str += "view.source('" + removeNamespaceFromVariable(this.source()) + "')\n"; } if(typeof this.fontfamily() != "undefined"){ str += "view.fontfamily('" + this.fontfamily() + "')\n"; } if(typeof this.show_force() != "undefined"){ str += "view.show_force('" + this.show_force() + "')\n"; } if(typeof this.fix_nodes() != "undefined"){ str += "view.fix_nodes('" + this.fix_nodes() + "')\n"; } if(typeof this.explode_out() != "undefined"){ str += "view.explode_out('" + this.explode_out() + "')\n"; } if(typeof this.selected_grows() != "undefined"){ str += "view.selected_grows('" + this.selected_grows() + "')\n"; } if(typeof this.width() != "undefined"){ str += "view.width('" + this.width() + "')\n"; } if(typeof this.height() != "undefined"){ str += "view.height('" + this.height() + "')\n"; } if(typeof this.edges() != "undefined"){ var nedges = this.edges(); var estrs = []; for(var i = 0; i<nedges.length; i++){ estrs.push("['" + nedges[i][0] + ", " + nedges[i][1] + "']"); } str += "view.edges('" + estrs.join(", ") + "')\n"; } for(var i = 0; i<this.rules.length ; i++){ str += "view." + this.rules[i].prettyPrint("graph") + "\n"; } return str; } WOQLGraphConfig.prototype.json = function(){ let jr = []; for(var i = 0; i<this.rules.length; i++){ jr.push(this.rules[i].json()); } let mj = {"graph" : this.getConfigAsJSON(), "rules": jr}; return mj; } function WOQLRule(s){ this.rule = { scope: s }; } WOQLRule.prototype.prettyPrint = function(type){ //starts with obj. ... var str = this.rule.scope + "('"; if(this.rule.variables){ str += this.rule.variables.join("', '"); } str += "')"; if(typeof this.literal() != "undefined"){ str += ".literal(" + this.literal() + ")"; } if(typeof this.type() != "undefined"){ str += ".type(" + JSON.stringify(removeNamespacesFromVariables(this.type())) + ")"; } if(typeof this.selected() != "undefined"){ str += ".selected(" + this.selected() + ")"; } if(typeof this.label() != "undefined"){ str += ".label(" + this.label() + ")"; } if(typeof this.size() != "undefined"){ str += ".size('" + this.size() + "')"; } if(typeof this.color() != "undefined"){ str += ".color([" + this.color().join(",") + "])"; } if(typeof this.charge() != "undefined"){ str += ".charge('" + this.charge() + "')"; } if(typeof this.distance() != "undefined"){ str += ".distance('" + this.distance() + "')"; } if(typeof this.weight() != "undefined"){ str += ".distance('" + this.weight() + "')"; } if(typeof this.symmetric() != "undefined"){ str += ".symmetric(" + this.symmetric() + ")"; } if(typeof this.collisionRadius() != "undefined"){ str += ".collisionRadius(" + this.collisionRadius() + ")"; } if(typeof this.icon() != "undefined"){ str += ".icon(" + JSON.stringify(this.icon()) + ")"; } if(typeof this.text() != "undefined"){ str += ".text(" + JSON.stringify(this.text()) + ")"; } if(typeof this.arrow() != "undefined"){ str += ".arrow(" + JSON.stringify(this.arrow()) + ")"; } if(typeof this.border() != "undefined"){ str += ".border(" + JSON.stringify(this.border()) + ")"; } if(typeof this.args() != "undefined"){ str += ".args(" + JSON.stringify(this.args()) + ")"; } if(typeof this.renderer() != "undefined"){ str += ".renderer('" + this.renderer() + "')"; } if(typeof this.render() != "undefined"){ str += ".render(" + this.render() + ")"; } if(typeof this.header() != "undefined"){ str += ".header('" + this.header() + "')"; } if(typeof this.click() != "undefined"){ str += ".click(" + this.click() + ")"; } if(typeof this.hover() != "undefined"){ str += ".hover(" + this.hover() + ")"; } for(var v in this.rule.constraints){ str += ".v('" + v + "')"; for(var i = 0; i<this.rule.constraints[v].length; i++){ if(typeof(this.rule.constraints[v][i]) == "function"){ str += ".filter(" + this.rule.constraints[v][i] + ")"; } else { str += ".in(" + JSON.stringify(this.rule.constraints[v][i]) + ")"; } } } return str; } /* * Graph */ WOQLRule.prototype.json = function(mjson){ if(!mjson) return this.rule; this.rule = mjson; return this; } WOQLRule.prototype.size = function(size){ if(typeof size == "undefined"){ return this.rule.size; } this.rule.size = size; return this; } WOQLRule.prototype.color = function(color){ if(typeof color == "undefined"){ return this.rule.color; } this.rule.color = color; return this; } WOQLRule.prototype.charge = function(v){ if(typeof v == "undefined"){ return this.rule.charge; } this.rule.charge = v; return this; } WOQLRule.prototype.collisionRadius = function(v){ if(typeof v == "undefined"){ return this.rule.collisionRadius; } this.rule.collisionRadius = v; return this; } WOQLRule.prototype.icon = function(json){ if(json){ this.rule.icon = json; return this; } return this.rule.icon; } WOQLRule.prototype.text = function(json){ if(json){ this.rule.text = json; return this; } return this.rule.text; } WOQLRule.prototype.border = function(json){ if(json){ this.rule.border = json; return this; } return this.rule.border; } WOQLRule.prototype.arrow = function(json){ if(json){ this.rule.arrow = json; return this; } return this.rule.arrow; } WOQLRule.prototype.distance = function(d){ if(typeof d != "undefined"){ this.rule.distance = d; return this; } return this.rule.distance; } WOQLRule.prototype.symmetric = function(d){ if(typeof d != "undefined"){ this.rule.symmetric = d; return this; } return this.rule.symmetric ; } WOQLRule.prototype.weight = function(w){ if(typeof w != "undefined"){ this.rule.weight = w; return this; } return this.rule.weight; } /* * Table */ WOQLRule.prototype.renderer = function(rend){ if(typeof rend == "undefined"){ return this.rule.renderer; } this.rule.renderer = rend; return this; } WOQLRule.prototype.header = function(hdr){ if(typeof hdr == "undefined"){ return this.rule.header; } this.rule.header = hdr; return this; } WOQLRule.prototype.render = function(func){ if(typeof func == "undefined"){ return this.rule.render; } this.rule.render = func; return this; } WOQLRule.prototype.click = function(onClick){ if(onClick){ this.rule.click = onClick; return this; } return this.rule.click; } WOQLRule.prototype.hover = function(onHover){ if(onHover){ this.rule.hover = onHover; return this; } return this.rule.hover; } /* * All */ WOQLRule.prototype.hidden = function(hidden){ if(typeof hidden == "undefined"){ return this.rule.hidden; } this.rule.hidden = hidden; return this; } WOQLRule.prototype.args = function(args){ if(typeof args == "undefined"){ return this.rule.args; } this.rule.args = args; return this; } /* * The below are conditions */ WOQLRule.prototype.literal = function(tf){ if(typeof tf == "undefined"){ return this.rule.literal; } this.rule.literal = tf; return this; } WOQLRule.prototype.type = function(...list){ if(typeof list == "undefined" || list.length == 0){ return this.rule.type; } this.rule.type = list; return this; } WOQLRule.prototype.setVariables = function(vars){ if(vars && vars.length){ this.rule.variables = addNamespacesToVariables(vars); this.current_variable = this.rule.variables[this.rule.variables.length - 1]; } return this; } WOQLRule.prototype.v = function(v){ if(v){ if(v.substring(0, 2) != "v:") v = "v:" + v; this.current_variable = v; return this; } return this.current_variable; } WOQLRule.prototype.in = function(...list){ if(this.current_variable){ if(!this.rule.constraints) this.rule.constraints = {}; if(!this.rule.constraints[this.current_variable]) this.rule.constraints[this.current_variable] = []; this.rule.constraints[this.current_variable].push(list); } return this; } WOQLRule.prototype.filter = function(tester){ if(this.current_variable){ if(!this.rule.constraints) this.rule.constraints = {}; if(!this.rule.constraints[this.current_variable]) this.rule.constraints[this.current_variable] = []; this.rule.constraints[this.current_variable].push(tester); } return this; } WOQLRule.prototype.label = function(l){ if(l){ this.rule.label = l; return this; } return this.rule.label; } WOQLRule.prototype.title = function(l){ if(l){ this.rule.title = l; return this; } return this.rule.title; } /* * This is for chooser */ WOQLRule.prototype.selected = function(s){ if(typeof s != "undefined"){ this.rule.selected = s; return this; } return this.rule.selected; } /* * Matches on * 1. scope (row, cell, column) * 2. variables - only match certain ones * 3. type - only match datatype * 4. constraints - on values of variables */ WOQLRule.prototype.match = function(data, key, context, action){ if(context && this.rule.scope != context) return false; if(key){ if(this.rule.variables && this.rule.variables.length){ if(typeof key == "object"){ if(this.rule.variables.indexOf(key[0]) == -1) return false; if(this.rule.variables.indexOf(key[1]) == -1) return false; } else if(this.rule.variables.indexOf(key) == -1) return false; } if(this.rule && this.rule.type){ if(typeof key == "object"){ if(!(data[key][0]["@type"] && this.rule.type.indexOf(data[key][0]["@type"]) != -1)){ return false; } } else if(!(data[key]["@type"] && this.rule.type.indexOf(data[key]["@type"]) != -1)){ return false; } } if(this.rule && typeof this.rule.literal != "undefined"){ if(typeof key == "object"){ if(data[key[0]]['@value']) { if(!this.rule.literal) return false; } else if(this.rule.literal) return false; } else { if(data[key]['@value']) { if(!this.rule.literal) return false; } else if(this.rule.literal) return false; } } if(typeof key == "object"){ if(this.rule.constraints && this.rule.constraints[key[0]]){ if(!data) return false; for(var i = 0; i<this.rule.constraints[key[0]].length; i++){ if(!this.test(data[key[0]], this.rule.constraints[key][0])){ return false; } } } if(this.rule.constraints && this.rule.constraints[key[1]]){ if(!data) return false; for(var i = 0; i<this.rule.constraints[key[1]].length; i++){ if(!this.test(data[key[1]], this.rule.constraints[key][1])){ return false; } } } } else if(this.rule.constraints && this.rule.constraints[key]){ if(!data) return false; for(var i = 0; i<this.rule.constraints[key].length; i++){ if(!this.test(data[key], this.rule.constraints[key])){ return false; } } } if(context == "edge"){ if(this.rule.source && this.rule.source != key[0]) return false; if(this.rule.target && this.rule.target != key[1]) return false; } } else { for(var k in this.rule.constraints){ if(!data) return false; for(var i = 0; i<this.rule.constraints[k].length; i++){ if(!this.test(data[k], this.rule.constraints[k])){ return false; } } } } if(action && typeof this.rule[action] == "undefined") return false; return true; } WOQLRule.prototype.test = function(value, constraint){ if(typeof constraint == "object" && constraint.length){ var vundertest = (value['@value'] ? value['@value'] : value); return (constraint.indexOf(vundertest) != -1); } if(typeof constraint == "function"){ return constraint(value); } } /* * Utility function adds v: to variables... */ function addNamespacesToVariables(vars){ var nvars = []; for(var i = 0; i<vars.length; i++){ var nvar = (vars[i].substring(0, 2) == "v:") ? vars[i] : "v:" + vars[i]; nvars.push(nvar); } return nvars; } function removeNamespaceFromVariable(mvar){ if(mvar.substring(0, 2) == "v:") return mvar.substring(2) return mvar; } function removeNamespacesFromVariables(vars){ var nvars = []; for(var i = 0; i<vars.length; i++){ nvars.push(removeNamespaceFromVariable(vars[i])); } return nvars; } function getMatchingRules(rules, row, key, context, action){ var matches = []; for(var i = 0; i<rules.length; i++){ if(rules[i].match(row, key, context, action)){ matches.push(rules[i].rule); } } return matches; } module.exports=TerminusClient.WOQL /* * var x = WOQL.schema(); x.addClass("my:Class").label("A class").comment("A comment").abstract().relationship(); x.addProperty("my:prop", "xsd:string").domain("my:Class").label("x").comment("x").max(2).min(1); x.execute(client).then ... */ function WOQLChartRule(scope){ WOQLRule.call(this,scope); }; WOQLChartRule.prototype = Object.create(WOQLRule.prototype); WOQLChartRule.prototype.constructor = WOQLRule; //{top:0, bottom:0, left: 30, right: 30 } WOQLChartRule.prototype.padding=function(paddingObj){ if(paddingObj){ this.rule.padding=paddingObj; return this; } return this.rule.padding=paddingObj; } WOQLChartRule.prototype.connectNulls =function(bool){ if(bool){ this.rule.connectNulls=bool; return this; } return this.rule.connectNulls=bool; } /* XAxis 'bottom' | 'top' YAxis 'left' | 'right' */ WOQLChartRule.prototype.orientation=function(orientation){ if(orientation){ this.rule.orientation = orientation; return this; } return this.rule.orientation; } WOQLChartRule.prototype.fill=function(color){ if(color){ this.rule.fill = color; return this; } return this.rule.fill; } WOQLChartRule.prototype.stroke=function(color){ if(color){ this.rule.stroke = color; return this; } return this.rule.stroke; } WOQLChartRule.prototype.strokeWidth=function(size){ if(size){ this.rule.strokeWidth = size; return this; } return this.rule.strokeWidth; } //"preserveStart" | "preserveEnd" | "preserveStartEnd" | Number WOQLChartRule.prototype.interval=function(interval){ if(interval){ this.rule.interval = interval; return this; } return this.rule.interval; } WOQLChartRule.prototype.dot=function(isVisible){ if(isVisible){ this.rule.dot = isVisible; return this; } return this.rule.dot; } WOQLChartRule.prototype.labelRotate=function(angle){ if(angle){ this.rule.labelRotate = angle; return this } return this.rule.labelRotate; } /* * axis type number| category */ WOQLChartRule.prototype.type=function(type){ if(type){ this.rule.type=type return this; } return this.rule.type } /* * works only if type is number * domainArr =[min,max]; */ WOQLChartRule.prototype.domain=function(domainArr){ if(domainArr){ this.rule.domain=domainArr return this; } return this.rule.domain } WOQLChartRule.prototype.strokeDasharray=function(dashArr){ if(dashArr){ this.rule.strokeDasharray=dashArr return this } return this.rule.strokeDasharray; } WOQLChartRule.prototype.iconSize=function(iconSize){ if(iconSize){ this.rule.iconSize=iconSize return this } return this.rule.iconSize; } /* 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'star' | 'triangle' | 'wye */ WOQLChartRule.prototype.iconType=function(iconType){ if(iconType){ this.rule.iconType=iconType return this } return this.rule.iconType; } WOQLChartRule.prototype.showTicks=function(showTicks){ if(showTicks){ this.rule.showTicks=showTicks return this } return this.rule.showTicks } WOQLChartRule.prototype.prettyPrint = function(type){ //starts with obj. ... var str = this.rule.scope + "('"; if(this.rule.variables){ str += this.rule.variables.join("', '"); } str += "')"; if(typeof this.orientation() != "undefined"){ str += ".orientation('" + this.orientation() + "')"; } if(typeof this.padding() != "undefined"){ str += ".padding(" + this.padding() + ")"; } if(typeof this.connectNulls() != "undefined"){ str += ".connectNulls(" + this.connectNulls() + ")"; } if(typeof this.fill() != "undefined"){ str += ".fill('" + this.fill() + "')"; } if(typeof this.stroke() != "undefined"){ str += ".stroke('" + this.stroke() + "')"; } if(typeof this.strokeWidth() != "undefined"){ str += ".strokeWidth(" + this.stroke() + ")"; } if(typeof this.interval() != "undefined"){ str += ".interval(" + this.interval() + ")"; } if(typeof this.dot() != "undefined"){ str += ".dot(" + this.dot() + ")"; } if(typeof this.labelRotate() != "undefined"){ str += ".labelRotate('" + this.labelRotate() + "')"; } if(typeof this.type() != "undefined"){ str += ".type('" + this.type() + "')"; } if(typeof this.domain() != "undefined"){ str += ".domain(" + this.domain() + ")"; } if(typeof this.strokeDasharray() != "undefined"){ str += ".strokeDasharray(" + this.strokeDasharray() + ")"; } if(typeof this.iconSize() != "undefined"){ str += ".iconSize(" + this.iconSize() + ")"; } if(typeof this.iconType() != "undefined"){ str += ".iconType('" + this.iconType() + "')"; } if(typeof this.showTicks() != "undefined"){ str += ".showTicks('" + this.showTicks() + "')"; } if(typeof this.label() != "undefined"){ str += ".label('" + this.label() + "')"; } return str; } function WOQLChartConfig(){ this.rules = []; this.type = "chart"; } /* {"XAxis":{dataKey:"date_i",type:'number'} ,"chartObj": [{'label':'Confident','dataKey':'conf',"chartType":"Area", "style":{"stroke":"#82ca9d", "fillOpacity":1, "fill":"#82ca9d"}}, {'label':'Predictions','dataKey':'predictions',"chartType":"Line", "style":{"strokeWidth":2, "stroke":"#ff8000"}}, {'label':'Picks','dataKey':'picks',"chartType":"Point","style": {"stroke": '#8884d8', "fill": '#8884d8'}}, {'label':'Stock','dataKey':'stock',"chartType":"Line","style": {"stroke": '#0000ff', "fill": '#0000ff'}}]} {"XAxis":{dataKey:"v:Date","label":{rotate:"-50"}},"chartObj": [{'dot':true, 'label':'Quantity','dataKey':'v:Quantity',"chartType":"Line", "style": {"stroke": '#FF9800', "fill": '#FF9800'}}] } */ WOQLChartConfig.prototype.xAxis = function(...vars){ let woqlRule = new WOQLChartRule("xAxis"); woqlRule.setVariables(vars); this.rules.push(woqlRule); return woqlRule; } WOQLChartConfig.prototype.bar = function(...vars){ let woqlRule=new WOQLChartRule("bar"); woqlRule.setVariables(vars); this.rules.push(woqlRule); return woqlRule; } WOQLChartConfig.prototype.line=function(...vars){ let woqlRule=new WOQLChartRule("line"); woqlRule.setVariables(vars); this.rules.push(woqlRule); return woqlRule; } WOQLChartConfig.prototype.point=function(...vars){ let woqlRule=new WOQLChartRule("point"); woqlRule.setVariables(vars); this.rules.push(woqlRule); return woqlRule; } WOQLChartConfig.prototype.area=function(...vars){ let woqlRule=new WOQLChartRule("area"); woqlRule.setVariables(vars); this.rules.push(woqlRule); return woqlRule; } WOQLChartConfig.prototype.cartesianGrid=function(...vars){ let woqlRule=new WOQLChartRule("cartesianGrid"); woqlRule.setVariables(vars); this.rules.push(woqlRule); return woqlRule; } WOQLChartConfig.prototype.legend=function(...vars){ let woqlRule=new WOQLChartRule("legend"); woqlRule.setVariables(vars); this.rules.push(woqlRule); return woqlRule; } WOQLChartConfig.prototype.title=function(title){ if(title){ this._title=title; return this } return this._title; } WOQLChartConfig.prototype.description=function(description){ if(description){ this._description=description; return this } return this._description; } //layout "vertical" | "horizontal" WOQLChartConfig.prototype.layout=function(layout){ if(layout){ this._layout=layout; return this } return this._layout; } //default is { top: 10, right: 30, left: 0, bottom: 0 } WOQLChartConfig.prototype.margin=function(marginObj){ if(marginObj){ this._margin=marginObj; return this } return this._margin; } WOQLChartConfig.prototype.json = function(){ let rulesArr = []; for(var i = 0; i<this.rules.length; i++){ rulesArr.push(this.rules[i].json()); } /* *general properties */ var conf = {}; if(typeof this.margin() != "undefined"){ conf['margin'] = this.margin(); } if(typeof this.title() != "undefined"){ conf['title'] = this.title(); } if(typeof this.description() != "undefined"){ conf['description'] = this.description(); } if(typeof this.layout() != "undefined"){ conf['layout'] = this.layout(); } let mj = {"chart" :conf, "rules": rulesArr}; return mj; } WOQLChartConfig.prototype.loadJSON = function(config, rules){ var jr = []; for(var i = 0; i<rules.length; i++){ var nr = new WOQLRule(); nr.json(rules[i]); jr.push(nr); } this.rules = jr; if(typeof config.margin != "undefined"){ this.margin(config.margin); } if(typeof config.title != "undefined"){ this.title(config.title); } if(typeof config.description != "undefined"){ this.description(config.description); } if(typeof config.layout != "undefined"){ this.layout(config.layout); } } WOQLChartConfig.prototype.prettyPrint = function(){ var str = "view = WOQL.chart();\n"; if(typeof this.margin() != "undefined"){ str += "view.margin(" + this.margin() + ")\n"; } if(typeof this.title() != "undefined"){ str += "view.title('" + this.title() + "')\n"; } if(typeof this.description() != "undefined"){ str += "view.description('" + this.description() + "')\n"; } if(typeof this.layout() != "undefined"){ str += "view.layout('" + this.layout() + "')\n"; } for(var i = 0; i<this.rules.length ; i++){ str += "view." + this.rules[i].prettyPrint("chart") + "\n"; } return str; } //WOQLChartConfig.prototype.style() //const woqlChart=new WOQLChartConfig();//TerminusClient.woql.chart(); //woqlChart.Bar('test'); <file_sep>/src/TerminusUI.js /** * Terminus UI object * * Traffic control of messages going between different Terminus UI pages and features * * @param opts - options array */ const ApiExplorer = require('./ApiExplorer'); const TerminusDBsdk = require('./TerminusDB'); const TerminusViolations = require('./html/TerminusViolation'); const TerminusQueryViewer = require('./TerminusQuery'); const TerminusSchemaViewer = require('./TerminusSchema'); const TerminusServersdk = require('./TerminusServer'); const TerminusURLLoader = require('./TerminusURL'); const TerminusTutorialLoader = require('./TerminusTutorial'); const TerminusPluginManager = require('./plugins/TerminusPlugin'); const UTILS = require('./Utils'); const HTMLHelper = require('./html/HTMLHelper'); const TerminusClient = require('@terminusdb/terminus-client'); //const {endpoint,apiKey} = window.env; function TerminusUI(opts){ this.client = new TerminusClient.WOQLClient(); this.controls = []; this.setOptions(opts); } /* * Client connects to specified server and specified part * opts is a json with the following fields: * server: mandatory URL of the server to connect to * key: optional client API key * dbid: id of the database to connect to * schema: if set, the UI will load the schema page after connecting * query: if set, the query will be sent to the server and the results will be loaded on the query page * document: if set, the document page corresponding to this document will be loaded after connecting * * (note: schema, query, document are mutually exclusive and must also have a dbid set) */ TerminusUI.prototype.connect = function(opts){ var self = this; this.client.connectionConfig.server = false; var key = ((opts && opts.key) ? opts.key : false); this.showBusy("Connecting to server at " + opts.server); return this.client.connect(opts.server, key) .then( function(response) { self.clearBusy(); if(opts && opts.db && self.getDBRecord(opts.db)){ self.connectToDB(opts.db); if(opts.document && self.showView("get_document")){ response = self.showDocumentPage(opts.document); } else if(opts.schema && self.showView("get_schema")){ response = self.showSchemaPage(opts.schema); } else if(opts.query && self.showView("woql_select")){ self.showQueryPage(opts.query); } else if(opts.explorer && self.showView("api_explorer")){ self.showExplorer(opts.explorer); } else { self.showDBMainPage(); } } else { self.showServerMainPage(); } self.redraw(); return response; }) .catch(function(err) { self.clearBusy(); self.showError(err); throw(err); }); } /** * Sends a request to create a new database to the server and interprets the response * * dbdets is a json object with the following fields: * id: the id of the new database (alphanumeric, no spaces, url friendly) mandatory * title: the text name of the new database for tables, etc. mandatory * description: text description of the database (optional) * key: a API client key for server auth * schema: the url of another Terminus DB from which to import schema * instance: the url of another Terminus DB from which to import data * */ TerminusUI.prototype.createDatabase = function(dbdets){ var self = this; if(!dbdets.id || !dbdets.title){ return Promise.reject(new Error(self.getBadArguments("createDatabase", "ID and title are mandatory fields"))); } var dbid = dbdets.id; self.showBusy("Creating Database " + dbdets.title + " with id " + dbid); var dbdoc = this.generateNewDatabaseDocument(dbdets); return this.client.createDatabase(dbid, dbdoc) .then(function(response){ //reload list of databases in background.. self.clearBusy(); return self.refreshDBList() .then(function(response){ if(crec = self.client.connection.getDBRecord(dbid)){ self.client.connectionConfig.dbid = dbid; self.showDBMainPage(); self.showMessage("Successfully Created Database " + dbid, "success"); } else { return Promise.reject(new Error(self.getCrashString("createDatabase", "Failed to retrieve record of created database " + dbid))); } }) }) .catch(function(error){ self.clearBusy(); self.showError(error); }); } /** * Deletes the database with the passed id from the currently connected server */ TerminusUI.prototype.deleteDatabase = function(dbid){ var self = this; var delrec = this.client.connection.getDBRecord(); var lid = (dbid ? dbid : this.db()); var dbn = (delrec && delrec['rdfs:label'] && delrec['rdfs:label']["@value"] ? delrec['rdfs:label']["@value"] + " (id: " + lid + ")" : lid); this.showBusy("Deleting database " + dbn); return this.client.deleteDatabase(lid) .then(function(response){ self.clearBusy(); self.showServerMainPage(); self.showMessage("Successfully Deleted Database " + dbn, "warning"); self.refreshDBList(); return response; }) .catch(function(error){ self.clearBusy(); self.showError(error); }); } /* * Transforms a details (id, title, description) array into json-ld document */ TerminusUI.prototype.generateNewDatabaseDocument = function(dets){ var doc = { "@context" : { rdfs: "http://www.w3.org/2000/01/rdf-schema#", terminus: "http://terminusdb.com/schema/terminus#" }, "@type": "terminus:Database" } if(dets.title){ doc['rdfs:label'] = { "@language": "en", "@value": dets.title }; } if(dets.description){ doc['rdfs:comment'] = { "@language": "en", "@value": dets.description }; } doc['terminus:allow_origin'] = { "@type" : "xsd:string", "@value" : "*" }; return doc; } TerminusUI.prototype.getBadArguments = function(fname, str){ return "Bad arguments to " + fname + ": " + str; } TerminusUI.prototype.getCrashString = function(fname, str){ return "Results from " + fname + " indicate the possibility of a system failure " + str; } /* * Parses the passed URL and turns it into a call to the connect function - loads the appropriate endpoing */ TerminusUI.prototype.load = function(url, key){ var args = {}; if(url && url.indexOf("/document/") != -1){ url = url.substring(0, url.indexOf("/document/")); args.document = url.substring(url.indexOf("/document/")+10); } else if(url && url.indexOf("/schema") != -1){ url = url.substring(0, url.indexOf("/schema")); args.schema = {}; } else if(url && url.indexOf("/woql") != -1){ url = url.substring(0, url.indexOf("/query")); args.query = url.substring(url.indexOf("/query")+7); } args.server = url; if(key) args.key = key; return this.connect(args); } /** * Fetches the DB URL from the url by chopping off the extra bits */ TerminusUI.prototype.getConnectionEndpoint = function(url){ if(url && url.lastIndexOf("/schema") != -1){ return url.substring(0, url.lastIndexOf("/schema")); } if(url && url.lastIndexOf("/document") != -1){ return url.substring(0, url.lastIndexOf("/document")); } if(url && url.lastIndexOf("/frame") != -1){ return url.substring(0, url.lastIndexOf("/frame")); } if(url && url.lastIndexOf("/woql") != -1){ return url.substring(0, url.lastIndexOf("/woql")); } return url; } TerminusUI.prototype.server = function(){ return this.client.connectionConfig.server; } TerminusUI.prototype.db = function(){ return this.client.connectionConfig.dbid; } TerminusUI.prototype.clearServer = function(){ this.client.connectionConfig.server = false; } TerminusUI.prototype.connectToDB = function(dbid){ this.client.connectionConfig.dbid = dbid; //set standard prefixes for the current db TerminusClient.UTILS.addURLPrefix('doc', this.client.connectionConfig.dbURL() + "/document/"); TerminusClient.UTILS.addURLPrefix('scm', this.client.connectionConfig.dbURL() + "/schema#"); } TerminusUI.prototype.clearDB = function(){ this.client.connectionConfig.dbid = false; } TerminusUI.prototype.removeDB = function(db, url){ this.client.connection.removeDB(db, url); } TerminusUI.prototype.getDBRecord = function(db, url){ return this.client.connection.getDBRecord(db, url); } TerminusUI.prototype.refreshDBList = function(){ var self = this; return this.client.connect(); } TerminusUI.prototype.showServerMainPage = function(){ this.viewer = new TerminusServersdk.TerminusServerViewer(this); this.redrawMainPage(); } TerminusUI.prototype.showCollaboratePage = function(){ this.viewer = new TerminusURLLoader(this); this.redrawMainPage(); } TerminusUI.prototype.showTutorialPage = function(){ this.viewer = new TerminusTutorialLoader(this); this.redrawMainPage(); } TerminusUI.prototype.showLoadURLPage = function(val){ this.viewer = new TerminusURLLoader(this, val); this.redrawMainPage(); } TerminusUI.prototype.showDBMainPage = function(){ this.viewer = new TerminusDBsdk.TerminusDBViewer(this); this.page = "db"; this.redraw(); } TerminusUI.prototype.showCreateDBPage = function(){ this.viewer = new TerminusDBsdk.TerminusDBCreator(this); this.redrawMainPage(); } TerminusUI.prototype.showSchemaPage = function(durl){ this.viewer = new TerminusSchemaViewer(this); this.redrawMainPage(); } TerminusUI.prototype.showQueryPage = function(query){ this.viewer = new TerminusQueryViewer(this, query, this.options); this.redrawMainPage(); } TerminusUI.prototype.showDocumentPage = function(durl){ this.viewer = new TerminusDBsdk.TerminusDBViewer(this); this.page = "docs"; if(durl){ this.viewer.docid = durl; } this.redrawMainPage(); } TerminusUI.prototype.showCreateDocument = function(durl){ this.viewer = new TerminusDocumentViewer(this, "create", this.getDocCreatorOptions()); const promise = this.viewer.loadCreateDocument(durl); this.redrawMainPage(); return promise; } TerminusUI.prototype.redrawMainPage = function(){ HTMLHelper.removeChildren(this.mainDOM); if(this.viewer && this.mainDOM){ var x = this.viewer.getAsDOM(); this.mainDOM.appendChild(x); } } TerminusUI.prototype.deleteDBPermitted = function(dbid){ if(dbid == "terminus") return false; if(this.client.connection.capabilitiesPermit("delete_database", dbid)){ return true; } return false; } TerminusUI.prototype.getDeleteDBButton = function(dbid){ if(!this.deleteDBPermitted(dbid)) return false; //var delbut = document.createElement('button'); var icon = document.createElement('i'); icon.setAttribute("class", "terminus-db-list-del-icon fa fa-trash"); //delbut.appendChild(icon); //delbut.appendChild(document.createTextNode("Delete Database")); //delbut.setAttribute("class", "terminus-control-button terminus-delete-db-button"); // function to fix db in a closure var self = this; var delDB = function(db){ return function(){ let deleteConfirm = confirm(`This action is irreversible, it will remove the database from the system permanently. Are you sure you want to delete ${db} Database?`); if (deleteConfirm == true) { self.deleteDatabase(db); } } }; icon.addEventListener("click", delDB(dbid)); return icon; } TerminusUI.prototype.showResult = function(response){ this.showMessage(response, "success"); }; TerminusUI.prototype.showError = function(response){ this.showMessage(response, "error"); }; TerminusUI.prototype.showWarning = function(response){ this.showMessage(response, "warning"); }; TerminusUI.prototype.setAttachedServer = function(url){ this.attached_server = url; } TerminusUI.prototype.attachedServer = function(){ return this.attached_server; } TerminusUI.prototype.clearMessages = function(response){ if(this.messages) HTMLHelper.removeChildren(this.messages); }; TerminusUI.prototype.clearMainPage = function(){ if(this.main) HTMLHelper.removeChildren(this.main); } TerminusUI.prototype.setMessageDOM = function(dom){ this.messages = dom; } TerminusUI.prototype.setbuttonControls = function(dom){ this.buttons = dom; } TerminusUI.prototype.setControllerDOM = function(dom){ this.controller = dom; } TerminusUI.prototype.setExplorerDOM = function(dom){ this.explorer = dom; } TerminusUI.prototype.setPluginsDOM = function(dom){ this.plugins = dom; } TerminusUI.prototype.setViewerDOM = function(dom){ this.mainDOM = dom; } TerminusUI.prototype.draw = function(comps, slocation){ if(comps && comps.viewer) this.setViewerDOM(comps.viewer); if(comps && comps.buttons) this.setbuttonControls(comps.buttons); if(comps && comps.messages) this.setMessageDOM(comps.messages); if(comps && comps.controller) this.setControllerDOM(comps.controller); //if(comps && comps.explorer) this.setExplorerDOM(comps.explorer); if(comps && comps.plugins) this.setPluginsDOM(comps.plugins); if(this.plugins){ this.drawPlugins(); } if(this.buttons){ //this.toggleControl(); } var self = this; var cdrawn = false; /* use envairoment variable */ const endpoint=process.env.API_URL const apiKey=process.env.API_KEY console.log("__TEST__",endpoint,apiKey) if(endpoint){ if(typeof this.client.connection.connection[endpoint] == "undefined") { return this.connect({server:endpoint,key:apiKey}) .catch(function(error){ self.showLoadURLPage(); }); } }else if(slocation && slocation.server){ if(typeof this.client.connection.connection[slocation.server] == "undefined") { return this.connect(slocation) .catch(function(error){ self.showLoadURLPage(); }); } } else { this.showLoadURLPage(); }; } TerminusUI.prototype.redraw = function(msg){ this.clearMessages(); this.redrawControls(); if(this.explorer){ HTMLHelper.removeChildren(this.explorer); //this.drawExplorer(); } if(this.viewer){ this.redrawMainPage(); } if(msg) this.showMessage(msg); }; TerminusUI.prototype.toggleDashboardWidget = function(widget){ HTMLHelper.removeChildren(this.controller); HTMLHelper.removeChildren(this.explorer); UTILS.removeSelectedNavClass('terminus-dashboard-selected'); widget.classList.add('terminus-dashboard-selected'); } TerminusUI.prototype.toggleControl = function(){ /* var self = this; this.buttons.client.addEventListener('click', function(){ self.toggleDashboardWidget(this); self.drawControls(); self.showServerMainPage(); }) this.buttons.explorer.addEventListener('click', function(){ self.toggleDashboardWidget(this); self.drawExplorer(); })*/ } TerminusUI.prototype.redrawControls = function(){ if(this.controller){ HTMLHelper.removeChildren(this.controller); this.drawControls(); } } TerminusUI.prototype.drawControls = function(){ this.controls = []; this.loadControls(); for(var i = 0; i<this.controls.length; i++){ var ncontrol = this.controls[i]; if(ncontrol && (nd = ncontrol.getAsDOM())){ this.controller.appendChild(nd); } } } TerminusUI.prototype.drawExplorer = function(){ if(this.explorer){ if(this.showControl("api_explorer")){ var exp = new ApiExplorer(this); ae = exp.getAsDOM(); this.explorer.appendChild(ae); this.explorer.style.display = 'block'; } } } TerminusUI.prototype.loadControls = function(){ if(this.showControl('server')){ var sc = new TerminusServersdk.TerminusServerController(this); if(sc) { this.controls.push(sc); } if(this.db() && this.showControl("db")){ var sc = new TerminusDBsdk.TerminusDBController(this); if(sc) this.controls.push(sc); } } } TerminusUI.prototype.showControl = function(el){ if(this.show_controls.indexOf(el) == -1) return false; if(this.pseudoCapability(el)) return true; if(this.client.connection.capabilitiesPermit(el)) { return true; } return false; } TerminusUI.prototype.showView = function(el){ if(this.show_views.indexOf(el) == -1) return false; if(this.pseudoCapability(el)) return true; if(this.client.connection.capabilitiesPermit(el)) { return true; } return false; } TerminusUI.prototype.clearBusy = function(response){ this.clearMessages(); if(this.viewer && typeof this.viewer.busy == "function") this.viewer.busy(false); } TerminusUI.prototype.getBusyLoader = function(bsyDom){ var pd = document.createElement('div'); var pbc = document.createElement('div'); pbc.setAttribute('class', 'term-progress-bar-container'); pd.appendChild(pbc); var pbsa = document.createElement('div'); pbsa.setAttribute('class', 'term-progress-bar term-stripes animated reverse slower'); pbc.appendChild(pbsa); var pbia = document.createElement('span'); pbia.setAttribute('class', 'term-progress-bar-inner'); pbsa.appendChild(pbia); bsyDom.appendChild(pd); } TerminusUI.prototype.showMessage = function(msg, type){ if(this.messages){ HTMLHelper.removeChildren(this.messages); var md = document.createElement('div'); switch(type){ case 'busy': var msgHolder = document.createElement('div'); msgHolder.setAttribute('class', 'terminus-busy-msg') msgHolder.appendChild(document.createTextNode(msg)); md.appendChild(msgHolder); this.getBusyLoader(md); break; case 'success': md.setAttribute('class', 'terminus-show-msg-success'); md.appendChild(document.createTextNode(msg)); break; case 'error': md.setAttribute('class', 'terminus-show-msg-error'); md.appendChild(document.createTextNode(msg)); break; case 'info': md.setAttribute('class', 'terminus-show-msg-info'); md.appendChild(document.createTextNode(msg)); break; case 'warning': md.setAttribute('class', 'terminus-show-msg-warning'); md.appendChild(document.createTextNode(msg)); break; } this.messages.appendChild(md); } }; TerminusUI.prototype.showViolations = function(vios, type){ var nvios = new TerminusViolations(vios, this); if(this.messages){ var cmsg = (type == "schema" ? " in Schema" : " in Document"); HTMLHelper.removeChildren(this.messages); this.messages.appendChild(nvios.getAsDOM(cmsg)); } } TerminusUI.prototype.showBusy = function(msg){ this.showMessage(msg, "busy"); if(this.viewer && typeof this.viewer.busy == "function") this.viewer.busy(msg); }; TerminusUI.prototype.pseudoCapability = function(el){ var pseuds = ["server", "db", "collaborate", "change-server", "api_explorer", "import_schema", "add_new_library"]; if(pseuds.indexOf(el) == -1) return false; return true; } TerminusUI.prototype.setOptions = function(opts){ this.show_controls = opts && opts.controls ? opts.controls : ["server", "db", "change-server", "schema_format", "import_schema", "class_frame", "create_database", "collaborate", "get_document", "update_schema", "get_schema", "woql_select" ]; this.show_views = opts && opts.views ? opts.views : this.show_controls; if(opts.document){ this.document_options = opts.document; } if(opts.schema){ this.schema_options = opts.schema; } if(opts.attach_server){ this.setAttachedServer(opts.attach_server) } this.piman = new TerminusPluginManager(); var self = this; this.piman.init(opts.plugins, function(){ /*var pins = ["gmaps", "quill", "select2"]; for(var i = 0; i<pins.length; i++){ if(self.piman.pluginAvailable(pins[i])){ //RenderingMap.addPlugin(pins[i]); } }*/ //self.redraw(); }); if(opts.css && this.piman){ this.piman.loadPageCSS(opts.css); } this.loadControls(); } TerminusUI.prototype.pluginAvailable = function(p){ return this.piman.pluginAvailable(p); } TerminusUI.prototype.drawPlugins = function(){ if(!this.piman) { console.log(new Error("No plugin manager initialised in UI object")); return false; } this.plugins.appendChild(this.piman.getAsDOM(this)); } TerminusUI.prototype.getDocViewerOptions = function(){ if(this.document_options && this.document_options['view']){ return this.document_options['view']; } return false; } TerminusUI.prototype.getDocCreatorOptions = function(){ if(this.document_options && this.document_options['view']){ return this.document_options['view']; } return false; } TerminusUI.prototype.getClassFrameOptions = function(){ return this.viewdoc_options; } module.exports=TerminusUI <file_sep>/src/html/datatypes/String.js const HTMLHelper = require('../HTMLHelper'); function HTMLStringViewer(options){ this.options(options); } HTMLStringViewer.prototype.options = function(options){ this.size = ((options && options.size) ? options.size : false); this.css = ((options && options.css) ? "terminus-literal-value " + options.css : "terminus-literal-value"); this.max_word_size = (options && options.max_word_size ? options.max_word_size : false); this.max_cell_size = (options && options.max_cell_size ? options.max_cell_size : false); this.show_types = (options && options.show_types ? options.show_types : false); } HTMLStringViewer.prototype.renderFrame = function(frame, dataviewer){ var value = frame.get(); return this.render(value); } HTMLStringViewer.prototype.renderValue = function(dataviewer){ return this.render(dataviewer.value()); } HTMLStringViewer.prototype.render = function(value){ var input = document.createElement("span"); input.setAttribute('class', this.css); input.setAttribute('data-value', value); if(this.show_types && this.type != "id"){ value += " (" + this.type + ")"; } if(this.max_word_size || this.max_cell_size){ HTMLHelper.wrapShortenedText(input, value, this.max_cell_size, this.max_word_size); } else { value = document.createTextNode(value); input.appendChild(value); } return input; } module.exports={HTMLStringViewer} <file_sep>/src/html/stream/SimpleStream.js const HTMLHelper = require('../HTMLHelper'); function SimpleStream(){ this.holder = document.createElement("div"); } SimpleStream.prototype.options = function(options){ for(var k in options){ this[k] = options[k]; } return this; } SimpleStream.prototype.render = function(stream){ if(stream) this.stream = stream; HTMLHelper.removeChildren(this.holder); //var ctls = this.getControlsDOM(); //var tab = this.getTableDOM(); //if(ctls) this.holder.appendChild(ctls) //this.holder.appendChild(tab); return this.holder; } module.exports = SimpleStream;<file_sep>/src/html/datatypes/ChoiceEditor.js const HTMLHelper = require('../HTMLHelper'); function HTMLChoiceEditor(options){}; HTMLChoiceEditor.prototype.renderFrame = function(frame, dataviewer){ var value = frame.get(); var optInput = document.createElement("select"); optInput.setAttribute('class', "terminus-choice-picker"); var foptions = frame.getChoiceOptions(); foptions.unshift({ value: "", label: "Not Specified"}); var callback = function(val){ frame.set(val); } var sel = HTMLHelper.getSelectionControl("select-choice", foptions, value, callback); return sel; } module.exports={HTMLChoiceEditor} <file_sep>/src/html/ResultPane.js const TerminusCodeSnippet = require('./query/TerminusCodeSnippet'); const Datatypes = require("./Datatypes"); const DatatypeRenderers = require("./DatatypeRenderers"); const SimpleTable = require("./table/SimpleTable"); const SimpleGraph = require("./graph/SimpleGraph"); const SimpleStream = require("./stream/SimpleStream"); const SimpleChooser = require("./chooser/SimpleChooser"); const HTMLHelper = require('./HTMLHelper'); /** * Result Pane is defined by a WOQL configuration object * Visually it consists of a single rule editor (showing the current state of the configuration object) which may be collapsed behind a configuration link * and a single result view which shows the result of the rule when applied to the current results. * */ function ResultPane(client, querypane, config){ this.client = client; this.qp = querypane; this.config = config; this.container = document.createElement('span'); this.container.setAttribute('class', 'terminus-result-pane'); } ResultPane.prototype.options = function(opts){ this.showConfig = (opts && typeof opts.showConfig != "undefined" ? opts.showConfig : false); this.editConfig = (opts && typeof opts.editConfig != "undefined" ? opts.editConfig : false); this.changeViewType = (opts && typeof opts.changeViewType != "undefined" ? opts.changeViewType : true); this.intro = (opts && typeof opts.intro != "undefined" ? opts.intro : false); this.renderers = (opts && opts.renderers ? opts.renderers : { table: new SimpleTable(), graph: new SimpleGraph(), stream: new SimpleStream(), chooser: new SimpleChooser() }); if(this.config){ this.viewers = [this.config]; } this.viewers = (opts && typeof opts.viewers != "undefined" ? this.viewers.concat(opts.viewers) : this.viewers); this.currentViewer = 0; return this; } ResultPane.prototype.getRenderer = function(){ if(this.config && this.config.renderer()){ return this.config.renderer(); } else { if(this.config.type && this.renderers[this.config.type]){ return this.renderers[this.config.type]; } } return false; } ResultPane.prototype.getAsDOM = function(){ if(this.intro){ var di = (typeof this.intro == "string" ? document.createTextNode(this.intro) : this.intro); this.container.appendChild(di); } var configspan = document.createElement("span"); configspan.setAttribute("class", "pane-config-icons"); this.container.appendChild(configspan); this.resultDOM = document.createElement('span'); this.resultDOM.setAttribute('class', 'terminus-result-view'); if(this.result){ this.resultDOM.appendChild(this.getResultDOM()); } this.container.appendChild(this.resultDOM); if(this.showConfig){ this.showingQuery = (this.showConfig != "icon"); var mode = (this.editConfig ? "edit" : "view"); this.input = this.createInput(mode); var ipdom = this.input.getAsDOM(); var ispan = document.createElement("span"); ispan.addEventListener('mouseover', function(){ this.style.cursor = "pointer"; }); ispan.setAttribute("class", "result-pane-config"); var ic = document.createElement("i"); ispan.appendChild(ic); configspan.appendChild(ispan); var self = this; function showQueryConfig(){ configspan.title="Click to Hide View Configuration"; ic.setAttribute("class", "fas fa fa-times-circle"); if(configspan.nextSibling){ self.container.insertBefore(ipdom, configspan.nextSibling); if(self.input.snippet.value) self.input.stylizeSnippet(); } else{ self.container.appendChild(ipdom); if(self.input.snippet.value) self.input.stylizeSnippet(); } } function hideQueryConfig(){ configspan.title="Click to View Configuration"; ic.setAttribute("class", "terminus-result-icons terminus-result-view-icon " + self.getViewConfigIconClass()); self.container.removeChild(ipdom); } ispan.addEventListener("click", () => { if(this.showingQuery) hideQueryConfig(); else showQueryConfig(); this.showingQuery = !this.showingQuery; }); showQueryConfig(); if(this.showConfig == "icon") hideQueryConfig(); } if(this.changeViewType){ cvicons = this.getViewTypeIconDOM(ipdom); if(cvicons) configspan.prepend(cvicons); } return this.container; } ResultPane.prototype.getViewConfigIconClass = function(){ if(this.changeViewType && this.viewers.length > 1){ return "fas fa fa-vial"; } if(this.viewers[this.currentViewer].icon){ return this.viewers[this.currentViewer].icon; } var def = this.getDefaultViewerIcon(this.viewers[this.currentViewer]); return def.icon; } ResultPane.prototype.getViewTypeIconDOM = function(sp, ipdom){ var bsp = document.createElement('span'); bsp.setAttribute('class', 'terminus-result-icons'); if(this.viewers.length > 1){ for(var i = 0; i<this.viewers.length; i++){ var isp = this.getIconForViewer(this.viewers[i], i, bsp); bsp.appendChild(isp); } } return bsp; } ResultPane.prototype.changeViewerType = function(viewer, index){ this.currentViewer = index; this.config = viewer; if(this.input){ this.input.setQuery(viewer); this.input.submit(this.input.qObj); } else { this.updateView(viewer); } } ResultPane.prototype.getDefaultViewerIcon = function(viewer){ var view_types = { table: {label: "Table", icon: "fa fa-table"}, graph: {label: "Graph", icon: "fas fa-code-branch"}, chooser: {label: "Drop-down List", icon: "fas fa-caret-down"}, stream: {label: "Result Stream", icon: "fa fa-list"} } return view_types[viewer.type]; } ResultPane.prototype.getIconForViewer = function(viewer, index, container){ var isp = document.createElement('span'); var icon = document.createElement("i"); var def = this.getDefaultViewerIcon(viewer); icon.title = (viewer.label) ? viewer.label : def.label; var ic = (viewer.icon ? viewer.icon : def.icon); icon.setAttribute("class", ic); icon.classList.add('terminus-result-view-icon'); //icon.classList.add('circle-icon'); isp.appendChild(icon); if(this.currentViewer == index){ isp.setAttribute("class", "result-icon-selected selected terminus-result-selected"); icon.classList.add('terminus-view-selected'); } else { isp.setAttribute("class", "result-icon-selectable selectable"); isp.addEventListener('mouseover', function(){ this.style.cursor = "pointer"; }); } isp.addEventListener("click", () => { this.changeViewerType(viewer, index); HTMLHelper.removeChildren(container); for(var i = 0; i<this.viewers.length; i++){ var isp = this.getIconForViewer(this.viewers[i], i, container); container.appendChild(isp); } }); return isp; } ResultPane.prototype.createInput = function(mode){ let input = new TerminusCodeSnippet("rule", mode); if(this.config){ input.setQuery(this.config); } var self = this; input.submit = function(config){ self.updateView(config); }; return input; } ResultPane.prototype.setResult = function(wres){ this.result = wres; } ResultPane.prototype.clearResult = function(){ this.result = false; HTMLHelper.removeChildren(this.resultDOM); } ResultPane.prototype.updateResult = function(wres){ this.result = wres; HTMLHelper.removeChildren(this.resultDOM); this.resultDOM.appendChild(this.getResultDOM()); } ResultPane.prototype.updateView = function(config){ this.config = config; HTMLHelper.removeChildren(this.resultDOM); if(this.result){ this.resultDOM.appendChild(this.getResultDOM()); } } ResultPane.prototype.getResultDOM = function(){ let span = document.createElement("span"); span.setAttribute("class", "terminus-query-results"); let viewer = this.config.create(this.client); viewer.datatypes = new DatatypeRenderers(); Datatypes.initialiseDataRenderers(viewer.datatypes); var self = this; viewer.notify = function(r){ self.qp.updateResult(r); } this.result.first(); viewer.setResult(this.result); var html_renderer = this.getRenderer(); span.appendChild(html_renderer.render(viewer)); return span; } module.exports = ResultPane; <file_sep>/cypress/integration/tests/test_4.3.spec.js // create documents context('create document <NAME>', () => { beforeEach(() => { //connect to server and db cy.visit('http://localhost:6363/dashboard'); cy.get('#terminus-content-viewer') .find('table tbody tr td p') .contains('database_e2e_test') .click(); }) it('create documents', () => { cy.get('.terminus-db-controller') .find('a') .contains('Document') .click().then(() => { cy.wait(2000); cy.get('.terminus-create-doc') .get('span[class="terminus-class-chooser"]') .find('select') .select('Person').then(() => { cy.wait(1000); // input id cy.get('#terminus-content-viewer') .find('input[class="terminus-object-id-input" ]') .focus().type('doc:JackieChan'); // input member of cy.get('#terminus-content-viewer') .find('div[data-property="tcs:member_of"]') .find('input[type="text"]') .focus().type('doc:KarateGroup'); cy.wait(1000); // input Label cy.get('#terminus-content-viewer') .find('div[data-property="rdfs:label"]') .find('input[type="text"]') .focus().type('<NAME>'); cy.wait(1000); // input comment cy.get('#terminus-content-viewer') .find('div[data-property="rdfs:comment"]') .find('textarea') .focus().type('Creating a person <NAME>'); cy.wait(1000); // input fb cy.get('#terminus-content-viewer') .find('div[data-property="tcs:facebook_page"]') .find('input[type="text"]') .focus().type('https://facebook/JackieChan.555'); cy.wait(1000); // hit save cy.get('#terminus-content-viewer') .find('button') .contains('Save') .click().then(() => { alert('createDocument Person <NAME> success'); }) }) }) }) // create document }) <file_sep>/src/html/chooser/SimpleChooser.js function SimpleChooser(){} SimpleChooser.prototype.options = function(options){ this.options = options; return this; } SimpleChooser.prototype.render = function(chooser){ if(chooser) this.chooser = chooser; if(this.chooser.config.show_empty() == false && this.chooser.count() < 1) return false; var ccdom = document.createElement("span"); ccdom.setAttribute("class", "woql-chooser"); var ccsel = document.createElement("select"); ccsel.setAttribute("class", " woql-chooser"); var self = this; ccsel.addEventListener("change", function(){ self.chooser.set(this.value); }); var opts = []; if(this.chooser.config.show_empty()){ opts.push(this.getEmptyOption()) } this.chooser.first(); while(choice = this.chooser.next()){ var opt = this.createOptionFromChoice(choice); opts.push(opt); } for(var i = 0; i<opts.length; i++){ ccsel.appendChild(opts[i]); } ccdom.appendChild(ccsel); return ccdom; } SimpleChooser.prototype.getEmptyOption = function(){ var choice = { id: "", label: this.chooser.config.show_empty()}; return this.createOptionFromChoice(choice); } SimpleChooser.prototype.createOptionFromChoice = function(choice){ var opt = document.createElement("option"); opt.setAttribute("class", "terminus-woql-chooser-choice"); opt.value = choice.id; if(choice.selected) opt.selected = true; if(typeof choice.label == "string"){ opt.appendChild(document.createTextNode(choice.label)); } else if(choice.label){ opt.appendChild(choice.label); } if(choice.title){ opt.setAttribute("title", choice.title); } return opt; } module.exports = SimpleChooser;<file_sep>/src/index.js const TerminusUI = require('./TerminusUI'); const TerminusViewer =require('./html/TerminusViewer') module.exports={TerminusUI:TerminusUI, TerminusViewer:TerminusViewer} <file_sep>/src/html/datatypes/CoordinateEditor.js function HTMLCoordinateEditor(options){ this.inputs = []; } HTMLCoordinateEditor.prototype.getInputDOMs = function(lat, long, change){ var latdom = document.createElement("input"); latdom.setAttribute("type", "text"); latdom.value = lat; var longdom = document.createElement("input"); longdom.setAttribute("type", "text"); longdom.value = long; latdom.addEventListener("change", change); longdom.addEventListener("change", change); return [latdom, longdom]; } HTMLCoordinateEditor.prototype.getLatLongDOM = function(lat, long, ty, index, parent){ var lldom = document.createElement("span"); lldom.setAttribute("class", "terminus-lat-long"); var firstcol = document.createElement("span"); firstcol.setAttribute("class", "terminus-lat-long-col"); lldom.appendChild(firstcol); if(index > 2 || (ty == "xdd:coordinatePolyline" && index > 1)){ var delbut = document.createElement("button"); delbut.setAttribute("class", "delete-coordinate"); delbut.appendChild(document.createTextNode("Remove")); delbut.addEventListener("click", function(){ long.value = ""; lat.value = ""; parent.removeChild(lldom); }); firstcol.appendChild(delbut); } lldom.appendChild(document.createTextNode("Latitude: ")); lldom.appendChild(lat); lldom.appendChild(document.createTextNode(" °" + " ")); lldom.appendChild(document.createTextNode(" Longitude: ")); lldom.appendChild(long); lldom.appendChild(document.createTextNode(" ° " )); return lldom; } HTMLCoordinateEditor.prototype.renderFrame = function(frame, dataviewer){ var value = frame.get(); var input = document.createElement("span"); input.setAttribute('class', "terminus-literal-value terminus-literal-coordinate"); input.setAttribute('data-value', value); try { var parsed = (value ? JSON.parse(value) : false); } catch(e){ this.error = this.type + " failed to parse as json", e.toString(); var parsed = false; } var self = this; var updateValueFromForm = function(){ var vals = []; for(var i = 0; i<self.inputs.length; i++){ if(self.inputs[i][0].value && self.inputs[i][1].value){ var val = "[" + self.inputs[i][0].value + "," + self.inputs[i][1].value + "]"; vals.push(val); } } if(vals.length == 0){ frame.set(""); } else if(this.type == "xdd:coordinate"){ frame.set(vals[0]); } else { var op = "["; for(var i = 0; i<vals.length; i++){ op += vals[i]; if(i+1 < vals.length) op += ","; } op += "]"; frame.set(op); } }; if(!parsed){ if(this.type == "xdd:coordinate") parsed = ["",""]; else { parsed = [["",""],["",""]]; if(this.type == "xdd:coordinatePolygon") parsed.push(["",""]); } } if(this.type == "xdd:coordinate"){ parsed = [parsed]; } for(var i = 0; i < parsed.length; i++){ this.inputs.push(this.getInputDOMs(parsed[i][0], parsed[i][1], updateValueFromForm)) } var lldoms = document.createElement("span"); for(var i = 0; i < this.inputs.length; i++){ var lldom = this.getLatLongDOM(this.inputs[i][0], this.inputs[i][1], this.type, i, lldoms); lldoms.appendChild(lldom); } input.appendChild(lldoms); var self = this; if(this.type != "xdd:coordinate"){ var butspan = document.createElement("span"); butspan.setAttribute("class", "terminus-add-coordinate") var addbut = document.createElement("button"); addbut.setAttribute("class", "terminus-add-coordinate"); addbut.appendChild(document.createTextNode("Add")); addbut.addEventListener("click", function(){ var ipdoms = self.getInputDOMs("", "", updateValueFromForm); var lldom = self.getLatLongDOM(ipdoms[0], ipdoms[1], this.type, self.inputs.length, lldoms); lldoms.appendChild(lldom); self.inputs.push(ipdoms); }); butspan.appendChild(addbut); input.appendChild(butspan); } return input; } module.exports={HTMLCoordinateEditor}<file_sep>/src/plugins/datatables.terminus.js const TerminusClient = require('@terminusdb/terminus-client'); const HTMLHelper = require('../html/HTMLHelper'); const UTILS= require('../Utils') /*** client side processing ***/ function CspDatatables(ui){ this.ui = ui; } CspDatatables.prototype.convertToDatatable = function(tab){ var dt = this; var table = jQuery(tab).DataTable({ searching : false, pageLength: 25, lengthMenu: [10, 25, 50, 75, 100], paging : true, select : true, initComplete: function(settings) { var ict =settings.oInstance.api(); ict.$('td').each(function(){ this.setAttribute('title', $(this).html()) })}, columnDefs:[{targets:'_all',className:"truncate"}], createdRow: function(row) { var td = $(row).find(".truncate"); td.attr("title", td.html());} }); //jQuery(tab) // on click of row connect to db, on click of 5th column delete db jQuery(tab, 'tbody').on('click', 'td', function(){ if(table.cell(this).index().column == 5){ var dbInfo = table.row(jQuery(this).parents('tr')).data(); var dbId = UTILS.extractValueFromCell(dbInfo[0]); dt.ui.deleteDatabase(dbId); return; } else dt.ui.showDBMainPage(); }); // on click tab.setAttribute('class' , 'stripe dataTable terminus-db-size'); tab.setAttribute('cellpadding', '1'); tab.setAttribute('cellspacing', '0'); tab.setAttribute('border' , '0'); return tab; } CspDatatables.prototype.draw = function(dtResult){ return(this.convertToDatatable(dtResult)); } /*** server side processing ***/ function Datatables(wResViewer, qPage){ this.wrViewer = wResViewer; this.wQuery = wResViewer.wQuery; this.ui = wResViewer.ui; this.qPage = qPage; this.currDTSettings = wResViewer.settings; } /* query: new woqlquery with current pagination changes pageInfo: current drawCallBack page change info resultDOM: result dom on veiwer page */ Datatables.prototype.executeQuery = function(qObj, pageInfo, resultDOM){ var self = this; // return this.wQuery.execute(query) return qObj.execute(this.ui.client) .then(function(result){ var dtResult = {}; var wqRes = new TerminusClient.WOQLResult(result, qObj); dtResult = self.wrViewer.formatResultsForDatatableDisplay(result.bindings, pageInfo) return dtResult.data; }) .catch(function(err){ console.error(err); self.ui.showError(err); }); } /* get query string based on datatable pagination and current query */ /*Datatables.prototype.getQueryOnPagination = function(wq, settings){ switch(settings.query){ case 'Show_All_Documents': return wq.getAllDocumentQuery(null, settings.pageLength, settings.start); break; case 'Show_All_Data': return wq.getEverythingQuery(null, settings.pageLength, settings.start); break; case 'Show_All_Schema_Elements': return wq.getElementMetaDataQuery(null, settings.pageLength, settings.start); break; case 'Show_Document_Classes': var sqp = wq.getConcreteDocumentClassPattern("Class"); return wq.getClassMetaDataQuery(sqp); break; case 'Show_All_Properties': return wq.getPropertyListQuery(null, settings.pageLength, settings.start); break; case 'Show_All_Classes': return wq.getClassMetaDataQuery(null, settings.pageLength, settings.start); break; case 'Show_Data_Class': return wq.getDataOfChosenClassQuery(settings.chosenValue, settings.pageLength, settings.start); break; case 'Show_Property_Class': return wq.getDataOfChosenPropertyQuery(settings.chosenValue, settings.pageLength, settings.start); break; case 'Show_Document_Info_by_Id': return wq.getDocumentQuery(settings.chosenValue, settings.pageLength, settings.start); break; case 'Show_All_Document_classes': return wq.getClassesQuery(settings.pageLength, settings.start); break; default: console.log('Invalid woql option passed'); break; } } */ /* pageInfo: current drawCallBack page change info */ Datatables.prototype.generateNewQueryOnPageChange = function(pageInfo){ if(this.qPage) UTILS.deleteStylizedEditor(this.ui, pageInfo.qTextDom); var qObj = UTILS.getCurrentWoqlQueryObject(null, pageInfo); //var query = this.getQueryOnPagination(this.wQuery, pageInfo) if(this.qPage) { if(pageInfo.queryMode.value == 'woql') pageInfo.qTextDom.value = JSON.stringify(qObj.prettyPrint(), undefined, 2); else pageInfo.qTextDom.value = JSON.stringify(qObj, undefined, 2); UTILS.stylizeEditor(this.ui, pageInfo.qTextDom, 'query', 'javascript'); } //return query; return qObj; } /* dt: Datatable reference len : current number of records to display */ Datatables.prototype.getCallbackSettings = function(dt, dtAPIChangeSettings){ var pageInfo = {}; pageInfo.pageLength = dtAPIChangeSettings._iDisplayLength; pageInfo.start = dtAPIChangeSettings._iDisplayStart; pageInfo.draw = dtAPIChangeSettings.iDraw; pageInfo.qTextDom = dt.qTextDom; pageInfo.queryMode = dt.queryMode; if(this.qPage) pageInfo.query = dt.query; else pageInfo.query = 'Show_All_Document_classes'; pageInfo.chosenValue = dt.chosenValue; return pageInfo; } /* tab: datatable table dom settings : settings from woql txt generator resultDOM: result dom of viewer */ Datatables.prototype.setUp = function(tab, settings, resultDOM){ // delete previous datatable HTMLHelper.removeChildren(this.dtdom); this.dtdom = document.createElement('div'); this.dtdom.appendChild(tab); resultDOM.appendChild(this.dtdom); // saving query text box dom to change limit value on change of datatable page length this.qTextDom = settings.qTextDom; this.query = settings.query; this.chosenValue = settings.chosenValue; this.queryMode = settings.queryMode; } // update datatables settings so it can be reused in WOQLTextboxGenerator to re write query in woql/ jsonld Datatables.prototype.updateCurrDTSettings = function(pageInfo){ this.currDTSettings.pageLength = pageInfo.pageLength; this.currDTSettings.start = pageInfo.start; } Datatables.prototype.getNewDataOnChange = function(drawnTab, aSettings, resultDOM){ var pageInfo = this.getCallbackSettings(this, aSettings); this.updateCurrDTSettings(pageInfo); // var query = this.generateNewQueryOnPageChange(pageInfo); var qObj = this.generateNewQueryOnPageChange(pageInfo); return this.executeQuery(qObj, pageInfo, resultDOM); //return this.executeQuery(query, pageInfo, resultDOM); //return dtResult.result.data; } Datatables.prototype.getDataFromServer = function(dtResult, resultDOM){ var dt = this; var tab = dtResult.tab; this.setUp(tab, this.wrViewer.settings, resultDOM); // initialize datatables var table = jQuery(tab).DataTable({ searching : false, pageLength : dt.wrViewer.settings.pageLength, serverSide : true, processing : true, lengthMenu : [25, 50, 75, 100], dom : 'RBlftip', columns : dtResult.result.columns, paging : true, select : true, autoWidth : true, ajax : function (data, callback, settings) { if(Object.entries(dtResult.result.data).length > 0){ // first draw is loaded var res = dtResult.result.data; dtResult.result.data = {}; callback(res); } else{ dt.getNewDataOnChange(this, settings, resultDOM) .then(function(result){ callback(result); }) } }, buttons : [{ extend: 'copy', text: 'Copy to clipboard' }, { extend: 'excel', text: 'Export to Excel' }], columnDefs : [{ targets:'_all', className:"truncate"}], createdRow : function(row){ var td = $(row).find(".truncate"); td.attr("title", td.html());}, scrollX : true }); //jQuery(tab) // on click of doc jQuery(tab, 'tbody').on('click', 'td', function(){ if(table.cell(this).data){ if(this.innerText.substring(0, 4) == "doc:"){ if(dt.wrViewer.result.ui) { dt.wrViewer.result.ui.showDocument(this.innerText); dt.wrViewer.result.ui.redraw(); dt.wrViewer.selectDocumentNavBar(dt.ui); } } } }); // on click //styling tab.setAttribute('class' , 'stripe dataTable'); tab.setAttribute('style' , 'margin: 0!important'); tab.setAttribute('cellpadding', '1'); tab.setAttribute('cellspacing', '1'); tab.setAttribute('border' , '0'); return tab; } /* serverside: true or false */ Datatables.prototype.draw = function(dtResult, resultDOM){ return(this.getDataFromServer(dtResult, resultDOM)); } module.exports={Datatables, CspDatatables} <file_sep>/cypress/integration/tests/test_0.spec.js // to check server connect context('check connection', () => { beforeEach(() => { cy.visit('http://localhost:6363/dashboard'); }) it('Connect to a Server', () => { cy.wait(2000); cy.get('#terminus-control-panel') .find('a') .contains('Change Server') .click().then(() => { cy.wait(1000); // enter server url cy.get('#terminus-content-viewer') .find('input[placeholder="Terminus DB URL"]') .focus().type("http://192.168.3.11:6363"); // enter key cy.get('#terminus-content-viewer') .find('input[placeholder="Server API Key"]') .focus().type("root"); cy.wait(1000); // click on connect button cy.get('#terminus-content-viewer') .find('button').click().then(() => { alert('connect success'); }) }) }) // connect to a server }) <file_sep>/cypress/integration/tests/test_4.2.spec.js // create documents context('create document Bruce Lee', () => { beforeEach(() => { //connect to server and db cy.visit('http://localhost:6363/dashboard'); cy.get('#terminus-content-viewer') .find('table tbody tr td p') .contains('database_e2e_test') .click(); }) it('create documents', () => { cy.get('.terminus-db-controller') .find('a') .contains('Document') .click().then(() => { cy.wait(2000); cy.get('.terminus-create-doc') .get('span[class="terminus-class-chooser"]') .find('select') .select('Person').then(() => { cy.wait(1000); // input id cy.get('#terminus-content-viewer') .find('input[class="terminus-object-id-input" ]') .focus().type('doc:BruceLee'); // input member of cy.get('#terminus-content-viewer') .find('div[data-property="tcs:member_of"]') .find('input[type="text"]') .focus().type('doc:KarateGroup'); cy.wait(1000); // input Label cy.get('#terminus-content-viewer') .find('div[data-property="rdfs:label"]') .find('input[type="text"]') .focus().type('<NAME>'); cy.wait(1000); // input comment cy.get('#terminus-content-viewer') .find('div[data-property="rdfs:comment"]') .find('textarea') .focus().type('Creating a person <NAME>'); cy.wait(1000); // input fb cy.get('#terminus-content-viewer') .find('div[data-property="tcs:facebook_page"]') .find('input[type="text"]') .focus().type('https://facebook/BruceLee.555'); cy.wait(1000); // input email cy.get('#terminus-content-viewer') .find('div[data-property="tcs:email_address"]') .find('input[type="text"]') .focus().type('<EMAIL>'); cy.wait(3000); // hit save cy.get('#terminus-content-viewer') .find('button') .contains('Save') .click().then(() => { alert('createDocument Person <NAME> success'); }) }) }) }) // create document })
7c2ffa512508f8ca53cd5d85d6f4ef5bc64c0caf
[ "JavaScript", "Markdown", "Shell" ]
47
Shell
terminusdb/terminus-dashboard
f578c3004cbea315fc8f41c789cf57f59db01c39
8ccaea963bdec1ebf255ae7bab217f25005a9f03
refs/heads/master
<file_sep>#!/usr/bin/env python from random import randint import SimpleMFRC522 import time import subprocess import os import logging import random import glob import RPi.GPIO as GPIO def playsound(video, loop = 0): global myprocess global directory logging.debug('linux: omxplayer %s' % video) proccount = isplaying() if proccount == 1 or proccount == 0: logging.debug('No videos playing, so play video') else: logging.debug('Video already playing, so quit current video, then play') myprocess.communicate(b"q") if loop == 0: myprocess = subprocess.Popen(['omxplayer',directory + video],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE, close_fds=True) else: myprocess = subprocess.Popen(['omxplayer','--loop',directory + video],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE, close_fds=True) time.sleep(3) def isplaying(): """check if omxplayer is running if the value returned is a 1 or 0, omxplayer is NOT playing a video if the value returned is a 2, omxplayer is playing a video""" processname = 'omxplayer' tmp = os.popen("ps -Af").read() proccount = tmp.count(processname) return proccount #program start logging.basicConfig(level=logging.DEBUG) reader = SimpleMFRC522.SimpleMFRC522() directory = '/home/pi/sounds/' print("Begin Player") try: while True: proccount = isplaying() if proccount == 1 or proccount == 0: current_sound_id = long(10) start_time = time.time() logging.debug("Waiting for ID to be scanned") id, sound_name = reader.read() logging.debug("ID: %s" % id) logging.debug("Sound Name: %s" % sound_name) sound_name = sound_name.rstrip() if current_sound_id != id: logging.debug('New sound') #this is a check in place to prevent omxplayer from restarting video if ID is left over the reader. #better to use id than sound_name as there can be a problem reading sound_name occasionally if sound_name.endswith(('.mp3')): current_sound_id = id #we set this here instead of above bc it may mess up on first read logging.debug("playing: omxplayer %s" % sound_name) playsound(sound_name) else: end_time = time.time() elapsed_time = end_time - start_time proccount = isplaying() if proccount != 1 and proccount != 0: if elapsed_time > 0.6: #pause, unpause sound logging.debug('Pausing sound - or - Playing sound') myprocess.stdin.write("p") except KeyboardInterrupt: GPIO.cleanup() print("\nAll Done") <file_sep># Project leerjaar 3 * Play sounds/videos with NFC RFID RC522 Raspberry Pi Oorspronkelijk een video player, hier is het iets aangepast zodat ik mp3 bestanden kan afspelen. Videos werken ook. wat ben je nodig: * Raspberry Pi 3 * RFID RC522 Kit * RFID 13.56 MHz Cards ### Hieronder staan sites met informatie hoe je je RaspberryPi gebruikt met RC522 NFC reader: * [How to setup a Raspberry Pi RFID RC522 Chip - Pi My Life Up](https://pimylifeup.com/raspberry-pi-rfid-rc522/) * [RFID (RC522) - piddlerintheroot | piddlerintheroot](https://www.piddlerintheroot.com/rfid-rc522-raspberry-pi/) ### Belangrijk!!!! Je moet je NFC tags (kaarten) wel beschrijven met ```write.py``` en niet met een telefoon, dan wordt de kaart niet goed beschreven en heb je kans dat de kaart niet meer werkt. ### SoundPlay.py: * Hieronder staan een paar belangrijke punten over het bestand SoundPlay.py om het te begrijpen. De lijn hieronder geeft aan waar de muziek/video fragmenten staan, deze kan je uiteraard aanpassen. ``` directory = '/home/pi/sounds/' ``` Hieronder zie je ```id``` en ``` sound_name ```. ```id``` is het id van de NFC tag(kaart) en ```sound_name``` is de naam van het fragment, die je op de kaart gezet hebt met write.py ``` id, sound_name = reader.read() ``` Hieronder wordt sound_name gebruikt en wordt er met ```.rstrip()``` gezorgt dat alle characters achter de ```sound_name``` worden weggehaald(bvb spaties). ``` sound_name = sound_name.rstrip() ``` Hieronder zie je de ```.endswith``` dit zorgt ervoor dat je alleen mp3 bestanden kan aanroepen. je kan hier uiteraard ook mp4 enz. aan toevoegen. ``` if sound_name.endswith(('.mp3')): current_sound_id = id #we set this here instead of above bc it may mess up on first read logging.debug("playing: omxplayer %s" % sound_name) playsound(sound_name) ``` ### De Raspberry Pi 3 heeft een video/muziek player ingebouwd die werkt via de terminal : OMXPlayer * [OMXPlayer: An accelerated command line media player - Raspberry Pi Documentation](https://www.raspberrypi.org/documentation/raspbian/applications/omxplayer.md) ### Bestanden * SoundPlay.py - Dit bestand scant de NFC tag en speeld het bestand af (Video is ook mogelijk) * read.py - Testen van NFC tags. * write.py - schrijf naam van bestand op NFC tag. Voorbeeld: sound1.mp3 Je kan de verschillende bestanden uitvoeren door: ``` sudo python SoundPlay.py sudo python read.py sudo python write.py ``` Ook kunnen de fragmenten op pauze gezet worden. Als je een tag leest en dus een fragment afspeeld, kan je daarna nog een keer dezelfde tag lezen. Dan wordt het fragment gepauzeerd. Scan je het voor de derde keer dan gaat het weer verder waar je was gebleven **Code automatisch uitvoeren** Met het bestand /etc/rc.local kan je, doormiddel van toevoegen van: * /ect/rc.local: ``` python /home/pi/projectmap/SoundPlay.py ``` Automatisch laten afspelen. [rc.local - Raspberry Pi Documentation](https://www.raspberrypi.org/documentation/linux/usage/rc-local.md)
af727dee533a137d812adb20e8924994889fac09
[ "Markdown", "Python" ]
2
Python
deltionJP/rfid-raspberry-sounds
97456b7d59c2c7681044d8b9c6191ace80201fbf
cddfed0a24a301da3fe0e39accad5444275c084a
refs/heads/master
<repo_name>Realityloop/vue-drupal-entity<file_sep>/src/components/DrupalEntityField/index.js import DrupalEntityField from './DrupalEntityField.vue' export default DrupalEntityField <file_sep>/src/components/DrupalEntity/index.js import DrupalEntity from './DrupalEntity.vue' export default DrupalEntity <file_sep>/README.md # Vue \<drupal-entity /> Render Drupal Entities and fields with Drupal JSON:API Entities schema support. _This is a proof of concept, documentation is incomplete._ ## Installation `$ npm install vue-drupal-entity ## Usage ```jsx <template> <drupal-entity :entity="entity" :schema="schema" /> </template> <script> import Vue from 'vue' import VueDrupalEntity from 'vue-drupal-entity' Vue.use(VueDrupalEntity) export default { data: () => ({ entity: { ... }, schema: { ... } }) } </script> ```
836f405ca0dd78c126e9cd62361a74256c11f38d
[ "JavaScript", "Markdown" ]
3
JavaScript
Realityloop/vue-drupal-entity
0e43d8697091dbe206576b660deb2575c116e3db
51146bf2b6444fc83b6b33e7ef083a1ce7ff1260
refs/heads/master
<file_sep>jQuery(document).ready(function() { // Hide everything mentioning certain key words from a certain user. var hider = function() { var el = jQuery('a[href="/102780726906835902473"]').parentsUntil('div.md.gi') el.each(function() { var t = jQuery(this) if(/Hung out|HANGOUT|eBay/i.test(t.text())) t.hide(); }); } setInterval(hider, 1000); });
dd11590a93cd1581f5d141d5168c07c4bb182e2e
[ "JavaScript" ]
1
JavaScript
aredridel/.js
90070a0099ef8452d6a330a6d0bcb6d7a9c9acbc
8bb92c5b640e17aca314ae9e81ba27a6219467f4
refs/heads/master
<file_sep>// This file is distributed under the MIT license. // See the LICENSE file for details. #pragma once #include <vkt/config.h> #include <cstddef> #if VKT_HAVE_CUDA #include <cuda_runtime_api.h> #endif #include <vkt/Memory.hpp> #include "macros.hpp" namespace vkt { void Allocate_cuda(void** ptr, std::size_t size) { #if VKT_HAVE_CUDA VKT_CUDA_SAFE_CALL__(cudaMalloc(ptr, size)); #endif } void Free_cuda(void* ptr) { #if VKT_HAVE_CUDA VKT_CUDA_SAFE_CALL__(cudaFree(ptr)); #endif } } // vkt <file_sep>#include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <vkt/InputStream.h> #include <vkt/LookupTable.h> #include <vkt/RawFile.h> #include <vkt/Render.h> #include <vkt/StructuredVolume.h> int main(int argc, char** argv) { vktRawFile file; vktVec3i_t dims; uint16_t bpv; vktStructuredVolume volume; vktInputStream is; float rgba[20]; vktLookupTable lut; vktRenderState_t renderState; if (argc < 2) { fprintf(stderr, "Usage: %s file.raw\n", argv[0]); return EXIT_FAILURE; } vktRawFileCreateS(&file, argv[1], "r"); dims = vktRawFileGetDims3iv(file); if (dims.x * dims.y * dims.z < 1) { fprintf(stderr, "%s", "Cannot parse dimensions from file name\n"); return EXIT_FAILURE; } bpv = vktRawFileGetBytesPerVoxel(file); if (bpv == 0) { fprintf(stderr, "%s", "Cannot parse bytes per voxel from file name, guessing 1...\n"); bpv = 1; } vktStructuredVolumeCreate(&volume, dims.x, dims.y, dims.z, bpv, 1.f, 1.f, 1.f, 0.f, 1.f); vktInputStreamCreateF(&is, file); vktInputStreamReadSV(is, volume); rgba[ 0] = 1.f; rgba[ 1] = 1.f; rgba[ 2] = 1.f; rgba[ 3] = .005f; rgba[ 4] = 0.f; rgba[ 5] = .1f; rgba[ 6] = .1f; rgba[ 7] = .25f; rgba[ 8] = .5f; rgba[ 9] = .5f; rgba[10] = .7f; rgba[11] = .5f; rgba[12] = .7f; rgba[13] = .7f; rgba[14] = .07f; rgba[15] = .75f; rgba[16] = 1.f; rgba[17] = .3f; rgba[18] = .3f; rgba[19] = 1.f; vktLookupTableCreate(&lut,5,1,1,vktColorFormatRGBA32F); vktLookupTableSetData(lut,(uint8_t*)rgba); vktRenderStateDefaultInit(&renderState); //renderState.renderAlgo = vktRenderAlgoRayMarching; //renderState.renderAlgo = vktRenderAlgoImplicitIso; renderState.renderAlgo = vktRenderAlgoMultiScattering; renderState.rgbaLookupTable = vktLookupTableGetResourceHandle(lut); vktRenderSV(volume, renderState, NULL); vktLookupTableDestroy(lut); vktInputStreamDestroy(is); vktStructuredVolumeDestroy(volume); vktRawFileDestroy(file); } <file_sep>// This file is distributed under the MIT license. // See the LICENSE file for details. #pragma once struct vktLookupTable_impl; struct vktRawFile_impl; struct vktInputStream_impl; struct vktStructuredVolume_impl; typedef struct vktLookupTable_impl* vktLookupTable; typedef struct vktRawFile_impl* vktRawFile; typedef struct vktInputStream_impl* vktInputStream; typedef struct vktStructuredVolume_impl* vktStructuredVolume; <file_sep>// This file is distributed under the MIT license. // See the LICENSE file for details. #pragma once #include "common.h" #ifdef __cplusplus extern "C" { #endif struct vktCudaTimer_impl; typedef struct vktCudaTimer_impl* vktCudaTimer; VKTAPI void vktCudaTimerCreate(vktCudaTimer* timer); VKTAPI void vktCudaTimerDestroy(vktCudaTimer timer); VKTAPI void vktCudaTimerReset(vktCudaTimer timer); VKTAPI double vktCudaTimerGetElapsedSeconds(vktCudaTimer timer); #ifdef __cplusplus } #endif <file_sep>// This file is distributed under the MIT license. // See the LICENSE file for details. #pragma once #include <GL/glew.h> #include <vkt/LookupTable.hpp> #include <vkt/ManagedResource.hpp> namespace vkt { class TransfuncEditor { public: ~TransfuncEditor(); //! Set a user-provided LUT that a copy is created from void setLookupTableResource(ResourceHandle handle); //! Get an updated LUT that is a copied of the user-provided one LookupTable* getUpdatedLookupTable() const; //! Indicates that the internal copy of the LUT has changed bool updated() const; //! Render with ImGui void show(); private: // Local LUT copy LookupTable* rgbaLookupTable_ = nullptr; // User-provided LUT LookupTable* userLookupTable_ = nullptr; // Flag indicating that texture needs to be regenerated bool lutChanged_ = false; // RGB texture GLuint texture_ = GLuint(-1); // Drawing canvas size Vec2i canvasSize_ = { 300, 150 }; // Mouse state for drawing struct MouseEvent { enum Type { PassiveMotion, Motion, Press, Release }; enum Button { Left, Middle, Right, None }; Vec2i pos = { 0, 0 }; int button = None; Type type = Motion; }; // The last mouse event MouseEvent lastEvent_; // Drawing in progress bool drawing_ = false; // Raster LUT to image and upload with OpenGL void rasterTexture(); // Generate mouse event when mouse hovered over rect MouseEvent generateMouseEvent(); // Handle mouse event void handleMouseEvent(MouseEvent const& event); }; } // vkt <file_sep>// This file is distributed under the MIT license. // See the LICENSE file for details. #pragma once #include <cstddef> #include <cstdint> #include <vkt/ManagedBuffer.hpp> #include "linalg.hpp" namespace vkt { class StructuredVolume : public ManagedBuffer<uint8_t> { public: constexpr static uint16_t GetMaxBytesPerVoxel() { return 8; } public: StructuredVolume(); StructuredVolume( int32_t dimX, int32_t dimY, int32_t dimZ, uint16_t bytesPerVoxel, float distX = 1.f, float distY = 1.f, float distZ = 1.f, float mappingLo = 0.f, float mappingHi = 1.f ); StructuredVolume(StructuredVolume& rhs) = default; StructuredVolume(StructuredVolume&& rhs) = default; StructuredVolume& operator=(StructuredVolume& rhs) = default; StructuredVolume& operator=(StructuredVolume&& rhs) = default; void setDims(int32_t dimX, int32_t dimY, int32_t dimZ); void getDims(int32_t& dimX, int32_t& dimY, int32_t& dimZ); void setDims(Vec3i dims); Vec3i getDims() const; void setBytesPerVoxel(uint16_t bpv); uint16_t getBytesPerVoxel() const; void setDist(float distX, float distY, float distZ); void getDist(float& distX, float& distY, float& distZ); void setDist(Vec3f dist); Vec3f getDist() const; void setVoxelMapping(float lo, float hi); void getVoxelMapping(float& lo, float& hi); void setVoxelMapping(Vec2f mapping); Vec2f getVoxelMapping() const; uint8_t* getData(); float sampleLinear(int32_t x, int32_t y, int32_t z); void setValue(int32_t x, int32_t y, int32_t z, float value); void getValue(int32_t x, int32_t y, int32_t z, float& value); float getValue(int32_t x, int32_t y, int32_t z); void setValue(Vec3i index, float value); void getValue(Vec3i index, float& value); float getValue(Vec3i index); void setBytes(int32_t x, int32_t y, int32_t z, uint8_t const* data); void getBytes(int32_t x, int32_t y, int32_t z, uint8_t* data); void setBytes(Vec3i index, uint8_t const* data); void getBytes(Vec3i index, uint8_t* data); std::size_t getSizeInBytes() const; private: Vec3i dims_; uint16_t bytesPerVoxel_; Vec3f dist_; Vec2f voxelMapping_; std::size_t linearIndex(int32_t x, int32_t y, int32_t z) const; std::size_t linearIndex(Vec3i index) const; }; } // vkt <file_sep> #include <vkt/config.h> #if VKT_HAVE_VIRVO #include <virvo/vvfileio.h> #include <virvo/vvvoldesc.h> #endif #include <vkt/VirvoFile.hpp> namespace vkt { struct VirvoFile::Impl { Impl(char const* fileName) #if VKT_HAVE_VIRVO : vd(fileName) #endif { } #if VKT_HAVE_VIRVO vvVolDesc vd; #endif bool loaded() const { return vd.vox[0] * vd.vox[1] * vd.vox[2] > 0; } bool load() { vvFileIO fileio; return fileio.loadVolumeData(&vd) == vvFileIO::OK; } std::size_t readOffset = 0; }; VirvoFile::VirvoFile(char const* fileName) : impl_(new Impl(fileName)) { } VirvoFile::~VirvoFile() { } std::size_t VirvoFile::read(char* buf, std::size_t len) { if (!impl_->loaded() && !impl_->load()) return 0; uint8_t* raw = impl_->vd.getRaw(); // TODO: error / bounds checking std::memcpy(buf, raw + impl_->readOffset, len); impl_->readOffset += len; return len; } bool VirvoFile::good() const { return true; // TODO (check if exists / can be created??) } Vec3i VirvoFile::getDims() { if (!impl_->loaded() && !impl_->load()) return { 0, 0, 0 }; return { (int)impl_->vd.vox[0], (int)impl_->vd.vox[1], (int)impl_->vd.vox[2] }; } uint16_t VirvoFile::getBytesPerVoxel() { if (!impl_->loaded() && !impl_->load()) return 0; return (uint16_t)impl_->vd.bpc; } } // vkt <file_sep>// This file is distributed under the MIT license. // See the LICENSE file for details. #include <cassert> #include <cmath> #include <cstdint> #include <vector> #include <imgui.h> #include "ColorFormatInfo.hpp" #include "TransfuncEditor.hpp" #include "linalg.hpp" static void enableBlendCB(ImDrawList const*, ImDrawCmd const*) { glEnable(GL_BLEND); } static void disableBlendCB(ImDrawList const*, ImDrawCmd const*) { glDisable(GL_BLEND); } namespace vkt { TransfuncEditor::~TransfuncEditor() { // TODO: cannot be sure we have a GL context here! glDeleteTextures(1, &texture_); delete rgbaLookupTable_; } void TransfuncEditor::setLookupTableResource(ResourceHandle handle) { lutChanged_ = true; userLookupTable_ = (LookupTable*)GetManagedResource(handle); } LookupTable* TransfuncEditor::getUpdatedLookupTable() const { return rgbaLookupTable_; } bool TransfuncEditor::updated() const { return lutChanged_; } void TransfuncEditor::show() { if (userLookupTable_ == nullptr) return; ImGui::Begin("TransfuncEditor"); rasterTexture(); ImGui::GetWindowDrawList()->AddCallback(disableBlendCB, nullptr); ImGui::ImageButton( (void*)(intptr_t)texture_, ImVec2(canvasSize_.x, canvasSize_.y), ImVec2(0, 0), ImVec2(1, 1), 0 // frame size = 0 ); MouseEvent event = generateMouseEvent(); handleMouseEvent(event); ImGui::GetWindowDrawList()->AddCallback(enableBlendCB, nullptr); ImGui::End(); } void TransfuncEditor::rasterTexture() { if (!lutChanged_) return; // TODO: maybe move to a function called by user? if (texture_ == GLuint(-1)) { glGenTextures(1, &texture_); glBindTexture(GL_TEXTURE_2D, texture_); } Vec3i dims = userLookupTable_->getDims(); ColorFormat format = userLookupTable_->getColorFormat(); if (dims.x >= 1 && dims.y == 1 && dims.z == 1 && format == ColorFormat::RGBA32F) { float* colors = nullptr; float* updated = nullptr; if (rgbaLookupTable_ == nullptr) { rgbaLookupTable_ = new LookupTable(canvasSize_.x, 1, 1, userLookupTable_->getColorFormat()); // The user-provided colors colors = (float*)userLookupTable_->getData(); // Updated colors updated = (float*)rgbaLookupTable_->getData(); // Lerp colors and alpha for (int i = 0; i < canvasSize_.x; ++i) { float indexf = i / (float)(canvasSize_.x - 1) * (dims.x - 1); int indexa = (int)indexf; int indexb = indexa + 1; Vec3f rgb1{ colors[4 * indexa], colors[4 * indexa + 1], colors[4 * indexa + 2] }; float alpha1 = colors[4 * indexa + 3]; Vec3f rgb2{ colors[4 * indexb], colors[4 * indexb + 1], colors[4 * indexb + 2] }; float alpha2 = colors[4 * indexb + 3]; float frac = indexf - indexa; Vec3f rgb = lerp(rgb1, rgb2, frac); float alpha = lerp(alpha1, alpha2, frac); updated[4 * i] = rgb.x; updated[4 * i + 1] = rgb.y; updated[4 * i + 2] = rgb.z; updated[4 * i + 3] = alpha; } } else { // The user-provided colors colors = (float*)userLookupTable_->getData(); // Updated colors updated = (float*)rgbaLookupTable_->getData(); } // Blend on the CPU (TODO: figure out how textures can be // blended with ImGui..) std::vector<Vec4f> rgba(canvasSize_.x * canvasSize_.y); for (int y = 0; y < canvasSize_.y; ++y) { for (int x = 0; x < canvasSize_.x; ++x) { Vec3f rgb{ updated[4 * x], updated[4 * x + 1], updated[4 * x + 2] }; float alpha = updated[4 * x + 3]; float grey = .9f; float a = ((canvasSize_.y - y - 1) / (float)canvasSize_.y) <= alpha ? .6f : 0.f; rgba[y * canvasSize_.x + x].x = (1 - a) * rgb.x + a * grey; rgba[y * canvasSize_.x + x].y = (1 - a) * rgb.y + a * grey; rgba[y * canvasSize_.x + x].z = (1 - a) * rgb.z + a * grey; rgba[y * canvasSize_.x + x].w = 1.f; } } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D( GL_TEXTURE_2D, 0, ColorFormatInfoTableGL[(int)format].internalFormat, canvasSize_.x, canvasSize_.y, 0, ColorFormatInfoTableGL[(int)format].format, ColorFormatInfoTableGL[(int)format].type, rgba.data() ); } else assert(0); lutChanged_ = false; } TransfuncEditor::MouseEvent TransfuncEditor::generateMouseEvent() { MouseEvent event; int x = ImGui::GetIO().MousePos.x - ImGui::GetCursorScreenPos().x; int y = ImGui::GetCursorScreenPos().y - ImGui::GetIO().MousePos.y - 1; event.pos = { x, y }; event.button = ImGui::GetIO().MouseDown[0] ? MouseEvent::Left : ImGui::GetIO().MouseDown[1] ? MouseEvent::Middle : ImGui::GetIO().MouseDown[2] ? MouseEvent::Right: MouseEvent::None; // TODO: handle the unlikely case that the down button is not // the same as the one from lastEvent_. This could happen as // the mouse events are tied to the rendering frame rate if (event.button == MouseEvent::None && lastEvent_.button == MouseEvent::None) event.type = MouseEvent::PassiveMotion; else if (event.button != MouseEvent::None && lastEvent_.button != MouseEvent::None) event.type = MouseEvent::Motion; else if (event.button != MouseEvent::None && lastEvent_.button == MouseEvent::None) event.type = MouseEvent::Press; else event.type = MouseEvent::Release; return event; } void TransfuncEditor::handleMouseEvent(TransfuncEditor::MouseEvent const& event) { bool hovered = ImGui::IsItemHovered() && event.pos.x >= 0 && event.pos.x < canvasSize_.x && event.pos.y >= 0 && event.pos.y < canvasSize_.y; if (event.type == MouseEvent::PassiveMotion || event.type == MouseEvent::Release) drawing_ = false; if (drawing_ || (event.type == MouseEvent::Press && hovered && event.button == MouseEvent::Left)) { float* updated = (float*)rgbaLookupTable_->getData(); updated[4 * event.pos.x + 3] = event.pos.y / (float)(canvasSize_.y - 1); // Also set the alphas that were potentially skipped b/c // the mouse movement was faster than the rendering frame // rate if (lastEvent_.button == MouseEvent::Left && std::abs(lastEvent_.pos.x - event.pos.x) > 1) { float alpha1; float alpha2; if (lastEvent_.pos.x > event.pos.x) { alpha1 = updated[4 * lastEvent_.pos.x + 3]; alpha2 = updated[4 * event.pos.x + 3]; } else { alpha1 = updated[4 * event.pos.x + 3]; alpha2 = updated[4 * lastEvent_.pos.x + 3]; } int inc = lastEvent_.pos.x < event.pos.x ? 1 : -1; for (int x = lastEvent_.pos.x + inc; x != event.pos.x; x += inc) { if (x < 0 || x >= canvasSize_.x) break; float frac = (event.pos.x - x) / (float)std::abs(event.pos.x - lastEvent_.pos.x); updated[4 * x + 3] = lerp(alpha1, alpha2, frac); } } lutChanged_ = true; drawing_ = true; } lastEvent_ = event; } } // vkt <file_sep>// This file is distributed under the MIT license. // See the LICENSE file for details. #include <cstring> #include <future> #include <memory> #include <GL/glew.h> #include <visionaray/math/simd/simd.h> #include <visionaray/math/aabb.h> #include <visionaray/math/ray.h> #include <visionaray/texture/texture.h> #include <visionaray/cpu_buffer_rt.h> #include <visionaray/scheduler.h> #include <visionaray/thin_lens_camera.h> // Private visionaray_common includes! #include <common/config.h> #include <common/manip/arcball_manipulator.h> #include <common/manip/pan_manipulator.h> #include <common/manip/zoom_manipulator.h> #if VSNRAY_COMMON_HAVE_SDL2 #include <common/viewer_sdl2.h> #else #include <common/viewer_glut.h> #endif #include <vkt/LookupTable.hpp> #include <vkt/Render.hpp> #include <vkt/StructuredVolume.hpp> #include <vkt/Render.h> #include <vkt/StructuredVolume.h> #include "Render_kernel.hpp" #include "StructuredVolume_impl.hpp" #include "TransfuncEditor.hpp" using namespace visionaray; #if VSNRAY_COMMON_HAVE_SDL2 using ViewerBase = viewer_sdl2; #else using ViewerBase = viewer_glut; #endif //------------------------------------------------------------------------------------------------- // Visionaray viewer (CPU) // struct ViewerCPU : ViewerBase { //using RayType = basic_ray<simd::float4>; using RayType = basic_ray<float>; vkt::StructuredVolume& volume; vkt::RenderState const& renderState; aabb bbox; thin_lens_camera cam; // Two render targets for double buffering cpu_buffer_rt<PF_RGBA32F, PF_UNSPECIFIED> host_rt[2]; tiled_sched<RayType> host_sched; std::vector<vec4> accumBuffer; unsigned frame_num; vkt::TransfuncEditor transfuncEditor; std::future<void> renderFuture; std::mutex displayMutex; int frontBufferIndex; ViewerCPU( vkt::StructuredVolume& volume, vkt::RenderState const& renderState, char const* windowTitle = "", unsigned numThreads = std::thread::hardware_concurrency() ); void clearFrame(); void on_display(); void on_mouse_move(visionaray::mouse_event const& event); void on_space_mouse_move(visionaray::space_mouse_event const& event); void on_resize(int w, int h); }; ViewerCPU::ViewerCPU( vkt::StructuredVolume& volume, vkt::RenderState const& renderState, char const* windowTitle, unsigned numThreads ) : ViewerBase(renderState.viewportWidth, renderState.viewportHeight, windowTitle) , volume(volume) , renderState(renderState) , host_sched(numThreads) , frontBufferIndex(0) { if (renderState.rgbaLookupTable != vkt::ResourceHandle(-1)) transfuncEditor.setLookupTableResource(renderState.rgbaLookupTable); } void ViewerCPU::clearFrame() { std::unique_lock<std::mutex> l(displayMutex); frame_num = 0; } void ViewerCPU::on_display() { if (transfuncEditor.updated()) clearFrame(); // Prepare a kernel with the volume set up appropriately // according to the provided texel type auto prepareTexture = [&](auto texel) { using TexelType = decltype(texel); using VolumeRef = texture_ref<TexelType, 3>; VolumeRef volume_ref( volume.getDims().x, volume.getDims().y, volume.getDims().z ); volume_ref.reset((TexelType*)volume.getData()); volume_ref.set_filter_mode(Nearest); volume_ref.set_address_mode(Clamp); return volume_ref; }; auto prepareTransfunc = [&]() { using namespace vkt; texture_ref<vec4f, 1> transfunc_ref(0); if (renderState.rgbaLookupTable != ResourceHandle(-1)) { LookupTable* lut = transfuncEditor.getUpdatedLookupTable(); if (lut == nullptr) lut = (LookupTable*)GetManagedResource(renderState.rgbaLookupTable); transfunc_ref = texture_ref<vec4f, 1>(lut->getDims().x); transfunc_ref.set_filter_mode(Nearest); transfunc_ref.set_address_mode(Clamp); transfunc_ref.reset((vec4*)lut->getData()); } return transfunc_ref; }; auto prepareRayMarchingKernel = [&](auto volume_ref, auto transfunc_ref) { using VolumeRef = decltype(volume_ref); using TransfuncRef = decltype(transfunc_ref); RayMarchingKernel<VolumeRef, TransfuncRef> kernel; kernel.bbox = bbox; kernel.volume = volume_ref; kernel.transfunc = transfunc_ref; kernel.dt = renderState.dtRayMarching; kernel.width = width(); kernel.height = height(); kernel.frameNum = frame_num; kernel.accumBuffer = accumBuffer.data(); kernel.sRGB = (bool)renderState.sRGB; return kernel; }; auto prepareImplicitIsoKernel = [&](auto volume_ref, auto transfunc_ref) { using VolumeRef = decltype(volume_ref); using TransfuncRef = decltype(transfunc_ref); ImplicitIsoKernel<VolumeRef, TransfuncRef> kernel; kernel.bbox = bbox; kernel.volume = volume_ref; kernel.transfunc = transfunc_ref; kernel.numIsoSurfaces = renderState.numIsoSurfaces; std::memcpy( &kernel.isoSurfaces, &renderState.isoSurfaces, sizeof(renderState.isoSurfaces) ); kernel.dt = renderState.dtImplicitIso; kernel.width = width(); kernel.height = height(); kernel.frameNum = frame_num; kernel.accumBuffer = accumBuffer.data(); kernel.sRGB = (bool)renderState.sRGB; return kernel; }; auto prepareMultiScatteringKernel = [&](auto volume_ref, auto transfunc_ref) { using VolumeRef = decltype(volume_ref); using TransfuncRef = decltype(transfunc_ref); float heightf(this->width()); MultiScatteringKernel<VolumeRef, TransfuncRef> kernel; kernel.bbox = bbox; kernel.volume = volume_ref; kernel.transfunc = transfunc_ref; kernel.mu_ = renderState.majorant; kernel.heightf_ = heightf; kernel.width = width(); kernel.height = height(); kernel.frameNum = frame_num; kernel.accumBuffer = accumBuffer.data(); kernel.sRGB = (bool)renderState.sRGB; return kernel; }; auto callKernel = [&](auto texel) { using TexelType = decltype(texel); if (!renderFuture.valid() || renderFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready) { { std::unique_lock<std::mutex> l(displayMutex); // swap render targets frontBufferIndex = !frontBufferIndex; ++frame_num; } renderFuture = std::async( [&,this]() { pixel_sampler::jittered_type blend_params; auto sparams = make_sched_params( blend_params, cam, host_rt[!frontBufferIndex] ); if (renderState.renderAlgo == vkt::RenderAlgo::RayMarching) { auto kernel = prepareRayMarchingKernel( prepareTexture(TexelType{}), prepareTransfunc() ); host_sched.frame(kernel, sparams); } else if (renderState.renderAlgo == vkt::RenderAlgo::ImplicitIso) { auto kernel = prepareImplicitIsoKernel( prepareTexture(TexelType{}), prepareTransfunc() ); host_sched.frame(kernel, sparams); } else if (renderState.renderAlgo == vkt::RenderAlgo::MultiScattering) { auto kernel = prepareMultiScatteringKernel( prepareTexture(TexelType{}), prepareTransfunc() ); host_sched.frame(kernel, sparams); } }); } }; switch (volume.getBytesPerVoxel()) { case 1: callKernel(uint8_t{}); break; case 2: callKernel(uint16_t{}); break; case 4: callKernel(uint32_t{}); break; } // display the rendered image auto bgcolor = background_color(); glClearColor(bgcolor.x, bgcolor.y, bgcolor.z, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); { std::unique_lock<std::mutex> l(displayMutex); host_rt[frontBufferIndex].display_color_buffer(); } if (have_imgui_support() && renderState.rgbaLookupTable != vkt::ResourceHandle(-1)) transfuncEditor.show(); } void ViewerCPU::on_mouse_move(visionaray::mouse_event const& event) { if (event.buttons() != mouse::NoButton) clearFrame(); ViewerBase::on_mouse_move(event); } void ViewerCPU::on_space_mouse_move(visionaray::space_mouse_event const& event) { clearFrame(); ViewerBase::on_space_mouse_move(event); } void ViewerCPU::on_resize(int w, int h) { if (renderFuture.valid()) renderFuture.wait(); cam.set_viewport(0, 0, w, h); float aspect = w / static_cast<float>(h); cam.perspective(45.0f * constants::degrees_to_radians<float>(), aspect, 0.001f, 1000.0f); { std::unique_lock<std::mutex> l(displayMutex); accumBuffer.resize(w * h); host_rt[0].resize(w, h); host_rt[1].resize(w, h); } clearFrame(); ViewerBase::on_resize(w, h); } //------------------------------------------------------------------------------------------------- // Render common impl for both APIs // static void Render_impl( vkt::StructuredVolume& volume, vkt::RenderState const& renderState, vkt::RenderState* newRenderState ) { ViewerCPU viewer(volume, renderState); int argc = 1; char const* argv = "vktRender"; viewer.init(argc, (char**)&argv); vkt::Vec3i dims = volume.getDims(); vkt::Vec3f dist = volume.getDist(); viewer.bbox = aabb( { 0.f, 0.f, 0.f }, { dims.x * dist.x, dims.y * dist.y, dims.z * dist.z } ); float aspect = viewer.width() / static_cast<float>(viewer.height()); viewer.cam.perspective( 45.f * constants::degrees_to_radians<float>(), aspect, .001f, 1000.f ); viewer.cam.set_lens_radius(0.05f); viewer.cam.set_focal_distance(10.0f); viewer.cam.view_all(viewer.bbox); viewer.add_manipulator(std::make_shared<arcball_manipulator>(viewer.cam, mouse::Left)); viewer.add_manipulator(std::make_shared<pan_manipulator>(viewer.cam, mouse::Middle)); // Additional "Alt + LMB" pan manipulator for setups w/o middle mouse button viewer.add_manipulator(std::make_shared<pan_manipulator>(viewer.cam, mouse::Left, keyboard::Alt)); viewer.add_manipulator(std::make_shared<zoom_manipulator>(viewer.cam, mouse::Right)); viewer.event_loop(); // when finished, write out the new render state if (newRenderState != nullptr) { } } //------------------------------------------------------------------------------------------------- // C++ API // namespace vkt { Error Render(StructuredVolume& volume, RenderState const& renderState, RenderState* newRenderState) { Render_impl(volume, renderState, newRenderState); return NoError; } } // vkt //------------------------------------------------------------------------------------------------- // C API // vktError vktRenderSV( vktStructuredVolume volume, vktRenderState_t renderState, vktRenderState_t* newRenderState) { static_assert(sizeof(vktRenderState_t) == sizeof(vkt::RenderState), "Type mismatch"); vkt::RenderState renderStateCPP; std::memcpy(&renderStateCPP, &renderState, sizeof(renderState)); vkt::RenderState newRenderStateCPP; Render_impl(volume->volume, renderStateCPP, &newRenderStateCPP); if (newRenderState != nullptr) std::memcpy(newRenderState, &newRenderStateCPP, sizeof(newRenderStateCPP)); return vktNoError; } <file_sep># This file is distributed under the MIT license. # See the LICENSE file for details. find_package(CUDA) find_package(SDL2) find_package(SWIG) find_package(Virvo) find_package(Visionaray) vkt_use_package(CUDA) vkt_use_package(SDL2) vkt_use_package(SWIG) vkt_use_package(Virvo) if(VIRVO_FOUND) set(__VKT_LINK_LIBRARIES ${__VKT_LINK_LIBRARIES} ${VIRVO_FILEIO_LIBRARY}) endif() #vkt_use_package(Visionaray COMPONENTS common) # TODO!! vkt_use_package(Visionaray) cmake_policy(SET CMP0078 NEW) if(SWIG_FOUND) include(${SWIG_USE_FILE}) find_package(Python3 3.6 COMPONENTS Interpreter Development REQUIRED) include_directories(SYSTEM ${Python3_INCLUDE_DIRS}) endif() #--------------------------------------------------------------------------------------------------- # Dependencies pulled in by visionaray # if(VISIONARAY_FOUND AND VISIONARAY_COMMON_LIBRARY) find_package(GLEW REQUIRED) find_package(GLUT REQUIRED) find_package(OpenGL REQUIRED) vkt_use_package(GLEW) vkt_use_package(GLUT) vkt_use_package(OpenGL) # Private visionaray_common headers include_directories(${VISIONARAY_INCLUDE_DIR}/visionaray/private) # TODO set(3DCONNEXIONCLIENT_FOUND NOTFOUND) if (APPLE) include(CMakeFindFrameworks) CMAKE_FIND_FRAMEWORKS(3DconnexionClient) if (3DconnexionClient_FRAMEWORKS) set(__VKT_LINK_LIBRARIES ${__VKT_LINK_LIBRARIES} ${3DconnexionClient_FRAMEWORKS}) set(__VKT_USED_PACKAGES ${__VKT_USED_PACKAGES} 3DCONNEXIONCLIENT) set(3DCONNEXIONCLIENT_FOUND FOUND) endif() endif() endif() #--------------------------------------------------------------------------------------------------- # ImGui submodule # if(VKT_ENABLE_IMGUI) # Make visible for config file creation # That's a submodule after all, so just set to FOUND set(IMGUI_FOUND FOUND) set(__VKT_USED_PACKAGES ${__VKT_USED_PACKAGES} IMGUI) # ImGui is compiled directly into the library set(IMGUI_DIR ${PROJECT_SOURCE_DIR}/src/3rdparty/imgui) set(IMGUI_INCLUDE_DIR ${IMGUI_DIR}) include_directories(${IMGUI_INCLUDE_DIR}) set(IMGUI_HEADERS ${IMGUI_INCLUDE_DIR}/imconfig.h ${IMGUI_INCLUDE_DIR}/imgui.h ${IMGUI_INCLUDE_DIR}/imgui_internal.h ${IMGUI_INCLUDE_DIR}/imstb_rectpack.h ${IMGUI_INCLUDE_DIR}/imstb_textedit.h ${IMGUI_INCLUDE_DIR}/imstb_truetype.h ) set(IMGUI_SOURCES ${IMGUI_DIR}/imgui.cpp ${IMGUI_DIR}/imgui_demo.cpp ${IMGUI_DIR}/imgui_draw.cpp ${IMGUI_DIR}/imgui_widgets.cpp ) endif() #--------------------------------------------------------------------------------------------------- # Create config file # foreach(p ${__VKT_USED_PACKAGES}) set(VKT_HAVE_${p} 1) endforeach() set(CONFIG_DIR ${__VKT_CONFIG_DIR}) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/config.h.in ${CONFIG_DIR}/vkt/config.h) include_directories(${__VKT_CONFIG_DIR}) #--------------------------------------------------------------------------------------------------- # Volkit library # include_directories(${PROJECT_SOURCE_DIR}/include/c) include_directories(${PROJECT_SOURCE_DIR}/include/cpp) include_directories(${PROJECT_SOURCE_DIR}/include/shared) set(C_HEADER_DIR ${PROJECT_SOURCE_DIR}/include/c/vkt) set(CPP_HEADER_DIR ${PROJECT_SOURCE_DIR}/include/cpp/vkt) set(HEADERS ${C_HEADER_DIR}/StructuredVolume.h ) set(SOURCES Aggregates.cpp Arithmetic.cpp Copy.cpp CudaTimer.cpp Decompose.cpp ExecutionPolicy.cpp Fill.cpp Flip.cpp InputStream.cpp LookupTable.cpp ManagedResource.cpp Memory.cpp RawFile.cpp Render.cpp Rotate.cpp Scan.cpp StructuredVolume.cpp TransfuncEditor.cpp Transform.cpp VirvoFile.cpp Voxel.cpp ) vkt_cuda_compile(CUDA_SOURCES Arithmetic_cuda.cu Copy_cuda.cu Decompose_cuda.cu Fill_cuda.cu Flip_cuda.cu ) vkt_add_library(volkit ${HEADERS} ${SOURCES} ${IMGUI_HEADERS} ${IMGUI_SOURCES} ${CUDA_SOURCES} ) # Explicitly link with visionaray_common if(VISIONARAY_COMMON_LIBRARY) target_link_libraries(volkit ${VISIONARAY_COMMON_LIBRARY}) endif() if(SWIG_FOUND) set_property(SOURCE volkit.i PROPERTY CPLUSPLUS ON) swig_add_library(volkitpy LANGUAGE python SOURCES volkit.i) swig_link_libraries(volkitpy ${Python3_LIBRARIES}) swig_link_libraries(volkitpy volkit) endif() <file_sep>#pragma once #include <cstddef> #include <cstdint> #include <memory> #include "common.hpp" #include "linalg.hpp" namespace vkt { class VirvoFile : public DataSource { public: VirvoFile(char const* fileName); ~VirvoFile(); virtual std::size_t read(char* buf, std::size_t len); virtual bool good() const; Vec3i getDims(); uint16_t getBytesPerVoxel(); private: struct Impl; std::unique_ptr<Impl> impl_; }; } // vkt <file_sep>// This file is distributed under the MIT license. // See the LICENSE file for details. #include <cassert> #include <vkt/InputStream.hpp> #include <vkt/StructuredVolume.hpp> #include <vkt/InputStream.h> #include <vkt/StructuredVolume.h> #include "InputStream_impl.hpp" #include "StructuredVolume_impl.hpp" //------------------------------------------------------------------------------------------------- // C++ API // namespace vkt { InputStream::InputStream(DataSource& source) : dataSource_(source) { } Error InputStream::read(StructuredVolume& volume) { if (!dataSource_.good()) return InvalidDataSource; std::size_t len = dataSource_.read((char*)volume.getData(), volume.getSizeInBytes()); if (len != volume.getSizeInBytes()) return ReadError; return NoError; } Error InputStream::readRange( StructuredVolume& dst, int32_t firstX, int32_t firstY, int32_t firstZ, int32_t lastX, int32_t lastY, int32_t lastZ, int32_t dstOffsetX, int32_t dstOffsetY, int32_t dstOffsetZ ) { return NoError; } Error InputStream::readRange( StructuredVolume& dst, Vec3i first, Vec3i last, Vec3i dstOffset ) { return NoError; } } // vkt //------------------------------------------------------------------------------------------------- // C API // void vktInputStreamCreateF(vktInputStream* stream, vktRawFile file) { assert(stream != nullptr); *stream = new vktInputStream_impl(file); } void vktInputStreamDestroy(vktInputStream stream) { delete stream; } vktError vktInputStreamReadSV(vktInputStream stream, vktStructuredVolume volume) { stream->stream.read(volume->volume); return vktNoError; } vktError vktInputStreamReadRangeSV( vktInputStream stream, vktStructuredVolume volume, int32_t firstX, int32_t firstY, int32_t firstZ, int32_t lastX, int32_t lastY, int32_t lastZ, int32_t dstOffsetX, int32_t dstOffsetY, int32_t dstOffsetZ ) { /*stream->stream.readRange( volume->volume, firstX, firstY, firstZ, lastX, lastY, lastZ, dstOffsetX, dstOffsetY, dstOffsetZ );*/ return vktNoError; } <file_sep>// This file is distributed under the MIT license. // See the LICENSE file for details. #pragma once #include <vkt/InputStream.hpp> #include "RawFile_impl.hpp" struct vktInputStream_impl { vktInputStream_impl(vktRawFile_impl* file) : stream(file->file) { } vkt::InputStream stream; }; <file_sep>// This file is distributed under the MIT license. // See the LICENSE file for details. #pragma once #include <cstdio> #include <vkt/RawFile.hpp> struct vktRawFile_impl { vktRawFile_impl(char const* fileName, char const* mode) : file(fileName, mode) { } vktRawFile_impl(FILE* fd) : file(fd) { } vkt::RawFile file; }; <file_sep>// This file is distributed under the MIT license. // See the LICENSE file for details. #pragma once #include <cstdint> #include "common.hpp" #include "forward.hpp" #include "linalg.hpp" namespace vkt { VKTAPI Error Sum(StructuredVolume& dest, StructuredVolume& source1, StructuredVolume& source2); VKTAPI Error SumRange(StructuredVolume& dest, StructuredVolume& source1, StructuredVolume& source2, int32_t firstX, int32_t firstY, int32_t firstZ, int32_t lastX, int32_t lastY, int32_t lastZ, int32_t dstOffsetX = 0, int32_t dstOffsetY = 0, int32_t dstOffsetZ = 0); VKTAPI Error SumRange(StructuredVolume& dest, StructuredVolume& source1, StructuredVolume& source2, Vec3i first, Vec3i last, Vec3i dstOffset = { 0, 0, 0 }); VKTAPI Error Diff(StructuredVolume& dest, StructuredVolume& source1, StructuredVolume& source2); VKTAPI Error DiffRange(StructuredVolume& dest, StructuredVolume& source1, StructuredVolume& source2, int32_t firstX, int32_t firstY, int32_t firstZ, int32_t lastX, int32_t lastY, int32_t lastZ, int32_t dstOffsetX = 0, int32_t dstOffsetY = 0, int32_t dstOffsetZ = 0); VKTAPI Error DiffRange(StructuredVolume& dest, StructuredVolume& source1, StructuredVolume& source2, Vec3i first, Vec3i last, Vec3i dstOffset = { 0, 0, 0 }); VKTAPI Error Prod(StructuredVolume& dest, StructuredVolume& source1, StructuredVolume& source2); VKTAPI Error ProdRange(StructuredVolume& dest, StructuredVolume& source1, StructuredVolume& source2, int32_t firstX, int32_t firstY, int32_t firstZ, int32_t lastX, int32_t lastY, int32_t lastZ, int32_t dstOffsetX = 0, int32_t dstOffsetY = 0, int32_t dstOffsetZ = 0); VKTAPI Error ProdRange(StructuredVolume& dest, StructuredVolume& source1, StructuredVolume& source2, Vec3i first, Vec3i last, Vec3i dstOffset = { 0, 0, 0 }); VKTAPI Error Quot(StructuredVolume& dest, StructuredVolume& source1, StructuredVolume& source2); VKTAPI Error QuotRange(StructuredVolume& dest, StructuredVolume& source1, StructuredVolume& source2, int32_t firstX, int32_t firstY, int32_t firstZ, int32_t lastX, int32_t lastY, int32_t lastZ, int32_t dstOffsetX = 0, int32_t dstOffsetY = 0, int32_t dstOffsetZ = 0); VKTAPI Error QuotRange(StructuredVolume& dest, StructuredVolume& source1, StructuredVolume& source2, Vec3i first, Vec3i last, Vec3i dstOffset = { 0, 0, 0 }); VKTAPI Error AbsDiff(StructuredVolume& dest, StructuredVolume& source1, StructuredVolume& source2); VKTAPI Error AbsDiffRange(StructuredVolume& dest, StructuredVolume& source1, StructuredVolume& source2, int32_t firstX, int32_t firstY, int32_t firstZ, int32_t lastX, int32_t lastY, int32_t lastZ, int32_t dstOffsetX = 0, int32_t dstOffsetY = 0, int32_t dstOffsetZ = 0); VKTAPI Error AbsDiffRange(StructuredVolume& dest, StructuredVolume& source1, StructuredVolume& source2, Vec3i first, Vec3i last, Vec3i dstOffset = { 0, 0, 0 }); VKTAPI Error SafeSum(StructuredVolume& dest, StructuredVolume& source1, StructuredVolume& source2); VKTAPI Error SafeSumRange(StructuredVolume& dest, StructuredVolume& source1, StructuredVolume& source2, int32_t firstX, int32_t firstY, int32_t firstZ, int32_t lastX, int32_t lastY, int32_t lastZ, int32_t dstOffsetX = 0, int32_t dstOffsetY = 0, int32_t dstOffsetZ = 0); VKTAPI Error SafeSumRange(StructuredVolume& dest, StructuredVolume& source1, StructuredVolume& source2, Vec3i first, Vec3i last, Vec3i dstOffset = { 0, 0, 0 }); VKTAPI Error SafeDiff(StructuredVolume& dest, StructuredVolume& source1, StructuredVolume& source2); VKTAPI Error SafeDiffRange(StructuredVolume& dest, StructuredVolume& source1, StructuredVolume& source2, int32_t firstX, int32_t firstY, int32_t firstZ, int32_t lastX, int32_t lastY, int32_t lastZ, int32_t dstOffsetX = 0, int32_t dstOffsetY = 0, int32_t dstOffsetZ = 0); VKTAPI Error SafeDiffRange(StructuredVolume& dest, StructuredVolume& source1, StructuredVolume& source2, Vec3i first, Vec3i last, Vec3i dstOffset = { 0, 0, 0 }); VKTAPI Error SafeProd(StructuredVolume& dest, StructuredVolume& source1, StructuredVolume& source2); VKTAPI Error SafeProdRange(StructuredVolume& dest, StructuredVolume& source1, StructuredVolume& source2, int32_t firstX, int32_t firstY, int32_t firstZ, int32_t lastX, int32_t lastY, int32_t lastZ, int32_t dstOffsetX = 0, int32_t dstOffsetY = 0, int32_t dstOffsetZ = 0); VKTAPI Error SafeProdRange(StructuredVolume& dest, StructuredVolume& source1, StructuredVolume& source2, Vec3i first, Vec3i last, Vec3i dstOffset = { 0, 0, 0 }); VKTAPI Error SafeQuot(StructuredVolume& dest, StructuredVolume& source1, StructuredVolume& source2); VKTAPI Error SafeQuotRange(StructuredVolume& dest, StructuredVolume& source1, StructuredVolume& source2, int32_t firstX, int32_t firstY, int32_t firstZ, int32_t lastX, int32_t lastY, int32_t lastZ, int32_t dstOffsetX = 0, int32_t dstOffsetY = 0, int32_t dstOffsetZ = 0); VKTAPI Error SafeQuotRange(StructuredVolume& dest, StructuredVolume& source1, StructuredVolume& source2, Vec3i first, Vec3i last, Vec3i dstOffset = { 0, 0, 0}); VKTAPI Error SafeAbsDiff(StructuredVolume& dest, StructuredVolume& source1, StructuredVolume& source2); VKTAPI Error SafeAbsDiffRange(StructuredVolume& dest, StructuredVolume& source1, StructuredVolume& source2, int32_t firstX, int32_t firstY, int32_t firstZ, int32_t lastX, int32_t lastY, int32_t lastZ, int32_t dstOffsetX = 0, int32_t dstOffsetY = 0, int32_t dstOffsetZ = 0); VKTAPI Error SafeAbsDiffRange(StructuredVolume& dest, StructuredVolume& source1, StructuredVolume& source2, Vec3i first, Vec3i last, Vec3i dstOffset = { 0, 0, 0 }); } // vkt <file_sep>#include <cstdlib> #include <iostream> #include <ostream> #include <vkt/InputStream.hpp> #include <vkt/LookupTable.hpp> #include <vkt/RawFile.hpp> #include <vkt/Render.hpp> #include <vkt/StructuredVolume.hpp> int main(int argc, char** argv) { if (argc < 2) { std::cerr << "Usage: " << argv[0] << " file.raw\n"; return EXIT_FAILURE; } vkt::RawFile file(argv[1], "r"); vkt::Vec3i dims = file.getDims(); if (dims.x * dims.y * dims.z < 1) { std::cerr << "Cannot parse dimensions from file name\n"; return EXIT_FAILURE; } uint16_t bpv = file.getBytesPerVoxel(); if (bpv == 0) { std::cerr << "Cannot parse bytes per voxel from file name, guessing 1...\n"; bpv = 1; } vkt::StructuredVolume volume(dims.x, dims.y, dims.z, bpv); vkt::InputStream is(file); is.read(volume); float rgba[] = { 1.f, 1.f, 1.f, .005f, 0.f, .1f, .1f, .25f, .5f, .5f, .7f, .5f, .7f, .7f, .07f, .75f, 1.f, .3f, .3f, 1.f }; vkt::LookupTable lut(5,1,1,vkt::ColorFormat::RGBA32F); lut.setData((uint8_t*)rgba); vkt::RenderState renderState; //renderState.renderAlgo = vkt::RenderAlgo::RayMarching; //renderState.renderAlgo = vkt::RenderAlgo::ImplicitIso; renderState.renderAlgo = vkt::RenderAlgo::MultiScattering; renderState.rgbaLookupTable = lut.getResourceHandle(); vkt::Render(volume, renderState); } <file_sep>// This file is distributed under the MIT license. // See the LICENSE file for details. #pragma once namespace vkt { struct Vec2f { float x; float y; }; struct Vec3f { float x; float y; float z; }; struct Vec4f { float x; float y; float z; float w; }; struct Vec2i { int x; int y; }; struct Vec3i { int x; int y; int z; }; struct Mat3f { Vec3f col0; Vec3f col1; Vec3f col2; }; enum class Axis { X, Y, Z, }; } // vkt <file_sep>// This file is distributed under the MIT license. // See the LICENSE file for details. #include <cassert> #include <vkt/CudaTimer.hpp> #include <vkt/CudaTimer.h> #include "macros.hpp" //------------------------------------------------------------------------------------------------- // C++ API // namespace vkt { CudaTimer::CudaTimer() { VKT_CUDA_SAFE_CALL__(cudaEventCreate(&start_)); VKT_CUDA_SAFE_CALL__(cudaEventCreate(&stop_)); reset(); } CudaTimer::~CudaTimer() { VKT_CUDA_SAFE_CALL__(cudaEventDestroy(start_)); VKT_CUDA_SAFE_CALL__(cudaEventDestroy(stop_)); } void CudaTimer::reset() { VKT_CUDA_SAFE_CALL__(cudaEventRecord(start_)); } double CudaTimer::getElapsedSeconds() const { VKT_CUDA_SAFE_CALL__(cudaEventRecord(stop_)); VKT_CUDA_SAFE_CALL__(cudaEventSynchronize(stop_)); float ms = 0.f; VKT_CUDA_SAFE_CALL__(cudaEventElapsedTime(&ms, start_, stop_)); return static_cast<double>(ms) / 1000.; } } // vkt //------------------------------------------------------------------------------------------------- // C API // struct vktCudaTimer_impl { vkt::CudaTimer timer; }; void vktCudaTimerCreate(vktCudaTimer* timer) { assert(timer != nullptr); *timer = new vktCudaTimer_impl; } void vktCudaTimerDestroy(vktCudaTimer timer) { delete timer; } void vktCudaTimerReset(vktCudaTimer timer) { timer->timer.reset(); } double vktCudaTimerGetElapsedSeconds(vktCudaTimer timer) { return timer->timer.getElapsedSeconds(); } <file_sep>// This file is distributed under the MIT license. // See the LICENSE file for details. #pragma once #include "common.hpp" namespace vkt { struct ExecutionPolicy { enum class Device { CPU, GPU, Unspecified, }; enum class HostAPI { Serial, //OpenMP, //TBB, }; enum class DeviceAPI { CUDA, //OpenCL, }; Device device = Device::CPU; HostAPI hostApi = HostAPI::Serial; DeviceAPI deviceApi = DeviceAPI::CUDA; }; /*! * @brief set the execution of the current thread */ VKTAPI void SetThreadExecutionPolicy(ExecutionPolicy policy); /*! * @brief get the execution of the current thread */ VKTAPI ExecutionPolicy GetThreadExecutionPolicy(); } // vkt <file_sep>// This file is distributed under the MIT license. // See the LICENSE file for details. #pragma once #include <cstddef> #include <cstdint> #include <vkt/ManagedBuffer.hpp> #include "common.hpp" #include "linalg.hpp" namespace vkt { /*! * @brief 1D|2D|3D lookup table class */ class LookupTable : public ManagedBuffer<uint8_t> { public: LookupTable(int32_t dimX, int32_t dimY, int32_t dimZ, ColorFormat format); void setDims(int32_t dimX, int32_t dimY, int32_t dimZ); void getDims(int32_t& dimX, int32_t& dimY, int32_t& dimZ); void setDims(Vec3i dims); Vec3i getDims() const; void setColorFormat(ColorFormat pf); ColorFormat getColorFormat() const; /*! * @brief Provide data buffer: LUT will copy that data to its own memory */ void setData(uint8_t* data); uint8_t* getData(); std::size_t getSizeInBytes() const; private: Vec3i dims_ = { 0, 0, 0 }; ColorFormat format_ = ColorFormat::Unspecified; }; } // vkt <file_sep>// This file is distributed under the MIT license. // See the LICENSE file for details. #pragma once #include <cstddef> #include <cstdlib> #include <cstring> #include <vkt/Memory.hpp> namespace vkt { inline void Allocate_serial(void** ptr, std::size_t size) { *ptr = malloc(size); } inline void Free_serial(void* ptr) { free(ptr); } } // vkt <file_sep>#!/usr/bin/python3 import ctypes import sys import volkit as vkt def main(): if len(sys.argv) < 2: print("Usage: ", sys.argv[0], "file.raw") return file = vkt.RawFile(sys.argv[1], "r") dims = file.getDims() if dims.x * dims.y * dims.y < 1: print("Cannot parse dimensions from file name") return bpv = file.getBytesPerVoxel() if bpv == 0: print("Cannot parse bytes per voxel from file name, guessing 1...") bpv = 1 volume = vkt.StructuredVolume(dims.x, dims.y, dims.z, bpv) ips = vkt.InputStream(file) ips.read(volume) rgba = [ 1., 1., 1., .005, 0., .1, .1, .25, .5, .5, .7, .5, .7, .7, .07, .75, 1., .3, .3, 1. ] lut = vkt.LookupTable(5,1,1,vkt.ColorFormat_RGBA32F) lut.setData(rgba) rs = vkt.RenderState() #rs.renderAlgo = vkt.RenderAlgo_RayMarching #rs.renderAlgo = vkt.RenderAlgo_ImplicitIso rs.renderAlgo = vkt.RenderAlgo_MultiScattering rs.rgbaLookupTable = lut.getResourceHandle() vkt.Render(volume, rs) if __name__ == '__main__': main()
a9fee56ffa92f1c1802933d5ad025c72425cb837
[ "C", "Python", "CMake", "C++" ]
22
C++
malei-pku/volkit
6b6899433f06e698f205ce04b70438aa34e567fd
9ac3587b450b9ea9e3997ba05952affdc2f66745
refs/heads/master
<file_sep>#include"ELaser.h" ELaser::ELaser(float px, float py) :GameObject( px, py, "enemylaser", 1) { } ELaser::~ELaser() { } void ELaser::init() { DDS_FILE* dds = readDDS("dds/laserE2.dds"); float x = dds->header.dwWidth*0.5; float y = dds->header.dwHeight*0.5; setAnchor(x, y); setDDS(dds); speed = 400; } void ELaser::update() { float dist = getDeltaTime() * speed; translate(0, dist); }<file_sep>#include"LivesInterface.h" #include<cstdio> #include<string.h> LivesInterface::LivesInterface(Origin origin) { this->origin = origin; } LivesInterface::LivesInterface(Origin origin, const char* name) { this->origin = origin; this->name = name; } LivesInterface::~LivesInterface() { delete this->name; } const char* LivesInterface::getName() { return this->name; } LivesInterface::Origin LivesInterface::getOrigin() { return this->origin; } LivesInterface::Position& LivesInterface::getPosition() { return this->position; } void::LivesInterface::setPosition(LivesInterface::Position position) { this->position = position; } void::LivesInterface::setPosition(float x, float y) { this->position.x = x; this->position.y = y; } void::LivesInterface::printToConsole() { using namespace std; cout << "종: "<< this->getSpeciesString() << endl; cout << "이름: " << this->name << endl; cout << "현재위치: "<<this->position.x<<" , "<<this->position.y << endl; }<file_sep>#include<windows.h> #include<tchar.h> #include"debug.h" #pragma warning(disable:4996) void START_DEBUG_CONSOLE() { AllocConsole(); //윈도우에서 콘솔창 시작하기 함수 freopen("CONOUT$", "w", stdout); //printf 또는 cout에 의해서 출력되는 표준 출력창으로 만듬 freopen("CONIN$", "r", stdin); //scanf_s 또는 cin에 의해서 입력을 받을 수 있는 표준 입력 창으로 만듬 } void STOP_DEBUG_CONSOLE() { FreeConsole(); //윈도우에서 콘솔창 종료하기 함수 } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM IParam); int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE hprevInstance, LPWSTR IpCmdLine, int nCmdShow) { ///////윈도우 클래스 등록//////// WNDCLASSEXW wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; //윈도우 클래스 스타일 - 가로/세로 방향 그리기 스타일 wcex.lpfnWndProc = WndProc; //윈도우 창의 메뉴/마우스 이벤트 처리 함수 등록 wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; //이 윈도우 클래스를 관리하는 어플리케이션 인스턴스핸들 wcex.hIcon = nullptr; //아이콘 이미지 등록 - 현재 없음 wcex.hCursor = LoadCursor(nullptr, IDC_ARROW); //커서 형태 등록 - 화살표 아이콘 wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);//윈도우 바탕색 지정 wcex.lpszMenuName = nullptr; //윈도우 메뉴 등록 - 현재 없음 wcex.lpszClassName = L"MyWndClass"; //등록된 클래스의 이름 - 윈도우를 만들때 참조됨-L은 2바이트 문자열 wcex.hIconSm = nullptr; //작은 아이콘 등록 - 현재 없음 RegisterClassExW(&wcex); HWND hWnd = CreateWindowW(L"MyWndClass", //윈도우를 생성하기 위한 클래스 - 위에서 등록한 클래스 L"윈도우창", //생성되는 윈도우의 이름 WS_OVERLAPPEDWINDOW, //생성되는 윈도우의 형식 - 기존 위도우 형식임 CW_USEDEFAULT, //시작 위치와 윈도우 크기 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, //생성된 윈도우 창을 과닐하는 프로그램 인스턴스 nullptr); if (hWnd != nullptr) { ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); } START_DEBUG_CONSOLE(); printf("디버기 콘솔창을 시작 합니다."); ///////윈도우 메시지 반복 처리하기///////// MSG msg = { 0, }; //사용자 입력 - 메뉴/마우스/키보드 등의 이멘트(메시지)를 받아오는 구조체 while (GetMessage(&msg, nullptr, 0, 0) == TRUE) { //반복적으로 원영체제에서 메시를 받아온다. TranslateMessage(&msg); //메시지 전잘전에 필요한 처리를 한다. DispatchMessage(&msg); //처리된 메시지를 해당 윈도우 창에 전달한다. } ////////콘솔창 종료하기//////////////////// STOP_DEBUG_CONSOLE(); return (int)msg.wParam; } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM IParam) { PAINTSTRUCT ps; //윈도우 창 화면에 그리기를 할 정보를 저장하는 구조체 HDC hdc; //화면 그리기 장치 정보 핸드 -Device Context Handle switch (message) { case WM_COMMAND: //사용자 메뉴 입력 처리 부분 break; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); EndPaint(hWnd, &ps); break; case WM_DESTROY: PostQuitMessage(0); //윈도우 종료 처리 break; default: return DefWindowProc(hWnd, message, wParam, IParam); } return 0; } <file_sep>#pragma once #include "header.h" class Player : public GameObject { private: //플레이어 변수 float speed; public: Player(); virtual ~Player(); virtual void init(); virtual void update(); };<file_sep>#include"PLaser.h" PLaser::PLaser() :GameObject(240, 500, "player laser", 0) { } PLaser::PLaser(float x, float y) : GameObject(x, y, "player laser", 0) { } PLaser::~PLaser() { } void PLaser::init() { DDS_FILE* dds = readDDS("dds/laserP.dds"); float x = dds->header.dwWidth* 0.5; float y = dds->header.dwHeight* 0.5; setAnchor(x, y); setDDS(dds); /////레이져가 날라가는 속도 speed = 1000; } void PLaser::update() { float x = getPx(); float y = getPy(); float dist = getDeltaTime() * speed; translate(0, -dist); if (y < 0) { dead_Alive(); // 상태만 바꿔주는거 } }<file_sep>#include"keyboard.h" float prevTime; //이전 프레임의 시작 시간 float currTime; //현재 프레임의 시작 시간 float deltaTime; //현재 프레임과 이전 프레임의 시간 간격 enum KeyState { KEY_UP_REP = 0, KEY_DOWN, KEY_DOWN_REP, KEY_UP }; KeyState keyState[256]; void initKey() { for (int i = 0; i < 256; i++) { keyState[i] = KeyState::KEY_UP_REP; //모든 키는 놓임 지속으로 초기 상태를 가진다. } } void updateKey() { for (int i = 0; i < 256; i++) { int key = GetAsyncKeyState(i); if (keyState[i] == KeyState::KEY_UP_REP) { if ((key & 0x8000) == 0x8000) { keyState[i] = KEY_DOWN; } else { keyState[i] = KEY_UP_REP; } } else if (keyState[i] == KeyState::KEY_DOWN) { if ((key & 0x8000) == 0x8000) { keyState[i] = KEY_DOWN_REP; } else { keyState[i] = KEY_UP; } } else if (keyState[i] == KeyState::KEY_DOWN_REP) { if ((key & 0x8000) == 0x8000) { keyState[i] = KEY_DOWN_REP; } else { keyState[i] = KEY_UP; } } else if (keyState[i] == KeyState::KEY_UP) { if ((key & 0x8000) == 0x8000) { keyState[i] = KEY_DOWN; } else { keyState[i] = KEY_UP_REP; } } } } //키를 지속적으로 누르고 있는지를 검사한다. bool GetKey(int keyCode) { if (keyState[keyCode] == KEY_DOWN_REP) { return true; } else { return false; } } bool GetKeyDown(int keyCode) { if (keyState[keyCode] == KEY_DOWN) { return true; } else { return false; } } void initTimer() { prevTime = (float)(GetTickCount() / 1000.0); //GetTickCount는 컴퓨터가 부팅되면서 시간이 측정되고(부팅시 값은 0) 측정단위는 밀리세컨드이다(즉 1000이 1초임) currTime = prevTime; deltaTime = 0; } void updateTimer() { currTime = (float)(GetTickCount() / 1000.0); //현재 시간을 측정한다. deltaTime = currTime - prevTime; //이전 프레임과의 시간 차이를 측정한다. prevTime = currTime; //현재 측정된 시간은 이전 프레임 값으로 저장된다. } float getDeltaTime() { return deltaTime; } void gotoxy(int x, int y) { COORD Pos = { x,y }; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), Pos); } void hide() { CONSOLE_CURSOR_INFO ConsoleCursor; GetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &ConsoleCursor); ConsoleCursor.bVisible = 0; SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &ConsoleCursor); //변경값 적용 } <file_sep>#ifndef __DOG_H__ #define __DOG_H__ #include"LivesInterface.h" #define FUR_COLOR_WHITE 0xffffff #define FUR_COLOR_BLACK 0x000000 #define FUR_COLOR_GOLDEN 0x9b8509 class Dog : public LivesInterface { protected: int furColor = FUR_COLOR_WHITE; char* ownerName; void setColor(int furColor); public: Dog(LivesInterface::Origin origin, const char* name); virtual ~Dog(); void setOwnerName(const char* ownerName); }; #endif<file_sep>#pragma once ///////최상위 부모///////// //#include"header.h" #include "DDS.h" class GameObject { private: const char* name; int tag; //////게임객체의 위치, 회전, 크기- 트랜스폼////// float px, py; //위치 좌표 float speed; //속도 //////이미지의 앵커포인트/////// float ax; float ay; bool alive; //////이미지 DDS 포인터//////// DDS_FILE* dds; public: //만약에 넣을 데이터가 없다면 오른쪽 파라미터부터 채워나가자 GameObject(float px, float py, const char* name = "", int tag = 0); //생성자 virtual ~GameObject(); //(가상)소멸자 /////////이동 함수/////////// void translate(float x, float y); //-현재 위치에서 이동 //게터(Getter)+세터(Setter) const char* getName(); int getTag(); float getPx(); float getPy(); float getAx(); float getAy(); void setName(const char* name); void setTag(int tag); void setXY(float x, float y); void setAnchor(float x, float y); void setDDS(DDS_FILE* dds); void dead_Alive(); bool getAlive(); //기본 메소드// virtual void init(); virtual void update(); virtual void render(); //충돌 체크하기// virtual bool checkCollision(GameObject* target); public: int keycode; void setKeyCode(int keycode) { this->keycode = keycode; } int getKeyCode() { return this->keycode; } };<file_sep>#include"Retriever.h" #include<cstdio> Retriever::Retriever(const char* name) :Dog(LivesInterface::EVERYWHERE, name) { setColor(FUR_COLOR_GOLDEN); } Retriever::~Retriever() {} void Retriever::printToConsole() { using namespace std; cout << "리트리버는 착하고 영리합니다" << endl; Dog::printToConsole(); cout << endl; } const char* Retriever::getSpeciesString() { return "리트리버"; }<file_sep>#pragma once #include<stdio.h> void START_DEBUG_CONSOLE(); //디버그 콘솔창을 시작한다. void STOP_DEBUG_CONSOLE(); //디버그 콘솔창을 종료한다.<file_sep>#ifndef __RETRIEVER_H__ #define __RETRIEVER_H__ #include"Dog.h" class Retriever : public Dog { public: Retriever(const char* name); virtual ~Retriever(); virtual void printToConsole(); virtual const char* getSpeciesString(); }; #endif <file_sep>#ifndef __ROSE_H__ #define __ROSE_H__ #include"LivesInterface.h" #define ROSE_COLOR_RED 1 #define ROSE_COLOR_YELLOW 2 class Rose : public LivesInterface { protected: // 꽃잎의 갯수 int petal = 4; // 꽃의 색상 int color = ROSE_COLOR_RED; public: Rose(int petal, int color); virtual ~Rose(); int getPetal(); int getColor(); virtual void printToConsole(); //생물종에 대한 순수 가상함수 구현 virtual const char* getSpeciesString(); }; #endif <file_sep>#pragma once #include"graphic.h" #include"keyboard.h" #include"DDS.h" #include "GameObject.h" //#include <iostream><file_sep>#include"Player.h" Player::Player():GameObject(245,550,"Player",0){ } Player::~Player() { } void Player::init() { using namespace std; ////////플레이어 그림 로드///////// // cout << " 플레이어 init" << endl; DDS_FILE* dds = readDDS("dds/player.dds"); float x = dds->header.dwWidth * 0.5; float y = dds->header.dwHeight * 0.5; setAnchor(x, y); setDDS(dds); ////////////플레이어 변수//////////// speed = 100; //1초에 100픽셀 이동 } void Player::update() { float dist = getDeltaTime(); dist = speed * getDeltaTime(); if (GetKey(VK_LEFT)) { translate(-dist, 0); //float x = getPx() - dist; //float y = getPy(); //setXY(x, y); } if (GetKey(VK_RIGHT)) { translate(dist, 0); } if (GetKey(VK_UP)) { translate(0, -dist); } if (GetKey(VK_DOWN)) { translate(0, dist); } ////////레이저 발사 기능 추가////////// if (GetKey(VK_SPACE)) { using namespace std; //cout << " 플레이어 레이저 발사" << endl; //(1) 플레이어 레이저 클래스 //(2) 플레이어 레이저 객체생성 <== 클래스에서 //PLaser* o = new PLaser; //레이저 위치 변경하기////////////// //(1) 현재 플레이어 위치 구하기 float x = getPx(); //플레이어 위치 float y = getPy()-65; //(2) 플레이어 위치에 따라서 레이저 위치 변경하기 //o->setXY(x, y); //(3) 객체 풀에 추가 //addGameObj(o); setKeyCode(VK_SPACE); addGameObj(new PLaser(getPx(),getPy())); } else { setKeyCode(NULL); } } <file_sep>#include"GameObject.h" GameObject::GameObject(float px, float py, const char* name, int tag) { this->px = px; this->py = py; this->name = name; this->tag = tag; this->dds = NULL; this->alive = true; } GameObject::~GameObject() { if (dds != NULL) { delete dds; dds = NULL; } } void GameObject::init() { /****************************************************** //DDS 읽어오기///// dds = readDDS("dds/player.dds"); //회전 시키기 공식 /////이미지의 중점에 앵커(회전시킬때의 중심)를(을) 설정함///// ax = dds->header.dwWidth*0.5; //그림의 가로축의 중간 ay = dds->header.dwHeight*0.5; //그림의 세로축의 중간 ********************************************************/ } void GameObject::update() { } void GameObject::translate(float x, float y) { px = px + x; py = py + y; } void GameObject::render() { if (dds != NULL) { //////이미지 그림 그리기/////// BYTE * data = dds->data; for (int y = 0; y < dds->header.dwHeight; y++){ for (int x = 0; x < dds->header.dwWidth; x++){ BYTE a = data[3]; BYTE r = data[2]; BYTE g = data[1]; BYTE b = data[0]; setPixel(px + x-ax, py + y -ay, r, g, b); data = data + 4; } } } } bool GameObject::checkCollision(GameObject* target) { return false; } void GameObject::dead_Alive() { alive = false; } bool GameObject::getAlive() { return alive; } const char* GameObject::getName() { return name; } int GameObject::getTag() { return tag; } float GameObject::getPx() { return px; } float GameObject::getAx() { return ax; } float GameObject::getAy() { return ay; } void GameObject::setAnchor(float x, float y) { this -> ax = x; this -> ay = y; } float GameObject::getPy() { return py; } void GameObject::setDDS(DDS_FILE* dds) { this->dds = dds; } void GameObject::setName(const char* name) { this->name = name; } void GameObject::setTag(int tag) { this->tag = tag; } void GameObject::setXY(float x, float y) { this->px = x; this->py = y; } <file_sep>#include"Enemy.h" Enemy::Enemy() :GameObject(244,100,"enemy",1) { } Enemy::~Enemy() { } void Enemy::init() { DDS_FILE* dds = readDDS("dds/enemy2.dds"); float x = dds->header.dwWidth*0.5; float y = dds->header.dwHeight*0.5; setAnchor(x, y); setDDS(dds); fireTime = 0; fireRate = 1; speed = 150; } void Enemy::update() { float dist; float x = getPx(); //에너미의 현재 x-축 좌표를 구한다. float y = getPy(); //에너미의 현재 y-축 좌표를 구한다. if (getPx() > 425) { speed = -speed; } else if (getPx() < 45) { speed = -speed; } dist = 0.01*speed; translate(dist, 0); ///////////레이져 발사 기능/////////////// /* fireTime = fireTime + getDeltaTime(); //발사 시간을 구하기 위해서 시간을 계속 측정한다. if (fireTime >= fireRate) { addGameObj(new ELaser(x, y+ 65)); fireTime = 0; } */ } <file_sep>#ifndef __HUMAN_H__ #define __HUMAN_H__ #include"LivesInterface.h" class Human : public LivesInterface { public: enum Race{ WHITE = 0, BLACK, ASIAN }; protected: //인종 Race race; //국가명 const char* country; public: Human(LivesInterface::Origin origin, Race race, const char* name, const char* country); virtual ~Human(); Race getRace(); const char* getCountry(); void setCountry(const char* country); virtual void printToConsole(); //생물 종에 대한 순수 가상함수 구현 virtual const char* getSpeciesString(); }; #endif <file_sep>#ifndef __LIVES_INTERFACE_H__ #define __LIVES_INTERFACE_H__ #include<iostream> class LivesInterface { public: enum Origin { ASIA=0,AFRICA,EUROPE,AMERICA,EVERYWHERE,UNKNOWN }; struct Position { float x; float y; }; protected: Position position; Origin origin; const char* name; public: LivesInterface(Origin origin); LivesInterface(Origin origin, const char* name); //클래스의 생성자 //소멸자를 정의한다. virtual ~LivesInterface(); //이름 const char* getName(); Origin getOrigin(); //현재 위치를 Reference 형태로 반환한다. Position& getPosition(); void setPosition(Position position); void setPosition(float x, float y); virtual void printToConsole(); //이 생물이 어떤한 종에 속해있는지를 리턴해야 하는 순수가상함수 virtual const char* getSpeciesString() = 0; }; #endif<file_sep>#include"DDS.h" DDS_FILE* readDDS(const char* filename) { FILE* fp = NULL; DDS_FILE* DDS = NULL; errno_t errnno; int size; if ((errnno = fopen_s(&fp, filename, "rb")) != 0) { fprintf(stderr, "파일 열기 실패: file %s errno %d\n", filename, errnno); return NULL; } fseek(fp, 0, SEEK_END); size = ftell(fp); fseek(fp, 0, SEEK_SET); if ((DDS = (DDS_FILE*)new BYTE[size]) == NULL) { fprintf(stderr, "메모리를 할당 받지 못함\n"); fclose(fp); return NULL; } fread(DDS, size, 1, fp); fclose(fp); return DDS; } DDS_FILE* readDDSRect(const char* filename, int x, int y, int width, int height) { FILE* fp = NULL; DDS_FILE* DDS = NULL; errno_t errno_d; int header_size; int total_size; //////파일 열기////// if ((errno_d = fopen_s(&fp, filename, "rb")) != 0) { fprintf(stderr, "파일 열기 실패:file %s errno %d\n", filename, errno_d); return NULL; } ///////전체 파일이 아닌 읽어올 이미지 크기에 맞춰서 메모리 크기를 구함/////// header_size = sizeof(DWORD) + sizeof(DDS_HEADER); //이미지 영역을 제외한 파일 헤더 크기 total_size = header_size + width * height * 4; //읽어올 이미지 크기를 추가한 전체 크기 //필요할 만큼 메모리를 할당 받는다. - 전체 파일 크기가 아닌.. 읽어올 이미지 크기와 헤더 크기만큼 if ((DDS = (DDS_FILE*)new BYTE[total_size]) == NULL) { fprintf(stderr, "메모리를 할당 받지 못함\n"); fclose(fp); //전체 블록 읽기를 한다 - 바이너리 모드 읽기 return NULL; } ////////파일에 헤더만 읽어옴-이미지의 위치를 찾아서 특정 영역만 읽어와야 한다//////// fread(DDS, header_size, 1, fp); ////////파일에서 원하는 영역을 읽기 위한 변수 계산///////// int imgSize = width * height * 4; //로드할 이미지 데이타 크기 int lineSize = width * 4; //로드할 이미지 한줄 데이타 크기 int stride = DDS->header.dwPitchOrLinearSize; //파일의 이미지 한줄 데이타 크기 int offset = y * stride + x * 4; //파일의 이미지 로드 시작 위치 int lineGap = stride - lineSize; //파일과 이미지 한줄 데이타 크기의 차 fseek(fp, offset, SEEK_CUR); //데이타 읽기 시작 위치로 이동 for (int k = 0; k < height; k++) { fread(&DDS->data[k * width * 4], lineSize, 1, fp); //파일에서 한줄을 읽는다. fseek(fp, lineGap, SEEK_CUR); //파일에서 읽고 남은 줄을 건너뛰고.. 다음 읽을 위치로 이동한다. } /////실제 읽어온 이미지의 크기로.. 이미지 크기를 변경함///// DDS->header.dwHeight = height; DDS->header.dwWidth = width; /////파일 닫기///// fclose(fp); return DDS; }<file_sep>//#include<iostream> #include "main.h" int main() { /////장치 초기화 하기///////// initGraphic(); initKey(); initTimer(); initPool(); //게임 오브젝트 관리 풀을 초기화함 system("mode 100, 80"); //콘솔창 크기 조정 addGameObj(new Player()); addGameObj(new Enemy()); //getSize(); //풀에 들어있는 오브젝트 갯수 ///////업데이트 반복///////// while (true) { clear(0, 0, 255); updateKey(); updateTimer(); /////////////////// //게임객체 업데이트 for (int i = 0; i < getSize(); i++) { GameObject* o = getGameObj(i); // 객체를 받아옴 0번부터 getSize까지 if (o != NULL) { o->update(); // 받아온 객체를 업데이트 if (o->getName() == "Player") { if (o->getKeyCode() == VK_SPACE) { addGameObj(new PLaser(o->getPx(), o->getPy())); } } o->render(); } } render(); deleteArray(); } return 0; }<file_sep>#pragma once #include "header.h" class PLaser : public GameObject { private: float speed; public: PLaser(); //플레이어 레이져 생성자 PLaser(float x, float y); virtual ~PLaser(); //플레이어 레이져 소멸자 virtual void init(); //플레이어 레이져 초기화 정보 virtual void update(); };<file_sep>#include"pool.h" GameObject* obj[MAX]; //Max는 배열의 최대 크기 int arraySize; //size는 현재까지 추가된 오브젝트의 갯수 void initPool() { ////풀 초기화 함수//// for(int i=0; i<MAX; i++){ obj[i] = NULL; //NULL 은 아직 오브젝트가 들어 있지 않음 } ////풀에 빈자리를 지정하는 변수//// arraySize = 0; } void deleteArray() { for (int i = 0; i < getSize(); ) // 3 { if (obj[i]->getAlive() == false) { //지우기 deleteGameObj(i); //delete obj[i]; //obj[i] = NULL; printf(" delete = %d\n", arraySize); for (int k = i; k <= getSize()-1; k++) { obj[k] = obj[k + 1]; } minus_size(); } else { i++; } } } void deleteGameObj(int index) { delete obj[index]; obj[index] = NULL; } void addGameObj(GameObject* o) { if (arraySize < MAX) { //최대 풀의 공간을 확인 obj[arraySize] = o; obj[arraySize]->init(); //게임객체가 게임에 추가되어서 시작함 // printf(" create = %d\n", arraySize); arraySize++; } } int getSize() { return arraySize; //현재까지 배열에 들어 있는 객체 갯수 } void minus_size() { arraySize--; } GameObject* getGameObj(int i) { if (i < arraySize) { return obj[i]; } else { //만약 i가 size보다 작으면 아직 만들어지지 않았음을 뜻함으로 NULL을 넣어준다. return NULL; } }<file_sep>#ifndef __MALTESE_H__ #define __MALTESE_H__ #include"Dog.h" class Maltese : public Dog { public: Maltese(const char* name); virtual ~Maltese(); virtual void printToConsole(); virtual const char* getSpeciesString(); }; #endif <file_sep>#pragma once #include<Windows.h> #include <stdio.h> #include"graphic.h" #define DDPF_ALPHAPIXELS 0x00000001 #define DDPF_RGB 0x0000040 struct DDS_PIXELFORMAT { DWORD dwSize; DWORD dwFlags; DWORD dwFourCC; DWORD dwRGBBitCount; DWORD dwRBitMask; DWORD dwGBitMask; DWORD dwBBitMask; DWORD dwABitMask; }; struct DDS_HEADER { DWORD dwSize; DWORD dwFlags; DWORD dwHeight; DWORD dwWidth; DWORD dwPitchOrLinearSize; DWORD dwDepth; DWORD dwMipMapCount; DWORD dwReserved1[11]; DDS_PIXELFORMAT ddspf; DWORD dwCaps; DWORD dwCaps2; DWORD dwCaps3; DWORD dwCaps4; DWORD dwReserved2; }; struct DDS_FILE { DWORD magic; DDS_HEADER header; BYTE data[1]; }; DDS_FILE* readDDS(const char* filename); DDS_FILE* readDDSRect(const char* filename, int x, int y, int width, int height);<file_sep>#include<stdio.h> #include"direct2d.h" #define WIDTH 1400 #define HEIGHT 750 ///////DirectDraw 라이브러리 추가/////////// #pragma comment(lib,"ddraw.lib") //DirectDraw 함수 라이브러리 #pragma comment(lib,"dxguid.lib") //DirectDraw ID 저장 라이브러리 //DirectDraw를 사용하기 위해서는 라이브러리를 추가해야 한다. "ddraw.lib"는 //DirectDraw를 사용할 수 있는 모든 기능을 제고하고, "dxguid.lib"는 그래픽 장치/버퍼를 //구분하기 위하여 아이디 정보를 제공해 준다. HWND Direct2D::hWnd = NULL; //윈도우 핸들 unsigned int* Direct2D::BackBuffer = NULL; //백 버퍼 주소 저장 포인터 IDirectDraw7* Direct2D::IDirectDraw = NULL; //DirectDraw 장치 주소 저장 포인터 IDirectDrawSurface7* Direct2D::IDDPriSurf = NULL; //화면 출려 버퍼 객체(COM)주소(인터페이스)저장 포인터 IDirectDrawSurface7* Direct2D::IDDBackSurf = NULL; //그림 그리기 버퍼 객체(COM)주소(인터페이스)저장 포인터 int Direct2D::width = 0; //백퍼버의 실제 가로 크기 int Direct2D::height = 0; //백버퍼의 실제 세로 크기 //C++에서 클래스 안에 선언된 정적 멤버 변수는 실제로 변수가 만들어 지지는 않는다. //즉, (벽수가 정의 되지는 않음). 실제 변수를 만들기 위해서는 클래스 외부에서 변수를 정의하고 필요하면 초기화 해야 한다. bool Direct2D::init(int width, int height, HWND hWnd) { //전달된 변수를 클래스의 정적 변수에 저장한다. - 저장하고 이후에 필요할 때 사용함 Direct2D::width = width; Direct2D::height = height; Direct2D::hWnd = hWnd; HRESULT hr; //HRESULT는 윈도우에서 사용하는 함수 성공/실패 반환 데이타 형임 //DirectDraw 장치를 생성하고 생성된 장치 포인터를 저장한다. hr = DirectDrawCreateEx(NULL, //GUID의 값을 반환 받음 (LPVOID*)&(Direct2D::IDirectDraw), //객체 인터페이스(포인터)를 반환 받음 IID_IDirectDraw7, //DirectDraw7 구분 아이디 - dxguid.lib에 저장됨 NULL); if (FAILED(hr)) { //FAILED는 HRESULT를 반환된 값이 실패 인지를 체크하는 매크로 함수임 printf("DirectDraw7 장치 생성 실패"); return false; } //생성된 DirectDraw는 그림을 출력할 윈도우 창과 연결되어야 한다. SetCooperativeLevel 은 장치와 윈도우 창이 연결 되어서 서로 //협력 동작하는 방식을 결정한다. hr = Direct2D::IDirectDraw->SetCooperativeLevel(Direct2D::hWnd, DDSCL_NORMAL); if (FAILED(hr)) { printf("협력 레벨 설정 실패"); return false; } //화면 출력 버퍼 - Primary Surface 만들기 DDSURFACEDESC2 DESC; ZeroMemory(&DESC, sizeof(DESC)); //ZeroMemory는 특정 메모리 영역을 0을 초기화 해주는 Window API 함수임 DESC.dwSize = sizeof(DESC); DESC.dwFlags = DDSD_CAPS; //ddsCaps 구조체를 사용함 DESC.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE; //프라이머리 Surface를 만듬 hr = Direct2D::IDirectDraw->CreateSurface(&DESC, &Direct2D::IDDPriSurf, NULL); if (FAILED(hr)) { printf("프라이머리 서피스 생성 실패"); return false; } //그림 그리는 백 버퍼 - Back Surface 만들기 ZeroMemory(&DESC, sizeof(DESC)); DESC.dwSize = sizeof(DESC); DESC.dwFlags = DDSD_WIDTH | DDSD_HEIGHT | DDSD_CAPS | DDSD_PIXELFORMAT; DESC.dwWidth = Direct2D::width; DESC.dwHeight = Direct2D::height; DESC.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN | DDSCAPS_SYSTEMMEMORY; DESC.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT); DESC.ddpfPixelFormat.dwFlags = DDPF_RGB; DESC.ddpfPixelFormat.dwRGBBitCount = 32; //픽셀의 비트 크기 (32비트 - 4바이트) DESC.ddpfPixelFormat.dwRBitMask = 0x00FF0000; //픽셀에서 R 값 위치 DESC.ddpfPixelFormat.dwGBitMask = 0x0000FF00; //픽셀에서 G 값 위치 DESC.ddpfPixelFormat.dwBBitMask = 0x000000FF; //픽셀에서 B 값 위치 DESC.ddpfPixelFormat.dwRGBAlphaBitMask = 0xFF000000; //픽셀에서 Alpha 값 위치 hr = Direct2D::IDirectDraw->CreateSurface(&DESC, &(Direct2D::IDDBackSurf), NULL); if (FAILED(hr)) { printf("백 서피스 생성 실패"); return false; } return true; } void Direct2D::exit() { #define ReleaseCOM(x){if(x!=NULL)x->Release(); x=NULL;}; ReleaseCOM(Direct2D::IDDBackSurf); ReleaseCOM(Direct2D::IDDPriSurf); ReleaseCOM(Direct2D::IDirectDraw); //DirectDraw 에서 사용되는 객체는 일반 C++ 객체와는 다른 COM 객체로 생성된다. //COM 객체는 객체에서 제공하는 Release 메소드를 호출해서 //객체를 지워야 한다(COM 객체는 delete는 사용 할 수없음) } void Direct2D::render() { POINT pt; Direct2D::IDDBackSurf->Unlock(NULL); //백버퍼를 전송할 수 있게 잠금을 해제한다. pt.x = 0; pt.y = 0; ClientToScreen(Direct2D::hWnd, &pt); //출력할 영역의 우치를 구해온다. - 메뉴/테두리 영역을 제외한 그림 출력 영역 위치를 구함 Direct2D::IDDPriSurf->BltFast(pt.x, pt.y, Direct2D::IDDBackSurf, NULL, 0); //백 버퍼의 내용을 프라이머리 버퍼로 전송한다. } void Direct2D::setPixel(int x, int y, unsigned int col) { if( (Direct2D::height > y&&y >= 0) && (Direct2D::width > x&&x >= 0)){ BackBuffer[y*Direct2D::width + x] = col; } } void Direct2D::clear(unsigned int col) { DDSURFACEDESC2 DESC; //백 버퍼의 정보를 가져오기 위한 구조체 ZeroMemory(&DESC, sizeof(DESC)); DESC.dwSize = sizeof(DESC); if (Direct2D::IDDBackSurf->Lock(NULL, &DESC, DDLOCK_WAIT, NULL) == DD_OK) { BackBuffer = (unsigned int*)DESC.lpSurface; Direct2D::width = DESC.dwLinearSize >> 2; //내부 버퍼의 크기 DESC.dwLinearSize는 바이트 단위임 Direct2D::height = DESC.dwHeight; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { BackBuffer[y*width + x] = col; } } } } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM IParam) { PAINTSTRUCT ps; //윈도우 창 화면에 그리기를 할 정보를 저장하는 구조체 HDC hdc; //화면 그리기 장치 정보 핸드 -Device Context Handle switch (message) { case WM_COMMAND: //사용자 메뉴 입력 처리 부분 break; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); EndPaint(hWnd, &ps); break; case WM_DESTROY: PostQuitMessage(0); //윈도우 종료 처리 break; default: return DefWindowProc(hWnd, message, wParam, IParam); } return 0; } void START_DEBUG_CONSOLE() { AllocConsole(); //윈도우에서 콘솔창 시작하기 함수 } void STOP_DEBUG_CONSOLE() { FreeConsole(); //윈도우에서 콘솔창 종료하기 함수 } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM IParam); int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE hprevInstance, LPWSTR IpCmdLine, int nCmdShow) { ///////윈도우 클래스 등록//////// WNDCLASSEXW wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; //윈도우 클래스 스타일 - 가로/세로 방향 그리기 스타일 wcex.lpfnWndProc = WndProc; //윈도우 창의 메뉴/마우스 이벤트 처리 함수 등록 wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; //이 윈도우 클래스를 관리하는 어플리케이션 인스턴스핸들 wcex.hIcon = nullptr; //아이콘 이미지 등록 - 현재 없음 wcex.hCursor = LoadCursor(nullptr, IDC_ARROW); //커서 형태 등록 - 화살표 아이콘 wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);//윈도우 바탕색 지정 wcex.lpszMenuName = nullptr; //윈도우 메뉴 등록 - 현재 없음 wcex.lpszClassName = L"MyWndClass"; //등록된 클래스의 이름 - 윈도우를 만들때 참조됨-L은 2바이트 문자열 wcex.hIconSm = nullptr; //작은 아이콘 등록 - 현재 없음 RegisterClassExW(&wcex); HWND hWnd = CreateWindowW(L"MyWndClass", //윈도우를 생성하기 위한 클래스 - 위에서 등록한 클래스 L"윈도우창", //생성되는 윈도우의 이름 WS_OVERLAPPEDWINDOW, //생성되는 윈도우의 형식 - 기존 위도우 형식임 CW_USEDEFAULT, //시작 위치와 윈도우 크기 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, //생성된 윈도우 창을 과닐하는 프로그램 인스턴스 nullptr); if (hWnd != nullptr) { ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); } START_DEBUG_CONSOLE(); printf("디버깅 콘솔창을 시작 합니다."); ///////DirectDraw 디바이스 초기화//////// Direct2D::init(WIDTH, HEIGHT, hWnd); ///////윈도우 메시지 반복 처리하기///////// MSG msg = { 0, }; //사용자 입력 - 메뉴/마우스/키보드 등의 이멘트(메시지)를 받아오는 구조체 while (GetMessage(&msg, nullptr, 0, 0) == TRUE) { //반복적으로 원영체제에서 메시를 받아온다. TranslateMessage(&msg); //메시지 전잘전에 필요한 처리를 한다. DispatchMessage(&msg); //처리된 메시지를 해당 윈도우 창에 전달한다. Direct2D::clear(0x000000FF); //백 버퍼를 파란색으로 초기화 한다. Direct2D::render(); //백 버퍼를 프라이머리 버퍼로 전송 - 화면에 출력된다. } /////////DirectDraw 디바이스 종료////////////// Direct2D::exit(); ////////콘솔창 종료하기//////////////////// STOP_DEBUG_CONSOLE(); return (int)msg.wParam; } <file_sep>#include<stdio.h> #include<windows.h> void initKey(); void updateKey(); bool GetKey(int keyCode); bool GetKeyDown(int keyCode); void initTimer(); void updateTimer(); float getDeltaTime(); void gotoxy(int x, int y); void hide(); <file_sep>#include"Maltese.h" #include<cstdio> Maltese::Maltese(const char* name) : Dog(LivesInterface::Origin::EVERYWHERE, name) { setColor(FUR_COLOR_WHITE); } Maltese::~Maltese() {} void Maltese::printToConsole() { using namespace std; cout << "우리 귀여운 말티즈~" << endl; Dog::printToConsole(); cout << endl; } const char* Maltese::getSpeciesString() { return "말티즈"; } <file_sep>#pragma once #include "header.h" #include "pool.h" #include "Player.h" #include "Enemy.h" #include "PLaser.h" #include "ELaser.h" //#include<iostream><file_sep>#include"Dog.h" #include<cstdio> #include<cstring> Dog::Dog(LivesInterface::Origin origin, const char* name) :LivesInterface(origin, name) { ownerName = new char[100]; } Dog::~Dog() { delete[] ownerName; } void Dog::setColor(int furColor) { this->furColor = furColor; } void Dog::setOwnerName(const char* ownerName) { strcpy_s(this->ownerName, 100, ownerName); }<file_sep>#pragma once #include "header.h" #define MAX 100 void initPool(); void addGameObj(GameObject* o); void deleteGameObj(int index); void deleteArray(); int getSize(); void minus_size(); GameObject* getGameObj(int i); extern GameObject* obj[MAX]; //Max는 배열의 최대 크기 extern int arraySize; //size는 현재까지 추가된 오브젝트의 갯수<file_sep>#pragma once #include<ddraw.h> class Direct2D { private: static HWND hWnd; //윈도우 핸들 static unsigned *BackBuffer; //백 버퍼 주소 static IDirectDraw7 *IDirectDraw; //DirectDraw 장치 주소 저장 포인터 static IDirectDrawSurface7 *IDDPriSurf; //화면 출력 버퍼 객체(COM)주소(인터페이스)저장 포인터 static IDirectDrawSurface7 *IDDBackSurf;//그림 그리기 버퍼 객체(COM)주소(인터페이스)저장 포인터 static int width; //백버퍼의 실제 가로 크기 static int height; //백버퍼의 실제 세로 크기 public: static bool init(int width, int height, HWND hWnd); //그래픽 초기화 메소드 static void exit(); //그래픽 종료 메소드 static void clear(unsigned int col); //화면지우기 - 백버퍼를 지움 static void render(); //백 버퍼를 화면으로 출력 static void setPixel(int x, int y, unsigned int col); //픽셀 출력 static unsigned int getPixel(int x, int y); //픽셀 가져오기 static HWND getHwnd(); //윈도우 핸들 가져오기 };<file_sep>#pragma once #include "header.h" //#include<iostream> class Enemy : public GameObject { private: //Àû±â º¯¼ö float speed; float fireRate; float fireTime; public: Enemy(); virtual ~Enemy(); virtual void init(); virtual void update(); };<file_sep>#include "graphic.h" //화면 출력이전에 그림을 그리는 백버퍼 배열임 unsigned int BackBuffer[HEIGHT][WIDTH]; unsigned int rgb(int r, int g, int b) { unsigned int rgb = ((unsigned int)r) << 16 | ((unsigned int)g) << 8 | ((unsigned int)b) << 0; return rgb; } void setPixel(int x, int y, unsigned int col) { //범위 검사 추가 if (0 <= y && y <HEIGHT) //y 좌표값을 검사 { if (0 <= x && x < WIDTH) { BackBuffer[y][x] = col; } } } unsigned int getPixel(int x, int y) { //범위 검사 추가 if (0 <= y && y <HEIGHT) //y 좌표값을 검사 { if (0 <= x && x < WIDTH) { return BackBuffer[y][x]; } } return 0; } void setPixel(int x, int y, int r, int g, int b) { //범위 검사 추가 if (0 <= y && y <HEIGHT) //y 좌표값을 검사 { if (0 <= x && x < WIDTH) { BackBuffer[y][x] = rgb(r, g, b); } } } void drawLine(int x0, int y0, int x1, int y1, unsigned int col) { int temp1; int temp2; //(A)수평선 그리기 인지를 판단하여, 수평선 그리기이면 .... if (y0 == y1) { //(A.a) 시작점(x0, y0) 이 끝점(x1, y1) 보다 오른쪽이면 끝점과 시작점을 바꾼다. if (x0 > x1) { temp1 = x0; x0 = x1; x1 = temp1; temp2 = y0; y0 = y1; y1 = temp2; } //(A.b) 수평선 그리기한다. (위 그림의(1) 수평그리기 참고) for (int x = x0; x <= x1; x++) { setPixel(x, y0, col); } } //(B) 수직선 그리기인지를 판단한다, 수직선 그리기 이면.... else if (x0 == x1) { //(B.a) 시작점(x0, y0) 이 끝점(x1, y1) 보다 아래쪽 이면 끝점과 시작점을 바꾼다. if (y0 > y1) { temp1 = x0; x0 = x1; x1 = temp1; temp2 = y0; y0 = y1; y1 = temp2; } //(B.b) 수직선 그리기한다. (위 그림의(3) 수직 그리기 참고) for (int y = y0; y <= y1; y++) { setPixel(x0, y, col); //col 값은 각자가 선택함 } } //(C) 수직 / 수평선 그리기가 아니면..입력 점(시작점 끝점)으로 기울기를 구한다. (기울기 변수 는 실수형으로 함) else { float m = (float)(y1 - y0) / (float)(x1 - x0); //(D) 기울기가 - 1 에서 + 1 사이에 있는지 판단하여...기울기가 - 1 에서 + 1 사이이면... if (-1 <= m && m <= 1) { //(D.a) 시작점(x0, y0)이 끝점(x1, y1) 보다 오른쪽이면..끝점과 시작점을 바꾼다. if (x0 > x1) { temp1 = x0; x0 = x1; x1 = temp1; temp2 = y0; y0 = y1; y1 = temp2; } //(D.b) 기울기가 - 1 ~+ 1 인 직선을 그린다. (위 그림(5) 번 그리기 참고) for (int x = x0; x <= x1; x++) { setPixel(x, (int)(y0 + (x - x0)*m + 0.5), col); } } //(E) 나머지 경우이면..(기울기가 - 1 이하, +1 이상인 직선이면 else { //(E.a) 시작점(x0, y0)이 끝점(x1, y1) 보다 아래쪽이면..끝점과 시작점을 바꾼다. if (y0 > y1) { temp1 = x0; x0 = x1; x1 = temp1; temp2 = y0; y0 = y1; y1 = temp2; } //(E.b) 기울기가 - 1 이하, +1 이상인 직선을 그린다. (위 그림(7) 번 그리기 참고) for (int y = y0; y <= y1; y++) { setPixel((int)(x0 + (y - y0) * 1 / m + 0.5), y, col); //col 값은 각자가 선택함 } } } } void drawLine(int x0, int y0, int x1, int y1, int r, int g, int b) { drawLine(x0, y0, x1, y1, rgb(r, g, b)); } void drawCircle(int cx, int cy, int r, unsigned int col) { int x = 0, y = 0; for (x = 0; x <= y; x++) { y = (int)(sqrt(r*r - x * x) + 0.5); // y 축 좌표를 계산한다. setPixel(cx + x, cy + y, col); //(1)계산된 (x,y) 좌표에 픽셀을 출력한다. setPixel(cx + x, cy - y, col); //(2)픽셀의 출력은 원점(cx, cy) 만큼 setPixel(cx - x, cy + y, col); // 평행 이동 시킨다. setPixel(cx - x, cy - y, col); setPixel(cx + y, cy + x, col); setPixel(cx + y, cy - x, col); setPixel(cx - y, cy + x, col); setPixel(cx - y, cy - x, col); } } void drawCircle(int cx, int cy, int radius, int r, int g, int b) { drawCircle(cx, cy, radius, rgb(r, g, b)); } /////////////////////////////////////////////////////////////////////////////////////////// //아래의 함수는 단순 실습용입니다. 게임 제작에 사용되지 않으므로..기능을 이용만함 /////////////////////////////////////////////////////////////////////////////// HWND hWnd = NULL; void initGraphic() { HWND GetConsoleHwnd(); //커서 숨기기 HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_CURSOR_INFO info; info.dwSize = 100; info.bVisible = FALSE; SetConsoleCursorInfo(consoleHandle, &info); //그래픽 모들 핸들러를 구해옴 hWnd = GetConsoleHwnd(); } void clear(unsigned int col) { for (int j = 0; j < HEIGHT; j++) { for (int i = 0; i < WIDTH; i++) { BackBuffer[j][i] = col; //배열을 지운다 } } } void clear(int r, int g, int b) { clear(rgb(r, g, b)); } void render() { HDC hDC, hMemDC; HBITMAP hBmp; void * pBmp = NULL; int size; hDC = GetDC(hWnd); hMemDC = CreateCompatibleDC(hDC); size = WIDTH * HEIGHT * 4; BITMAPINFO bi; ZeroMemory(&bi, sizeof(BITMAPINFO)); bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bi.bmiHeader.biWidth = WIDTH; bi.bmiHeader.biHeight = -HEIGHT; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biBitCount = 32; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biSizeImage = 0; bi.bmiHeader.biXPelsPerMeter = 0; bi.bmiHeader.biYPelsPerMeter = 0; bi.bmiHeader.biClrUsed = 0; bi.bmiHeader.biClrImportant = 0; hBmp = CreateDIBSection(hDC, &bi, DIB_RGB_COLORS, &pBmp, NULL, 0); SelectObject(hMemDC, hBmp); CopyMemory(pBmp, BackBuffer, size); BitBlt(hDC, STARTX, STARTY, WIDTH, HEIGHT, hMemDC, 0, 0, SRCCOPY); DeleteObject(hBmp); DeleteDC(hMemDC); DeleteObject(hDC); } inline void getARGB(unsigned int color, unsigned char* a, unsigned char* r, unsigned char* g, unsigned char* b) { *a = (color >> 24) & 0xff; *r = (color >> 16) & 0xff; *g = (color >> 8) & 0xff; *b = (color >> 0) & 0xff; } inline unsigned int makeARGB(unsigned char a, unsigned char r, unsigned char g, unsigned char b) { return (a << 24) || (r << 16) || (g << 8) || (b << 0); } inline unsigned int pixelBlierp(unsigned int c00, unsigned int c10, unsigned int c01, unsigned int c11, float dx, float dy) { unsigned char A[4]; unsigned char B[4]; unsigned char C[4]; unsigned char D[4]; getARGB(c00, &A[0], &A[1], &A[2], &A[3]); getARGB(c10, &B[0], &B[1], &B[2], &B[3]); getARGB(c01, &C[0], &C[1], &C[2], &C[3]); getARGB(c11, &D[0], &D[1], &D[2], &D[3]); float x1; float x2; float x[4]; for (int i = 0; i < 4; i++) { x1 = A[i] * (1 - dx) + B[i] * dx; x2 = C[i] * (1 - dx) + D[i] * dx; x[i] = x1 * (1 - dy) + x2 * dy; } return makeARGB((unsigned char)x[0], (unsigned char)x[1], (unsigned char)x[2], (unsigned char)x[3]); } unsigned int getImagePixel(DDS_FILE* image, float x, float y) { float x0 = 0.0f; float y0 = 0.0f; float x1 = image->header.dwWidth - 2.0f; float y1 = image->header.dwHeight - 2.0f; if ((x1 >= x && x >= x0) && (y1 >= y && y >= y0)) { int xp = (int)floor(x); int yp = (int)floor(y); float dx = x - xp; float dy = y - yp; unsigned int A = image->data[(yp + 0)*image->header.dwWidth + (xp + 0)]; unsigned int B = image->data[(yp + 0)*image->header.dwWidth + (xp + 1)]; unsigned int C = image->data[(yp + 1)*image->header.dwWidth + (xp + 0)]; unsigned int D = image->data[(yp + 1)*image->header.dwWidth + (xp + 1)]; return pixelBlierp(A, B, C, D, dx, dy); } return 0x00000000; } unsigned int alphaBlending(unsigned int c0, unsigned int c1) { unsigned char C[4]; unsigned char B[4]; getARGB(c0, &C[0], &C[1], &C[2], &C[3]); getARGB(c1, &B[0], &B[1], &B[2], &B[3]); unsigned char A = C[0]; unsigned char r = (unsigned char)((A*C[1] + (255 - A)*B[1])/ 255.0f); unsigned char g = (unsigned char)((A*C[2] + (255 - A)*B[2])/ 255.0f); unsigned char b = (unsigned char)((A*C[3] + (255 - A)*B[3])/ 255.0f); return makeARGB(B[0], r, g, b); } #ifdef GRAPHIC_MODE_0 HWND GetConsoleHwnd() { #define MY_BUFSIZE 1024 // Buffer size for console window titles. HWND hwndFound; // This is what is returned to the caller. WCHAR pszNewWindowTitle[MY_BUFSIZE]; // Contains fabricated // WindowTitle. WCHAR pszOldWindowTitle[MY_BUFSIZE]; // Contains original // WindowTitle. // Fetch current window title. GetConsoleTitle(pszOldWindowTitle, MY_BUFSIZE); // Format a "unique" NewWindowTitle. wsprintf(pszNewWindowTitle, "%d/%d", GetTickCount(), GetCurrentProcessId()); // Change current window title. SetConsoleTitle(pszNewWindowTitle); // Ensure window title has been updated. Sleep(40); // Look for NewWindowTitle. hwndFound = FindWindow(NULL, pszNewWindowTitle); // Restore original window title. SetConsoleTitle(pszOldWindowTitle); return(hwndFound); } #else HWND GetConsoleHwnd() { #define MY_BUFSIZE 1024 // Buffer size for console window titles. HWND hwndFound; // This is what is returned to the caller. CHAR pszNewWindowTitle[MY_BUFSIZE]; // Contains fabricated // WindowTitle. CHAR pszOldWindowTitle[MY_BUFSIZE]; // Contains original // WindowTitle. // Fetch current window title. GetConsoleTitle(pszOldWindowTitle, MY_BUFSIZE); // Format a "unique" NewWindowTitle. wsprintf(pszNewWindowTitle, "%d/%d", GetTickCount(), GetCurrentProcessId()); // Change current window title. SetConsoleTitle(pszNewWindowTitle); // Ensure window title has been updated. Sleep(40); // Look for NewWindowTitle. hwndFound = FindWindow(NULL, pszNewWindowTitle); // Restore original window title. SetConsoleTitle(pszOldWindowTitle); return(hwndFound); } #endif <file_sep>#pragma once #include <Windows.h> #include <math.h> #include"DDS.h" #define STARTX 0 //그래픽 화면의 시작 #define STARTY 0 //그래픽 화면의 시작 #define WIDTH 480 //그래픽 화면의 가로 크기 #define HEIGHT 720 //그래픽 화면의 세로 크기 //#define GRAPHIC_MODE_0 void initGraphic(); void clear(int r, int g, int b); void render(); void setPixel(int x, int y, int r, int g, int b); void drawLine(int x0, int y0, int x1, int y1, int r, int, int b); void drawCircle(int cx, int cy, int radius, int r, int g, int b); unsigned int getPixel(int x, int y); inline void getARGB(unsigned int color, unsigned char* a, unsigned char*r, unsigned char* g, unsigned char* b); inline unsigned int makeARGB(unsigned char a, unsigned char r, unsigned char g, unsigned char b); inline unsigned int pixelBlierp(unsigned int c00, unsigned int c10, unsigned int c01, unsigned int c11, float dx, float dy); unsigned int alphaBlending(unsigned int c0, unsigned int c1);<file_sep>#pragma once #include "header.h" class ELaser :public GameObject { private: float speed; public: ELaser(float px,float py); virtual ~ELaser(); //객체 생성 위치를 생성자로.. 받아올 수도 있음 virtual void init(); virtual void update(); };<file_sep>#include"Human.h" #include<cstdio> #include<string.h> Human::Human(LivesInterface::Origin origin, Race race, const char* name, const char* country):LivesInterface(origin,name) { this->race = race; this->country = country; } Human::~Human() { delete this->country; } Human::Race Human::getRace() { return this->race; } const char* Human::getCountry() { return this->country; } void::Human::setCountry(const char* country) { this->country = country; } void::Human::printToConsole() { LivesInterface::printToConsole(); using namespace std; cout << "국가명: " << this->country << endl; cout << "race: " << this->race << endl << endl; } const char* Human::getSpeciesString() { return "사람"; }<file_sep>#include"Rose.h" #include<cstdio> Rose::Rose(int petal, int color) :LivesInterface(LivesInterface::Origin::EUROPE, getSpeciesString()) { this->petal = petal; this->color = color; } Rose::~Rose() {} int Rose::getPetal() { return this->petal; } int Rose::getColor() { return this->color; } void Rose::printToConsole() { using namespace std; if (this->color == ROSE_COLOR_RED) { cout << "아름다운 그대에게 정열적인 빨간 장미를" << endl; } else if (this->color == ROSE_COLOR_YELLOW) { cout << "사랑하는 당신에게 귀여운 노란장미를" << endl; } LivesInterface::printToConsole(); cout << "꽃잎의 갯수: " << this->petal << endl<<endl; } const char* Rose::getSpeciesString() { return "장미"; }
3b1c73efb39c33ef8e6bc57c0c32e400955588fb
[ "C", "C++" ]
37
C++
HaeilSeo/Window
637b7cbe09e9410e1eb99c5a8293cafe2a7c0dcb
3b82a590c6d3cd44c4d5022fbbd3d749b86524e9
refs/heads/master
<repo_name>deanriverson/JudgeAdviser<file_sep>/src/app/judges/judge-list/judge-list.component.ts import {Component, OnInit} from "@angular/core"; import {AppStoreService} from "../../services/app-store.service"; import {Judge} from "../../models/judge"; import * as _ from "lodash"; @Component({ selector: 'app-judge-list', templateUrl: './judge-list.component.html', styleUrls: ['./judge-list.component.css'], providers: [AppStoreService] }) export class JudgeListComponent implements OnInit { private coreJudges: Judge[]; private robotJudges: Judge[]; private projectJudges: Judge[]; constructor(private store: AppStoreService) {} ngOnInit() { this.store.judgesObservable.subscribe(items => { let judges:Judge[] = items; this.robotJudges = _.filter(judges, j => j.role.indexOf('Robot') >= 0).sort(this._compareFn); this.projectJudges = _.filter(judges, j => j.role.indexOf('Project') >= 0).sort(this._compareFn); this.coreJudges = _.filter(judges, j => j.role.indexOf('Core') >= 0).sort(this._compareFn); }); } private _compareFn = (a, b) => { if (a.role.indexOf('Head') === 0) return -1; if (b.role.indexOf('Head') === 0) return 1; if (a.lastName < b.lastName) return -1; if (a.lastName > b.lastName) return 1; return 0; }; } <file_sep>/src/app/models/judge.ts export class Judge { constructor(readonly firstName: string, readonly lastName: string, readonly email: string, readonly phone: string, readonly role: string, readonly years: string, readonly teamAffiliation: string) {} } <file_sep>/src/app/models/tournament-info.ts export class TournamentInfo { $key: string; name = ''; } <file_sep>/src/app/deliberation/deliberation/deliberation.component.ts import {Component, OnInit} from '@angular/core'; import {AppStoreService} from "../../services/app-store.service"; import {Award} from "../../models/award"; import {Team, FirebaseTeam} from "../../models/team"; import * as _ from 'lodash'; @Component({ selector: 'app-deliberation', templateUrl: './deliberation.component.html', styleUrls: ['./deliberation.component.css'] }) export class DeliberationComponent implements OnInit { private awards: Award[]; private teams: Team[] = []; private sortedTeams: Team[]; private teamListDisplay: number; constructor(private store: AppStoreService) { store.awardsObservable.subscribe(unused => this.awards = store.awards); store.teamsObservable.subscribe(teams => { this.teams = teams.map(t => new Team(t as FirebaseTeam)); this.sortedTeams = _.sortBy(this.teams, t => t.id); this.createNominations(this.teams); }); } ngOnInit() { this.teamListDisplay = 1; } setTeamListDisplay(index) { this.teamListDisplay = index; } private createNominations(teams: Team[]) { } } <file_sep>/src/app/teams/team-list/team-list.component.ts import {Component, OnInit} from "@angular/core"; import {Team, FirebaseTeam} from "../../models/team"; import {AppStoreService} from "../../services/app-store.service"; @Component({ selector: 'app-team-list', templateUrl: 'team-list.component.html', styleUrls: ['team-list.component.css'], providers: [AppStoreService] }) export class TeamListComponent implements OnInit { teams: Team[]; constructor(private store: AppStoreService) { store.teamsObservable.subscribe(teams => this.teams = teams.map(t => new Team(t as FirebaseTeam))); } ngOnInit() { } } <file_sep>/src/app/judges/judge-card/judge-card.component.ts import {Component, OnInit, Input} from '@angular/core'; import {Judge} from "../../models/judge"; @Component({ selector: 'judge-card', templateUrl: './judge-card.component.html', styleUrls: ['./judge-card.component.css'] }) export class JudgeCardComponent implements OnInit { @Input() judge: Judge; private icon: string; private iconColor: string; private background: string; ngOnInit() { this.icon = '/assets/'; this.iconColor = 'black'; if (this.judge.role.startsWith('Head')) { this.icon += 'crown.svg'; this.iconColor = 'goldenrod'; } else if (this.judge.years === '0') { this.icon += 'rook.svg'; this.iconColor = 'darkgoldenrod'; } else { this.icon += 'person.svg'; } if (this.judge.role.indexOf('Robot') >= 0) { this.background = '#ffcccc'; } else if (this.judge.role.indexOf('Project') >= 0) { this.background = '#ccffcc'; } else if (this.judge.role.indexOf('Core') >= 0) { this.background = '#ddeeff'; } else { this.background = "white"; } } } <file_sep>/src/app/judges/judge-import/judge-import.component.ts import {Component, OnInit} from '@angular/core'; import {AppStoreService} from "../../services/app-store.service"; import {FirebaseListObservable, FirebaseObjectObservable} from "angularfire2"; import {Judge} from "../../models/judge"; import {AppConstants} from "../../models/app-constants"; import * as _ from 'lodash'; import * as Papa from 'papaparse'; @Component({ selector: 'judge-import', templateUrl: './judge-import.component.html', styleUrls: ['./judge-import.component.css'], providers: [AppStoreService] }) export class JudgeImportComponent implements OnInit { private JUDGE_HEADERS: {colIndex: number, colName: string, processFunc?: (data: string)=> string}[] = []; private appConstants: AppConstants; private currentJudges: FirebaseListObservable<any>; private newJudges: Judge[] = []; private dropHover = false; private error = ""; constructor(private store: AppStoreService) { store.appConstantsObservable.subscribe(snapshot => { this.appConstants = snapshot; this.createJudgeHeaderArray(); }); this.currentJudges = store.judgesObservable; } ngOnInit() { } onSubmit() { this.currentJudges.remove(); _.each(this.newJudges, (j) => this.currentJudges.push(j)); this.newJudges = []; } onCancel() { this.newJudges = []; } onFilesDropped(files) { // let result = Papa.parse("one, two, three, four"); this.error = this.verifyDroppedFiles(files); if (this.error) { return; } Papa.parse(files[0], { complete: (results => this.createJudgesFromData(results)) }); } private createJudgesFromData(results: any) { this.error = this.checkHeaders(results.data[0]); if (this.error) { return; } let extractRowData = (row, colIndex) => { return _.find(this.JUDGE_HEADERS, (h) => h.colIndex === colIndex).processFunc(row[colIndex]); }; let judgeMapper = row => new Judge( extractRowData(row, this.appConstants.judgeImportColumnFirstName), extractRowData(row, this.appConstants.judgeImportColumnLastName), extractRowData(row, this.appConstants.judgeImportColumnEmail), extractRowData(row, this.appConstants.judgeImportColumnPhone), extractRowData(row, this.appConstants.judgeImportColumnRole), extractRowData(row, this.appConstants.judgeImportColumnYears), extractRowData(row, this.appConstants.judgeImportColumnTeamAffiliation) ); let judgeData:(string[])[] = results.data.slice(1); this.newJudges = _.map(judgeData, judgeMapper); } private verifyDroppedFiles(dropFiles: FileList): string { if (dropFiles.length == 0 || dropFiles.length > 1) { return "Please drop only one file at a time."; } if (dropFiles[0].type !== "text/csv") { return "Please drop a .csv file only. If that was a CSV file, give it the .csv extension." } return null; } private checkHeaders(headers): string { for (let h of this.JUDGE_HEADERS) { if (headers[h.colIndex] !== h.colName) { return this.formatHeaderErrorMsg(h.colName, h.colIndex); } } return null; } private formatHeaderErrorMsg(fieldName: string, columnIndex: number): string { return `The "${fieldName}" column should be at index ${columnIndex}`; } private createJudgeHeaderArray() { let splitRole: (d:string)=>string = d => d.split(',')[0]; this.JUDGE_HEADERS = [ { colIndex: this.appConstants.judgeImportColumnFirstName, colName: "First Name", processFunc: _.identity }, { colIndex: this.appConstants.judgeImportColumnLastName, colName: "Last Name", processFunc: _.identity }, { colIndex: this.appConstants.judgeImportColumnEmail, colName: "Email", processFunc: _.identity }, { colIndex: this.appConstants.judgeImportColumnPhone, colName: "Phone", processFunc: _.identity }, { colIndex: this.appConstants.judgeImportColumnRole, colName: "Roles", processFunc: splitRole }, { colIndex: this.appConstants.judgeImportColumnYears, colName: "Years of Service", processFunc: _.identity }, { colIndex: this.appConstants.judgeImportColumnTeamAffiliation, colName: "Team Affiliation", processFunc: _.identity } ]; } } <file_sep>/src/app/deliberation/robot-performance-list/robot-performance-list.component.ts import {Component, OnInit} from '@angular/core'; import {Team} from "../../models/team"; import {AppStoreService} from "../../services/app-store.service"; import * as _ from 'lodash'; @Component({ selector: 'robot-performance-list', templateUrl: './robot-performance-list.component.html', styleUrls: ['./robot-performance-list.component.css'] }) export class RobotPerformanceListComponent implements OnInit { private teams: Team[]; constructor(store: AppStoreService) { store.teamsObservable.subscribe(teams => { this.teams = teams .map(t => new Team(t)) .sort((a, b) => a.performanceRank - b.performanceRank) }); } ngOnInit() { } } <file_sep>/src/app/models/award.ts import {AwardCategory} from "./award-category"; export interface FirebaseAward { $key: string; category: string, rank: number, winner: string, script: string } export class Award { private static readonly ORDINALS = [ "Zero", "First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eighth", "Ninth", "Tenth" ]; constructor(private fbAward: FirebaseAward, private category: AwardCategory) {} get categoryName(): string { return this.category.name; } get rank(): number { return this.fbAward.rank; } get script(): string { return this.fbAward.script; } set script(value: string) { this.fbAward.script = value; } get winner(): string { return this.fbAward.winner; } set winner(value: string) { this.fbAward.winner = value; } get ordinal(): string { return Award.ORDINALS[this.rank]; } get awardCategory(): AwardCategory { return this.category; } get description(): string { let desc = this.categoryName; if (this.category.numGiven > 1) { desc += ` - ${this.ordinal} Place`; } return desc; } toFirebase():FirebaseAward { return this.fbAward; } } <file_sep>/src/app/deliberation/deliberation-team-list/deliberation-team-list.component.ts import { Component, OnInit } from '@angular/core'; import {Team} from "../../models/team"; import {AppStoreService} from "../../services/app-store.service"; @Component({ selector: 'deliberation-team-list', templateUrl: './deliberation-team-list.component.html', styleUrls: ['./deliberation-team-list.component.css'] }) export class DeliberationTeamListComponent implements OnInit { private teams: Team[]; constructor(store: AppStoreService) { store.teamsObservable.subscribe(teams => { this.teams = teams .map(t => new Team(t)) .sort((a, b) => a.id - b.id) }); } ngOnInit() { } } <file_sep>/src/app/deliberation/judging-scores-list/judging-scores-list.component.ts import { Component, OnInit } from '@angular/core'; import {Team} from "../../models/team"; import {AppStoreService} from "../../services/app-store.service"; @Component({ selector: 'judging-scores-list', templateUrl: './judging-scores-list.component.html', styleUrls: ['./judging-scores-list.component.css'] }) export class JudgingScoresListComponent implements OnInit { private teams: Team[]; constructor(store: AppStoreService) { store.teamsObservable.subscribe(teams => { this.teams = teams .map(t => new Team(t)) .sort((a, b) => a.judgingScore - b.judgingScore) }); } ngOnInit() { } } <file_sep>/src/app/models/award-category.ts export class AwardCategory { constructor( readonly name: string, readonly numGiven: number, readonly exclusive: boolean, readonly order: number ) {} } <file_sep>/src/app/models/app-constants.ts export interface AppConstants { judgeImportColumnFirstName: number; judgeImportColumnLastName: number; judgeImportColumnEmail: number; judgeImportColumnPhone: number; judgeImportColumnRole: number; judgeImportColumnYears: number; judgeImportColumnTeamAffiliation: number; robotDesignNominations: number; projectNominations: number; coreValuesNominations: number; judgesAwardNominations: number; } <file_sep>/src/app/deliberation/deliberation-team-card/deliberation-team-card.component.ts import {Component, OnInit, Input} from '@angular/core'; import {Team} from "../../models/team"; @Component({ selector: 'deliberation-team-card', templateUrl: './deliberation-team-card.component.html', styleUrls: ['./deliberation-team-card.component.css'] }) export class DeliberationTeamCardComponent implements OnInit { @Input() team: Team; @Input() rank: number; @Input() cardType: string; constructor() { } ngOnInit() { } } <file_sep>/src/app/teams/team-import/team-import.component.ts import {Component} from "@angular/core"; import {CsvImportService} from "../../services/csv-import.service"; import {Team} from "../../models/team"; import {AppStoreService} from "../../services/app-store.service"; import {FirebaseListObservable} from "angularfire2"; @Component({ selector: 'app-team-import', templateUrl: 'team-import.component.html', styleUrls: ['team-import.component.css'], providers: [CsvImportService] }) export class TeamImportComponent { private error = ""; private newTeams: Team[] = []; private currentTeams: FirebaseListObservable<Team>; constructor(private importService: CsvImportService, store: AppStoreService) { this.currentTeams = store.teamsObservable; } onSubmit() { this.currentTeams.remove(); this.newTeams.forEach(t => this.currentTeams.push(t)); this.newTeams = []; } onCancel() { this.newTeams = []; } onFilesDropped(files) { this.importService.verifyDroppedFiles(files) .then(file => this.importService.importTeamsFromFile(file)) .then(teams => this.newTeams = teams) .catch(reason => this.error = reason); } } <file_sep>/src/app/services/csv-import.service.ts ///<reference path="../models/team.ts"/> import {Injectable} from "@angular/core"; import {AppStoreService} from "./app-store.service"; import {Team, FirebaseTeam} from "../models/team"; import * as Papa from "papaparse"; import * as _ from "lodash"; import {ColorService} from "./color.service"; @Injectable() export class CsvImportService { private static readonly EXPECTED_VERSION = '1'; private static readonly EXPECTED_VERSION_STR = 'Version Number'; private static readonly EXPECTED_BLOCK_FORMAT_STR = 'Block Format'; private static readonly EXPECTED_TEAM_BLOCK_NUM = '1'; private appConstants; constructor(store:AppStoreService, private colorService:ColorService) { store.appConstantsObservable.subscribe(obj => this.appConstants = obj); } verifyDroppedFiles(dropFiles: FileList): Promise<File> { return new Promise((resolve, reject) => { if (dropFiles.length == 0 || dropFiles.length > 1) { reject("Please drop only one file at a time."); } let csvFile = dropFiles[0]; if (csvFile.type && csvFile.type !== "text/csv" && csvFile.type !== 'application/vnd.ms-excel') { reject("Please drop a .csv file only. If that was a CSV file, give it the .csv extension."); } resolve(csvFile); }); } importTeamsFromFile(file:File): Promise<Team[]> { return new Promise((resolve, reject) => { Papa.parse(file, { complete: (results => this.processTeamResults(results, resolve, reject)) }); }); } importTeamScoresFromFile(file: File, teams: Team[]): Promise<Team[]> { return new Promise((resolve, reject) => { Papa.parse(file, { complete: (results => this.processTeamScoreResults(teams, results, resolve, reject)) }); }); } private processTeamResults(results, resolve, reject) { if (results.errors.length > 0) { reject(this.buildErrorStrings(results.errors)); } try { let teamCount = this.readHeaderSection(results.data, CsvImportService.EXPECTED_TEAM_BLOCK_NUM); let teams = this.createTeamsFromRows(results.data.slice(3), teamCount); resolve(teams); } catch (e) { reject(e); } } private processTeamScoreResults(teams:Team[], results, resolve, reject) { if (results.errors.length > 0) { reject(this.buildErrorStrings(results.errors)); } let findTeamById = (id:number) => _.find(teams, t => t.id === id); try { // First row is headers _.each(results.data.slice(1), row => { let teamId = Number(row[1]); if (isNaN(teamId)) { return; } let team = findTeamById(teamId); if (team === undefined) { throw "Score file contained unknown team " + teamId; } team.performanceRank = Number(row[0]); team.setRoundScores(_.map(row.slice(4, -1), score => +score)); }); resolve(teams); } catch (e) { reject(e); } } private createTeamsFromRows(rows: string[][], teamCount): Team[] { if (rows.length < teamCount) { console.log(`Warning: team count should be ${teamCount} but there are only ${rows.length} rows left in file`); } return _(rows) .map(row => { if (row.length < 2 || !row[0] || !row[1]) { return null; } else { return new Team({ id: Number(row[0]), name: row[1], color: this.colorService.randomColor(), organization: '' } as FirebaseTeam); } }) .compact() .value(); } private buildErrorStrings(errors: PapaParse.ParseError[]): string { let rowFormatter = row => row !== undefined ? 'row '+row : 'undefined row'; let msgFormatter = (msg, e) => msg + `${e.code}: ${e.message} at ${rowFormatter(e.row)}. `; return errors.reduce(msgFormatter, ''); } private readHeaderSection(rows: string[][], blockNum: string): number { let versionRow = rows[0]; if (versionRow[0] !== CsvImportService.EXPECTED_VERSION_STR) { throw `Unexpected version string "${versionRow[0]}" in first line of header`; } if (versionRow[1] !== CsvImportService.EXPECTED_VERSION) { throw `Unexpected version number: expected "${CsvImportService.EXPECTED_VERSION}" but found "${versionRow[1]}"`; } let blockFormatRow = rows[1]; if (blockFormatRow[0] !== CsvImportService.EXPECTED_BLOCK_FORMAT_STR) { throw `Unexpected block format string "${blockFormatRow[0]}" in second line line of header`; } if (blockFormatRow[1] !== blockNum) { throw `Unexpected block number: expected "${blockNum}" but found "${blockFormatRow[1]}"`; } return Number(rows[2][1]); } } <file_sep>/src/app/tournament/tournament-info/tournament-info.component.ts import {Component} from "@angular/core"; import {AppStoreService} from "../../services/app-store.service"; import {TournamentInfo} from "../../models/tournament-info"; import {Award, FirebaseAward} from "../../models/award"; import * as _ from "lodash"; import {AwardCategory} from "../../models/award-category"; @Component({ selector: 'tournament-info', templateUrl: './tournament-info.component.html', styleUrls: ['./tournament-info.component.css'] }) export class TournamentInfoComponent { private awards: Award[] = []; private tournamentInfo: TournamentInfo = new TournamentInfo(); constructor(private store: AppStoreService) { store.awardsObservable.subscribe(awards => this.awards = store.awards); store.tournamentInfoObservable.subscribe(info => { this.tournamentInfo = info.$key ? info : this.tournamentInfo; }); } onSaveTournamentInfo() { this.store.tournamentInfoObservable.set(this.tournamentInfo); } onCreateAwards() { this.store.awardsObservable.remove(); _.each(this.store.awardCategories, cat => { let awardCreator = this.getAwardCreatorForCategory(cat); _.times(cat.numGiven, awardCreator); }); } private getAwardCreatorForCategory(cat:AwardCategory): (number)=>void { return rank => this.store.awardsObservable.push({category: cat.name, rank: rank+1, script: '', winner: ''} as FirebaseAward); } } <file_sep>/e2e/app.e2e-spec.ts import { JudgeAdvisorPage } from './app.po'; describe('judge-advisor App', function() { let page: JudgeAdvisorPage; beforeEach(() => { page = new JudgeAdvisorPage(); }); it('should display message saying app works', () => { page.navigateTo(); expect(page.getParagraphText()).toEqual('app works!'); }); }); <file_sep>/src/app/deliberation/award-list/award-list.component.ts import { Component, OnInit } from '@angular/core'; import {Award, FirebaseAward} from "../../models/award"; import {Team, FirebaseTeam} from "../../models/team"; import {AppStoreService} from "../../services/app-store.service"; import * as _ from 'lodash'; @Component({ selector: 'award-list', templateUrl: './award-list.component.html', styleUrls: ['./award-list.component.css'] }) export class AwardListComponent implements OnInit { private awards: Award[] = []; private teams: Team[] = []; private mode = 1; constructor(private store:AppStoreService) { store.awardsObservable.subscribe(awards => { this.awards = _.map(awards, award => { let fbAward = award as FirebaseAward; return new Award(fbAward, store.findAwardCategoryByName(fbAward.category)) }); }); store.teamsObservable.subscribe(teams => this.teams = teams.map(t => new Team(t as FirebaseTeam))); } ngOnInit() { } onSaveList() { let toFirebaseMapper = a => a.toFirebase(); let awardsObs = this.store.awardsObservable; let updateWinners = fbAward => awardsObs.update(fbAward.$key, {winner: fbAward.winner}); _(this.awards).map(toFirebaseMapper).each(updateWinners); this.mode = 1; } onEditList() { this.mode = 2; } } <file_sep>/src/app/services/color.service.ts import { Injectable } from '@angular/core'; // import Color = require("color"); // import * as Color from 'color'; var Color = require('color'); @Injectable() export class ColorService { private static readonly COLORS = [ "#c0c0c0", "#808080", "#800000", "#ff0000", "#800080", "#ff00ff", "#008000", "#00ff00", "#808000", "#ffff00", "#000080", "#0000ff", "#008080", "#00ffff", "#ffa500", "#faebd7", "#7fffd4", "#ffe4c4", "#8a2be2", "#a52a2a", "#deb887", "#5f9ea0", "#7fff00", "#d2691e", "#ff7f50", "#6495ed", "#dc143c", "#00008b", "#008b8b", "#b8860b", "#a9a9a9", "#006400", "#a9a9a9", "#bdb76b", "#8b008b", "#556b2f", "#ff8c00", "#9932cc", "#8b0000", "#e9967a", "#8fbc8f", "#483d8b", "#2f4f4f", "#2f4f4f", "#00ced1", "#9400d3", "#ff1493", "#00bfff", "#696969", "#696969", "#1e90ff", "#b22222", "#228b22", "#ffd700", "#daa520", "#adff2f", "#808080", "#ff69b4", "#cd5c5c", "#4b0082", "#7cfc00", "#add8e6", "#f08080", "#e0ffff", "#fafad2", "#d3d3d3", "#90ee90", "#ffb6c1", "#ffa07a", "#20b2aa", "#87cefa", "#778899", "#778899", "#b0c4de", "#32cd32", "#66cdaa", "#0000cd", "#ba55d3", "#9370db", "#3cb371", "#7b68ee", "#00fa9a", "#48d1cc", "#c71585", "#191970", "#6b8e23", "#ff4500", "#da70d6", "#eee8aa", "#98fb98", "#afeeee", "#db7093", "#ffefd5", "#ffdab9", "#cd853f", "#ffc0cb", "#dda0dd", "#b0e0e6", "#bc8f8f", "#4169e1", "#8b4513", "#fa8072", "#f4a460", "#2e8b57", "#a0522d", "#87ceeb", "#6a5acd", "#708090", "#708090", "#00ff7f", "#4682b4", "#d2b48c", "#d8bfd8", "#ff6347", "#40e0d0", "#ee82ee", "#f5deb3", "#9acd32", "#663399" ]; constructor() { } randomColor(): string { let index = Math.round(Math.random()*ColorService.COLORS.length); return ColorService.COLORS[index]; } } <file_sep>/src/app/teams/team-details/team-details.component.ts import {Component, OnInit, Input} from '@angular/core'; import {Team} from "../../models/team"; @Component({ selector: 'ja-team-details', templateUrl: 'team-details.component.html', styleUrls: ['team-details.component.css'] }) export class TeamDetailsComponent implements OnInit { @Input() team: Team; constructor() { } ngOnInit() { } } <file_sep>/src/app/deliberation/nomination-list/nomination-list.component.ts import {Component, OnInit, Input} from '@angular/core'; import {AppStoreService} from "../../services/app-store.service"; import {Team, FirebaseTeam} from "../../models/team"; import * as _ from 'lodash'; @Component({ selector: 'nomination-list', templateUrl: './nomination-list.component.html', styleUrls: ['./nomination-list.component.css'] }) export class NominationListComponent implements OnInit { @Input() category: string; @Input() count: number; private teams: Team[]; constructor(private store: AppStoreService) { } ngOnInit() { this.store.teamsObservable.subscribe(teams => { this.teams = _(teams) .map(t => new Team(t as FirebaseTeam)) .filter(t => t[this.category + 'Nomination'] < this.count) .sortBy(t => t[this.category + 'Nomination']) .value(); while (this.teams.length < this.count) { this.teams.push(null); } }); } } <file_sep>/src/app/deliberation/nomination-card/nomination-card.component.ts import {Component, OnInit, Input} from '@angular/core'; import {Team} from "../../models/team"; @Component({ selector: 'nomination-card', templateUrl: './nomination-card.component.html', styleUrls: ['./nomination-card.component.css'] }) export class NominationCardComponent implements OnInit { @Input() team: Team; @Input() rank: number; @Input() category: string = 'robot'; private backgroundColor: string; constructor() { } ngOnInit() { switch(this.category) { case 'robot': this.backgroundColor = '#FFDDDD'; return; case 'project': this.backgroundColor = '#DDFFDD'; return; default: this.backgroundColor = '#BBDDFF'; } } } <file_sep>/src/app/app.routing.ts import {NgModule} from "@angular/core"; import {Routes, RouterModule} from "@angular/router"; import {TeamImportComponent} from "./teams/team-import/team-import.component"; import {TeamListComponent} from "./teams/team-list/team-list.component"; import {JudgeListComponent} from "./judges/judge-list/judge-list.component"; import {HomeComponent} from "./home/home.component"; import {JudgeImportComponent} from "./judges/judge-import/judge-import.component"; import {TournamentInfoComponent} from "./tournament/tournament-info/tournament-info.component"; import {DeliberationComponent} from "./deliberation/deliberation/deliberation.component"; import {ScoresComponent} from "./deliberation/scores/scores.component"; const routes: Routes = [ { path: 'tournament', component: TournamentInfoComponent }, { path: 'deliberation', component: DeliberationComponent }, { path: 'deliberation/scores', component: ScoresComponent }, { path: 'team', component: TeamListComponent }, { path: 'team/import', component: TeamImportComponent }, { path: 'judge', component: JudgeListComponent }, { path: 'judge/import', component: JudgeImportComponent }, { path: '', component: HomeComponent }, { path: '**', component: HomeComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule {} export const routingComponents = [ HomeComponent, TournamentInfoComponent, DeliberationComponent, ScoresComponent, TeamListComponent, TeamImportComponent, JudgeListComponent, JudgeImportComponent ]; <file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import {AngularFireModule, AuthProviders, AuthMethods} from 'angularfire2'; import {MaterialModule} from "@angular/material"; import { AppComponent } from './app.component'; import { AppRoutingModule, routingComponents } from "./app.routing"; import { TeamCardComponent } from './teams/team-card/team-card.component'; import { JudgeCardComponent } from './judges/judge-card/judge-card.component'; import { JudgeImportComponent } from './judges/judge-import/judge-import.component'; import { ErrorMessageComponent } from './common/error-message/error-message.component'; import { DropTargetComponent } from './common/drop-target/drop-target.component'; import { TournamentInfoComponent } from './tournament/tournament-info/tournament-info.component'; import { DeliberationComponent } from './deliberation/deliberation/deliberation.component'; import { AwardSlotComponent } from './deliberation/award-slot/award-slot.component'; import { RobotPerformanceListComponent } from './deliberation/robot-performance-list/robot-performance-list.component'; import { ScoresComponent } from './deliberation/scores/scores.component'; import { DeliberationTeamCardComponent } from './deliberation/deliberation-team-card/deliberation-team-card.component'; import { DeliberationTeamListComponent } from './deliberation/deliberation-team-list/deliberation-team-list.component'; import { JudgingScoresListComponent } from './deliberation/judging-scores-list/judging-scores-list.component'; import { NominationCardComponent } from './deliberation/nomination-card/nomination-card.component'; import { NominationListComponent } from './deliberation/nomination-list/nomination-list.component'; import { AwardListComponent } from './deliberation/award-list/award-list.component'; export const firebaseConfig = { apiKey: "<KEY>", authDomain: "judgeadvisor.firebaseapp.com", databaseURL: "https://judgeadvisor.firebaseio.com", storageBucket: "judgeadvisor.appspot.com", messagingSenderId: "1007941678332" }; const firebaseAuthConfig = { provider: AuthProviders.Google, method: AuthMethods.Redirect }; @NgModule({ declarations: [ AppComponent, routingComponents, TeamCardComponent, JudgeCardComponent, ErrorMessageComponent, DropTargetComponent, TournamentInfoComponent, DeliberationComponent, AwardSlotComponent, RobotPerformanceListComponent, ScoresComponent, DeliberationTeamCardComponent, DeliberationTeamListComponent, JudgingScoresListComponent, NominationCardComponent, NominationListComponent, AwardListComponent ], imports: [ BrowserModule, FormsModule, HttpModule, MaterialModule.forRoot(), AngularFireModule.initializeApp(firebaseConfig, firebaseAuthConfig), AppRoutingModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/src/app/common/drop-target/drop-target.component.ts import {Component, Input, Output, EventEmitter} from "@angular/core"; @Component({ selector: 'drop-target', templateUrl: './drop-target.component.html', styleUrls: ['./drop-target.component.css'] }) export class DropTargetComponent { @Input() prompt:string; @Output() filesDropped = new EventEmitter(); private dropHover = false; constructor() { } handleDragOver(evt) { evt.stopPropagation(); evt.preventDefault(); this.dropHover = true; evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy. } handleDragLeave() { this.dropHover = false; } handleFileSelect(evt) { evt.stopPropagation(); evt.preventDefault(); this.dropHover = false; this.filesDropped.emit(evt.dataTransfer.files); // FileList object. } } <file_sep>/src/app/models/team.ts import * as Color from "color"; import * as _ from "lodash"; export interface TeamScores { rank: number; max: number; scores: number[]; } export interface TeamNominations { robot: number; project: number; coreValues: number; } export interface FirebaseTeam { $key: string; id: number; name: string; color: string; organization: string; scores?: TeamScores; nominations?: TeamNominations; } export class Team { private static readonly DEFAULT_SCORES: TeamScores = {rank: 1, max: 0, scores: [0, 0, 0]}; private static readonly DEFAULT_NOMINATIONS: TeamNominations = {robot: 11, project: 11, coreValues: 11}; readonly backgroundColor: string; constructor(private fbTeam:FirebaseTeam) { fbTeam.scores = fbTeam.scores || Team.DEFAULT_SCORES; fbTeam.nominations = fbTeam.nominations || Team.DEFAULT_NOMINATIONS; this.backgroundColor = Color(this.color).alpha(.1).rgbaString(); } get id(): number { return this.fbTeam.id; } get name(): string { return this.fbTeam.name; } get color(): string { return this.fbTeam.color; } get organization(): string { return this.fbTeam.organization; } get performanceRank(): number { return this.fbTeam.scores.rank; } set performanceRank(rank: number) { this.fbTeam.scores.rank = rank; } get maxScore(): number { return this.fbTeam.scores.max; } get roundScores(): number[] { return this.fbTeam.scores.scores; } setRoundScores(newScores: number[]) { let scores = this.fbTeam.scores; scores.scores = newScores.slice(0); scores.max = _.max(scores.scores); } get robotNomination(): number { return this.fbTeam.nominations.robot; } set robotNomination(value: number) { this.fbTeam.nominations.robot = value; } get projectNomination(): number { return this.fbTeam.nominations.project; } set projectNomination(value: number) { this.fbTeam.nominations.project = value; } get coreValuesNomination(): number { return this.fbTeam.nominations.coreValues; } set coreValuesNomination(value: number) { this.fbTeam.nominations.coreValues = value; } get judgingScore(): number { let noms = this.fbTeam.nominations; return noms.robot ** 2 + noms.project ** 2 + noms.coreValues ** 2; } toFirebase(): FirebaseTeam { return this.fbTeam; } static clone(t: Team) { let fbClone = _.cloneDeep(t.toFirebase()); return new Team(fbClone); } } <file_sep>/src/app/app.component.ts import {Component, OnInit} from "@angular/core"; import {AngularFire} from "angularfire2"; import {AppStoreService} from "./services/app-store.service"; import {CsvImportService} from "./services/csv-import.service"; import {ColorService} from "./services/color.service"; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], providers: [AppStoreService, CsvImportService, ColorService] }) export class AppComponent implements OnInit { constructor(private af: AngularFire) { } ngOnInit(): void { } } <file_sep>/src/app/deliberation/scores/scores.component.ts import {Component} from "@angular/core"; import {Team, FirebaseTeam} from "../../models/team"; import {AppStoreService} from "../../services/app-store.service"; import {CsvImportService} from "../../services/csv-import.service"; import * as _ from 'lodash'; @Component({ selector: 'app-scores', templateUrl: './scores.component.html', styleUrls: ['./scores.component.css'] }) export class ScoresComponent { private error: string; private newTeams: Team[] = []; private currentTeams: Team[] = []; constructor(private store:AppStoreService, private importService:CsvImportService) { store.teamsObservable.subscribe(teams => this.currentTeams = _(teams) .map(t => new Team(t)) .sortBy(t => t.performanceRank) .value() ); } onSubmit() { let toFirebaseMapper = t => t.toFirebase(); let teamsObservable = this.store.teamsObservable; let updateScores = fbTeam => teamsObservable.update(fbTeam.$key, {scores: fbTeam.scores}); _(this.newTeams).map(toFirebaseMapper).each(updateScores); this.newTeams = []; } onCancel() { this.newTeams = []; } onFilesDropped(files) { this.importService.verifyDroppedFiles(files) .then(file => { let teamsClone = this.currentTeams.map(t => Team.clone(t)); return this.importService.importTeamScoresFromFile(file, teamsClone) }) .then(teams => this.newTeams = _.sortBy(teams, t => t.performanceRank)) .catch(reason => this.error = reason); } } <file_sep>/src/app/services/app-store.service.ts import {Injectable} from "@angular/core"; import {AngularFire, FirebaseListObservable, FirebaseObjectObservable} from "angularfire2"; import {AppConstants} from "../models/app-constants"; import {AwardCategory} from "../models/award-category"; import {TournamentInfo} from "../models/tournament-info"; import {Team, FirebaseTeam} from "../models/team"; import {Award, FirebaseAward} from "../models/award"; import * as _ from 'lodash'; @Injectable() export class AppStoreService { private _teamsObservable: FirebaseListObservable<any>; private _judgesObservable: FirebaseListObservable<any>; private _awardsObservable: FirebaseListObservable<any>; private _awardCategoriesObservable: FirebaseListObservable<any>; private _appConstantsObservable: FirebaseObjectObservable<AppConstants>; private _tournamentInfoObservable: FirebaseObjectObservable<TournamentInfo>; private _teams: Team[]; private _awards: Award[]; private _awardCategories: AwardCategory[]; constructor(private af: AngularFire) { this._appConstantsObservable = af.database.object('/appConstants'); this._tournamentInfoObservable = af.database.object('/tournamentInfo'); this._teamsObservable = af.database.list('/teams'); this._teamsObservable.subscribe(teams => this._teams = _.map(teams, t => new Team(t as FirebaseTeam))); this._judgesObservable = af.database.list('/judges'); this._awardsObservable = af.database.list('/awards'); this._awardCategoriesObservable = af.database.list('/awardCategories'); this._awardCategoriesObservable.subscribe(cats => { this._awardCategories = cats; this._awardsObservable.subscribe(awards => { this._awards = _.map(awards, award => { let fbAward = award as FirebaseAward; return new Award(fbAward, this.findAwardCategoryByName(fbAward.category)) }); }) }); } get appConstantsObservable(): FirebaseObjectObservable<any> { return this._appConstantsObservable; } get teamsObservable(): FirebaseListObservable<any> { return this._teamsObservable; } get judgesObservable(): FirebaseListObservable<any> { return this._judgesObservable; } get awardCategoriesObservable(): FirebaseListObservable<any> { return this._awardCategoriesObservable; } get awardsObservable(): FirebaseListObservable<any> { return this._awardsObservable; } get tournamentInfoObservable(): FirebaseObjectObservable<TournamentInfo> { return this._tournamentInfoObservable; } get awardCategories(): AwardCategory[] { return this._awardCategories; } get awards(): Award[] { return this._awards; } get teams(): Team[] { return this._teams.slice(0); } findTeamByNumber(teamNum: number): Team { return _.find(this._teams, t => t.id === teamNum); } findAwardCategoryByName(name: string): AwardCategory { return _.find(this._awardCategories, c => c.name === name); } } <file_sep>/src/app/teams/team-card/team-card.component.ts import {Component, Input} from "@angular/core"; import {Team} from "../../models/team"; @Component({ selector: 'team-card', templateUrl: './team-card.component.html', styleUrls: ['./team-card.component.css'] }) export class TeamCardComponent { @Input() team: Team; constructor() { } }
67ba278cfc7d3bfab3aadd674c18bc33b44f3185
[ "TypeScript" ]
31
TypeScript
deanriverson/JudgeAdviser
d5d065138a157bcb14f83c91a2d0220d1baf3d6d
aa8ba62d3f1dfdcf433af7402bbc4fa84722a705
refs/heads/master
<repo_name>eteries/34198-keksobooking<file_sep>/js/synchronize-fields.js 'use strict'; window.synchronizeFields = (function () { return function (elementFrom, arrayFrom, arrayTo, cb) { var selectedIndex = arrayFrom.indexOf(elementFrom.value); var setField = cb; var newValue = arrayTo[selectedIndex]; if (typeof setField === 'function') { setField(newValue); } }; })(); <file_sep>/js/show-card.js 'use strict'; window.showCard = (function () { var infoWindow = document.querySelector('.dialog'); var closer = document.querySelector('.dialog__close'); var onClose; // Закрыть диалог var closeInfoWindow = function (event, cb) { event.preventDefault(); infoWindow.style.display = 'none'; infoWindow.setAttribute('aria-hidden', 'true'); document.removeEventListener('keydown', documentKeyDownHandler); if (typeof onClose === 'function') { onClose(); } }; // Закрывать по Escape var documentKeyDownHandler = function (event) { if (window.utils.isEscape(event)) { closeInfoWindow(event); } }; // Заполнить карточку соотвествующими данными var fillCard = function (data) { infoWindow.querySelector('.lodge__title').innerText = data.offer.title; infoWindow.querySelector('.lodge__address').innerText = data.offer.address; infoWindow.querySelector('.lodge__price').innerText = data.offer.price + '₽/ночь'; infoWindow.querySelector('.lodge__description').innerText = data.offer.description; infoWindow.querySelector('.dialog__title img').src = data.author.avatar; var roomWord = window.utils.declineWords(data.offer.rooms, 'комната', 'комнаты', 'комнат'); var guestWord = window.utils.declineWords(data.offer.guests, 'гостя', 'гостей', 'гостей'); var text = 'Не для гостей'; if (data.offer.guests > 0) { text = data.offer.rooms + ' ' + roomWord + ' для ' + data.offer.guests + ' ' + guestWord; } infoWindow.querySelector('.lodge__rooms-and-guests').innerText = text; // Типы жилья var types = { FLAT: 'flat', BUNGALO: 'bungalo', HOUSE: 'house' }; switch (data.offer.type) { case types.FLAT: text = 'Квартира'; break; case types.BUNGALO: text = 'Лачуга'; break; case types.HOUSE: text = 'Дворец'; } infoWindow.querySelector('.lodge__type').innerText = text; infoWindow.querySelector('.lodge__checkin-time').innerText = 'Заезд после ' + data.offer.checkin + ', выезд до ' + data.offer.checkout; var featuresList = ''; data.offer.features.forEach(function (feature) { featuresList += '<span class="feature__image feature__image--' + feature + '"></span>'; }); infoWindow.querySelector('.lodge__features').innerHTML = featuresList; var imagesList = ''; data.offer.photos.forEach(function (image, index) { imagesList += '<img src="' + image + '" alt="Фото ' + index + '" width="52" height="42"> '; }); infoWindow.querySelector('.lodge__photos').innerHTML = imagesList; }; // Ожидание клика на закрытие closer.addEventListener('click', function (event) { closeInfoWindow(event); }); // Ожидание нажатия Enter или Escape на закрытие closer.addEventListener('keydown', function (event) { if (window.utils.isEnter(event) || window.utils.isEscape(event)) { closeInfoWindow(event); } }); // Возврат функции для выполнения действий при открытии и приёма колбэка return function (data, cb) { fillCard(data); infoWindow.style.display = 'block'; infoWindow.setAttribute('aria-hidden', 'false'); document.addEventListener('keydown', documentKeyDownHandler); onClose = cb; }; })(); <file_sep>/js/utils.js 'use strict'; window.utils = (function () { var keys = { ENTER: 13, ESCAPE: 27 }; var declineWords = function (number, case1, case2, case5) { number %= 100; if (number >= 5 && number <= 20) { return case5; } number %= 10; if (number === 1) { return case1; } if (number >= 2 && number <= 4) { return case2; } return case5; }; return { // Нажали Enter? isEnter: function (event) { return event.keyCode && event.keyCode === keys.ENTER; }, // Нажали Escape? isEscape: function (event) { return event.keyCode && event.keyCode === keys.ESCAPE; }, // Склонять слова declineWords: declineWords }; })(); <file_sep>/js/form.js 'use strict'; (function () { // Форма и её элементы var form = document.querySelector('.notice__form'); var formTitle = form.querySelector('#title'); var formPrice = form.querySelector('#price'); var formAddress = form.querySelector('#address'); var formCheckIn = form.querySelector('#time'); var formCheckOut = form.querySelector('#timeout'); var formType = form.querySelector('#type'); var formRooms = form.querySelector('#room_number'); var formGuests = form.querySelector('#capacity'); // Валидация formTitle.required = true; formTitle.minLength = 30; formTitle.maxLength = 100; formPrice.required = true; formPrice.min = 1000; formPrice.max = 1000000; formAddress.required = true; // Синхронизация времени въезда - выезда formCheckIn.addEventListener('change', function () { window.synchronizeFields(formCheckIn, ['12', '13', '14'], ['12', '13', '14'], function (newValue) { formCheckOut.value = newValue; }); }); formCheckOut.addEventListener('change', function () { window.synchronizeFields(formCheckOut, ['12', '13', '14'], ['12', '13', '14'], function (newValue) { formCheckIn.value = newValue; }); }); // Синхронизация типа жилья и минимальных значений цены formType.addEventListener('change', function () { window.synchronizeFields(formType, ['sm', 'md', 'lg'], ['0', '1000', '10000'], function (newValue) { formPrice.min = newValue; }); }); // Синхронизация количества комнат и гостей window.synchronizeFields(formGuests, ['3', '0'], ['2', '1'], function (newValue) { formRooms.value = newValue; }); formGuests.addEventListener('change', function () { window.synchronizeFields(formGuests, ['3', '0'], ['2', '1'], function (newValue) { formRooms.value = newValue; }); }); formRooms.addEventListener('change', function () { window.synchronizeFields(formRooms, ['1', '2', '100'], ['0', '3', '3'], function (newValue) { formGuests.value = newValue; }); }); })();
9e1dea19a3ee3370d1db781e47b729955356853e
[ "JavaScript" ]
4
JavaScript
eteries/34198-keksobooking
b380245e68f104a7522e941354bdfa192acbba68
6b598c7f1294857a37cde19673375043c25e1a77
refs/heads/master
<file_sep><?php class HomePage extends SiteTree { } class HomePage_Controller extends ContentController { }
9155c834038875c4a5d31b4f3372b31f814c7e77
[ "PHP" ]
1
PHP
reinkrijgsman/silverstripe
7d56c4b9a885b2f8d816713594b721e28860b378
919b8838c5607a13613424b74e061974c5bc0cdc
refs/heads/master
<repo_name>BiagioeCarmine/morra-test-vue<file_sep>/src/backend.ts import axios from 'axios'; //const URL = "http://localhost:5000"; const URL = "https://morra.carminezacc.com"; export default { async logIn(username: string, password: string) { const res = await axios.post( URL+"/users/login", `username=${username}&password=${password}`, { headers: { "Content-Type": "application/x-www-form-urlencoded" } } ); console.log(res); return {data: res.data, status: res.status}; }, async signUp(username: string, password: string) { const res = await axios.post( URL+"/users/signup", `username=${username}&password=${<PASSWORD>}`, { headers: { "Content-Type": "application/x-www-form-urlencoded" } } ); console.log(res); return {data: res.data, status: res.status}; }, async addToPublicQueue(jwt: string) { const res = await axios.post( URL+`/mm/queue`, 'type=public', { headers: { "Content-Type": "application/x-www-form-urlencoded", "Authorization": "Bearer "+jwt } } ); console.log(res); return {data: res.data, status: res.status}; }, async verifyUser(jwt: string) { const res = await axios.get( URL+`/users/verify`, { headers: { "Authorization": "Bearer "+jwt } } ); console.log(res); return {data: res.data, status: res.status}; }, async getQueueStatus(jwt: string) { const res = await axios.get( URL+`/mm/queue_status`, { headers: { "Authorization": "Bearer "+jwt } } ); console.log(res); return {data: res.data, status: res.status}; }, async addToPrivateQueue(jwt: string) { const res = await axios.post( URL+`/mm/queue`,'type=private', { headers: { "Authorization": "Bearer "+jwt } } ); console.log(res); return {data: res.data, status: res.status}; }, async playWithFriend(userid: string, jwt: string) { const res = await axios.post( URL+`/mm/play_with_friend`, "user="+userid, { headers: { "Authorization": "Bearer "+jwt } } ); console.log(res); return {data: res.data, status: res.status}; }, async setMove(hand: string, prediction: string, matchid: string, jwt: string) { const res = await axios.post( URL+`/matches/${matchid}/move`, `hand=${hand}&prediction=${prediction}`, { headers: { "Content-Type": "application/x-www-form-urlencoded", "Authorization": "Bearer "+jwt } } ); console.log(res); return {data: res.data, status: res.status}; }, async getMove(matchid: string) { const res = await axios.get( URL+`/matches/${matchid}/last_round`, ); console.log(res); return res; }, async getMatch(id: string) { const res = await axios.get( URL+"/matches/"+id ); return res.data; } }
e383dbbaea5694fb092829046c98974eae2c1db3
[ "TypeScript" ]
1
TypeScript
BiagioeCarmine/morra-test-vue
68ba920b9f68f9f0058bebcea48ae833df2a98b7
0f82e01019e070269bf2774e24cbd89e7d57a681
refs/heads/master
<file_sep>import { BASE_URL } from '../config' export const FETCH_CHEESES_REQUEST = 'FETCH_CHEESES_REQUEST' export const fetchCheesesRequest = () => ({ type: FETCH_CHEESES_REQUEST }) export const FETCH_CHEESES_SUCCESS = 'FETCH_CHEESES_SUCCESS' export const fetchCheesesSuccess = (cheeses) => ({ type: FETCH_CHEESES_SUCCESS, cheeses // pass in value with the action }) export const FETCH_CHEESES_ERROR = 'FETCH_CHEESES_ERROR' export const fetchCheesesError = (error) => ({ type: FETCH_CHEESES_ERROR, error }) export const fetchCheeses = () => dispatch => { dispatch(fetchCheesesRequest()) return fetch(`${BASE_URL}cheeses`) .then(res => res.json()) .then(data => dispatch(fetchCheesesSuccess(data))) .catch(error => dispatch(fetchCheesesError(error))) } <file_sep>import React, { Component } from 'react' import { connect } from 'react-redux' import { fetchCheeses } from '../actions/cheese' class CheeseList extends Component { //constructor allows to set state on component // can also bind methods // // this.methodName = this.methodName.bind(this) // constructor() { // constructor is always optional, used to setup things on class if need additional functionallity // super() // necessary if constructor used // let cheeses = ['Bath Blue', 'Barkham Blue', 'Buxton Blue'] // this.state = { cheeses } // not using state because we've moved information into redux store (in this context) // } componentDidMount() { this.props.dispatch(fetchCheeses()) // dispatch async action } render() { return ( <ul> {this.props.cheeses.map((cheese, index) => ( <li className='cheese' key={index}> {cheese} </li> ))} </ul> ) } } // console.log('props', props) const mapStateToProps = state => ({ cheeses: state.cheeses, // redux-store or state }) // export CheeseList export default connect(mapStateToProps)(CheeseList) <file_sep>import { FETCH_CHEESES_REQUEST, FETCH_CHEESES_SUCCESS, FETCH_CHEESES_ERROR, } from '../actions/cheese' const initialState = { cheeses: [], loading: false, error: null, } const fetchCheeseReducer = (state = initialState, action) => { switch (action.type) { case FETCH_CHEESES_REQUEST: return { ...state, loading: true } case FETCH_CHEESES_SUCCESS: return { ...state, loading: false, error: null, cheeses: action.cheeses } case FETCH_CHEESES_ERROR: console.log('action.error', action.error) return { ...state, loading: false, error: action.error } default: return state } } export default fetchCheeseReducer
298696b440c86f2672cccfed771863059530f869
[ "JavaScript" ]
3
JavaScript
thinkful-ei26/bryan-serve-ya-cheezburger
956da08802ed0b0ff87aac071066fdb600bfb9a8
e7034e824f2312a545afbf14fee44196bd483464
refs/heads/master
<file_sep>var google = { container: document.getElementById('google'), // Required path: 'google.json', // Required renderer: 'svg', loop: false, autoplay: false, // Optional name: "google", // Name for future reference. Optional. }; var shopify = { container: document.getElementById('shopify'), // Required path: 'shopify.json', // Required renderer: 'svg', loop: false, autoplay: false, // Optional name: "shopify", // Name for future reference. Optional. } var anyService = { container: document.getElementById('any-service'), // Required path: 'any-service.json', // Required renderer: 'svg', loop: false, autoplay: false, // Optional name: "any-service", // Name for future reference. Optional. } function AnimationController(animationConfig) { this.animationConfig = animationConfig; this.state = false; console.log(animationConfig) this.controller = bodymovin.loadAnimation(this.animationConfig); return this; } AnimationController.prototype.setIncomingPartner = function(partner) { this.incomingPartner = partner; } AnimationController.prototype.setOutgoingPartner = function (partner) { this.outgoingPartner = partner; } AnimationController.prototype.isOn = function() { return this.state; } AnimationController.prototype.toggle = function() { let oldState = this.state; this.state = !this.state; this._check(); } AnimationController.prototype._check = function() { this._checkFromSelf(); } AnimationController.prototype._checkFromSelf = function() { if(this.isOn()) { if(this.outgoingPartner.isOn()) { this.outgoingPartner._run(this.SEGMENTS.SELF_PARTNER); } else { this.outgoingPartner._run(this.SEGMENTS.PARTNER); } if(this.incomingPartner.isOn()) { this._run(this.SEGMENTS.PARTNER_SELF); } else { this._run(this.SEGMENTS.SELF); } } else { if(this.outgoingPartner.isOn()) { this.outgoingPartner._run(this.SEGMENTS.SELF_PARTNER_REVERSE); } else { this.outgoingPartner._run(this.SEGMENTS.PARTNER_REVERSE); } if(this.incomingPartner.isOn()) { this._run(this.SEGMENTS.PARTNER_SELF_REVERSE); } else { this._run(this.SEGMENTS.SELF_REVERSE); } } } AnimationController.prototype._run = function(segment) { if(!this.controller.isPaused) { this.controller.playSegments(segment, false); } else { this.controller.playSegments(segment, true); } } AnimationController.prototype.SEGMENTS = { SELF: [60,160], SELF_REVERSE: [400,500], SELF_PARTNER: [180,280], SELF_PARTNER_REVERSE: [280, 380], PARTNER: [540,640], PARTNER_REVERSE: [860, 960], PARTNER_SELF: [640,740], PARTNER_SELF_REVERSE: [760, 860], } var googleController = new AnimationController(google); var shopifyController = new AnimationController(shopify); var anyServiceController = new AnimationController(anyService); googleController.setIncomingPartner(shopifyController); googleController.setOutgoingPartner(anyServiceController); shopifyController.setIncomingPartner(anyServiceController) shopifyController.setOutgoingPartner(googleController) anyServiceController.setIncomingPartner(googleController) anyServiceController.setOutgoingPartner(shopifyController); function toggleGoogle() { googleController.toggle(); } function toggleShopify() { shopifyController.toggle(); } function toggleAnyService() { anyServiceController.toggle(); }
d7bc0c68ea65290714b20caf5ae196f893a32a48
[ "JavaScript" ]
1
JavaScript
nickvenne/nickvenne.github.io
87d06d0394b4bc049c747597047b2b0f737f2da1
75e24c6d6ae03b5374fb70caa88399a86f8391ad
refs/heads/master
<repo_name>HideinBushes/PracticeNote<file_sep>/tree.cc #include <iostream> using namespace std; class tree{ private: class treeNode{ public: int val; treeNode* left; treeNode* right; treeNode(int v, treeNode* left, treeNode* right): val(v), left(left), right(right){} ~treeNode(){ delete left; delete right; } void inorder(){ //left, me, right if(left != nullptr) left->inorder(); cout << val << ' '; if(right != nullptr) right->inorder(); } void preorder(){ //me, left, right cout<< val << ' '; if(left != nullptr) left->preorder(); if(right != nullptr) right->preorder(); } void postorder(){ //left, right, me if(left != nullptr) left->postorder(); if(right != nullptr) right->postorder(); cout<<val<<' '; } }; treeNode* root; public: tree():root(nullptr){} ~tree(){ delete root; } void add(int val){ if(root == nullptr){ root = new treeNode(val,nullptr,nullptr); return; } treeNode* p = root; while(true){ if(val > p->val){ if(p->right ==nullptr){ p->right = new treeNode(val,nullptr, nullptr); return; }else{ p = p->right; } }else{ if(p->left ==nullptr){ p->left = new treeNode(val, nullptr, nullptr); return; }else{ p = p->left; } } } } void printInorder(){ if(root == nullptr) return; root->inorder(); cout<<'\n'; } void printPostorder(){ if(root == nullptr ) return; root->postorder(); cout<<'\n'; } void printPreorder(){ if(root == nullptr) return; root->preorder(); cout<<'\n'; } }; int main(){ tree b; b.add(5); for(int i = 0 ; i< 10; i++){ b.add(i); } b.printInorder(); b.printPreorder(); b.printPostorder(); }<file_sep>/linkedList.cc //author: <NAME> //ID: 10403801 #include <iostream> #include <fstream> #include <sstream> #include <cstring> #include <string> #include <vector> using namespace std; class linkedList { private: class node { public: int val; node* next; node(int v, node* n): val(v), next(n){} }; node* head; node* tail; public: linkedList(): head(nullptr), tail(nullptr){} ~linkedList(){ node* q; for(node *p = head; p!= nullptr; p = q){ q= p->next; delete p; } } void addEnd(int v){ if(tail == nullptr){ head = new node(v, nullptr); tail = head; return; } node* p=tail; p->next =new node(v, nullptr); tail = p->next; } void addStart(int v){ if(head == nullptr){ head = new node(v, nullptr); tail = head; return; } head = new node(v,head); } void insert(int i, int v){ if(head == nullptr){ head = new node(v ,nullptr); tail = head; return; } node* p=head; for(int j=0; j<i && p->next != nullptr; j++){ p=p->next; } if(p->next == nullptr){ p->next = new node(v, nullptr); tail = p->next; return; } node* temp = new node(v, p->next); p->next = temp; } void removeEnd(){ if(tail == nullptr) throw "No elements"; if(head == tail){ head = nullptr; tail = nullptr; return; } node* p = head; for(; p->next->next != nullptr; p=p->next){ ; } tail = p; p->next = nullptr; } void removeStart(){ if(head == nullptr) throw "No elements"; if(head == tail){ head = nullptr; tail = nullptr; return; } head = head->next; } void add(string command, vector<string> s){ int start = stoi(s[0]); int step = stoi(s[1]); int end = stoi(s[2]); if(command == "ADD_FRONT"){ for(int i=start;i<=end;i+=step) addStart(i); } if(command == "ADD_BACK"){ for(int i=start; i<=end;i+=step) addEnd(i); } } void remove(string command, int bits){ if(command == "REMOVE_FRONT"){ for(int i=0;i<bits;i++) removeStart(); } if(command == "REMOVE_BACK"){ for(int i=0;i<bits;i++) removeEnd(); } } int get(int i) const{ node* p = head; for(;i>0;i--, p=p->next){ if(p ==nullptr) throw "linkedList index out of bounds"; } return p->val; } int operator[](int i)const{ node* p; for(p=head;p->next != nullptr;p=p->next) ; return p->val; } friend ostream& operator<<(ostream& s, const linkedList& list){ if (list.head ==nullptr){ s<<"No elements in the list"; return s; } s << list.head->val; for (node* p=list.head->next; p!= nullptr; p=p->next){ s << ','<< p->val; } return s; } }; vector<string> str_split(string str){ char* cstr=const_cast<char*>(str.c_str()); char* current; vector<string> arr; current=strtok(cstr,":"); while(current!=NULL){ arr.push_back(current); current=strtok(NULL,":"); } return arr; } int main(){ linkedList list; ifstream infile("HW4b.txt"); string line; cout<< "OUTPUT:"<<"\n"; while(getline(infile, line)){ if(!line.empty()){ istringstream l(line); string command; string para; int bits; l>>command; if(command =="ADD_FRONT" || command == "ADD_BACK"){ while(l>>para){ vector<string> s; l>>para; s=str_split(para); list.add(command, s); } } if(command =="REMOVE_FRONT" || command == "REMOVE_BACK"){ while(l>>bits){ list.remove(command, bits); } } if(command =="OUTPUT"){ cout<<list<<'\n'; } } } }<file_sep>/README.md # PracticeNote Algorithm practice note <file_sep>/growArray.cc //Author:<NAME> //ID: 10403801 #include <iostream> #include <fstream> #include <sstream> #include <cstring> #include <string> #include <vector> using namespace std; class growArray{ private: int* data; int used; int capacity; void grow(){ int* temp = data; capacity = capacity*2; data = new int[capacity]; for(int i=0; i<used; i++){ data[i] = temp[i]; } delete [] temp; } public: growArray(): data(new int[1]), used(0), capacity(1){} growArray(int initialCapacity){ data = new int[initialCapacity]; used = 0; capacity = initialCapacity; } ~growArray(){ delete [] data; } int length(){ return used; } void addEnd(int v){ if(used+1 > capacity) grow(); data[used] = v; used++; } //using grow() will be two times slower. void addStart(int v){ int *temp = data; if(used+1 > capacity){ capacity = capacity*2; data = new int[capacity]; } for(int i=used-1; i>=0;i--) data[i+1]=temp[i]; data[0] = v; used++; } void removeEnd(){ used--; } void removeStart(){ for(int i=0;i<used-1; i++) data[i]=data[i+1]; used--; } void show(){ for(int i=0; i<used; i++) cout<<data[i]<<' '; cout<<'\n'; } void add(string command, vector<string> s){ int start = stoi(s[0]); int step = stoi(s[1]); int end = stoi(s[2]); if(command == "ADD_FRONT"){ for(int i=start;i<=end;i+=step) addStart(i); } if(command == "ADD_BACK"){ for(int i=start; i<=end;i+=step) addEnd(i); } } void remove(string command, int bits){ if(command == "REMOVE_FRONT"){ for(int i=0;i<bits;i++) removeStart(); } if(command == "REMOVE_BACK"){ for(int i=0;i<bits;i++) removeEnd(); } } int operator[](int i){ return data[i]; } }; vector<string> str_split(string str){ char* cstr=const_cast<char*>(str.c_str()); char* current; vector<string> arr; current=strtok(cstr,":"); while(current!=NULL){ arr.push_back(current); current=strtok(NULL,":"); } return arr; } int main(){ growArray a; ifstream infile("HW4a.txt"); string line; cout<< "OUTPUT:"<<"\n"; while(getline(infile, line)){ if(!line.empty()){ istringstream l(line); string command; string para; int bits; l>>command; if(command =="ADD_FRONT" || command == "ADD_BACK"){ while(l>>para){ vector<string> s; l>>para; s=str_split(para); a.add(command, s); } } if(command =="REMOVE_FRONT" || command == "REMOVE_BACK"){ while(l>>bits){ a.remove(command, bits); } } if(command =="OUTPUT"){ a.show(); } } } } <file_sep>/string_naive.cc #include <iostream> #include <string> using namespace std; bool naive(string search, string target){ for(int i =0; i<search.length(); i++){ int j; if(search[i]== target[0]){ for(j=1;j<target.length();j++){ if(search[i+j]!=target[j]){ break; } } if(j == target.length()) return true; } } return false; } bool BM(string search, string target){ int table[256]; int n = search.length(); int m = target.length(); int i, j; for(i = 0;i<255;i++){ //ascii table[i] = m; // } for(i = 0; i<m;i++){ table[target[i]] = m - 1 - i; } i = m-1; while(i<n){ int jump = table[search[i]]; if(jump == 0){ for(j = 1; j<m; j++){ if(search[i-j] != target[m-j-1]){ i=i+m; break; } } if(j==m) return true; } i = i+jump; } return false; } int main(){ string s = "this is my string, hello"; string sub; cin>>sub; cout<<BM(s,sub)<<'\n'; }<file_sep>/hashing.cc #include <iostream> #include <vector> #include <cstring> using namespace std; class growArray{ private: int size; //int used; int* data; int hash(int val){ return val % size; } public: growArray():size(0), data(nullptr){ } growArray(int s): size(s), data(new int[s]){ } ~growArray(){ delete [] data; } vector<int> v; void add(int val){ v.push_back(val); size++; } bool find(int val){ if(data[hash(val)] != 0) return true; return false; } void hashing(){ data = new int[size]; for(int i =0; i<size;i++){ data[i] = 0; } for(int i =0;i<size;i++){ int index = hash(v[i]); if(data[index] == 0){ data[index] = v[i]; } else{ data = new int[++size]; for(int i =0; i<size;i++) data[i] = 0; i = 0; } } } }; class perfectHashing{ private: growArray* table; int size; int used; int hash(int val){ return val % size; } void grow(){ growArray* temp = table; table = new growArray[size*2]; size = size*2; for(int i =0; i<size/2; i++){ if(temp[i].v.size() == 0) continue; vector<int> p; for(int j = 0; j<p.size(); j++){ int val = temp[i].v[j]; table[hash(val)].add(val); } } delete [] temp; } public: perfectHashing(): used(0),size(8),table(new growArray[8]){ } void add(int val){ if(used >= size){ grow(); } table[hash(val)].add(val); used++; } bool find(int val){ int index1 = hash(val); if(table[index1].find(val)) return true; return false; } void built(){ for(int i =0; i<size;i++){ if(table[i].v.size() == 0) continue; table[i].hashing(); } } }; int main(){ int a[6] = {11,37,5,21,22,27}; perfectHashing lib; for(int i =0; i<6;i++) lib.add(a[i]); lib.built(); // for(int i =0; i<6; i++){ // cout<<a[i]<<' '<<lib.find(a[i])<<'\n'; // } cout<<lib.find(8)<<'\n'; }
af844c42e361079e9775e0697f258b3ff3ad6a89
[ "Markdown", "C++" ]
6
C++
HideinBushes/PracticeNote
d3a005b28bb18e92a181eafe5be7d910312beca0
e3cb127b3217e9c5a8c6f9d4bec91f20f88c037b
refs/heads/master
<repo_name>mahadirz/CarND-Behavioral-Cloning-P3<file_sep>/readme.md # **Behavioral Cloning** [![Udacity - Self-Driving Car NanoDegree](https://s3.amazonaws.com/udacity-sdc/github/shield-carnd.svg)](http://www.udacity.com/drive) ## Writeup --- **Behavioral Cloning Project** [![video](./writeup_images/youtube.png)](https://youtu.be/14mb9vo7EgQ) The goals / steps of this project are the following: * Use the simulator to collect data of good driving behavior * Build, a convolution neural network in Keras that predicts steering angles from images * Train and validate the model with a training and validation set * Test that the model successfully drives around track one without leaving the road * Summarize the results with a written report [//]: # (Image References) [arch]: ./writeup_images/arch.png "arch" [model_1_loss]: ./writeup_images/model_1_loss.png "model_1_loss" [distribution_skewed]: ./writeup_images/distribution_skewed.png "distribution_skewed" [distribution_normal]: ./writeup_images/distribution_normal.png "distribution_normal" [right_recover]: ./writeup_images/right_recover.gif "right_recover" [center_driving]: ./writeup_images/center_driving.gif "center_driving" [left_recover]: ./writeup_images/left_recover.gif "left_recover" [flipped]: ./writeup_images/flipped.png "flipped" --- ### Files Submitted & Code Quality #### 1. Project files to run the simulator in autonomous mode * model.py containing the script to create and train the model * drive.py for driving the car in autonomous mode * model.h5 containing a trained convolution neural network * readme.md summarizing the results #### 2. Simulation Using the Udacity provided simulator and my drive.py file, the car can be driven autonomously around the track by executing ```sh python drive.py model.h5 ``` #### 3. Training For the model training I had used free Google Colab GPU notebook. The Tensorflow and Keras version used were 1.15.2 and 2.31 respectively. To follow this technique, `colab_training.ipynb` provides the examples. The final cell shows the command used to execute the training job. ```sh python model.py training --batch=128 --es-patience=1 --epoch=10 --artifact-dst=model.h5 ``` Note: The `model.py` file must be uploaded through **upload to session storage** first before executing the above command. * training is the directory of driving_log and images. * es-patience is the Early Stopping parameter for the number of time to wait before stop the training. * artifact-dst is the full path to save the model. This can be used to save into mounted folder in case of the notebook terminated unexpectedly during training. ### Model Architecture and Training Strategy #### 1. Model Architecture My model consisted of 6 convolutionals layers and 3 fully connected layers. The architecture was adapted from the [Nvidia Research](http://images.nvidia.com/content/tegra/automotive/images/2016/solutions/pdf/end-to-end-dl-using-px.pdf). In the first and second layers, images are normalized and cropped at the top and bottom to remove noises unrelated to driving. After that, followed by 3 convolutional layers with kernel size 5x5 and strides 2x2 and another 3 with kernel size 3x3 and strides 1x1. I used ELU instead of RELU for non-linear activation functions as from this [ELU as an activation function](https://deeplearninguniversity.com/elu-as-an-activation-function-in-neural-networks/) #### 2. Reduce overfitting To reduce overfitting I used dropout with probability of 20%. The Early stopping is also used to stop the training automatically after the performance of the validation dataset hasn't improved after a preset number. This can be configured through `--es-patience` parameter. #### 3. Model parameter tuning The model used an adam optimizer after several try and errors I found the the default parameter for learning rate was better. #### 4. training data Training data was chosen to keep the vehicle driving on the road. I used a combination of center lane driving, recovering from the left and right sides of the road. For details about how I created the training data, see the next section. ### Model Architecture and Training Strategy #### 1. Solution Design Approach My first step was to use a convolution neural network model similar to the [comma.ai](https://github.com/commaai/research/blob/master/train_steering_model.py). The codes for the keras is used to bootstrap my experiments. However the model above was not able drive pass the sharp curve part of the road. The following diagram shows the diagnostic of the model ![alt text][model_1_loss] I was puzzled, everything looks correct at least from the loss chart. I had hypothesized either the data was not captured right or the model may require more convolutional layers to identify curvature. I decided to give a try for Nvidia architecture introduced during the lesson as it consisted more convolutional layers. The modification from the Nvidia only the 6th convolutional layers as the model performed better by adding this from my experimentation. This architecture performance was better, fewer spots where the vehicle fell off the track. I suspected the training data was probably the reason as I only use keyboard for control. ![alt text][distribution_skewed] From the dataset distribution of steering angle, I can see the angle 0 overly skewed the data. This may have effect to the performance of the model. I used data resampling to achieve near normal distribution. ![alt text][distribution_normal] The vehicle finally able to drive the track without leaving the road but the driving was a bit jitter. At the end I implemented the data augmentation to use left and right with angle correction and dropped the resampling, the car is able to drive more smoothly and able to pass the second track until to the point of super sharp corner. #### 2. Final Model Architecture The final model architecture is the one adapted from Nvidia. | Layer | Description | |---------------|-------------------------------------------| | Input | RGB Image 160x320x3 | | Normalization | Data normalization | | Cropping | Output 80x320x3 | | Convolutional | Kernel 5x5, Strides 2x2, Output 38x158x24 | | ELU | Activation function | | Convolutional | Kernel 5x5, Strides 2x2, Output 17x77x36 | | ELU | Activation function | | Convolutional | Kernel 5x5, Strides 2x2, Output 7x37x48 | | ELU | Activation function | | Convolutional | Kernel 3x3, Strides 1x1, Output 5x35x64 | | ELU | Activation function | | Convolutional | Kernel 3x3, Strides 1x1, Output 3x33x64 | | ELU | Activation function | | Convolutional | Kernel 3x3, Strides 1x1, Output 1x31x64 | | ELU | Activation function | | Flatten | Output 1x1984 | | Dense | Output 1x100 | | ELU | Activation function | | Dense | Output 1x50 | | ELU | Activation function | | Dense | Output 1x10 | | ELU | Activation function | | Dense | Output 1x1 | Here is a visualization of the architecture. ![alt text][arch] #### 3. Creation of the Training Set & Training Process To capture good driving behavior, I first recorded several laps on track one using center lane driving. Here is an example image of center lane driving: ![alt text][center_driving] I then recorded the vehicle recovering from the left side and right sides of the road back to center so that the vehicle would learn to recover back to center. These images show what a recovery looks: ![alt text][left_recover] ![alt text][right_recover] To augment the dataset, I flipped the left, right and center images and negate its angle. The following image show how the flipped looks like. ![alt text][flipped] After the collection process, I had 26,709 driving log records. Each of the records consisted of 3 images and then each were flipped. Overall the total data generated is 160,254. These data were then randomly splitted into 20% for validation set and 80% for training. I used this training data for training the model. The validation set helped determine if the model was over or under fitting. <file_sep>/requirements.txt Keras==2.3.1 pendulum==2.1.2 tensorflow==1.15.2 <file_sep>/model.py """ The training was tested using Google Colab GPU notebook with %tensorflow_version 1.x The version compatible with this artifact saved may be as following Keras==2.3.1 tensorflow==1.15.2 """ import argparse import os import random from math import ceil import imageio import numpy as np import pandas as pd import pendulum import sklearn import tensorflow as tf from keras.callbacks import EarlyStopping from keras.callbacks import ModelCheckpoint from keras.layers import Flatten, Dense, Dropout, Lambda, Cropping2D, ELU, Conv2D from keras.models import Sequential from keras.optimizers import Adam from sklearn.model_selection import train_test_split random.seed(10) def generator(samples, batch_size=128, img_path='./training/IMG/'): """ Generator for model training :param samples: :param batch_size: :param img_path: :return: """ num_samples = len(samples) while 1: # Loop forever so the generator never terminates random.shuffle(samples) for offset in range(0, num_samples, batch_size): batch_samples = samples[offset:offset + batch_size] images = [] angles = [] for batch_sample in batch_samples: center_image = imageio.imread(img_path + batch_sample[0]) left_image = imageio.imread(img_path + batch_sample[1]) right_image = imageio.imread(img_path + batch_sample[2]) center_angle = float(batch_sample[3]) # create adjusted steering measurements for the side camera images correction = 0.2 # this is a parameter to tune left_angle = center_angle + correction right_angle = center_angle - correction # center image_flipped = np.fliplr(center_image) measurement_flipped = -center_angle images.append(center_image) angles.append(center_angle) images.append(image_flipped) angles.append(measurement_flipped) # left image_flipped = np.fliplr(left_image) measurement_flipped = -left_angle images.append(left_image) angles.append(left_angle) images.append(image_flipped) angles.append(measurement_flipped) # right image_flipped = np.fliplr(right_image) measurement_flipped = -right_angle images.append(right_image) angles.append(right_angle) images.append(image_flipped) angles.append(measurement_flipped) # trim image to only see section with road X = np.array(images) y = np.array(angles) xy = sklearn.utils.shuffle(X, y) yield xy[0], xy[1] def create_model(): """ Function to create model neural network architecture The architecture is based on loosely modified Nvidia research http://images.nvidia.com/content/tegra/automotive/images/2016/solutions/pdf/end-to-end-dl-using-px.pdf :return: """ model = Sequential() # the input image is 320x160x3 row, col, ch = 160, 320, 3 model.add( Lambda(lambda x: x / 127.5 - 1., input_shape=(row, col, ch)) ) # Crop the top by 60x and bottom 20x model.add(Cropping2D(cropping=((60, 20), (0, 0)))) model.add(Conv2D(filters=24, kernel_size=(5, 5), strides=(2, 2), padding="valid")) model.add(ELU()) model.add(Conv2D(filters=36, kernel_size=(5, 5), strides=(2, 2), padding="valid")) model.add(ELU()) model.add(Conv2D(filters=48, kernel_size=(5, 5), strides=(2, 2), padding="valid")) model.add(ELU()) model.add(Conv2D(filters=64, kernel_size=(3, 3), strides=(1, 1), padding="valid")) model.add(ELU()) model.add(Conv2D(filters=64, kernel_size=(3, 3), strides=(1, 1), padding="valid")) model.add(ELU()) model.add(Conv2D(filters=64, kernel_size=(3, 3), strides=(1, 1), padding="valid")) model.add(ELU()) model.add(Flatten()) model.add(Dense(units=100)) model.add(ELU()) model.add(Dropout(0.20)) model.add(Dense(units=50)) model.add(ELU()) model.add(Dense(units=10)) model.add(ELU()) model.add(Dense(units=1)) # optimizer = Adam(lr=0.0001) # optimizer = Adam(lr=0.001) optimizer = Adam() model.compile(loss='mse', optimizer=optimizer) return model if __name__ == '__main__': parser = argparse.ArgumentParser(description='Training Path') parser.add_argument( 'training_folder', type=str, help='Path to training folder, inside should have csv and IMG folder' ) parser.add_argument( 'log_file', type=str, nargs='?', default='driving_log.csv', help="The name of the driving log in csv formatted of 'center_img','left_img', 'right_img', " "'steering_angle', 'throttle', 'break', 'speed' " ) parser.add_argument( '--batch', type=int, default=128, help='Batch size.' ) parser.add_argument( '--es-patience', type=int, default=1, help='Early Stopping patience. This is the number of epoch to wait ' 'before stop when the loss_val no longer improving' ) parser.add_argument( '--epoch', type=int, default=10, help='Epoch parameter for the training' ) parser.add_argument( '--artifact-dst', type=str, default="model.h5", help='The artifact or model saved filename, default is current folder under model.h5, can ' 'specify to mounted folder to automatically make it persistent' ) args = parser.parse_args() device_name = tf.test.gpu_device_name() if device_name: print('Found GPU at: {}'.format(device_name)) else: print("Cannot find any GPU") training_df = pd.read_csv(os.path.join(args.training_folder, args.log_file), header=None, names=[ 'center_img', 'left_img', 'right_img', 'steering_angle', 'throttle', 'break', 'speed']) # remove the hardcoded IMG src location training_df['center_img'] = training_df['center_img'].str.split("/").str[-1] training_df['left_img'] = training_df['left_img'].str.split("/").str[-1] training_df['right_img'] = training_df['right_img'].str.split("/").str[-1] # In my data collection, 0 angle is too skewed # Resample it to only 500 to make it more evenly distributed # zero_angle = training_df.loc[training_df['steering_angle'] == 0] # non_zero = training_df.loc[training_df['steering_angle'] != 0] # training_df = non_zero # training_df = training_df.append(zero_angle.sample(500)) # training_df = training_df.reset_index(drop=True) # del zero_angle # del non_zero # split the train and validation set train_df, validation_df = train_test_split(training_df, test_size=0.2, random_state=1) model = create_model() start = pendulum.now() batch_size = args.batch train_generator = generator(train_df.values, batch_size=batch_size) validation_generator = generator(validation_df.values, batch_size=batch_size) # simple early stopping # # https://machinelearningmastery.com/how-to-stop-training-deep-neural-networks-at-the-right-time-using-early-stopping/ es = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=args.es_patience) mc = ModelCheckpoint(args.artifact_dst, monitor='val_loss', mode='min', verbose=1, save_best_only=True) history = model.fit_generator(train_generator, steps_per_epoch=ceil(len(train_df) / batch_size), validation_data=validation_generator, validation_steps=ceil(len(validation_df) / batch_size), epochs=args.epoch, verbose=1, callbacks=[es, mc]) end = pendulum.now() print("The whole training took", (end - start).in_words())
5db3115b152b8fdba3befa6aedf47c9afede67b0
[ "Markdown", "Python", "Text" ]
3
Markdown
mahadirz/CarND-Behavioral-Cloning-P3
d719ab8529b21a53be01d5eb05c7aa0359c8b7d9
f3082406bcb7065f01d81560f3b18edd3342bb43
refs/heads/master
<repo_name>hulakdar/UE_Runner<file_sep>/Source/MyProject/MyProjectCharacter.h // Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "GameFramework/Character.h" #include "MyProjectCharacter.generated.h" UCLASS(config=Game) class AMyProjectCharacter : public ACharacter { GENERATED_BODY() /** Camera boom positioning the camera behind the character */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true")) class USpringArmComponent* CameraBoom; /** Follow camera */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true")) class UCameraComponent* FollowCamera; public: AMyProjectCharacter(); virtual void Tick(float DeltaSeconds) override; /** Base turn rate, in deg/sec. Other scaling may affect final turn rate. */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category=Camera) float BaseTurnRate; /** Base look up/down rate, in deg/sec. Other scaling may affect final rate. */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category=Camera) float BaseLookUpRate; UPROPERTY(VisibleAnywhere, Category = "Runner", meta = (DisplayName = "Can Turn")) uint8 bCanTurn : 1; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Runner", meta = (DisplayName = "Alive")) uint8 bAlive : 1; protected: void MoveForward(); /** * Called for side to side input * @param Rate Only sign matters. Positive turns right. */ void MoveRight(float Rate); /** * Turning 90 degrees. * @param Rate Only sign matters. Positive turns right. */ void Turn(float Rate); /** Handler for when a touch input begins. */ void TouchStarted(ETouchIndex::Type FingerIndex, FVector Location); /** Handler for when a touch input stops. */ void TouchStopped(ETouchIndex::Type FingerIndex, FVector Location); protected: // APawn interface virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override; // End of APawn interface public: /** Returns CameraBoom subobject **/ FORCEINLINE class USpringArmComponent* GetCameraBoom() const { return CameraBoom; } /** Returns FollowCamera subobject **/ FORCEINLINE class UCameraComponent* GetFollowCamera() const { return FollowCamera; } };
de7218fbdb0192aaaee62b1a49b5a820d87f2b08
[ "C++" ]
1
C++
hulakdar/UE_Runner
b9b04503ac555c40d1fd301799f7dba5294c0793
b65f6de5d25ce59c5eaa70f20d20114f90d1211f