branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep># nextjs-socketsio
An example of next.js working with sockets.io
<file_sep>import {Component} from 'react';;
import io from 'socket.io-client';
class Home extends Component {
constructor(props) {
super(props);
this.state = {
hello: ''
}
}
componentDidMount() {
this.socket = io();
this.socket.on('now', data => {
this.setState({
hello: data.message,
});
});
}
render() {
return (
<h1>{this.state.hello}</h1>
)
}
}
export default Home;
| 8f0941e1c63463b0cd99d3f2f54ef6115ee164b2 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | HDv2b/nextjs-socketsio | 9a7f3963295cbb585b17023dfc8090a07db6fb81 | 5e6cbd0eae05bf3b570180423911d40e56903da5 |
refs/heads/master | <file_sep>let express=require('express')
let router=express.Router();
let feedbackController = require('./controller')
router.post('/feedbackdetails',feedbackController.feedbackadd)
module.exports=router;<file_sep>let express=require('express')
let router=express.Router();
let loginController = require('./controller')
router.post('/login',loginController.loginadd)
module.exports=router;<file_sep>module.exports = {
port : 3001,
jwt : {
secret:"<KEY>",
options: {expiresIn: 365 * 60 * 60 * 24 }
},
db : {
mongo:{
// uri:"mongodb://localhost:27017/logindb",
uri:"mongodb://localhost:27017/sample",
options : {
user :'',
pass : ''
}
}
},
baseUrl:'http://localhost:'+3001,
}
<file_sep>// let mongoose = require('mongoose');
/* let UserService = require('./service'); */
// let jwt = require('jsonwebtoken');
// let config = require('../../../config/config');
let usersCollection = require('../login/model')
let useradd = (req,res)=>{
console.log(req.body);
usersCollection.find({ Name : { $exists: true } })
.then(
(response)=>{
// console.log(response)
res.status(200).json({ status : true , message :"Success" , addDetails:response});
}
)
.catch(
(error)=>{
res.status(500).json({ status : false , message :"Error while creating userlist , please do again" })
}
)
}
module.exports = {
useradd
}<file_sep>let express = require('express');
let router = express.Router();
let SupportController = require('./controller');
router.post('/add', SupportController.add);
router.get('/get-all-by-user',SupportController.getAllByUser);
module.exports = router;<file_sep>// let mongoose = require('mongoose');
/* let UserService = require('./service'); */
// let jwt = require('jsonwebtoken');
// let config = require('../../../config/config');
let loginCollection = require('./model')
let loginadd = (req, res) => {
console.log(req.body)
loginCollection.findOne({ Email: req.body.email, Password: <PASSWORD> })
.then(
(response) => {
console.log(response)
if (response != null) {
res.status(200).json({ status: true, message: "Success", addDetails: response });
}
else {
res.status(200).json({ status: false, message: "Wrong Credentials" });
}
}
)
.catch(
(error) => {
res.status(500).json({ status: false, message: "Error while creating add , please again" })
}
)
}
module.exports = {
loginadd
}<file_sep>let express=require('express')
let router=express.Router();
let userListController = require('./controller');
router.get('/userlist',userListController.useradd);
module.exports=router;<file_sep>let mongoose = require('mongoose');
let ObjectId = mongoose.SchemaTypes.ObjectId;
let Schema = new mongoose.Schema({
comment: { type: String },
}, {
timestamps: true
});
module.exports = mongoose.model('sample', Schema);<file_sep>let feedbackcollection = require('../login/model')
let feedbackadd=(req,res)=>{
console.log(req.body);
feedbackcollection.find({ Email : req.body.empEmail })
.then(
(response)=>{
console.log(response)
if(response!=null){
feedbackcollection.update({Email: req.body.empEmail},{$push:{"feedback": {senderEmail: req.body.youremail,
SenderName : req.body.yourname,comments : req.body.comments,overalExprericne : {good :req.body.radiobutton.good,
bad :req.body.radiobutton.bad,average :req.body.radiobutton.average}}}})
.then(
(response)=>{
console.log(response);
res.status(200).json({ status : true , message :"Success" , addDetails:response})
}
)
.catch(
(error)=>{
res.status(200).json({ status : false , message :"Error while creating , please do again" })
}
)
}
else{
res.status(500).json({ status : false , message :"syntax error"})
}
}
)
}
module.exports = {
feedbackadd
}<file_sep>let express = require('express');
let router = express.Router();
// let loginRouter = require('../api/v1/login/route');
let loginRouter = require('../api/v1.0/login/route');
let userRouter = require('../api/v1.0/userslist/route');
let feedbackrouter = require('../api/v1.0/feedback/route');
let SupportRouter=require('../api/v1.0/support/route');
// let submitRouter = require('../api/v1/submitadd/route')
// router.use('/create',loginRouter)
router.use('/Login',loginRouter);
router.use('/UserDetails',userRouter);
router.use('/feedback',feedbackrouter);
router.use('/support',SupportRouter);
module.exports = router;<file_sep>let mongoose = require('mongoose');
// let objectId = mongoose.Schema.objectId;
let loginDetails = new mongoose.Schema({
Email : String,
Password : <PASSWORD>,
Name:String,
Designation : String,
EmpId : Number,
DateOfJoining : Date,
feedback : [{
senderEmail : String,
SenderName : String,
comments : String,
overalExprericne :[{
good : String,
bad : String,
average : String
}]
}]
})
let registerModel = mongoose.model('EmployeeDetails',loginDetails);
module.exports = registerModel; | 29fe1e7d6c4d30fc6aa696f2c065666c7dc8a57f | [
"JavaScript"
] | 11 | JavaScript | sukumar-p/konnect-backend | 2617087cf99c5d1ec24c0bc297629bf3f6c11253 | 1447021ed467becb12c870f08065d59bd997b591 |
refs/heads/master | <file_sep>//
// main.cpp
// scrapeToUDP
//
// Created by <NAME> on 10/30/12.
// Copyright (c) 2012 Adobe. All rights reserved.
//
#include <iostream>
void printUsage(const char*name);
int main(int argc, const char * argv[])
{
if(argc == 1)
printUsage(argv[0])
int i = 1;
while(i < argc)
i = eatArgs(argv, i);
// insert code here...
return 0;
}
void printUsage(const char*name) {
printf("usage: %s <x> <y> <width> <height> [scale] \n",argv[0]);
}
NSColor *MyColorAtScreenCoordinate(CGDirectDisplayID displayID, NSInteger x, NSInteger y) {
CGImageRef image = CGDisplayCreateImageForRect(displayID, CGRectMake(x, y, 1, 1));
NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc] initWithCGImage:image];
CGImageRelease(image);
NSColor *color = [bitmap colorAtX:0 y:0];
[bitmap release];
}<file_sep># scrapeToUDP
comamnd line tool to scrape pixels to a UDP port
build as a simple xcode project
todo: detail command line options here
(options set width, height, zoom factor & frame rate)
| b02301ed8cc9b814ebdf291c57f77215bb40ba46 | [
"Markdown",
"C++"
] | 2 | C++ | kukulski/scrapeToUDP | c323979c6ac3ec1f60b25c661e04015ba00efa2a | 6a406cfb0b1d57ee9d85b0e717dd8e150c118081 |
refs/heads/master | <repo_name>raeynok/gathering-mean<file_sep>/app/models/competency.server.model.js
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Competency Schema
*/
var CompetencySchema = new Schema({
name: {
type: String,
default: '',
required: 'Please fill Competency name',
trim: true
},
createdOn: {
type: Date,
default: Date.now
},
users: [{
type: Schema.ObjectId,
ref: 'User'
}],
missions: [{
type: Schema.ObjectId,
ref: 'Mission'
}],
tasks: [{
type: Schema.ObjectId,
ref: 'Task'
}]
});
/**
* Competency methods
*/
/**
* @brief Ajoute une mission qui contient cette compétence
* @param userId Utilisateur qui cherche à ajouter une mission à cette compétence
* @param missionIdToAdd Mission à ajouter
*/
CompetencySchema.methods.addMission = function(userId, missionIdToAdd){
CompetencySchema.methods.verifyRole(userId, 'admin', function(){
this.model('Competency').missions.push(missionIdToAdd, function(){
console.log(missionIdToAdd + ' ajoutée');
});
});
};
/**
* @brief Ajoute un utilisateur qui contient cette compétence
* @param userId Utilisateur qui cherche à ajouter un utilisateur à cette compétence
* @param userIdToAdd Utilisateur à ajouter
*/
CompetencySchema.methods.addUser = function(userId, userIdToAdd){
CompetencySchema.methods.verifyRole(userId, 'admin', function(){
this.model('Competency').users.push(userIdToAdd, function(){
console.log(userIdToAdd + ' ajouté(e)');
});
});
};
/**
* @brief Ajoute une tache qui contient cette compétence
* @param userId Utilisateur qui cherche à ajouter une tache à cette compétence
* @param taskIdToAdd Id de la tache à ajouter
*/
CompetencySchema.methods.addTask = function(userId, taskIdToAdd){
CompetencySchema.methods.verifyRole(userId, 'admin', function(){
this.model('Competency').tasks.push(taskIdToAdd, function(){
console.log(taskIdToAdd + ' ajoutée');
});
});
};
/**
* @brief Ajoute une mission qui contient cette compétence
* @param userId Utilisateur qui cherche à ajouter une tache à cette compétence
* @param missionIdToAdd Id de la mission à ajouter
*/
CompetencySchema.methods.addMission = function(userId, missionIdToAdd){
CompetencySchema.methods.verifyRole(userId, 'admin', function(){
this.model('Competency').missions.push(missionIdToAdd, function(){
console.log(missionIdToAdd + ' ajoutée');
});
});
};
/**
* @brief Vérifie qu'un utilisateur a assez de droits pour accéder à une méthode.
* @param userId Utilisateur qui veut faire un truc
* @param userRole Role qu'on cherche pour l'utilisateur
* @param cb Callback : si l'utilisateur a le rôle
* @returns {*} cf callback
*/
CompetencySchema.methods.verifyRole = function(userId, userRole, cb){
return this.model('Mission').members.findOne({user : userId}, function(foundMember){
if(userRole.indexOf(foundMember.role) > -1){
return cb;
}
else{
return console.log('Vous n\'avez pas accès à cela');
}
});
};
mongoose.model('Competency', CompetencySchema);
<file_sep>/public/modules/cards/config/cards.client.config.js
'use strict';
// Configuring the Articles module
angular.module('cards').run(['Menus',
function(Menus) {
// Set top bar menu items
Menus.addMenuItem('topbar', 'Cards', 'cards', 'dropdown', '/cards(/create)?');
Menus.addSubMenuItem('topbar', 'cards', 'List Cards', 'cards');
Menus.addSubMenuItem('topbar', 'cards', 'New Card', 'cards/create');
}
]);<file_sep>/app/models/task.server.model.js
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Task Schema
*/
var TaskSchema = new Schema({
name: {
type: String,
default: '',
required: 'Please fill Task name',
trim: true
},
createdOn: {
type: Date,
default: Date.now
},
missions: [{
type: Schema.ObjectId,
ref: 'Mission'
}],
users: [{ //Liste de tous les gens qui font la tâche actuellement
type: Schema.ObjectId,
ref: 'User'
}],
currentUser: { //User qui a téléchargé cette copie de la tâche
type: Schema.ObjectId,
ref: 'User'
},
competencies: [{
type: Schema.ObjectId,
ref: 'Competency'
}],
themes: [{
type: Schema.ObjectId,
ref: 'Theme'
}],
weeklyTask: {
type: Boolean,
default: false
},
achieved: { //N'a un intérêt que sur les "copies" de la task
type: Boolean,
default: false
},
result: { //Résultat obtenu pour cette tâche. Valeur chiffrée. N'est pas requise.
type: Number,
default: 0
},
gold: {
type: Number,
default: 0
}
});
/*
* Task methods
*/
/**
* @brief Teste si un résultat a la valeur attendue
* @param resultTest Valeur à laquelle on compare result
* @param currentUser Utilisateur dont on teste le résultat
*/
TaskSchema.methods.checkResult = function(resultTest, currentUser){
if(resultTest<=this.model('Task').result) { //Si on a assez de points
for(var i=0;i<this.model('Task').missions.size;i++) {
currentUser.achieveTask(this.model('Task')._id,this.model('Task').missions(i));
}
}
else
{
console.log('Result ne match pas.');
}
};
mongoose.model('Task', TaskSchema);
<file_sep>/public/modules/patterns/config/patterns.client.routes.js
'use strict';
//Setting up route
angular.module('patterns').config(['$stateProvider',
function($stateProvider) {
// Patterns state routing
$stateProvider.
state('listPatterns', {
url: '/patterns',
templateUrl: 'modules/patterns/views/list-patterns.client.view.html'
}).
state('createPattern', {
url: '/patterns/create',
templateUrl: 'modules/patterns/views/create-pattern.client.view.html'
}).
state('viewPattern', {
url: '/patterns/:patternId',
templateUrl: 'modules/patterns/views/view-pattern.client.view.html'
}).
state('editPattern', {
url: '/patterns/:patternId/edit',
templateUrl: 'modules/patterns/views/edit-pattern.client.view.html'
});
}
]);<file_sep>/app/routes/competencies.server.routes.js
'use strict';
module.exports = function(app) {
var users = require('../../app/controllers/users.server.controller');
var competencies = require('../../app/controllers/competencies.server.controller');
// Competencies Routes
app.route('/competencies')
.get(competencies.list)
.post(users.requiresLogin, competencies.create);
app.route('/competencies/:competencyId')
.get(competencies.read)
.delete(users.requiresLogin, competencies.hasAuthorization, competencies.delete);
// Finish by binding the Competency middleware
app.param('competencyId', competencies.competencyByID);
};
<file_sep>/public/modules/missions/config/missions.client.routes.js
'use strict';
//Setting up route
angular.module('missions').config(['$stateProvider',
function($stateProvider) {
// Missions state routing
$stateProvider.
state('mission',{
abstract : true,
template : '<ui-view/>',
resolve: {missions: function (allMissionsLoader) {return allMissionsLoader();}},
controller: 'MissionsController'
}).
state('mission.listMissions', {
url: '/missions',
templateUrl: 'modules/missions/views/list-missions.client.view.html'
}).
state('mission.createMission', {
url: '/missions/create',
templateUrl: 'modules/missions/views/create-mission.client.view.html'
}).
state('mission.viewMission', {
url: '/missions/:missionId',
templateUrl: 'modules/missions/views/view-mission.client.view.html',
resolve: {currentMission: function(missionLoader){return missionLoader();}}
}).
state('mission.editMission', {
url: '/missions/:missionId/edit',
templateUrl: 'modules/missions/views/edit-mission.client.view.html',
});
}
]);
<file_sep>/public/modules/patterns/services/patterns.client.service.js
'use strict';
//Patterns service used to communicate Patterns REST endpoints
angular.module('patterns').factory('Patterns', ['$resource',
function($resource) {
return $resource('patterns/:patternId', { patternId: '@_id'
}, {
update: {
method: 'PUT'
}
});
}
]);<file_sep>/app/routes/search.server.routes.js
'use strict';
module.exports = function(app) {
// User Routes
var search = require('../../app/controllers/search.server.controller');
app.route('/search').get(search.read);
};
<file_sep>/public/modules/messages/config/messages.client.routes.js
'use strict';
//Setting up route
angular.module('messages').config(['$stateProvider',
function($stateProvider) {
// Messages state routing
$stateProvider.
state('listMessages', {
url: '/messages/:userId',
templateUrl: 'modules/messages/views/list-messages.client.view.html',
controller : 'MessagesController',
resolve : {allMessages : function(allMessagesLoader) {return allMessagesLoader();} }
}).
state('createMessage', {
url: '/messages/create',
controller : 'MessagesController',
templateUrl: 'modules/messages/views/create-message.client.view.html'
}).
state('viewMessage', {
url: '/messages/:userId/:messageId',
controller : 'MessagesController',
templateUrl: 'modules/messages/views/view-message.client.view.html'
});
}
]);
<file_sep>/app/routes/avatars.server.routes.js
'use strict';
module.exports = function(app) {
var users = require('../../app/controllers/users.server.controller');
var avatars = require('../../app/controllers/avatars.server.controller');
// Avatars Routes
app.route('/avatars')
.get(avatars.list)
.post(users.requiresLogin, avatars.create);
app.route('/avatars/:avatarId')
.get(avatars.read)
.put(users.requiresLogin, avatars.hasAuthorization, avatars.update)
.delete(users.requiresLogin, avatars.hasAuthorization, avatars.delete);
// Finish by binding the Avatar middleware
app.param('avatarId', avatars.avatarByID);
};
| f23b002b03f06bc993f4d1adb090352614ff67b3 | [
"JavaScript"
] | 10 | JavaScript | raeynok/gathering-mean | 19a5b0e78971141f827112e61bb7a040c780bdf5 | a514112a7236f85f18bd8712e66024aa45ba780c |
refs/heads/master | <repo_name>EmmanuelJoshua/TicTicToe<file_sep>/TicTacToe/src/tictactoe/PlayerO.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tictactoe;
import javafx.scene.image.Image;
/**
*
* @author Spark
*/
public class PlayerO {
static int score;
String player = "PlayerO";
static Image oImage = new Image("/tictactoe/images/o.png");
public static Image getOImage() {
return oImage;
}
public void incrementOScore(){
score++;
}
public static int getOScore(){
return score;
}
}
<file_sep>/TicTacToe/src/tictactoe/PlayerX.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tictactoe;
import javafx.scene.image.Image;
/**
*
* @author Spark
*/
public class PlayerX {
static int score;
String player = "PlayerX";
static Image xImage = new Image("/tictactoe/images/x.png");
public static Image getXImage() {
return xImage;
}
public void incrementXScore(){
score++;
}
public static int getXScore(){
return score;
}
}
| 9f8d6750e36d237dd72d440b64ecdcac9712a89d | [
"Java"
] | 2 | Java | EmmanuelJoshua/TicTicToe | 886543e60d2728079486f5df2398589f511932d3 | eecd80e66a6a8a06034955a9d5a304005c407418 |
refs/heads/master | <file_sep>library(shiny)
shinyServer(function(input, output) {
output$distPlot <- renderPlot({
#par(mfrow=c(3,1))
curve(input$a*x^0,-6,6,ylim=c(-6,6),xlim=c(-6,6),lwd=2,col="blue",ylab="f(x)",main="y=f(x)=a")
grid(12,12,col="red", lwd=1, lty=2)
abline(v=0,col="black", lwd=1,lty=2)
abline(h=0,col="black", lwd=1,lty=2)
})
})
<file_sep>nose
====
noseque colocar
<file_sep>library(shiny)
shinyUI(fluidPage(
# Comentar...
titlePanel("O gráfico da função constante segundo <NAME> (Cálculo I)"),
# Comentar...
sidebarLayout(
sidebarPanel(
sliderInput("a",
"Valor da constante a",
min = -6,
max = 6,
step = 0.5,
value = 1)
),
# Comentar...
mainPanel(
plotOutput("distPlot")
)
)
))
| ccb861448d04fe61361104e1d7e7e8b859f005c8 | [
"Markdown",
"R"
] | 3 | R | clobos/nose | e1f6038ce61a4b33a4354130da600fbfece8f6ab | 6315247fa924b394793c0556e2bbe32ec780a9cd |
refs/heads/master | <repo_name>pipo02mix/IseeClient<file_sep>/public/js/main.js
require.config({
paths: {
// Major libraries
jquery: 'libs/jquery/jquery-min',
async: 'libs/require/async',
underscore: 'libs/underscore/underscore-min', // https://github.com/amdjs
backbone: 'libs/backbone/backbone-min', // https://github.com/amdjs
sinon: 'libs/sinon/sinon.js',
// Require.js plugins
text: 'libs/require/text',
order: 'libs/require/order'
}
});
// Let's kick off the application
require([
'jquery',
'events',
'app',
'backbone',
'collections/quejas',
'mapProvider'
], function($, Event, app, B, QuejasCollection, geo){
var quejas = new QuejasCollection();
quejas.on("sync", function(){
_.each(this.models, function(model){
geo.addMarker({
'lat': model.get('coords')[0],
'lon': model.get('coords')[1],
'title': model.get('title')
});
});
});
Event.on("map-load", function(){
quejas.fetch({ data: geo.cp() , success: function(quejas) {
quejas.trigger("sync");
}});
});
Event.on("map-moved", function(){
quejas.fetch({ data: geo.vp() });
});
$(function(){
//init map system
geo.init(app.consts.mapProvider);
});
});<file_sep>/public/js/mapProvider.js
define([
'underscore',
'backbone',
'events',
'jquery',
'mapProviderGoogle'
], function(_, Backbone, Event, $, provider) {
var map
, markers = []
, currentPosition
, viewportPosition;
function initialize() {
getGeolocation();
Event.on("currentPosition-load", function(){
provider.drawMap(currentPosition);
viewportPosition = currentPosition;
});
}
function reDraw(){
}
function addMarker(marker){
markers.push(marker);
provider.addMarker(marker);
}
function getCurrentPosition(){
return currentPosition;
}
function getViewportPosition(){
viewportPosition = provider.getViewportCenterPosition();
return viewportPosition;
}
function getGeolocation(){
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
currentPosition = {
lat: position.coords.latitude,
lon: position.coords.longitude
};
Event.trigger("currentPosition-load");
}, function() {
currentPosition = handleNoGeolocation(true);
Event.trigger("currentPosition-load");
});
} else {
// Browser doesn't support Geolocation
currentPosition = handleNoGeolocation(false);
Event.trigger("currentPosition-load");
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var pos = {
lat: 40.42761,
lon: -1.195107,
title: 'No hemos podido localizar tu posicion'
};
return pos;
}
return {
init: initialize,
addMarker: addMarker,
cp: getCurrentPosition,
vp: getViewportPosition,
markers: markers
};
});
<file_sep>/public/js/models/queja.js
define([
'backbone'
], function(B){
var QuejaModel = B.Model.extend({
idAttribute: "_id",
defaults: {
"title" : "mi queja",
description: String,
createdAt: Date.now(),
votes: 1,
state: 'pendiente',
owner: user._id ,
category: 'otros',
image: '',
"coords": [ 42.12, 0.221 ]
}
});
return QuejaModel;
});<file_sep>/public/js/app.js
define([
'jquery',
], function($){
var app = {};
app.consts = {
mapProvider : 'Google'
};
return app;
});
<file_sep>/CHANGELOG.md
== 1.0.0
* Loading map center in location of user
* Query complaints one kilometer around position of map's center
*<file_sep>/public/js/collections/quejas.js
define([
'backbone',
'models/queja'
], function(B, QuejaModel){
var QuejasCollection = B.Collection.extend({
model: QuejaModel,
url: 'http://isee.tiatere.es:8080/quejas'
});
return QuejasCollection;
});<file_sep>/public/js/quejas.js
var QuejaModel = B.Model.extend({
idAttribute: "_id",
urlRoot : '/quejas',
defaults: {
"title" : "mi queja",
"coords": [ 42.12, 0.221 ]
}
});
var QuejasCollection = B.Collection.extend({
model: QuejaModel,
url: 'http://isee.tiatere.es:3000/quejas'
});
var QuejaView = B.View.extend({
initialize: function (){
this.render();
},
render: function(){
app.modules.geolocation.addMarker({
'lat': this.model.get('coords')[0],
'lon': this.model.get('coords')[1]
});
}
});
/*var queja = new QuejaModel({
"title": "mi primera queja",
"loc": [41.118778, 1.242837]
});*/
var c_queja = new QuejasCollection();
c_queja.on("sync", function(){
_.each(this.models, function(model){
app.modules.geolocation.addMarker({
'lat': model.get('loc')[0],
'lon': model.get('loc')[1],
'title': model.get('title')
});
});
});
$(document).bind("map-load", function(){
c_queja.fetch({ data: app.modules.geolocation.currentPosition,
success: function(quejas) {
//console.log(quejas);
}
});
});
$(document).bind("map-moved", function(){
if (app.modules.geolocation.viewportPosition) {
c_queja.fetch({ data: app.modules.geolocation.viewportPosition,
success: function(quejas) {
console.log("query server");
}
});
}
});
| b39bb94f23dccef1b2cc7d850408ff3a19517521 | [
"JavaScript",
"Markdown"
] | 7 | JavaScript | pipo02mix/IseeClient | 861431d78abed02642bdcfbb6a94307ce1d0abb7 | 0085274f13a4153361d75fc8d17cbc512cadee12 |
refs/heads/master | <repo_name>swayamraina/Fix-Imports<file_sep>/testDir/innerTestDir/test_2.py
import pandas;
import tinytree;
<file_sep>/README.md
# Fix-Imports
<file_sep>/testDir/test_3.py
import django
print("another test file")
<file_sep>/testDir/test_1.py
import innerTestDir.test_2;
from . import test_3;
import tinytree;
from os import walk;
import utils;
from django.core import management;
for i in range(5):
print(i);
<file_sep>/fix-imports.py
import os;
_EMPTY = ""
_SCRIPT_NAME = 'fix-imports.py'
class FixImports:
def __init__(self, project_path):
self._project_path = project_path;
self._files = [];
self._imports = [];
self._failed_imports = [];
def read_file(self, file_path):
try:
file = open(file_path, 'r');
except FileNotFoundError as error:
print(error);
return [];
return file.readlines();
def extract_imports(self, file_content):
imports = [];
for line_content in file_content:
line_content = line_content.strip();
if not line_content.startswith('#'):
words = line_content.split(' ');
for index in range(len(words)):
if words[index] == 'from' or words[index] == 'import':
index = index + 1;
while words[index] == '':
index = index + 1;
pkg = words[index].split('.')[0];
if len(pkg) > 0:
if pkg.endswith(';'):
imports.append(pkg[:-1]);
else:
imports.append(pkg);
break;
return imports;
def remove_local_packages(self):
for file in self._files:
if file in self._imports:
self._imports.remove(file);
def try_imports(self, packages, append=False):
for import_pkg in packages:
try:
__import__(import_pkg);
except ImportError as error:
print(error);
if append: self._failed_imports.append(import_pkg);
def download_libraries(self, packages):
try:
import pip;
except ImportError as error:
print(error);
return ;
for import_pkg in packages:
try:
pip.main(['install',import_pkg,'--user']);
except SystemExit as error:
print(error);
def fix(self):
for root, dirs, files in os.walk(self._project_path):
for file in files:
if file.strip().endswith('.py') and (file != _SCRIPT_NAME):
self._files.append(file.strip()[:-3]);
file_content = self.read_file(_EMPTY.join([root,'/',file]));
for import_pkg in self.extract_imports(file_content):
if import_pkg not in self._imports:
self._imports.append(import_pkg);
self.remove_local_packages();
self.try_imports(self._imports, True);
self.download_libraries(self._failed_imports);
if __name__ == '__main__':
imports = FixImports(os.getcwd());
imports.fix();
| c57ce3a14db0d076eef5e999bdc496f75e8a8d56 | [
"Markdown",
"Python"
] | 5 | Python | swayamraina/Fix-Imports | 99b0189b90774dc5f319bf01596847c0e5df6712 | 004738d6e60521c1fcd1f7fd1b41b057a182eed4 |
refs/heads/master | <file_sep><!DOCTYPE html>
<html>
<head>
<title>Loteria</title>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
</head>
<body>
<?php
use Loteria\Loteria;
require('Loteria.class.php');
$loteria = new Loteria(2, 5);
if ($loteria->_isValid) {
$loteria->gerandoJogos();
$loteria->sorteio();
$tabelaJogos = $loteria->confereSorteio();
echo $tabelaJogos;
}
?>
</body>
</html><file_sep><?php
namespace Loteria;
use FFI\Exception;
class Loteria
{
private $dezenas;
private $resultado;
private $total;
private $jogos = array();
public $_isValid = true;
public function getDezenas()
{
return $this->dezenas;
}
public function setDezenas($dezenas)
{
$dezenasAceitas = array(6, 7, 8, 9, 10);
if (!in_array($dezenas, $dezenasAceitas)) {
throw new Exception('As dezenas devem ser escolhidas entre 6 e 10');
}
$this->dezenas = $dezenas;
}
public function getResultado()
{
return $this->resultado;
}
public function setResultado($resultado)
{
$this->resultado = $resultado;
}
public function getTotal()
{
return $this->total;
}
public function setTotal($total)
{
$this->total = $total;
}
public function getJogos()
{
return $this->jogos;
}
public function setJogos($jogos)
{
$this->jogos = $jogos;
}
/**
* Classe construtora para receber os valores de Quantidade Dezena e Total de Jogos.
* Caso nao sejam enviados a Quantidade Dezena recebera 6, e o Total de Jogos recebera 1.
*
* @param $qttyDezenas int
* @param $totalJogos int
*/
public function __construct(int $qttyDezenas = 6, int $totalJogos = 1)
{
try {
$this->setDezenas($qttyDezenas);
$this->setTotal($totalJogos);
} catch (Exception $e) {
$this->_isValid = false;
echo 'Exceção capturada: ', $e->getMessage(), "\n";
}
}
/**
* Classe privada para gerar um jogo baseado no valor de Dezenas passadas no __construct.
*
* @return $numeros array
*/
private function gerandoNumeros()
{
$numeros = range(01, 60);
shuffle($numeros);
$numeros = array_slice($numeros, 0, $this->getDezenas());
asort($numeros);
return $numeros;
}
/**
* Classe publica para gerar o numero de jogos passados no Total de Jogos do __construct.
* Usa a funcao gerandoNumeros() para retornar os numeros de cada jogo.
*
*/
public function gerandoJogos()
{
$jogosArr = array();
for ($i = 0; $i < $this->getTotal(); $i++) {
$novoJogo = $this->gerandoNumeros();
array_push($jogosArr, $novoJogo);
}
$this->setJogos($jogosArr);
}
/**
* Classe publica para gerar o jogo que e considerado o resultado.
*/
public function sorteio()
{
$this->setResultado($this->gerandoNumeros());
}
/**
* Classe publica para verificar o resultado dos jogos e exibi-los na tela.
* Usa as funcoes geraLinhas() e geraResultado() para montar a tabela.
*/
public function confereSorteio()
{
$linhas = "";
foreach ($this->getJogos() as $jogo) {
$jogoConferido = array_intersect($jogo, $this->getResultado());
$linhas .= (string) $this->geraLinhas($jogo, $jogoConferido);
}
return $this->geraResultado($linhas);
}
/**
* Classe publica para gerar as linhas que serao exibidas na tabela.
*
* @param $jogo array
* @param $jogoConferido array
*
* @return $linha string
*/
private function geraLinhas(array $jogo, array $jogoConferido)
{
$jogoMontado = (string) implode(" - ", $jogo);
$acertos = (string) implode(" - ", $jogoConferido);
$nAcertos = (int) count($jogoConferido);
$linha = "
<tr>
<td>{$jogoMontado}</td>
<td>{$nAcertos}</td>
<td>{$acertos}</td>
</tr>
";
return (string) $linha;
}
/**
* Classe publica para gerar a tabela com o resultado dos jogos.
*
* @param $linhas string
*
* @return $tabela string
*/
private function geraResultado(string $linhas)
{
$resultadoSorteio = implode(" - ", $this->getResultado());
$tabela = "
<p><b>Dezenas Sorteadas: {$resultadoSorteio}</b></p>
<table style='width:100%; font-family: arial, sans-serif; border-collapse: collapse; text-align:center'>
<tr>
<th>Dezenas</th>
<th>Quantidade de Acertos</th>
<th>Dezenas Acertadas</th>
</tr>
{$linhas}
</table>
";
return $tabela;
}
}
<file_sep><p align="center"><a target="_blank" href="https://matheus.sgomes.dev"><img src="https://matheus.sgomes.dev/img/logo_azul.png"></a></>
👤 **<NAME>**
* Website: https://matheus.sgomes.dev
* Github: [@Matheussg42](https://github.com/Matheussg42)
* LinkedIn: [@matheussg](https://linkedin.com/in/matheussg)
---
#### Nesta Página:
* [Tecnologias](#tecnologias)
* [Projeto](#projeto)
<span id="tecnologias"></span>
## Tecnologias
Esse projeto foi desenvolvido com as seguintes tecnologias:
- [PHP](https://www.php.net/)
<span id="projeto"></span>
## Projeto
O index.php exibe as dezenas sorteadas, os jogos feitos, o número de acerto em cada jogo, e as dezenas acertadas. | 94b8ec984e9b36ed2634e1f1eb2bd27353f0f96f | [
"Markdown",
"PHP"
] | 3 | PHP | Matheussg42/gerenciador-loteria | 9aae8fefbea269d819f8b807916e24e932a88115 | 092804f19af8ab44ea25bc6b3a18f9e7e903b4d9 |
refs/heads/master | <repo_name>mikrozone/ARM_SWIM-LCD-DEMO_LPC1788-SK<file_sep>/README.md
ARM_SWIM-LCD-DEMO_LPC1788-SK<br>
=============================<br>
<br>
Simple example of the NXP's SWIM graphics library on LPC1788 (IAR LPC1788-SK board)<br>
<br>
After starting, are printed demo 5 text lines with different fonts.<br>
<br>
Application create two windows on screen:<br>
- main window, with full display size<br>
- second windows is floating and smaller one, with moving on x direction<br>
<br>
On each window running counter<br>
<file_sep>/ARM_SWIM-LCD-DEMO_LPC1788-SK/main.c
// ******************************************************************************************************
// main.c
//
// Created on: 20.8.2014
// Author: "<EMAIL>"
// version: 0.1
// ******************************************************************************************************
#include "global.h"
#include "../Chip/Drivers/Include/lpc177x_8x_lcd.h"
// ******************************************************************************************************
// Globals
// ******************************************************************************************************
extern LCD_Config_Type lcd_config; // LCD active struct
// ******************************************************************************************************
// Function prototypes
// ******************************************************************************************************
// ------------------------------------------------------------------------------------------------------
// Function description
void main(void)
{
BOOL_32 Result;
SWIM_WINDOW_T MainWindow;
SWIM_WINDOW_T FloatWindow;
COLOR_T clr, *fblog;
Init_SDRAM();
Init_LCD();
//Init_LCD_Cursor();
Init_LCD_BackLight();
//Init_TS();
Enable_LCD();
Set_LCD_BackLight(100); // set backlight to 20%
fblog = (COLOR_T *)lcd_config.lcd_panel_upper;
Result = swim_window_open(&MainWindow, LCD_H_SIZE, LCD_V_SIZE, fblog, 0, 0, 319, 239, 2, GREEN, WHITE, BLUE);
//swim_set_title(&MainWindow, "Main\0", BLUE);
swim_set_pen_color(&MainWindow, BLACK);
swim_set_font(&MainWindow,(FONT_T *)&font_x5x7);
swim_put_text(&MainWindow, "Font: font_x5x7\n");
swim_set_font(&MainWindow,(FONT_T *)&font_x6x13);
swim_put_text(&MainWindow, "Font: font_x6x13\n");
swim_set_font(&MainWindow,(FONT_T *)&font_rom8x8);
swim_put_text(&MainWindow, "Font: font_rom8x8\n");
swim_set_font(&MainWindow,(FONT_T *)&font_rom8x16);
swim_put_text(&MainWindow, "Font: font_rom8x16\n");
swim_set_font(&MainWindow,(FONT_T *)&font_winfreesys14x16);
swim_put_text(&MainWindow, "Font: font_winfreesys14x16\n");
Result = swim_window_open(&FloatWindow, LCD_H_SIZE, LCD_V_SIZE, fblog, 0, 150, 220 , 220, 2, RED, YELLOW, YELLOW);
swim_set_title(&FloatWindow, "Floating window\0", GREEN);
swim_set_font(&FloatWindow,(FONT_T *)&font_x5x7);
unsigned long i=0;
unsigned char buff[200];
do
{
swim_set_font(&MainWindow,(FONT_T *)&font_winfreesys14x16);
sprintf(&buff[0],"Counter main: %d\n",i);
swim_put_text_xy(&MainWindow, buff, 160,80);
swim_set_font(&FloatWindow,(FONT_T *)&font_x5x7);
sprintf(&buff[0],"Counter float: %d\n",i);
swim_put_text_xy(&FloatWindow, buff,50,20);
i ++;
if(i%202 == 0)
{
if(i>5200) i=0;
//swim_window_close(&FloatWindow);
Result = swim_window_open(&FloatWindow, LCD_H_SIZE, LCD_V_SIZE, fblog, (i/100) +2, 150, (i/100 )+220 , 220, 2, RED, YELLOW, YELLOW);
swim_set_title(&FloatWindow, "Floating window\0", GREEN);
}
}while(1);
}
<file_sep>/ARM_SWIM-LCD-DEMO_LPC1788-SK/DRV/TouchScreen/TS_Analog.c
/*
* TS_Analog.c
*
* Created on: 11.8.2014
* Author: peterj
*/
#include "global.h"
#include "../Chip/Drivers/Include/lpc177x_8x_timer.h"
#include "../Chip/Drivers/Include/lpc177x_8x_gpio.h"
#include "../Chip/Drivers/Include/lpc177x_8x_pinsel.h"
#include "../Chip/Drivers/Include/lpc177x_8x_adc.h"
// ******************************************************************************************************
// Function prototypes
// ******************************************************************************************************
// extern unsigned long install_irq(unsigned long IntNumber, void *HandlerAddr, unsigned long Priority);
void Init_TS(void);
void Enable_TS(void);
void Disable_TS(void);
// private
static void _Set_TS_to_digital(void); // switch pin function to digital sensing of press touch area
// ******************************************************************************************************
// Globals
// ******************************************************************************************************
static int16_t ConvertCoord(int16_t Coord, int16_t MinVal, int16_t MaxVal, int16_t TrueSize);
uint8_t TS_Activated_Flag;
unsigned int x_values[num_samples]; // array to store x_samples
unsigned int y_values[num_samples]; // array to store y_samples
static short TS_x_value = 1;
static short TS_y_value = -1;
TS_Init_Type TS_Config;
// --------------------------------------------------
// --------------------------------------------------
// Reconfigure appropriate pins connected to TS for digital function.
// After press to TS, this event generate interrupt.
void _Set_TS_to_digital(void)
{
//unsigned int test;
//X2 pin - Input, without pull resistors
PINSEL_ConfigPin(TS_X2_PORT,TS_X2_PIN, 0); // Set default function no. - GPIO
PINSEL_SetPinMode(TS_X2_PORT,TS_X2_PIN, PINSEL_BASICMODE_PULLUP); // without pull resistors
FIO_SetDir(TS_X2_PORT, 1 << TS_X2_PIN, GPIO_DIRECTION_INPUT); // Set as Input
//Y2 pin - Output, set to 0
PINSEL_ConfigPin(TS_Y2_PORT,TS_Y2_PIN, 0); // Set default function no. - GPIO
PINSEL_SetPinMode(TS_Y2_PORT,TS_Y2_PIN, PINSEL_BASICMODE_PLAINOUT); // without pull resistors
FIO_SetDir(TS_Y2_PORT, 1 << TS_Y2_PIN, GPIO_DIRECTION_OUTPUT); // Set as Output
FIO_ClearValue(TS_Y2_PORT, 1 << TS_Y2_PIN); // set to log.0
//Y1 pin - Output, without pull resistors
PINSEL_ConfigPin(TS_Y1_PORT,TS_Y1_PIN, 0); // Set default function no. - GPIO
PINSEL_SetPinMode(TS_Y1_PORT,TS_Y1_PIN, PINSEL_BASICMODE_PLAINOUT); // without pull resistors
FIO_SetDir(TS_Y1_PORT, 1 << TS_Y1_PIN, GPIO_DIRECTION_OUTPUT); // Set as Output
FIO_ClearValue(TS_Y1_PORT, 1 << TS_Y1_PIN); // set to log.0
//X1 pin - Input, without pull resistors
PINSEL_SetAnalogPinMode(TS_X1_PORT, TS_X1_PIN, DISABLE); // set to analog mode
PINSEL_ConfigPin(TS_X1_PORT,TS_X1_PIN, 0); // Set default function no. - GPIO
PINSEL_SetPinMode(TS_X1_PORT,TS_X1_PIN, PINSEL_BASICMODE_PLAINOUT); // without pull resistors
FIO_SetDir(TS_X1_PORT, 1 << TS_X1_PIN, GPIO_DIRECTION_INPUT); // Set as Input
}
// --------------------------------------------------
// return True if Touch screen is pressed
int _Get_TS_PressStatus(void)
{
if ((GPIO_ReadValue(TS_X1_PORT) & (1 << TS_X1_PIN))) return (FALSE);
else return (TRUE);
}
// --------------------------------------------------
// Detected IRQ event from X-Plus line, Falling edge.
void GPIO_IRQHandler(void)
{
if(GPIO_GetIntStatus(TS_X1_PORT, TS_X1_PIN, 1))
{
GPIO_ClearInt(TS_X1_PORT, 1 << TS_X1_PIN);
if (TS_Activated_Flag == TRUE) return;
TIM_Waitms (debounce); // debounce the touch
if(_Get_TS_PressStatus() == TRUE ) // set flag ...
{
TS_Activated_Flag = SET;
}
}
}
// --------------------------------------------------
// Firts initialization of the TS hardware
void Init_TS(void)
{
TIM_TIMERCFG_Type TIM_ConfigStruct;
TS_Config.ad_left = TOUCH_AD_LEFT;
TS_Config.ad_right = TOUCH_AD_RIGHT;
TS_Config.ad_top = TOUCH_AD_TOP;
TS_Config.ad_bottom = TOUCH_AD_BOTTOM;
TS_Config.lcd_h_size = LCD_H_SIZE;
TS_Config.lcd_v_size = LCD_V_SIZE;
TS_Config.Priority = 31;
// init timer
TIM_ConfigStruct.PrescaleOption = TIM_PRESCALE_USVAL;
TIM_ConfigStruct.PrescaleValue = 1;
// Set configuration for Tim_config and Tim_MatchConfig
TIM_Init(LPC_TIM0, TIM_TIMER_MODE,&TIM_ConfigStruct);
GPIO_Init();
_Set_TS_to_digital(); // set TS pins to digital mode
// next, read IO0IntEnF register and set only desired bit.
if (TS_X1_PORT == 0)
{
FIO_IntCmd(TS_X1_PORT, LPC_GPIOINT->IO0IntEnF | (1 << TS_X1_PIN), 1); // set IRQ for X1 to Falling edge
}
else if(TS_X1_PORT == 2)
{
FIO_IntCmd(TS_X1_PORT, LPC_GPIOINT->IO2IntEnF | (1 << TS_X1_PIN), 1); // set IRQ for X1 to Falling edge
}
NVIC_SetPriority(GPIO_IRQn, TS_Config.Priority);
NVIC_EnableIRQ(GPIO_IRQn);
}
// --------------------------------------------------
// freeing memory
void DeInit_TS(void)
{
GPIO_Deinit();
}
// --------------------------------------------------
// conversion from ADC value to the screen resolution values
static int16_t ConvertCoord(int16_t Coord, int16_t MinVal, int16_t MaxVal, int16_t TrueSize)
{
int16_t tmp;
int16_t ret;
uint8_t convert = 0;
if (MinVal > MaxVal) // Swap value
{
tmp = MaxVal;
MaxVal = MinVal;
MinVal = tmp;
convert = 1;
}
ret = (Coord - MinVal) * TrueSize / (MaxVal - MinVal);
if (convert)
ret = TrueSize - ret;
return ret;
}
// --------------------------------------------------
// reconfigure appropriate TS pins to analog function
// and read ADC val;ue for X and Y coord.
void TS_Read(void)
{
uint32_t i;
NVIC_DisableIRQ(GPIO_IRQn); // Important !
//X2 pin - Output, without pull resistors - set to 0
PINSEL_ConfigPin(TS_X2_PORT,TS_X2_PIN, 0); // Set default function no. - GPIO
PINSEL_SetPinMode(TS_X2_PORT,TS_X2_PIN, PINSEL_BASICMODE_PLAINOUT); // without pull resistors
FIO_SetDir(TS_X2_PORT, 1 << TS_X2_PIN, GPIO_DIRECTION_OUTPUT); // Set as Output
FIO_ClearValue(TS_X2_PORT, 1 << TS_X2_PIN); // set to log.0
//Y2 pin - Input, without pull resistors - set as floating
PINSEL_ConfigPin(TS_Y2_PORT,TS_Y2_PIN, 0); // Set default function no. - GPIO
PINSEL_SetPinMode(TS_Y2_PORT,TS_Y2_PIN, PINSEL_BASICMODE_PLAINOUT); // without pull resistors
FIO_SetDir(TS_Y2_PORT, 1 << TS_Y2_PIN, GPIO_DIRECTION_INPUT); // Set as Input
//X1 pin - Output, with pull-up resistors - set to 1
PINSEL_ConfigPin(TS_X1_PORT,TS_X1_PIN, 0); // Set default function no. - GPIO
PINSEL_SetPinMode(TS_X1_PORT,TS_X1_PIN, PINSEL_BASICMODE_PLAINOUT); // without pull resistors
FIO_SetDir(TS_X1_PORT, 1 << TS_X1_PIN, GPIO_DIRECTION_OUTPUT); // Set as Output
FIO_SetValue(TS_X1_PORT, 1 << TS_X1_PIN); // set to log.1
//Y1 pin - connected to AD Converter
PINSEL_ConfigPin(TS_Y1_PORT,TS_Y1_PIN, TS_Y1_FUNC_NO); // switch alternate function no.
PINSEL_SetAnalogPinMode(TS_Y1_PORT, TS_Y1_PIN, ENABLE); // set to analog mode
TIM_Waitms(TS_SETTLING_TIME); // settling time for switching
ADC_Init(LPC_ADC, 400000);
for (i = 0; i < num_samples; i++)
{
ADC_ChannelCmd(LPC_ADC, TS_Y1_ADC_CH, ENABLE);
ADC_StartCmd(LPC_ADC, ADC_START_NOW);
while (!(ADC_ChannelGetStatus(LPC_ADC, TS_Y1_ADC_CH, ADC_DATA_DONE)));
ADC_ChannelCmd(LPC_ADC, TS_Y1_ADC_CH, DISABLE);
x_values[i] = (ADC_ChannelGetData(LPC_ADC,TS_Y1_ADC_CH) >> 4 ) & TS_CONVERSION_MAX; //mask for TS_CONVERSION BITS AD Convert result !
}
//ADC_DeInit(LPC_ADC);
//Y2 pin - Output, without pull resistors - set to 0
PINSEL_ConfigPin(TS_Y2_PORT,TS_Y2_PIN, 0); // Set default function no. - GPIO
PINSEL_SetPinMode(TS_Y2_PORT,TS_Y2_PIN, PINSEL_BASICMODE_PLAINOUT); // without pull resistors
FIO_SetDir(TS_Y2_PORT, 1 << TS_Y2_PIN, GPIO_DIRECTION_OUTPUT); // Set as Output
FIO_ClearValue(TS_Y2_PORT, 1 << TS_Y2_PIN); // set to log.0
//X2 pin - Input, without pull resistors - set as floating
PINSEL_ConfigPin(TS_X2_PORT,TS_X2_PIN, 0); // Set default function no. - GPIO
PINSEL_SetPinMode(TS_X2_PORT,TS_X2_PIN, PINSEL_BASICMODE_PLAINOUT); // without pull resistors
FIO_SetDir(TS_X2_PORT, 1 << TS_X2_PIN, GPIO_DIRECTION_INPUT); // Set as Input
//Y1 pin - Output, with pull-up resistors - set to 1
PINSEL_SetAnalogPinMode(TS_Y1_PORT, TS_Y1_PIN, DISABLE); // set back to digital mode
PINSEL_ConfigPin(TS_Y1_PORT,TS_Y1_PIN, 0); // Set default function no. - GPIO
PINSEL_SetPinMode(TS_Y1_PORT,TS_Y1_PIN, PINSEL_BASICMODE_PLAINOUT); // without pull resistors
FIO_SetDir(TS_Y1_PORT, 1 << TS_Y1_PIN, GPIO_DIRECTION_OUTPUT); // Set as Output
FIO_SetValue(TS_Y1_PORT, 1 << TS_Y1_PIN); // set to log.1
//X1 pin - connected to AD Converter
PINSEL_ConfigPin(TS_X1_PORT,TS_X1_PIN, TS_X1_FUNC_NO); // switch alternate function no.
PINSEL_SetAnalogPinMode(TS_X1_PORT, TS_X1_PIN, ENABLE); // set to analog mode
TIM_Waitms(TS_SETTLING_TIME); // settling time for switching
ADC_Init(LPC_ADC, 400000);
for (i = 0; i < num_samples; i++)
{
ADC_ChannelCmd(LPC_ADC, TS_X1_ADC_CH, ENABLE);
ADC_StartCmd(LPC_ADC, ADC_START_NOW);;
while (!(ADC_ChannelGetStatus(LPC_ADC, TS_X1_ADC_CH, ADC_DATA_DONE)));
ADC_ChannelCmd(LPC_ADC, TS_X1_ADC_CH, DISABLE);
y_values[i] = (ADC_ChannelGetData(LPC_ADC,TS_X1_ADC_CH) >> 4) & TS_CONVERSION_MAX; //mask for TS_CONVERSION BITS AD Convert result !
}
PINSEL_SetAnalogPinMode(TS_X1_PORT, TS_X1_PIN, DISABLE); // set back to digital mode
ADC_DeInit(LPC_ADC);
_Set_TS_to_digital(); // switch TS pins back to digital functions
NVIC_EnableIRQ(GPIO_IRQn); // Can be ...
TS_x_value = 0; // initial value
for (i=0; i < num_samples; i++) TS_x_value += x_values[i]; // add up the conversion results
TS_x_value = TS_x_value /num_samples; // get average
TS_y_value = 0; // initial value
for (i=0; i < num_samples; i++) TS_y_value += y_values[i]; // add up conversion results
TS_y_value = TS_y_value /num_samples; // get average
}
// --------------------------------------------------
// fill pointer to X and Y coord with newest values
void GetTouchCoord(int16_t *pX, int16_t* pY)
{
uint16_t i, tmp;
int16_t coord, x = -1, y = -1, z1 = -1, z2 = -1, z;
TS_Read();
if ((TS_x_value >= 0) && (TS_y_value >= 0)) // adjust to truly size of LCD
{
*pY = ConvertCoord(TS_y_value, TS_Config.ad_bottom, TS_Config.ad_top, TS_Config.lcd_v_size);
*pX = ConvertCoord(TS_x_value, TS_Config.ad_left, TS_Config.ad_right, TS_Config.lcd_h_size);
}
TS_x_value = TS_y_value = -1;
}
// --------------------------------------------------
// enable IRQ from TS press event
void Enable_TS(void)
{
// next, read IO0IntEnF register and set only desired bit.
if (TS_X1_PORT == 0)
{
FIO_IntCmd(TS_X1_PORT, LPC_GPIOINT->IO0IntEnF | (1 << TS_X1_PIN), 1); // set IRQ for X1 to Falling edge
}
else if(TS_X1_PORT == 2)
{
FIO_IntCmd(TS_X1_PORT, LPC_GPIOINT->IO2IntEnF | (1 << TS_X1_PIN), 1); // set IRQ for X1 to Falling edge
}
}
// --------------------------------------------------
// disable IRQ from TS press event
void Disable_TS(void)
{
// next, read IO0IntEnF register and clear only desired bit.
if (TS_X1_PORT == 0)
{
FIO_IntCmd(TS_X1_PORT, LPC_GPIOINT->IO0IntEnF & ~(1 << TS_X1_PIN), 1); // clear IRQ for X1 to Falling edge
}
else if(TS_X1_PORT == 2)
{
FIO_IntCmd(TS_X1_PORT, LPC_GPIOINT->IO2IntEnF & ~(1 << TS_X1_PIN), 1); // clear IRQ for X1 to Falling edge
}
}
<file_sep>/ARM_SWIM-LCD-DEMO_LPC1788-SK/Include/Configuration.h
/***********************************************************
* Configuration.h
*
* Created on: 25.7.2014
* Author: peterj
***********************************************************/
#ifndef CONFIGURATION_H_
#define CONFIGURATION_H_
#define CHIP_LPC177X_8X
#define __STACK_SIZE 0x400
#define __HEAP_SIZE 0xd00
#warning "Add into assembler's include also Configuration.h file!"
#define ARM_MATH_CM3
//HW drivers loading:
#define _CURR_USING_BRD _IAR_OLIMEX_BOARD // nacuita drivery !!!!
// ********************************************************************************
// SWIM Configuration
#define COLORS_DEF 16
#define PORTRAIT 1
#define FONT font_x6x13 // font_x5x7 font_x6x13 font_rom8x8 font_rom8x16 font_winfreesys14x16
#endif /* CONFIGURATION_H_ */
<file_sep>/ARM_SWIM-LCD-DEMO_LPC1788-SK/LIB/GUI-SWIM/Include/SMA_16bpp_example.h
/***********************************************************************
* $Id:: SMA_16bpp_example.h 6 2007-08-27 20:47:57Z kevinw $
*
* Project: Common bitmap files
*
* Description:
* This file, SMA_16bpp_example.h,
* was automatically generated from file
* example.bmp
* using utility
* bmp2c, Revision: 1.3 .
* Edit this file at your own risk.
*
***********************************************************************
* Software that is described herein is for illustrative purposes only
* which provides customers with programming information regarding the
* products. This software is supplied "AS IS" without any warranties.
* NXP Semiconductors assumes no responsibility or liability for the
* use of the software, conveys no license or title under any patent,
* copyright, or mask work right to the product. NXP Semiconductors
* reserves the right to make changes in the software without
* notification. NXP Semiconductors also make no representation or
* warranty that such application will be suitable for the specified
* use without further testing or modification.
**********************************************************************/
#ifndef SMA_16BPP_EXAMPLE_H
#define SMA_16BPP_EXAMPLE_H
#include "..\..\..\swim\lpc_types.h"
#define EXAMPLE_BPP 16
extern const UNS_16 example_w;
extern const UNS_16 example_h;
extern const UNS_16 example[];
#define example_palette NULL
#endif /* #ifndef SMA_16BPP_EXAMPLE_H */
<file_sep>/ARM_SWIM-LCD-DEMO_LPC1788-SK/DRV/ExRAM/Include/sdram_k4s561632j.h
/*
* sdram_k4s561632l.h
*
* Created on: 11.8.2014
* Author: peterj
*/
#ifndef __SDRAM_K4S561632J_H_
#define __SDRAM_K4S561632J_H_
//#include "bsp.h"
// ******************************************************************************************************
// Configuration
// ******************************************************************************************************
#define SDRAM_BASE_ADDR 0xA0000000
#define SDRAM_SIZE 0x10000000
#define SDRAM_REFRESH 7813
#define SDRAM_TRP 20
#define SDRAM_TRAS 45
#define SDRAM_TAPR 1
#define SDRAM_TDAL 3
#define SDRAM_TWR 3
#define SDRAM_TRC 65
#define SDRAM_TRFC 66
#define SDRAM_TXSR 67
#define SDRAM_TRRD 15
#define SDRAM_TMRD 3
// ******************************************************************************************************
// Export
// ******************************************************************************************************
// Do NOT modify next lines !!!
extern void Init_SDRAM( void );
#endif /* __SDRAM_K4S561632J_H_ */
<file_sep>/ARM_SWIM-LCD-DEMO_LPC1788-SK/BSP/bsp.h
// ******************************************************************************************************
// bsp.h
//
// Created on: 20.8.2014
// Author: "<EMAIL>"
// Board support Package for IAR LPC1788-SK
// ******************************************************************************************************
#ifndef BSP_H_
#define BSP_H_
#include "global.h"
#ifndef __BUILD_WITH_EXAMPLE__
#define __BUILD_WITH_EXAMPLE__ 1
#endif
//LED indicators preset
#define BSP_LED_1_CONNECTED_PORT 1
#define BSP_LED_1_CONNECTED_PIN 13
#define BSP_LED_2_CONNECTED_PORT 1
#define BSP_LED_2_CONNECTED_PIN 18
// ******************************************************************************************************
// External SDRAM memory:
// ******************************************************************************************************
#include "../DRV/ExRAM/Include/sdram_k4s561632j.h" // include a driver
// ******************************************************************************************************
// LCD TFT Display - GiFar GFT035EA320240Y:
// ******************************************************************************************************
#define BSP_LCD_BL_PWM_PERI_ID PWM_1
#define BSP_LCD_BL_PWM_PERI_CHA 0 // Match channel register - cycle - 100%
#define BSP_LCD_BL_PWM_PERI_CHB 2 // Match channel register - duty cycle - xx %
#define BSP_LCD_BL_PWM_PORT 2 // pwm output port for pwm output pin...
#define BSP_LCD_BL_PWM_PIN 1 // pwm output connected to LCD Backlight transistor's base
#include "../DRV/LCD/Include/GFT035EA320240Y.h" // include a driver
// ******************************************************************************************************
// ADC Input - Potentiometer - hardware connection:
// ******************************************************************************************************
#define BSP_RPOT_ADC_PREPARED_CHANNEL ADC_CHANNEL_7
//#define BSP_RPOT_ADC_PREPARED_INTR ADC_ADINTEN7
#define BSP_RPOT_ADC_PREPARED_CH_PORT 0
#define BSP_RPOT_ADC_PREPARED_CH_PIN 13
#define BSP_RPOT_ADC_PREPARED_CH_FUNC_NO 3 // AD converter as alternative function no.3
#include "../DRV/RPOT/Include/RPOT.h" // include a driver
// ******************************************************************************************************
// Touch screen reader - analog - hardware connection:
// ******************************************************************************************************
// X1 = X plus
// X2 = X minus
// Y1 = Y plus
// Y2 = Y minus
#define BSP_TS_X1_PORT 0
#define BSP_TS_X1_PIN 24 // ADC Input
#define BSP_TS_X1_ADC_CH ADC_CHANNEL_1 // ADC channel no.
#define BSP_TS_X1_FUNC_NO 1 // analog function of this pin is as alternate function no.1
#define BSP_TS_X2_PORT 0
#define BSP_TS_X2_PIN 19
#define BSP_TS_Y1_PORT 0
#define BSP_TS_Y1_PIN 23 // ADC input
#define BSP_TS_Y1_ADC_CH ADC_CHANNEL_0 // ADC channel no.
#define BSP_TS_Y1_FUNC_NO 1 // analog funsction of this pin is as alternate function no.1
#define BSP_TS_Y2_PORT 0
#define BSP_TS_Y2_PIN 21
#include "../DRV/TouchScreen/Include/TS_Analog.h" // include a driver
#endif /* BSP_H_ */
<file_sep>/ARM_SWIM-LCD-DEMO_LPC1788-SK/DRV/TouchScreen/Include/TS_Analog.h
/*
* TS_Analog.h
*
* Created on: 11.8.2014
* Author: peterj
*/
#ifndef TS_ANALOG_H_
#define TS_ANALOG_H_
// ******************************************************************************************************
// Configuration
// ******************************************************************************************************
#define debounce 100 // debounce delay
#define num_samples 16 // number of A/D samples per axis
#define TS_SETTLING_TIME 100 // settling time delay
#define TS_CONVERSION_MAX 0xfff // max vaule of the AD Converter for TS inputs
#define TOUCH_AD_LEFT 34 // default values, have to calibrate it
#define TOUCH_AD_RIGHT 220 // default values, have to calibrate it
#define TOUCH_AD_TOP 46 // default values, have to calibrate it
#define TOUCH_AD_BOTTOM 212 // default values, have to calibrate it
// ******************************************************************************************************
// Hardware connection - see bsp.h
// ******************************************************************************************************
#define TS_X1_PORT BSP_TS_X1_PORT
#define TS_X1_PIN BSP_TS_X1_PIN
#define TS_X1_IRQ PIN_INT0_IRQHandler // route wakeup event to IRQ
#define TS_X1_ADC_CH BSP_TS_X1_ADC_CH
#define TS_X1_FUNC_NO BSP_TS_X1_FUNC_NO
#define TS_X2_PORT BSP_TS_X2_PORT
#define TS_X2_PIN BSP_TS_X2_PIN
#define TS_Y1_PORT BSP_TS_Y1_PORT
#define TS_Y1_PIN BSP_TS_Y1_PIN
#define TS_Y1_ADC_CH BSP_TS_Y1_ADC_CH
#define TS_Y1_FUNC_NO BSP_TS_Y1_FUNC_NO
#define TS_Y2_PORT BSP_TS_Y2_PORT
#define TS_Y2_PIN BSP_TS_Y2_PIN
// ******************************************************************************************************
// Export
// ******************************************************************************************************
// Do NOT modify next lines !!!
typedef struct
{
int16_t ad_left; // left margin
int16_t ad_right; // right margin
int16_t ad_top; // top margin
int16_t ad_bottom; // bottom margin
int16_t lcd_h_size; // lcd horizontal size
int16_t lcd_v_size; // lcd vertical size
uint8_t Priority; // priority level for TS Interrupt
} TS_Init_Type;
extern TS_Init_Type TS_Config;
extern uint8_t TS_Activated_Flag;
// Initialize TS on analog sub-system
void Init_TS(void);
void Enable_TS(void);
void Disable_TS(void);
void GetTouchCoord(int16_t *pX, int16_t* pY); // Get current Touch Coordinates
#endif /* TS_ANALOG_H_ */
<file_sep>/ARM_SWIM-LCD-DEMO_LPC1788-SK/DRV/ExRAM/sdram_k4s561632j.c
/*
* sdram_k4s561632l.c
*
* Created on: 11.8.2014
* Author: peterj
*/
#include "global.h"
#define _EMC 1
#include "../Chip/Drivers/Include/lpc177x_8x_emc.h"
#include "../Chip/Drivers/Include/lpc177x_8x_clkpwr.h"
#include "../Chip/Drivers/Include/lpc177x_8x_pinsel.h"
#include "../Chip/Drivers/Include/lpc177x_8x_timer.h"
//#include "./Include/sdram_k4s561632j.h"
// --------------------------------------------------
// Initialize external SDRAM memory Micron K4S561632J, 256Mbit(8M x 32)
void Init_SDRAM( void )
{
volatile uint32_t i;
volatile unsigned long Dummy;
EMC_DYN_MEM_Config_Type config;
TIM_TIMERCFG_Type TIM_ConfigStruct;
TIM_ConfigStruct.PrescaleOption = TIM_PRESCALE_USVAL;
TIM_ConfigStruct.PrescaleValue = 1;
// Set configuration for Tim_config and Tim_MatchConfig
TIM_Init(LPC_TIM0, TIM_TIMER_MODE,&TIM_ConfigStruct);
config.ChipSize = 256;
config.AddrBusWidth = 32;
config.AddrMap = EMC_ADD_MAP_ROW_BANK_COL;
config.CSn = 0;
config.DataWidth = 16;
config.TotalSize = SDRAM_SIZE;
config.CASLatency= 3;
config.RASLatency= 3;
config.Active2ActivePeriod =EMC_NS2CLK( SDRAM_TRC);
config.ActiveBankLatency =EMC_NS2CLK( SDRAM_TRRD);
config.AutoRefrehPeriod = EMC_NS2CLK( SDRAM_TRFC);
config.DataIn2ActiveTime = SDRAM_TDAL + EMC_NS2CLK( SDRAM_TRP);
config.DataOut2ActiveTime = SDRAM_TAPR;
config.WriteRecoveryTime = SDRAM_TWR;
config.ExitSelfRefreshTime = EMC_NS2CLK( SDRAM_TXSR);
config.LoadModeReg2Active = SDRAM_TMRD;
config.PrechargeCmdPeriod = EMC_NS2CLK( SDRAM_TRP);
config.ReadConfig = 1; // Command delayed strategy, using EMCCLKDELAY
config.RefreshTime = EMC_NS2CLK( SDRAM_REFRESH) >> 4;
config.Active2PreChargeTime = EMC_NS2CLK( SDRAM_TRAS);
config.SeftRefreshExitTime = EMC_NS2CLK( SDRAM_TXSR);
DynMem_Init(&config);
EMC_DynCtrlSDRAMInit(EMC_DYNAMIC_CTRL_SDRAM_NOP); // Issue NOP command
TIM_Waitms(100); // wait 200ms
EMC_DynCtrlSDRAMInit(EMC_DYNAMIC_CTRL_SDRAM_PALL); // Issue Pre-charge command
for(i = 0; i < 0x80; i++); // wait 128 AHB clock cycles
TIM_Waitms(100);
EMC_DynCtrlSDRAMInit(EMC_DYNAMIC_CTRL_SDRAM_MODE); // Issue MODE command
Dummy = *((volatile uint32_t *)(SDRAM_BASE_ADDR | (0x32<<13))); // Mode Register Setting
//Timing for 48/60/72MHZ Bus
EMC_DynCtrlSDRAMInit(EMC_DYNAMIC_CTRL_SDRAM_NORMAL); // Issue NORMAL command
//enable buffers
EMC_DynMemConfigB(0, EMC_DYNAMIC_CFG_BUFF_ENABLED);
for(i = 100000; i;i--);
TIM_DeInit(LPC_TIM0);
}
<file_sep>/ARM_SWIM-LCD-DEMO_LPC1788-SK/DRV/LCD/GFT035EA320240Y.c
//
// GFT035EA320240Y.c
//
// Created on: 20.8.2014
// Author: "<EMAIL>"
//
// ******************************************************************************************************
#include "global.h"
#include "../Chip/Drivers/Include/lpc177x_8x_lcd.h"
#include "../Chip/Drivers/Include/lpc177x_8x_pwm.h"
#include "../Chip/Drivers/Include/lpc177x_8x_gpio.h"
#include "../Chip/Drivers/Include/lpc177x_8x_clkpwr.h"
// ******************************************************************************************************
// Globals
// ******************************************************************************************************
extern LCD_Config_Type lcd_config; // LCD active struct
// ******************************************************************************************************
// Function prototypes
// ******************************************************************************************************
void Init_LCD_BackLight(void);
void Set_LCD_BackLight(uint16_t level);
void Init_LCD(void);
void Enable_LCD(void);
void Disable_LCD(void);
// ******************************************************************************************************
// Globals
// ******************************************************************************************************
LCD_Cursor_Config_Type cursor_config;
// --------------------------------------------------
void Enable_LCD(void)
{
LCD_Enable (ENABLE); // Enable LCD
}
void Disable_LCD(void)
{
LCD_Enable (DISABLE); // Disable LCD
}
void Enable_LCD_Cursor(void)
{
LCD_Cursor_Enable(ENABLE, 0); // ToDo: Cursor is hardly set to zero. In future make it as variable
}
void Disable_LCD_Cursor(void)
{
LCD_Cursor_Enable(DISABLE, 0);
}
void Init_LCD(void)
{
LCD_Enable (FALSE);
lcd_config.big_endian_byte = 0;
lcd_config.big_endian_pixel = 0;
lcd_config.hConfig.hbp = LCD_H_BACK_PORCH;
lcd_config.hConfig.hfp = LCD_H_FRONT_PORCH;
lcd_config.hConfig.hsw = LCD_H_PULSE;
lcd_config.hConfig.ppl = LCD_H_SIZE;
lcd_config.vConfig.lpp = LCD_V_SIZE;
lcd_config.vConfig.vbp = LCD_V_BACK_PORCH;
lcd_config.vConfig.vfp = LCD_V_FRONT_PORCH;
lcd_config.vConfig.vsw = LCD_V_PULSE;
lcd_config.panel_clk = LCD_PIX_CLK;
lcd_config.polarity.active_high = 1;
lcd_config.polarity.cpl = LCD_H_SIZE;
lcd_config.polarity.invert_hsync = 1;
lcd_config.polarity.invert_vsync = 1;
lcd_config.polarity.invert_panel_clock = 1;
// lcd_config.lcd_panel_upper = LCD_VRAM_BASE_ADDR_START;// //povodny stav.
// lcd_config.lcd_panel_lower = LCD_VRAM_BASE_ADDR_TOP;
lcd_config.lcd_panel_upper = LCD_VRAM_BASE_ADDR_TOP; //ToDo: toto bolo naopak.
lcd_config.lcd_panel_lower = LCD_VRAM_BASE_ADDR_START;
lcd_config.lcd_bpp = LCD_BPP_16; //LCD_BPP_24;
lcd_config.lcd_type = LCD_TFT;
lcd_config.lcd_palette = _NULL;
lcd_config.lcd_bgr = FALSE;
// Init LCD HW
LCD_Init (&lcd_config);
// clear background.
LCD_SetImage(LCD_PANEL_UPPER, NULL);
LCD_SetImage(LCD_PANEL_LOWER, NULL);
}
void Init_LCD_Cursor(void)
{
cursor_config.baseaddress = LCD_CURSOR_BASE_ADDR;
cursor_config.framesync = 1;
#if (CURSOR_SIZE == 64)
cursor_config.size32 = 0;
#else
cursor_config.size32 = 1;
#endif
cursor_config.palette[0].Red = 0x00;
cursor_config.palette[0].Green = 0x00;
cursor_config.palette[0].Blue = 0x00;
cursor_config.palette[1].Red = 0xFF;
cursor_config.palette[1].Green = 0xFF;
cursor_config.palette[1].Blue = 0xFF;
LCD_Cursor_Cfg(&cursor_config);
LCD_Cursor_SetImage((uint32_t *)Cursor, 0, sizeof(Cursor)/sizeof(uint32_t)) ;
}
// --------------------------------------------------
// Initialization of the backlight LCD. Using PWM.
void Init_LCD_BackLight(void)
{
uint32_t pclk;
PWM_TIMERCFG_Type PWMCfgDat;
PWM_MATCHCFG_Type PWMMatchCfgDat;
pclk = CLKPWR_GetCLK(CLKPWR_CLKTYPE_PER);
PWMCfgDat.PrescaleOption = PWM_TIMER_PRESCALE_TICKVAL;
PWMCfgDat.PrescaleValue = 1;
PWM_Init(LCD_BL_PWM_PERI_ID, PWM_MODE_TIMER, (void *) &PWMCfgDat);
PINSEL_ConfigPin(LCD_BL_PWM_PORT, LCD_BL_PWM_PIN, 1); // funct.no.1 - PWM1[2] — Pulse Width Modulator 1, channel 2 output.
PWM_MatchUpdate(LCD_BL_PWM_PERI_ID, LCD_BL_PWM_PERI_CHA, pclk / LCD_BL_PWM_BASE, PWM_MATCH_UPDATE_NOW);
// UPDATE VALUE OF THE PWM DUTY CYCLE
PWM_MatchUpdate(LCD_BL_PWM_PERI_ID, LCD_BL_PWM_PERI_CHB , 0 *(( pclk / LCD_BL_PWM_BASE) / 100), PWM_MATCH_UPDATE_NOW); // switch off backlight
PWMMatchCfgDat.IntOnMatch = DISABLE; // without interrupt
PWMMatchCfgDat.MatchChannel = LCD_BL_PWM_PERI_CHB; // Match channel register - duty cycle - xx %
PWMMatchCfgDat.ResetOnMatch = DISABLE; //
PWMMatchCfgDat.StopOnMatch = DISABLE;
PWM_ConfigMatch(LCD_BL_PWM_PERI_ID, &PWMMatchCfgDat); // store it
PWM_ChannelCmd(LCD_BL_PWM_PERI_ID, LCD_BL_PWM_PERI_CHB, ENABLE); // Enable PWM Channel Output
PWM_ResetCounter(LCD_BL_PWM_PERI_ID); // reset and start counter
PWM_CounterCmd(LCD_BL_PWM_PERI_ID, ENABLE); // start PWM Counter
PWM_Cmd(LCD_BL_PWM_PERI_ID, ENABLE); // start PWM
}
// --------------------------------------------------
// Set nev intensity [%] of backlight.
void Set_LCD_BackLight(uint16_t level) // Level: 0-100%
{
uint32_t pclk;
pclk = CLKPWR_GetCLK(CLKPWR_CLKTYPE_PER);
if (level > 100) level = 100;
PWM_MatchUpdate(LCD_BL_PWM_PERI_ID, LCD_BL_PWM_PERI_CHB,level * ((pclk / LCD_BL_PWM_BASE) / 100), PWM_MATCH_UPDATE_NOW);
}
void Set_LCD_Cursor(int x, int y)
{
LCD_Move_Cursor( x, y);
}
<file_sep>/ARM_SWIM-LCD-DEMO_LPC1788-SK/DRV/RPOT/Include/RPOT.h
/*
* RPOT.h
*
* Created on: 11.8.2014
* Author: peterj
*/
#ifndef RPOT_H_
#define RPOT_H_
// ******************************************************************************************************
// ADC Input - Potentiometer - connection:
// ******************************************************************************************************
#define RPOT_ADC_PREPARED_CHANNEL BSP_RPOT_ADC_PREPARED_CHANNEL
#define RPOT_ADC_PREPARED_INTR BSP_RPOT_ADC_PREPARED_INTR
#define RPOT_ADC_PREPARED_CH_PORT BSP_RPOT_ADC_PREPARED_CH_PORT
#define RPOT_ADC_PREPARED_CH_PIN BSP_RPOT_ADC_PREPARED_CH_PIN
#define RPOT_ADC_PREPARED_CH_FUNC_NO BSP_RPOT_ADC_PREPARED_CH_FUNC_NO
// ******************************************************************************************************
// Export
// ******************************************************************************************************
// Do NOT modify next lines !!!
void Init_RPOT(void);
uint16_t Get_RPOT_Value(void);
#endif /* RPOT_H_ */
<file_sep>/ARM_SWIM-LCD-DEMO_LPC1788-SK/Include/global.h
// ******************************************************************************************************
// global.h
//
// Created on: 20.8.2014
// Author: "<EMAIL>"
//
// ******************************************************************************************************
// ******************************************************************************************************
// USER - some useful macros....
// ******************************************************************************************************
#ifndef GLOBAL_H_
#define GLOBAL_H_
// standard constants
#ifndef _NULL
#define _NULL ((void*) 0)
#endif
// BIT manipulation macros
#define _SBIT(word, bit) (word |= 1 << (bit)) // Set bit macro
#define _CBIT(word, bit) (word &= ~(1 << bit)) // Clear bit macro
#define _TBIT(word, bit) ((word && (1 << bit))? CBIT(word, bit): SBIT (word, bit)) // Toogle bit macro
// ******************************************************************************************************
// SYSTEM
// ******************************************************************************************************
#include "stdint.h"
#include "../Chip/Drivers/Include/lpc_types.h"
// ******************************************************************************************************
// PROJECT CONFIGURATION
// ******************************************************************************************************
#include "Configuration.h"
// ******************************************************************************************************
// CMSIS CORE
// ******************************************************************************************************
//#include "lpc177x_8x_libcfg_default.h"
//#include "../Chip/Include/arm_common_tables.h"
//#include "../Chip/Include/arm_const_structs.h"
//#include "../Chip/Include/arm_math.h"
//#include "../Chip/Include/core_cm0.h"
//#include "../Chip/Include/core_cm0plus.h"
//#include "../Chip/Include/core_cm3.h"
//#include "../Chip/Include/core_cm4.h"
//#include "../Chip/Include/core_cm4_simd.h"
//#include "../Chip/Include/core_cmFunc.h"
//#include "../Chip/Include/core_cmInstr.h"
//#include "../Chip/Include/core_sc000.h"
//#include "../Chip/Include/core_sc300.h"
// ******************************************************************************************************
// CMSIS Drivers
// ******************************************************************************************************
#include "../Chip/Drivers/Include/lpc177x_8x_pinsel.h"
// other CMSIS drivers called from included libraries, framevork or drivers
// ******************************************************************************************************
// BOARD SUPPORT PACKAGE HEADERS
// ******************************************************************************************************
#include "../BSP/bsp.h"
// ******************************************************************************************************
// FRAMEWORK HEADERS
// ******************************************************************************************************
//#include "bsp.h"
//#pragma GCC system_header
// SWIM Graphics User Interface Library
//#include "LPC177x_8x.h"
//#include "type.h"
//#include "ex_sdram.h"
//#include "lcd_params.h"
//#include "lcd_driver.h"
//#include "lcd_type.h"
#include "../LIB/GUI-SWIM/Include/lpc_swim_font.h"
#include "../LIB/GUI-SWIM/Include/lpc_swim.h"
#include "../LIB/GUI-SWIM/Include/lpc_rom8x8.h"
#include "../LIB/GUI-SWIM/Include/lpc_rom8x16.h"
#include "../LIB/GUI-SWIM/Include/lpc_winfreesystem14x16.h"
#include "../LIB/GUI-SWIM/Include/lpc_x5x7.h"
#include "../LIB/GUI-SWIM/Include/lpc_x6x13.h"
#endif /* GLOBAL_H_ */
<file_sep>/ARM_SWIM-LCD-DEMO_LPC1788-SK/DRV/RPOT/RPOT.c
/*
* RPOT.c
*
* Created on: 11.8.2014
* Author: peterj
*/
#include "global.h"
#include "../Chip/Drivers/Include/lpc177x_8x_pinsel.h"
#include "../Chip/Drivers/Include/lpc177x_8x_adc.h"
// ******************************************************************************************************
// Function prototypes
// ******************************************************************************************************
void Init_RPOT(void);
// ******************************************************************************************************
// Globals
// ******************************************************************************************************
// --------------------------------------------------
// First HW initialization
void Init_RPOT(void)
{
PINSEL_ConfigPin (RPOT_ADC_PREPARED_CH_PORT, RPOT_ADC_PREPARED_CH_PIN, RPOT_ADC_PREPARED_CH_FUNC_NO);
PINSEL_SetAnalogPinMode(RPOT_ADC_PREPARED_CH_PORT, RPOT_ADC_PREPARED_CH_PIN,ENABLE);
ADC_Init(LPC_ADC, 400000);
//ADC_IntConfig(LPC_ADC, RPOT_ADC_PREPARED_INTR, DISABLE);
ADC_ChannelCmd(LPC_ADC, RPOT_ADC_PREPARED_CHANNEL, ENABLE);
}
// --------------------------------------------------
// Freeing memory
void DeInit_RPOT(void)
{
}
// --------------------------------------------------
// Get fresh value.
uint16_t Get_RPOT_Value(void)
{
uint16_t res;
ADC_Init(LPC_ADC, 400000);
ADC_ChannelCmd(LPC_ADC, RPOT_ADC_PREPARED_CHANNEL, ENABLE);
ADC_StartCmd(LPC_ADC, ADC_START_NOW);
do
{
if ((LPC_ADC->CR & (1 << RPOT_ADC_PREPARED_CHANNEL))==0) // if current channel is another then selected -> exit
{
ADC_ChannelCmd(LPC_ADC, RPOT_ADC_PREPARED_CHANNEL, DISABLE);
ADC_DeInit(LPC_ADC);
return (-1);
}
}
while (!(ADC_ChannelGetStatus(LPC_ADC, RPOT_ADC_PREPARED_CHANNEL, ADC_DATA_DONE)));
res = ADC_ChannelGetData(LPC_ADC, RPOT_ADC_PREPARED_CHANNEL);
ADC_DeInit(LPC_ADC);
return(res);
}
<file_sep>/ARM_SWIM-LCD-DEMO_LPC1788-SK/DRV/LCD/Include/GFT035EA320240Y.h
/*
* GFT035EA320240Y.h
*
* Created on: 11.8.2014
* Author: peterj
*/
#ifndef __GFT035EA320240Y_H
#define __GFT035EA320240Y_H
// ******************************************************************************************************
// Configuration
// ******************************************************************************************************
// LCD Config
#define LCD_H_SIZE 320
#define LCD_H_PULSE 30
#define LCD_H_FRONT_PORCH 20
#define LCD_H_BACK_PORCH 38
#define LCD_V_SIZE 240
#define LCD_V_PULSE 3
#define LCD_V_FRONT_PORCH 5
#define LCD_V_BACK_PORCH 15
#define LCD_PIX_CLK (6.5*1000000l)
// CUrsor config
#define LCD_CURSOR_SIZE 32
//Cursor 64x64 pixels
#define LCD_CURSOR_H_SIZE 32
#define LCD_CURSOR_V_SIZE 32
#define LCD_CURSOR_OFF_X (LCD_CURSOR_H_SIZE/2)
#define LCD_CURSOR_OFF_Y (LCD_CURSOR_V_SIZE/2)
// Memory
#define LCD_VRAM_BASE_ADDR_START ((uint32_t)SDRAM_BASE_ADDR + 0x00100000)
#define LCD_VRAM_BASE_ADDR_TOP (LCD_VRAM_BASE_ADDR_START + LCD_H_SIZE*LCD_V_SIZE*4)
#define LCD_CURSOR_BASE_ADDR ((uint32_t)0x20088800)
// Backlight defines:
#define LCD_BACK_LIGHT_BASE_CLK (1000/4)
#define LCD_BL_PWM_BASE (CLKPWR_GetCLK(CLKPWR_CLKTYPE_PER) / LCD_BACK_LIGHT_BASE_CLK) // base frequency for PWM backlight
//#define LCD_PWR_ENA_DIS_DLY 10000
// ******************************************************************************************************
// Hardware connection - see bsp.h
// ******************************************************************************************************
#define LCD_BL_PWM_PERI_ID BSP_LCD_BL_PWM_PERI_ID
#define LCD_BL_PWM_PERI_CHA BSP_LCD_BL_PWM_PERI_CHA // Match channel register - cycle - 100%
#define LCD_BL_PWM_PERI_CHB BSP_LCD_BL_PWM_PERI_CHB // Match channel register - duty cycle - xx %
#define LCD_BL_PWM_PORT BSP_LCD_BL_PWM_PORT // pwm output port for pwm output pin...
#define LCD_BL_PWM_PIN BSP_LCD_BL_PWM_PIN // pwm output connected to LCD Backlight transistor's base
// ******************************************************************************************************
// Export
// ******************************************************************************************************
// Do NOT modify next lines !!!
extern void Init_LCD(void);
extern void Init_LCD_Cursor(void);
extern void Init_LCD_BackLight(void);
extern void Set_LCD_BackLight(uint16_t level);
extern void Enable_LCD(void);
extern void Disable_LCD(void);
extern void Enable_LCD_Cursor(void);
extern void Disable_LCD_Cursor(void);
extern const unsigned char Cursor[(LCD_CURSOR_H_SIZE/4)*LCD_CURSOR_H_SIZE];
extern void Set_LCD_Cursor(int x, int y);
//extern LCD_Config_Type lcd_config; // LCD active struct
#endif /* _GFT035EA320240Y_H */
| 1feea3e14f40d194a8017a310bbff5401bf06abf | [
"Markdown",
"C"
] | 14 | Markdown | mikrozone/ARM_SWIM-LCD-DEMO_LPC1788-SK | 62b85a04062e05024b39c4aac7c631d76057574a | bc58ef7d7f713d81cc5e6ace50a9e440b28cf700 |
refs/heads/master | <repo_name>coderodde/JavaDB<file_sep>/src/test/java/net/coderodde/javadb/TableCellTest.java
package net.coderodde.javadb;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
import org.junit.Test;
import static org.junit.Assert.*;
import static net.coderodde.javadb.TableCellType.*;
import static net.coderodde.javadb.TableCell.*;
public class TableCellTest {
private TableCell tableCell;
@Test
public void testGetTableCellType() {
tableCell = new TableCell(TableCellType.TYPE_BINARY);
assertEquals(TableCellType.TYPE_BINARY, tableCell.getTableCellType());
assertNotEquals(TableCellType.TYPE_BOOLEAN,
tableCell.getTableCellType());
assertNotEquals(TableCellType.TYPE_DOUBLE,
tableCell.getTableCellType());
assertNotEquals(TableCellType.TYPE_FLOAT,
tableCell.getTableCellType());
assertNotEquals(TableCellType.TYPE_INT,
tableCell.getTableCellType());
assertNotEquals(TableCellType.TYPE_LONG,
tableCell.getTableCellType());
assertNotEquals(TableCellType.TYPE_STRING,
tableCell.getTableCellType());
assertNotEquals(TableCellType.TYPE_BOOLEAN,
tableCell.getTableCellType());
assertNotEquals(TableCellType.TYPE_DOUBLE,
tableCell.getTableCellType());
assertNotEquals(TableCellType.TYPE_FLOAT,
tableCell.getTableCellType());
assertEquals(TableCellType.TYPE_BINARY,
tableCell.getTableCellType());
assertNotEquals(TableCellType.TYPE_LONG,
tableCell.getTableCellType());
assertNotEquals(TableCellType.TYPE_STRING,
tableCell.getTableCellType());
}
@Test
public void testGetIntValue() {
tableCell = new TableCell(11);
assertEquals(Integer.valueOf(11), tableCell.getIntValue());
tableCell.setIntValue(12);
assertEquals(Integer.valueOf(12), tableCell.getIntValue());
}
@Test(expected = IllegalStateException.class)
public void testGetIntValueThrowsOnWrongType() {
tableCell = new TableCell(11);
tableCell.getBooleanValue();
}
@Test
public void testGetLongValue() {
tableCell = new TableCell(111L);
assertEquals(Long.valueOf(111L), tableCell.getLongValue());
tableCell.setLongValue(123L);
assertEquals(Long.valueOf(123L), tableCell.getLongValue());
}
@Test(expected = IllegalStateException.class)
public void testGetLongValueThrowsOnWrongType() {
tableCell = new TableCell(11L);
tableCell.getIntValue();
}
@Test
public void testGetFloatValue() {
tableCell = new TableCell(1.0f);
assertEquals(Float.valueOf(1.0f), tableCell.getFloatValue());
tableCell.setFloatValue(2.0f);
assertEquals(Float.valueOf(2.0f), tableCell.getFloatValue());
}
@Test(expected = IllegalStateException.class)
public void testGetFloatValueThrowsOnWrongType() {
tableCell = new TableCell(1.0f);
tableCell.getDoubleValue();
}
@Test
public void testGetDoubleValue() {
tableCell = new TableCell(1.0);
assertEquals(Double.valueOf(1.0), tableCell.getDoubleValue());
tableCell.setDoubleValue(2.0);
assertEquals(Double.valueOf(2.0), tableCell.getDoubleValue());
}
@Test(expected = IllegalStateException.class)
public void testGetDoubleValueThrowsOnWrongType() {
tableCell = new TableCell(1.0);
tableCell.getFloatValue();
}
@Test
public void testGetStringValue() {
tableCell = new TableCell("hello");
assertEquals("hello", tableCell.getStringValue());
tableCell.setStringValue("world");
assertEquals("world", tableCell.getStringValue());
}
@Test(expected = IllegalStateException.class)
public void testGetStringValueThrowsOnWrongType() {
tableCell = new TableCell("yeah");
tableCell.getBinaryData();
}
@Test
public void testGetBooleanValue() {
tableCell = new TableCell(false);
assertEquals(Boolean.FALSE, tableCell.getBooleanValue());
tableCell.setBooleanValue(true);
assertEquals(Boolean.TRUE, tableCell.getBooleanValue());
}
@Test(expected = IllegalStateException.class)
public void testGetBooleanValueThrowsOnWrongType() {
tableCell = new TableCell(true);
tableCell.getIntValue();
}
@Test
public void testGetBinaryData() {
tableCell = new TableCell(new byte[]{ 4, 5 });
assertTrue(Arrays.equals(new byte[]{ 4, 5 },
tableCell.getBinaryData()));
tableCell.setBinaryData(new byte[]{ 1, 2, 3 });
assertTrue(Arrays.equals(new byte[]{ 1, 2, 3 },
tableCell.getBinaryData()));
}
@Test(expected = IllegalStateException.class)
public void testGetBinaryDataThrowsOnWrongType() {
tableCell = new TableCell(new byte[]{ 2, 3, 4 });
tableCell.getBooleanValue();
}
@Test(expected = IllegalStateException.class)
public void throwsOnWrongSetInt() {
tableCell = new TableCell(1);
tableCell.setLongValue(2L);
}
@Test(expected = IllegalStateException.class)
public void throwsOnWrongSetLong() {
tableCell = new TableCell(1L);
tableCell.setIntValue(2);
}
@Test(expected = IllegalStateException.class)
public void throwsOnWrongSetFloat() {
tableCell = new TableCell(1.0f);
tableCell.setDoubleValue(2.0);
}
@Test(expected = IllegalStateException.class)
public void throwsOnWrongSetDouble() {
tableCell = new TableCell(1.0);
tableCell.setFloatValue(2.0f);
}
@Test(expected = IllegalStateException.class)
public void throwsOnWrongSetString() {
tableCell = new TableCell("yeah");
tableCell.setBinaryData(new byte[]{});
}
@Test(expected = IllegalStateException.class)
public void throwsOnWrongSetByteData() {
tableCell = new TableCell(new byte[]{});
tableCell.setStringValue("yeah");
}
@Test(expected = IllegalStateException.class)
public void throwsOnWrongSetBoolean() {
tableCell = new TableCell(true);
tableCell.setIntValue(1);
}
@Test
public void testNullify() {
tableCell = new TableCell(10);
assertEquals(Integer.valueOf(10), tableCell.getIntValue());
tableCell.nullify();
assertNull(tableCell.getIntValue());
}
@Test
public void testSerializeNullInt() {
tableCell = new TableCell(TableCellType.TYPE_INT);
ByteBuffer bb = ByteBuffer.allocate(2);
bb.put((byte) 10);
tableCell.serialize(bb);
bb.position(0);
assertEquals((byte) 10, bb.get());
assertEquals(INT_NULL, bb.get());
}
@Test
public void testSerializeNullLong() {
tableCell = new TableCell(TableCellType.TYPE_LONG);
ByteBuffer bb = ByteBuffer.allocate(2);
bb.put((byte) 11);
tableCell.serialize(bb);
assertEquals((byte) 11, bb.get(0));
assertEquals(LONG_NULL, bb.get(1));
}
@Test
public void testSerializeNullFloat() {
tableCell = new TableCell(TableCellType.TYPE_FLOAT);
ByteBuffer bb = ByteBuffer.allocate(2);
bb.put((byte) 12);
tableCell.serialize(bb);
bb.position(0);
assertEquals((byte) 12, bb.get());
assertEquals(FLOAT_NULL, bb.get());
}
@Test
public void testSerializeNullDouble() {
tableCell = new TableCell(TableCellType.TYPE_DOUBLE);
ByteBuffer bb = ByteBuffer.allocate(2);
bb.put((byte) 13);
tableCell.serialize(bb);
bb.position(0);
assertEquals((byte) 13, bb.get());
assertEquals(DOUBLE_NULL, bb.get());
}
@Test
public void testSerializeNullString() {
tableCell = new TableCell(TableCellType.TYPE_STRING);
ByteBuffer bb = ByteBuffer.allocate(2);
bb.put((byte) 14);
tableCell.serialize(bb);
bb.position(0);
assertEquals((byte) 14, bb.get());
assertEquals(STRING_NULL, bb.get());
}
@Test
public void testSerializeNullBoolean() {
tableCell = new TableCell(TableCellType.TYPE_BOOLEAN);
ByteBuffer bb = ByteBuffer.allocate(2);
bb.put((byte) 15);
tableCell.serialize(bb);
bb.position(0);
assertEquals((byte) 15, bb.get());
assertEquals(BOOLEAN_NULL, bb.get());
}
@Test
public void testSerializeNullBlob() {
tableCell = new TableCell(TableCellType.TYPE_BINARY);
ByteBuffer bb = ByteBuffer.allocate(2);
bb.put((byte) 16);
tableCell.serialize(bb);
assertEquals((byte) 16, bb.get(0));
assertEquals(BLOB_NULL, bb.get(1));
}
@Test
public void testDeserializeNullInt() {
ByteBuffer bb = ByteBuffer.allocate(2);
bb.put((byte) 20);
bb.put(INT_NULL);
bb.position(1);
TableCell tableCell = TableCell.deserialize(bb);
assertNull(tableCell.getValue());
assertEquals(TYPE_INT, tableCell.getTableCellType());
}
@Test
public void testDeserializeNullLong() {
ByteBuffer bb = ByteBuffer.allocate(2);
bb.put((byte) 21);
bb.put(LONG_NULL);
bb.position(1);
TableCell tableCell = TableCell.deserialize(bb);
assertNull(tableCell.getValue());
assertEquals(TYPE_LONG, tableCell.getTableCellType());
}
@Test
public void testDeserializeNullFloat() {
ByteBuffer bb = ByteBuffer.allocate(2);
bb.put((byte) 22);
bb.put(FLOAT_NULL);
bb.position(1);
TableCell tableCell = TableCell.deserialize(bb);
assertNull(tableCell.getValue());
assertEquals(TYPE_FLOAT, tableCell.getTableCellType());
}
@Test
public void testDeserializeNullDouble() {
ByteBuffer bb = ByteBuffer.allocate(2);
bb.put((byte) 23);
bb.put(DOUBLE_NULL);
bb.position(1);
TableCell tableCell = TableCell.deserialize(bb);
assertNull(tableCell.getValue());
assertEquals(TYPE_DOUBLE, tableCell.getTableCellType());
}
@Test
public void testDeserializeNullString() {
ByteBuffer bb = ByteBuffer.allocate(2);
bb.put((byte) 24);
bb.put(STRING_NULL);
bb.position(1);
TableCell tableCell = TableCell.deserialize(bb);
assertNull(tableCell.getValue());
assertEquals(TYPE_STRING, tableCell.getTableCellType());
}
@Test
public void testDeserializeNullBoolean() {
ByteBuffer bb = ByteBuffer.allocate(2);
bb.put((byte) 25);
bb.put(BOOLEAN_NULL);
bb.position(1);
TableCell tableCell = TableCell.deserialize(bb);
assertNull(tableCell.getValue());
assertEquals(TYPE_BOOLEAN, tableCell.getTableCellType());
}
@Test
public void testDeserializeNullBlob() {
ByteBuffer bb = ByteBuffer.allocate(2);
bb.put((byte) 26);
bb.put(BLOB_NULL);
bb.position(1);
TableCell tableCell = TableCell.deserialize(bb);
assertNull(tableCell.getValue());
assertEquals(TYPE_BINARY, tableCell.getTableCellType());
}
@Test
public void testSerializeInt() {
tableCell = new TableCell(100);
ByteBuffer bb = ByteBuffer.allocate(1000)
.order(ByteOrder.LITTLE_ENDIAN);
tableCell.serialize(bb);
assertEquals(INT_NOT_NULL, bb.get(0));
assertEquals(100, bb.getInt(1));
}
@Test
public void testDeserializeInt() {
ByteBuffer bb = ByteBuffer.allocate(10);
bb.put(0, INT_NOT_NULL);
bb.putInt(1, 121);
TableCell tc = TableCell.deserialize(bb);
assertEquals(TYPE_INT, tc.getTableCellType());
assertEquals((Integer) 121, tc.getIntValue());
}
@Test
public void testSerializeLong() {
tableCell = new TableCell(376L);
ByteBuffer bb = ByteBuffer.allocate(1000)
.order(ByteOrder.LITTLE_ENDIAN);
tableCell.serialize(bb);
assertEquals(LONG_NOT_NULL, bb.get(0));
assertEquals(376L, bb.getLong(1));
}
@Test
public void testDeserializeLong() {
ByteBuffer bb = ByteBuffer.allocate(10);
bb.put(0, LONG_NOT_NULL);
bb.putLong(1, 376L);
TableCell tc = TableCell.deserialize(bb);
assertEquals(TYPE_LONG, tc.getTableCellType());
assertEquals((Long) 376L, tc.getLongValue());
}
@Test
public void testSerializeFloat() {
tableCell = new TableCell(3.14f);
ByteBuffer bb = ByteBuffer.allocate(1000)
.order(ByteOrder.LITTLE_ENDIAN);
tableCell.serialize(bb);
assertEquals(FLOAT_NOT_NULL, bb.get(0));
assertEquals(3.14f, bb.getFloat(1), 0.0f);
}
@Test
public void testDeserializeFloat() {
ByteBuffer bb = ByteBuffer.allocate(10);
bb.put(0, FLOAT_NOT_NULL);
bb.putFloat(1, 3.14f);
TableCell tc = TableCell.deserialize(bb);
assertEquals(TYPE_FLOAT, tc.getTableCellType());
assertEquals((Float) 3.14f, tc.getFloatValue());
}
@Test
public void testSerializeDouble() {
tableCell = new TableCell(1.618);
ByteBuffer bb = ByteBuffer.allocate(1000)
.order(ByteOrder.LITTLE_ENDIAN);
tableCell.serialize(bb);
assertEquals(DOUBLE_NOT_NULL, bb.get(0));
assertEquals(1.618, bb.getDouble(1), 0.0);
}
@Test
public void testDeserializeDouble() {
ByteBuffer bb = ByteBuffer.allocate(10);
bb.put(0, DOUBLE_NOT_NULL);
bb.putDouble(1, 1.618);
TableCell tc = TableCell.deserialize(bb);
assertEquals(TYPE_DOUBLE, tc.getTableCellType());
assertEquals((Double) 1.618, tc.getDoubleValue());
}
@Test
public void testSerializeBoolean() {
tableCell = new TableCell(false);
ByteBuffer bb = ByteBuffer.allocate(1000)
.order(ByteOrder.LITTLE_ENDIAN);
tableCell.serialize(bb);
assertEquals(BOOLEAN_NOT_NULL, bb.get(0));
assertEquals(BOOLEAN_FALSE, bb.get(1));
}
@Test
public void testDeserializeBoolean() {
ByteBuffer bb = ByteBuffer.allocate(10).order(ByteOrder.LITTLE_ENDIAN);
bb.put(0, BOOLEAN_NOT_NULL);
bb.put(1, BOOLEAN_TRUE);
TableCell tc = TableCell.deserialize(bb);
assertEquals(TYPE_BOOLEAN, tc.getTableCellType());
assertEquals((Boolean) true, tc.getBooleanValue());
}
@Test
public void testSerializationString() {
tableCell = new TableCell("Hello!");
ByteBuffer bb = ByteBuffer.allocate(50).order(ByteOrder.LITTLE_ENDIAN);
tableCell.serialize(bb);
bb.position(0);
assertEquals(STRING_NOT_NULL, bb.get());
assertEquals("Hello!".length(), bb.getInt());
for (char c : "Hello!".toCharArray()) {
assertEquals(c, bb.getChar());
}
}
@Test
public void testDeserializationString() {
ByteBuffer bb = ByteBuffer.allocate(50).order(ByteOrder.LITTLE_ENDIAN);
bb.put(STRING_NOT_NULL);
bb.putInt(4);
for (char c : "funk".toCharArray()) {
bb.putChar(c);
}
bb.position(0);
TableCell tc = TableCell.deserialize(bb);
assertEquals(TYPE_STRING, tc.getTableCellType());
assertEquals("funk", tc.getStringValue());
}
@Test
public void testSerializationBinary() {
tableCell = new TableCell(new byte[] { 2, 6, 9 });
ByteBuffer bb = ByteBuffer.allocate(50).order(ByteOrder.LITTLE_ENDIAN);
tableCell.serialize(bb);
bb.position(0);
assertEquals(BLOB_NOT_NULL, bb.get());
assertEquals(3, bb.getInt());
assertEquals((byte) 2, bb.get());
assertEquals((byte) 6, bb.get());
assertEquals((byte) 9, bb.get());
}
@Test
public void testDeserializationBinary() {
ByteBuffer bb = ByteBuffer.allocate(50).order(ByteOrder.LITTLE_ENDIAN);
bb.put(BLOB_NOT_NULL);
bb.putInt(3);
bb.put((byte) 2);
bb.put((byte) 6);
bb.put((byte) 9);
bb.position(0);
TableCell tc = TableCell.deserialize(bb);
assertEquals(TYPE_BINARY, tc.getTableCellType());
assertTrue(Arrays.equals(new byte[] {2, 6, 9}, tc.getBinaryData()));
}
}
<file_sep>/src/test/java/net/coderodde/javadb/DatabaseTest.java
package net.coderodde.javadb;
import java.nio.ByteBuffer;
import org.junit.Test;
import static org.junit.Assert.*;
public class DatabaseTest {
@Test
public void testSerializeDeserialize() {
Database db = new Database("hello_db");
TableColumnDescriptor cola1 =
new TableColumnDescriptor("cola1", TableCellType.TYPE_BINARY);
TableColumnDescriptor cola2 =
new TableColumnDescriptor("cola2", TableCellType.TYPE_BOOLEAN);
TableColumnDescriptor colb1 =
new TableColumnDescriptor("colb1", TableCellType.TYPE_FLOAT);
TableColumnDescriptor colb2 =
new TableColumnDescriptor("colb2", TableCellType.TYPE_STRING);
TableColumnDescriptor colb3 =
new TableColumnDescriptor("colb3", TableCellType.TYPE_LONG);
Table tablea = db.createTable("tablea", cola1, cola2);
Table tableb = db.createTable("tableb", colb1, colb2, colb3);
TableRow rowa1 = tablea.putTableRow(new byte[] { 1, 2, 3}, true);
TableRow rowa2 = tablea.putTableRow(null, false);
TableRow rowb1 = tableb.putTableRow(1.0f, "hello", 100L);
TableRow rowb2 = tableb.putTableRow(1.1f, "funky", 101L);
TableRow rowb3 = tableb.putTableRow(1.2f, "you", 102L);
ByteBuffer byteBuffer = db.serialize();
byteBuffer.position(0);
Database db2 = Database.deserialize(byteBuffer);
assertEquals(db, db2);
tableb.removeTableColumnDescriptor("colb2");
rowb2.get("colb3");
ByteBuffer bb2 = db.serialize();
bb2.position(0);
db2 = Database.deserialize(bb2);
assertEquals(db, db2);
assertEquals(2, rowb1.getNumberOfCells());
assertEquals(2, rowb2.getNumberOfCells());
assertEquals(2, rowb3.getNumberOfCells());
}
@Test
public void test1() {
Database db = new Database("hello_db");
assertEquals("hello_db", db.getDatabaseName());
TableColumnDescriptor col1 =
new TableColumnDescriptor("col1", TableCellType.TYPE_STRING);
TableColumnDescriptor col2 =
new TableColumnDescriptor("col2", TableCellType.TYPE_LONG);
db.createTable("table1", col1, col2);
assertEquals("table1", db.getTable("table1").getTableName());
Table table = db.getTable("table1");
TableRow row1 = table.putTableRow("Yeah", 12L);
TableRow row2 = table.putTableRowAt(0, "Ok", 26L);
assertEquals("Yeah", row1.get("col1").getStringValue());
assertEquals((Long) 12L, row1.get("col2").getLongValue());
assertEquals("Ok", row2.get("col1").getStringValue());
assertEquals((Long) 26L, row2.get("col2").getLongValue());
table.addTableColumnDescriptor(
new TableColumnDescriptor("col3", TableCellType.TYPE_BINARY));
assertEquals(3, row1.getNumberOfCells());
assertEquals(3, row2.getNumberOfCells());
assertNull(row1.get(2).getBinaryData());
assertNull(row2.get(2).getBinaryData());
assertNull(row1.get("col3").getBinaryData());
assertNull(row2.get("col3").getBinaryData());
table.removeTableColumnDescriptor("col2");
assertEquals(2, row1.getNumberOfCells());
assertEquals(2, row2.getNumberOfCells());
assertFalse(table.containsTableColumnDescriptor("col2"));
assertTrue(table.containsTableColumnDescriptor("col1"));
assertTrue(table.containsTableColumnDescriptor("col3"));
assertNull(row1.get(1).getValue());
assertNull(row2.get(1).getValue());
assertEquals("Yeah", row1.get(0).getStringValue());
assertEquals("Ok", row2.get(0).getStringValue());
assertEquals("Yeah", row1.get("col1").getStringValue());
assertEquals("Ok", row2.get("col1").getStringValue());
}
@Test(expected = IllegalArgumentException.class)
public void testTableGetThrowsOnNonExistentTable() {
Database db = new Database("hello_db");
db.createTable("fds"); // No columns here!
}
@Test(expected = NullPointerException.class)
public void testTableGetThrowsOnNullColumnDescriptor() {
Database db = new Database("hello_db");
db.createTable("fds",
new TableColumnDescriptor("col1", TableCellType.TYPE_INT),
null,
new TableColumnDescriptor("col3", TableCellType.TYPE_FLOAT));
}
}
<file_sep>/src/main/java/net/coderodde/javadb/TableCell.java
package net.coderodde.javadb;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* This class implements an individual table cell.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Dec 21, 2016)
*/
public final class TableCell {
private static final byte NON_NULL_MASK = 0x10;
static final byte INT_NULL = 1;
static final byte LONG_NULL = 2;
static final byte FLOAT_NULL = 3;
static final byte DOUBLE_NULL = 4;
static final byte STRING_NULL = 5;
static final byte BOOLEAN_NULL = 6;
static final byte BLOB_NULL = 7;
static final byte INT_NOT_NULL = INT_NULL | NON_NULL_MASK;
static final byte LONG_NOT_NULL = LONG_NULL | NON_NULL_MASK;
static final byte FLOAT_NOT_NULL = FLOAT_NULL | NON_NULL_MASK;
static final byte DOUBLE_NOT_NULL = DOUBLE_NULL | NON_NULL_MASK;
static final byte STRING_NOT_NULL = STRING_NULL | NON_NULL_MASK;
static final byte BOOLEAN_NOT_NULL = BOOLEAN_NULL | NON_NULL_MASK;
static final byte BLOB_NOT_NULL = BLOB_NULL | NON_NULL_MASK;
static final Integer DEFAULT_INT = 0;
static final Long DEFAULT_LONG = 0L;
static final Float DEFAULT_FLOAT = 0.0f;
static final Double DEFAULT_DOUBLE = 0.0;
static final String DEFAULT_STRING = "";
static final Boolean DEFAULT_BOOLEAN = Boolean.FALSE;
static final byte[] DEFAULT_BLOB = new byte[0];
/**
* Number of bytes used to decode string and byte array lengths.
*/
private static final int SIZE_BYTES = 4;
static final EnumMap<TableCellType, Object> defaults =
new EnumMap<>(TableCellType.class);
private static final Map<Byte, TableCellDeserializer>
deserializerDispatchMap = new HashMap<>();
private static final Map<TableCellType, TableCellSerializer>
serializerDispatchMap = new HashMap<>();
static {
defaults.put(TableCellType.TYPE_INT, DEFAULT_INT );
defaults.put(TableCellType.TYPE_LONG, DEFAULT_LONG );
defaults.put(TableCellType.TYPE_FLOAT, DEFAULT_FLOAT );
defaults.put(TableCellType.TYPE_DOUBLE, DEFAULT_DOUBLE );
defaults.put(TableCellType.TYPE_STRING, DEFAULT_STRING );
defaults.put(TableCellType.TYPE_BOOLEAN, DEFAULT_BOOLEAN);
defaults.put(TableCellType.TYPE_BINARY, DEFAULT_BLOB );
Map<Byte, TableCellDeserializer> d = deserializerDispatchMap;
d.put(INT_NOT_NULL, TableCell::deserializeInt);
d.put(LONG_NOT_NULL, TableCell::deserializeLong);
d.put(FLOAT_NOT_NULL, TableCell::deserializeFloat);
d.put(DOUBLE_NOT_NULL, TableCell::deserializeDouble);
d.put(STRING_NOT_NULL, TableCell::deserializeString);
d.put(BOOLEAN_NOT_NULL, TableCell::deserializeBoolean);
d.put(BLOB_NOT_NULL, TableCell::deserializeBlob);
d.put(INT_NULL, TableCell::deserializeNullInt);
d.put(LONG_NULL, TableCell::deserializeNullLong);
d.put(FLOAT_NULL, TableCell::deserializeNullFloat);
d.put(DOUBLE_NULL, TableCell::deserializeNullDouble);
d.put(STRING_NULL, TableCell::deserializeNullString);
d.put(BOOLEAN_NULL, TableCell::deserializeNullBoolean);
d.put(BLOB_NULL, TableCell::deserializeNullBlob);
Map<TableCellType, TableCellSerializer> s = serializerDispatchMap;
s.put(TableCellType.TYPE_INT, TableCell::serializeInt);
s.put(TableCellType.TYPE_LONG, TableCell::serializeLong);
s.put(TableCellType.TYPE_FLOAT, TableCell::serializeFloat);
s.put(TableCellType.TYPE_DOUBLE, TableCell::serializeDouble);
s.put(TableCellType.TYPE_STRING, TableCell::serializeString);
s.put(TableCellType.TYPE_BOOLEAN, TableCell::serializeBoolean);
s.put(TableCellType.TYPE_BINARY, TableCell::serializeBlob);
}
static final byte BOOLEAN_TRUE = 1;
static final byte BOOLEAN_FALSE = 0;
private Object value;
private final TableCellType tableCellType;
public Object getValue() {
return value;
}
public TableCell(Integer intValue) {
this.value = intValue;
tableCellType = TableCellType.TYPE_INT;
}
public TableCell(Long longValue) {
this.value = longValue;
tableCellType = TableCellType.TYPE_LONG;
}
public TableCell(Float floatValue) {
this.value = floatValue;
tableCellType = TableCellType.TYPE_FLOAT;
}
public TableCell(Double doubleValue) {
this.value = doubleValue;
tableCellType = TableCellType.TYPE_DOUBLE;
}
public TableCell(String stringValue) {
this.value = stringValue;
tableCellType = TableCellType.TYPE_STRING;
}
public TableCell(Boolean booleanValue) {
this.value = booleanValue;
tableCellType = TableCellType.TYPE_BOOLEAN;
}
public TableCell(byte[] binaryData) {
this.value = binaryData;
tableCellType = TableCellType.TYPE_BINARY;
}
/**
* Constructs a new table cell of particular data type with {@code null}
* value.
*
* @param tableCellType the type of the cell.
*/
public TableCell(TableCellType tableCellType) {
this.tableCellType = Objects.requireNonNull(tableCellType,
"Table cell type is null.");
}
public TableCellType getTableCellType() {
return tableCellType;
}
public Integer getIntValue() {
checkTypesMatchOnRead(TableCellType.TYPE_INT);
return (Integer) value;
}
public Long getLongValue() {
checkTypesMatchOnRead(TableCellType.TYPE_LONG);
return (Long) value;
}
public Float getFloatValue() {
checkTypesMatchOnRead(TableCellType.TYPE_FLOAT);
return (Float) value;
}
public Double getDoubleValue() {
checkTypesMatchOnRead(TableCellType.TYPE_DOUBLE);
return (Double) value;
}
public String getStringValue() {
checkTypesMatchOnRead(TableCellType.TYPE_STRING);
return (String) value;
}
public Boolean getBooleanValue() {
checkTypesMatchOnRead(TableCellType.TYPE_BOOLEAN);
return (Boolean) value;
}
public byte[] getBinaryData() {
checkTypesMatchOnRead(TableCellType.TYPE_BINARY);
return (byte[]) value;
}
public void setIntValue(Integer intValue) {
checkTypesMatchOnWrite(TableCellType.TYPE_INT);
this.value = intValue;
}
public void setLongValue(Long longValue) {
checkTypesMatchOnWrite(TableCellType.TYPE_LONG);
this.value = longValue;
}
public void setFloatValue(Float floatValue) {
checkTypesMatchOnWrite(TableCellType.TYPE_FLOAT);
this.value = floatValue;
}
public void setDoubleValue(Double doubleValue) {
checkTypesMatchOnWrite(TableCellType.TYPE_DOUBLE);
this.value = doubleValue;
}
public void setStringValue(String stringValue) {
checkTypesMatchOnWrite(TableCellType.TYPE_STRING);
this.value = stringValue;
}
public void setBooleanValue(Boolean booleanValue) {
checkTypesMatchOnWrite(TableCellType.TYPE_BOOLEAN);
this.value = booleanValue;
}
public void setBinaryData(byte[] binaryData) {
checkTypesMatchOnWrite(TableCellType.TYPE_BINARY);
this.value = binaryData;
}
public void nullify() {
value = null;
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (o == this) {
return true;
}
if (!getClass().equals(o.getClass())) {
return false;
}
TableCell other = (TableCell) o;
if (!getTableCellType().equals(other.getTableCellType())) {
return false;
}
if (getTableCellType().equals(TableCellType.TYPE_BINARY)) {
return Arrays.equals((byte[]) value, (byte[]) other.value);
}
return Objects.equals(value, other.value);
}
int getSerializationLength() {
switch (tableCellType) {
case TYPE_INT:
return 1 + (value != null ? Integer.BYTES : 0);
case TYPE_LONG:
return 1 + (value != null ? Long.BYTES : 0);
case TYPE_FLOAT:
return 1 + (value != null ? Float.BYTES : 0);
case TYPE_DOUBLE:
return 1 + (value != null ? Double.BYTES : 0);
case TYPE_STRING:
if (value == null) {
return 1;
}
int stringChars = ((String) value).length();
int stringBytes = stringChars * Character.BYTES;
return 1 + SIZE_BYTES + stringBytes;
case TYPE_BOOLEAN:
return 1 + (value != null ? 1 : 0);
case TYPE_BINARY:
if (value == null) {
return 1;
}
return 1 + SIZE_BYTES + ((byte[]) value).length;
default:
throw new IllegalStateException("Unknown table cell type.");
}
}
void serialize(ByteBuffer byteBuffer) {
TableCellSerializer tableCellSerializer =
serializerDispatchMap.get(getTableCellType());
if (tableCellSerializer == null) {
throw new IllegalStateException(
"This exception must never be thrown. One " +
"possibility is that a new data type is introduced, " +
"yet is not handled in this method.");
}
tableCellSerializer.serialize(byteBuffer, value);
}
static TableCell deserialize(ByteBuffer byteBuffer) {
Objects.requireNonNull(byteBuffer,
"The input data byte array is null.");
byte tableCellType = byteBuffer.get();
TableCellDeserializer deserializerRoutine =
deserializerDispatchMap.get(tableCellType);
if (deserializerRoutine == null) {
throw new IllegalStateException(
"Invalid table cell type descriptor.");
}
return deserializerRoutine.deserialize(byteBuffer);
}
private static void serializeInt(ByteBuffer byteBuffer, Object value) {
if (value == null) {
byteBuffer.put(INT_NULL);
} else {
byteBuffer.put(INT_NOT_NULL).putInt((int) value);
}
}
private static void serializeLong(ByteBuffer byteBuffer, Object value) {
if (value == null) {
byteBuffer.put(LONG_NULL);
} else {
byteBuffer.put(LONG_NOT_NULL).putLong((long) value);
}
}
private static void serializeFloat(ByteBuffer byteBuffer, Object value) {
if (value == null) {
byteBuffer.put(FLOAT_NULL);
} else {
byteBuffer.put(FLOAT_NOT_NULL).putFloat((float) value);
}
}
private static void serializeDouble(ByteBuffer byteBuffer, Object value) {
if (value == null) {
byteBuffer.put(DOUBLE_NULL);
} else {
byteBuffer.put(DOUBLE_NOT_NULL).putDouble((double) value);
}
}
private static void serializeString(ByteBuffer byteBuffer, Object value) {
if (value == null) {
byteBuffer.put(STRING_NULL);
} else {
byteBuffer.put(STRING_NOT_NULL);
byteBuffer.putInt(((String) value).length());
for (char c : ((String) value).toCharArray()) {
byteBuffer.putChar(c);
}
}
}
private static void serializeBoolean(ByteBuffer byteBuffer, Object value) {
if (value == null) {
byteBuffer.put(BOOLEAN_NULL);
} else {
byteBuffer.put(BOOLEAN_NOT_NULL);
byteBuffer.put(((boolean) value) ? BOOLEAN_TRUE : BOOLEAN_FALSE);
}
}
private static void serializeBlob(ByteBuffer byteBuffer, Object value) {
if (value == null) {
byteBuffer.put(BLOB_NULL);
} else {
byteBuffer.put(BLOB_NOT_NULL);
byte[] blob = (byte[]) value;
byteBuffer.putInt(blob.length);
for (int i = 0; i < blob.length; ++i) {
byteBuffer.put(blob[i]);
}
}
}
private static TableCell deserializeNullInt(ByteBuffer byteBuffer) {
return new TableCell(TableCellType.TYPE_INT);
}
private static TableCell deserializeNullLong(ByteBuffer byteBuffer) {
return new TableCell(TableCellType.TYPE_LONG);
}
private static TableCell deserializeNullFloat(ByteBuffer byteBuffer) {
return new TableCell(TableCellType.TYPE_FLOAT);
}
private static TableCell deserializeNullDouble(ByteBuffer byteBuffer) {
return new TableCell(TableCellType.TYPE_DOUBLE);
}
private static TableCell deserializeNullString(ByteBuffer byteBuffer) {
return new TableCell(TableCellType.TYPE_STRING);
}
private static TableCell deserializeNullBoolean(ByteBuffer byteBuffer) {
return new TableCell(TableCellType.TYPE_BOOLEAN);
}
private static TableCell deserializeNullBlob(ByteBuffer byteBuffer) {
return new TableCell(TableCellType.TYPE_BINARY);
}
private static TableCell deserializeInt(ByteBuffer byteBuffer) {
int value = byteBuffer.getInt();
TableCell tableCell = new TableCell(value);
return tableCell;
}
private static TableCell deserializeLong(ByteBuffer byteBuffer) {
long value = byteBuffer.getLong();
TableCell tableCell = new TableCell(value);
return tableCell;
}
private static TableCell deserializeFloat(ByteBuffer byteBuffer) {
float value = byteBuffer.getFloat();
TableCell tableCell = new TableCell(value);
return tableCell;
}
private static TableCell deserializeDouble(ByteBuffer byteBuffer) {
double value = byteBuffer.getDouble();
TableCell tableCell = new TableCell(value);
return tableCell;
}
private static TableCell deserializeString(ByteBuffer byteBuffer) {
// Get the string length:
int stringLength = byteBuffer.getInt();
StringBuilder sb = new StringBuilder(stringLength);
for (int i = 0; i < stringLength; ++i) {
sb.append(byteBuffer.getChar());
}
TableCell tableCell = new TableCell(sb.toString());
return tableCell;
}
private static TableCell deserializeBlob(ByteBuffer byteBuffer) {
// Get the byte array length:
int byteArrayLength = byteBuffer.getInt();
byte[] byteArray = new byte[byteArrayLength];
for (int index = 0; index != byteArrayLength; ++index) {
byteArray[index] = byteBuffer.get();
}
TableCell tableCell = new TableCell(byteArray);
return tableCell;
}
private static TableCell deserializeBoolean(ByteBuffer byteBuffer) {
boolean value;
switch (byteBuffer.get()) {
case BOOLEAN_TRUE:
value = true;
break;
case BOOLEAN_FALSE:
value = false;
break;
default:
throw new BadDataFormatException(
"Unknown boolean literal encoding.");
}
TableCell tableCell = new TableCell(value);
return tableCell;
}
private void checkTypesMatchOnRead(TableCellType requestedType) {
if (!tableCellType.equals(requestedType)) {
throw new IllegalStateException(
"Attempted to read " + requestedType.getTypeName() +
" from a table cell holding " + tableCellType.getTypeName() + ".");
}
}
private void checkTypesMatchOnWrite(TableCellType requestedType) {
if (!tableCellType.equals(requestedType)) {
throw new IllegalStateException(
"Attempted to write " + requestedType.getTypeName() +
" to a table cell holding " + tableCellType.getTypeName() + ".");
}
}
}
<file_sep>/README.md
# JavaDB
JavaDB is a simplistic database management system. It supports cells holding the following data types: `int`, `long`, `float`, `double`, `boolean`, `String`, and `byte[]`.
Just like in conventional databases, a [`Database`](https://github.com/coderodde/JavaDB/blob/master/src/main/java/net/coderodde/javadb/Database.java) is a list of [`Table`](https://github.com/coderodde/JavaDB/blob/master/src/main/java/net/coderodde/javadb/Table.java)s, a [`Table`](https://github.com/coderodde/JavaDB/blob/master/src/main/java/net/coderodde/javadb/Table.java) is a list of [`TableRow`](https://github.com/coderodde/JavaDB/blob/master/src/main/java/net/coderodde/javadb/TableRow.java)s, and a [`TableRow`](https://github.com/coderodde/JavaDB/blob/master/src/main/java/net/coderodde/javadb/TableRow.java) is a list of [`TableCell`](https://github.com/coderodde/JavaDB/blob/master/src/main/java/net/coderodde/javadb/TableCell.java)s.
The `Database` provides a simple API for saving the entire database into a file, and later, reading it into main memory.
The API documentation is [here](http://coderodde.github.io/javadb/).
<file_sep>/src/test/java/net/coderodde/javadb/TableRowTest.java
package net.coderodde.javadb;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import org.junit.Test;
import static org.junit.Assert.*;
public class TableRowTest {
@Test
public void testSerialization() {
// TableCell tableCell1 = new TableCell(TableCellType.TYPE_BINARY);
// TableCell tableCell2 = new TableCell("Hello!");
//
// TableRow row = new TableRow();
//
// row.add(tableCell1);
// row.add(tableCell2);
//
// ByteBuffer bb = ByteBuffer.allocate(1000)
// .order(ByteOrder.LITTLE_ENDIAN);
//
// row.serialize(bb);
//
// bb.position(0);
//
// assertEquals(TableCell.BLOB_NULL, bb.get());
// assertEquals(TableCell.STRING_NOT_NULL, bb.get());
// assertEquals(6, bb.getInt());
//
// for (char c : "Hello!".toCharArray()) {
// assertEquals(c, bb.getChar());
// }
}
@Test
public void testDeserialization() {
ByteBuffer bb = ByteBuffer.allocate(100).order(ByteOrder.LITTLE_ENDIAN);
bb.put(TableCell.BLOB_NULL);
bb.put(TableCell.STRING_NOT_NULL);
bb.putInt(6);
for (char c : "Hello!".toCharArray()) {
bb.putChar(c);
}
bb.position(0);
TableRow row = TableRow.deserialize(bb, 2);
assertEquals(2, row.getNumberOfCells());
TableCell tc1 = row.get(0);
TableCell tc2 = row.get(1);
assertEquals(TableCellType.TYPE_BINARY, tc1.getTableCellType());
assertEquals(TableCellType.TYPE_STRING, tc2.getTableCellType());
assertNull(tc1.getValue());
assertEquals("Hello!", tc2.getStringValue());
}
@Test
public void testEquals() {
// TableCell tableCell1 = new TableCell(12321);
// TableCell tableCell2 = new TableCell("hello");
// TableCell tableCell3 = new TableCell(new byte[] { 1, 5, 8 });
// TableCell tableCell3a = new TableCell(4.5f);
//
// TableRow tableRow1 = new TableRow();
// TableRow tableRow2 = new TableRow();
//
// assertTrue(tableRow1.equals(tableRow2));
// assertTrue(tableRow1.equals(tableRow1));
// assertFalse(tableRow1.equals(null));
//
// tableRow1.add(0, tableCell1);
// tableRow1.add(1, tableCell2);
//
// tableRow2.add(0, tableCell1);
// tableRow2.add(1, tableCell2);
//
// assertTrue(tableRow1.equals(tableRow2));
//
// tableRow1.add(2, tableCell3);
//
// assertFalse(tableRow1.equals(tableRow2));
//
// tableRow2.add(2, tableCell3a);
//
// assertFalse(tableRow1.equals(tableRow2));
//
// tableRow2.set(2, new TableCell(new byte[] {1, 5}));
//
// assertFalse(tableRow1.equals(tableRow2));
//
// tableRow2.set(2, new TableCell(new byte[] { 1, 5, 9 }));
//
// assertFalse(tableRow1.equals(tableRow2));
//
// tableRow2.set(2, new TableCell(new byte[] { 1, 5, 8 }));
// assertTrue(tableRow1.equals(tableRow2));
}
}
<file_sep>/src/main/java/net/coderodde/javadb/TableCellType.java
package net.coderodde.javadb;
/**
* This enumeration communicates the type stored in a table cell.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Dec 20, 2016)
*/
public enum TableCellType {
/**
* 32-bit signed integer.
*/
TYPE_INT ((byte) 1, "an integer"),
/**
* 64-bit signed integer.
*/
TYPE_LONG ((byte) 2, "a long integer"),
/**
* 32-bit floating point number.
*/
TYPE_FLOAT ((byte) 3, "a float number"),
/**
* 64-bit floating point number.
*/
TYPE_DOUBLE ((byte) 4, "a double number"),
/**
* Variable length string.
*/
TYPE_STRING ((byte) 5, "a string"),
/**
* A boolean value.
*/
TYPE_BOOLEAN ((byte) 6, "a boolean"),
/**
* Binary data (BLOB).
*/
TYPE_BINARY ((byte) 7, "a binary object");
/**
* The actual type ID identifier.
*/
private final byte typeId;
private final String typeName;
private TableCellType(byte typeId, String typeName) {
this.typeId = typeId;
this.typeName = typeName;
}
public String getTypeName() {
return typeName;
}
public byte getTypeId() {
return typeId;
}
public static TableCellType getTableCellType(byte typeId) {
switch (typeId) {
case 1:
return TYPE_INT;
case 2:
return TYPE_LONG;
case 3:
return TYPE_FLOAT;
case 4:
return TYPE_DOUBLE;
case 5:
return TYPE_STRING;
case 6:
return TYPE_BOOLEAN;
case 7:
return TYPE_BINARY;
default:
throw new IllegalArgumentException(
"Unknown type ID: " + typeId);
}
}
}
<file_sep>/src/main/java/net/coderodde/javadb/TableView.java
package net.coderodde.javadb;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public final class TableView {
private final List<TableRow> tableRowList = new ArrayList<>();
private final List<TableColumnDescriptor> tableColumnDescriptorList;
private final Map<TableColumnDescriptor, Integer> cellMap = new HashMap<>();
TableView(Table ownerTable,
List<TableColumnDescriptor> tableColumnDescriptorList) {
this.tableColumnDescriptorList = tableColumnDescriptorList;
for (int i = 0; i < ownerTable.tableColumnDescriptorList.size(); ++i) {
if (tableColumnDescriptorList
.contains(ownerTable.tableColumnDescriptorList.get(i))) {
cellMap.put(ownerTable.tableColumnDescriptorList.get(i), i);
}
}
}
public void addTableRow(TableRow tableRow) {
tableRowList.add(Objects.requireNonNull(tableRow, "Table row is null."));
}
public TableRow removeTableRow(int index) {
return tableRowList.remove(index);
}
public TableRow getTableRow(int index) {
return tableRowList.get(index);
}
@Override
public String toString() {
Map<TableColumnDescriptor, Integer> columnWidthMap =
getColumnWidthMap();
int viewWidth = getViewWidth(columnWidthMap);
int viewHeight = tableRowList.size() + 4;
StringBuilder sb = new StringBuilder(viewHeight * (viewWidth + 1) - 1);
StringBuilder separatorBar = getSeparatorBar(columnWidthMap, viewWidth);
sb.append(separatorBar).append('\n');
sb.append(header(viewWidth, columnWidthMap)).append('\n');
sb.append(separatorBar);
for (TableRow tableRow : tableRowList) {
sb.append('\n');
sb.append(tableRowToString(tableRow, viewWidth, columnWidthMap));
}
return sb.append('\n').append(separatorBar).toString();
}
private StringBuilder tableRowToString(
TableRow tableRow,
int width,
Map<TableColumnDescriptor, Integer> columnWidthMap) {
StringBuilder sb = new StringBuilder(width);
sb.append('|');
for (TableColumnDescriptor tableColumnDescriptor
: tableColumnDescriptorList) {
Object value = tableRow.get(cellMap.get(tableColumnDescriptor))
.getValue();
String text;
if (value == null) {
text = "NULL";
} else {
text = value.toString();
}
sb.append(getCellText(columnWidthMap.get(tableColumnDescriptor),
text));
}
return sb;
}
private StringBuilder getCellText(int width, String text) {
StringBuilder sb = new StringBuilder(width);
int len = width - 1;
sb.append(String.format(" %-" + len + "s|", text));
return sb;
}
private StringBuilder
header(int width, Map<TableColumnDescriptor, Integer> columnWidthMap) {
StringBuilder sb = new StringBuilder(width);
sb.append('|');
for (TableColumnDescriptor tableColumnDescriptor
: tableColumnDescriptorList) {
String columnName = tableColumnDescriptor.getTableColumnName();
int len = columnWidthMap.get(tableColumnDescriptor) - 1;
sb.append(String.format(" %-" + len + "s|", columnName));
}
return sb;
}
private StringBuilder
getSeparatorBar(Map<TableColumnDescriptor, Integer> columnWidthMap,
int viewWidth) {
StringBuilder sb = new StringBuilder(viewWidth).append('+');
for (TableColumnDescriptor tableColumnDescriptor :
tableColumnDescriptorList) {
sb.append(getBar(columnWidthMap.get(tableColumnDescriptor)))
.append('+');
}
return sb;
}
private String getBar(int width) {
StringBuilder sb = new StringBuilder(width);
for (int i = 0; i < width; ++i) {
sb.append('-');
}
return sb.toString();
}
private int getViewWidth(
Map<TableColumnDescriptor, Integer> columnWidthMap) {
int width = columnWidthMap.size() + 1;
for (Map.Entry<TableColumnDescriptor, Integer> e
: columnWidthMap.entrySet()) {
width += e.getValue();
}
return width;
}
private Map<TableColumnDescriptor, Integer> getColumnWidthMap() {
Map<TableColumnDescriptor, Integer> columnLengthMap = new HashMap<>();
for (TableColumnDescriptor tableColumnDescriptor :
tableColumnDescriptorList) {
columnLengthMap.put(tableColumnDescriptor,
tableColumnDescriptor.getTableColumnName()
.length());
}
for (TableColumnDescriptor tableColumnDescriptor :
tableColumnDescriptorList) {
int index = cellMap.get(tableColumnDescriptor);
int maxColumnWidth = columnLengthMap.get(tableColumnDescriptor);
for (TableRow tableRow : tableRowList) {
String cellContent = tableRow.get(index).getValue().toString();
int cellContentWidth = cellContent.length();
maxColumnWidth = Math.max(maxColumnWidth, cellContentWidth);
}
columnLengthMap.put(tableColumnDescriptor, maxColumnWidth);
}
for (Map.Entry<TableColumnDescriptor, Integer> e
: columnLengthMap.entrySet()) {
// Add the left and right margin spaces.
e.setValue(e.getValue() + 2);
}
return columnLengthMap;
}
public static void main(String[] args) {
Database db = new Database("mydb");
TableColumnDescriptor col1 =
new TableColumnDescriptor("first_name",
TableCellType.TYPE_STRING);
TableColumnDescriptor col2 =
new TableColumnDescriptor("last_name",
TableCellType.TYPE_STRING);
TableColumnDescriptor col3 =
new TableColumnDescriptor("age", TableCellType.TYPE_INT);
db.createTable("person", col1, col2, col3);
Table table = db.getTable("person");
TableRow row1 = table.putTableRow("Violetta", "Efremov", 24);
TableRow row2 = table.putTableRow("Rodion", "Efremov", 28);
TableView tableView = table.createTableView(col3, col2, col1);
tableView.addTableRow(row2);
tableView.addTableRow(row1);
System.out.println(tableView.toString());
}
}
| 4f644567986ffb5465790b96196020989ea5051d | [
"Markdown",
"Java"
] | 7 | Java | coderodde/JavaDB | 3a30df149cec9fc486dec4151f70a75e2c9720f6 | 5026198f4bc1346b89761d125357a6e3e9544706 |
refs/heads/main | <file_sep>#include <sys/types.h>
#include <sys/capability.h>
#include <dirent.h>
#include <stdio.h>
#include <ctype.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int readable = 0;
char fieldNames[8][20] = {{"NAME"},
{"PID"},
{"TID"},
{"INHERITABLE"},
{"PERMITTED"},
{"EFFECTIVE"},
{"BOUNDING"},
{"AMBIENT"}};
void printReadable(char *capNum) {
unsigned long long value;
unsigned cap;
const char *sep = "";
value = strtoull(capNum, NULL, 16);
printf("0x%016llx=", value);
if (!memcmp("0000003fffffffff", capNum, 16)) {
printf("all\n");
return;
}
if (!memcmp("0000000000000000", capNum, 16)) {
printf("none\n");
return;
}
for (cap = 0; (cap < 64) && (value >> cap); ++cap) {
if (value & (1ULL << cap)) {
char *ptr;
ptr = cap_to_name(cap);
if (ptr != NULL) {
printf("%s%s", sep, ptr);
cap_free(ptr);
} else {
printf("%s%u", sep, cap);
}
sep = ",";
}
}
printf("\n");
}
int processFile(char *p, int pid, int tid) {
const int fieldCount = 6;
char keys[6][10] = {{"Name:"},
{"CapInh:"},
{"CapPrm:"},
{"CapEff:"},
{"CapBnd:"},
{"CapAmb:"}};
char values[fieldCount][20];
for (int i = 0; i < fieldCount; ++i) {
char *ptr = strstr(p, keys[i]);
ptr += strlen(keys[i]) + 1; // + 1 to skip \t
int j;
for (j = 0; j < 19 && *ptr != '\n'; ++j, ++ptr) {
values[i][j] = *ptr;
}
values[i][j] = '\0';
}
if (readable) {
printf("%20s %6d %-6d \n\n", values[0], pid, tid);
for (int i = 3; i < 8; ++i) {
printf("%12s ", fieldNames[i]);
printReadable(values[i - 2]);
}
printf("\n");
} else {
printf("%20s %6d %-6d 0x%-18s 0x%-18s 0x%-18s 0x%-18s 0x%-18s\n", values[0], pid,
tid, values[1], values[2], values[3], values[4], values[5]);
}
return 1;
}
int isPidFolder(const struct dirent *entry) {
const char *p;
for (p = entry->d_name; *p; p++) {
if (!isdigit(*p)) {
return 0;
}
}
return 1;
}
int printCaps(int pid) {
DIR *threadDir;
struct dirent *entry;
char dirName[50];
snprintf(dirName, sizeof(dirName), "/proc/%d/task", pid);
char error[100];
threadDir = opendir(dirName);
if (!threadDir) {
snprintf(error, sizeof(error), "Error with opening /proc/%d/task folder", pid);
perror(error);
return 1;
}
while ((entry = readdir(threadDir))) {
if (!isPidFolder(entry)) {
continue;
}
int tid = atoi(entry->d_name);
char capPath[50];
snprintf(capPath, sizeof(capPath), "/proc/%d/task/%d/status", tid, tid);
int fd;
if ((fd = open(capPath, O_RDONLY)) == -1) {
snprintf(error, sizeof(error), "Error with opening %s", capPath);
perror(error);
return 0;
}
int fileSize = 1500;
char *file = malloc(fileSize * sizeof(char));
if (file == NULL) {
printf("Error with malloc\n");
close(fd);
return 0;
}
int n = read(fd, file, fileSize);
if (n == -1) {
perror("Error while reading file");
}
processFile(file, pid, tid);
free(file);
close(fd);
}
return 1;
}
int main(int argc, char *argv[]) {
int pid = 0;
for (int optIdx = 1; optIdx < argc; ++optIdx) {
if (argv[optIdx][0] == '-') {
switch (argv[optIdx][1]) {
case 'p':
pid = atoi(argv[optIdx + 1]);
continue;
case 'r':
readable = 1;
continue;
case 'h':
default:
printf("Usage: %s [-p pid] [-r] \n", argv[0]);
return -1;
}
}
}
if (readable) {
printf("%20s %6s %-6s \n", fieldNames[0], fieldNames[1], fieldNames[2]);
} else {
printf("%20s %6s %-6s %-20s %-20s %-20s %-20s %-20s\n", fieldNames[0], fieldNames[1],
fieldNames[2], fieldNames[3], fieldNames[4], fieldNames[5], fieldNames[6], fieldNames[7]);
}
if (pid != 0) {
printCaps(pid);
return 0;
}
DIR *procDir;
struct dirent *entry;
procDir = opendir("/proc");
if (!procDir) {
perror("Error with opening /proc");
return 1;
}
while ((entry = readdir(procDir))) {
if (!isPidFolder(entry)) {
continue;
}
int pid = atoi(entry->d_name);
printCaps(pid);
}
closedir(procDir);
return 0;
}<file_sep>#include <unistd.h>
int main() {
if (fork() == 0) {
nice(-20);
execl("/bin/sleep", "sleep", "1000", NULL);
}
return 0;
}
<file_sep>cmake_minimum_required(VERSION 3.16)
project(Capabilities)
set(CMAKE_C_STANDARD 11)
add_executable(capshow capShow.c)
add_executable(capenv capEnviron.c)
add_executable(socket_test socketTest.c)
target_link_libraries(capshow cap)
target_link_libraries(capenv cap-ng)
<file_sep># capshow
Prints out info about capabilities
## Building
You need libcap-dev
```sh
$ sudo apt-get install libcap-dev
```
Then compile using gcc
```sh
$ gcc capShow.c -o capshow -lcap
```
## Usage
Show every capability of all threads
```sh
$ ./capshow
```
Show capabilities of particular process
```sh
$ ./capshow -p pid
```
Show readable version of capabilities
```sh
$ ./capshow -r
```
# capenv
An application locks itself, and all of its descendants, into an environment where the only way of gaining capabilities is by executing a program with associated file capabilities
## Building
You need libcap-ng-dev
```sh
$ sudo apt-get install libcap-ng-dev
```
Then compile using gcc
```sh
$ gcc capEnviron.c -o capenv -lcap-ng
```
## Usage
Run program with some capabilities
```sh
$ sudo ./capenv (capabilities_to_add ...) -p program_path program_args
```
Run programm without any capabilities
```sh
$ sudo ./capenv -p program_path program_args
```
## services
Services were used for testing ways of manipulating capabilities of a program
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <cap-ng.h>
#include <sys/prctl.h>
#include <linux/securebits.h>
#include <string.h>
#include <wait.h>
int createCapabilityEnvironment(const int *caps, int capsAmount) {
capng_get_caps_process();
capng_clear(CAPNG_SELECT_BOTH);
if (capng_update(CAPNG_ADD, CAPNG_EFFECTIVE |
CAPNG_PERMITTED |
CAPNG_BOUNDING_SET, CAP_SETPCAP) == -1) {
printf("Cannot add cap\n");
return -1;
}
for (int i = 0; i < capsAmount; ++i) {
int cap = caps[i];
if (capng_update(CAPNG_ADD, CAPNG_INHERITABLE |
CAPNG_PERMITTED |
CAPNG_BOUNDING_SET, cap) == -1) {
printf("Cannot add %s to caps\n", capng_capability_to_name(cap));
return -1;
}
}
int ret = capng_apply(CAPNG_SELECT_BOTH);
if (ret < 0) {
printf("capng_apply failed to apply caps with return value %d\n", ret);
return -1;
}
//printf("Inheritable: %s \n", capng_print_caps_text(CAPNG_PRINT_BUFFER, CAPNG_INHERITABLE));
//printf("Permitted: %s \n", capng_print_caps_text(CAPNG_PRINT_BUFFER, CAPNG_PERMITTED));
//printf("Effective: %s \n", capng_print_caps_text(CAPNG_PRINT_BUFFER, CAPNG_EFFECTIVE));
//printf("Bounding: %s \n", capng_print_caps_text(CAPNG_PRINT_BUFFER, CAPNG_BOUNDING_SET));
for (int i = 0; i < capsAmount; ++i) {
int cap = caps[i];
if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, cap, 0, 0) != 0) {
char error[50];
snprintf(error, sizeof(error), "Cannot set %s as ambient cap", capng_capability_to_name(cap));
perror(error);
return -1;
}
}
if (prctl(PR_SET_SECUREBITS,
SECBIT_KEEP_CAPS_LOCKED |
SECBIT_NO_SETUID_FIXUP |
SECBIT_NO_SETUID_FIXUP_LOCKED |
SECBIT_NOROOT |
SECBIT_NOROOT_LOCKED) != 0) {
perror("Cannot set secure bits");
return -1;
}
return 0;
}
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s [allowed capabilities] -p prog_path prog_args\n", argv[0]);
return 0;
}
int capsArgsBorder;
int i = 0;
while (memcmp("-p", argv[i], 2) != 0) {
++i;
}
capsArgsBorder = i;
int capsAmount = 0;
int caps[capsArgsBorder - 1];
for (i = 1; i < capsArgsBorder; ++i) {
int cap = capng_name_to_capability(argv[i]);
if (cap == -1) {
printf("No such capability: %s\n", argv[i]);
continue;
}
caps[capsAmount] = cap;
++capsAmount;
}
if (createCapabilityEnvironment(caps, capsAmount) == -1) {
return -1;
}
pid_t child;
if ((child = fork()) == 0) {
execvp(argv[capsArgsBorder + 1], &argv[capsArgsBorder + 1]);
perror("Error occurred when trying to execute a program");
return -1;
} else if (child == -1) {
perror("Error occurred when trying to fork a process");
return -1;
}
printf("Waiting for child with pid %d\n", child);
int status;
child = wait(&status);
if (child == -1) {
perror("Error occurred while waiting for child death");
return -1;
}
if (WIFEXITED(status)) {
printf("Exit status of child with pid %d: %d\n", child, WEXITSTATUS(status));
} else {
printf("Child %d exited incorrectly\n", child);
}
return 0;
}
| b984bc762e6b1b463f3fbf941a7c3bd2aa6009d4 | [
"Markdown",
"C",
"CMake"
] | 5 | C | borodun/linux-capabilities | a960e50397fa73949af0b4f08353399923d7e10e | c6f2329776e9f014b26ff66630fe03a3907cdf43 |
refs/heads/master | <repo_name>cloverstd/restc-next<file_sep>/src/components/Main.jsx
import React, { Component } from 'react';
import Result from './ResultView';
import SideBar from './SideBar';
import styled from 'styled-components'
const Container = styled.div`
position: relative;
flex: 1;
width: 100%;
min-height: 0;
&.sidebar-collapse {
> section {
width: 100%;
transition: none;
}
> aside {
transform: translateX(100%);
}
}
`
export default class Main extends Component {
constructor(props) {
super(props)
this.state = {}
}
onRequest(request, $response) {
this.result.update(request, $response)
}
toggle() {
this.setState(state => {
return {
collapse: state.collapse === 'sidebar-collapse' ? void 0 : 'sidebar-collapse'
}
})
}
render() {
return (
<Container className={this.state.collapse}>
<Result ref={r => this.result = r} />
<SideBar onRequest={(req, resp) => this.onRequest(req, resp)} />
</Container>
)
}
}
<file_sep>/Makefile
release:
npm run build
docs: release
mkdir -p docs docs/image docs/get docs/post
rm -rf docs/static
cp -r build/static docs/static
sed -i '' 's/"\/static/"\/restc-next\/static/g' build/index.html
cp build/index.html docs/image
cp build/index.html docs/get
cp build/index.html docs/post
<file_sep>/README.md
This project is rewrite with React for [restc](https://github.com/ElemeFE/restc).
<file_sep>/src/components/ResultView/index.jsx
import React, { Component } from 'react';
import styled from 'styled-components'
import Highlight from 'react-highlight.js'
import { ImageView, DownloadView } from './FileView'
const Section = styled.section`
left: 0;
width: 57%;
transition: width .01s .7s;
position: absolute;
top: 0;
bottom: 0;
`
const DL = styled.dl`
position: relative;
height: 100%;
box-sizing: border-box;
margin: 0;
display: flex;
flex-direction: column;
> dt {
position: relative;
border-bottom: 1px solid #e4e4ec;
padding: 0 ${props => props.padding}px;
margin: 0;
font-size: 0;
> a {
position: relative;
z-index: 1;
text-decoration: none;
display: inline-block;
box-sizing: border-box;
padding: .5em 1em;
font-size: 16px;
width: ${props => props.btnWidth}px;
text-align: center;
font-weight: 600;
color: #5d6576;
&:hover {
opacity: .8;
cursor: pointer;
}
}
> span {
transition: left 200ms ease, right 200ms ease;
position: absolute;
top: 0;
bottom: -1px;
font-size: 16px;
width: ${props => props.btnWidth}px;
border-bottom: 2px solid #2d2f3b;
background: #f1f1f6;
}
}
> dd {
flex: 1;
overflow: auto;
margin: 0;
}
&.loading:after {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
content: '';
background: rgba(248, 248, 250, 0.8) url('data:image/svg+xml;base<KEY>+') 50% 50% no-repeat;
cursor: progress;
z-index: 1000;
}
&.waiting:after {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
display: flex;
align-items: center;
justify-content: center;
content: 'Click “Send” to send the request';
font-weight: 500;
font-size: 1.2em;
background: rgba(248, 248, 250, 0.8);
z-index: 1000;
}
`
const Underline = styled.span`
left: ${props => props.underline}px;
`
const ResultWrapper = styled.div`
font-size: 12px;
line-height: 1.5;
margin-bottom: 0 8px;
& code {
padding: 20px 32px 0px;
background: transparent;
overflow: visible;
}
& a {
margin-left: 32px;
}
`
export default class Result extends Component {
constructor(props) {
super(props)
this.state = {
underline: this.padding + 0 * this.btnWidth,
$response: void 0,
target: 0,
loading: false
}
}
stringifyHeader([key, value]) {
key = key.replace(/(?:^|-)./g, $0 => $0.toUpperCase());
return [key, value].join(': ');
}
updateRequest({ method, path, queryString, body, headers }) {
let uri = path;
if (queryString) uri += '?' + queryString;
headers = Object.keys(headers)
.map(key => ({ key, value: headers[key] }))
.map(({ key, value }) => ({ key, values: Array.isArray(value) ? value : [value] }))
.reduce((result, { key, values }) => [...result, ...values.map(value => ({ key, value }))], []);
let request = [
[method, uri, 'HTTP/1.1'].join(' '),
...headers.map(({ key, value }) => [key, value].join(': '))
].join('\n');
if (!['HEAD', 'GET'].includes(method) && body) request = [request, body].join('\n\n');
this.setState({ request })
}
update(request, $response) {
this.updateRequest(request)
this.updateResponse($response)
}
updateResponse($response) {
this.setState({
response: void 0,
loading: true
})
this.click(0)
Promise.resolve($response).then(response => {
let status = ['HTTP/1.1', response.status, response.statusText].join(' ');
let headers = [...response.headers.entries()].map(this.stringifyHeader).join('\n');
let contentType = response.headers.get('Content-Type');
let json = /json/.test(contentType);
let javascript = /javascript/.test(contentType);
let binary = !(/text/.test(contentType) || json || javascript);
let image = /image/.test(contentType);
let contentDisposition = response.headers.get('Content-Disposition') || '';
try {
contentDisposition = window.ContentDispositionAttachment.parse(contentDisposition);
} catch (error) {
contentDisposition = { attachment: false };
}
let { attachment, filename } = contentDisposition;
let $body
if (binary || attachment || image) {
$body = response.blob().then(URL.createObjectURL).then(url => {
let key = image ? 'image' : 'file'
return {
[key]: { filename, url }
}
});
} else {
$body = response.text().then(result => {
let body = result;
if (json) {
try {
body = window.jsonFormatSafely(body);
} catch (e) { /* ignore */ }
}
return { body };
});
}
return $body.then(({ body, image, file }) => {
this.setState({
response: [status, headers, '', body].join('\n'),
image: image,
file: file
})
})
}).catch(({ message }) => {
this.setState({
response: message,
image: void 0,
file: void 0
})
}).then(() => {
this.setState({
loading: false
})
})
}
get padding() {
return 40
}
get btnWidth() {
return 120
}
click(i) {
if (i === this.state.target) {
return
}
this.setState(state => {
let target = state.target === 0 ? 1 : 0
return {
underline: this.padding + target * this.btnWidth,
target: target
}
})
}
render() {
return (
<Section>
<DL padding={this.padding} btnWidth={this.btnWidth} className={this.state.loading && 'loading'}>
<dt>
<Underline underline={this.state.underline} />
<a onClick={() => this.click(0)}>Response</a>
<a onClick={() => this.click(1)}>Request</a>
</dt>
<dd>
{this.state.target === 0 && (
<ResultWrapper>
<Highlight language={'http'}>
{this.state.response || ''}
</Highlight>
{this.state.image && <ImageView image={this.state.image} />}
{this.state.file && <DownloadView file={this.state.file} />}
</ResultWrapper>
)}
{this.state.target === 1 && (
<ResultWrapper>
<Highlight language={'http'}>
{this.state.request || ''}
</Highlight>
</ResultWrapper>
)}
</dd>
</DL>
</Section>
)
}
}
<file_sep>/src/components/SideBar/Body.jsx
import React, { Component } from 'react';
import styled from 'styled-components'
import { KeyValue } from './Input';
import CodeMirror from 'react-codemirror';
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/material.css'
import 'codemirror/mode/javascript/javascript'
const BodyWrapper = styled.div`
& > ul {
display: flex;
padding: 0;
margint: 0;
white-space: nowrap;
justify-content: space-between;
> li {
display: block;
text-align: center;
&:hover {
border-bottom: 2px solid #5d6577;
cursor: pointer;
}
}
> .active {
border-bottom: 2px solid #5d6577;
}
}
.CodeMirror {
margin-top: 1em;
padding: 1em;
height: 10em;
border-radius: 8px;
background: #3f4555;
font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace;
line-height: 1.5;
}
`
export default class Body extends Component {
constructor(props) {
super(props)
let index = this.props.index
if (index === void 0) {
index = 1
}
index = parseInt(index, 10)
let formData = []
if (index === 2) {
let params = new URLSearchParams(this.props.value)
for (let [key, value] of params.entries()) {
formData.push({ key, value, checked: true})
}
}
this.state = {
index,
body: this.props.value,
formData,
}
}
active(index) {
return index === this.state.index ? 'active' : void 0
}
get index() {
return this.state.index
}
set index(index) {
this.setState({ index })
}
setValue({ body, index }) {
if (index === void 0) {
index = this.state.index
}
this.setState({ index }, () => {
switch (index) {
case 0: case 1:
break
case 2:
let params = new URLSearchParams(body)
let data = []
for (let [key, value] of params.entries()) {
data.push({ key, value, checked: true})
}
this.form.setData(data)
break
case 3:
break
default: throw new Error('not support body type');
}
this.setState({
body
})
})
}
click(index) {
let body = this.state.body
if (index <= 1 && body && typeof body !== 'string') {
let counter = 0
for (let _ of body.keys()) {
counter++
}
if (counter === 0) {
body = ''
} else {
if (confirm('the body will be lost')) {
body = ''
} else {
return
}
}
}
this.setState({
index, body
})
}
onChange(data) {
let body
switch (this.state.index) {
case 0: case 1:
body = data; break
case 2:
body = new URLSearchParams()
data && data.filter(item => item.checked).map(item => body.append(item.key, item.value))
body = body.toString()
break
case 3:
body = new FormData()
data && data.filter(item => item.checked).map(item => body.append(item.key, item.value))
break
default: throw new Error('not support body type');
}
this.setState({ body }, () => {
this.props.onChange(body)
})
}
render() {
let body
switch (this.state.index) {
case 0: case 1:
let options = {
theme: 'material'
}
options.mode = this.state.index === 1 ? 'javascript' : void 0
body = (
<CodeMirror className="CodeMirror" value={this.state.body} onChange={(e) => this.onChange(e)} options={options} />
)
break;
case 2: case 3:
body = (
<KeyValue data={this.state.formData} addText="add form field" onChange={data => this.onChange(data)} ref={ref => this.form = ref}/>
)
break;
default: throw new Error('not support body type');
}
return (
<BodyWrapper>
<ul>
<li className={this.active(0)} onClick={() => this.click(0)}>Text</li>
<li className={this.active(1)} onClick={() => this.click(1)}>JSON</li>
<li className={this.active(2)} onClick={() => this.click(2)}>Form URL-Encoded</li>
{/* <li className={this.active(3)} onClick={() => this.click(3)}>Multipart</li> */}
</ul>
{body}
</BodyWrapper>
)
}
}
<file_sep>/src/App.js
import React, { Component } from 'react';
import Header from './components/Header';
import Main from './components/Main';
import styled, { createGlobalStyle } from 'styled-components'
const GlobalStyle = createGlobalStyle`
html {
height: 100%;
overflow: hidden;
}
body {
margin: 0;
height: 100%;
background: #fff;
color: #4c555a;
font-family: "Alright Sans LP", "Avenir Next", "Helvetica Neue", Helvetica, Arial, "PingFang SC", "Source Han Sans SC", "Hiragino Sans GB", "Microsoft YaHei", "WenQuanYi MicroHei", sans-serif;
font-size: 14px;
-webkit-font-smoothing: antialiased;
line-height: 26px;
}
pre, code {
font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace;
}
#root {
height: 100%;
}
`
const AppStyle = styled.div`
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
`
class App extends Component {
toggle() {
this.main.toggle()
}
render() {
return (
<AppStyle>
<GlobalStyle />
<Header onToggleClick={() => this.toggle()} />
<Main ref={ref => this.main = ref} />
</AppStyle>
);
}
}
export default App;
<file_sep>/src/components/SideBar/index.jsx
import React, { Component } from 'react';
import styled from 'styled-components'
import { Input, KeyValue } from './Input';
import Body from './Body'
const Aside = styled.aside`
left: 57%;
right: 0;
transition: transform .7s;
position: absolute;
top: 0;
bottom: 0;
`
const Form = styled.form`
padding: 40px;
box-sizing: border-box;
color: #fff;
background: #2d2f3b;
transition: transform 1s;
height: 100%;
box-sizing: border-box;
overflow: auto;
`
const H = styled.h3`
margin-left: -40px;
margin-right: -40px;
padding: 20px 40px;
border-bottom: 1px solid #373b48;
font-size: 17px;
font-weight: 600;
`
const MethodSection = styled.div`
margin: -.25em;
display: flex;
> * {
margin: .25em;
}
`
const Select = styled.select`
padding: 0 1.5em 0 1em;
color: #dbdfeb;
background: #3f4555;
font: inherit;
width: 100px;
height: 40px;
border: 0 none;
border-radius: 8px;
outline: none;
-webkit-appearance: none;
-moz-appearance: none;
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAqdJREFUeNpi/P//P8NAAiaGAQajDhh1wKgDGEDlADqGAnYgNoLS5AI2IDaEmYHVLhwOYFVT1/HOLqzdoaKm<KEY>CwemBiAyU4kNENhCynKBfgiY4MUAwAg30qsTUvUQ4YbRGNOmDUAaMOoCcACDAAFHYu4lUVtcQAAAAASUVORK5CYII=');
background-position: 90% 50%;
background-repeat: no-repeat;
background-size: 16px;
cursor: pointer;
&:hover {
color: #fff;
}
`
const QueryString = styled(Input)`
flex: 1;
&:before {
margin-right: .2em;
content: '?';
color: #5d6577;
}
`
const SendButton = styled.button`
padding: 0 1em;
height: 40px;
color: #dbdfeb;
background: transparent;
font: inherit;
border: 2px solid #959cad;
border-radius: 4px;
outline: none;
cursor: pointer;
transition: .15s background;
`
export default class SideBar extends Component {
constructor(props) {
super(props)
this.state = {
...this.parseParams()
}
this.handleSubmit = this.handleSubmit.bind(this)
}
handleSubmit(e) {
e.preventDefault()
let { method, queryString, body, headers } = this.state
let path = window.requestInfo.path
if (!method) {
method = 'GET'
}
let host = window.requestInfo.host
let uri = `//${host}${path}`
if (queryString) uri += '?' + queryString
if (method === 'GET' || method === 'HEAD' || !method) {
body = void 0
}
let $response = new Promise((resolve, reject) => {
let defaultHeaders = new Headers({
Accept: 'application/json, */*',
'Content-Type': 'application/json',
})
headers && headers.map(header => defaultHeaders.append(encodeURIComponent(header.key), header.value))
if (method !== 'GET' && method !== 'HEAD') {
switch (this.body.index) {
case 0:
defaultHeaders.set('Content-Type', 'text/plain')
break
case 1:
defaultHeaders.set('Content-Type', 'application/json')
if (body) {
if (typeof body !== 'string') {
return reject(new Error('body not a valid JSON object'))
}
try {
JSON.parse(body)
} catch (e) {
return reject(e)
}
}
break
case 2:
defaultHeaders.set('Content-Type', 'application/x-www-form-urlencoded')
break
case 3:
// defaultHeaders.set('Content-Type', 'multipart/form-data')
break
case 4:
defaultHeaders.set('Content-Type', 'application/octet-stream')
break
default: throw new Error('not support body type');
}
}
headers = defaultHeaders
let options = { method, headers, credentials: 'include', body }
resolve(fetch(uri, options))
this.encodeHash()
})
// let $response = fetch(uri, options)
this.props.onRequest && this.props.onRequest({ method, path, queryString, body, headers }, $response)
// sync title
document.title = [method, uri].join(' ');
}
onChange(key, value) {
this.setState({
[key]: value
}, () => {
if (key === 'query') {
this.encodeQueryString(value)
}
})
}
parseParams() {
let params = new URLSearchParams(location.hash.slice(2))
let query = []
let body = params.get('body') || ''
let method = params.get('method') || 'GET'
let bodyType = params.get('bodyType') || 1
let headers
try {
query = JSON.parse(params.get('query'))
} catch (e) { }
try {
headers = JSON.parse(params.get('headers'))
} catch (e) { }
return { method, query, body, headers, bodyType }
}
componentDidMount() {
addEventListener('hashchange', () => {
let { method, query, body, headers, bodyType } = this.parseParams()
this.setState({ method, query, body, headers }, () => {
this.headerKeyValue.setData(headers)
this.queryKeyValue.setData(query)
this.body.setValue({ body, index: parseInt(bodyType, 10)})
this.encodeQueryString(this.state.query)
})
})
}
encodeQueryString(value) {
if (!value) {
return
}
let query = new URLSearchParams();
value.filter(item => item.checked).map(item => query.append(item.key, item.value))
let queryString = query.toString()
this.setState({
queryString
}, () => {
this.queryStringInput.setValue(queryString)
})
}
onMethodChange(e) {
this.setState({
method: e.target.value
}, () => {
if (this.state.method === 'GET' || !this.state.method) {
this.setState({
body: void 0
})
}
})
}
onQueryStringChange(v) {
let query = [];
for (let [key, value] of new URLSearchParams(v)) {
query.push({
checked: true,
key, value
})
}
this.setState({
query
}, () => {
this.queryKeyValue.setData(this.state.query)
})
}
onQueryChange(query) {
this.setState({
query
}, () => {
this.encodeQueryString(this.state.query)
})
}
onBodyChange(body) {
this.setState({ body }, () => {
this.body.setValue({ body })
})
}
onHeaderChange(headers) {
this.setState({ headers })
}
encodeHash() {
let query = this.state.query ? JSON.stringify(this.state.query) : '[]'
let body = this.state.body || ''
let method = this.state.method || 'GET'
let headers = this.state.headers ? JSON.stringify(this.state.headers) : '[]'
let bodyType = this.body.index || 0
let params = new URLSearchParams({ method, query, body, headers, bodyType })
location.hash = '#!' + params.toString()
}
render() {
let body
if (this.state.method !== 'GET' && this.state.method) {
body = (
<div>
<H>Body</H>
<Body value={this.state.body} index={this.state.bodyType} ref={ref => this.body = ref} onChange={v => this.onBodyChange(v)}/>
</div>
)
}
return (
<Aside>
<Form onSubmit={this.handleSubmit}>
<MethodSection>
<Select onChange={e => this.onMethodChange(e)} value={this.state.method}>
<option>GET</option>
<option>POST</option>
<option>PUT</option>
<option>PATCH</option>
<option>DELETE</option>
</Select>
<QueryString ref={input => this.queryStringInput = input} value={this.state.queryString} onChange={v => this.onQueryStringChange(v)} />
<SendButton>Send</SendButton>
</MethodSection>
<H>Query Parameters</H>
<KeyValue addText={'add query parameter'} ref={keyValue => this.queryKeyValue = keyValue} onChange={v => this.onQueryChange(v)} defaultValue={this.state.query && this.state.query.length > 0 && this.state.query[0]} />
{body}
<H>Headers</H>
<KeyValue addText={'add header'} ref={ref => this.headerKeyValue = ref} onChange={v => this.onHeaderChange(v)} />
</Form>
</Aside>
)
}
}
<file_sep>/src/components/ResultView/HightlightBlock.jsx
import React, { Component } from 'react';
import styled from 'styled-components';
import Highlight from 'react-highlight.js'
const Pre = styled.pre`
font-size: 12px;
line-height: 1.5;
& > code {
margin: 0 8px;
padding: 20px 32px;
background: transparent;
overflow: visible;
}
`
export default class HighlightBlock extends Component {
constructor(props) {
super(props)
this.state = {
content: this.props.content
}
}
setValue(content) {
this.setState({ content })
}
render() {
return (
<Pre>
<Highlight language={'http'}>
{this.state.content || ''}
</Highlight>
</Pre>
)
}
}
| e2358c425bb6fc7922649cfbfb40f45260a5536d | [
"JavaScript",
"Makefile",
"Markdown"
] | 8 | JavaScript | cloverstd/restc-next | 9286bc4f4881843d5155b34ebc73c84e0c31647d | 8d8b9c14b51a9687cc813064024f8fb433e2bd8b |
refs/heads/main | <file_sep>import random
carac = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789*#<@.>_'
compr = 8
print("gerador de senhas")
print("senhas geradas:")
for i in range (compr):
senha = "".join(random.sample(carac, compr))
print(senha)<file_sep># Gerador_de_Senhas
Projeto: Gerador de Senhas
Este programa serve para usuários que querem senhas fortes, dificeis de serem quebradas, para usar em seus sites e redes sociais, com mais segurança.
O programa irá criar oito senhas aleatórias com oito dígitos cada, toda vez que for rodado. Nelas irá conter números de 0 a 9, sinais de pontuação e letras de A a Z maiúscula e minúsculas.
Sua estrutura: Foi necessário a importação da biblioteca random para gerar números pseudoaleatórios, depois houve a criação das variáveis carac e compr e definiu-se os itens contidos nela.
O uso da estrutura de repetição for i in range, para que a repetição sequencial da senha esteja de acordo com o número de vezes que foi informado.
No final do código a variável "senha" é definida. E houve também a utilização de .join que serve para unir as variáveis carac e compr, e random.sample para que retorne dessas variáveis uma lista de certo tamanho contendo itens escolhidos da sequência.
Então quando roda o código, é impresso oito senhas com oito caracteres cada. As senhas são sempre diferente todas as vezes que o programa é rodado.
| 2a47b16f98302c9b2601172998a566b4cc8bd36d | [
"Markdown",
"Python"
] | 2 | Python | vivianemsilva/Gerador_de_Senhas | 924538b112f56aa7333e8c9a75a6bc00b7c66223 | 3a9919535195864913acefc90e692b0b4fb3fbec |
refs/heads/master | <repo_name>PowerClaw/PowerClaw_SDK_Java<file_sep>/README.md
# PowerClaw_SDK_Java
PowerClaw SDK Java
<file_sep>/PowerClawSDK.java
/**
* Copyright © VIVOXIE S DE RL DE CV
*
* @author <NAME><<EMAIL>>
* @version 1.0
*/
package com.vivoxie.powerclaw.sdk;
import com.fazecast.jSerialComm.SerialPort;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
/*import com.fazecast.jSerialComm.SerialPortDataListener;
import com.fazecast.jSerialComm.SerialPortEvent;
import com.fazecast.jSerialComm.SerialPortPacketListener;
import java.io.InputStream;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;*/
public class PowerClawSDK /*implements Runnable*/ {
/**
* Instance to PowerClaw
*/
private SerialPort _serialPort = null;
/**
* Sensation to stop
*/
private static String _stop = null;
/**
* Determine if serial port is closed or open
*/
private static boolean _open = false;
/**
* Runtime sensation
*/
private static int _timeStop;
/**
* Return list of the available serial ports
*
* @return string
*/
public SerialPort[] serialPortsGet()
{
SerialPort[] ports = SerialPort.getCommPorts();
return ports;
}
/**
* Return available PowerClaw
*
* @param name
* @return SerialPort
*/
public SerialPort serialPortGet(String name)
{
if(name.equals("")) {
name = this.defaultSerialPortGet();
}
/*SerialPort ports = null;
for (SerialPort port : SerialPort.getCommPorts()) {
if(port.getSystemPortName().equals(name)) {
return port;
}
continue;
}
return ports;*/
SerialPort port = SerialPort.getCommPort(name);
return port;
}
/**
* Return default serial port name by OS
*
* @return String
*/
public String defaultSerialPortGet()
{
if(System.getProperty("os.name").toLowerCase().contains("linux")) {
return "/dev/ttyUSB0";
} else if(System.getProperty("os.name").toLowerCase().contains("windows")) {
try {
Process cmd = Runtime.getRuntime().exec("cmd /c REG QUERY HKEY_LOCAL_MACHINE\\HARDWARE\\DEVICEMAP\\SERIALCOMM");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(cmd.getInputStream()));
String comm = null;
if( (comm = stdInput.readLine()) == null) {
return "COM1";
}
while ((comm = stdInput.readLine()) != null){
if (comm.contains(" COM")) {
comm = comm.replaceAll(" ", " ");
String[] spl = comm.split(" ");
return spl[6];
}
}
} catch (IOException ioe) {
return "COM1";
}
return "COM1";
} else if(System.getProperty("os.name").toLowerCase().contains("mac")) {
return "/dev/tty.usbserial";
}
return "COM1";
}
/**
* Create instance to PowerClaw
*
* @param serial
* @param baud
* @throws com.vivoxie.powerclaw.sdk.CommException
*/
public void serialPortSet(SerialPort serial, int baud) throws CommException
{
if(baud == 0){
baud = 115200;
}
if(serial == null) {
throw new CommException("PowerClaw is null");
}
this._serialPort = serial;
this._serialPort.setBaudRate(baud);
}
/**
* Create instance to PowerClaw
*
* @throws com.vivoxie.powerclaw.sdk.CommException
*/
public void serialPortSet() throws CommException
{
SerialPort serial = this.serialPortGet(this.defaultSerialPortGet());
if(serial == null) {
throw new CommException("PowerClaw no exist");
}
this._serialPort = serial;
this._serialPort.setBaudRate(115200);
}
/**
* Open communication with PowerClaw
*
* @return boolean
* @throws CommException
*/
public boolean serialPortOpen() throws CommException
{
if(this._serialPort == null) {
try {
this.serialPortSet();
} catch(Exception e) {
throw new CommException("Unable connect to PowerClaw");
}
}
if(PowerClawSDK._open) {
return true;
}
this._serialPort.openPort();
PowerClawSDK._open = true;
return true;
}
/**
* Send sensation to PowerClaw
*
* @param sensation
* @throws java.lang.InterruptedException
*/
private boolean sensationSend(String sensation) throws InterruptedException, CommException {
String list = "";
int intensity, phalange;
String[] split = sensation.split(",");
if(!PowerClawSDK._open) {
throw new CommException("Connection to PowerClaw is closed");
}
switch (split[0]) {
case "right":
list += "r";
break;
case "left":
list += "l";
break;
case "hands":
list += "h";
break;
case "zero":
list += "z";
break;
default:
throw new CommException("Hand <" + split[0] + "> not found");
}
switch (split[1]) {
case "thumb":
list += "t";
break;
case "index":
list += "i";
break;
case "middle":
list += "m";
break;
case "ring":
list += "r";
break;
case "pinkie":
list += "p";
break;
case "zero":
list += "z";
break;
case "hand":
list += "h";
break;
default:
throw new CommException("Finger <" + split[1] + "> not found");
}
try{
phalange = Integer.parseInt(split[2]);
} catch(Exception e) {
throw new CommException("Phalanx <" + split[2] + "> not int");
}
list += split[2];
switch (split[3]) {
case "vibration":
list += "v";
break;
case "roughness":
list += "r";
break;
case "contact":
list += "c";
break;
case "heat":
list += "h";
break;
case "cold":
list += "o";
break;
case "zero":
list += "z";
break;
default:
throw new CommException("Sensation <" + split[3] + "> not found");
}
try{
intensity = Integer.parseInt(split[4]);
} catch(Exception e) {
throw new CommException("Intensity <" + split[3] + "> not int");
}
if (intensity < 0) {
split[4] = "000";
} else if (intensity > 100) {
split[4] = "100";
} else if (intensity < 10) {
split[4] = "00" + split[4];
} else if (intensity < 100) {
split[4] = "0" + split[4];
}
list += split[4];
list = "." + list;
this._serialPort.writeBytes(list.getBytes(), list.length());
return true;
}
/**
* Send sensation to Power Claw with runtime
*
* @param sensation
* @param time
* @return String
* @throws java.lang.InterruptedException
* @throws com.vivoxie.powerclaw.sdk.CommException
*/
@SuppressWarnings("static-access")
public boolean sensationSend(String sensation, int time) throws InterruptedException, CommException
{
String[] split = sensation.split(",");
if(!"zero".equals(split[0]) || !"zero".equals(split[1]) || !"zero".equals(split[3])) {
this._timeStop = time;
this._stop = split[0] + "," + split[1] + "," + split[2] + "," + split[3] + ",000";
} else {
this._stop = null;
this._timeStop = -1;
}
return this.sensationSend(sensation);
}
/**
* Close communication with serial port
*
* @return boolean
*/
public boolean serialPortClose()
{
if(!PowerClawSDK._open) {
return true;
}
this._serialPort.closePort();
PowerClawSDK._open = false;
return true;
}
/**
* Thread stop
*
*
@Override
public void run() {
if(PowerClawSDK._timeStop == -1){
return;
}
try {
Thread.sleep(PowerClawSDK._timeStop);
this.sensationSend(PowerClawSDK._stop);
} catch (InterruptedException | CommException ex) {
Logger.getLogger(PowerClawSDK.class.getName()).log(Level.SEVERE, null, ex);
}
return;
}*/
/**
* Standalone
*
* @param args
*
static public void main(String[] args)
{
Comm comm = new Comm();
SerialPort ports[];
ports = comm.serialPortsGet();
//ports = comm.serialPortGet("ttyUSB7");
//System.out.println(ports.getSystemPortName());
for (int i = 0; i < ports.length; ++i) {
System.out.println("[" + i + "] " + ports[i].getSystemPortName() + ": " + ports[i].getDescriptivePortName());
}
System.out.print("\nChoose your second desired serial port, or enter -1 to skip this test: ");
try {
comm.serialPortSet(ports[(new Scanner(System.in)).nextInt()], 115200);
comm.serialPortOpen();
//comm.sensationSend("right,ring,0,heat,100", 1000);
} catch (Exception e) {
System.out.println("error");
}
try {
comm.sensationSend("right,hand,0,vibration,95", 2000);
} catch (InterruptedException ex) {
Logger.getLogger(Comm.class.getName()).log(Level.SEVERE, null, ex);
}
try {
comm.sensationSend("left,hand,0,vibration,95", 3000);
} catch (InterruptedException ex) {
Logger.getLogger(Comm.class.getName()).log(Level.SEVERE, null, ex);
}
}*/
} | 3783f750664111db585a11ddfc5d6f7d7b41b5a1 | [
"Markdown",
"Java"
] | 2 | Markdown | PowerClaw/PowerClaw_SDK_Java | df6c45e68d6b007103fe5afbe8903008c95365e4 | 494afcfcd5d2c1ed0b380f1984ee70f82e263d53 |
refs/heads/master | <repo_name>Jakelee24/Sentiment-Analysis-tensorflow<file_sep>/LSTM_module.py
import tensorflow as tf
import pickle
from tensorflow.nn import rnn_cell
from tensorflow.contrib.rnn.python.ops import rnn
from tensorflow.python.platform import gfile
import numpy as np
import os
from Helper import Helper
class DataFeeder:
# This class is made to hold the data that should be input into the system for processing
# init function converts stored numpy arrays into an in-memory thing that can be
# passed in batches to the model
def __init__(self, trainpath=None, testpath=None, batch_size=None):
# this init function takes the stored numpy arrays of word indices and converts
# them into a suitable format for passing to the model
# lists with data/labels
self.train_data = []
self.test_data = []
# indexes for the data, needed for fetching a training batch
self.train_data_index = 0
self.test_data_index = 0
# first load the filepaths and labels into memory
# li_train and li_test are lists of tuples
# li_train[i][0] is the path to the i^th data example
# actual file stored at this location is a numpy array
# li_train[i][1] is the label associated with that example
# to do - pass this as an arg?
if trainpath is None and testpath is None:
li_train, li_test = Helper.get_stuff("li_train.pickle", "li_test.pickle")
# now store the test/train data in the right arrays
self._init_data(li_train, test=False)
np.random.shuffle(self.train_data)
self._init_data(li_test, test=True)
np.random.shuffle(self.test_data)
if batch_size is not None:
self.batch_size = batch_size
else:
self.batch_size = 200
# arrays loaded with the right data - all done.
def get_batch(self, test=False):
# returns a batch of the training/test data, as requested
# batch is of size self.batch_size
# also returns the sequence length - how long is the review?
# (in terms of num of words)
# This is now done at batch fetch time. Ideally this is done
# as part of the tensorflow computation graph, but using
# zero padding is proving challenging...
data_batch = []
label_batch = []
seq_length = []
temp_index = 0
if test:
li = self.test_data
temp_index = self.test_data_index % len(self.test_data)
self.test_data_index = (self.test_data_index +self.batch_size) % len(self.test_data)
else:
li = self.train_data
temp_index = self.train_data_index % len(self.train_data)
self.train_data_index = (self.train_data_index + self.batch_size) % len(self.train_data)
for _ in range(self.batch_size):
np_data = li[temp_index][0]
# look for zero elements - these are PADDING elements!
# these are used to determine the length of the review.
# TODO find out what's happening with this- something bizarre is going on
# and makes indices 2D even when np_data is a single dimension?
# Hack below with swallowing exception works, but is not a permanent fix
# Solved - this should really be if len(indices.shape) > 1.
# Haven't tested this fully, so remains a todo.
indices = np.where(np_data == 0)
if len(indices) > 0:
try:
seq_len = indices[0][0]
except IndexError:
seq_len = len(np_data)
else:
seq_len = len(np_data)
# we've found how many elements are zero - append this to the return seq_length
seq_length.append(seq_len)
data_batch.append(np_data)
label_batch.append(li[temp_index][1])
if test:
temp_index = ((temp_index + 1) % len(self.test_data))
else:
temp_index = ((temp_index + 1) % len(self.train_data))
return data_batch, label_batch, seq_length
def _init_data(self, li, test=False):
temp = []
count = 0
for elem in li:
data = np.load(elem[0])[0]
if elem[1] == 1:
# positive example
label = np.array([1, 0])
else:
# negative example
label = np.array([0, 1])
# data contains the word indices as a np array
# label contains the associated class label as a np array
item = (data, label)
temp.append(item)
if test:
self.test_data.extend(temp)
else:
self.train_data.extend(temp)
del temp
class LSTM:
def __init__(self, batch_size, basedir, steps_per_checkpoint):
self.__batch_size = batch_size
self.__feeder = DataFeeder(batch_size=batch_size)
self.__steps_per_checkpoint = steps_per_checkpoint
def __unpack_sequence(self, tensor):
return tf.unstack(tf.transpose(tensor, perm=[1, 0, 2]))
def build_model(self,max_length, vocabulary_size, embedding_size,
num_hidden, num_layers,num_classes, learn_rate):
self.__graph = tf.Graph()
with self.__graph.as_default():
# to track progress
self.__global_step = tf.Variable(0, trainable=False)
# input parameters
self.__dropout = tf.placeholder(tf.float32)
self.__data = tf.placeholder(tf.int32, shape=[self.__batch_size, max_length], name="data")
self.__labels = tf.placeholder(tf.float32, shape=[self.__batch_size, num_classes], name="labels")
self.__seq_length = tf.placeholder(tf.int32, shape=[self.__batch_size], name="seqlength")
# LSTM definition
network = rnn_cell.LSTMCell(num_hidden, embedding_size)
network = rnn_cell.DropoutWrapper(network, output_keep_prob=self.__dropout)
network = rnn_cell.MultiRNNCell([network] * num_layers)
# loaded value from word2vec
self.__embeddings_lstm = tf.Variable(tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0),
name="embeddings_lstm")
# get the word vectors learned previously
embed = tf.nn.embedding_lookup(self.__embeddings_lstm, self.__data)
#try:
outputs, states = tf.contrib.rnn.static_rnn(network, self.__unpack_sequence(embed), dtype=tf.float32, sequence_length=self.__seq_length)
#except AttributeError:
#outputs, states = rnn(network, unpack_sequence(embed), dtype=tf.float32, sequence_length=seq_length)
# Compute an average of all the outputs
# FOR VARIABLE SEQUENCE LENGTHS
# place the entire sequence into one big tensor using tf_pack.
packed_op = tf.stack(outputs)
# reduce sum the 0th dimension, which is the number of timesteps.
summed_op = tf.reduce_sum(packed_op, reduction_indices=0)
# Then, divide by the seq_length input - this is an np array of size
# batch_size that stores the length of each sequence.
# With any luck, this gives the output results.
averaged_op = tf.div(summed_op, tf.cast(self.__seq_length, tf.float32))
# output classifier
# TODO perhaps put this within a context manager
softmax_weight = tf.Variable(tf.truncated_normal([num_hidden, num_classes], stddev=0.1))
softmax_bias = tf.Variable(tf.constant(0.1, shape=[num_classes]))
temp = tf.matmul(averaged_op, softmax_weight) + softmax_bias
prediction = tf.nn.softmax(temp)
predict_output = tf.argmax(prediction, 1)
tf.summary.histogram("prediction", prediction)
self.__prin = tf.Print(prediction, [prediction], message="pred is ")
# standard cross entropy loss
self.__loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=temp, labels=self.__labels))
tf.summary.scalar("loss-xentropy", self.__loss)
self.__optimizer = tf.train.AdamOptimizer(learn_rate).minimize(self.__loss, global_step=self.__global_step)
# examine performance
with tf.variable_scope("accuracy"):
correct_predictions = tf.equal(tf.argmax(prediction, 1),tf.argmax(self.__labels, 1))
self.__accuracy = tf.reduce_mean(tf.cast(correct_predictions, tf.float32), name="accuracy")
tf.summary.scalar("accuracy", self.__accuracy)
self.__merged = tf.summary.merge_all()
self.__train_writer = tf.summary.FileWriter(os.getcwd() + '/train', self.__graph)
self.__test_writer = tf.summary.FileWriter(os.getcwd() + '/test')
def train(self, old_ckpt_path, ckpt_path, num_train_steps):
with tf.Session(graph=self.__graph) as session:
# this is ugly - only for the embeddings, which were trained before.
# TODO make this nicer!
ckpt1 = tf.train.get_checkpoint_state(old_ckpt_path)
ckpt2 = tf.train.get_checkpoint_state(ckpt_path)
saver_lstm_embed = tf.train.Saver({"embeddings": self.__embeddings_lstm})
saver = tf.train.Saver(tf.all_variables())
started_before = False
if ckpt2 and gfile.Exists(ckpt2.model_checkpoint_path):
print("Reading model parameters from {0}".format(ckpt2.model_checkpoint_path))
saver.restore(session, ckpt2.model_checkpoint_path)
print("done")
started_before = True
else:
print("Creating model with fresh parameters.")
tf.initialize_all_variables().run()
print('Initialized')
if ckpt1 and gfile.Exists(ckpt1.model_checkpoint_path) and not started_before:
print("Reading embeddings from {0}".format(ckpt1.model_checkpoint_path))
embed_path = os.path.join(old_ckpt_path, "embeddings")
saver_lstm_embed.restore(session, embed_path)
print("done")
average_loss = 0
average_acc = 0
for step in range(num_train_steps):
batch_data, batch_labels, seq_len = self.__feeder.get_batch(test=False)
feed_dict = {self.__data: batch_data, self.__labels: batch_labels, self.__dropout: 0.5,
self.__seq_length: seq_len}
_, l, acc, summ = session.run([self.__optimizer, self.__loss, self.__accuracy, self.__merged], feed_dict=feed_dict)
average_loss += l
average_acc += acc
if step % self.__steps_per_checkpoint == 0:
# save stuff
checkpoint_path = os.path.join(ckpt_path, "lstm_checkpoints")
saver.save(session, checkpoint_path, global_step=self.__global_step)
self.__train_writer.add_summary(summ,step)
if step % 200 == 0:
if step > 0:
average_loss = average_loss / 200
average_acc = average_acc / 200
# The average loss is an estimate of the loss over the last 2000 batches.
print('Average loss at step %d: %f' % (step, average_loss))
print('Average accuracy at step %d: %f' % (step, average_acc))
average_loss = 0
average_acc = 0
num_test_steps = int(len(self.__feeder.test_data) / self.__batch_size)
test_loss = 0
test_accuracy = 0
for _ in range(num_test_steps):
batch_data, batch_labels, seq_len = self.__feeder.get_batch(test=True)
feed_dict = {self.__data: batch_data, self.__labels: batch_labels, self.__dropout: 1,
self.__seq_length: seq_len}
l, acc = session.run([self.__loss, self.__accuracy], feed_dict=feed_dict)
test_accuracy += acc
test_loss += l
print('Test acc is %f' % (test_accuracy/num_test_steps))
print('Test loss is %f' % (test_loss / num_test_steps))
# Module usage example
if __name__ == '__main__':
# step 1: init the LSTM module
batch_size = 200
basedir = os.getcwd()
steps_per_checkpoint = 100
lstm = LSTM(batch_size, basedir, steps_per_checkpoint)
# step 2: build LSTM model
max_length = 120
vocabulary_size = 65466
embedding_size = 128
num_hidden = 200
num_layers = 1
num_classes = 2
learning_rate = 0.005
lstm.build_model(max_length, vocabulary_size, embedding_size,
num_hidden, num_layers, num_classes, learning_rate)
# step 3: start traning
old_ckpt_path = os.path.join(basedir, "checkpoints", "embeddings")
ckpt_path = os.path.join(basedir, 'lstm_checkpoints')
if not os.path.exists(ckpt_path):
os.makedirs(ckpt_path)
num_steps =1001
lstm.train(old_ckpt_path, ckpt_path, num_steps)<file_sep>/word2vec_module.py
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import math
import urllib
import urllib.request
import tarfile
import os
import random
import string
import pickle
from Helper import Helper
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.python.platform import gfile
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
# training_data_pth = "JakeDrive/training-data-large.txt"
# for small is 124
# for large is 65466
# vocabulary_size = 65466
class Data_Processer:
def __init__(self, training_data, vocabulary_size):
basedir = os.getcwd()
self.__training_data_pth = training_data
self.__vocabulary_size = vocabulary_size
# Take all the reviews associated with the training set
# both pos and neg reviews
# for each of these files
# open it and read the contents into another file "all_data.txt"
self.__target = os.path.join(basedir, 'all_data.txt')
self.__CreateWordsFile()
def __CreateWordsFile(self):
with open(os.path.join(self.__target), "w") as fo:
training_set = self.__training_data_pth
train_df = pd.read_csv(training_set, sep= '\t', names=["Label", "Text"])
train_text = train_df["Text"]
for i in range(len(train_text)):
fo.write(train_text[i])
fo.write('\n')
def __get_words_text(self,basedir):
data_set = "all_data.txt"
data_df = pd.read_csv(data_set,sep='\t', names=["Text"])
data = data_df["Text"]
li = list()
for i in range(len(data)):
temp = data[i].split(',')
for j in range(len(temp)):
li.append(temp[j])
return li
def build_dataset(self, basedir):
words = self.__get_words_text(basedir)
count = [['UNK', -1]]
count.extend(collections.Counter(words).most_common(self.__vocabulary_size))
dictionary = dict()
dictionary["<PAD>"] = len(dictionary)
for word, _ in count:
# dictionary contains words as keys, values are the occurrence rank
# ie most common word has value 1
# second value two
# etc
dictionary[word] = len(dictionary)
data = list()
unk_count = 0
for word in words:
if word in dictionary:
index = dictionary[word]
else:
index = 0
unk_count = unk_count + 1
# the index of the word (unique token) is equal to its occurrence rank
# data contains all the words' unique tokens in order, as they appear
# in the text file with all the reviews
data.append(index)
count[0][1] = unk_count
# reverse dict enables us to go from token for word (occurrence rank)
# to the actual word
reverse_dictionary = dict(zip(dictionary.values(), dictionary.keys()))
del words
return data, count, dictionary, reverse_dictionary
def generate_batch(self, data, batch_size, num_skips, skip_window):
assert batch_size % num_skips == 0
assert num_skips <= 2 * skip_window
data_index = 0
batch = np.ndarray(shape=batch_size, dtype=np.int32)
labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)
span = 2 * skip_window + 1 # [ skip_window target skip_window ]
buffer = collections.deque(maxlen=span)
for _ in range(span):
buffer.append(data[data_index])
data_index = (data_index + 1) % len(data)
for i in range(batch_size // num_skips):
target = skip_window # target label at the center of the buffer
targets_to_avoid = [skip_window]
for j in range(num_skips):
while target in targets_to_avoid:
target = random.randint(0, span - 1)
targets_to_avoid.append(target)
batch[i * num_skips + j] = buffer[skip_window]
labels[i * num_skips + j, 0] = buffer[target]
buffer.append(data[data_index])
data_index = (data_index + 1) % len(data)
return batch, labels
def batch_tester(self, data, reverse_dictionary):
print('data:', [reverse_dictionary[di] for di in data[:8]])
for num_skips, skip_window in [(2, 1), (4, 2)]:
batch, labels = self.generate_batch(data, batch_size=8, num_skips=num_skips, skip_window=skip_window)
print('\nwith num_skips = %d and skip_window = %d:' % (num_skips, skip_window))
print(' batch:', [reverse_dictionary[bi] for bi in batch])
print(' labels:', [reverse_dictionary[li] for li in labels.reshape(8)])
def plot_with_labels(self, low_dim_embs, labels, filename='tsne.png'):
assert low_dim_embs.shape[0] >= len(labels), "More labels than embeddings"
plt.figure(figsize=(18, 18)) # in inches
for i, label in enumerate(labels):
x, y = low_dim_embs[i, :]
x = round(x,4)
y = round(y,4)
plt.scatter(x, y)
plt.annotate(str(label),
xy=(x, y),
xytext=(5, 2),
textcoords='offset points',
ha='right',
va='bottom')
plt.savefig(filename)
class Word2Vec:
def __init__(self, batch_size, num_skips, skip_window, embedding_size, vocabulary_size ,ckpt_path):
self.__batch_size = batch_size
self.__embedding_size = embedding_size
self.__vocabulary_size = vocabulary_size
self.__num_skips = num_skips
self.__skip_window = skip_window
self.__ckpt_path = ckpt_path
self.__graph = None
self.__loss = None
self.__optimizer = None
self.__similarity = None
self.__valid_size = None
self.__valid_window = None
self.__normalized_embeddings = None
def create_plt(self, reverse_dictionary):
final_embeddings = self.__normalized_embeddings.eval()
tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000)
#plot_only = 500
plot_only = 100
low_dim_embs = tsne.fit_transform(final_embeddings[1:plot_only+1, :])
labels = [reverse_dictionary[i] for i in range(plot_only)]
data_preprocess.plot_with_labels(low_dim_embs, labels)
# from here, need to take the embedding parameters and then pass them to the next stage of the
# system - the sentiment analyser
# ie , save final_embeddings. This has been done in the actual operation.
def __generate_batch(self, data, batch_size, num_skips, skip_window):
assert batch_size % num_skips == 0
assert num_skips <= 2 * skip_window
data_index = 0
batch = np.ndarray(shape=batch_size, dtype=np.int32)
labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)
span = 2 * skip_window + 1 # [ skip_window target skip_window ]
buffer = collections.deque(maxlen=span)
for _ in range(span):
buffer.append(data[data_index])
data_index = (data_index + 1) % len(data)
for i in range(batch_size // num_skips):
target = skip_window # target label at the center of the buffer
targets_to_avoid = [skip_window]
for j in range(num_skips):
while target in targets_to_avoid:
target = random.randint(0, span - 1)
targets_to_avoid.append(target)
batch[i * num_skips + j] = buffer[skip_window]
labels[i * num_skips + j, 0] = buffer[target]
buffer.append(data[data_index])
data_index = (data_index + 1) % len(data)
return batch, labels
def train(self, data, reverse_dictionary):
# This helps us terminate early if training started before.
started_before = False
with tf.Session(graph=self.__graph) as session:
# want to save the overall state and the embeddings for later.
# I think we can do this in one, but I haven't had time to test this yet.
# TODO make this a bit more efficient, avoid having to save stuff twice.
# NOTE - this part is very closely coupled with the lstm.py script, as it
# reads the embeddings from the location specified here. Might be worth
# relaxing this dependency and passing the save location as a variable param.
ckpt = tf.train.get_checkpoint_state(self.__ckpt_path)
saver = tf.train.Saver(tf.global_variables())
saver_embed = tf.train.Saver({'embeddings': self.__embeddings})
if ckpt and gfile.Exists(ckpt.model_checkpoint_path):
print("Reading model parameters from {0}".format(ckpt.model_checkpoint_path))
saver.restore(session, ckpt.model_checkpoint_path)
print("done")
started_before = True
else:
print("Creating model with fresh parameters.")
tf.global_variables_initializer().run()
print('Initialized')
average_loss = 0
for step in range(num_steps):
batch_data, batch_labels = self.__generate_batch(data, self.__batch_size,
self.__num_skips, self.__skip_window)
feed_dict = {self.__train_dataset: batch_data, self.__train_labels: batch_labels}
_, l = session.run([self.__optimizer, self.__loss], feed_dict=feed_dict)
average_loss += l
if step >= 10000 and (average_loss / 2000) < 5 and started_before:
print('early finish as probably loaded from earlier')
break
if step % steps_per_checkpoint == 0:
# save stuff
checkpoint_path = os.path.join(ckpt_path, "model_ckpt")
embed_path = os.path.join(ckpt_embed,"embeddings_ckpt")
saver.save(session, checkpoint_path, global_step=self.__global_step)
saver_embed.save(session, embed_path)
print(embed_path)
if step % 2000 == 0:
if step > 0:
average_loss = average_loss / 2000
# The average loss is an estimate of the loss over the last 2000 batches.
print('Average loss at step %d: %f' % (step, average_loss))
average_loss = 0
# note that this is expensive (~20% slowdown if computed every 500 steps)
if step % 10000 == 0:
sim = self.__similarity.eval()
for i in range(valid_size):
valid_word = reverse_dictionary[valid_examples[i]]
top_k = 8 # number of nearest neighbors
nearest = (-sim[i, :]).argsort()[1:top_k + 1]
log = 'Nearest to %s:' % valid_word
for k in range(top_k):
#if nearest[k]<len(reverse_dictionary)
close_word = reverse_dictionary[nearest[k]]
log = '%s %s,' % (log, close_word)
print(log)
def optmize(self, valid_size, valid_window, num_sampled):
self.__valid_size = valid_size
self.__valid_window = valid_window
valid_examples = np.array(random.sample(range(valid_window), valid_size))
self.__graph = tf.Graph()
with self.__graph.as_default():
# variable to track progress
self.__global_step = tf.Variable(0, trainable=False)
# Input data.
self.__train_dataset = tf.placeholder(tf.int32, shape=[self.__batch_size])
self.__train_labels = tf.placeholder(tf.int32, shape=[self.__batch_size, 1])
valid_dataset = tf.constant(valid_examples, dtype=tf.int32)
with tf.device('/cpu:0'):
# Variables.
self.__embeddings = tf.Variable(tf.random_uniform([self.__vocabulary_size, self.__embedding_size], -1.0, 1.0),
name = "embeddings")
nce_weights = tf.Variable(
tf.truncated_normal([self.__vocabulary_size, self.__embedding_size],
stddev=1.0 / math.sqrt(self.__embedding_size)))
nce_biases = tf.Variable(tf.zeros([self.__vocabulary_size]))
# Model.
# Look up embeddings for inputs.
# note that the embeddings are Variable params that will
# be optimised!
embed = tf.nn.embedding_lookup(self.__embeddings, self.__train_dataset)
# Compute the nce loss, using a sample of the negative labels each time.
# tried using sampled_softmax_loss, but performance was worse, so decided
# to use NCE loss instead. Might be worth some more testing, especially with
# the hyperparameters (ie num_sampled), to see what gives the best performance.
self.__loss = tf.reduce_mean(
tf.nn.nce_loss(nce_weights, nce_biases, self.__train_labels,
embed, num_sampled, self.__vocabulary_size))
# PART BELOW LIFTED FROM TF EXAMPLES
# Optimizer.
# Note: The optimizer will optimize the nce weights AND the embeddings.
# This is because the embeddings are defined as a variable quantity and the
# optimizer's `minimize` method will by default modify all variable quantities
# that contribute to the tensor it is passed.
# See docs on `tf.train.Optimizer.minimize()` for more details.
self.__optimizer = tf.train.GradientDescentOptimizer(1.0).minimize(self.__loss, global_step=self.__global_step)
# Compute the similarity between minibatch examples and all embeddings.
# We use the cosine distance:
norm = tf.sqrt(tf.reduce_sum(tf.square(self.__embeddings), 1, keepdims =True))
self.__normalized_embeddings = self.__embeddings / norm
valid_embeddings = tf.nn.embedding_lookup(
self.__normalized_embeddings, valid_dataset)
self.__similarity = tf.matmul(valid_embeddings, tf.transpose(self.__normalized_embeddings))
# Module usage example
if __name__ == '__main__':
batch_size = 128 # how many target/context words to get in each batch
embedding_size = 128 # Dimension of the embedding vector.
skip_window = 1 # How many words to consider left and right - context size
num_skips = 2 # How many times to reuse an input to generate a label
vocabulary_size = 65466
# TAKEN FROM TF WEBSITE EXAMPLE:
# We pick a random validation set to sample nearest neighbors. here we limit the
# validation samples to the words that have a low numeric ID, which by
# construction are also the most frequent.
valid_size = 16 # Random set of words to evaluate similarity on.
valid_window = 100 # Only pick dev samples in the head of the distribution.
valid_examples = np.array(random.sample(range(valid_window), valid_size))
num_sampled = 64# Number of negative examples to sample.
#num_steps = 50001 # steps to run for
num_steps = 1001
steps_per_checkpoint = 50 # save the params every 50 steps.
data_preprocess = Data_Processer("training-data-large.txt", vocabulary_size)
basedir = os.getcwd()
data, count, dictionary, reverse_dictionary = data_preprocess.build_dataset(basedir)
# save the dictionary to file - very important for Data Processor
Helper.store_stuff(dictionary, "dictionary.pickle")
Helper.store_stuff(reverse_dictionary, "reverse_dictionary.pickle")
print('Most common words (+UNK)', count[:5])
print('Sample data', data[:10])
data_preprocess.batch_tester(data, reverse_dictionary)
print('three index', dictionary['X773579']) # X773579 is the sample data, it cant replace to any other word
ckpt_path = os.path.join(basedir, 'checkpoints')
if not os.path.exists(ckpt_path):
os.makedirs(ckpt_path)
ckpt_embed = os.path.join(ckpt_path, "embeddings")
if not os.path.exists(ckpt_embed):
os.makedirs(ckpt_embed)
# finish the data preprocessing, now let's do the word2vec computation
word2vec = Word2Vec(batch_size, num_skips, skip_window, embedding_size, vocabulary_size, ckpt_path)
word2vec.optmize(valid_size, valid_window, num_sampled)
word2vec.train(data, reverse_dictionary)
<file_sep>/README.md
# Sentiment-Analysis
### Introduction
Sentiment analysis is contextual mining of text which identifies and extracts subjective information in source material, and helping a business to understand the social sentiment of their brand, product or service while monitoring online conversations.
In this project I create the machine learning model which can classify positive and negative result of the sentence by using word2vec and LSTM. enjoy it 🙂

### Setup
**Make sure you have the following is installed:**
- Python3
- Tensorflow
- NumPy
- SciPy
- Pandas
- Matplotlib
### Dataset
for the dataset please make sure your training data .txt file is like following:
| Sentence | Class |
| ------------ | ------------ |
| I like this movie! | 1 |
| I hate this feeling. | 0 |
|............... | ..|
### Pipline
The following is the project pipline:

### Run
**Notice:**
Before you start to run this project please make sure to analysis the vocabulary size of training data as following:

Once you prepared the training data, you can simply by execute the **example.py** to run the whole pipline.
```shell
python example.py
```
Or If you want to run the pipline step by step, please make sure you prepared the needed dataset for each module, Please check the Pipline chart to find it out.
```shell
python word2vec_module.py
python DataProcess_module.py
python LSTM_module.py
```
<file_sep>/Helper.py
import os
import pickle
# The Helper class has a few common static methods
# that are used throughout the system.
# More methods can be added here - would be useful!
class Helper:
def __init__(self):
pass
@staticmethod
def remove_file_extension(name):
indices = [i for i, ltr in enumerate(name) if ltr == '.']
return name[:indices[-1]]
@staticmethod
def remove_file_silently(filename):
try:
os.remove(filename)
except OSError:
pass
# this pickles a couple of items and stores them on the filesystem,
# given the filepath to store the items at.
# The method below this one (get_stuff) does the opposite.
# TODO- this isn't scalable! use *args and **kwargs to make these
# two methods accept a variable number of parameters, so that they
# can load/store more files if the caller wants it.
@staticmethod
def store_stuff(item1, item1filepath):
with open(item1filepath, "wb") as output_file:
pickle.dump(item1, output_file)
@staticmethod
def store_stuff_submission(item, itemfilepath):
with open(itemfilepath, "wb") as output_file:
pickle.dump(item, output_file)
@staticmethod
def get_stuff(item1filepath, item2filepath):
with open(item1filepath, "rb") as input_file:
item1 = pickle.load(input_file)
with open(item2filepath, "rb") as input_file:
item2 = pickle.load(input_file)
return item1, item2
@staticmethod
def get_stuff_submission(itemfilepath):
with open(itemfilepath, "rb") as input_file:
item = pickle.load(input_file)
return item<file_sep>/example.py
import word2vec_module
def main():
print("to do")
#do something
if __name__ == '__main__':
main()<file_sep>/DataProcess_module.py
import string
import os
import numpy as np
import pandas as pd
import pickle
from sklearn.model_selection import train_test_split
from Helper import Helper
class PreProcess:
def __init__(self, data_file_pth, dict, rever_dict):
if not os.path.exists("processed"):
os.makedirs("processed/")
print("No processed data found - generating")
else:
print("Some data may exist!!")
self.__loadDictionary(dict, rever_dict)
self.__data_file_pth = data_file_pth
def __loadDictionary(self, dict, rever_dict):
if not os.path.exists(dict) or not os.path.exists(rever_dict):
print("Can't find dictionary, please create dictionary first!")
return
self.__word_ids, self.__rev_word_ids = Helper.get_stuff(dict, rever_dict)
def __cleanup_test(self,text):
li = text.split(',')
return li
def __save_data(self,npArray, path):
start = os.getcwd()
path = os.path.join(start, path)
np.save(path, npArray)
def __process_review(self ,review_data, word_ids, max_seq_length, data_type, data_id):
data = np.array([i for i in range(max_seq_length)])
word_indices = []
processed_dir = os.path.join("processed", data_type)
if not os.path.exists(processed_dir):
os.makedirs(processed_dir)
new_name = data_id + ".npy"
processed_path = os.path.join(processed_dir, new_name)
if os.path.exists(processed_path):
print(processed_path)
return processed_path
word_list = self.__cleanup_test(review_data)
for word in word_list:
if word in word_ids:
token = word_ids[word]
else:
token = word_ids["UNK"]
word_indices.append(token)
if len(word_indices) < max_seq_length:
padding = word_ids["<PAD>"]
assert(padding == 0)
word_indices = word_indices + [padding for i in range(max_seq_length - len(word_indices))]
else:
word_indices = word_indices[0:max_seq_length]
data = np.vstack((data, word_indices))
# data is set up to have the right size, but the first row is just full of dummy data.
# this slicing procedure extracts JUST the word indices.
data = data[1::]
self.__save_data(data, processed_path)
return processed_path
def __seq_data(self, data_unsep):
data_seq = list()
for data in data_unsep:
data_seq.append(data)
return data_seq
def create_processed_files(self, data_label ,data_texts, max_seq_length, datatype):
internal_list = []
li_test = []
li_train = []
for i in range(len(data_texts)):
output_file = self.__process_review(data_texts[i], self.__word_ids, max_seq_length, datatype, str(i))
if output_file is not None:
internal_list.append((output_file, data_label[i]))
print (internal_list[:10])
# very important to store these so that LSTM can use them.
if datatype =="test":
li_test.extend(internal_list)
Helper.store_stuff(li_test, "li_test.pickle")
else:
li_train.extend(internal_list)
Helper.store_stuff(li_train, "li_train.pickle")
def split_data(self, percent):
data_df = pd.read_csv(self.__data_file_pth, sep='\t', names=["Label", "Text"])
data_text = data_df["Text"]
data_label = data_df["Label"]
# example: set percent to 0.2 it will be 80% for training 20% for test
train_datas, test_datas, train_labels, test_labels = train_test_split(data_text,
data_label, test_size=percent, random_state=42)
return self.__seq_data(train_datas), self.__seq_data(test_datas),\
self.__seq_data(train_labels), self.__seq_data(test_labels)
# Module usage example
if __name__ == '__main__':
# step 1: init preprocess first
preprocess = PreProcess("training-data-large.txt", "dictionary.pickle", "reverse_dictionary.pickle")
# step 2: split the train data to 80% of training 20% of testing by this case
data_trains, data_tests, label_trains, label_tests = preprocess.split_data(0.2)
# step 3: create the train and test file for the LSTM
max_seq_length = 120
preprocess.create_processed_files(label_trains, data_trains, max_seq_length, "train")
preprocess.create_processed_files(label_tests, data_tests, max_seq_length, "test")
| a97657bfda00441e91b8154e326e8c1ceb86f87f | [
"Markdown",
"Python"
] | 6 | Python | Jakelee24/Sentiment-Analysis-tensorflow | 4eb82a9890516bf6516e19141e93624d1c5c51b6 | 4a3dfda6be9784deba27f99d7999b5a71a427efb |
refs/heads/master | <repo_name>kalai15/tools-cookbook<file_sep>/recipes/gcc_update.rb
#
# Cookbook Name:: askci
# Recipe:: gcc_update
#
# Copyright 2013, Ask.com
#
# All rights reserved - Do Not Redistribute
if node.platform_version == "6.4"
yum_packages = {
'lapack-devel' => '3.2.1-4.el6',
'lapack' => '3.2.1-4.el6',
'blas-devel' => '3.2.1-4.el6',
'blas' => '3.2.1-4.el6',
'gcc-gfortran' => '4.4.7-3.el6',
'gcc-c++' => '4.4.7-3.el6',
'gcc' => '4.4.7-3.el6'
}
yum_packages.each do |k,v|
package k do
version v
action :remove
end
end
yum_packages = {
'devtoolset-2-runtime' => '2.1-4.el6',
'devtoolset-2-gcc' => '4.8.2-15.1.el6',
'devtoolset-2-libstdc++-devel' => '4.8.2-15.1.el6',
'devtoolset-2-gcc-c++' => '4.8.2-15.1.el6'
}
yum_packages.each do |k,v|
package k do
version v
action :install
end
end
link "/usr/bin/gcc" do
to "/opt/rh/devtoolset-2/root/usr/bin/gcc"
end
link "/usr/bin/g++" do
to "/opt/rh/devtoolset-2/root/usr/bin/g++"
end
link "/usr/bin/cc" do
to "/opt/rh/devtoolset-2/root/usr/bin/cc"
end
end
<file_sep>/files/default/bin/koji-scratch-build
#!/usr/bin/env python
import os, sys, subprocess, getopt
options, arguments = getopt.getopt(sys.argv[1:], 'target:', ['target='])
for opt, arg in options:
if opt in ('--target='):
target = arg
sha = os.environ['GIT_COMMIT']
jenkins_url = os.environ['JENKINS_URL']
job_name = os.environ['JOB_NAME']
build_dir = os.environ['WORKSPACE']+'/build'
task = 0
def get_task(line):
global task
if line[-4:].isdigit():
task = line[-4:]
def parse_stdout(output):
for line in output:
print(line.rstrip())
if "Task info: " in line.rstrip():
get_task(line.rstrip())
#if "something else " in output.line():
# call_another_method
def run_command(command):
proc = subprocess.Popen(command, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
return_code = proc.wait()
parse_stdout(proc.stdout)
for line in proc.stderr:
print(line.rstrip())
if return_code != 0:
sys.exit(1)
run_command( 'rm -rf %s; mkdir -p %s' %(build_dir, build_dir) )
git_url = os.getenv("GIT_URL")
repo_name = git_url.split(':')[-1]
run_command( 'koji build --scratch %s git+http://gitrepo.jeeves.ask.info/git-repos/%s#%s' %(target, repo_name, sha) )
if task == 0:
print "No build was kicked off on koji"
sys.exit(1)
else:
run_command( 'koji watch-task %s' %(task) )
os.system( 'wget -P %s -r -nH --cut-dirs=4 --no-parent --reject="index.html*" --level=1 http://koji.ask.com/kojifiles/scratch/Release%%20Engineering/task_%s/' %(build_dir, task) )
sys.exit(0)
<file_sep>/files/default/bin/pypi/promote-to-askprod
#!/bin/bash
usage() {
echo "promote-to-askprod -v <python-version> [-p <path to setup.py>]"
echo " where"
echo " <python-version> is a valid version of Python available under /ask/Python-<python-version>"
echo " <path to setup.py> is an optional argument. If this is not specified, it is assumed to be at the root of the project"
exit 1
}
die() {
echo "ERROR: $1"
exit 1
}
clean() {
pushd ${WORKSPACE}
rm -rf setup.py || die "Could not clean up setup.py" "$?"
rm -rf dist || die "Could not clean up distribution folder" "$?"
rm -rf venv || die "Could not clean up virtual environment" "$?"
popd
}
init() {
PYTHON_DIR=/ask/Python-${version}
if [ ! -d ${PYTHON_DIR} ]; then
echo "Python was not found under ${PYTHON_DIR}"
usage
fi
mkdir -p ${WORKSPACE}/dist || die "Could not create dist directory" "$?"
}
get_artifacts() {
pushd ${WORKSPACE}
wget ${PROMOTED_URL}artifact/${setup_py_path}/setup.py || die "Could now download original setup.py" "$?"
popd
${PYTHON_DIR}/bin/virtualenv venv || die "Could not create virtual environment from ${PYTHON_DIR}" "$?"
source venv/bin/activate || die "Could not activate python virtual environment" "$?"
package_name=`python setup.py --name`
package_version=`python setup.py --version`
deactivate || die "Could not deactivate python virtual environment" "$?"
pushd ${WORKSPACE}/dist
wget ${PROMOTED_URL}artifact/${setup_py_path}/dist/${package_name}-${package_version}.tar.gz || die "Could not download original package ${package_name}-${package_version}.tar.gz" "$?"
popd
}
prevent_overwrites() {
check=`curl -s http://pypi.ask.com/pypi/ | grep ${package_name}-${package_version}`
if [ "${check}" != "" ]; then
echo "${package_name}-${package_version} already exists on https://pypi.ask.com/pypi/"
echo "Please update the version in setup.py which will trigger a new build"
exit 1
fi
}
upload() {
pushd ${WORKSPACE}
${PYTHON_DIR}/bin/virtualenv venv || die "Could not create virtual environment from ${PYTHON_DIR}" "$?"
source venv/bin/activate || die "Could not activate python virtual environment" "$?"
python setup.py register -r askprod sdist upload -r askprod || die "Failed to upload package to pypi.ask.com" "$?"
deactivate || die "Could not deactivate python virtual environment" "$?"
popd
}
while getopts ":v:p:" opt
do
case "$opt" in
v) version="$OPTARG"
;;
p) setup_py_path="$OPTARG"
;;
\?) usage
;;
*) usage
;;
esac
done
clean
init
get_artifacts
prevent_overwrites
upload
<file_sep>/recipes/setup.rb
#
# Cookbook Name:: askci
# Recipe:: setup
#
execute "setup-svn-config-files" do
user "#{node['askci']['user']['name']}"
command "/usr/bin/svn help"
environment ({'HOME' => "#{node['askci']['user']['home']}"})
end
ruby_block "allow_svn_plain_text_passwords" do
block do
file = Chef::Util::FileEdit.new("#{node['askci']['user']['home']}/.subversion/servers")
file.insert_line_if_no_match(/^store-plaintext-passwords/, 'store-plaintext-passwords = yes')
file.write_file
end
end
<file_sep>/recipes/buildtools-centos.rb
#
# Cookbook Name:: askci
# Recipe:: buildtools-centos.rb
#
yum_packages={}
rpm_packages={}
case node['platform_version'][0...3]
when '5.4'
case node['kernel']['machine']
when 'i686'
yum_packages['ruby'] = '1.8.5-5.el5_3.7'
yum_packages['apr'] = '1.2.7-11.el5_3.1'
yum_packages['apr-util'] = '1.2.7-7.el5_3.2'
yum_packages['neon'] = '0.28.4-1'
yum_packages['sqlite'] = '3.5.9-2'
yum_packages['subversion'] = '1.6.17-1'
yum_packages['rpm-build'] = '4.4.2.3-18.el5'
template "#{node['askci']['user']['home']}/.rpmmacros" do
owner node['askci']['user']['name']
group node['askci']['group']['name']
mode '664'
source 'rpmmacros_32.erb'
end
when 'x86_64'
yum_packages['nfs-utils'] = '1.0.9-70.el5'
yum_packages['rpm-build'] = '4.4.2.3-18.el5'
yum_packages['git'] = '1.7.4.1-1.el5'
yum_packages['ruby'] = '1.8.5-5.el5_3.7'
yum_packages['vim-enhanced'] = '7.0.109-6.el5'
yum_packages['apr'] = '1.2.7-11.el5_3.1'
yum_packages['apr-util'] = '1.2.7-7.el5_3.2'
yum_packages['libxml2-devel'] = '2.6.26-2.1.2.8'
yum_packages['Percona-Server-shared-compat'] = '5.5.13-rel20.4.138.rhel5'
yum_packages['Percona-Server-devel-55'] = '5.5.13-rel20.4.138.rhel5'
yum_packages['Percona-Server-shared-55'] = '5.5.13-rel20.4.138.rhel5'
yum_packages['cyrus-sasl-devel'] = '2.1.22-5.el5'
yum_packages['openldap-devel'] = '2.3.43-3.el5'
yum_packages['glib2-devel'] = '2.12.3-4.el5_3.1'
yum_packages['python-ctypes'] = '1.0.2-2.el5'
# Koji
yum_packages['python-krbV'] = '1.0.90-1.el5'
yum_packages['pyOpenSSL'] = '0.6-1.p24.7.2.2'
yum_packages['koji'] = '1.6.0-1.el5'
yum_packages['python-setuptools'] = '0.6c5-2.el5'
# SAE/Xdict
yum_packages['curl-devel'] = '7.15.5-2.1.el5_3.5'
yum_packages['libxml2-devel'] = '2.6.26-2.1.2.8'
yum_packages['vim-common'] = '7.0.109-6.el5'
yum_packages['libxslt-devel'] = '1.1.17-2.el5_2.2'
yum_packages['lua-devel'] = '5.1.4-4.el5'
yum_packages['cppunit-devel'] = '1.12.0-4.el5.1'
yum_packages['unixODBC-devel'] = '2.2.11-7.1'
# C/C++
yum_packages['scons'] = '1.2.0-3.el5'
yum_packages['gcc'] = '4.1.2-46.el5'
yum_packages['gcc-c++'] = '4.1.2-46.el5'
yum_packages['binutils'] = '2.17.50.0.6-12.el5'
yum_packages['binutils-devel'] = '2.17.50.0.6-12.el5'
yum_packages['pcre-devel'] = '6.6-2.el5_1.7'
yum_packages['ncurses-devel'] = '5.5-24.20060715'
yum_packages['compat-libstdc++-33'] = '3.2.3-61'
# REL-2096 compat-libstdc++-33 i386 package needed for NAF metaserver
yum_packages['compat-libstdc++-33.i386'] = '3.2.3-61'
yum_packages['autoconf'] = '2.59-12'
yum_packages['automake'] = '1.9.6-2.1'
# Adwise
yum_packages['bison'] = '2.3-2.1'
yum_packages['compat-gcc-34'] = '3.4.6-4'
yum_packages['compat-gcc-34-c++'] = '3.4.6-4'
yum_packages['flex'] = '2.5.4a-41.fc6'
yum_packages['bzip2-devel'] = '1.0.3-4.el5_2'
yum_packages['python26'] = '2.6.5-6.el5'
yum_packages['gperf'] = '3.0.1-7.2.2'
yum_packages['gsl'] = '1.13-3.el5'
yum_packages['gsl-devel'] = '1.13-3.el5'
# Python26
yum_packages['redhat-rpm-config'] = '8.0.45-32.el5.centos'
yum_packages['python26'] = '2.6.5-6.el5'
yum_packages['python26-devel'] = '2.6.5-6.el5'
yum_packages['neon'] = '0.28.4-1'
yum_packages['sqlite'] = '3.5.9-2'
yum_packages['subversion'] = '1.6.17-1'
yum_packages['alt-httpd-event-mod-rh5'] = '2.2.13-1'
yum_packages['ask-apache-log4cxx'] = '0.10.0-1'
yum_packages['ask-libmicrohttpd'] = '0.4.1-1.el5'
yum_packages['ask-fcgi'] = '2.4.0-1'
yum_packages['ask-pcre'] = '6.6-1'
yum_packages['ask-pcre++'] = '0.9.5-1'
yum_packages['ask-muparser'] = '130-1'
# NAF ProtoBuf
yum_packages['ask-python'] = '2.7-0'
# REL-2096, REL-2145 NAF Metaserver and QAThrift
yum_packages['libevent'] = '1.4.13-1'
yum_packages['libevent-devel'] = '1.4.13-1'
template '/etc/yum.repos.d/ask-epel.repo' do
owner 'root'
group 'root'
mode '0644'
source 'ask-epel5-yum.erb'
action :nothing
end.run_action(:create)
end
when '7.0'
yum_packages['git'] = '1.8.3.1-4.el7'
# yum_packages['ruby'] = '1.8.5-5.el5_3.7'
# SVN
yum_packages['subversion'] = '1.7.14-6.el7'
yum_packages['apr'] = '1.4.8-3.el7'
yum_packages['apr-util'] = '1.5.2-6.el7'
yum_packages['neon'] = '0.30.0-3.el7'
yum_packages['pakchois'] = '0.4-10.el7'
yum_packages['subversion-libs'] = '1.7.14-6.el7'
# Koji
yum_packages['python-krbV'] = '1.0.90-8.el7'
yum_packages['pyOpenSSL'] = '0.13.1-3.el7'
# yum_packages['koji'] = '1.6.0-1.el5'
when '7.1'
yum_packages['git'] = '1.8.3.1-4.el7'
yum_packages['apr'] = '1.5.0-1'
# SVN
yum_packages['apr-util'] = '1.5.3-1'
yum_packages['neon'] = '0.30.0-3.el7'
yum_packages['pakchois'] = '0.4-10.el7'
yum_packages['subversion'] = '1.7.14-6.el7'
yum_packages['subversion-libs'] = '1.7.14-6.el7'
# Koji
yum_packages['python-krbV'] = '1.0.90-8.el7'
yum_packages['pyOpenSSL'] = '0.13.1-3.el7'
# Selenium
yum_packages['xorg-x11-server-Xvfb'] = '1.15.0-32.el7'
yum_packages['xorg-x11-xauth.x86_64'] = '1.0.7-6.1.el7'
yum_packages['firefox'] = '31.4.0-1.el7.centos'
yum_packages['google-chrome-stable'] = '46.0.2490.80-1'
yum_packages['redhat-lsb'] = '4.1-27.el7.centos.1'
yum_packages['mesa-dri-drivers'] = '10.2.7-5.20140910.el7'
yum_packages['libXScrnSaver'] = '1.2.2-6.1.el7'
yum_packages['xorg-x11-server-Xvfb'] = '1.15.0-32.el7'
yum_packages['rubygems'] = '2.0.14-24.el7'
yum_packages['openssl-devel'] = '1.0.1e-42.el7'
yum_packages['ruby-devel'] = '2.0.0.598-24.el7'
execute "install-selenium-webdriver" do
command "gem install selenium-webdriver"
end
directory "/logs/xvfb" do
action :create
owner "root"
group "root"
mode "755"
end
cookbook_file "/usr/local/bin/chromedriver" do
owner "root"
group "root"
mode "0755"
source "chromedriver"
end
cookbook_file "/etc/init.d/xvfb" do
owner "root"
group "root"
mode "0755"
source "xvfb-init"
end
execute "xbfb-init-config" do
command "/usr/sbin/chkconfig --add xvfb"
end
service 'xvfb' do
action [:start, :enable]
end
when '7.2'
yum_packages['git'] = '1.8.3.1-4.el7'
yum_packages['apr'] = '1.4.8-3.el7'
# SVN
yum_packages['apr-util'] = '1.5.3-1'
yum_packages['neon'] = '0.30.0-3.el7'
yum_packages['pakchois'] = '0.4-10.el7'
yum_packages['subversion'] = '1.7.14-10.el7'
yum_packages['subversion-libs'] = '1.7.14-10.el7'
# Koji
yum_packages['python-krbV'] = '1.0.90-8.el7'
yum_packages['pyOpenSSL'] = '0.13.1-3.el7'
# Selenium
yum_packages['xorg-x11-server-Xvfb'] = '1.17.2-10.el7'
yum_packages['xorg-x11-xauth'] = '1.0.9-1.el7'
yum_packages['firefox'] = '38.3.0-2.el7.centos'
yum_packages['google-chrome-stable'] = '46.0.2490.80-1'
yum_packages['redhat-lsb'] = '4.1-27.el7.centos.1'
yum_packages['mesa-dri-drivers'] = '10.6.5-3.20150824.el7'
yum_packages['libXScrnSaver'] = '1.2.2-6.1.el7'
yum_packages['xorg-x11-server-Xvfb'] = '1.17.2-10.el7'
yum_packages['rubygems'] = '2.0.14-25.el7_1'
yum_packages['openssl-devel'] = '1.0.1e-42.el7.9'
yum_packages['ruby-devel'] = '2.0.0.598-25.el7_1'
execute "install-selenium-webdriver" do
command "gem install selenium-webdriver"
end
directory "/logs/xvfb" do
action :create
owner "root"
group "root"
mode "755"
end
cookbook_file "/usr/local/bin/chromedriver" do
owner "root"
group "root"
mode "0755"
source "chromedriver"
end
cookbook_file "/etc/init.d/xvfb" do
owner "root"
group "root"
mode "0755"
source "xvfb-init"
end
execute "xbfb-init-config" do
command "/usr/sbin/chkconfig --add xvfb"
end
service 'xvfb' do
action [:start, :enable]
end
end
yum_packages.each do |k,v|
yum_package k do
version v
action :install
end
end
link '/usr/local/lib/libevent.a' do
to '/usr/lib64/libevent.a'
only_if 'test -f /usr/lib64/libevent.a'
end
include_recipe 'askci::koji'
include_recipe 'askci::setup'
<file_sep>/files/default/bin/sem/sem-tools-nightly-automation
#!/bin/bash
usage() { echo $@; echo "Usage: $0 [-j <Jenkins job name>][-p <promotion-name>] " 1>&2; exit 1; }
PACKAGER_DIR=`dirname $0`
while getopts ":j:p:" o; do
case "${o}" in
j)
jenkinsJobName=${OPTARG}
;;
p)
promotionName=${OPTARG}
;;
\?)
usage
;;
*)
usage
;;
esac
done
trigger() {
lastSuccessfulBuildNumber=`python $PACKAGER_DIR/../get-last-successful-build.py --job-name=$jenkinsJobName`
echo "Last successful build for ${jenkinsJobName} was ${lastSuccessfulBuildNumber}"
promote=`python $PACKAGER_DIR/../trigger-promotion.py --job-name=${jenkinsJobName} --build-number=${lastSuccessfulBuildNumber} --promotion-process=${promotionName}`
echo ${promote}
exit 0
}
trigger
<file_sep>/files/default/bin/generate-compiled.sh
set -e
ourl='http://dev-master.jeeves.ask.info/cgi-bin/viewcvs.cgi/trunk/htdocs9/sh/config/ldservice/compiled/#?revision=@%26root=static'
nurl='http://dev-master.jeeves.ask.info/cgi-bin/viewcvs.cgi/trunk/htdocs9/sh/config/ldservice/source/#?revision=@%26root=static'
#cd /ask/ask/LDService
if [ ! -e ldservice ] ; then
svn co svn+ssh://builder@dev-master.jeeves.ask.info/ask/svn/static/trunk/htdocs9/sh/config/ldservice
fi
#make sure compiled dir is uptodate and store the latest revisions of compiled files
cd ldservice/compiled
svn up
svn status -v | awk '{print $2 "\t" $4}' > /tmp/ld_revisions_c.txt
orev=($(awk '{print $1}' /tmp/ld_revisions_c.txt))
ofil=($(awk '{print $2}' /tmp/ld_revisions_c.txt))
rm /tmp/ld_revisions_c.txt
#update to the revision of build and store the output in output.txt
cd ../source
svn up -r $1 > /tmp/ld_output.txt
#store the latest revisions of src files
svn status -v | awk '{print $2 "\t" $4}' > /tmp/ld_revisions.txt
rev=($(awk '{print $1}' /tmp/ld_revisions.txt))
fil=($(awk '{print $2}' /tmp/ld_revisions.txt))
rm /tmp/ld_revisions.txt
#function to get compiled file using api, getting latest revisions from dev-master
failure=''
warnings=''
getconfig(){
updated=$(echo $1 | awk '{print $2}')
of='ld_'$updated
nf=$updated
#get new file revision num
nrevision=-1
i=0
for f in "${fil[@]}" ; do
if [ "$nf" == "$f" ]; then
nrevision=${rev[$i]}
fi
i=`expr $i + 1`
done
#get old file revision num
orevision=-1
i=0
for f in "${ofil[@]}" ; do
if [ "$of" == "$f" ]; then
orevision=${orev[$i]}
fi
i=`expr $i + 1`
done
if [ $2 -eq 0 ]; then
ou=''
else
if [ $orevision -eq -1 ]; then
ou=''
else
ou=$(echo $ourl |sed -e s/"#"/"$of"/ -e s/"@"/"$orevision"/)
fi
fi
if [ $nrevision -eq -1 ]; then
failure=$failure": "$updated
else
nu=$(echo $nurl |sed -e s/"#"/"$nf"/ -e s/"@"/"$nrevision"/)
ncf=$of
OIFS=$IFS
IFS=$'\n'
output_status=($(curl -s "http://ldservicestg001iad.io.askjeeves.info:8010/config?ourl="$ou"&nurl="$nu -o ../compiled/$ncf -D /dev/stdout | grep -e ld_expired -e ld_status -e ld_overlaps | sed -e 's/[[:cntrl:]]//'))
IFS=$OLDIFS
if [ ! -s ../compiled/$ncf ]; then
failure=$failure": "$updated
else
if grep -q '</ldService>' ../compiled/$ncf; then
for j in "${output_status[@]}" ; do
if [ "ld_status: warn" == "$j" ]; then
warnings=$warnings": "$updated
fi
if [[ "$j" == ld_expired* ]]; then
echo "There are expired tests for $updated"
echo "$j"
fi
if [[ "$j" == ld_overlaps* ]]; then
echo "There are overlapping testsets for $updated"
echo "$j"
fi
done
else
failure=$failure": "$updated
svn revert ../compiled/$ncf
fi
fi
fi
}
#main step, reads svn status output and passes to getconfig to generate new file, either added or updated or deleted
while read line ;do
if `echo $line | grep -E "^U " >/dev/null 2>&1`; then
echo "getting config"
getconfig "$line" 1
elif `echo $line | grep -E "^A " >/dev/null 2>&1`; then
getconfig "$line" 0
elif `echo $line | grep -E "^D " >/dev/null 2>&1`; then
del=$(echo $line | awk '{print $2}')
of='ld_'$del
svn delete ../compiled/$of
else
echo "nothing"
fi
done < /tmp/ld_output.txt
#go to compiled dir to see whats added, deleted or updated and commit everything
cd ../compiled
svn status > /tmp/ld_new.txt
while read line ; do
status=`echo $line | awk ' { print $1 }' `
filename=`echo $line | awk ' { print $2 }' `
if [ "$status" == "?" ] ; then
if [ ! -s $filename ] ; then
rm $filename
else
svn add $filename
fi
fi
if [ "$status" == "M" ] ; then
if [ ! -s $filename ] ; then
svn revert $filename
fi
fi
done < /tmp/ld_new.txt
rm /tmp/ld_new.txt
svn ci -m "generated ld configs $1"
if [ "$failure" != "" ] ; then
echo "Config generation failed for $failure"
fi
if [ "$warnings" != "" ] ; then
echo "Warnings for files - $warnings"
echo "See above for overlaping testsets or expired tests"
fi
if [ "$failure" != "" ] || [ "$warnings" != "" ] ; then
exit 1;
fi
<file_sep>/files/default/parse-logs.sh
#!/bin/bash
#
# Parse mpssh console output and print meaningful message
# Prints FAILURE/SUCCES MESSAGE
# Hudson will use PATTERN INSTALLATION FAILED ON: for making builds unstable
outputfile=$1
if [ -e $outputfile ]; then
if `grep -E "]=: [^0]" $outputfile > /dev/null 2>&1` ; then
echo "***************************************"
echo "INSTALLATION FAILED ON:"
grep -E "]=: [^0]" $outputfile
fi
if `grep -E "]=: [0]" $outputfile > /dev/null 2>&1` ; then
echo "***************************************"
echo "INSTALLATION Completed Successfully ON "
grep -E "]=: [0]" $outputfile
echo "***************************************"
fi
fi
<file_sep>/files/default/bin/get_aske_version
#!/bin/sh
rm -f version.txt
rm -f version.properties
find modules/app/target -maxdepth 1 -name "*.json" | awk -F "/" '{print $4}' | awk -F ".json" '{print $1}' > version.txt
cp -f modules/app/target/*.json modules/app/target/aske-$1-1.0-SNAPSHOT-binary
echo "$1version=$(cat version.txt)" > version.properties
<file_sep>/files/default/bin/push-to-s3
#!/usr/bin/env python
import os, sys, subprocess, getopt, json
options, arguments = getopt.getopt(sys.argv[1:], 'key:env:', ['key=', 'env='])
for opt, arg in options:
if opt in ('--key='):
key = arg
elif opt in ('--env'):
env = arg
build_dir = os.environ['WORKSPACE']+'/build'
promoted_url = os.environ['PROMOTED_URL']
xmlfile = build_dir + '/output.xml'
jsonfile = build_dir + '/s3bucket.json'
#for param in os.environ.keys():
# print "%20s %s" % (param,os.environ[param])
def run_command(command):
proc = subprocess.Popen(command, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
return_code = proc.wait()
for line in proc.stdout:
print(line.rstrip())
for line in proc.stderr:
print(line.rstrip())
def get_bucket_name(artifact_name):
#bucket_names = [item['name'] for item in data['bucket']]
#bucket_artifacts = [item['artifact-list'] for item in data['bucket']]
with open(jsonfile, 'r') as input:
data = json.load(input)
for item in data['bucket']:
if type(item['artifact-list']) is list:
if any(artifact_name in s for s in item['artifact-list']):
return item['name']
elif item['artifact-list'] == artifact_name:
return item['name']
def get_s3_config():
from xml.etree import ElementTree as et
tree = et.parse(xmlfile)
root = tree.getroot()
for child in root.findall('artifact'):
filename = child.find('fileName').text
if filename == 's3bucket.json':
relative_path = child.find('relativePath').text
artifact = promoted_url + 'artifact/' + relative_path
print( "Grabbing %s" %(artifact) )
run_command( 'wget %s -q -O %s/%s' %(artifact, build_dir, filename) )
print ""
run_command( 'rm -rf %s; mkdir -p %s;' %(build_dir, build_dir) )
run_command( 'wget %s/api/xml -nv -O %s' %(promoted_url, xmlfile) )
get_s3_config()
from xml.etree import ElementTree as et
tree = et.parse(xmlfile)
root = tree.getroot()
for child in root.findall('artifact'):
filename = child.find('fileName').text
if filename == 's3bucket.json':
continue
relative_path = child.find('relativePath').text
artifact = promoted_url + 'artifact/' + relative_path
print( "Grabbing %s" %(artifact) )
run_command( 'wget %s -q -O %s/%s' %(artifact, build_dir, filename) )
bucket = get_bucket_name(filename)
if bucket == None:
print( "Skipping copy of %s...no corresponding bucket found in s3bucket.json" %(filename) )
continue
print( "Pushing to S3 bucket %s-%s:%s" %(env, bucket, filename) )
run_command( 'source ~/jenkins/s3_keys/%s; ~/jenkins/bin/s3sync/s3cmd.rb put --progress %s-%s:%s %s/%s' %(key, env, bucket, filename, build_dir, filename) )
print ""
sys.exit(0)
<file_sep>/files/default/bin/pypi/packager
#!/bin/bash
usage() {
echo "packager -v <python-version> [-p <path to setup.py>]"
echo " where"
echo " <python-version> is a valid version of Python available under /ask/Python-<python-version>"
echo " <path to setup.py> is an optional argument. If this is not specified, it is taken as the current path ($PWD)"
exit 1
}
die() {
echo "ERROR: $1"
exit 1
}
clean() {
if [ -z ${setup_py_path} ]; then
setup_py_path=${PWD}
fi
pushd ${setup_py_path}
rm -rf dist || die "Could not clean up distribution folder" "$?"
rm -rf venv || die "Could not clean up virtual environment" "$?"
popd
}
init() {
PYTHON_DIR=/ask/Python-${version}
if [ ! -d ${PYTHON_DIR} ]; then
echo "Python was not found under ${PYTHON_DIR}"
usage
fi
if [ ! -e ${setup_py_path}/setup.py ]; then
echo "setup.py was not found at ${setup_py_path}"
usage
fi
}
package() {
pushd ${setup_py_path}
${PYTHON_DIR}/bin/virtualenv venv || die "Could not create virtual environment from ${PYTHON_DIR}" "$?"
source venv/bin/activate || die "Could not activate python virtual environment" "$?"
description=`python setup.py --description`
if [ "${description}" == "UNKNOWN" ]; then
echo "Please make sure setup.py includes a 'description'"
exit 1
fi
python setup.py sdist --formats=gztar || die "Failed to build python package" "$?"
deactivate || die "Could not deactivate python virtual environment" "$?"
popd
}
upload() {
pushd ${setup_py_path}
source venv/bin/activate || die "Could not activate python virtual environment" "$?"
python setup.py register -r askdev sdist upload -r askdev
deactivate || die "Could not deactivate python virtual environment" "$?"
popd
}
while getopts ":v:p:" opt
do
case "$opt" in
v) version="$OPTARG"
;;
p) setup_py_path="$OPTARG"
;;
\?) usage
;;
*) usage
;;
esac
done
clean
init
package
upload
<file_sep>/files/default/bin/tram/promote-service-pack_env
#!/bin/bash
# This script must be run via the Jenkins Promote plugin #
set -x
usage() {
echo ""
echo "Usage: promote-service-pack -e tram-environment -c tram-cluster -n jenkins-job-name [-a artifact_location]"
echo "where"
echo " tram-environment is one of development|staging|landp"
echo " tram-cluster is one of md-offline|md-online|alps"
echo " jenkins-job-name must match the name of the service pack and is the name of a job on http://askci.jeeves.ask.info:8080 which produces the service pack"
echo " artifact-location is an optional argument which points to the location of run.json"
exit 1
}
die() {
echo "ERROR: $1"
exit $2
}
clean() {
if [ -e run.json ]; then
echo "The present working directory is :`pwd` "
rm run.json run.json.*
fi
}
determine_promotion_url() {
case $tram_environment in
development)
if [ "${tram_cluster}" == "md-offline" ]; then
tram1_promotion_url=""
tram2_promotion_url=""
fi
;;
staging)
if [ "${tram_cluster}" == "md-offline" ]; then
tram2_promotion_url="tramstgmdoff.iad.ask.com"
fi
if [ "${tram_cluster}" == "md-online" ]; then
tram2_promotion_url="tramstgmdon.iad.ask.com"
fi
if [ "${tram_cluster}" == "alps" ]; then
tram2_promotion_url="tramstgalpsoff.iad.ask.com"
fi
if [ "${tram_cluster}" == "qts-online" ]; then
tram2_promotion_url="tramstgqts.iad.ask.com"
fi
;;
landp)
if [ "${tram_cluster}" == "md-online" ]; then
tram2_promotion_url="tram2plxonapi.iad.ask.com"
fi
if [ "${tram_cluster}" == "alps" ]; then
tram2_promotion_url="tramplxalpsoff.iad.ask.com"
fi
if [ "${tram_cluster}" == "tram-online" ]; then
tram2_promotion_url="trampilotplxonapi.iad.ask.com"
fi
;;
\?)
echo "Unrecognized environment ${tram_environment}"
usage
;;
esac
}
promote_to_tram2() {
echo "The present working directory:`pwd`"
if [ -z "$artifact_location" ] && [ "$tram_cluster" != "qts-online" ]; then
wget ${JENKINS_URL}job/${jenkins_job_name}/${PROMOTED_NUMBER}/artifact/build/run.json || die "Could not find run.json for ${jenkins_job_name}" "$?"
elif [ "$tram_cluster" == "qts-online" ]; then
wget ${JENKINS_URL}job/${jenkins_job_name}/${PROMOTED_NUMBER}/artifact/build/qts/run.json || die "Could not find run.json for ${jenkins_job_name}" "$?"
else
wget ${JENKINS_URL}job/${jenkins_job_name}/${PROMOTED_NUMBER}/${artifact_location} || die "Could not find run.json for ${jenkins_job_name}" "$?"
fi
if [ "$tram_cluster" != "qts-online" ]; then
echo ""
echo "###################################################################################################"
echo "Promoting Service Pack to TRAM 2"
echo "###################################################################################################"
echo "Validating service pack for ${jenkins_job_name} against ${tram2_promotion_url}"
echo "###################################################################################################"
curl -X POST -d@run.json "http://${tram2_promotion_url}/api/validate_service_pack" || die "Service pack for ${jenkins_job_name} failed validation on ${tram2_promotion_url}" "$?"
echo ""
echo "###################################################################################################"
echo "Creating service pack for ${jenkins_job_name} against ${tram2_promotion_url}"
echo "###################################################################################################"
curl -X POST -d@run.json "http://${tram2_promotion_url}/api/create_service_pack" || die "Could not create service pack for ${jenkins_job_name} on ${tram2_promotion_url}" "$?"
echo ""
echo "###################################################################################################"
echo "Updating service pack for ${jenkins_job_name} against ${tram2_promotion_url}"
echo "###################################################################################################"
curl -XPOST -d@run.json "http://${tram2_promotion_url}/api/update_service_pack" || die "Could not update service pack for ${jenkins_job_name} on ${tram2_promotion_url}" "$?"
else
echo ""
echo "###################################################################################################"
echo "Promoting Service Pack to TRAM 2"
echo "###################################################################################################"
echo "Validating service pack for ${jenkins_job_name} against ${tram2_promotion_url}"
echo "###################################################################################################"
curl -X POST -d@run.json "http://${tram2_promotion_url}/api/validate_service_pack" || die "Service pack for ${jenkins_job_name} failed validation on ${tram2_promotion_url}" "$?"
echo ""
echo "###################################################################################################"
echo "Creating service pack for ${jenkins_job_name} against ${tram2_promotion_url}"
echo "###################################################################################################"
curl -X POST -d@run.json "http://${tram2_promotion_url}/api/create_service_pack" || die "Could not create service pack for ${jenkins_job_name} on ${tram2_promotion_url}" "$?"
echo ""
echo "###################################################################################################"
echo "Updating service pack for ${jenkins_job_name} against ${tram2_promotion_url}"
echo "###################################################################################################"
curl -X POST -d@run.json "http://${tram2_promotion_url}/api/update_service_pack" || die "Could not update service pack for ${jenkins_job_name} on ${tram2_promotion_url}" "$?"
fi
}
if [ $# -le 4 ] ; then
echo "Please pass the right number of arguments to this script"
usage
fi
while getopts :e:c:n:a: option
do
case $option in
e)
tram_environment=$OPTARG;
;;
c)
tram_cluster=$OPTARG;
;;
n)
jenkins_job_name=$OPTARG;
;;
a)
artifact_location=$OPTARG;
;;
\?)
echo "Invalid options! $option"
usage
;;
esac
done
pushd $WORKSPACE
clean
determine_promotion_url
promote_to_tram2 $tram2_promotion_url $jenkins_job_name $artifact_location
popd
<file_sep>/definitions/install_pip.rb
define :install_pip_virtualenv, :install_method => "source", :python_binary => nil, :pip_location => nil, :python_prefix_dir => nil do
puts params[:python_binary]
puts params[:pip_location]
if params[:install_method] == 'source'
pip_binary = "#{params[:python_prefix_dir]}/bin/pip"
elsif platform_family?("rhel", "fedora")
pip_binary = "/usr/bin/pip"
elsif platform_family?("smartos")
pip_binary = "/opt/local/bin/pip"
else
pip_binary = "/usr/local/bin/pip"
end
cookbook_file Chef::Config['file_cache_path'] + '/get-pip.py' do
source 'get-pip.py'
mode "0644"
not_if { ::File.exists?(pip_binary) }
end
script "install-pip" do
interpreter 'bash'
code <<-EOH
#{params[:python_binary]} #{Chef::Config[:file_cache_path]}/get-pip.py || exit 1
EOH
not_if { ::File.exists?(pip_binary) }
end
askci_pip 'setuptools' do
action :upgrade
pip_location params[:pip_location]
end
askci_pip 'virtualenv' do
action :upgrade
pip_location params[:pip_location]
end
end
<file_sep>/files/default/xvfb-init
#!/bin/bash
# xvfb - this script starts and stops Xvfb
#
# chkconfig: 345 95 50
# description: Starts xvfb on display 99
# processname: Xvfb
# pidfile: /logs/xvfb/xvfb.pid
# Source function library.
. /etc/rc.d/init.d/functions
log_dir=/logs/xvfb
error_log=$log_dir/xvfb_error.log
std_log=$log_dir/xvfb_std.log
pid_file=$log_dir/xvfb.pid
xvfb=$( which Xvfb )
user=root
screen_options=":99 -ac -screen 0 1024x768x8"
start() {
if test -f $pid_file
then
PID=`cat $pid_file`
if ps --pid $PID >/dev/null;
then
echo "Xvfb is already running: $PID"
exit 0
else
echo "Removing stale pid file: $pid_file"
fi
fi
echo -n "Starting Xvfb..."
su $user -c "$xvfb $screen_options -nolisten tcp >$std_log 2>$error_log &"
if [ $? == "0" ]; then
success
else
failure
fi
echo
ps -C Xvfb -o pid,cmd | grep Xvfb | awk {'print $1 '} > $pid_file
}
stop() {
if test -f $pid_file
then
echo -n "Stopping Xvfb..."
PID=`cat $pid_file`
su $user -c "kill -15 $PID"
if kill -9 $PID ;
then
sleep 2
test -f $pid_file && rm -f $pid_file
success
else
echo "Xvfb could not be stopped..."
failure
fi
else
echo "Xvfb is not running."
failure
fi
echo
}
status() {
if test -f $pid_file
then
PID=`cat $pid_file`
if ps --pid $PID >/dev/null ;
then
echo "Xvfb is running...$PID"
else
echo "Xvfb isn't running..."
fi
else
echo "Xvfb isn't running..."
fi
}
case "$1" in
start)
$1
;;
stop)
$1
;;
restart)
stop
start
;;
status)
$1
;;
*)
echo "Usage: $SELF start|stop|restart|status"
exit 1
;;
esac
<file_sep>/recipes/buildtools-scientific.rb
#
# Cookbook Name:: askci
# Recipe:: buildtools-scientific.rb
#
yum_packages={}
# Packages that change depending on platform_version
case node['platform_version']
when '6.1'
yum_packages.merge!({
'rpm-build' => '4.8.0-16.el6',
'make' => '3.81-19.el6',
'libxml2-devel' => '2.7.6-1.el6',
'gcc-c++' => '4.4.5-6.el6',
'zlib-devel' => '1.2.3-25.el6',
'openssl-devel' => '1.0.1e-15.el6',
'pcre-devel' => '7.8-3.1.el6',
'libicu-devel' => '4.2.1-9.el6',
'libxslt' => '1.1.26-2.el6',
'asciidoc' => '8.4.5-4.1.el6',
'cyrus-sasl-devel' => '2.1.23-8.el6',
'cyrus-sasl-gssapi' => '2.1.23-8.el6',
'libtidy' => '0.99.0-19.20070615.1.el6',
'libxslt-devel' => '1.1.26-2.el6',
'openldap-devel' => '2.4.23-15.el6',
'python-devel' => '2.6.6-20.el6',
'python-simplejson' => '2.0.9-3.1.el6',
'sqlite-devel' => '3.6.20-1.el6'
})
#yum_packages['mysql-devel'] = '5.1.52-1.el6_0.1'
yum_base_url = "http://#{node['reyumserver']}/yum/el6/#{node['kernel']['machine']}"
# ask-python (since we don't have 2.7.8-1.el6 for SL 6.1)
%w{2.7.6-1.el6}.each do |ver|
ask_rpm_package 'ask-python' do
packagename yum_base_url + '/ask-python-' + ver + '.x86_64.rpm'
action :install
end
end
when '6.4'
yum_packages.merge!({
'rpm-build' => '4.8.0-32.el6',
'make' => '3.81-20.el6',
'libxml2-devel' => '2.7.6-8.el6_3.4',
'gcc-c++' => '4.4.7-3.el6',
'zlib-devel' => '1.2.3-29.el6',
'openssl-devel' => '1.0.1e-15.el6',
'pcre-devel' => '7.8-6.el6',
'libicu-devel' => '4.2.1-9.1.el6_2',
'libxslt' => '1.1.26-2.el6_3.1',
'asciidoc' => '8.4.5-4.1.el6',
'cyrus-sasl-devel' => '2.1.23-13.el6_3.1',
'cyrus-sasl-gssapi' => '2.1.23-13.el6_3.1',
'libtidy' => '0.99.0-19.20070615.1.el6',
'libxslt-devel' => '1.1.26-2.el6_3.1',
'openldap-devel' => '2.4.23-31.el6',
'python-devel' => '2.6.6-36.el6',
'python-simplejson' => '2.0.9-3.1.el6',
'sqlite-devel' => '3.6.20-1.el6',
'zeromq' => '4.1.2-1.el6',
'libwurfl' => '1.5.3.2-1'
})
yum_base_url = "http://#{node['reyumserver']}/yum/el6.4/#{node['kernel']['machine']}"
# multiple versions of ask-python
%w{2.7.6-1.el6 2.7.8-1.el6}.each do |ver|
ask_rpm_package 'ask-python' do
packagename yum_base_url + '/ask-python-' + ver + '.x86_64.rpm'
action :install
end
end
end
yum_packages.merge!({
# Base packages
'git' => '1.7.1-2.el6_0.1',
'dos2unix' => '3.1-37.el6',
'subversion' => '1.6.15-0.1.el6.rfx',
# Data Base
'Percona-Server-shared-compat' => '5.5.13-rel20.4.138.rhel6',
'Percona-Server-devel-55' => '5.5.13-rel20.4.138.rhel6',
'Percona-Server-shared-55' => '5.5.13-rel20.4.138.rhel6',
# Koji
'python-krbV' => '1.0.90-3.el6',
'pyOpenSSL' => '0.10-2.el6',
'koji' => '1.8.0-1.el6',
# C/C++
'scons' => '2.0.1-1.el6',
'kyotocabinet-devel' => '1.2.75-1',
'kyotocabinet-python' => '1.17-1.el6',
'thrift' => '0.8.0-1',
'thrift-lib-cpp-devel' => '0.8.0-1',
'log4cxx-devel' => '0.10.0-12.el6',
'libpion-devel' => '4.0.11-1.sl6',
'apr-util-devel' => '1.5.3-1',
'ncurses-devel' => '5.7-3.20090208.el6',
'compat-libstdc++-33' => '3.2.3-69.el6',
'python-setuptools' => '0.6.10-3.el6',
# packages for Neptune
'blt-devel' => '2.4-32.z.el6',
'tk-devel' => '8.5.7-5.el6',
# packages for Zoom
'flex' => '2.5.35-8.el6',
'bison' => '2.4.1-5.el6'
})
# NAF builds
# yum_packages['protobuf'] = '2.3.0-7.el5'
yum_packages.each do |k,v|
package k do
version v
action :install
end
end
# Section to install pip and coudbdb for default python,
# it depends on the version of python-setuptools installed
script 'Install couchdb python module' do
user 'root'
interpreter 'bash'
code <<-EOH
easy_install pip==1.5.6
pip install couchdb
pip install python-jenkins
pip install jinja2
pip install requests
EOH
end
## REL-4516 Update the recipe to install pychef and argparse python module
bash 'Install python module for archie python script' do
code <<-EOH
pip install PyChef
pip install argparse
EOH
end
include_recipe 'askci::koji'
include_recipe 'askci::setup'
<file_sep>/recipes/master.rb
#
# Cookbook Name:: askci
# Recipe:: master
#
# Copyright 2013, Ask.com
#
# All rights reserved - Do Not Redistribute
#
include_recipe 'askci::common'
case node['platform']
when 'macos'
include_recipe 'askci::buildtools-mac'
else
include_recipe "askci::buildtools-#{node['platform']}"
end
cookbook_file "#{node['askci']['user']['home']}/.ssh/id_dsa" do
owner node['askci']['user']['name']
group node['askci']['group']['name']
source 'master_pvk'
mode 0400
action :create
end
cookbook_file "#{node['askci']['user']['home']}/.ssh/authorized_keys" do
owner node['askci']['user']['name']
group node['askci']['group']['name']
source 'master_authorized_keys'
mode 0600
action :create
end
#Now setup Jenkins/Hudson/etc
%w{data app app/war}.each do |name|
directory "#{node['askci']['base_dir']}/#{name}" do
owner node['askci']['user']['name']
group node['askci']['group']['name']
mode 0755
action :create
end
end
# templates for email-template under JENKINS_HOME directory
directory "#{node['askci']['base_dir']}/.jenkins/email-templates" do
owner node['askci']['user']['name']
group node['askci']['group']['name']
mode 0755
recursive true
action :create
end
["site-question-it.jelly"].each do |jelly_file_name|
template "#{node['askci']['base_dir']}/.jenkins/email-templates/#{jelly_file_name}" do
source "email-templates/#{jelly_file_name}"
owner node['askci']['user']['name']
group node['askci']['group']['name']
mode 0644
action :create
end
end
[node['askci']['log_dir'],'/var/run/jenkins/'].each do |name|
directory name do
owner node['askci']['user']['name']
group node['askci']['group']['name']
mode 0755
action :create
end
end
remote_file "#{node['askci']['base_dir']}/app/jenkins.war" do
source "#{node['askci']['thirdparty_binary_repo']}/jenkins/#{node['askci']['jenkins']['version']}/jenkins.war"
checksum '5bdf1dd796b6ebc241f8a5bff4c6846a1eadbb455f7e3efcc5fb8d8749ae7192'
owner 'root'
group 'root'
mode 0755
action :create
end
case node['fqdn']
when node['askci']['primary']
template '/etc/init.d/jenkins' do
source 'jenkins-init.erb'
owner 'root'
group 'root'
mode 0755
action :create
notifies :restart, 'service[jenkins]' , :delayed
end
service 'jenkins' do
action [:start, :enable]
end
when node['askci']['secondary']
template '/etc/init.d/jenkins' do
source 'jenkins-init.erb'
owner 'root'
group 'root'
mode 0755
action :create
end
service 'jenkins' do
action [:stop, :disable]
end
end
<file_sep>/files/default/bin/get_npm_version_file
#!/bin/sh
filename=$1
[ -f $filename ] && rm -f $filename
echo "Grabbing $filename"
echo "Job Name: ${PROMOTED_JOB_NAME} Build Number: ${PROMOTED_NUMBER}"
echo "URL: http://askci.jeeves.ask.info:8080/job/${PROMOTED_JOB_NAME}/${PROMOTED_NUMBER}/artifact/$filename"
wget http://askci.jeeves.ask.info:8080/job/${PROMOTED_JOB_NAME}/${PROMOTED_NUMBER}/artifact/$filename
if [ "$filename" == "version.txt" ] ; then
export VERSION_NUMBER=$(cat version.txt)
fi
<file_sep>/files/default/bin/promote-npm-packages
#!/bin/bash
# This script it used to push npm repositories to npm data centers
function getNpmPackageFromJenkins() {
pushd $WORKSPACE
rm -f $1-$(cat version.txt).tgz
rm -f version.txt
popd
if [[ $3 == "" ]]; then
wget http://askci.jeeves.ask.info:8080/job/$1/$2/artifact/version.txt || die "version.txt for $1 $2 not present on npmstore" "$?"
wget http://askci.jeeves.ask.info:8080/job/$1/$2/artifact/$1/$1-$(cat version.txt).tgz || die "$1 $2 not present on jenkins" "$?"
else
wget http://askci.jeeves.ask.info:8080/job/$3/$2/artifact/version.txt || die "version.txt for $1 $2 not present on npmstore" "$?"
wget http://askci.jeeves.ask.info:8080/job/$3/$2/artifact/$1/$1-$(cat version.txt).tgz || die "$1 $2 not present on jenkins" "$?"
fi
}
function getNpmPackageFromNpmStore() {
pushd $WORKSPACE
rm -f $1-$2.tgz
rm -rf $1
rm -rf package
popd
wget http://npmstore.ask.com/registry/$1/$1-$2.tgz || die "$1 $2 not present on npmstore" "$?"
}
function clean() {
rm -rf $1
rm -f $1-$(cat version.txt).tgz
rm -f version.txt
}
function die() {
echo "ERROR: $1"
exit 1
}
function pushNpmPackagetoNpm() {
if [[ "$shrinkwrap" == "1" ]]; then
rm -rf $1-$2
echo "Creating directory $1-$2"
mkdir -p $1-$2
echo "Moving $1-$2.tgz to $1-$2"
mv $1-$2.tgz $1-$2/
pushd $1-$2
tar -xzf $1-$2.tgz --strip-components 1
rm -f $1-$2.tgz
rm -rf $HOME/.npm
$HOME/software/nodejs/bin/npm cache clean --registry=http://npmstore.ask.com/registry
$HOME/software/nodejs/bin/npm install --registry=http://npmstore.ask.com/registry -verbose || die "npm push failed" "$?"
$HOME/software/nodejs/bin/npm shrinkwrap || die "npm shrinkwrap failed" "$?"
if [[ "$prepublish" == "true" ]]; then
echo "Running prepublish ....."
$HOME/software/nodejs/bin/npm run prepublish || die "npm prepublish failed" "$?"
fi
echo "python $HOME/jenkins/bin/npm-packages.py > dependencies"
python $HOME/jenkins/bin/npm-packages.py > dependencies
rm -rf node_modules
for datacenter in $4
do
rm -f exists
$HOME/software/nodejs/bin/npm show $1 --registry=http://npm.$datacenter.ask.com/registry | grep "version: '$2'" > exists
if [ -s exists ]; then
echo "$1 $2 exists on npm.$datacenter.ask.com"
else
rm -f $1.$2.tgz
pushd $WORKSPACE
rm -f $1.$2.tgz
tar -cvzf $1.$2.tgz $1-$2
echo "Publishing $1 $2 to $datacenter"
$HOME/software/nodejs/bin/npm publish $1.$2.tgz --registry=http://npm.$datacenter.ask.com/registry/_design/app/_rewrite || die "npm publish failed for $1 $2" "$?"
popd
fi
done
popd
else
echo "$@ arguments $4"
mkdir -p $1-$2
echo "Moving $1-$2.tgz to $1-$2"
mv $1-$2.tgz $1-$2/
pushd $1-$2
tar -xzf $1-$2.tgz --strip-components 1
for datacenter in $4
do
rm -f exists
echo /ask/builder/askci/software/nodejs/bin/npm show $1 --registry=http://npm.$datacenter.ask.com/registry | grep $2 > exists
/ask/builder/askci/software/nodejs/bin/npm show $1 --registry=http://npm.$datacenter.ask.com/registry | grep $2 > exists
if [ -s exists ]; then
echo "$1 $2 exists on npm.$datacenter.ask.com"
else
rm -f $1-$2.tgz
echo "Publishing $1-$2 to $datacenter"
/ask/builder/askci/software/nodejs/bin/npm publish --registry=http://npm.$datacenter.ask.com/registry/_design/app/_rewrite --verbose || die "npm publish failed for $1 $2" "$?"
fi
done
popd
fi
}
function pushNpmPackagetoNpmstore() {
echo "Publishing $1 to http://npmstore.ask.com"
$HOME/software/nodejs/bin/npm publish $1-$(cat version.txt).tgz --registry=http://npmstore.ask.com/registry/_design/app/_rewrite -verbose || die "npm push failed" "$?"
}
usage() { echo $@; echo "Usage: $0 [-n <module>] [-b <build_number>] [-v <version_number>] [-t <depot-type>] [-s <0 or 1>] [-d <depot list>] [-j <jenkins job name>] [-p prepublish flag]" 1>&2; exit 1; }
depots="iad las"
jenkins_job_name=""
prepublish="false"
while getopts ":n:b:t:s:d:v:j:p:" o; do
case "${o}" in
n)
module_name=${OPTARG}
;;
b)
build_number=${OPTARG}
;;
t)
depot_type=${OPTARG}
;;
s)
shrinkwrap=${OPTARG}
;;
d)
depots=${OPTARG}
;;
v)
version_number=${OPTARG}
;;
j)
jenkins_job_name=${OPTARG}
;;
p)
prepublish=${OPTARG}
;;
*)
usage
;;
esac
done
shift $((OPTIND-1))
echo "Command executed:" $0 $module_name $build_number $depot_type $shrinkwrap "to depots " $depots "with jenkins_job_name" $jenkins_job_name
if [ $depot_type == "prod" ]; then
getNpmPackageFromNpmStore $module_name $version_number
pushNpmPackagetoNpm $module_name $version_number $shrinkwrap "$depots" || die "npm push failed" "$?"
else
getNpmPackageFromJenkins $module_name $build_number $jenkins_job_name
pushNpmPackagetoNpmstore $module_name $build_number || die "npm push failed" "$?"
fi
exit;
<file_sep>/files/default/bin/promote-npm-dependencies
#!/bin/bash
$HOME/jenkins/bin/promote-npm-packages -n $1 -v $2 -t prod -s $3 -p $4 -d "${*:5}"
if [[ $3 -eq 1 ]];
then
pushd $1-$2
cat dependencies
for depot in ${*:5}
do
while read line;
do
array=($line)
rm -f exists
~/software/nodejs/bin/npm show ${array[0]} --registry=http://npm.$depot.ask.com/registry | grep "${array[0]}: '${array[1]}'" > exists
if [ -s exists ]; then
echo "${array[0]} ${array[1]} exists on npm.$depot.ask.com"
else
echo $line | awk '{print "-n" $1,"-v" $2}' | xargs ~/jenkins/bin/promote-npm-packages -d $depot -s 0 -t prod;
fi
done < dependencies
done
rm -f dependencies
popd
fi
<file_sep>/files/default/bin/tram/tramUpdateJson.py
import sys
import json
def updateJson(filetoupdate, url):
jsonFile = open(filetoupdate, "r")
data = json.load(jsonFile)
jsonFile.close()
data["production_artifact_url"] = url
jsonFile = open(filetoupdate, "w+")
jsonFile.write(json.dumps(data))
jsonFile.close()
if __name__ == '__main__':
if len(sys.argv) < 3:
print "Usage: python updatejson.py <json-file-path> <production-artifact-url>"
else:
updateJson(sys.argv[1], sys.argv[2])
<file_sep>/recipes/multi_python.rb
## Multiple Python Virtual environment support
multipy = {
'2.7.6' => {
'version' => '2.7.6',
'install_method' => 'source',
'prefix_dir' => '/ask/Python-2.7.6',
'binary' => '/ask/Python-2.7.6/bin/python',
'pip_location' => '/ask/Python-2.7.6/bin/pip'
},
'2.7.8' => {
'version' => '2.7.8',
'install_method' => 'source',
'prefix_dir' => '/ask/Python-2.7.8',
'binary' => '/ask/Python-2.7.8/bin/python',
'pip_location' => '/ask/Python-2.7.8/bin/pip'
}
}
multipy.each_pair do |key, value|
install_pip_virtualenv 'install' do
install_method value['install_method']
python_binary value['binary']
pip_location value['pip_location']
python_prefix_dir value['prefix_dir']
only_if { ::File.exists?('pip_location') }
end
end
<file_sep>/files/default/bin/promote-outside-npm-packages
#!/bin/bash
# This script is used to push outside npm packages from npmstore to npm depots
function usage() {
echo "Usage: promote-outside-npm-packages <package_name> <package_version> <npm_location>"
exit 1
}
function clean() {
pushd $WORKSPACE
rm -f $1-$2.tgz
rm -rf $1-$2
popd
}
function die() {
echo "ERROR: $1"
exit 1
}
function pushNpmPackage() {
wget ${3}/${1}/-/${1}-${2}.tgz --no-check-certificate || die "wget failed" "$?"
mkdir $1-$2
mv $1-$2.tgz $1-$2
pushd $1-$2
tar -xvzf $1-$2.tgz --strip-components 1
rm -f $1-$2.tgz
$HOME/software/nodejs/bin/npm install --registry=$3 --verbose || die "npm install on $1 failed" "$?"
$HOME/software/nodejs/bin/npm shrinkwrap --dev || die "npm shrinkwrap on $1 failed" "$?"
rm -f dependencies
echo "python $HOME/jenkins/bin/npm-packages.py > dependencies"
python $HOME/jenkins/bin/npm-packages.py > dependencies
while read line;
do
array=($line)
echo ${array[0]} ${array[1]}
rm -f ${array[0]}-${array[1]}.tgz
rm -f exists
$HOME/software/nodejs/bin/npm show ${array[0]} --registry=http://npmstore.ask.com/registry | grep "${array[0]}: '${array[1]}'" > exists
if [ -s exists ]; then
echo "${array[0]}-${array[1]} exists in npm dev store"
else
wget $3/${array[0]}/-/${array[0]}-${array[1]}.tgz --no-check-certificate || die "wget failed" "$?"
$HOME/software/nodejs/bin/npm publish ${array[0]}-${array[1]}.tgz --registry=http://npmstore.ask.com/registry/_design/app/_rewrite || die "npm publish failed for ${array[0]}" "$?"
fi
done < dependencies
popd
}
if [ $# -eq 3 ]; then
clean $1 $2
pushd $WORKSPACE
pushNpmPackage $1 $2 $3
popd
else
usage
fi
<file_sep>/recipes/buildtools-android.rb
#
# Cookbook Name:: askci
# Recipe:: buildtools-android
#
{"r21" => "083a2d49f12f3b5e3512c5d17c23daad6215fdc0c52d4d9616718d7b6eab1e0e" , "r15" => "5e7f56f314355ad5f8d0c4ba6dd94c2d0764ccc0d64986c878464a44129fc474"}.each do |k,v|
ark "android-sdk-#{k}" do
url "#{node['askci']['thirdparty_binary_repo']}/android-sdk/#{k}/android-sdk_#{k}-linux.tgz"
version k
path node['askci']['software_dir']
checksum v
owner node['askci']['user']['name']
action :put
end
end
link "#{node['askci']['software_dir']}/android-sdk" do
to "#{node['askci']['software_dir']}/android-sdk-#{node['askci']['androidsdk_latest']}"
end
path="#{node['askci']['software_dir']}/java/bin:%s" %(ENV['PATH'])
puts path
execute "update-android-tools" do
command "tools/android update sdk --no-ui"
user node['askci']['user']['name']
cwd "#{node['askci']['software_dir']}/android-sdk-#{node['askci']['androidsdk_latest']}"
environment ({'JAVA_HOME' => "#{node['askci']['software_dir']}/java", 'PATH' => path})
action :run
end
<file_sep>/files/default/bin/promote-outside-npm-packages.rb
#! /usr/bin/env ruby
require 'net/http'
require 'json'
require 'open-uri'
require 'zlib'
class OutsideNpmStore
attr_accessor :npm_module_name, :npm_module_version, :npm_location
attr_accessor :response
attr_accessor :dependent_modules
def initialize(npm_module_name, npm_module_version, npm_location)
@npm_module_name = npm_module_name
@npm_module_version = npm_module_version
@npm_location = npm_location
@dependent_modules = []
end
def pull
tar_name = "#{@npm_module_name}-#{@npm_module_version}"
unless !module_exits
tar_location = JSON.parse(@response.body)['dist']['tarball']
system("rm -f present.txt; npm show #{@npm_module_name} --registry=http://npmstore.ask.com/registry | grep \"'#{@npm_module_version}':\" > present.txt")
if File.zero? "present.txt"
unless File.directory?(tar_name)
begin
system("rm -f #{tar_name}.tgz; rm -rf #{tar_name}; wget #{tar_location}")
system("mkdir #{tar_name}; mv #{tar_name}.tgz #{tar_name}; ")
system("cd #{@npm_module_name}-#{@npm_module_version}; tar -xzf #{tar_name}.tgz --strip-components=1; rm -f #{tar_name}.tgz")
system("cd #{@npm_module_name}-#{@npm_module_version}; npm install --registry=http://npmstore.ask.com/registry")
system("cd #{@npm_module_name}-#{@npm_module_version}; npm shrinkwrap")
get_dependencies(JSON.parse(File.read("#{@npm_module_name}-#{@npm_module_version}/npm-shrinkwrap.json"))['dependencies'])
system("rm -f #{@npm_module_name}-#{@npm_module_version}/npm-shrinkwrap.json")
system("cd #{@npm_module_name}-#{@npm_module_version}; npm publish --registry=http://npmstore.ask.com/registry/_design/app/_rewrite")
rescue StandardError => e
puts e.message
exit 1
end
end
else
puts "#{tar_name} present in npmstore"
end
unless @dependent_modules.length == 0
@dependent_modules.each do |package|
package.each do |package_name, package_version|
@npm_module_name = package_name
@npm_module_version = package_version
tar_name = "#{@npm_module_name}-#{@npm_module_version}"
begin
unless !module_exits
system("rm -f present.txt; npm show #{@npm_module_name} --registry=http://npmstore.ask.com/registry | grep \"'#{@npm_module_version}':\" > present.txt")
unless File.zero? "present.txt"
puts "Pushing #{package_name} #{package_version}"
tar_location = JSON.parse(@response.body)['dist']['tarball']
system("rm -f #{tar_name}.tgz; rm -rf #{tar_name}; wget #{tar_location}")
system("npm publish #{tar_name}.tgz --registry=http://npmstore.ask.com/registry/_design/app/_rewrite;")
system("rm -f #{tar_name}.tgz")
else
puts "#{@npm_module_name}-#{@npm_module_version} present in npmstore"
end
end
rescue StandardError => e
puts e.message
exit 1
end
end
end
end
else
puts "#{tar_name} can't be found"
exit 1
end
end
def module_exits(npm_location=@npm_location,npm_module_name=@npm_module_name, npm_module_version=@npm_module_version)
begin
uri = URI.parse npm_location + "/" + npm_module_name + "/" + npm_module_version
uri.port = 80
res = Net::HTTP.get_response(uri)
@response = Net::HTTP.get_response(uri)
res.code == "200"
rescue StandardError => e
puts e.message
false
end
end
def get_dependencies(dependencies)
unless dependencies.nil?
dependencies.each_key { | key |
@dependent_modules << {key => dependencies[key]['version']}
get_dependencies(dependencies[key]['dependencies'])
}
end
end
end
if ARGV.size != 3
puts "Usage: promote-outside-npm-packages.rb npm-module-name npm-module-version npm-location<optional>"
exit 1
end
OutsideNpmStore.new(ARGV[0], ARGV[1], ARGV[2]).pull
<file_sep>/files/default/bin/sem-merge-master-to-integration
#!/bin/bash
cd ${WORKSPACE}
git checkout integration
echo "Git merging master back onto branch integration"
git merge master
git push
<file_sep>/files/default/bin/tram/tramUtils.py
import json
import sys
import urllib
import urllib2
import os
import shutil
class ParseJson:
filename = ""
parentdirectory = ""
def __init__(self, filename):
if not os.path.isfile(filename):
print "%s does not exist" %filename
sys.exit(1)
self.parentdirectory = os.path.dirname(filename)
self.filename = filename
f = open(self.filename, "r")
data = f.read()
f.close()
self.jsondata = json.loads(str(data))
def downloadFiles(self):
for key,value in self._getArtifactsFromJson().items():
if not (value["local-location"] == ""):
if (value["local-location"]).rfind("/") == -1:
print ("The local-location *must* have at least one parent folder!")
sys.exit(1)
self._removeDirectories(os.path.join(self.parentdirectory, value["local-location"]))
for key,value in self._getArtifactsFromJson().items():
remote_location = value["remote-location"]
local_location = value["local-location"]
self._getFiles(remote_location, os.path.join(self.parentdirectory, local_location))
def getName(self):
return self.jsondata['name']
def _removeDirectories(self, local_location):
dir = local_location[:local_location.rfind("/")]
if os.path.exists(os.path.abspath(dir)):
shutil.rmtree(dir, True)
def _getServicepackDependencies(self):
return self.jsondata['services'][0]['dependancies']
def _getArtifactsFromJson(self, ):
return self.jsondata['artifacts'][0]
def _getFiles(self, remote_location, local_location):
dir = local_location[:local_location.rfind("/")]
file = local_location[local_location.rfind("/")+1:]
# Create the dir if it doesn't exits
if not os.path.exists(os.path.abspath(dir)):
os.makedirs(dir)
try:
urllib2.urlopen(remote_location)
urllib.urlretrieve(remote_location, local_location)
except:
print "Url: %s not found" %remote_location
sys.exit(1)
<file_sep>/files/default/bin/pypi/pypipush
#!/bin/bash
usage() {
echo "promote-to-askprod -v <python-version> [-p <path-to-setup.py>] [-e <environment-name>"
echo " where"
echo " <python-version> is a valid version of Python available under /ask/Python-<python-version>"
echo " <path-to-setup.py> is an optional argument. If this is not specified, it is assumed to be at the root of the project"
echo " <environment name> is optional as well. It defines the environment to promote to. Defaults to prod. Valid environments are dev or prod."
exit 1
}
die() {
echo "ERROR: $1"
exit 1
}
clean() {
pushd ${WORKSPACE}
rm -rf setup.py || die "Could not clean up setup.py" "$?"
rm -rf dist || die "Could not clean up distribution folder" "$?"
rm -rf venv || die "Could not clean up virtual environment" "$?"
popd
}
init() {
PYTHON_DIR=/ask/Python-${version}
if [ ! -d ${PYTHON_DIR} ]; then
echo "Python was not found under ${PYTHON_DIR}"
usage
fi
mkdir -p ${WORKSPACE}/dist || die "Could not create dist directory" "$?"
}
get_artifacts() {
pushd ${WORKSPACE}
wget ${PROMOTED_URL}artifact/${setup_py_path}/setup.py || die "Could now download original setup.py" "$?"
popd
${PYTHON_DIR}/bin/virtualenv venv || die "Could not create virtual environment from ${PYTHON_DIR}" "$?"
source venv/bin/activate || die "Could not activate python virtual environment" "$?"
package_name=`python setup.py --name`
package_version=`python setup.py --version`
deactivate || die "Could not deactivate python virtual environment" "$?"
pushd ${WORKSPACE}/dist
wget ${PROMOTED_URL}artifact/${setup_py_path}/dist/${package_name}-${package_version}.tar.gz || die "Could not download original package ${package_name}-${package_version}.tar.gz" "$?"
popd
}
prevent_overwrites() {
check=`curl -s ${check_url} | grep ${package_name}-${package_version}`
if [ "${check}" != "" ]; then
echo "${package_name}-${package_version} already exists on ${repos}"
echo "Please update the version in setup.py which will trigger a new build"
exit 1
fi
}
upload() {
pushd ${WORKSPACE}
${PYTHON_DIR}/bin/virtualenv venv || die "Could not create virtual environment from ${PYTHON_DIR}" "$?"
source venv/bin/activate || die "Could not activate python virtual environment" "$?"
python setup.py register -r ${repos} sdist upload -r ${repos} || die "Failed to upload package to pypi.ask.com" "$?"
deactivate || die "Could not deactivate python virtual environment" "$?"
popd
}
while getopts ":v:p:e:" opt
do
case "$opt" in
v) version="$OPTARG"
;;
p) setup_py_path="$OPTARG"
;;
e) target_env="$OPTARG"
;;
\?) usage
;;
*) usage
;;
esac
done
if [ "$version" = "" ]; then
usage
exit1
fi
case $target_env in
prod)
echo "Deploying to production pypi server."
repos="askprod"
check_url="http://pypi.ask.com/pypi/"
;;
dev)
echo "Deploying to development pypi server."
repos="askdev"
check_url="http://pypi-dev.ask.com/pypi/"
;;
*)
echo "No valid environment given. Setting target promotion environment to production."
repos="askprod"
check_url="http://pypi.ask.com/pypi/"
esac
clean
init
get_artifacts
prevent_overwrites
upload
<file_sep>/recipes/tako.rb
#
# Cookbook Name:: askci
# Recipe:: tako
#
#%w{subversion rpm-build}.each do |name|
# package name do
# action :install
# end
#end
include_recipe "askci::slave"
template "/etc/sudoers.local" do
owner "root"
group "root"
mode "440"
source "sudoers.local.tako.erb"
end
%w{rpmbuild distfiles .m2 .m2/repository repository software webfiles}.each do |name|
directory "/ask/builder/#{name}" do
owner node['askci']['user']['name']
group node['askci']['group']['name']
recursive true
mode "0755"
action :create
end
end
%w{rpmbuild distfiles webfiles}.each do |name|
link "#{node['askci']['user']['home']}/#{name}" do
to "/ask/builder/#{name}"
end
end
%w{/logs/tako /ask/builder /ask/builder/mpssh}.each do|name|
directory name do
owner node['askci']['user']['name']
group node['askci']['group']['name']
mode "0755"
action :create
end
end
remote_file "#{node['askci']['software_dir']}/apache-tomcat-5.5.35.tar.gz" do
source "#{node['askci']['thirdparty_binary_repo']}/apache-tomcat/5.5.35/apache-tomcat-5.5.35.tar.gz"
owner node['askci']['user']['name']
group node['askci']['group']['name']
action :create_if_missing
not_if "test -d #{node['askci']['software_dir']}/apache-tomcat-5.5.35"
end
execute "extract tomcat" do
command "tar zxvf #{node['askci']['software_dir']}/apache-tomcat-5.5.35.tar.gz; chown -R #{node['askci']['user']['name']}:#{node['askci']['group']['name']} #{node['askci']['software_dir']}/apache-tomcat-5.5.35"
cwd node['askci']['software_dir']
action :run
not_if "test -d #{node['askci']['software_dir']}/apache-tomcat-5.5.35"
end
remote_file "#{node['askci']['software_dir']}/apache-tomcat-5.5.35/common/lib/log4j-1.2.8.jar" do
source "http://dev-master.jeeves.ask.info/ask/distfiles/java/log4j-1.2.8.jar"
owner node['askci']['user']['name']
group node['askci']['group']['name']
action :create
not_if "test -f #{node['askci']['software_dir']}/apache-tomcat-5.5.35/common/lib/log4j-1.2.8.jar"
end
remote_file "#{node['askci']['software_dir']}/apache-tomcat-5.5.35/common/lib/commons-logging-1.0.3.jar" do
source "http://dev-master.jeeves.ask.info/ask/distfiles/java/commons-logging-1.0.3.jar"
owner node['askci']['user']['name']
group node['askci']['group']['name']
action :create
not_if "test -f #{node['askci']['software_dir']}/apache-tomcat-5.5.35/common/lib/commons-logging-1.0.3.jar"
end
remote_file "#{node['askci']['software_dir']}/apache-tomcat-5.5.35/common/lib/ask-inetlib-current.jar" do
source "http://dev-master.jeeves.ask.info/ask/repository/maven2/com/ask/core/ask-inetlib/ask-inetlib-current.jar"
owner node['askci']['user']['name']
group node['askci']['group']['name']
action :create
not_if "test -f #{node['askci']['software_dir']}/apache-tomcat-5.5.35/common/lib/ask-inetlib-current.jar"
end
remote_file "#{node['askci']['software_dir']}/apache-tomcat-5.5.35/common/lib/recaptcha4j-0.0.7.jar" do
source "http://dev-master.jeeves.ask.info/ask/repository/myStuff/recaptcha4j-0.0.7.jar"
owner node['askci']['user']['name']
group node['askci']['group']['name']
action :create
not_if "test -f #{node['askci']['software_dir']}/apache-tomcat-5.5.35/common/lib/recaptcha4j-0.0.7.jar"
end
execute "checkout_hudson_tako_scripts" do
command "svn co http://dev-master.jeeves.ask.info:8888/svn/tool/scripts/generic_scripts/hudson-tako-scripts --username anon --password <PASSWORD>"
user node['askci']['user']['name']
cwd "/ask/builder"
action :run
environment ({'HOME' => "#{node['askci']['user']['home']}"})
not_if "test -d /ask/builder/hudson-tako-scripts"
end
%w{mpssh parse-logs.sh}.each do |file|
cookbook_file "/ask/builder/mpssh/#{file}" do
owner node['askci']['user']['name']
group node['askci']['group']['name']
mode "0755"
action :create
end
end
execute "Install-jdk6u26" do
command "rpm -ivh http://dev-master.jeeves.ask.info/ask/distfiles/java/ask-jdk-6u26-1.x86_64.rpm --force"
user "root"
action :run
not_if "test -d /usr/java/jdk1.6.0_26"
end
%w{distfiles repository}.each do |file|
link "/ask/#{file}" do
to "/ask/builder/#{file}"
end
end
cookbook_file "#{node['askci']['software_dir']}/apache-tomcat-5.5.35/common/classes/log4j.properties" do
source "tako-log4j.properties"
owner node['askci']['user']['name']
group node['askci']['group']['name']
action :create
mode "0644"
end
cookbook_file "#{node['askci']['base_dir']}/tools/clean-tako-builds" do
source "clean-tako-builds"
mode "0755"
owner node['askci']['user']['name']
group node['askci']['group']['name']
action :create
end
cron "clean-tako-builds" do
minute "0"
hour "0,4,8,12,16,20"
user node['askci']['user']['name']
command "#{node['askci']['base_dir']}/tools/clean-tako-builds"
action :create
end
<file_sep>/files/default/bin/sem-tools_release_merge
#!/bin/bash
cd ${WORKSPACE}
tag=`grep scm.tag= release.properties | sed 's/scm.tag=//g'`
rm release.properties
echo Build Tag $tag
git checkout release
echo "Git merging $tag onto branch release"
git merge $tag -X theirs
git push
#merging snapshot version back to integration
git checkout integration
echo "Git merging master back onto branch integration"
git merge master
git push
<file_sep>/attributes/default.rb
default['askci']['log_dir'] = '/logs/askci'
default['askci']['user']['name'] = 'builder'
default['askci']['group']['name'] = 'builder'
default['askci']['port'] = '8080'
default['askci']['jenkins']['version'] = '1.580.3'
default['askci']['jdk_latest'] = '1.8.0_66'
default['askci']['maven_latest'] = '3.3.3'
default['askci']['ant_latest'] = '1.9.6'
default['askci']['sbt_latest'] = '0.12.3'
default['askci']['hadoop_latest'] = '2.5.2'
default['askci']['primary'] = 'rextt101mwh.io.askjeeves.info'
default['askci']['secondary'] = 'rextt103mwh.io.askjeeves.info'
default['npmall'] = {
'development' => 'http://nexusdev001.iad.ops.ask.com:8081/nexus/content/groups/npmall/',
'staging' => 'http://nexusstg001.iad.ops.ask.com:8081/nexus/content/groups/npmall/',
'production-iad' => 'http://mvnrepo.ask.com/nexus/content/groups/npmall/',
'production-las' => 'http://mvnrepo.ask.com/nexus/content/groups/npmall/'
}
default['publish_registry'] = {
'staging' => 'http://npmstorestg001.iad.ops.ask.com/registry/_design/app/_rewrite',
'production-iad' => 'http://npmstore.ask.com/registry/_design/app/_rewrite',
'production-las' => 'http://npmstore.ask.com/registry/_design/app/_rewrite'
}
default['show_registry'] = {
'staging' => 'http://npmstorestg001.iad.ops.ask.com/registry',
'production-iad' => 'http://npmstore.ask.com/registry',
'production-las' => 'http://npmstore.ask.com/registry'
}
case node['fqdn']
when node['askci']['primary']
set['group_id_list'] = [5208, 5209]
set['user_id_list'] = [2005, 2006, 2007, 2008]
default['askci']['base_dir'] = '/data/builder/askci'
default['askci']['user']['home'] = '/data/builder/askci'
default['askci']['software_dir'] = '/data/builder/askci/software'
set['ask_commons']['software_directory'] = '/data/builder/askci/software'
when node['askci']['secondary']
set['group_id_list'] = [5208, 5209]
set['user_id_list'] = [2005, 2006, 2007, 2008]
default['askci']['base_dir'] = '/data/builder/askci'
default['askci']['user']['home'] = '/data/builder/askci'
default['askci']['software_dir'] = '/data/builder/askci/software'
set['ask_commons']['software_directory'] = '/data/builder/askci/software'
else
set['group_id_list'] = [5208]
set['user_id_list'] = [2005, 2006]
default['askci']['base_dir'] = '/ask/builder/askci'
default['askci']['user']['home'] = '/ask/builder/askci'
default['askci']['software_dir'] = '/ask/builder/askci/software'
set['ask_commons']['software_directory'] = '/ask/builder/askci/software'
end
set['npmhome'] = '/data/builder/askci'
set['npmuser'] = node['askci']['user']['name']
set['npmgroup'] = node['askci']['group']['name']
set['npmcache'] = '/data/builder/askci/.npm'
set['npmauth'] = 'YnVpbGRlcjpidWlsZGVy'
default['npmtmp'] = '/data/builder/askci/.tmp'
if node['kernel']['machine'].eql?('x86_64')
default['askci']['arch_prefix'] = 'x86_64'
else
default['askci']['arch_prefix'] = 'i386'
end
if node.chef_environment =~ /production|firstcall|staging|landp/
default['askci-slave']['artifact'] = "http://#{node['depotserver']}/chefrelease/scripts/#{node['appversion']['askci-slave']['build_number']}/production/scripts-#{node['appversion']['askci-slave']['version']}.tgz"
else
default['askci-slave']['artifact'] = "http://artifactor.ask.com/~builder/scripts/#{node['appversion']['askci-slave']['build_number']}/production/scripts-#{node['appversion']['askci-slave']['version']}.tgz"
end
default['askci']['thirdparty_binary_repo'] = 'http://dev-depot.jeeves.ask.info/ReleaseEngineering/3p-source-repo'
set['ask_commons']['nodejs']['version'] = '4.2.3'
default['nodejs']['path']['node'] = '/usr/local/bin/node'
default['php']['path'] = '/usr/bin/php'
default['php']['composer'] = '/usr/local/bin/composer'
default['gradle']['version'] = '1.12'
default['askci']['bower']['version'] = '1.3.12'
default['askci']['grunt-cli']['version'] = '0.1.13'
default['askci']['gulp']['version'] = '3.9.0'
default['askci']['phantomjs']['version'] = '1.9.15'
default['askci']['coffee-script']['version'] = '1.9.1'
default['askci']['blas']['version'] = '3.2.1-4.el6'
default['askci']['lapack']['version'] = '3.2.1-4.el6'
<file_sep>/recipes/common.rb
#
# Cookbook Name:: askci
# Recipe:: common
#
include_recipe "askci::users-groups"
include_recipe "re-tools::yum"
# Create npm .tmp directory for user builder to overwrite the template
directory node['npmtmp'] do
owner node['askci']['user']['name']
group node['askci']['group']['name']
action :create
recursive true
end
include_recipe "re-tools::npm"
template "#{node['npmhome']}/.npmrc" do
source "npmrc.erb"
owner node['askci']['user']['name']
group node['askci']['group']['name']
action :create
end
# Installing common rpms here
if not node['platform'].eql?("mac_os_x")
{"rpm-wrap" => "1.13-1"}.each do |k,v|
package k do
version v
action :install
end
end
end
# Setting up open file descriptor
bash "set_open_file_limit_for_#{node['askci']['user']['name']}" do
code <<-EOS
perl -pi -e "s|^# End of file$|#{node['askci']['user']['name']} soft nofile 102400\n#{node['askci']['user']['name']} hard nofile 102400\n\n\# End of file|g" /etc/security/limits.conf
EOS
not_if "grep -q #{node['askci']['user']['name']} /etc/security/limits.conf"
end
# Verfiying open file descriptor
execute "enforce_limits" do
command "sysctl -w fs.file-max=102400 && sysctl -p"
action :run
returns [0, 255]
end
[".ssh",".m2", ".ivy2"].each do |name|
directory "#{node['askci']['user']['home']}/#{name}" do
owner node['askci']['user']['name']
group node['askci']['group']['name']
mode "0700"
action :create
end
end
directory "#{node['askci']['base_dir']}/tools/" do
owner node['askci']['user']['name']
group node['askci']['group']['name']
mode "0755"
recursive true
action :create
end
%w{git-tag.rb koji-scratch-build mvn-release push-to-s3 jenkins-cli.jar promote-npm-packages replication-status npm-package-builder npm-packages.py promote-npm-dependencies trigger-pe-jenkins.py git-details.py generate-compiled.sh promote-outside-npm-packages.rb get_aske_version get_npm_version_file sem-tools_release_merge sem-merge-master-to-integration npm-package-builder_with_branch get-last-successful-build.py}.each do |name|
cookbook_file "#{node['askci']['base_dir']}/tools/#{name}" do
source "bin/#{name}"
owner node['askci']['user']['name']
group node['askci']['group']['name']
mode "0755"
end
end
%w{nodejs pypi tram sem}.each do |name|
directory "#{node['askci']['base_dir']}/tools/#{name}" do
owner node['askci']['user']['name']
group node['askci']['group']['name']
mode "0755"
recursive true
action :create
end
end
cookbook_file "#{node['askci']['base_dir']}/.pypirc" do
source "bin/pypi/pypirc"
owner node['askci']['user']['name']
group node['askci']['group']['name']
mode "0644"
end
# pypi scripts
%w{packager promote-to-askprod pypipush}.each do |name|
cookbook_file "#{node['askci']['base_dir']}/tools/pypi/#{name}" do
source "bin/pypi/#{name}"
owner node['askci']['user']['name']
group node['askci']['group']['name']
mode "0755"
end
end
link "#{node['askci']['base_dir']}/tools/nodejs/packager" do
to "/ask/scripts/jenkins/bin/nodejs/packager"
action :create
end
link "#{node['askci']['base_dir']}/tools/nodejs/npm-package-version-update.py" do
to "/ask/scripts/jenkins/bin/nodejs/npm-package-version-update.py"
action :create
end
link "#{node['askci']['base_dir']}/tools/nodejs/npm-package-version-update_with_branch.py" do
to "/ask/scripts/jenkins/bin/nodejs/npm-package-version-update_with_branch.py"
action :create
end
# sync-script for Jenkins slaves
template "#{node['askci']['base_dir']}/tools/sync-slaves.sh" do
source "bin/sync-slaves.sh.erb"
owner node['askci']['user']['name']
group node['askci']['group']['name']
mode "0755"
end
# tram executable scripts
%w{tramBuildMe_env tramBuildMe tramBuildMe_generic promote-service-pack promote-service-pack_env}.each do |name|
cookbook_file "#{node['askci']['base_dir']}/tools/tram/#{name}" do
source "bin/tram/#{name}"
owner node['askci']['user']['name']
group node['askci']['group']['name']
mode "0755"
end
end
# tram python scripts
%w{tramDependencies.py tramName.py tramParseJson.py tramUpdateJson.py tramUpdateJson_generic.py tramUtils.py}.each do |name|
cookbook_file "#{node['askci']['base_dir']}/tools/tram/#{name}" do
source "bin/tram/#{name}"
owner node['askci']['user']['name']
group node['askci']['group']['name']
mode "0644"
end
end
# sem executable scripts
%w{sem-tools-nightly-automation}.each do |name|
cookbook_file "#{node['askci']['base_dir']}/tools/sem/#{name}" do
source "bin/sem/#{name}"
owner node['askci']['user']['name']
group node['askci']['group']['name']
mode "0755"
end
end
template "#{node['askci']['base_dir']}/tools/trigger-promotion.py" do
source "bin/sem/trigger-promotion.py.erb"
owner node['askci']['user']['name']
group node['askci']['group']['name']
mode "0644"
end
# Setting up promote-outside-npm-packages symlink to support existing scripts
link "#{node['askci']['base_dir']}/tools/promote-outside-npm-packages" do
to "#{node['askci']['base_dir']}/tools/promote-outside-npm-packages.rb"
action :create
end
# Setting up git-tag symlink to support older versions
link "#{node['askci']['base_dir']}/tools/git-tag" do
to "#{node['askci']['base_dir']}/tools/git-tag.rb"
action :create
end
# Setting up git config
cookbook_file "#{node['askci']['user']['home']}/.gitconfig" do
owner node['askci']['user']['name']
group node['askci']['group']['name']
mode "0664"
source "gitconfig"
end
# Setting up ssh config
cookbook_file "#{node['askci']['user']['home']}/.ssh/config" do
owner node['askci']['user']['name']
group node['askci']['group']['name']
mode "0644"
source "ssh_config"
end
if not node['kernel']['machine'].eql?("i686")
include_recipe "ask-commons::grails"
link "#{node['askci']['software_dir']}/grails" do
to "#{node['askci']['software_dir']}/grails-#{node['ask_commons']['grails']['version']}"
end
include_recipe "ask-commons::nodejs"
link "#{node['askci']['software_dir']}/nodejs" do
to "#{node['askci']['software_dir']}/nodejs-#{node['ask_commons']['nodejs']['version']}"
end
link "#{node['nodejs']['path']['node']}" do
to "#{node['askci']['software_dir']}/nodejs/bin/node"
end
execute "bower" do
command "#{node['askci']['software_dir']}/nodejs/bin/npm install -g bower@#{node['askci']['bower']['version']} --verbose"
cwd "#{node['askci']['software_dir']}"
not_if "test -d #{node['askci']['software_dir']}/nodejs/lib/node_modules/bower"
end
execute "grunt-cli" do
command "#{node['askci']['software_dir']}/nodejs/bin/npm install -g grunt-cli@#{node['askci']['grunt-cli']['version']}"
cwd "#{node['askci']['software_dir']}"
not_if "test -d #{node['askci']['software_dir']}/nodejs/lib/node_modules/grunt-cli"
end
execute "gulp" do
command "#{node['askci']['software_dir']}/nodejs/bin/npm install -g gulp@#{node['askci']['gulp']['version']}"
cwd "#{node['askci']['software_dir']}"
not_if "test -d #{node['askci']['software_dir']}/nodejs/lib/node_modules/gulp"
end
execute "phantomjs" do
command "#{node['askci']['software_dir']}/nodejs/bin/npm install -g phantomjs@#{node['askci']['phantomjs']['version']}"
not_if "test -d #{node['askci']['software_dir']}/nodejs/lib/node_modules/phantomjs"
end
execute "coffee-script" do
command "#{node['askci']['software_dir']}/nodejs/bin/npm install -g coffee-script@#{node['askci']['coffee-script']['version']}"
not_if "test -d #{node['askci']['software_dir']}/nodejs/lib/node_modules/coffee-script"
end
end
case node['platform_version'][0...3]
when '5.4'
yum_packages = {
'make' => '3.81-3.el5',
'gcc-c++' => '4.1.2-46.el5'
}
when '6.1'
yum_packages = {
'make' => '3.81-19.el6',
'gcc-c++' => '4.4.5-6.el6',
'ask-php' => '5.3.23-el6'
}
link "#{node['php']['path']}" do
to "/ask/php/bin/php"
end
when '6.4'
yum_packages = {
'make' => '3.81-20.el6',
'gcc-c++' => '4.4.7-3.el6',
'php' => '5.3.3-22.el6',
'php-xml' => '5.3.3-22.el6'
}
when '7.0'
yum_packages = {
'make' => '3.82-21.el7',
'gcc-c++' => '4.8.2-16.el7',
'php' => '5.4.16-21.el7',
'php-xml' => '5.4.16-21.el7'
}
when '7.1'
yum_packages = {
'make' => '3.82-21.el7',
'gcc-c++' => '4.8.3-9.el7',
'php' => '5.6.19-1.el7.remi',
'php-xml' => '5.6.19-1.el7.remi'
}
when '7.2'
yum_packages = {
'make' => '3.82-21.el7',
'gcc-c++' => '4.8.5-4.el7',
'php' => '5.6.19-1.el7.remi',
'php-xml' => '5.6.19-1.el7.remi'
}
end
yum_packages.each do |k,v|
package k do
version v
action :install
end
end
################################
# INSTALL COMPOSER IN SL 6.1, 6.4 & Centos 7.1 slaves
################################
if node.platform_version.start_with?('6') or node.platform_version.start_with?('7')
remote_file "#{node['php']['composer']}" do
source "#{node['askci']['thirdparty_binary_repo']}/composer/1.2.0/composer.phar"
owner 'root'
group 'root'
mode '0755'
action :create
end
end
################################
# Dependencies for compass gem #
################################
if node.platform_version.start_with?('6') or node.platform_version.start_with?('7')
execute "install-sass-gem-3.1.0" do
command "gem install sass -v 3.1.0"
not_if "gem list | grep '^sass .*[( ]3.1.0[,)]'"
end
execute "install-sass-gem-3.2.13" do
command "gem install sass -v 3.2.13"
not_if "gem list | grep '^sass .*[( ]3.2.13[,)]'"
end
execute "install-sass-gem-3.4.13" do
command "gem install sass -v 3.4.13"
not_if "gem list | grep '^sass .*[( ]3.4.13[,)]'"
end
execute "install-fssm-gem-0.2.7" do
command "gem install fssm -v 0.2.7"
not_if "gem list | grep '^fssm .*[( ]0.2.7[,)]'"
end
execute "install-chunky_png-gem-1.2" do
command "gem install chunky_png -v 1.2"
not_if "gem list | grep '^chunky_png .*[( ]1.2.0[,)]'"
end
execute "install-compass-gem-0.12.2" do
command "gem install compass -v 0.12.2"
not_if "gem list | grep '^compass .*[( ]0.12.2[,)]'"
end
end
if node.platform_version.start_with?('6') # version 1.0.3 of compass does not install on AskOS 7
execute "install-compass-gem-1.0.3" do
command "gem install compass -v 1.0.3"
not_if "gem list | grep '^compass .*[( ]1.0.3[,)]'"
end
end
################################
include_recipe "ask-commons::play"
link "#{node['askci']['software_dir']}/play" do
to "#{node['askci']['software_dir']}/play-#{node['ask_commons']['play']['version']}"
end
# Install gradle and create symlink to the latest version
ark "gradle-#{node['gradle']['version']}" do
url "#{node['askci']['thirdparty_binary_repo']}/gradle/#{node['gradle']['version']}/gradle-#{node['gradle']['version']}.tar.gz"
version node['gradle']['version']
path node['askci']['software_dir']
owner node['askci']['user']['name']
action :put
end
link "#{node['askci']['software_dir']}/gradle" do
to "#{node['askci']['software_dir']}/gradle-#{node['gradle']['version']}"
action :create
end
# Install multiple versions of java, Add version => sha256sum to the map. JDK depends on architecture 32/64
jdk_map={}
if node['kernel']['machine'].eql?("x86_64")
jdk_map={"1.8.0_73" => "46a8149efaf9d87a147b244e503f1d7791ec8abbc35a5011c99ed909edb2e3e6", "1.8.0_66" => "537797c9023ef486364b04320b8959b22dd2306b6f5cb0b89ed5d52b0ad63245", "1.8.0_60" => "ff46fd25523b7f6aa6f324e93b713e95e9f23265b8c36225b1bf48effaf88e86", "1.8.0_45" => "f298ca9239051dfddf8642fcc9e264f7fe5af10adb67027feb3a0ed0a1a2316d", "1.8.0_31" => "efe015e8402064bce298160538aa1c18470b78603257784ec6cd07ddfa98e437", "1.8.0_20" => "803930bb61bf86f70b28a5b443fdf9f59e6bee7d2bdf445dfba0e3ca04dbc9e4", "1.7.0_21" => "089857fc542f47fda8b04f7d68863e190560d7ae3143e99a321a78f3b003ce98", "1.7.0_25" => "f80dff0e19ca8d038cf7fe3aaa89538496b80950f4d10ff5f457988ae159b2a6", "1.6.0_35" => "e3ab5385c2fecbd578f92fa40718cef4fd5ef93c54f4478d68d3d05060a3810b", "1.6.0_26" => "8840a23def518640defac6bc2029e552e16bc9cb95dafd05bc08a9206a90950e", "1.6.0_21" => "1891b21d6af656dd7801f70d9d168c60186d911ac75f6aba25b6fb7e1f8fa5cc"}
jdk_map.each do |k,v|
ark "jdk-#{k}" do
url "#{node['askci']['thirdparty_binary_repo']}/jdk/#{k}/jdk#{k}.tar.gz"
version k
path node['askci']['software_dir']
checksum v
owner node['askci']['user']['name']
action :put
end
end
link "#{node['askci']['software_dir']}/java" do
to "#{node['askci']['software_dir']}/jdk-#{node['askci']['jdk_latest']}"
end
else
jdk_map={"1.6.0_35" => "45556fee70e6038de2977079ff7f6e85275ab7288563b5fd33086ce346ca64e3", "1.6.0_21" => "1891b21d6af656dd7801f70d9d168c60186d911ac75f6aba25b6fb7e1f8fa5cc"}
jdk_map.each do |k,v|
ark "jdk-#{k}" do
url "#{node['askci']['thirdparty_binary_repo']}/jdk/#{k}/jdk#{k}_x86.tar.gz"
version k
path node['askci']['software_dir']
checksum v
owner node['askci']['user']['name']
action :put
end
end
link "#{node['askci']['software_dir']}/java" do
to "#{node['askci']['software_dir']}/jdk-1.6.0_35"
end
end
{"2.5.2" => "0bdb4850a3825208fc97fd869fb2a4e5b7ad1b49f153d21b75c2da1ad5016b43"}.each do |k,v|
ark "hadoop-#{k}" do
url "#{node['askci']['thirdparty_binary_repo']}/hadoop/#{k}/hadoop-#{k}.tar.gz"
version k
path node['askci']['software_dir']
checksum v
owner node['askci']['user']['name']
action :put
end
end
link "#{node['askci']['software_dir']}/hadoop" do
to "#{node['askci']['software_dir']}/hadoop-#{node['askci']['hadoop_latest']}"
end
# Install multiple versions of maven. Add version => sha256sum to the map
{"3.3.3" => "3a8dc4a12ab9f3607a1a2097bbab0150c947ad6719d8f1bb6d5b47d0fb0c4779", "3.2.1" => "cdee2fd50b2b4e34e2d67d01ab2018b051542ee759c07354dd7aed6f4f71675c", "3.0.4" => "d35a876034c08cb7e20ea2fbcf168bcad4dff5801abad82d48055517513faa2f", "2.2.1" => "b9a36559486a862abfc7fb2064fd1429f20333caae95ac51215d06d72c02d376"}.each do |k,v|
ark "maven-#{k}" do
url "#{node['askci']['thirdparty_binary_repo']}/maven/#{k}/apache-maven-#{k}-bin.tar.gz"
version k
path node['askci']['software_dir']
checksum v
owner node['askci']['user']['name']
action :put
end
end
link "#{node['askci']['software_dir']}/maven" do
to "#{node['askci']['software_dir']}/maven-#{node['askci']['maven_latest']}"
end
ark "groovy-http-builder" do
url "#{node['askci']['thirdparty_binary_repo']}/http-builder/0.6/http-builder-0.6-all.tar.gz"
version "0.6"
path node['askci']['software_dir']
checksum "210329995e09a57758de0bb0d453f87a657c8a8de99e11df0486d52b7d5d9c50"
owner node['askci']['user']['name']
action :put
end
ark "jira-cli" do
url "#{node['askci']['thirdparty_binary_repo']}/jira-cli/2.7.0/jira-cli-2.7.0.tar.gz"
version "2.7.0"
path node['askci']['software_dir']
checksum "bed7641b2bb0bd6a943cf823122c03da256346439c6f65bd87c3dc6317d39ac8"
owner node['askci']['user']['name']
action :put
end
cookbook_file "#{node['askci']['software_dir']}/jira-cli/jira.sh" do
owner node['askci']['user']['name']
group node['askci']['group']['name']
mode "0755"
source "jira.sh"
end
cookbook_file "#{node['askci']['user']['home']}/.m2/settings.xml" do
owner node['askci']['user']['name']
group node['askci']['group']['name']
source "m2/settings.xml"
end
{"1.9.6" => "90d<KEY>", "1.8.2" => "<KEY>9<KEY>"}.each do |k,v|
ark "ant-#{k}" do
url "#{node['askci']['thirdparty_binary_repo']}/apache-ant/#{k}/apache-ant-#{k}-bin.tar.gz"
version k
path node['askci']['software_dir']
checksum v
owner node['askci']['user']['name']
action :put
end
end
link "#{node['askci']['software_dir']}/ant" do
to "#{node['askci']['software_dir']}/ant-#{node['askci']['ant_latest']}"
end
{"4.6.0" => "<KEY>", "6.6.0" => "fdf4377ea4dc9ba2f09d81d9ad1eae42e7eb8<KEY>", "6.3.0" => "d26c09fc95ebb457b79fcb0a2890fe8417b2c04f4016dadf2d165c0<KEY>", "4.2.3" => "644d4c0b206ebcb75383fbe42f6025e7253a61992816289359d0f4dcdb6087d7", "0.12.7" => "6a2b3077f293d17e2a1e6dba0297f761c9e981c255a2c82f329d4173acf9b9d5", "0.12.0" => "3bdb7267ca7ee24ac59c54ae146741f70a6ae3a8a8afd42d06204647fe9d4206", "0.10.40" => "0bb15c00fc4668ce3dc1a70a84b80b1aaaaea61ad7efe05dd4eb91165620a17e", "0.10.45" => "54d095d12b6227460f08ec81e50f9db930ec51fa05af1b7722fa85bd2cabb5d7","0.10.46" => "58116256f3060703e2e71f2cb5dc265a1d9fab7854a4eee15e78a95a0a87c750", "0.10.38" => "d0f5771c3adefa4a3c1718206521c603526a3b67d5b1b66abd2e155d0fb77f5e", "0.10.33" => "<KEY>", "0.10.30" => "173d2b9ba4cbfb45a2472029f2904f965081498381a34d01b3889a850238de2b", "0.10.24" => "6ef93f4a5b53cdd4471786dfc488ba9977cb3944285ed233f70c508b50f0cb5f"}.each do |k,v|
ark "nodejs-#{k}" do
url "#{node['askci']['thirdparty_binary_repo']}/nodejs/#{k}/node-v#{k}-linux-x64.tar.gz"
version k
path node['askci']['software_dir']
checksum v
owner node['askci']['user']['name']
action :put
end
end
link "#{node['askci']['software_dir']}/nodejs" do
to "#{node['askci']['software_dir']}/nodejs-#{node['ask_commons']['nodejs']['version']}"
end
{"0.12.1" => "<KEY>", "0.12.2" => "83b20e2ed0bee02ebfc53a58222494d88c18b0470e9b975fc045ce9234f18ef9", "0.12.3" => "464effc8e4aff6c59acb6ac176634b2d72ef7e70ee2a9cd7b734b0c4dcefb5df"}.each do |k,v|
ark "sbt-#{k}" do
url "#{node['askci']['thirdparty_binary_repo']}/sbt/#{k}/sbt-#{k}.tgz"
version k
path node['askci']['software_dir']
checksum v
owner node['askci']['user']['name']
action :put
end
end
link "#{node['askci']['software_dir']}/sbt" do
to "#{node['askci']['software_dir']}/sbt-#{node['askci']['sbt_latest']}"
end
include_recipe "ask-commons::drush"
cookbook_file "#{node['askci']['user']['home']}/.bash_profile" do
owner node['askci']['user']['name']
group node['askci']['group']['name']
mode "0644"
source "bash_profile"
end
template "#{node['askci']['user']['home']}/.bashrc" do
owner node['askci']['user']['name']
group node['askci']['group']['name']
mode "0644"
source "bashrc.erb"
end
case node['fqdn']
when node['askci']['primary']
puts "sudoers.local template will be picked up from dev-depot"
when node['askci']['secondary']
puts "sudoers.local template will be picked up from dev-depot"
else
template "/etc/sudoers.local" do
owner "root"
group "root"
mode "440"
source "sudoers.local.erb"
end
end
cookbook_file "#{node['askci']['user']['home']}/.ivy2/.credentials" do
owner node['askci']['user']['name']
group node['askci']['group']['name']
mode "0644"
source "ivy/sbt-publishing-credentials"
end
############ Back porting ########################
#link "#{node['askci']['user']['home']}/software" do
# to "#{node['askci']['software_dir']}"
#end
# Create ${home}/jenkins/bin
directory "#{node['askci']['user']['home']}/jenkins" do
owner node['askci']['user']['name']
group node['askci']['group']['name']
mode "0755"
action :create
end
link "#{node['askci']['user']['home']}/jenkins/bin" do
to "#{node['askci']['base_dir']}/tools/"
end
############ Back porting ########################
<file_sep>/recipes/koji.rb
#
# Cookbook Name:: askci
# Recipe:: koji
#
# Copyright 2013, Ask.com
#
# All rights reserved - Do Not Redistribute
#
############################################
# koji configuration
############################################
cookbook_file "/etc/koji.conf" do
owner "root"
group "root"
mode "0644"
source "koji/koji.conf"
end
directory "#{node['askci']['user']['home']}/.koji/" do
owner node['askci']['user']['name']
group node['askci']['group']['name']
mode "0755"
end
%w{client.crt clientca.crt serverca.crt}.each do |name|
cookbook_file "#{node['askci']['user']['home']}/.koji/#{name}" do
owner node['askci']['user']['name']
group node['askci']['group']['name']
mode "0644"
source "koji/#{name}"
end
end
<file_sep>/recipes/slave.rb
#
# Cookbook Name:: askci
# Recipe:: slave
#
include_recipe 'askci::users-groups'
%w{#{node['askci']['base_dir']} #{node['askci']['base_dir']}/data #{node['askci']['base_dir']}/logs}.each do |dir|
directory "#{dir}" do
owner node['askci']['user']['name']
group node['askci']['group']['name']
action :create
end
end
link "/data" do
to "/ask"
end
include_recipe "askci::common"
case node['platform']
when "macos"
include_recipe "askci::buildtools-mac"
else
include_recipe "askci::buildtools-#{node['platform']}"
end
cookbook_file "#{node['askci']['user']['home']}/.ssh/authorized_keys" do
owner node['askci']['user']['name']
group node['askci']['group']['name']
source "slave_authorized_keys"
mode "0600"
action :create
end
cookbook_file "#{node['askci']['user']['home']}/.ssh/id_dsa" do
owner node['askci']['user']['name']
group node['askci']['group']['name']
source "master_pvk"
mode "0400"
action :create
end
template "#{node['askci']['user']['home']}/setup_ssh_known_hosts" do
owner node['askci']['user']['name']
group node['askci']['group']['name']
source "setup_ssh_known_hosts"
mode "0755"
action :create
end
template "#{node['askci']['user']['home']}/ci_scripts.config" do
owner node['askci']['user']['name']
group node['askci']['group']['name']
source "ci_scripts.erb"
mode "0755"
action :create
end
execute "setup_ssh_know_hosts" do
command "su - builder sh -c #{node['askci']['user']['home']}/setup_ssh_known_hosts"
end
ark "scripts-#{node['appversion']['askci-slave']['version']}" do
url node['askci-slave']['artifact']
path '/ask'
owner 'builder'
group 'builder'
version node['askci-slave']['version']
action :put
end
link "/ask/scripts" do
to "/ask/scripts-#{node['appversion']['askci-slave']['version']}"
end
case node['platform_version']
when "6.1"
node.set['python']['version'] = "2.7.6"
node.set['python']['install_method'] = 'source'
node.set['python']['prefix_dir'] = "/ask/Python-#{node['python']['version']}"
node.set['python']['binary'] = "#{node['python']['prefix_dir']}/bin/python"
node.set['python']['pip_location'] = "#{node['python']['prefix_dir']}/bin/pip"
## REL-2995 Installing Python 2.7 on SL6.1 OS
install_pip_virtualenv 'install' do
install_method 'source'
python_binary '/ask/Python-2.7.6/bin/python'
pip_location '/ask/Python-2.7.6/bin/pip'
python_prefix_dir '/ask/Python-2.7.6'
end
link "/ask/builder/askci/software/Python-2.7.6" do
to "/ask/Python-2.7.6"
end
when "6.4"
include_recipe 'askci::multi_python'
%w{2.7.6 2.7.8}.each do |name|
link "/ask/builder/askci/software/Python-#{name}" do
to "/ask/Python-#{name}"
end
end
when "7.1.1503"
yum_base_url = "http://#{node['reyumserver']}/yum/el7.1/#{node['kernel']['machine']}"
%w{2.7.8-2.el7.centos}.each do |ver|
ask_rpm_package 'ask-python' do
packagename yum_base_url + '/ask-python-' + ver + '.x86_64.rpm'
action :install
end
end
node.set['python']['version'] = "2.7.8"
node.set['python']['install_method'] = 'source'
node.set['python']['prefix_dir'] = "/ask/Python-#{node['python']['version']}"
node.set['python']['binary'] = "#{node['python']['prefix_dir']}/bin/python"
node.set['python']['pip_location'] = "#{node['python']['prefix_dir']}/bin/pip"
## REL-2995 Installing Python 2.7 on SL7.1 OS
install_pip_virtualenv 'install' do
install_method 'source'
python_binary '/ask/Python-2.7.8/bin/python'
pip_location '/ask/Python-2.7.8/bin/pip'
python_prefix_dir '/ask/Python-2.7.8'
end
link "/ask/builder/askci/software/Python-2.7.8" do
to "/ask/Python-2.7.8"
end
end
if node.platform_version.start_with? ("6")
## REL-2995 Adding blas-devel and lapack-devel needed for tram cp_detector service pack testing
yum_package "blas-devel" do
version node['askci']['blas']['version']
action :install
end
yum_package "lapack-devel" do
version node['askci']['lapack']['version']
action :install
end
%w{graphviz perl-CPAN}.each do |package|
yum_package package do
action :install
end
end
execute "Installing Perl Test" do
command "perl -MCPAN -e 'install Test::More'"
end
execute "Installing Perl JSON" do
command "perl -MCPAN -e 'install JSON::Parse'"
end
end
<file_sep>/metadata.rb
name 'askci'
maintainer '<EMAIL>'
maintainer_email '<EMAIL>'
license 'All rights reserved'
description 'Installs/Configures askci'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '3.2.BUILD_NUMBER'
depends 're-tools', '= 0.0.16'
depends 'ask-commons', '= 3.0.8'
supports 'centos', '= 5.4'
supports 'scientific', '= 6.1'
supports 'scientific', '= 6.4'
supports 'centos', '= 7.0'
supports 'centos', '= 7.1'
supports 'centos', '= 7.2'
<file_sep>/files/default/bin/npm-packages.py
import commands
import json
import os
import datetime
def updatePackageJson():
f = open("package.json", "r")
data = json.loads(f.read())
data["_shasum"] = os.getenv("GIT_COMMIT")
f = open("version.txt", "w")
f.write("%s-build%s" %(data["version"], os.getenv("BUILD_NUMBER")))
f.close()
data["version"] = "%s-build%s" %(data["version"], os.getenv("BUILD_NUMBER"))
data["_buildTime"] = datetime.datetime.now().strftime("%Y-%m-%d.%H:%M")
with open('package.json', 'w') as outfile:
json.dump(data, outfile, sort_keys = True, indent = 4, ensure_ascii=False)
f.close()
def uploadPackageDependencies():
if not os.path.exists("npm-shrinkwrap.json"):
raise "Shrink wrap json doesnt exist"
f = open("npm-shrinkwrap.json", "r")
data = json.loads(f.read())
f.close()
_dependencyParser(data['dependencies'])
def _dependencyParser(dependencies):
for package_name, package_detail in dependencies.items():
package_version = package_detail['version']
# Call the shell script here to push the dependency
# promote-npm-packages $package_name $package_version prod 0
print package_name, package_version
if package_detail.has_key('dependencies'):
_dependencyParser(package_detail['dependencies'])
uploadPackageDependencies()
<file_sep>/files/default/bin/replication-status
#!/bin/bash
ping -c 1 npmstore.ask.com > temp
PRIMARY=$(cat temp | head -1 | awk -F "PING " '{print $2}' | awk '{print $1}')
if [ $PRIMARY == "npmstore001iad.io.askjeeves.info" ]; then
SECONDRY=npmstore001las.io.askjeeves.info
else
SECONDRY=npmstore001iad.io.askjeeves.info
fi
#echo "Checking replication status for $PRIMARY"
#curl http://builder:builder\@$PRIMARY:5984/_active_tasks > temp
#if [[ $(cat temp) != *replication* ]]; then
# echo "Replication has stopped, starting replication"
# curl -X POST http://builder:builder\@$PRIMARY:5984/_replicate -d '{"source":"http://isaacs.iriscouch.com/registry/", "target":"registry", "continuous":true,"create_target":true}' -H "Content-Type: application/json"
#else
# echo "All is good on primary $PRIMARY"
#fi
#rm -f temp
echo "Checking replication status for $SECONDRY"
curl http://builder:builder\@$SECONDRY:5984/_active_tasks > temp
if [[ $(cat temp) != *replication* ]]; then
echo "Replication has stopped, starting replication"
curl -X POST http://builder:builder\@$SECONDRY:5984/_replicate -d '{"source":"http://npmstore.ask.com/registry", "target":"registry", "continuous":true,"create_target":true}' -H "Content-Type: application/json"
else
echo "All is good on secondry $SECONDRY"
fi
rm -f temp
<file_sep>/files/default/bin/tram/tramBuildMe_env
#!/bin/bash
set -x
PACKAGER_DIR=`dirname $0`
# Commenting this out as this condition is not appropriate as package_directory would be /ask/builder/askci/jenkins/bin
#if [ $PACKAGER_DIR == "packager" ]; then
# PACKAGER_DIR=$PWD/packager
#fi
if [ -z $BUILD_NUMBER ]; then
BUILD_NUMBER=$USER
fi
SRC_DIR=${WORKSPACE}
TMP_DIR=$SRC_DIR/tmp
BUILD_DIR=$SRC_DIR/build
PRODUCT_NAME=`python $PACKAGER_DIR/tramName.py $SRC_DIR/run.json`
# Initialize Array and insert them as Array elements
array=()
while IFS= read -r -d $'\0'; do
array+=("$REPLY")
done < <(find $SRC_DIR -type f -maxdepth 1 -name "run.json*" -print0)
die() {
echo "ERROR: $1"
exit 1
}
clean() {
rm -rf $BUILD_DIR
rm -rf $SRC_DIR/run.json.bkup
rm -rf $TMP_DIR
}
package() {
for i in "${array[@]}"
do
env_name=`echo $i| cut -d'/' -f8|cut -d'.' -f3`
if [ -z $env_name ]; then
cp $i $SRC_DIR/run.json.bkup
python $PACKAGER_DIR/tramParseJson.py $i || die "Failed downloading artifacts in $i"
python $PACKAGER_DIR/tramUpdateJson.py $i "http://artifactor.ask.com/~service-packs/${JOB_NAME}/$BUILD_NUMBER/build/${PRODUCT_NAME}.zip"
mkdir -p $BUILD_DIR || die "Failed to create $BUILD_DIR" "$?"
pushd $SRC_DIR
zip -r $PRODUCT_NAME * -x 'packager/*' build/\* run.json.bkup run.json.* tmp/\* || die "Failed to create $SRC_DIR/$PRODUCT_NAME.zip" "$?"
zip -u $PRODUCT_NAME.zip build
popd
mv $i $BUILD_DIR
mv $SRC_DIR/run.json.bkup $SRC_DIR/run.json
mv $SRC_DIR/$PRODUCT_NAME.zip $BUILD_DIR || die "Failed to move $SRC_DIR/$PRODUCT_NAME.zip into $BUILD_DIR"
else
BUILD_DIR_ENV=$BUILD_DIR/$env_name
python $PACKAGER_DIR/tramParseJson.py $i || die "Failed downloading artifacts in $i"
python $PACKAGER_DIR/tramUpdateJson.py $i "http://artifactor.ask.com/~service-packs/${JOB_NAME}/$BUILD_NUMBER/build/$env_name/${PRODUCT_NAME}.zip"
mkdir -p $BUILD_DIR_ENV $TMP_DIR || die "Failed to create $BUILD_DIR_ENV & $TMP_DIR" "$?"
pushd $SRC_DIR
mv run.json $TMP_DIR
mv run.json.$env_name run.json
cp run.json $BUILD_DIR_ENV
zip -r $PRODUCT_NAME * -x 'packager/*' build/\* run.json.* run.json.$env_name.bkup tmp/\* || die "Failed to create $SRC_DIR/$PRODUCT_NAME.zip" "$?"
zip -u $PRODUCT_NAME.zip build
mv run.json run.json.$env_name
mv $TMP_DIR/run.json .
popd
mv $SRC_DIR/$PRODUCT_NAME.zip $BUILD_DIR_ENV || die "Failed to move $SRC_DIR/$PRODUCT_NAME.zip into $BUILD_DIR_ENV"
fi
done
}
createVirtualEnv() {
if [ ! -d ${WORKSPACE}/virtualenv ]
then
mkdir ${WORKSPACE}/virtualenv
fi
/ask/Python-2.7.8/bin/virtualenv ${WORKSPACE}/virtualenv/env
for pymod in `${HOME}/software/python-2.7.6/bin/python $PACKAGER_DIR/tramDependencies.py $SRC_DIR/run.json`
do
${WORKSPACE}/virtualenv/env/bin/pip install $pymod
done
}
executeTest() {
export BLAS=/usr/lib64/libblas.a
export LAPACK=/usr/lib64/liblapack.a
pushd ${WORKSPACE}
virtualenv/env/bin/python -m $testClass || die "Python tests failed" "$?"
popd
}
while getopts t: opt ; do
case $opt in
t) testClass=$OPTARG;
;;
esac
done
clean
package
if [ "$testClass" != "" ]
then
createVirtualEnv
executeTest
fi
<file_sep>/files/default/bin/jenkins
#!/bin/bash
export APP_HOME=${HOME}/jenkins
ulimit -n 4096
export JAVA_OPTS="-Xms1024m -Xmx2048m -XX:MaxPermSize=256m"
help () {
echo "./jenkins [ start | stop | help ]"
}
case $@ in
"start")
if [ -e ${APP_HOME}/current.pid ]; then
echo "Jenkins is already running with PID `cat ${APP_HOME}/current.pid`"
else
java $JAVA_OPTS -jar ${APP_HOME}/war/jenkins.war >> ${APP_HOME}/log/stdout.log 2>&1 &
echo $! > ${APP_HOME}/current.pid
echo "Fired up Jenkins"
fi
;;
"stop")
if [ -e ${APP_HOME}/current.pid ]; then
kill `cat ${APP_HOME}/current.pid`
rm ${APP_HOME}/current.pid
fi
echo "Jenkins has been shutdown"
;;
*)
help
;;
esac
<file_sep>/files/default/bin/git-details.py
import sys
import os
import time
def createEntries(location):
try:
os.remove(os.path.join(location, "git.properties"))
except:
pass
f = open (os.path.join(location, "git.properties"), "w")
lines = "git.branch = %s\n" %os.getenv("GIT_BRANCH")
lines += "git.build.user.name = Release Engineering\n"
lines += "git.build.user.email = <EMAIL>\n"
lines += "git.build.time = %s\n" %time.strftime("%m.%d.%Y @ %H.%M.%S %Z")
lines += "git.commit.id = %s\n" %os.getenv("GIT_COMMIT")
lines += "git.commit.id.abbrev = %s\n" %os.getenv("GIT_COMMIT")[:7]
lines += "git.commit.user.name = %s\n" %os.getenv("GIT_COMMIT_USER_NAME")
lines += "git.commit.user.email = %s\n" %os.getenv("GIT_COMMIT_USER_EMAIL")
lines += "git.commit.message.full = %s\n" %os.getenv("GIT_COMMIT_MESSAGE")
lines += "git.commit.message.short = %s\n" %os.getenv("GIT_COMMIT_MESSAGE")
lines += "git.commit.time = %s\n" %os.getenv("GIT_COMMIT_TIME")
f.writelines(lines)
f.close()
if __name__ == '__main__':
if len(sys.argv) != 2:
print "Usage: python git-details.py <location>"
sys.exit(1)
createEntries(sys.argv[1])
<file_sep>/files/default/bin/sem/install-pip-dependencies.rb
pip_packages = {
"google-api-python-client" => "1.2",
"hive-thrift-py" => "0.0.1",
"hive-utils" => "0.0.1",
"httplib2" => "0.8",
"oauth2client" => "1.2",
"py2app" => "0.7.1",
"python-dateutil" => "1.5",
"python-gflags" => "2.0",
"mechanize" => "0.2.5",
"googleads" => "3.4.0",
"argparse" =>"1.2.1",
"unidecode" =>"0.04.16",
"snakebite" => "1.3.9",
"requests" => "2.7.0",
"psycopg2" => "2.6.1",
"pycurl" => "7.19.5.3",
"paramiko" => "1.15.2",
"futures" => "3.0.3",
"Cheetah" => "2.4.4",
"thrift" => "0.9.1",
"BeautifulSoup" => "3.2.1",
"html" => "1.16",
"http" => "0.02",
"poster" => "0.8.1",
"simplejson" => "3.6.5",
"bingads" => "10.4.5",
"boto3" => "1.3.1",
"snowflake-connector-python" => "1.2.7",
"pybloom" => "1.1"
}
pip_packages.each do |pip_name,pip_version|
`${WORKSPACE}/virtualenv/env/bin/pip install #{pip_name}==#{pip_version}`
end<file_sep>/files/default/bin/npm-package-builder_with_branch
#!/bin/bash
usage() { echo $@; echo "Usage: $0 [-n <module_name>] [-t test] [-a asset]" 1>&2; exit 1; }
test=""
run_script=""
while getopts ":n:t:a:b:" o; do
case "${o}" in
n)
module_name=${OPTARG}
;;
t)
test=${OPTARG}
;;
a)
build_assets=${OPTARG}
;;
b)
build_bower=${OPTARG}
;;
*)
usage
;;
esac
done
shift $((OPTIND-1))
set -x
BUILD_DIR=$module_name
PRODUCT_NAME=$module_name
TEST=$test
BUILD_ASSETS=$build_assets
BUILD_BOWER=$build_bower
die() {
echo "ERROR: $1"
exit 1
}
clean() {
rm -rf $BUILD_DIR || die "Could not remove build directory" "$?"
rm -rf development production node_modules $module_name
rm "version.txt"
}
init() {
python ~/jenkins/bin/nodejs/npm-package-version-update_with_branch.py
export VERSION_NUMBER=`cat version.txt`
mkdir -p $BUILD_DIR || die "Could not create build directory" "$?"
}
install() {
#Install the npm package and run the test
#npm cache clean --cache=$WORKSPACE/.npm -verbose || die "Could not clean npm cache" "$?"
#npm install --registry=http://npmstore.ask.com/registry --cache=$WORKSPACE/.npm -verbose || die "Could not install $PRODUCT_NAME" "$?"
{
#npm install --registry=http://npmstore.ask.com/registry --cache=$WORKSPACE/.npm -verbose || die "Could not install $PRODUCT_NAME" "$?"
npm install --registry=http://npmstore.ask.com/registry --cache=/ask/builder/askci/.npm
} || {
npm install --registry=https://registry.npmjs.org --cache=/ask/builder/askci/.npm
}
if [[ ! -z "$TEST" ]]; then
if [[ "$TEST" = 'test' ]]; then
npm test -verbose || die "Test failed for $PRODUCT_NAME" "$?"
else
node $TEST || die "Test failed for $PRODUCT_NAME" "$?"
fi
fi
if [[ "$BUILD_ASSETS" = 'true' ]]; then
npm install grunt@latest --registry=http://npmstore.ask.com/registry --cache=/ask/builder/askci/.npm -verbose || die "Could not install grunt" "$?"
if [[ "$BUILD_BOWER" = 'true' ]]; then
bower install || die "Could not install client-side components by bower" "$?"
fi
npm run-script build || die "Could not build assets" "$?"
fi
echo "Removing npm cache and node_modules directories"
rm -rf $WORKSPACE/.npm $WORKSPACE/node_modules $WORKSPACE/.git $WORKSPACE/.gitignore
}
package() {
#FILE_LIST=`ls | egrep -v -x ".npm|node_modules|packager|$BUILD_DIR|version.txt|npm-debug.log|.gitignore|.git|cookbooks"`
FILE_LIST=`ls -A | egrep -v -x ".npm|node_modules|packager|$BUILD_DIR|version.txt|npm-debug.log|.gitignore|.git|cookbooks"`
echo $FILE_LIST
for name in $FILE_LIST
do
cp -pr $name $BUILD_DIR || die "File copy failed" "$?"
done
tar cvf - $BUILD_DIR | gzip -9 > $PRODUCT_NAME-$(cat version.txt).tgz
mv $PRODUCT_NAME-$VERSION_NUMBER.tgz $BUILD_DIR
}
clean
init
install
package
<file_sep>/files/default/bin/tram/tramUpdateJson_generic.py
import sys
import json
def updateJson(filetoupdate, url, service_name, service_type):
jsonFile = open(filetoupdate, "r")
data = json.load(jsonFile)
jsonFile.close()
data["production_artifact_url"] = url
data["name"] = service_name+"_detector"
data["services"][0]["Name"] = service_name+"_detector"
data["services"][0]["service-type"] = service_type
jsonFile = open(filetoupdate, "w+")
jsonFile.write(json.dumps(data))
jsonFile.close()
if __name__ == '__main__':
if len(sys.argv) < 5:
print "Usage: python updatejson.py <json-file-path> <production-artifact-url> <service-name> <service-path>"
else:
updateJson(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
<file_sep>/recipes/users-groups.rb
#
# Cookbook Name:: askci
# Recipe:: users-groups
#
usergroups node['askci']['user']['name'] do
action :create
groups ["#{node['askci']['group']['name']}"]
home node['askci']['base_dir']
end
directory node['askci']['base_dir'] do
owner node['askci']['user']['name']
group node['askci']['group']['name']
recursive true
end
<file_sep>/files/default/bin/git-tag.rb
#!/usr/bin/ruby
#
## This script must be run via the Jenkins Promote plugin #
require 'rexml/document'
include REXML
label = ENV['LABEL']
build_dir = "#{ENV['WORKSPACE']}/build"
job_name = ENV['PROMOTED_JOB_NAME']
if ENV['PROMOTED_GIT_COMMIT'].nil?
sha = ENV['GIT_COMMIT']
else
sha = ENV['PROMOTED_GIT_COMMIT']
end
promotion_type = ENV['JOB_NAME'].split("/").last.downcase
if ( promotion_type == "release candidate" )
message = "Release candidate #{label}"
else
message = "Production release #{label}"
end
system( "rm -rf #{build_dir}; mkdir -p #{build_dir}/repo;" )
if !ENV['GIT_URL'].nil?
url = ENV['GIT_URL']
else
url = ENV['PROMOTED_GIT_URL']
end
puts "Tagging #{url} (#{sha}) as #{label}"
if system( "cd #{build_dir}; git clone #{url} repo; cd repo; git checkout #{sha}; git tag -a -f \"#{label}\" -m \"#{message}\";" )
system( "cd #{build_dir}/repo; git push --tags" )
system( "rm -rf #{build_dir}" )
else
exit(1)
end
<file_sep>/CHANGELOG.md
# CHANGELOG for askci
##
* [Kalai Muthusamy] - DTOOLS-448 :Modify TRAM build/promotion job for qts
##
* [Kalai Muthusamy] - DTOOLS-467: Added Nodejs 4.6.0 in all Jenkins slaves
##
* [Kalai Muthusamy] - DTOOLS-418: Added tram qts online staging cluster VIP in TRAM script
##
* [AbdulKareem] - DTOOLS-382: Adding pip install dependencies for sem
##
* [AbdulKareem] - DTOOLS-356: Removed dublin datacenter references as it is deprecated
##
* [Kalai Muthusamy] - DTOOLS-272: Added support for centos-7.0
##
* [AbdulKareem] - DTOOLS-235: Adding support for nodejs 6.6.0
##
* [AbdulKareem] - DTOOLS-134: Adding support for nodejs 0.10.46
##
* [<NAME>] - DTOOLS-134: Updates to build jenkins 7.2 slave
## 3.5
* [Kalai Muthusamy] - DTOOLS-134: Added recipe to install composer for Jenkins slaves SL-6.1 6.4 & 7.1
## 3.4
* [AbdulKareem] - DTOOLS-147: Removed london datacenter references as it is deprecated
## 3.3
* [Kalai Muthusamy] - DTOOLS-128: Added Nodejs 6.2.3 to Jenkins slaves.
## 3.2
* [Kalai Muthusamy] - REL-4997: Purged HKG references from the askci cookbook
## 3.1
* [Kalai Muthusamy] - REL-5004: Updated promote-service-pack to add the new environment for landp
## 3.0
* [<NAME>] - REL-4967: added packager script to cookbook jenkins build and testing.
## 2.0.68
* [Kalle Hoffman] - REL-4841: Changed script to askci-slave in appversion to match role
## 2.0.67
* [Kalai Muthusamy] - REL-4841: Move packager script to scripts repository
## 2.0.66
* [Kalai Muthusamy] - REL-4738: Installing ask-python 2.7.8 on CentOS 7.1
## 2.0.65
* [Saravanan Krishnamoorthy] - REL-4812 Installing the latest jdk version 1.8.0_73
## 2.0.64
* [Saravanan Krishnamoorthy] - REL-4516 Update the recipe to install pychef and argparse python module
## 2.0.63
* [Kalai Muthusamy] - REL-4367 :Updating gcc 4.8.2 from 4.4.7 in gcc_update recipe for SL 6.4 machines(rexbuild605 &rexbuild606)
## 2.0.62
* [Kalle Hoffman] - REL-4440: added RAD_SERVER to ci_scripts.config
* [Kalle Hoffman] - REL-4440: added BASE_DIR to ci_scripts.config
## 2.0.61
* [Kalle Hoffman] - REL-4440: Added scripts deployment from jenkins archive
## 2.0.60
* [Eddie Howe] - REL-4418: Added script to replace promote-to-askprod to allow flexible environment promotions.
## 2.0.59
* [Kalai Muthusamy] - REL-4366: Reverted back to Nodejs 4.2.3 and placed node in the path
## 2.0.58
* [Kalle Hoffman] - REL-4440: Added ci_scripts.config
* [Kalle Hoffman] - REL-4366: Reverted Nodejs 4.2.3
## 2.0.57
* [Kalai Muthusamy] - REL-4366: Added Nodejs 4.2.3 to Jenkins slaves
## 2.0.56
* [Kalle Hoffman] - REL-4385: removed "recursive true" for /data dir creation
* [Kalle Hoffman] - REL-4385: added Perl Test::More
* [Kalle Hoffman] - REL-4385: added not_if test for npm installs
* [Kalle Hoffman] - REL-4385: fixed not_if test for gem installs
## 2.0.55
* [Kalai Muthusamy] - REL-4308: updating TRAM 2.0 promotion urls for L&P
## 2.0.54
* [Kalle Hoffman] - REL-4312: adding graphviz yum package
## 2.0.53
* [Kalai Muthusamy] - REL-4178: Sync script for jenkins staging machines.
## 2.0.52
* [Kalai Muthusamy] - REL-4112: Re-ordering the packager script across all platforms.
## 2.0.51
* [ Kalai Muthusamy ] - REL-4281: Including JDK 1.8u66 for all Jenkins slaves
## 2.0.50
* [ Eddie Howe ] - REL-4235: Multipy checks to make sure pip program exists before attempting to run it on 6.4 nodes.
## 2.0.49
* [ Eddie Howe ] - REL-4235: Added additional driver to allow selenium to handle chrome requests.
## 2.0.47
* [ Eddie Howe ] - REL-4235: Added support for CentOS 7.1 to support new devdepot nodes.
## 2.0.46
* [Kalle Hoffman] - REL-4036: removed dustjs version check
## 2.0.45
* [Saravanan Krishnamoorthy] - REL-3345: Fixed the email template to send Triggered by and git branch.
## 2.0.44
* [Kalle Hoffman] - REL-4036: Deprecated npm-legacy
## 2.0.43
* [Rohan Fernandes] - ZENOSS-1098: Removed ask-python (1.4.6) dependency from metadata.rb (previous commented out by Saravanan Krishnamoorthy)
* [Rohan Fernandes] - ZENOSS-1098: Deprecated sudoers.local from master recipe (which is now pulled from the dev-depot cookbook)
* [Rohan Fernandes] - REL-3345: Updated email template for user and Git branch
## 2.0.42
* [Kalle Hoffman] - REL-4109: Add <EMAIL> to setup_ssh_known_hosts
## 2.0.41
* [Kalle Hoffman] - REL-4182: Add Jenkins disk usage report
## 2.0.40
* [Kalle Hoffman] - REL-4157: Added -T option to packager to tag successful builds.
## 2.0.39
* [Kalai Muthusamy] - REL-4183: Fixed to add yum_packages for different ASKOS
## 2.0.38
* [Saravanan Krishnamoorthy] - REL-4030: Updating the cookbook to install pip and virtualenv for multiple python versions
## 2.0.37
* [Kalle Hoffman] - REL-4109: added ssh -o StrictHostKeyChecking to set up known_hosts
## 2.0.36
* [Kalai Muthusamy] - REL-4109: Fixed to install make and gcc packages during common recipe run
## 2.0.35
* [Rohan Fernandes] REL-4155: Fixed typo in TRAM 2.0 promotion (validation) process
* [Rohan Fernandes] REL-4155: Turned on verbose logging for promotion script
## 2.0.34
* [Kalle Hoffman] - REL-4092: Phase out npm shrinkwrap
* [Kalle Hoffman] - REL-4136: added npm show to verify published package is available
## 2.0.33
* [Kalle Hoffman] - REL-4036: Enabled use of npmall proxy on environments that match /npm-legacy/
## 2.0.32
* [Kalai Muthusamy] - REL-4059: Added maven 3.3.3
* [Kalai Muthusamy] - REL-4059: Added jdk 1.8.0_60
* [Kalai Muthusamy] - REL-4059: Added ant 1.9.6
* [Kalai Muthusamy] - REL-4059: Added nodejs 0.10.38, 0.10.40, 0.12.7 and code block to install various versions of nodejs
* [Kalai Muthusamy] - REL-4059: Added node/npm version to packager script
## 2.0.31
* [Saravanan Krishnamoorthy] - REL-4030: Updated the cookbook to install multiple versions of Python packages side by side
## 2.0.30
* [Kalle Hoffman] - REL-4036: Disabled use of npmall proxy in production
## 2.0.29
* [Rohan Fernandes] - REL-3969: Updated VIPs for TRAM 2.0 staging environment
* [Rohan Fernandes] - REL-3969: Updated TRAM promotion scripts to promote to TRAM 1.0 *and* TRAM 2.0
## 2.0.28
* [Kalai Muthusamy] - REL-3771: Added check for npm ls for both production and development packages
* [Kalai Muthusamy] - Placed these npm-package-version-update_with_branch.py and npm-package-version-update.py scripts under nodejs
* [Kalai Muthusamy] - REL-3828: Changed sha field to _shasum in the npm-package-version-update_with_branch.py and npm-package-version-update.py scripts
* [Kalai Muthusamy] - REL-3771: Updated the packager script to give npm ls fail messgae for each package
## 2.0.27
* [<NAME>] REL-4043: Parameterized NPMstore and NPMall proxy
## 2.0.26
* [Kalai Muthusamy] REL-3839: Temaplatizing trigger-promotion.py script for each environment builder user API token in jenkins
## 2.0.25
* [Kalai Muthusamy] REL-3839: Added scripts for SEM nightly automation
## 2.0.24
* [Rohan Fernandes] REL-3969: Moved all TRAM scripts to their own folder
* [Rohan Fernandes] REL-3969: Updated TRAM service pack promotion script for multiple promotions (supports TRAM 1.0 and 2.0)
## 2.0.23
* [Rohan Fernandes] REL-4019: Support for multiple python virtual environments
## 2.0.22
* [Rohan Fernandes] REL-3982: Updated Python to 2.7.8 on SL 6.4 slaves
* [Rohan Fernandes] REL-3982: Changed ~/jenkins/bin/nodejs/packager to a template
* [Rohan Fernandes] REL-3982: Added pypirc configuration file
* [Rohan Fernandes] REL-3982: Added script to build python packages
* [Rohan Fernandes] REL-3982: Added script to promote python packages
* [Rohan Fernandes] REL-3982: Updated version of Python for tramBuildMe and nodejs/packager
## 2.0.21
* [Kalai Muthusamy] - REL-3771: Created reports folder
* [Kalai Muthusamy] - REL-3771: Added check (and report) for npm ls
## 2.0.20
* [Saravanan Krishnamoorthy] - REL-3929: Installing hadoop
## 2.0.19
* [Rohan Fernandes] - REL-3783: Added wurfl dependency
## 2.0.18:
* [Rohan Fernandes] - OPS-18229: Updated tako recipe
* [Rohan Fernandes] - OPS-18229: Removed old specification default['user1'] for user name/group node['askci']['user']['name']/node['askci']['group']['name']
## 2.0.17:
* [Rohan Fernandes] - REL-3480: Updated re-tools dependency to 0.0.10 (was 0.0.7)
* [Rohan Fernandes] - REL-3480: Updated version of gulpjs to 3.9.0 (was 3.8.6)
* [Rohan Fernandes] - REL-3480: Split buildtools-centos to install separate binaries on CentOS 5.4 vs 7.0
* [Rohan Fernandes] - REL-3480: Updated sass gem install to include version to 3.4.13
* [Rohan Fernandes] - REL-3480: Updated common recipe to install gems for AskOS 7
* [Rohan Fernandes] - REL-3480: Updated compass gem install to include version to 1.0.3 (does not install on AksOS 7)
## 2.0.16:
* REL-3844: updating cookbook to add Zeromq 4.1.2 package for SL 6.4
## 2.0.15:
* REL-3824: updating cookbook to fail gracefully for TRAM service pack
## 2.0.14:
* email-templates directory creation for jelly scripts
* Update to the archie build process (packager script)
## 2.0.13
* REL-3581: Changing the to latest version of jdk to 1.8.0_45
## 2.0.12
* Updated the cookbook not to remove the npm cahe before staging a build
## 2.0.11
* Fixing the ownership for .jenkins directory
* Bumped up the JVM memory
## 2.0.10
* REL-3434: Create new nodejs packaging script which would archive tar for development and production
* REL-3381: Created new directory .jenkins/email_template to drop jelly template files
* REL-3427: Migrate Koji from OAK to IAD
* REL-3492: Add coffee-script binary for nodejs
* REL-3329: Adding JMX_OPTS to JAVA_OPTS to monitor heap usage through zenoss
## 2.0.9
* REL-3422: modify the npm publish script to publish tarball instead of folder on all Jenkins jobs
* REL-3488: debug production npm publish scrip to run prepublish before pushing it to the stores
* REL-2477: updated outside npm pull to recursively pull the dependencies for module requested
## 2.0.8
* REL-3330: Update builder GID and chaging the group of data and logs to builder group in all jenkins slave
## 2.0.7:
* REL-3096: Updated slave recipe to have node tmp folder under the user builder instead of /tmp
## 2.0.6:
* REL-3274: Updated npm-package-builder to add .native folder with the package while pushing
* Created a ruby file to pull the outside dependencies
## 2.0.5:
* REL-3280: Adding error check in tramUtils.py
## 2.0.4:
* REL-3020: Adding grails 1.12 for Multi Jenkins automated plugin
## 2.0.3
* REL-2995: Installing Python 2.7 on SL 6.1 OS
## 2.0.1
* REL-3179: Updating the artifactor URL in tramBuildMe
## 2.0.0
* REL-2909: Updates to jenkins scripts to support new version of jenkins
## 1.0.31
* REL-3008: Adding get_npm_version_file script to jenkins slave
## 1.0.30
* REL-0000: Adding get_aske_version script to jenkins slaves
## 1.0.29
* REL-3029: Updated the publish script to check for modules before publishing
* REL-2765: Updated values that are added by git-details.py for aske applications
## 1.0.28
* REL-2994: Updates promote-outside-npm-packages to recursively promote all the dependencies
## 1.0.27
* Adding python virtual environments to slaves
* updating the npm-package-version-update.py to write the version of platform in form of java propertie file
## 1.0.26
* REL-2919: Updated npm-package-version-update.py to extract the version of platform and store it in a file for verification during deployment
* Added sudoers.local to be dropped under /etc/sudoers.local
## 1.0.24
* REL-2886: Updated the npm-package-build to run 'node it_test --env <name>' for sites
## 1.0.23
* REL-2174: New tech stack for mammoth editorial tool - hue
* Parameterized promote-outside-npm-packages script
* Added the mammoth editrial tool dependency for SL 64
* Updated nodejs version to 0.10.33
## 1.0.22
* REL-2920: Updating npm module name from <name>-version-build to <name>-version.build
## 1.0.21
* Adding LD configuration compile script to the slave
## 1.0.20
* Adding nodejs module phamtomjs for askus, askint and askflanker jobs
* Added new python script git-details.py to drop git.properties into specified location
## 1.0.19
* REL-2857 updated the version of ask-common cookbook used
This file is used to list changes made in each version of askci.
## 1.0.18
* New Python script to kick off jobs on PE jenkins
## 1.0.17
* Updates npm-package-builder to build site assets to be archived REL-2813
## 1.0.16
* Updated npm-package-builder to take optional parameters REL-2753
## 1.0.15
* Updated protomote-npm-package to take git branch as a argument
* Added promote-outside-npm-packages script to pull npm modules from outside and push it to npm-dev
## 1.0.14
* Updated the npm-package-version-update.py script to contruct the version as <application>-<version>-<git_branch>-<buildnumber>
## 1.0.11 - 1.0.13
* Added common package builder and version update for npm applications
* Added npm test argument for npm-package-builder script
* Updated promote-npm-package to promote for both dev and prod with shrinkwrap (1, 0) optional
## 1.0.10
* Added installation of easy_install and couchdb python modules
* Added libxslt library for 6.1 and 6.4 boxes
## 1.0.9
* REL-2547: Added support for jdk1.8.0_20 application build
## 1.0.8
* REL-2429: Added support for nodejs application build
## 1.0.7
* REL-2259: Added JAVA_OPTS to Jenkins startup script
## 1.0.6
* REL-2197: Added maven-3.2.1 for ImageCrawlerService
## 1.0.5
* REL-1519: Upgrading packages for 32-bit recipes
* REL-1519: Added .rpmmacros for 32-bit slave
## 1.0.4:
* REL-2096: Updated recipe to install packages for naf-metaserver and naf-qathrift
## 1.0.3:
* REL-2193: Updated tomcat permissions for tako hosts
## 1.0.2:
* Bumping up the re-tools cookbook verison
## 1.0.1:
* REL-2188: Install jdk-1.7.0_21 on all slaves
## 1.0.0:
* Initial release of askci
- - -
Check the [Markdown Syntax Guide](http://daringfireball.net/projects/markdown/syntax) for help with Markdown.
The [Github Flavored Markdown page](http://github.github.com/github-flavored-markdown/) describes the differences between markdown on github and standard markdown.
<file_sep>/README.md
# tools-cookbook
Installs Jenkins master and slave, resource to create users and groups, installs different versions of python, pip, koji, nodejs, jdk, maven, Ant, composer and other build libraries which are specific to operating systems !!!
dev-depot cookbook
===================
- The recipes in this cookbook install and configure Jenkins on the primary and secondary askci servers
- The master recipe is the entry point to this cookbook to setup the Jenkins master
- The slave recipe is the entry point to setup a Jenkins slave
- The users-groups recipe sets up the users and groups
- The common recipe sets up the software and configuration on the corresponding master/slave hosts
- The koji recipe sets up the koji configuration for a host
- The buildtools-android recipe sets up the software on an Android host
- The buildtools-centos recipe sets up the software on a CentOS 5.4 host
- The buildtools-scientific recipe sets up the software on an SL 6.1 host
- The setup recipe sets up SVN on a host
- The tako recipe sets up the software required to build Tako (tako builder)
Requirements
------------
- CentOS 5.4/7.1/7.2 and SL 6.1/6.4 hosts
- Cookbooks (specified in metadata.rb)
- Once the recipes have been run on the primary and secondary nodes, an explicit SSH connection *must* be initiated from the primary to the secondary node to cache the host keys. Otherwise lsync will fail.
Roles
-----
- dev-depot
Attributes
----------
- specified in attributes/default.rb
"rad": {
"host_name": "rad002iad.io.xxxx.info"
}
"askci-slave": {
"version": "1.0.132",
"build_number": "132"
}
Usage
-----
- For the dev-depot role, reference the recipes (along with the versions) in the env_run_list for each environment
- For each node, reference the dev-depot role under run_list
- For each node, reference the corresponding chef_environment
- Update attributes that change in each of the chef environments
License and Authors
-------------------
Authors: <EMAIL>
<file_sep>/files/default/bin/get-last-successful-build.py
import os
import sys
import getopt
import json
import urllib2
try:
options, arguments = getopt.getopt(sys.argv[1:], 'J:h', ['job-name=', 'help'])
except getopt.GetoptError:
sys.exit("Please check for the usage of the script with help option")
for opt, arg in options:
if opt in ('--help'):
print "<usage>: %s --<job-name=>" %(sys.argv[0])
sys.exit(0)
elif opt in ('--job-name'):
jobName = arg
else:
sys.exit("Please specify the argument correctly")
jenkinsUrl = os.environ['JENKINS_URL']
try:
jenkinsAPI = urllib2.urlopen( jenkinsUrl + "job/" + jobName + "/lastSuccessfulBuild/api/json" )
except urllib2.HTTPError, e:
print "URL Error: " + str(e.code)
print " (job name [" + jobName + "] probably wrong-please give the correct job name!!!!!)"
sys.exit()
try:
last_successfull_Json = json.load( jenkinsAPI )
except:
print "Failed to parse json file"
sys.exit()
if last_successfull_Json.has_key( "number" ):
LastSuccessfullBuildNum =str(last_successfull_Json[ "number"])
print str(last_successfull_Json["number"])
else:
sys.exit(0)
<file_sep>/files/default/bin/mvn-release
#!/bin/bash
# This script must be run via the Jenkins Promote plugin #
die() {
echo "ERROR: $1"
exit $2
}
cd $WORKSPACE/$POM_LOCATION || die "Cannot find parent directory for pom.xml" "$?"
if ! [ -z $SCM_TAG ]; then
SCM_TAG=`awk 'BEGIN{IGNORECASE=1;FS="="}/scm.tag/{print $2;exit}' release.properties` || die "Cannot extract scm.tag information from release.properties" "$?"
fi
mvn release:clean || die "Failed mvn release:clean" "$?"
if ! [ -z $RELEASE_BRANCH ]; then
git checkout $RELEASE_BRANCH || die "Failed to checkout branch '$RELEASE_BRANCH'" "$?"
git merge $SCM_TAG -m "Merge Release $SCM_TAG" || die "Failed to merge tag '$SCM_TAG' into branch '$RELEASE_BRANCH'" "$?"
git push || die "Failed to push changes to git repository" "$?"
fi
| 17f0401bf73b21ae1afe8d5416d73670053d5cd6 | [
"Markdown",
"Python",
"Ruby",
"Shell"
] | 48 | Ruby | kalai15/tools-cookbook | 50ecc49aa7e39e53ad15c73323d8dfb73059146f | 539467b114766b2d1be20b48a0c422ee566332a8 |
refs/heads/master | <file_sep>package com.mavendemo.pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.mavendemo.base.TestBaseFlip;
public class CartPage extends TestBaseFlip{
@FindBy(xpath="//span[text()='Place Order']")
WebElement placeorderbutton;
public CartPage() {
PageFactory.initElements(driver, this);
}
public boolean validatePriceAtCartPage() {
return driver.getPageSource().contains(prop.getProperty("price"));
}
public PaymentPage placeOrderButtonPageClick() {
placeorderbutton.click();
return new PaymentPage();
}
}
<file_sep>URL = https://www.flipkart.com/
username=<EMAIL>
password=<PASSWORD>
prod= fridge
title = Online Shopping Site for Mobiles, Electronics, Furniture, Grocery, Lifestyle, Books & More. Best Offers!
usern=Pearl
product=SAMSUNG 198 L Direct Cool Single Door 5 Star Refrigerator with Base Drawer
titleproductpage=Fridge- Buy Products Online at Best Price in India - All Categories | Flipkart.com
titlebuypage=SAMSUNG 198 L Direct Cool Single Door 5 Star Refrigerator with Base Drawer Online at Best Price in India | Flipkart.com
pincode=110004
price=17,490
cardNumber= 5166404106007722
cvv= 123
monthValue= 06
yearValue = 24
titlepaymentpage= Flipkart.com: Secure Payment: Login > Select Shipping Address > Review Order > Place Order
verification= Not a valid card number
excelsheetpath=C:\\Eclipse\\eclipse\\mavendemo\\src\\main\\java\\com\\mavendemo\\config\\dataentries.xlsx<file_sep>package com.mavendemo.test;
import java.io.IOException;
import java.util.Map;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.mavendemo.base.TestBaseFlip;
import com.mavendemo.pages.BuyPage;
import com.mavendemo.pages.HomePageAndProductSelectPage;
import com.mavendemo.pages.LoginPage;
import com.mavendemo.util.TestExcelUtil;
public class HomePageAndProductSelectPageTest extends TestBaseFlip{
LoginPage loginPage;
HomePageAndProductSelectPage homePageAndProductSelectPage;
BuyPage buyPage;
public HomePageAndProductSelectPageTest() throws IOException{
super();
}
@BeforeMethod
public void setup() throws IOException, InterruptedException {
Flipinitialization();
loginPage= new LoginPage();
homePageAndProductSelectPage= loginPage.login(prop.getProperty("username"),prop.getProperty("password"));
}
@Test(priority=1)
public void homePageTitleTest() {
log.info("****************** starting test case 1 ***********************");
String homePageTitle=homePageAndProductSelectPage.validateHomePageTitle();
Assert.assertEquals(homePageTitle, prop.getProperty("title"),"Home Page Title is not Matched");
log.info("******** ending test case ******************");
}
@Test(priority=2)
public void homeTest() throws InterruptedException, IOException {
log.info("****************** starting test case 2 ***********************");
Map<String,String>exceldata=TestExcelUtil.getData();
buyPage= homePageAndProductSelectPage.homeProductSearchAndClick(exceldata.get("prod"));
log.info("******** ending test case ******************");
}
@Test(priority=3)
public void homePageUserTest() throws InterruptedException {
log.info("****************** starting test case 3 ***********************");
boolean flagforname=homePageAndProductSelectPage.validateHomePageUser();
Assert.assertTrue(flagforname);
log.info("******** ending test case ******************");
}
@AfterMethod
public void teardown() throws InterruptedException {
Thread.sleep(1000);
driver.quit();
log.info("************* Browser is closed *************************");
}
}
| 7efaeeab380649ec89d54085e7b34523f53877db | [
"Java",
"INI"
] | 3 | Java | pearl95/flipkartAutomation | fa2a0e12e54eb20d33187478bf568a6481087e3f | 0465280e31ab849e516c857af70e2880b72ca98f |
refs/heads/main | <file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Conversor de Bases - Universidad Francisco José de Caldas</title>
<link rel="icon" href="favicon.ico">
</head>
<body style="background-color:rgb(231, 219, 186);">
<h1>
<img src="logo.png" width="300px"></img>
<center>
Conversor de Bases
</center>
</h1>
<p>
Bienvenido. Esta página fue creada para la clase de Introducción a la Teoría de Números del
programa de Ingeniería de Sistemas de la Universidad Distrital Francisco José de Caldas por
el estudiante <NAME> en agosto de 2021.<br>
En esta página usted podrá convertir números naturales hasta
<b>(2<sup>53</sup> - 1)<sub>10</sub></b> entre bases del 2 al 36.<br><br>
</p>
<form id="form">
<center>
<table>
<tr>
<td><label for="numero">Convertir el número</label></td>
<td><input type="text" id="numero" name="numero" ><br></td>
</tr>
<tr>
<td><label for="baseA">escrito en base</label></td>
<td><input id="baseA" type="number" name="baseA" min="2" max="36"><br></td>
</tr>
<tr>
<td><label for="baseB">a base</label></td>
<td><input id="baseB" type="number" name="baseB" min="2" max="36"><br></td>
</tr>
<tr>
<!--Al momento de clickear el botón, se ejecutará la última función de script.js-->
<td></td>
<td>
<input type="button" onclick="intercambiar()" value="Intercambiar bases">
<input type="button" onclick="doIt()" value="Enviar"><br>
</td>
</tr>
</table>
</center>
</form>
<p>
<center>
El número convertido:<br>
<textarea id="respuesta" readonly></textarea>
</center>
</p>
<script src="script.js"></script>
</body>
</html><file_sep>/*
AUTOR: <NAME>
PROGRAMA: Conversor de números naturales entre bases 2-36, versión JavaScript
FECHA: 11 de agosto de 2021
*/
//---------------------------------Constantes-----------------------------------
const SYMS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //Caracteres reconocibles.
//---------------------------------Funciones------------------------------------
function checkBase(baseA, num)//------------------------------------------------
{
//Se repite para cada caracter de la cadena num
for (let i = 0; i < num.length; i++)
{
//Controla si se encontró el caracter actual.
let encontrada = false;
//Compara el caracter con los primeros ${baseA} carácteres de la cadena SYMS.
for (let j = 0; j < baseA; j++)
if (num[i] == SYMS[j])
{
//Si lo encuentra, encontrada se hace real.
encontrada = true;
break;
}
//Si no encontró el caracter actual, retorna false.
if (!encontrada) return false;
}
//Si encontró todos los carácteres de la cadena, retorna true.
return true;
}
function invertir(str)//--------------------------------------------------------
{
if (typeof str != "string") return str; //Recibe únicamente strings
let array = str.split(""); //El método split convierte la cadena a arreglo
array = array.reverse(); //El método reverse invierte la posición de los elementos
str = array.join(""); //El método join convierte un arreglo a cadena
return str;
}
function convertir(baseA, baseB, num)//-----------------------------------------
{
//Iniciar guardando la cadena entrante en la cadena resultante.
let numCon = num;
//El algoritmo se ejecuta si las bases son diferentes
if (baseA != baseB)
{
//Si la base original no es diez, se realiza el proceso de conversión.
if (baseA != 10)
{
let numConInt = 0;
//Para cada caracter en la cadena a convertir:
for (let i = 0; i < num.length; i++)
//Pada cada caracter de la cadena de símbolos:
for (let j = 0; j < SYMS.length; j++)
//Cuando Si los carácteres coinciden...
if (num[i] == SYMS[j])
{
//Se suma el producto del valor decimal del símbolo en la poosición j de SYMS
//por la potencia de la base elevada a la posición de derecha a izquierda.
//Ej. i=3, num.length=4 => 4-1-i=0 (i va de desde 0 hasta num.length-1)
numConInt += j * parseInt(baseA ** (num.length - 1 - i));
break;
}
//La sumatoria resultante se guarda como cadena en numCon.
numCon = numConInt.toString();
}
//Si la base objetivo no es 10, se realiza el proceso de conversión.
if (baseB != 10)
{
//Se guarda el número obtenido en el proceso anterior como entero.
let dividendo = parseInt(numCon);
//Se vacía la cadena numCon.
numCon = "";
//Se divide el número entre la base objetivo sucesivamente y se concatena el resto
//en la cadena resultante hasta que el número a dividir sea menor que la base objetivo.
while (dividendo >= baseB)
{
numCon = numCon.toString() + SYMS[dividendo % baseB];
dividendo = Math.trunc(dividendo / baseB);
}
//Se concatena el dividendo final en la cadena resultante.
numCon = numCon + SYMS[dividendo];
//Finalmente se invierte el orden de la cadena.
numCon = invertir(numCon);
}
}
//Se envía la cadena resultante.
return numCon;
}
//-------Esta función se ejecuta desde la página html al oprimir el botón-------
function doIt()
{
//Este bloque de variables guarda las variables en la forma de la página html
let num = document.getElementById("numero").value.toUpperCase();
let baseA = document.getElementById("baseA").value;
let baseB = document.getElementById("baseB").value;
let respuesta = document.getElementById("respuesta");
if (num == "")
{
alert("Por favor escriba un número.");
respuesta.value = "<ERROR>";
}
else if (baseA < 2 || baseA > 36 || baseB < 2 || baseB > 36)
{
alert("Las bases deben ser mayores a 1 y menores a 37.");
respuesta.innerHTML = "<ERROR>";
}
else if (!checkBase(baseA, num))
{
alert("La cadena ingresada no corresponde a un número escrito en esa cadena.");
respuesta.innerHTML = "<ERROR>";
}
else
respuesta.innerHTML = convertir (baseA, baseB, num);
}
function intercambiar ()
{
let baseA = document.getElementById("baseA").value;
let baseB = document.getElementById("baseB").value;
document.getElementById("baseA").value = baseB;
document.getElementById("baseB").value = baseA;
}<file_sep>/*
AUTOR: <NAME>
PROGRAMA: Conversor de números naturales entre bases 2-36, versión JavaScript
FECHA: 11 de agosto de 2021
*/
//---------------------------------Constantes-----------------------------------
const SYMS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //Caracteres reconocibles.
//---------------------------------Funciones------------------------------------
function esInt (str)//---------------------------------------------------
{
//Revisa si todos los carácteres de la cadena son números.
for (let i of str)
if (+parseInt(i) !== +parseInt(i)) return false;
return true;
}
function checkBase(baseA, num)//------------------------------------
{
//Se repite para cada caracter de la cadena num
for (let i = 0; i < num.length; i++)
{
//Controla si se encontró el caracter actual.
let encontrada = false;
//Compara el caracter con los primeros ${baseA} carácteres de la cadena SYMS.
for (let j = 0; j < baseA; j++)
if (num[i] == SYMS[j])
{
//Si lo encuentra, encontrada se hace real.
encontrada = true;
break;
}
//Si no encontró el caracter actual, retorna false.
if (!encontrada) return false;
}
//Si encontró todos los carácteres de la cadena, retorna true.
return true;
}
function invertir(str)//-----------------------------------------
{
if (typeof str != "string") return str;
//Intercambia cada caracter de la primera mita de las posiciones con su
//posición complemento correspondiente.
let array = str.split("");
array = array.reverse();
str = array.join("");
return str;
}
function convertir(baseA, baseB, num)//------------------
{
//Iniciar guardando la cadena entrante en la cadena resultante.
let numCon = num;
//El algoritmo se ejecuta si las bases son diferentes
if (baseA != baseB)
{
//Si la base original no es diez, se realiza el proceso de conversión.
if (baseA != 10)
{
let numConInt = 0;
//Para cada caracter en la cadena a convertir:
for (let i = 0; i < num.length; i++)
//Pada cada caracter de la cadena de símbolos:
for (let j = 0; j < SYMS.length; j++)
//Cuando Si los carácteres coinciden...
if (num[i] == SYMS[j])
{
//Se suma el producto del valor decimal del símbolo en la poosición j de SYMS
//por la potencia de la base elevada a la posición de derecha a izquierda.
//Ej. i=3, num.length=4 => 4-1-i=0 (i va de desde 0 hasta num.length-1)
numConInt += j * parseInt(baseA ** (num.length - 1 - i));
break;
}
//La sumatoria resultante se guarda como cadena en numCon.
numCon = numConInt.toString();
}
//Si la base objetivo no es 10, se realiza el proceso de conversión.
if (baseB != 10)
{
//Se guarda el número obtenido en el proceso anterior como entero.
let dividendo = parseInt(numCon);
//Se vacía la cadena numCon.
numCon = "";
//Se divide el número entre la base objetivo sucesivamente y se concatena el resto
//en la cadena resultante hasta que el número a dividir sea menor que la base objetivo.
while (dividendo >= baseB)
{
numCon = numCon.toString() + SYMS[dividendo % baseB];
console.log(dividendo + " " + dividendo % baseB);
dividendo = Math.trunc(dividendo / baseB);
}
//Se concatena el dividendo final en la cadena resultante.
numCon = numCon + SYMS[dividendo];
//Finalmente se invierte el orden de la cadena.
numCon = invertir(numCon);
}
}
//Se envía la cadena resultante.
return numCon;
}
//------------------------------------Main--------------------------------------
alert("Bienvenido. En este programa podrá convertir de manera exacta " +
"números naturales hasta 2^53 - 1 (base 10) entre bases del 2 al 36.");
while (true)
{
let baseA = 0, baseB = 0;
let resp = "", num = "";
//Para este input se comprueba si es un número entero y luego si está entre 2 y 36.
while (true)
{
resp = prompt("Por favor ingrese la base de su número:");
if (typeof resp === "string" && esInt(resp))
{
baseA = parseInt(resp);
if (baseA > 1 && baseA < 37)
break;
}
alert("ERROR: Se esperaba un entero entre 2 y 36. inténtelo de nuevo.");
}
//Para este input se comprueba que todos los carácteres necesarios estén en el umbral
//0-${baseA} de los carácteres de la cadena SYMS.
while (true)
{
num = prompt("Por favor ingrese el número a convertir:");
if (typeof num === "string") num.toUpperCase();
if (num != "" && checkBase(baseA, num))
break;
else
alert("ERROR: La cadena ingresada no corresponde a un número en la base, inténtelo de nuevo.");
}
//Mismas comprobaciones que baseA.
while (true)
{
resp = prompt("Por favor ingrese la base a la que desea convertir:");
if (typeof resp === "string" && esInt(resp))
{
baseB = parseInt(resp);
if (baseB > 1 && baseB < 37)
break;
}
alert("ERROR: Se esperaba un entero entre 2 y 36. inténtelo de nuevo.");
}
//Finalmente se imprime directamente el resultado de la función convertir.
document.write(`Convertir ${num} de base ${baseA} a base ${baseB}<br>`);
document.write(`Resultado: ${convertir(baseA, baseB, num).toString()}<br>`);
//---------------------------Salir--------------------------------------
let salir = false;
while (true)
{
resp = prompt("¿Desea convertir otro número? (S/N)");
if (resp.toUpperCase() != 'S' && resp.toUpperCase() != 'N' || resp == null)
alert("ERROR: Carácter inválido, inténtelo de nuevo.");
else
{
//Si el usuario indica que quiere salir, salir se hace true.
if (resp.toUpperCase() == 'N') salir = true;
break;
}
}
if (salir) break;
} | 7d619274c2720c7d096874925b176c5d8d877526 | [
"JavaScript",
"HTML"
] | 3 | HTML | MrPocketMonsters/conversor-de-bases | 9e00b63e5a68a2b00bad5eaad8223b2f195bcd2c | 5a372fc1d88a727562123b499fbd88702eaee94d |
refs/heads/master | <repo_name>NichoBrando/Avaliador-Tabela-Periodica<file_sep>/README.md
# Avaliador-Tabela-Periodica
Programa para auxiliar no processo de avaliação, referente à testes sobre a tabela periódica de química.
<h2><b>REQUISITOS:</b></h2>
<ul>
<li>Primeramente, para poder usar o software, será necessário a instalação do <a href = "https://www.python.org/downloads/">Python no PC.</a></li>
<li>Todos os arquivos <b>devem</b> estar no mesmo diretório (pasta), para que o software possa ser usado. </li>
</ul>
<h2><b>Como utilizar?</b></h2>
<ol>
<li>Primeiramente, inicie o o arquivo <b>"Aplicação.py"</b> para poder iniciar o programa.</li>
<li>Após isso, será mostrado uma janela com todas as opções que o usuário irá usar.</li>
<li>Para escolher adicionar uma família ao teste, basta clicar em qual família deseja inserir. Dessa forma, o botão ficará azul, indicando que será usado aqueles elementos para a avaliação. Caso queira <b>remover</b> os elementos, basta clicar novamente na família. Dessa mesma forma, o botão ficará vermelhando, indicando que os elementos daquela família não estão inseridos na avaliação.</li>
<li>Após a seleção das famílias, o usuário poderá mostrar os elementos que serão sorteados. Ou, se quiser que não mostre mais, poderá clicar na opção "Apagar" para que não apareça mais.</li>
<li>Para iniciar os testes,selecione o total de alunos. Os alunos serão sorteados por números, de 1 até N, sendo N o valor indicado pelo usuário.</li>
<li>Logo após indicar a quantidade de alunos, a avaliação será iniciada, mostrando uma entrada para o nome do aluno, um botão de submeter nota e um botão para reinicar o teste de um só aluno.</li>
<li>Dentro do espaço para avaliação, que fica do lado direito, está a opção de escolher quantos elementos da tabela serão sorteados, além um botão para avançar, voltar, adicionar um acerto ou um erro.</li>
<li>Após realizar os testes, clique em "Salvar em arquivo .txt" para criar o arquivo "Resultados.txt" com todos os dados</li>
</ol><file_sep>/avaliador.py
from tabela import *
from tkinter import *
from random import choice
from functools import partial
class Janela(Mainfunctions):
#construtor da interface para avaliadores
def __init__(self):
super().__init__()
self.qntacertos = 0
self.create_tabela_aluno()
self.campo()
self.iniciado = False
#construir a interface:
#método para iniciar introduzir a quantidade de alunos que irão fazer a chamada
def create_tabela_aluno(self):
self.lblaluno = Label(text="Insira o último número da chamada")
self.lblaluno.place(x=320, y=50)
self.numerodealunos = Entry()
self.numerodealunos.place(x=350, y=80)
self.iniciar_chamada = Button(text="Iniciar chamada oral", fg ='red')
self.iniciar_chamada.place(x=350, y = 110)
self.iniciar_chamada["command"] = self.comecar_avaliacao
self.chamado = Label(text="Para iniciar a chamada:\nDigite a quantidade de alunos clique no botão", fg='red')
self.chamado.place(x=325, y=140)
#campo objetos para avaliação
def campo(self):
self.nome = Entry()
self.lblnome = Label(text="Nome")
self.lblnome.place(x=320, y=180)
self.nome.place(x=360, y=180)
self.acertos = Label(text="0 Acertos")
self.acertos.place(x=370, y=210)
self.create_avaliador()
self.alunos = []
self.acertoalunos = []
self.submeter = Button(text="Submeter", command=self.submit)
self.submeter.place(x=320, y=240)
self.reseta = Button(text="Retornar", command= self.retornar)
self.reseta.place(x=400, y=240)
self.salvar = Button(text="Salvar em .txt", command=self.save)
self.salvar.place(x=360, y=300)
self.lblsave = Label(text="Não salvo", fg='red')
self.lblsave.place(x=360, y=340)
#opções para realizar a chamada oral
def create_avaliador(self):
self.quantidade = Entry(width=10)
self.quantidade.place(x= 700, y= 50)
self.lblqnt = Label(text="Quantidade de elementos")
self.lblqnt.place(x=560, y=50)
self.starter = Button(text="comecar", command=self.startav)
self.starter.place(x=580, y= 80)
self.lblelemento = Label(text="X")
self.lblelemento.place(x=630, y= 120)
self.resetelementos()
self.botaoanterior = Button(text="<-", command=self.anterior)
self.botaoanterior.place(x=610, y= 140)
self.botaoavancar = Button(text="->", command=self.avancar)
self.botaoavancar.place(x=640, y= 140)
self.acertou = Button(text="Acertou", command=self.acertou)
self.errou = Button(text="Errou", command=self.avancar)
self.acertou.place(x=580, y=180)
self.errou.place(x=640, y=180)
#métodos:
#seleciona o primeiro aluno para a avaliação
def comecar_avaliacao(self):
if not self.iniciado:
tamanho = int(self.numerodealunos.get())
self.chamada = []
for i in range(tamanho):
self.chamada.append(i+1)
escolhido = choice(self.chamada)
self.remover(escolhido)
self.chamado["text"] = "Chamada iniciada!\no primeiro escolhido é o número " + str(escolhido)
#salva alunos e notas em um arquivo de texto
def save(self):
#salva em arquivo .txt
if len(self.alunos) == 0:
return
file = open("resultados.txt", "w+")
file.write("Resultados:\n")
for i in range(len(self.alunos)):
file.write("{} = {}%\n".format(self.alunos[i], round(self.acertoalunos[i], 2)))
file.close()
self.lblsave["text"] = "Salvo com " + str(len(self.alunos)) + (" alunos" if len(self.alunos)>1 else " aluno")
self.lblsave["fg"] = 'green'
#redefine o número de acertos e a pessoa que está fazendo o teste
def retornar(self):
self.nome.delete(0, END)
self.qntacertos = 0
self.acertos["text"] = "0 Acertos"
self.reset_tabela()
#armazena o nome e a pontuação da pessoa e sorteia um novo número
def submit(self):
if len(str(self.nome.get())) == 0:
return
self.alunos.append(str(self.nome.get()))
x = 100 *(self.qntacertos/(int(self.quantidade.get())))
self.acertoalunos.append(x)
self.retornar()
self.reset_tabela()
if len(self.chamada) == 0:
self.chamado["text"] = "todos os alunos foram avaliados!"
else:
escolhido = choice(self.chamada)
self.chamado["text"]= "Número " + str(escolhido) + " Foi selecionado!"
self.remover(escolhido)
#métodos da avaliação:
#inicia o teste de um aluno
def startav(self):
self.resetelementos()
self.getelementos()
self.reset_tabela()
self.qntacertos = 0
self.acertos["text"] = "0 Acertos"
#mostra um acerto a mais para o aluno
def atualiza_acertos(self):
self.qntacertos += 1
self.acertos["text"] = str(self.qntacertos) + " Acertos"
#remove o aluno da lista de espera para avaliação
def remover(self, valor):
for i in range(len(self.chamada)):
if self.chamada[i] == valor:
del self.chamada[i]
return
#adiciona um acerto no teste de um aluno e mostra o próximo elemento
def acertou(self):
if self.qntacertos == int(self.quantidade.get()):
pass
else:
if self.tabela_acertos[self.posicao] == 0:
self.atualiza_acertos()
self.tabela_acertos[self.posicao] = 1
self.avancar()
#marca o erro e mostra o próximo elemento
def errou(self):
if self.qntacertos == int(self.quantidade.get()):
pass
else:
if self.tabela_acertos[self.posicao] == 0:
self.tabela_acertos[self.posicao] = 1
self.avancar()
#métodos da avaliação
#adquire os elementos que irão ser mostrados na avaliação, de forma aleatória
def getelementos(self):
numeroderepeticoes = int(self.quantidade.get())
for i in range(numeroderepeticoes):
self.elementos.append(choice(self.sorteio))
self.lblelemento["text"] = str(self.elementos[0])
self.posicao = 0
self.reset_tabela()
#avança para o próximo elemento da avaliação
def avancar(self):
if self.posicao == len(self.elementos) - 1:
return
self.posicao += 1
self.lblelemento["text"] = str(self.elementos[self.posicao])
#regressa um elemento da avaliação
def anterior(self):
if (self.posicao > 0):
self.posicao -= 1
self.lblelemento["text"] = str(self.elementos[self.posicao])
#zera o número de acertos e erros de alguém, para que o mesmo possa tentar o elemento depois
def reset_tabela(self):
self.tabela_acertos = []
numeroderepeticoes = int(self.quantidade.get())
for i in range(numeroderepeticoes):
self.tabela_acertos.append(0)
#remove todos os elementos que estão sendo usados em avaliação
def resetelementos(self):
self.elementos = []
<file_sep>/Aplicação.py
from avaliador import *
root = Janela()
root.geometry('800x600+0+0')
root.iconbitmap('icone.ico')
root.title('Chamada Oral')
root.mainloop()
<file_sep>/tabela.py
from tkinter import *
from random import choice
from functools import partial
class Mainfunctions(Tk):
def __init__(self, master=None):
super().__init__(master)
self.createtabela()
self.create_familias()
#cria as opções para selecionar as famílias
def create_familias(self):
self.titulo = Label(text="Tabela Periódica")
self.titulo.place(x=350, y=10)
self.subtitulo = Label(text="Famílias")
self.subtitulo.place(x=80, y= 50)
self.alabel = Label(text="A")
self.alabel.place(x=80, y=65)
self.blabel = Label(text="B")
self.blabel.place(x=120, y=65)
self.blista = []
self.alista = []
i = 0
cx = 120
cy = 85
while i<11:
if i == 10:
aux = Button(text='Especial', bg='red')
else:
aux = Button(text=str(i+1), bg='red')
self.blista.append(aux)
self.blista[i]['command'] = partial(self.adicionar_remover, (i+1) * -1)
self.blista[i].place(x = cx, y= cy)
i += 1
cy += 20
i = 0
cx = 80
cy = 85
while i<8:
aux = Button(text=str(i+1), bg='red')
self.alista.append(aux)
self.alista[i]['command'] = partial(self.adicionar_remover, i)
self.alista[i].place(x = cx, y=cy)
i += 1
cy += 20
self.lblsorteio = Label()
self.lblsorteio.place(x=50, y=380)
self.astatus = ['red', 'red', 'red', 'red', 'red', 'red', 'red','red']
self.bstatus = ['red','red','red','red','red','red','red','red','red','red', 'red']
self.escritor = Button(text="Mostrar", command= self.escreve_na_tela)
self.apagador = Button(text="Apagar", command= self.apaga)
self.escritor.place(x=50, y=340)
self.apagador.place(x=130, y=340)
#adiciona os elementos da família para uma lista
def adicionar_remover(self, i):
max = len(self.sorteio)
if 0>i:
i = -(i+1)
tipo = 'b'
if self.bstatus[i] == 'red':
for elementos in self.bfamilias[i]:
self.sorteio.append(elementos)
else:
for elementos in self.bfamilias[i]:
j = 0
while j<=max:
if self.sorteio[j] == elementos:
del self.sorteio[j]
j -=1
max-=1
break
else:
j+= 1
else:
tipo = 'a'
if self.astatus[i] == 'red':
for elementos in self.afamilias[i]:
self.sorteio.append(elementos)
else:
for elementos in self.afamilias[i]:
j = 0
while j<=len(self.sorteio):
if self.sorteio[j] == elementos:
del self.sorteio[j]
j -=1
max-=1
break
else:
j+= 1
self.mudarcor(tipo, i)
#mostra quais elementos estão na lista
def escreve_na_tela(self):
self.lblsorteio["text"] = ""
i = 0
for item in self.sorteio:
self.lblsorteio["text"] += str(item) + " | "
i+=1
if i > 10:
self.lblsorteio["text"] += "\n"
i = 0
#muda a cor do botão. Vermelho se estiver sem os elementos e azul se tiver adicionado
def mudarcor(self, tipo, i):
if tipo == 'a':
if self.astatus[i] == 'red':
self.astatus[i] = 'blue'
self.alista[i]['bg'] = 'blue'
else:
self.astatus[i] = 'red'
self.alista[i]['bg'] = 'red'
else:
if self.bstatus[i] == 'red':
self.bstatus[i] = 'blue'
self.blista[i]['bg'] = 'blue'
else:
self.bstatus[i] = 'red'
self.blista[i]['bg'] = 'red'
#apaga o texto mostrado
def apaga(self):
self.lblsorteio["text"] = ""
#lista com elementos da tabela periódica
def createtabela(self):
self.sorteio = []
self.afamilias = [['H', 'Li', 'Na', 'K', 'Rb', 'Cs', 'Fr'], ['Be', 'Mg', 'Ca', 'Sr', 'Ba', 'Ra'], ['B', 'Al', 'Ga', 'In', 'Ti', 'Nh'],
['C', 'Si', 'Ge', 'Sn', 'Pb', 'Fl'], ['N', 'P', 'As', 'Sb', 'Bi', 'Mc'], ['O', 'S', 'Se', 'Te', 'Po', 'Lv'],
['F', 'Cl', 'Br', 'I', 'At', 'Ts'], ['He', 'Ne', 'Ar', 'Kr', 'Xe', 'Rn', 'Og']]
self.bfamilias = [['Sc', 'Y'], ['Ti', 'Zr', 'Hf', 'Rf'], ['V', 'Nb', 'Ta', 'Db'], ['Cr', 'Mo', 'W', 'Sg'],
['Mn', 'Tc', 'Re', 'Bh'], ['Fe', 'Ru', 'Os', 'Hs'], ['Co', 'Rh', 'Ir', 'Mt'], ['Ni', 'Pd', 'Pt', 'Ds']
, ['Cu', 'Ag', 'Au', 'Rg'], ['Zn', 'Cd', 'Hg', 'Cn'], ["La", "Ce", "Pr", "Nd", "Pm", "Sm", "Eu", "Gd", "Tb", "Dy", "Ho", "Er", "Tm", "Yb", "Lu", "Ac", "Th", "Pa", "U", "Np", "Pu", "Am", "Cm", "Bk", "Cf", "Es", "Fm", "Md", "No", "Lr"]] | a2784660c30ec5560d8764508650f105bbe99490 | [
"Markdown",
"Python"
] | 4 | Markdown | NichoBrando/Avaliador-Tabela-Periodica | 5ab464a66fba41630c6bfff01c032d13706d3294 | 2086b76448692b38bffbdd03f1090bcb26875937 |
refs/heads/master | <repo_name>satyamohlan/Arduinore<file_sep>/sketch_dec16b/sketch_dec16b.ino
#include <NewPing.h>
#include <AFMotor.h>
AF_DCMotor motor1(1, MOTOR12_64KHZ);
AF_DCMotor motor2(2, MOTOR12_64KHZ);
int sensor[3] = {0, 0, 0};
int echopin = 22;
int trigpin = 24;
int distance;
int duration;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(echopin, INPUT);
pinMode(trigpin, OUTPUT);
}
void loop() {
int i = 0;
digitalWrite(trigpin, HIGH);
delay(10);
digitalWrite(trigpin, LOW);
duration = pulseIn(echopin, HIGH);
distance = (duration / 2 * 0.034);
Serial.println(distance);
sensor[0] = digitalRead(A0);
sensor[1] = digitalRead(A1);
sensor[2] = digitalRead(A2);
for (i = 0; i < 5; i++)
if ((sensor[0] == 1) && (sensor[1] == 0) && sensor[2] == 1) //STRAIGHT FW
{ motor1.run(FORWARD);
motor2.run(FORWARD);
motor1.setSpeed(190);
motor2.setSpeed(190);
}
if ((sensor[0] == 1) && (sensor[1] == 1) && sensor[2] == 1) //STRAIGHT FW
{ motor1.run(FORWARD);
motor2.run(FORWARD);
motor1.setSpeed(190);
motor2.setSpeed(190);
}
if ((sensor[0] == 0) && (sensor[1] == 0) && sensor[2] == 0) //STRAIGHT FW
{ motor1.run(FORWARD);
motor2.run(FORWARD);
motor1.setSpeed(190);
motor2.setSpeed(190);
}
if ((sensor[0] == 1) && (sensor[1] == 0) && sensor[2] == 0) //right
{ motor1.run(FORWARD);
motor2.run(BACKWARD);
motor1.setSpeed(225);
motor2.setSpeed(225);
}
if ((sensor[0] == 0) && (sensor[1] == 0) && sensor[2] == 1) //left
{ motor1.run(BACKWARD);
motor2.run(FORWARD);
motor1.setSpeed(225);
motor2.setSpeed(225);
}
if ((sensor[0] == 0) && (sensor[1] == 1) && sensor[2] == 1) //left
{ motor1.run(BACKWARD);
motor2.run(FORWARD);
motor1.setSpeed(125);
motor2.setSpeed(125);
} if ((sensor[0] == 1) && (sensor[1] == 1) && sensor[2] == 0) //right
{ motor1.run(FORWARD);
motor2.run(BACKWARD);
motor1.setSpeed(125);
motor2.setSpeed(125);
}
if ((distance < 16)&&(distance>6)) {
avoid();
}
}
void avoid() {
motor1.run(RELEASE);
motor2.run(RELEASE);
motor1.setSpeed(190);
motor2.setSpeed(190);
delay(500);
motor1.run(FORWARD);
motor2.run(BACKWARD);
motor1.setSpeed(190);
motor2.setSpeed(190);
delay(1500);
motor1.run(FORWARD);
motor2.run(FORWARD);
motor1.setSpeed(190);
motor2.setSpeed(190);
delay(2000);
motor1.run(BACKWARD);
motor2.run(FORWARD);
motor1.setSpeed(190);
motor2.setSpeed(190);
delay(1500);
motor1.run(FORWARD);
motor2.run(FORWARD);
motor1.setSpeed(190);
motor2.setSpeed(190);
delay(1700);
motor1.run(BACKWARD);
motor2.run(FORWARD);
motor1.setSpeed(190);
motor2.setSpeed(190);
motor1.run(FORWARD);
motor2.run(FORWARD);
motor1.setSpeed(190);
motor2.setSpeed(190);
delay(1500);
motor1.run(BACKWARD);
motor2.run(FORWARD);
motor1.setSpeed(190);
motor2.setSpeed(190);
delay(1000);
motor1.run(RELEASE);
motor2.run(RELEASE);
motor1.setSpeed(190);
motor2.setSpeed(190);
delay(100);
}
<file_sep>/car/car.ino
#include <Servo.h>
int state=0;
int left1=4;
int left2=5;
int right1=6;
int right2=7;
int pos=0;
unsigned long time;
float distance;
long duration;
int trigpin = 9;
int echopin = 10;
Servo myservo;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(right2,OUTPUT);
pinMode(right1,OUTPUT);
pinMode(left1,OUTPUT);
pinMode(left2,OUTPUT);
myservo.attach(9);
pinMode(trigpin, OUTPUT);
pinMode(echopin, INPUT);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
time=millis();
if(time>10000){
for (pos = 0; pos <= 180; pos += 1) {
digitalWrite(trigpin, LOW);
delay(2);
digitalWrite(trigpin, HIGH);
delay(10);
digitalWrite(trigpin, LOW);
duration = pulseIn(echopin, HIGH);
distance = duration * 0.034 / 2;
myservo.write(pos);
Serial.print(distance,1);
Serial.print("cm");
if(distance<10){
}
Serial.println();}
time=00;
}
if (Serial.available() > 0) {
state = Serial.read();}
if(state=='1'){
digitalWrite(left1,HIGH);
}
if(state=='2'){
digitalWrite(right2,HIGH);
}
if(state =='0'){
digitalWrite(left1,LOW);
digitalWrite(left2,LOW);
digitalWrite(right1,LOW);
digitalWrite(right2,LOW);
}
if(state =='3'){
digitalWrite(left1,HIGH);
digitalWrite(right2,HIGH);
}
if(state =='4'){
digitalWrite(left2,HIGH);
digitalWrite(right1,HIGH);
}
}
<file_sep>/ULTRASONIC_view/ULTRASONIC_view.ino
#include <AFMotor.h>
#include <NewPing.h>
AF_DCMotor motor1(4);
AF_DCMotor motor2(5);
float distance;
long duration;
int trigpin = 9;
int echopin = 10;
void setup() {
// put your setup code here, to run once:
pinMode(trigpin, OUTPUT);
pinMode(echopin, INPUT);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(trigpin, LOW);
delay(2);
digitalWrite(trigpin, HIGH);
delay(10);
digitalWrite(trigpin, LOW);
duration = pulseIn(echopin, HIGH);
distance = duration * 0.034 / 2;
Serial.print(distance,1);
Serial.print("cm");
Serial.println();
if (distance<10){
Serial.println("turn");
}delay(200);
}
<file_sep>/temprature_data/temprature_data.ino
double x;
void setup() {
// put your setup code here, to run once:
pinMode(7,INPUT);
}
void loop() {
// put your main code here, to run repeatedly:
Serial.begin(9600);
x=analogRead(7);
Serial.write(x);
delay(100);
}
<file_sep>/sketch_nov17a/sketch_nov17a.ino
int state=0;
int left1=4;
int left2=5;
int right1=6;
int right2=7;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(right2,OUTPUT);
pinMode(right1,OUTPUT);
pinMode(left1,OUTPUT);
pinMode(left2,OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
if (Serial.available() > 0) {
state = Serial.read();}
if(state=='1'){
digitalWrite(left1,HIGH);
}
if(state=='2'){
digitalWrite(right2,HIGH);
}
if(state =='0'){
digitalWrite(left1,LOW);
digitalWrite(left2,LOW);
digitalWrite(right1,LOW);
digitalWrite(right2,LOW);
}
if(state =='3'){
digitalWrite(left1,HIGH);
digitalWrite(right2,HIGH);
}
if(state =='4'){
digitalWrite(left2,HIGH);
digitalWrite(right1,HIGH);
}}
<file_sep>/sketch_dec16a/sketch_dec16a.ino
#include <AFMotor.h>
AF_DCMotor motor1(1, MOTOR12_64KHZ);
AF_DCMotor motor2(2, MOTOR12_64KHZ);
int sensor[3]={0, 0,0};
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
int i=0;
sensor[0]=digitalRead(A0);
sensor[1]=digitalRead(A1);
sensor[2]=digitalRead(A2);
for(i=0;i<5;i++)
{
Serial.print(sensor[i] );
Serial.print("\n");}
if((sensor[0]==1)&&(sensor[1]==0)&&(sensor[2]==1)) //STRAIGHT FW
{ motor1.run(FORWARD);
motor2.run(FORWARD);
motor1.setSpeed(200);
motor2.setSpeed(200);}
if((sensor[0]==1)&&(sensor[1]==1)&&(sensor[2]==1)) //STRAIGHT FW
{ motor1.run(FORWARD);
motor2.run(FORWARD);
motor1.setSpeed(200);
motor2.setSpeed(200);}
if((sensor[0]==0)&&(sensor[1]==0)&&(sensor[2]==0)) //STRAIGHT FW
{ motor1.run(FORWARD);
motor2.run(FORWARD);
motor1.setSpeed(200);
motor2.setSpeed(200);
}
if((sensor[0]==1)&&(sensor[1]==0)&&(sensor[2]==0)) //right
{ motor1.run(FORWARD);
motor2.run(BACKWARD);
motor1.setSpeed(255);
motor2.setSpeed(255);
}
if((sensor[0]==0)&&(sensor[1]==0)&&sensor[2]==1) //left
{ motor1.run(BACKWARD);
motor2.run(FORWARD);
motor1.setSpeed(255);
motor2.setSpeed(255);}
if((sensor[0]==0)&&(sensor[1]==1)&&sensor[2]==1) //left
{ motor1.run(BACKWARD);
motor2.run(FORWARD);
motor1.setSpeed(255);
motor2.setSpeed(255);}
if((sensor[0]==1)&&(sensor[1]==1)&&sensor[2]==0) //right
{ motor1.run(FORWARD);
motor2.run(BACKWARD);
motor1.setSpeed(255);
motor2.setSpeed(255);}
}
| 9899fe3ea51826f2ce2c669e361add24f714d593 | [
"C++"
] | 6 | C++ | satyamohlan/Arduinore | 2e10858a8c4437558ebe79e6f38ee0dbc72d0a5f | b11f92f78be3c8cb049d1552b56c7aff8d9f6688 |
refs/heads/master | <file_sep>package com.company;
import java.util.List;
public class Animal implements IObject {
boolean valid = true;
private Vector2d position = new Vector2d(2, 2);
private Direction direction = Direction.NORTH;
private int energy;
private Genes genes;
private int index;
Animal(Vector2d position, int[] tab, int energy, int index) {
this.position.x = position.getX();
this.position.y = position.getY();
this.energy = energy;
genes = new Genes(tab);
this.index = index;
}
private Animal(Vector2d position, int[] tab, int energy, Direction dir, boolean valid, int index) {
this.position.x = position.getX();
this.position.y = position.getY();
this.energy = energy;
genes = new Genes(tab);
this.direction = dir;
this.valid = valid;
this.index = index;
}
public int getIndex() {
return this.index;
}
Direction getDirection() {
return this.direction;
}
public Genes getGenes() {
return this.genes;
}
public String toString() {
return this.direction.toString();
}
public int getEnergy() {
return energy;
}
public void setEnergy(int energy) {
this.energy = energy;
}
public Vector2d getPosition() {
return this.position;
}
private void rotate(int number) {
for (int i = 0; i < number; i++) {
this.direction = this.direction.next();
}
}
void moveForward(Map map) {
this.position = this.position.add(this.direction.toUnitVector());
this.position = map.bound(this.position);
}
private void eatGrass(int grassEnergy) {
this.energy += grassEnergy;
}
private Direction randomDirection() {
Direction dir = Direction.NORTH;
int p = (int) (Math.random() * 8);
for (int i = 0; i < p; i++) {
dir = dir.next();
}
return dir;
}
void process(Map map, List<Animal> animalsToMove) {
this.rotate(this.genes.getRotation());
Vector2d newPosition = this.position.add(this.direction.toUnitVector());
newPosition = map.bound(newPosition); //Covers going out of edges
if (map.canMoveTo(newPosition, this.objectType())) {
if (map.isOccupied(newPosition)) {
IObject object = map.myObjectAt(newPosition);
if (object.objectType() == Type.GRASS) {
map.deleteFromPosition(newPosition);
this.eatGrass(map.getGrassEnergy());
map.replace(this, this.position, newPosition);
this.moveForward(map);
} else if (object.getEnergy() >= map.getGrassEnergy() / 2 && this.getEnergy() >= map.getGrassEnergy() / 2) {
int[] tab = this.genes.combine(object.getGenes());
Direction temp = this.randomDirection();
Vector2d childPosition = newPosition.add(temp.toUnitVector());
childPosition = map.bound(childPosition);
int childEnergy = (this.getEnergy() / 4) + (object.getEnergy() / 4);
Animal animal = new Animal(childPosition, tab, childEnergy, temp, false, map.actualIndex);
animalsToMove.add(this);
int i = 0;
for (i = 0; i < 20 && !(map.place(animal)); i++) {
temp = this.randomDirection();
childPosition = newPosition.add(temp.toUnitVector());
childPosition = map.bound(childPosition);
animal = new Animal(childPosition, tab, childEnergy, temp, false, map.actualIndex);
}
if (i != 20) {
map.options.add(map.actualIndex);
map.actualIndex++;
}
map.actualIndex++;
this.setEnergy((this.getEnergy() * 3) / 4);
object.setEnergy(3 * object.getEnergy() / 4);
this.valid = false;
}
this.energy--;
return;
}
map.replace(this, this.position, newPosition);
this.position = newPosition;
}
this.energy--;
}
@Override
public Type objectType() {
return Type.ANIMAL;
}
}
<file_sep>public class RectangularMap extends AbstractWorldMap {
int width;
int height;
public RectangularMap (int width, int height) {
this.width = width;
this.height = height;
}
@Override
public void draw(){
MapVisualizer a=new MapVisualizer(this);
System.out.print(a.draw(new Vector2d(0,0), new Vector2d(width-1,height-1)));
}
}
<file_sep>package com.company;
import javafx.collections.ObservableList;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.shape.Rectangle;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
class Map {
int[] genes = new int[32];
int maxAnimalEnergy = 0;
ObservableList<Integer> options;
int actualIndex = 0;
int choosenIndex = -1;
private int sizeX;
private int sizeY;
private List<Animal> animals = new LinkedList<Animal>();
private GridPane VisualizationArray;
private HashMap<Vector2d, IObject> hashMap = new HashMap<Vector2d, IObject>();
private int grassEnergy;
Map(int sizeX, int sizeY, int grassEnergy, GridPane VisualizationArray, ObservableList<Integer> options) {
this.sizeX = sizeX;
this.sizeY = sizeY;
this.options = options;
this.grassEnergy = grassEnergy;
this.VisualizationArray = VisualizationArray;
}
int getGrassEnergy() {
return this.grassEnergy;
}
boolean isOccupied(Vector2d position) { //Checks if there is anything on this spot
return hashMap.containsKey(position);
}
boolean canMoveTo(Vector2d position, Type type) { //Checks
if (!isOccupied(position)) return true;
return type != Type.GRASS;
}
public Animal getAnimal(int index) {
if (animals.size() == 0) return null;
this.choosenIndex = index;
if (index >= actualIndex) return null;
for (Animal animal : animals) {
if (animal.getIndex() == index) {
return animal;
}
}
return null;
}
Label getLabel(DrawType type) {
Rectangle rect = new Rectangle(6, 6);
rect.setStroke(type.getColor());
rect.setFill(type.getColor());
Label label = new Label(" ", rect);
return label;
}
boolean place(IObject object) {
if (isOccupied(object.getPosition())) return false;
if (object.objectType() == Type.GRASS) {
Label label = getLabel(DrawType.GRASS);
this.VisualizationArray.add(label, object.getPosition().getX(), object.getPosition().getY());
} else {
animals.add((Animal) object);
Label label1=getLabel(DrawType.ANIMAL);
if (object.getEnergy()<this.getGrassEnergy()) {
label1 = getLabel(DrawType.VeryVeryVeryTiredAnimal);
} else if(object.getEnergy()<2*this.getGrassEnergy()){
label1 = getLabel(DrawType.VeryVeryTiredAnimal);
}else if(object.getEnergy() <4*this.getGrassEnergy()){
label1 = getLabel(DrawType.VeryTiredAnimal);
}else if(object.getEnergy() <8*this.getGrassEnergy()){
label1 = getLabel(DrawType.TiredAnimal);
}
this.VisualizationArray.add(label1, object.getPosition().getX(), object.getPosition().getY());
}
hashMap.put(object.getPosition(), object);
return true;
}
void replace(Animal animal, Vector2d oldPosition, Vector2d newPosition) {
//Main coloring is done here
this.bound(oldPosition);
this.bound(newPosition);
if (newPosition == oldPosition) {
return;
}
hashMap.remove(oldPosition);
Label label2 = getLabel(DrawType.BLANK);
this.VisualizationArray.add(label2, oldPosition.getX(), oldPosition.getY());
hashMap.put(newPosition, animal);
Label label1=getLabel(DrawType.ANIMAL);
if (animal.getEnergy()<this.getGrassEnergy()) {
label1 = getLabel(DrawType.VeryVeryVeryTiredAnimal);
} else if(animal.getEnergy()<2*this.getGrassEnergy()){
label1 = getLabel(DrawType.VeryVeryTiredAnimal);
}else if(animal.getEnergy() <4*this.getGrassEnergy()){
label1 = getLabel(DrawType.VeryTiredAnimal);
}else if(animal.getEnergy() <8*this.getGrassEnergy()){
label1 = getLabel(DrawType.TiredAnimal);
}
this.VisualizationArray.add(label1, newPosition.getX(), newPosition.getY());
}
IObject myObjectAt(Vector2d position) {
return hashMap.get(position);
}
void deleteFromPosition(Vector2d position) {
IObject t = hashMap.get(position);
hashMap.remove(position);
if (t.objectType() == Type.ANIMAL)
animals.remove(t);
Label label = getLabel(DrawType.BLANK);
this.VisualizationArray.add(label, position.getX(), position.getY());
}
GridPane drawing() {
return this.VisualizationArray;
}
private void delete(Animal animal) {
hashMap.remove(animal.getPosition());
animals.remove(animal);
options.removeAll(animal.getIndex());
Label label = getLabel(DrawType.BLANK);
this.VisualizationArray.add(label, animal.getPosition().getX(), animal.getPosition().getY());
}
private void deleteDead() {
int size = animals.size();
Animal animal;
for (int i = 0; i < size; i++) {
animal = animals.get(0);
animals.remove(0);
animals.add(animal);
if (!(animal.getEnergy() > 0)) {
this.delete(animal);
}
}
}
boolean process() { //Basic part
int max_energy = 0;
List<Animal> animalsToMove = new LinkedList<Animal>();
this.deleteDead();
if (animals.size() == 0) return false;
Animal topAnimal = animals.get(0);
Animal animal;
while (animals.get(0).valid) {
animal = animals.get(0);
animals.remove(0);
animal.process(this, animalsToMove);
animal.valid = false;
animals.add(animal);
if (animal.getEnergy() > max_energy) {
topAnimal = animal;
max_energy = animal.getEnergy();
}
if (animal.getIndex() == this.choosenIndex) {
this.VisualizationArray.add(getLabel(DrawType.ChoosenAnimal), animal.getPosition().getX(), animal.getPosition().getY());
}
}
for (Animal value : animals) {
value.valid = true;
}
Generator tmp = new Generator();
for (int i = 0; i < 30 && !this.place(new Grass(tmp.outsidePoint(sizeX, sizeY))); i++)
; //To make it more realistic - the grass wont spawn every time
for (int i = 0; i < 30 && !this.place(new Grass(tmp.junglePoint(sizeX, sizeY))); i++)
; //It might not spawn if there is too much grass all around.
// I stayed with 30 tries, as it was efficient enough
// Now, when there are not many animals on a big map we might see their path in estimation as the map kind of shows where it was
for (Animal a : animalsToMove) {
Vector2d newPosition = a.getPosition().add(a.getDirection().toUnitVector());
newPosition = this.bound(newPosition);
if (!this.isOccupied(newPosition)) {
this.replace(a, a.getPosition(), newPosition);
a.moveForward(this);
if (a.getIndex() == this.choosenIndex) {
this.VisualizationArray.add(getLabel(DrawType.ChoosenAnimal), a.getPosition().getX(), a.getPosition().getY());
}
}
}
animalsToMove.clear();
Label label = getLabel(DrawType.TopAnimal);
this.VisualizationArray.add(label, topAnimal.getPosition().getX(), topAnimal.getPosition().getY());
this.genes = topAnimal.getGenes().getGenes();
this.maxAnimalEnergy = topAnimal.getEnergy();
return true;
}
Vector2d bound(Vector2d position) {
return new Vector2d((position.x + this.sizeX + 1) % (this.sizeX + 1), (position.y + this.sizeY + 1) % (this.sizeY + 1));
}
}
<file_sep>package com.company;
public class Grass implements IObject {
private Vector2d position;
Grass(Vector2d position) {
this.position = position;
}
public Type objectType() {
return Type.GRASS;
}
public int getEnergy() {
return 10;
}
public void setEnergy(int energy) {
throw new IllegalStateException("Unexpected setEnergy call at GRASS element");
}
public Vector2d getPosition() {
return this.position;
}
public String toString() {
return "g";
}
public Genes getGenes() {
throw new IllegalStateException("Unexpected getGenes call at GRASS element");
}
}
<file_sep>import org.junit.Test;
import java.util.*;
import static org.junit.Assert.assertEquals;
public class UnboundedTest {
@Test
public void fTest(){
String[] test={"f","b","r","l","f","f","r","r","f","f","f","f","f","f","f","f"};
MoveDirection[] directions = new OptionParser().parse(test);
List<HayStack> hays = new LinkedList<HayStack>();
hays.add(new HayStack(new vector2d(-4,-4)));
hays.add(new HayStack(new vector2d(7,7)));
hays.add(new HayStack(new vector2d(3,6)));
hays.add(new HayStack(new vector2d(2,0)));
IWorldMap map = new RectangularMap(10, 5);
Animal a=new Animal(map);
Animal b=new Animal(map,new vector2d(3,4));
map.place(a);
map.place(b);
map.run(directions);
assertEquals(a.getX(), 2);
assertEquals(a.getY(), 0);
assertEquals(b.getX(), 3);
assertEquals(b.getY(), 4);
assertEquals(a.toString(),"S");
assertEquals(b.toString(),"N");
}
}
<file_sep>package sample;
public class Position {
int x;
int y;
Position(int x, int y) {
this.x = x;
this.y = y;
}
int getX() {
return this.x;
}
int getY() {
return this.y;
}
Position add(Position position) {
return new Position(this.x + position.x, this.y + position.y);
}
}
<file_sep>package com.company;
import javafx.scene.paint.Color;
//Way of coloring animals
public enum DrawType {
ANIMAL,
GRASS,
BLANK,
TiredAnimal,
AboutToDieAnimal,
TopAnimal,
ChoosenAnimal,
VeryTiredAnimal,
VeryVeryTiredAnimal,
VeryVeryVeryTiredAnimal;
public Color getColor() {
switch (this) {
case ANIMAL:
return Color.DARKRED;
case GRASS:
return Color.GREEN;
case BLANK:
return Color.WHITE;
case TiredAnimal:
return Color.ORANGERED;
case AboutToDieAnimal:
return Color.BLACK;
case TopAnimal:
return Color.GOLDENROD;
case ChoosenAnimal:
return Color.BLUE;
case VeryTiredAnimal:
return Color.INDIANRED;
case VeryVeryTiredAnimal:
return Color.DARKGRAY;
case VeryVeryVeryTiredAnimal:
return Color.GRAY;
}
return Color.WHITE;
}
}
<file_sep>package com.company;
public interface IObject {
Type objectType();
int getEnergy();
void setEnergy(int energy);
Vector2d getPosition();
String toString();
Genes getGenes();
}
<file_sep>package com.company;
class Generator {
Vector2d point(int rangeX, int rangeY) {
int x = (int) ((Math.random()) * (rangeX + 1));
int y = (int) ((Math.random()) * (rangeY + 1));
return new Vector2d(x, y);
}
Vector2d outsidePoint(int rangeX, int rangeY) {
int x = (int) ((Math.random()) * (rangeX + 1));
int y = (int) ((Math.random()) * (rangeY + 1));
while (x > 3 * rangeX / 8 && x < (3 * rangeX / 8 + rangeX / 4 + 1) && y > 3 * rangeY / 8 && y < (3 * rangeY / 8 + rangeY / 4 + 1)) {
x = (int) ((Math.random()) * (rangeX + 1));
y = (int) ((Math.random()) * (rangeY + 1));
}
return new Vector2d(x, y);
}
Vector2d junglePoint(int rangeX, int rangeY) {
int x = (int) ((Math.random()) * (rangeX / 4 + 1) + 3 * rangeX / 8);
int y = (int) ((Math.random()) * (rangeY / 4 + 1) + 3 * rangeY / 8);
return new Vector2d(x, y);
}
int[] genesArray() {
int[] tab = new int[32];
for (int i = 0; i < 32; i++) {
tab[i] = (int) (Math.random() * 8);
}
return tab;
}
}
<file_sep>package com.company;
public enum Type {
GRASS,
ANIMAL
}
<file_sep>import java.util.*;
abstract class AbstractWorldMap implements IWorldMap {
HashMap<Vector2d, Object> hashMap = new HashMap<Vector2d, Object>();
List<Animal> animals = new LinkedList<Animal>();
List<HayStack> hays = new LinkedList<HayStack>();
@Override
public boolean canMoveTo(Vector2d position) {
return(!isOccupied(position));
}
@Override
public boolean place(Animal animal) {
if(canMoveTo(animal.getPosition())) {
animals.add(animal);
return true;
}
else return false;
}
@Override
public void add(Animal animal){
animals.add(animal);
hashMap.put(animal.getPosition(),animal);
}
@Override
public void run(MoveDirection[] directions) {
Animal temp=null;
for (MoveDirection direction : directions){
if(direction == MoveDirection.LEFT || direction == MoveDirection.RIGHT){
temp=animals.get(0);
temp.move(direction, this);
animals.add(temp);
animals.remove(0);
}
else {
temp = animals.get(0);
Vector2d tmp=temp.getPosition();
Animal p=null;
p=temp.move(direction, this);
if (p == null) animals.add(temp);
else {
hashMap.remove(tmp);
hashMap.put(temp.getPosition(),temp);
}
animals.remove(0);
}
}
// for (Animal i :animals) System.out.println("ANIMAL in list: " + i.getX() + " " + i.getY());
// for (HayStack i :hays) System.out.println("HAY in list");
}
@Override
public boolean isOccupied(Vector2d position) {
// System.out.println(" ");
// System.out.println("Checking if " + position.x + " "+ position.y + " " + "is occupied");
return hashMap.containsKey(position);
// for(HayStack i : hays){
//// System.out.println("There is a hay " + i.getPosition().x + " " + i.getPosition().y);
// if(i.getPosition().getX()==position.getX() && i.getPosition().getY()==position.getY()) return true;
// }
// for(Animal i : animals){
//// System.out.println("There is an animal " + i.getX() + " " + i.getY());
// if(i.getX()==position.getX() && i.getY()==position.getY()) return true;
// }
//// System.out.println("false");
// return false;
}
@Override
public void draw(){
MapVisualizer a=new MapVisualizer(this);
Animal tmp=animals.get(0);
int xmin=tmp.getX();
int xmax=tmp.getX();
int ymin=tmp.getY();
int ymax=tmp.getY();
for(Animal i : animals){
if(i.getX()>xmax)xmax=i.getX();
if(i.getX()<xmin)xmin=i.getX();
if(i.getY()>ymax)ymax=i.getY();
if(i.getY()<ymin)ymin=i.getY();
}
for(HayStack i : hays){
if(i.getX()>xmax)xmax=i.getX();
if(i.getX()<xmin)xmin=i.getX();
if(i.getY()>ymax)ymax=i.getY();
if(i.getY()<ymin)ymin=i.getY();
}
System.out.print(a.draw(new Vector2d(xmin,ymin), new Vector2d(xmax,ymax)));
}
@Override
public Object objectAt(Vector2d position) {
return hashMap.get(position);
// for(HayStack i : hays){
//// System.out.println("There is a hay");
// if(i.getPosition().getX()==position.getX() && i.getPosition().getY()==position.getY()) return i;
// }
// for(Animal i : animals){
//// System.out.println("There is an animal");
// if(i.getX()==position.getX() && i.getY()==position.getY()) return i;
// }
// return null;
}
}
<file_sep>public class vector2d {
int x;
int y;
public vector2d(int x, int y){
this.setX(x);
this.setY(y);
}
public int getX() {
return x;
}
private void setX(int x) {
this.x = x;
}
private void setY(int y) {
this.y = y;
}
public int getY() {
return y;
}
public boolean precedes(vector2d other){
return this.getX() <= other.getX() && this.getY() <= other.getY();
}
public boolean follows(vector2d other){
return this.getX() >= other.getX() && this.getY() >= other.getY();
}
public vector2d upperRight(vector2d other){
int a=this.x;
int b=this.y;
if(other.x>a)a=other.x;
if(other.y>b)b=other.y;
return new vector2d(a,b);
}
public vector2d lowerLeft(vector2d other){
int a=this.x;
int b=this.y;
if(other.x<a)a=other.x;
if(other.y<b)b=other.y;
return new vector2d(a,b);
}
public vector2d add(vector2d other){
int a=this.getX()+other.getX();
int b=this.getY()+other.getY();
vector2d temp = new vector2d(a,b);
return temp;
}
public vector2d subtract(vector2d other){
int a=this.getX()-other.getX();
int b=this.getY()-other.getY();
vector2d temp = new vector2d(a,b);
return temp;
}
public boolean equals(Object other){
if (this == other)
return true;
if (!(other instanceof vector2d))
return false;
vector2d that = (vector2d) other;
// tutaj przeprowadzane jest faktyczne porównanie
return true;
}
public vector2d opposite(){
int a= (-this.getX());
int b= (-this.getY());
return new vector2d(a,b);
}
public String toString(){
String w="(";
w+=x;
w+=',';
w+=y;
w+=')';
return w;
}
}
<file_sep>import java.util.SortedSet;
import java.util.TreeSet;
public class MapBoundary implements IPositionChangeObserver{
// SortedSet<IMapElement> sortedSetX=new TreeSet<>(new MyComparatorX());
// SortedSet<IMapElement> sortedSetY=new TreeSet<>(new MyComparatorY());
SortedSet<Vector2d> sortedSetX=new TreeSet<>(new MyComparatorX());
SortedSet<Vector2d> sortedSetY=new TreeSet<>(new MyComparatorY());
public void add(IMapElement i){
sortedSetX.add(i.getPosition());
sortedSetY.add(i.getPosition());
}
public void positionChanged(Vector2d oldPosition, Vector2d newPosition) {
// if(oldPosition.getX()!=newPosition.getX()){
// if(sortedSetX.first().getX()==oldPosition.getX() && sortedSetX.first().getY()==oldPosition.getY()){
// a=sortedSetX.
// }
// }
SortedSet<Vector2d> subSet = sortedSetX.subSet(oldPosition, newPosition);
if(!subSet.isEmpty()){ sortedSetX.remove(oldPosition); sortedSetX.add(oldPosition); }
subSet = sortedSetY.subSet(oldPosition, newPosition);
if(!subSet.isEmpty()){ sortedSetY.remove(oldPosition); sortedSetY.add(oldPosition); }
}
public Vector2d bottomCorner(){
return(new Vector2d(this.sortedSetX.first().getX(),this.sortedSetY.first().getY()));
}
public Vector2d topCorner(){
return(new Vector2d(this.sortedSetX.last().getX(),this.sortedSetY.last().getY()));
}
}
<file_sep>//import org.junit.Test;
//import static org.junit.Assert.assertEquals;
//OUTDATED
//public class ParserTest {
// @Test
// public void first(){
// String[] test={"forward","forward","forward","right","r"};
// Animal kot=new Animal();
// OptionParser tool=new OptionParser();
// MoveDirection tab[]=tool.parse(test);
// for (MoveDirection element:tab) {
// kot=kot.move(element);
// }
// assertEquals(kot.getX(),2);
// assertEquals(kot.getY(),4);
// assertEquals(kot.getdir(),MapDirection.SOUTH);
// }
// @Test
// public void second(){
// String[] test={"f","f","r","l","l","f","f","b","l"};
// Animal kot=new Animal();
// OptionParser tool=new OptionParser();
// MoveDirection tab[]=tool.parse(test);
// for (MoveDirection element:tab) {
// kot=kot.move(element);
// }
// assertEquals(kot.getX(),1);
// assertEquals(kot.getY(),4);
// assertEquals(kot.getdir(),MapDirection.SOUTH);
// }
// @Test
// public void third(){
// String[] test={"fo","for","forw","forwa","forwar","right","r","r","rig","rl"};
// Animal kot=new Animal();
// OptionParser tool=new OptionParser();
// MoveDirection tab[]=tool.parse(test);
// for (MoveDirection element:tab) {
// kot=kot.move(element);
// }
// assertEquals(kot.getX(),2);
// assertEquals(kot.getY(),2);
// assertEquals(kot.getdir(),MapDirection.WEST);
// }
//}
<file_sep>public class HayStack implements Comparable, IMapElement{
private Vector2d position;
public boolean isAnimal(){
return false;
}
public HayStack(Vector2d position) {
this.position=position;
}
public Vector2d getPosition(){
return this.position;
}
public String toString(){
return "s";
}
public int getX(){
return this.getPosition().getX();
}
public int getY(){
return this.getPosition().getY();
}
@Override
public int compareTo(Object o) {
return this.getX()*1000+this.getY();
}
}
<file_sep>package com.company;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class Evolution {
private int sizeX = 10;
private int sizeY = 10;
private int energy = 10;
private int animalNumber = 10;
private int grassEnergy = 10;
private Map map;
private GridPane VisualizationArray;
private ObservableList<Integer> options;
Evolution(int sizeX, int sizeY, int energy, int animalNumber, int grassEnergy, Stage stage, ObservableList<Integer> options) {
this.sizeX = sizeX;
this.sizeY = sizeY;
this.energy = energy;
this.options = options;
this.animalNumber = animalNumber;
this.grassEnergy = grassEnergy;
stage.setTitle("Step number 1");
this.VisualizationArray = new GridPane();
Generator generator = new Generator();
for (int x = 0; x < this.sizeX; x++) {
for (int y = 0; y < this.sizeY; y++) {
Rectangle rect = new Rectangle(6, 6);
rect.setStroke(DrawType.BLANK.getColor());
rect.setFill(DrawType.BLANK.getColor());
Label label = new Label(" ", rect);
this.VisualizationArray.add(label, x, y);
}
}
this.map = new Map(this.sizeX, this.sizeY, this.grassEnergy, this.VisualizationArray, this.options);
for (int i = 0; i < animalNumber; i++) {
if (this.map.place(new Animal(generator.point(sizeX, sizeY), generator.genesArray(), energy, map.actualIndex))) {
options.add(map.actualIndex);
map.actualIndex += 1;
}
}
Scene scene = new Scene(VisualizationArray);
stage.setScene(scene);
}
boolean next(Text p, Text p2) {
boolean flag = map.process();
print1(p, p2);
VisualizationArray = this.map.drawing();
return flag;
}
private void print1(Text p, Text p2) {
StringBuilder genes = new StringBuilder("[");
for (int i = 0; i < 32; i++) {
genes.append(this.map.genes[i]);
genes.append(", ");
}
genes.append("]");
String energy = "";
energy += this.map.maxAnimalEnergy;
p2.setText(energy);
p.setText(String.valueOf(genes));
}
public Animal getAnimal(int index) {
return map.getAnimal(index);
}
}
<file_sep>package sample;
public class Block {
boolean processed = false;
int value;
Position position;
Block(Position position, int value) {
this.value = value;
this.position = position;
}
Block join(Block block) {
this.value = this.value * 2;
block.value = 0;
return this;
}
Block move(Direction dir, SquareMap map) {
Position p = this.position.add(dir.toPosition());
if (map.bound(p)) this.position.add(dir.toPosition());
return this;
}
void setPosition(Position position) {
this.position = position;
}
}
<file_sep>import java.util.*;
public class Main {
public static void main(String[] args) {
// Animal kot = new Animal();
//// String temp[]=new String[5];
//// temp[0]="forward";
//// temp[1]="for";
//// temp[2]="forward";
//// temp[3]="right";
//// temp[4]="right";
////
//// OptionParser tool=new OptionParser();
//// MoveDirection tab[]=tool.parse(temp);
//// for (MoveDirection element:tab) {
//// kot=kot.move(element);
//// }
//// System.out.println(kot.toString());
//"f","b","r","l","f","f","l","r","f","f","f","f","f","f","f","f"
String[] test={"f","b","r","l","f","f","l","r","f","f","f","f","f","f","f","f"};
MoveDirection[] directions = new OptionParser().parse(test);
List<HayStack> hays = new LinkedList<HayStack>();
hays.add(new HayStack(new vector2d(-4,-4)));
hays.add(new HayStack(new vector2d(7,7)));
hays.add(new HayStack(new vector2d(3,6)));
hays.add(new HayStack(new vector2d(2,0)));
IWorldMap map = new UnboundedMap(10, 5, hays);
map.place(new Animal(map));
map.place(new Animal(map,new vector2d(3,4)));
map.run(directions);
map.draw();
}
}
<file_sep>import java.util.*;
public class UnboundedMap extends AbstractWorldMap {
//
// Object map[][];
// int width;
// int height;
// List<Animal> animals = new LinkedList<Animal>();
public UnboundedMap(int width, int height, List<HayStack> hays){
map = new Object[width+1][height+1];
this.width = width;
this.height = height;
for(HayStack i:hays){
if(i.getPosition().getX()<width && i.getPosition().getX()>=0
&& i.getPosition().getY()<height && i.getPosition().getY()>=0) {
if (canMoveTo(i.getPosition())) {
map[i.getPosition().getX()][i.getPosition().getY()] = i;
}
else throw new IllegalArgumentException("position " + i.getPosition().x + " " + i.getPosition().y + " is already occupied");
}
}
}
public String toString(){
MapVisualizer a=new MapVisualizer(this);
String b=a.draw(new vector2d(0,0), new vector2d(width,height));
return b;
}
// @Override
// public boolean canMoveTo(vector2d position) {
// if(position.getX()>=width || position.getX()<0
// || position.getY()>=height || position.getY()<0) return false;
// return(!isOccupied(position));
// }
//
// @Override
// public void clear(vector2d position){
// map[position.getX()][position.getY()]=null;
// }
//
// public boolean place(Animal animal) {
// if(canMoveTo(animal.getPosition())) {
// map[animal.getPosition().getX()][animal.getPosition().getY()] = animal;
// animals.add(animal);
// return true;
// }
// return false;
// }
//
// public boolean place(HayStack hay) {
// if(canMoveTo(hay.getPosition())) {
// map[hay.getPosition().getX()][hay.getPosition().getY()] = hay;
//// animals.add(animal);
// return true;
// }
// return false;
// }
//
// @Override
// public void run(MoveDirection[] directions) {
// Animal temp=null;
// for (MoveDirection direction : directions){
// if(direction == MoveDirection.LEFT || direction == MoveDirection.RIGHT){
// temp=animals.get(0);
// temp.move(direction, this);
// animals.add(temp);
// animals.remove(0);
// }
// else {
// temp = animals.get(0);
// Animal p=null;
// p=temp.move(direction, this);
// if (p == null) animals.add(temp);
// animals.remove(0);
// }
// //animals.add(temp);
// }
// }
//
// @Override
// public boolean isOccupied(vector2d position) {
// return !(map[position.getX()][position.getY()]==null);
// }
//
// @Override
// public void draw(){
// MapVisualizer a=new MapVisualizer(this);
//
// System.out.print(a.draw(new vector2d(0,0), new vector2d(width-1,height-1)));
// }
//
// @Override
// public Object objectAt(vector2d position) {
// if(position.getX()>=width || position.getX()<0
// || position.getY()>=height || position.getY()<0)return null;
// return map[position.getX()][position.getY()];
// }
}
| 6856ccf0409c4d55bdcdec87b68e63ea437ba0a3 | [
"Java"
] | 19 | Java | JanTry/PO-2019-2020 | e8733c111541749bc8dfa8433bac8bc2afff5e77 | 389fb515dc137ac923f09f324f0c39c7d243242a |
refs/heads/master | <file_sep>const regex = /\{\{(.+?)\}\}/g;
function renderer(str, vars) {
for (var va in vars) {
if (vars.hasOwnProperty(va)) {
this[va] = vars[va];
}
}
this.str = str;
const renderVars = str.match(regex)
for (var i = 0; i < renderVars.length; i++) {
this.str = this.str.replace(
renderVars[i],
eval(`this.${renderVars[i].substring(2, renderVars[i].length-2)}`)
);
}
}
module.exports = (str, vars) => {
let renderObj = new renderer(str, vars);
return renderObj.str;
};
<file_sep>const eassry = require('./index.js');
let var1 = "testing";
let var2 = "Neat";
let nonRendered = "I'm curently {{var1}} EaSSRy. {{var2}} huh? {{var1}}, {{custom.a}}{{custom.b}}";
console.log(
eassry(nonRendered, {
var1,
var2,
custom: {a: "how cool", b: "!"}
})
)
<file_sep>
## Install
```
npm i eassry --save
```
## How To Use
1. Require EaSSRy
```javascript
const eassry = require('eassry');
```
2. Make some variables
```javascript
let var1 = "testing";
let var2 = "Neat";
let nonRendered = "I'm curently {{var1}} EaSSRy. {{var2}} huh? {{var1}}, {{custom.a}}{{custom.b}}";
```
3. Use eassry( string, {variables} ) to render your string.
```javascript
let rendered = eassry(nonRendered, {
var1,
var2,
custom: {a: "how cool", b: "!"}
})
console.log(rendered) // -> I'm curently testing EaSSRy. Neat huh? testing, how cool!
```
It's that easy to use.
## License
```
The MIT License (MIT)
Copyright (c) 2017 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
```
| fd2c7f31ebb2c67ce7ef55931da25dcc9905a869 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | leahlundqvist/EaSSRy | 4327d1cb092ebe9d1e92cb5a718afb5ef53b559d | c1950169d4941a1d81355f877095f36dc3be7e52 |
refs/heads/master | <repo_name>timotech/LoginAuthSystem<file_sep>/LoginAuthSystem/Controllers/AdminController.cs
using LoginAuthSystem.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace LoginAuthSystem.Controllers
{
public class AdminController : Controller
{
// GET: Admin
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult AddRoles()
{
RolesModel rm = new RolesModel();
return View(rm);
}
//Save New Roles
[HttpPost]
public ActionResult AddRoles(RolesModel rm)
{
if(ModelState.IsValid)
{
using (var db = new ApplicationDbContext())
{
IdentityResult IdRoleResult;
var roleStore = new RoleStore<IdentityRole>(db);
var roleMgr = new RoleManager<IdentityRole>(roleStore);
if (!roleMgr.RoleExists(rm.Name))
{
IdRoleResult = roleMgr.Create(new IdentityRole(rm.Name));
if (!IdRoleResult.Succeeded)
{
return View();
}
return RedirectToAction("AddRoles");
}
}
}
return View();
}
[HttpGet]
public ActionResult AddPost()
{
PostSetup ps = new PostSetup();
return View(ps);
}
[HttpPost]
public ActionResult AddPost(PostSetup ps)
{
if(ModelState.IsValid)
{
using (var db = new ApplicationDbContext())
{
db.PostSetups.Add(ps);
db.SaveChanges();
return RedirectToAction("AddPost");
}
}
return View(ps);
}
[HttpGet]
public ActionResult EditPost(int id)
{
using (var db = new ApplicationDbContext())
{
var post = db.PostSetups.Single(x => x.ID == id);
return View(post);
}
}
public ActionResult EditPost(PostSetup ps)
{
using (var db = new ApplicationDbContext())
{
if(ModelState.IsValid)
{
}
}
return View(ps);
}
[HttpPost]
public ActionResult DeletePost(int id)
{
var db = new ApplicationDbContext();
var entity = db.PostSetups.Where(x => x.ID == id).FirstOrDefault();
db.PostSetups.Remove(entity);
db.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult PostDetails(int id)
{
return View();
}
}
}<file_sep>/LoginAuthSystem/Startup.cs
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(LoginAuthSystem.Startup))]
namespace LoginAuthSystem
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
<file_sep>/LoginAuthSystem/Global.asax.cs
using LoginAuthSystem.Logic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace LoginAuthSystem
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
RoleActions r = new RoleActions();
r.createAdmin();
r.CreateUsers();
}
}
}
<file_sep>/README.md
# LoginAuthSystem
This is a Login Authenticated System For Altara
This system uses asp.net Mvc for Development with Authentication using asp.net Identity with Entity Framework
<file_sep>/LoginAuthSystem/Models/PostSetup.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace LoginAuthSystem.Models
{
[Table("tbl_Posts")]
public class PostSetup
{
public int ID { get; set; }
public string Title { get; set; }
[AllowHtml]
public string Description { get; set; }
public string PicPath { get; set; }
public DateTime DateAdded { get; set; }
[NotMapped]
public HttpPostedFileBase fleUploadImage { get; set; }
}
} | e3f52dfbc614aa589d4d2209d3fbf1a62c7bee98 | [
"Markdown",
"C#"
] | 5 | C# | timotech/LoginAuthSystem | 642bcba95fe02e40c618d88b556412d651c79b10 | 93840d2d8c6887a7818e639b3e259d0c2a998fd7 |
refs/heads/master | <file_sep>group 'com.example'
version '1.0-SNAPSHOT'
apply plugin: 'java'
repositories {
mavenCentral()
}
task compilej6(type: JavaCompile) {
source = fileTree(dir: "src/main/java")
classpath = sourceSets.main.compileClasspath
destinationDir = sourceSets.main.output.classesDir
includes = ['com/example/Java6Main.java']
sourceCompatibility = 1.6
targetCompatibility = 1.6
}
compileJava {
excludes = ['**/Java6Main.java']
sourceCompatibility = 1.8
targetCompatibility = 1.8
options.encoding = 'UTF-8'
}
tasks.compileJava.dependsOn('compilej6')
<file_sep>package com.example;
public class Java8Main {
public static void main(String[] args) {
System.out.println("I am running Java 8");
}
}
<file_sep>package com.example;
public class Java6Main {
public static void main(String[] args) {
System.out.println("I am not running Java 8!");
}
}
| 4c04078467ad446713abd014f1b0eb12e69a8037 | [
"Java",
"Gradle"
] | 3 | Gradle | diesieben07/MultiJavaBuild | 53a51ae782f7a6dc30bc8d35ae87b6746bc57adc | a48a548dd65bd3c6af2b1edc130f942100529daf |
refs/heads/master | <file_sep>//go:generate npm run build
package main
import (
"log"
"net/http"
"os"
_ "github.com/iheanyi/go-vue-statik/cmd/sampleapp/statik"
"github.com/rakyll/statik/fs"
)
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "1337"
}
statikFS, err := fs.New()
if err != nil {
log.Fatal(err)
}
staticHandler := http.FileServer(statikFS)
// Serves up the index.html file regardless of the path.
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
r.URL.Path = "/"
staticHandler.ServeHTTP(w, r)
})
http.Handle("/static/", staticHandler)
http.ListenAndServe(":"+port, nil)
}
<file_sep># Go-Vue-Statik
## Getting Started
### Installing Dependencies
1) `cd cmd/sampleapp && yarn` to install dependencies from npm.
2) Use `dep` to install Go dependencies.
### Building
1) Run `go generate` from `cmd/sampleapp` to build the front-end files needed.
2) Run `go install ./...` to install the sampleapp dependencies.
3) Run `sampleapp` and visit http://localhost:1337 to view the project.
[Demo deployed to Heroku](https://go-vue-statik.herokuapp.com/)
| a3ce0fde56a4aa198cbb26fb2ef38b84c08c9144 | [
"Markdown",
"Go"
] | 2 | Go | iheanyi/go-vue-statik | 73f2089c4f2e7b60a4b54d70c1220c66e0d34012 | 556b932ee6bc935537b5df9da187f3bae1556c57 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DSW2_Proyecto_Huron_Azul.localhost;
namespace DSW2_Proyecto_Huron_Azul.Controllers
{
public class UsuarioController : Controller
{
Huron_Azul_Service ws = new Huron_Azul_Service();
public ActionResult Editar()
{
return View((BeanUsuario)Session["Usuario"]);
}
[HttpPost]
public ActionResult Editar(BeanUsuario u)
{
if (u.EMAIL == null)
{
u.EMAIL = "";
}
if (u.TELEFONO == null)
{
u.TELEFONO = "";
}
string msg = ws.u_editar(u);
Session["Usuario"] = u;
return RedirectToAction("Index", "Confirmacion", new { mensaje = msg });
}
public ActionResult Registrar() {
return View(new BeanUsuario());
}
[HttpPost]
public ActionResult Registrar(BeanUsuario u) {
if (u.EMAIL == null)
{
u.EMAIL = "";
}
if (u.TELEFONO == null)
{
u.TELEFONO = "";
}
string msg = ws.u_registrar(u);
return RedirectToAction("Index", "Confirmacion", new { mensaje = msg });
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using DSW2_Proyecto_Huron_Azul.localhost;
namespace DSW2_Proyecto_Huron_Azul.Controllers
{
public class ProductoController : Controller
{
Huron_Azul_Service ws = new Huron_Azul_Service();
public ActionResult Registrar()
{
SelectList cboCat = new SelectList(ws.cat_listar(), "CODCAT", "DESCCAT");
ViewBag.cat = cboCat;
BeanProducto p = new BeanProducto();
return View(p);
}
[HttpPost]
public ActionResult Registrar(BeanProducto p, HttpPostedFileBase archivo)
{
string msg;
SelectList cboCat = new SelectList(ws.cat_listar(), "CODCAT", "DESCCAT", p.CATPROD);
if (archivo == null)
{
p.FOTOPROD = "-";
msg = ws.pro_registrar(p);
}
else
{
bool q = Path.GetExtension(archivo.FileName) == ".jpg";
bool r = Path.GetExtension(archivo.FileName) == ".png";
bool s = Path.GetExtension(archivo.FileName) == ".gif";
//si el archivo no es jpg, png o gif
if (!q && !r && !s)
{
ViewBag.ext_invalida = "Debe seleccionar una imagen en formato jpg,png o gif";
ViewBag.cat = cboCat;
return View(p);
}
try
{
string foto = "prod" + ws.pro_autogenera() + Path.GetExtension(archivo.FileName);
archivo.SaveAs(Server.MapPath("~/imagenes/productos/" + foto));
p.FOTOPROD = foto;
msg = ws.pro_registrar(p);
}
catch (Exception e)
{
msg = "Hubo un error al cargar el archivo: " + e.Message;
}
}
ViewBag.cat = cboCat;
return RedirectToAction("Index", "Confirmacion", new { mensaje = msg });
}
public ActionResult Editar(string codprod)
{
BeanProducto p = ws.pro_listar("1","0","").Where(x => x.CODPROD == codprod).FirstOrDefault();
SelectList cboCat = new SelectList(ws.cat_listar(), "CODCAT", "DESCCAT");
ViewBag.cat = cboCat;
return View(p);
}
[HttpPost]
public ActionResult Editar(BeanProducto p, HttpPostedFileBase archivo)
{
string msg;
SelectList cboCat = new SelectList(ws.cat_listar(), "CODCAT", "DESCCAT", p.CATPROD);
if (archivo == null)
{
msg = ws.pro_editar(p);
}
else
{
bool q = Path.GetExtension(archivo.FileName) == ".jpg";
bool r = Path.GetExtension(archivo.FileName) == ".png";
bool s = Path.GetExtension(archivo.FileName) == ".gif";
//si el archivo no es jpg, png o gif
if (!q && !r && !s)
{
ViewBag.ext_invalida = "Debe seleccionar una imagen en formato jpg,png o gif";
ViewBag.cat = cboCat;
return View(p);
}
try
{
string foto = "prod" + p.CODPROD + Path.GetExtension(archivo.FileName);
archivo.SaveAs(Server.MapPath("~/imagenes/productos/" + foto));
p.FOTOPROD = foto;
msg = ws.pro_editar(p);
}
catch (Exception e)
{
msg = "Hubo un error al cargar el archivo: " + e.Message;
}
}
ViewBag.cat = cboCat;
return RedirectToAction("Index", "Confirmacion", new { mensaje = msg });
}
public ActionResult Inactivar(string codprod)
{
string msg = ws.pro_inactivar(codprod);
return RedirectToAction("Index", "Confirmacion", new { mensaje = msg });
}
}
}<file_sep># DSW2_Proyecto_Huron_Azul_Cliente
Aplicación web ASP.net con patrón MVC con conexión de referencia a Servicio SOAP Huron Azul
## Para ejecutar el proyecto
1. Clonar la solución en un IDE como Visual Studio 2019.
1. Limpiar y Compilar la solución
1. El cliente está configurado para ejecutarse en la misma máquina que el servicio SOAP apuntando a "localhost:8080". Hacer las respectivas modificaciones si el SOAP se ejecuta de forma remota.
1. Ejecutar el proyecto en un servidor IIS local.
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DSW2_Proyecto_Huron_Azul.localhost;
namespace DSW2_Proyecto_Huron_Azul.Controllers
{
public class LogueoController : Controller
{
Huron_Azul_Service ws = new Huron_Azul_Service();
// GET: Logueo
public ActionResult Index(string mensaje)
{
ViewBag.mensaje = mensaje;
return View();
}
public ActionResult Log_In(string id, string pwd) {
BeanUsuario u = ws.u_logueo(id, pwd);
if (u.CODUSUARIO==null) return RedirectToAction("Index", new { mensaje = "Logueo Incorrecto" });
Session["Usuario"] = u;
return RedirectToAction("Index", "Home");
}
public ActionResult Log_Out() {
Session["Usuario"] = null;
return RedirectToAction("Index", "Home");
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace DSW2_Proyecto_Huron_Azul.Controllers
{
public class ConfirmacionController : Controller
{
// GET: Confirmacion
public ActionResult Index(string mensaje)
{
ViewBag.mensaje = mensaje;
return View();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DSW2_Proyecto_Huron_Azul.localhost;
using DSW2_Proyecto_Huron_Azul.Models;
namespace DSW2_Proyecto_Huron_Azul.Controllers
{
public class HomeController : Controller
{
Huron_Azul_Service ws = new Huron_Azul_Service();
public ActionResult Index()
{
if (Session["carrito"] == null) Session["carrito"] = new List<Carrito>();
if (Session["Usuario"] == null) return View(ws.pro_listar("2","0",""));
else
{
BeanUsuario u = (BeanUsuario)Session["Usuario"];
return View(ws.pro_listar(u.TIPOUSUARIO.ToString(), "0", ""));
}
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace DSW2_Proyecto_Huron_Azul.Models
{
public class Carrito
{
[Display(Name = "Nro. producto")]
public long codigo { get; set; }
[Display(Name = "Nombre")]
public string descripcion { get; set; }
[Display(Name = "Precio Unitario")]
public decimal precio { get; set; }
[Display(Name = "Cantidad solicitada")]
public int cantidad { get; set; }
[Display(Name = "Monto")]
public decimal monto { get { return precio * cantidad; } }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DSW2_Proyecto_Huron_Azul.localhost;
namespace DSW2_Proyecto_Huron_Azul.Controllers
{
public class CitaController : Controller
{
Huron_Azul_Service ws = new Huron_Azul_Service();
List<SelectListItem> Lista_Horas = new List<SelectListItem> {
new SelectListItem{Selected=true,Value="00:00:00",Text="Seleccione una hora" },
new SelectListItem{Selected=false,Value="10:00:00",Text="10:00 am" },
new SelectListItem{Selected=false,Value="10:30:00",Text="10:30 am" },
new SelectListItem{Selected=false,Value="11:00:00",Text="11:00 am" },
new SelectListItem{Selected=false,Value="11:30:00",Text="11:30 am" },
new SelectListItem{Selected=false,Value="12:00:00",Text="12:00 pm" },
new SelectListItem{Selected=false,Value="12:30:00",Text="12:30 pm" },
new SelectListItem{Selected=false,Value="13:00:00",Text="01:00 pm" },
new SelectListItem{Selected=false,Value="13:30:00",Text="01:30 pm" },
new SelectListItem{Selected=false,Value="14:00:00",Text="02:00 pm" },
new SelectListItem{Selected=false,Value="14:30:00",Text="02:30 pm" },
new SelectListItem{Selected=false,Value="15:00:00",Text="03:00 pm" },
new SelectListItem{Selected=false,Value="15:30:00",Text="03:30 pm" },
new SelectListItem{Selected=false,Value="16:00:00",Text="04:00 pm" },
new SelectListItem{Selected=false,Value="16:30:00",Text="04:30 pm" },
new SelectListItem{Selected=false,Value="17:00:00",Text="05:00 pm" },
new SelectListItem{Selected=false,Value="17:30:00",Text="05:30 pm" },
new SelectListItem{Selected=false,Value="18:00:00",Text="06:00 pm" },
new SelectListItem{Selected=false,Value="18:30:00",Text="06:30 pm" },
new SelectListItem{Selected=false,Value="19:00:00",Text="07:00 pm" },
new SelectListItem{Selected=false,Value="19:30:00",Text="07:30 pm" }
};
public ActionResult Registrar()
{
BeanUsuario u_sesion = (BeanUsuario)Session["Usuario"];
if (u_sesion == null) return RedirectToAction("Index", "Logueo");
ViewBag.horas = new SelectList(Lista_Horas, "Value", "Text");
ViewBag.sedes = new SelectList(ws.s_listar(), "CODSEDE", "REFSEDE");
BeanCita c = new BeanCita();
c.CLIENTE = u_sesion.CODUSUARIO;
return View(c);
}
[HttpPost]
public ActionResult Registrar(BeanCita c, DateTime fecha, string hora)
{
c.FECHA_HORA = fecha.ToString("yyyy-M-d ") + hora;
string msg = ws.ci_registrar(c);
ViewBag.horas = new SelectList(Lista_Horas, "Value", "Text", hora);
ViewBag.sedes = new SelectList(ws.s_listar(), "CODSEDE", "REFSEDE", c.SEDE);
return RedirectToAction("Index", "Confirmacion", new { mensaje = msg });
}
public ActionResult Listar(string usuario)
{
BeanCitaTuneado[] lista = ws.ci_listar(usuario);
if (lista == null) return RedirectToAction("Index", "Home");
return View(lista);
}
public ActionResult Detalle(string nrocita)
{
return View(ws.ci_detalle(nrocita));
}
public ActionResult Cancelar(string nrocita)
{
string msg = ws.ci_cancelar(nrocita);
return RedirectToAction("Index", "Confirmacion", new { mensaje = msg });
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DSW2_Proyecto_Huron_Azul.localhost;
using DSW2_Proyecto_Huron_Azul.Models;
namespace DSW2_Proyecto_Huron_Azul.Controllers
{
public class PedidoController : Controller
{
Huron_Azul_Service ws = new Huron_Azul_Service();
public ActionResult Carrito()
{
if (Session["carrito"] == null) Session["carrito"] = new List<Carrito>();
return View((List<Carrito>)Session["carrito"]);
}
public ActionResult Add_producto(long codprod, int cantidad)
{
//1. creo una lista de carrito y le asigno la lista de carrito en sesion
List<Carrito> carrito = (List<Carrito>)Session["carrito"];
//2.busco en la lista si ya existe un item carrito con el codigo de producto del parametro
Carrito c = carrito.Where(x => x.codigo == codprod).FirstOrDefault();
if (c != null)
{
//3.si existe, aumentar la cantidad
c.cantidad += cantidad;
}
else
{
//3.si no existe, obtengo el producto que tenga como codigo el parametro codprod
BeanProducto p = ws.pro_listar("1", "0", "").Where(x => x.CODPROD == codprod.ToString()).FirstOrDefault();
//4. creo una nuevo objeto carrito y le paso informacion del producto obtenido y la cantidad
c = new Carrito
{
codigo = long.Parse(p.CODPROD),
descripcion = p.DESCPROD,
precio = decimal.Parse(p.PREPROD),
cantidad = cantidad
};
//5. añado el objeto carrito a la lista de sesion carrito
carrito.Add(c);
}
//Se redirecciona a la pantalla de confirmacion
return RedirectToAction("Index", "Confirmacion", new { mensaje = "El producto fue añadido al carrito." });
}
public ActionResult Delete_producto(long codprod)
{
List<Carrito> carrito = (List<Carrito>)Session["carrito"];
Carrito c = carrito.Where(x => x.codigo == codprod).FirstOrDefault();
carrito.Remove(c);
return RedirectToAction("Carrito");
}
public ActionResult Registrar()
{
BeanUsuario u_sesion = (BeanUsuario)Session["Usuario"];
if (u_sesion == null) return RedirectToAction("Index", "Logueo");
List<Carrito> carrito = (List<Carrito>)Session["carrito"];
ViewBag.sedes = new SelectList(ws.s_listar(), "CODSEDE", "REFSEDE");
BeanPedido p = new BeanPedido
{
CLIENTE = u_sesion.CODUSUARIO,
FECPEDIDO = DateTime.Now.ToString("yyyy-M-d HH:mm:ss"),
MONTO = carrito.Sum(x => x.monto).ToString()
};
return View(p);
}
[HttpPost]
public ActionResult Registrar(BeanPedido p)
{
string msg;
List<BeanPedidoDetalle> temp = new List<BeanPedidoDetalle>();
foreach (Carrito reg in (List<Carrito>)Session["carrito"])
{
BeanPedidoDetalle pd = new BeanPedidoDetalle
{
PRODUCTO = reg.codigo.ToString(),
CANTIDAD = reg.cantidad.ToString(),
MONTO = reg.monto.ToString()
};
temp.Add(pd);
}
msg = ws.ped_registrar(p, temp.ToArray());
ws.listaBeanPedidoDetalle(temp.ToArray());
Session["carrito"] = null;
ViewBag.sedes = new SelectList(ws.s_listar(), "CODSEDE", "REFSEDE", p.SEDE);
return RedirectToAction("Index", "Confirmacion", new { mensaje = msg });
}
public ActionResult Listar(string usuario)
{
BeanPedidoTuneado[] lista = ws.ped_listar(usuario);
if (lista == null) return RedirectToAction("Index", "Home");
return View(lista);
}
public ActionResult Detalle(string nropedido)
{
return View(ws.ped_detalle(nropedido));
}
}
} | a7d9071f83eebfb69e6d1a215694228f7e9e0dfb | [
"Markdown",
"C#"
] | 9 | C# | hreinosoflores/DSW2_Proyecto_Huron_Azul_Cliente | 49f6dac6b33baea8d3408f58db4bcfbe521e1750 | 19dee2808142ba22e9d345faa9b174dfbd231032 |
refs/heads/main | <repo_name>chinni43/grade<file_sep>/grade.c
#include<stdio.h>
void main()
{
int marks;
printf("enter your marks");
scanf("%d",&marks);
printf("marks=%d",marks);
if(marks<0 || marks>100)
{
printf(" marks should not exceed 100");
}
else if(marks<40)
{
printf("you got E grade");
}
else if(marks>=85 && marks<100)
{
printf("you got A grade ");
}
else if(marks>=70 && marks<84)
{
printf("you got B grade");
}
else if(marks>=55 && marks<69)
{
printf("you got C grade);
}
else if(marks>=40 && marks<54)
{
printf("you got D grade ");
}
getch();
}
| 87e0232285d30db8b27d70c6f7db2a5e087bcb48 | [
"C"
] | 1 | C | chinni43/grade | 6d7b7e7b6783ff87f00c1d68a988dac77386acc3 | 7d0d727e7854e7135e654c28f277dbb0e672831d |
refs/heads/master | <file_sep>#====================== BEGIN GPL LICENSE BLOCK ======================
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
#======================= END GPL LICENSE BLOCK ========================
# <pep8 compliant>
import bpy
from ...utils.bones import compute_chain_x_axis, align_bone_x_axis, align_bone_z_axis
from ...utils.bones import align_bone_to_axis, flip_bone
from ...utils.naming import make_derived_name
from ..widgets import create_foot_widget, create_ballsocket_widget
from ...base_rig import stage
from .limb_rigs import BaseLimbRig
class Rig(BaseLimbRig):
"""Paw rig."""
segmented_orgs = 3
def initialize(self):
if len(self.bones.org.main) != 4:
self.raise_error("Input to rig type must be a chain of 4 bones.")
super().initialize()
def prepare_bones(self):
orgs = self.bones.org.main
foot_x = self.vector_without_z(self.get_bone(orgs[2]).y_axis).cross((0, 0, 1))
if self.params.rotation_axis == 'automatic':
axis = compute_chain_x_axis(self.obj, orgs[0:2])
for bone in orgs:
align_bone_x_axis(self.obj, bone, axis)
elif self.params.auto_align_extremity:
if self.main_axis == 'x':
align_bone_x_axis(self.obj, orgs[2], foot_x)
align_bone_x_axis(self.obj, orgs[3], -foot_x)
else:
align_bone_z_axis(self.obj, orgs[2], foot_x)
align_bone_z_axis(self.obj, orgs[3], -foot_x)
####################################################
# EXTRA BONES
#
# ctrl:
# heel:
# Foot heel control
# mch:
# toe_socket:
# IK toe orientation bone.
#
####################################################
####################################################
# IK controls
def get_extra_ik_controls(self):
return super().get_extra_ik_controls() + [self.bones.ctrl.heel]
def make_ik_control_bone(self, orgs):
name = self.copy_bone(orgs[3], make_derived_name(orgs[2], 'ctrl', '_ik'))
if self.params.rotation_axis == 'automatic' or self.params.auto_align_extremity:
align_bone_to_axis(self.obj, name, 'y', flip=True)
else:
flip_bone(self.obj, name)
bone = self.get_bone(name)
bone.tail[2] = bone.head[2]
bone.roll = 0
vec = self.get_bone(orgs[3]).tail - self.get_bone(orgs[2]).head
self.get_bone(name).length = self.vector_without_z(vec).length
return name
def register_switch_parents(self, pbuilder):
super().register_switch_parents(pbuilder)
pbuilder.register_parent(self, self.bones.org.main[3], exclude_self=True, tags={'limb_end'})
def make_ik_ctrl_widget(self, ctrl):
create_foot_widget(self.obj, ctrl)
####################################################
# Heel control
@stage.generate_bones
def make_heel_control_bone(self):
org = self.bones.org.main[2]
name = self.copy_bone(org, make_derived_name(org, 'ctrl', '_heel_ik'))
self.bones.ctrl.heel = name
flip_bone(self.obj, name)
@stage.parent_bones
def parent_heel_control_bone(self):
self.set_bone_parent(self.bones.ctrl.heel, self.get_ik_control_output())
@stage.configure_bones
def configure_heel_control_bone(self):
bone = self.get_bone(self.bones.ctrl.heel)
bone.lock_location = True, True, True
bone.lock_scale = True, True, True
@stage.generate_widgets
def generate_heel_control_widget(self):
create_ballsocket_widget(self.obj, self.bones.ctrl.heel)
####################################################
# FK parents MCH chain
@stage.generate_bones
def make_toe_socket_bone(self):
org = self.bones.org.main[3]
self.bones.mch.toe_socket = self.copy_bone(org, make_derived_name(org, 'mch', '_ik_socket'))
def parent_fk_parent_bone(self, i, parent_mch, prev_ctrl, org, prev_org):
if i == 3:
self.set_bone_parent(parent_mch, prev_org, use_connect=True)
self.set_bone_parent(self.bones.mch.toe_socket, self.get_ik_control_output())
else:
super().parent_fk_parent_bone(i, parent_mch, prev_ctrl, org, prev_org)
def rig_fk_parent_bone(self, i, parent_mch, org):
if i == 3:
con = self.make_constraint(parent_mch, 'COPY_TRANSFORMS', self.bones.mch.toe_socket)
self.make_driver(con, 'influence', variables=[(self.prop_bone, 'IK_FK')], polynomial=[1.0, -1.0])
else:
super().rig_fk_parent_bone(i, parent_mch, org)
####################################################
# IK system MCH
ik_input_head_tail = 1.0
def get_ik_input_bone(self):
return self.bones.ctrl.heel
@stage.parent_bones
def parent_ik_mch_chain(self):
super().parent_ik_mch_chain()
self.set_bone_parent(self.bones.mch.ik_target, self.bones.ctrl.heel)
####################################################
# Deform chain
def rig_deform_bone(self, i, deform, entry, next_entry, tweak, next_tweak):
super().rig_deform_bone(i, deform, entry, next_entry, tweak, next_tweak)
if tweak and not (next_tweak or next_entry):
self.make_constraint(deform, 'STRETCH_TO', entry.org, head_tail=1.0, keep_axis='SWING_Y')
####################################################
# Settings
@classmethod
def parameters_ui(self, layout, params):
super().parameters_ui(layout, params, 'Claw')
def create_sample(obj):
# generated by rigify.utils.write_metarig
bpy.ops.object.mode_set(mode='EDIT')
arm = obj.data
bones = {}
bone = arm.edit_bones.new('thigh.L')
bone.head[:] = 0.0000, 0.0017, 0.7379
bone.tail[:] = 0.0000, -0.0690, 0.4731
bone.roll = 0.0000
bone.use_connect = False
bones['thigh.L'] = bone.name
bone = arm.edit_bones.new('shin.L')
bone.head[:] = 0.0000, -0.0690, 0.4731
bone.tail[:] = 0.0000, 0.1364, 0.2473
bone.roll = 0.0000
bone.use_connect = True
bone.parent = arm.edit_bones[bones['thigh.L']]
bones['shin.L'] = bone.name
bone = arm.edit_bones.new('foot.L')
bone.head[:] = 0.0000, 0.1364, 0.2473
bone.tail[:] = 0.0000, 0.0736, 0.0411
bone.roll = -0.0002
bone.use_connect = True
bone.parent = arm.edit_bones[bones['shin.L']]
bones['foot.L'] = bone.name
bone = arm.edit_bones.new('toe.L')
bone.head[:] = 0.0000, 0.0736, 0.0411
bone.tail[:] = 0.0000, -0.0594, 0.0000
bone.roll = -3.1416
bone.use_connect = True
bone.parent = arm.edit_bones[bones['foot.L']]
bones['toe.L'] = bone.name
bpy.ops.object.mode_set(mode='OBJECT')
pbone = obj.pose.bones[bones['thigh.L']]
pbone.rigify_type = 'limbs.paw'
pbone.lock_location = (False, False, False)
pbone.lock_rotation = (False, False, False)
pbone.lock_rotation_w = False
pbone.lock_scale = (False, False, False)
pbone.rotation_mode = 'QUATERNION'
try:
pbone.rigify_parameters.fk_layers = [False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False]
except AttributeError:
pass
try:
pbone.rigify_parameters.tweak_layers = [False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, True, False, False, False, False, False, False, False, False, False, False, False, False, False]
except AttributeError:
pass
try:
pbone.rigify_parameters.limb_type = "paw"
except AttributeError:
pass
pbone = obj.pose.bones[bones['shin.L']]
pbone.rigify_type = ''
pbone.lock_location = (False, False, False)
pbone.lock_rotation = (False, False, False)
pbone.lock_rotation_w = False
pbone.lock_scale = (False, False, False)
pbone.rotation_mode = 'QUATERNION'
pbone = obj.pose.bones[bones['foot.L']]
pbone.rigify_type = ''
pbone.lock_location = (False, False, False)
pbone.lock_rotation = (False, False, False)
pbone.lock_rotation_w = False
pbone.lock_scale = (False, False, False)
pbone.rotation_mode = 'QUATERNION'
pbone = obj.pose.bones[bones['toe.L']]
pbone.rigify_type = ''
pbone.lock_location = (False, False, False)
pbone.lock_rotation = (False, False, False)
pbone.lock_rotation_w = False
pbone.lock_scale = (False, False, False)
pbone.rotation_mode = 'QUATERNION'
try:
pbone.rigify_parameters.limb_type = "paw"
except AttributeError:
pass
bpy.ops.object.mode_set(mode='EDIT')
for bone in arm.edit_bones:
bone.select = False
bone.select_head = False
bone.select_tail = False
for b in bones:
bone = arm.edit_bones[bones[b]]
bone.select = True
bone.select_head = True
bone.select_tail = True
arm.edit_bones.active = bone
| 7d3013cb7754481e78b5fa4adc1a95e07b982e0d | [
"Python"
] | 1 | Python | fire-archive/blender-addons | 1416eacdbea17df75634fc972e75d0bb8dd195f9 | e4e8c856b015f56d32e50d764b5a0cb3365e0ccd |
refs/heads/master | <repo_name>kitchell/STRright<file_sep>/js/tractname.js
var tractname = 'STR_right';
var fulltractname = 'Right Superior Thalamic Radiation'
// color for surfaces and point
var surfcolor = 0xd4d170;
// 4a95a1
var pointcolor = 0x1a3f7a;
var cameraPC1y = 500;
var cameraPC2y = 2500; | d7e91651375810ac21d7c6ad0e462ceba8d72091 | [
"JavaScript"
] | 1 | JavaScript | kitchell/STRright | badf4e39a98595f83c8e7c7d5b35d383428808f7 | 4243df2e8a308307c7c926f63688d1d49bfed3da |
refs/heads/master | <repo_name>pekkast/docker-hy-2019<file_sep>/part1/start-1.10.sh
#!/bin/sh
cd frontend-example-docker
./node_modules/.bin/serve -s -l 5000 dist
<file_sep>/part1/README.md
## 1.1
```console
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
5d6a1fa221c2 nginx "nginx -g 'daemon of…" About a minute ago Exited (0) 12 seconds ago suspicious_heisenberg
9f27daf84f85 nginx "nginx -g 'daemon of…" About a minute ago Up About a minute 80/tcp elated_solomon
69320ae6a77d nginx "nginx -g 'daemon of…" About a minute ago Exited (0) 12 seconds ago sleepy_banzai
````
## 1.2
```console
$ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
```
```console
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
```
## 1.3
```console
$ docker run -it devopsdockeruh/pull_exercise
Status: Downloaded newer image for devopsdockeruh/pull_exercise:latest
Give me the password: <PASSWORD>
You found the correct password. Secret message is:
"This is the secret message"
```
## 1.4
```console
$ docker run -d --name=bash_sample devopsdockeruh/exec_bash_exercise
$ docker exec -it bash_sample /bin/bash
root@ede7d118e3de:/usr/app# tail -f ./logs.txt
Secret message is:
"Docker is easy"
Sat, 05 Oct 2019 05:23:33 GMT
Sat, 05 Oct 2019 05:23:36 GMT
^C
root@ede7d118e3de:/usr/app# exit
$ docker stop bash_sample
$ docker rm bash_sample
$ docker rmi devopsdockeruh/exec_bash_exercise
Untagged: devopsdockeruh/exec_bash_exercise:latest
Untagged: devopsdockeruh/exec_bash_exercise@sha256:c463832132d1fb0b8b3b60348a6fc36fda7512a4ef2d1050e8bea7b6a6d7a2f3
Deleted: sha256:489b6d8f2ab81ec84032c0e16deeded4862006b787353c740f1a4659f1b28a09
Deleted: sha256:2183b84cef51c03f45122ea74e50c6a1f7f75805faa37ed02486c0543540ff52
```
## 1.5
```console
$ docker run -it ubuntu sh -c 'apt update;apt install -y curl;echo "Input website:"; read website; echo "Searching.."; sleep 1; curl http://$website;'
```
## 1.6
```console
$ docker build -f ./Dockerfile-1.6 -t docker-clock .
$ docker run docker-clock
```
## 1.7
```console
$ docker build -f ./Dockerfile-1.7 -t curler .
$ docker run -it curler
Input website:
helsinki.fi
```
## 1.8
```console
$ touch ./log-1.8.txt
$ docker run -v $(pwd)/log-1.8.txt:/usr/app/logs.txt devopsdockeruh/first_volume_exercise
```
## 1.9
```console
$ docker run -d -p 8002:80 devopsdockeruh/ports_exercise
$ wget http://localhost:8002
--2019-10-05 11:41:54-- http://localhost:8002/
Selvitetään osoitetta localhost (localhost)... ::1, 127.0.0.1
Yhdistetään palvelimeen localhost (localhost)|::1|:8002... yhdistetty.
HTTP-pyyntö lähetetty, odotetaan vastausta... 200 OK
Pituus: 28 [text/html]
```
## 1.10
```console
$ docker build -f ./Dockerfile-1.10 -t npm-docker-front .
$ docker run -d -p 5000:5000 npm-docker-front
```
## 1.11
```console
$ docker build -f ./Dockerfile-1.11 -t npm-docker-back .
$ docker run -d -p 8000:8000 -v $(pwd)/logs-1.11.txt:/usr/app/logs.txt npm-docker-back
```
## 1.12
Add ENV variables to both Dockerfiles then build & run again
```console
$ docker build -f ./Dockerfile-1.10 -t npm-docker-front .
$ docker build -f ./Dockerfile-1.11 -t npm-docker-back .
$ docker run -d -p 8000:8000 -v $(pwd)/logs-1.11.txt:/usr/app/logs.txt npm-docker-back
$ docker run -d -p 5000:5000 npm-docker-front
```
## 1.13
```console
$ docker build -f Dockerfile-1.13 -t spring-project .
```
## 1.14
```console
$ docker build -f Dockerfile-1.14 -t rails-project .
$ docker run -p 3000:3000 rails-project
```
<file_sep>/README.md
# docker-hy-2019 | 8060aa32c66c5bee08a797ad15b32b372e80598e | [
"Markdown",
"Shell"
] | 3 | Shell | pekkast/docker-hy-2019 | 94c16fc07205d7ca0f6ff2e718ad3d269dff5667 | 99c99b97678444d636efb4810e38ecaf56de1dd7 |
refs/heads/master | <file_sep>#include <iostream>
#include <string>
#include <stdexcept>
#include <algorithm>
#ifndef SUPERNUM_H
#define SUPERNUM_H
class SuperNum
{
public:
std::string num;
SuperNum(std::string n);
SuperNum operator * (const SuperNum&);
SuperNum operator * (const int&);
SuperNum operator + (const SuperNum&);
void operator += (const SuperNum&);
void operator = (const SuperNum&);
bool operator == (const SuperNum&);
void pushBack(std::string p);
void flip();
void print();
virtual ~SuperNum();
protected:
private:
std::string NUMLIST = "0123456789";
};
#endif // SUPERNUM_H
<file_sep>#include "SuperNum.h"
SuperNum::SuperNum(std::string n)
{
num = "";
for (unsigned int C = 0;C < n.length();C++)
if (NUMLIST.find(n[C]) == std::string::npos)
throw std::invalid_argument("Invalid input characters into number");
num = n;
}
SuperNum SuperNum::operator * (const SuperNum& rhs)
{
SuperNum lhs = (*this);
}
SuperNum SuperNum::operator * (const int& rhs)
{
SuperNum lhs = (*this);
SuperNum total {"0"};
for (int C = 0;C < rhs;C++)
{
total += lhs;
}
return total;
}
SuperNum SuperNum::operator + (const SuperNum& rhs)
{
SuperNum lhs = (*this);
SuperNum output {""};
unsigned int carry = 0, add;
for (unsigned int C = 0;C < lhs.num.length() && C < rhs.num.length();C++)
{
add = (rhs.num[rhs.num.length()-C-1] - '0') + (lhs.num[lhs.num.length()-C-1] - '0') + carry;
//std::cout << "Add: " << add << " rhs[" << C << "] = " << (rhs.num[rhs.num.length()-C-1] - '0')
// << ", lhs[" << C << "] = " << (lhs.num[lhs.num.length()-C-1] - '0') << std::endl;
std::string sadd = std::to_string(add);
add = sadd[sadd.length() - 1] - '0';
if (sadd.length() > 1)
carry = std::stoi(sadd.substr(0, sadd.length()-1));
else
carry = 0;
//std::cout << "Carry: " << carry << std::endl;
output.pushBack(std::to_string(add));
}
std::string appending = "";
if (lhs.num.length() > rhs.num.length())
appending = lhs.num.substr(0, lhs.num.length() - rhs.num.length());
else if (lhs.num.length() < rhs.num.length())
appending = rhs.num.substr(0, rhs.num.length() - lhs.num.length());
else if (carry != 0)
appending = std::to_string(carry);
output.pushBack(appending);
std::reverse(output.num.begin(), output.num.end());
return output;
}
void SuperNum::operator += (const SuperNum& rhs)
{
//rhs.print();
(*this) = (*this) + rhs;
}
void SuperNum::operator = (const SuperNum& rhs)
{
//SuperNum lhs = (*this);
(*this).num = rhs.num;
}
bool SuperNum::operator == (const SuperNum& rhs)
{
SuperNum lhs = (*this);
return (lhs.num == rhs.num);
}
void SuperNum::pushBack(std::string p)
{
(*this).num.append(p);
}
void SuperNum::flip()
{
std::reverse((*this).num.begin(), (*this).num.end());
}
void SuperNum::print()
{
std::cout << "Number is " << num << std::endl;
}
SuperNum::~SuperNum()
{
}
<file_sep>#include <iostream>
#include "SuperNum.h"
using namespace std;
int main()
{
SuperNum sn1 {"2"};
SuperNum sn2 {"102"};
SuperNum sn3 = sn1 * 8;
sn3.print();
return 0;
}
| e2c21e1ce4a98e23ab25bcb4d59859adde3dbca7 | [
"C++"
] | 3 | C++ | cameronswinoga/SuperNum | 53bc1cde6897c0caf6eb46e900668140dc2a1b2e | 239a6c683cef32f583573299d408433347ba4403 |
refs/heads/master | <file_sep>String.prototype.capitalizeFirstLetter = function() {
return this.join().charAt(0).toUpperCase() + this.slice(1);
};
String.prototype.splitCamelCase = function() {
return this.join().split(/(?=[A-Z])/).join(" ");
};
String.prototype.join = function() {
return this.split(" ").join("");
};
function addClickEventListenersById(id, clickHandler){
let item = document.getElementById(id);
if (item) {
item.removeEventListener("click", clickHandler);
item.addEventListener("click", clickHandler);
}
}
function addClickEventListenersByClassName(className, clickHandler){
let items = document.getElementsByClassName(className);
if (items) {
for (let itemIndex in items) {
if (items.hasOwnProperty(itemIndex)) {
let item = items[itemIndex];
if (item.addEventListener) {
item.removeEventListener("click", clickHandler);
item.addEventListener("click", clickHandler);
}
}
}
}
}
function addDoubleClickEventListenersByClassName(className, clickHandler){
let items = document.getElementsByClassName(className);
if (items) {
for (let itemIndex in items) {
if (items.hasOwnProperty(itemIndex)) {
let item = items[itemIndex];
if (item.addEventListener) {
item.removeEventListener("dblclick", clickHandler);
item.addEventListener("dblclick", clickHandler);
}
}
}
}
}
function addFocusAndSelectById(id){
let element = document.getElementById(id);
if (element) {
element.focus();
element.select();
}
}
/**
* Use:
* async function something(){
* for(const x in something){
* await wait(1000);
* //...do something
* }
* }
* @param waitTime
* @returns {Promise<any>}
*/
function wait(waitTime){
return new Promise(resolve => setTimeout(resolve, waitTime));
}<file_sep>let selectedElement = null;
function contextHandler(variable) {
selectedElement.value = (selectedElement && variable) ? variable : null;
}
function handleRightClickEvent(event) {
selectedElement = (event != null && 2 === event.button) ? event.target : null;
}
function getAllElementsAndAddRightClickHandler() {
let allElements = document.getElementsByTagName('*');
if (allElements !== null && allElements.length > 0) {
[...allElements].forEach(element => {
if (element) {
if (typeof element.addEventListener === 'function') {
element.removeEventListener("mousedown", handleRightClickEvent, true);
element.addEventListener("mousedown", handleRightClickEvent, true);
}
}
});
}
}
window.removeEventListener('load', getAllElementsAndAddRightClickHandler, false);
window.addEventListener('load', getAllElementsAndAddRightClickHandler, false);
chrome.runtime.onMessage.addListener((message) => {
if (message && 'fillerContextHandler' === message.messageName) {
contextHandler(message.variable);
}
});<file_sep># Filler Web Extension
Web extension that loads a key-value model to a context menu allowing an end user the ability to quickly fill
input fields without having to change contexts and copy/paste each time.
Ideally there would be an automated process to load the models bases on a the end user current task.
###API Example:
```javascript
<html>
<body>
<h3>Create your model using JSON. Once finished hit the send button</h3>
<textarea id="model" rows="25" cols="50">
{
"testKey":"testValue"
}
</textarea>
<button id="send-button" disabled>Send</button><span id="extension-info" style="margin-left:10px;color:red;">Extension not installed</span>
<div>
<h3>Test Here:</h3>
<p>Right click in the input field, hover over 'Filer' in the context menu, then 'Fill'</p>
<input style="width: 15%;">
</div>
</body>
<script>
document.getElementById("send-button").addEventListener("click",() =>{
window.postMessage({type: 'apiMessage', message: {messageName:'setModel', model:JSON.parse(document.getElementById('model').value) }}, "*");
}, false);
document.addEventListener("fillerExtensionMessage", (message)=>{
if (message && message.target && message.detail) {
if('extensionInfo' === message.detail.messageName){
let element = document.getElementById('extension-info');
element.textContent = `Extension version ${message.detail.message.extensionVersion} installed`;
element.style.color = 'green';
document.getElementById('send-button').removeAttribute('disabled');
}
console.log(message.detail);
}
}, false);
(()=>{
window.postMessage({type: 'apiMessage', message: {messageName:'extensionInfo'}}, "*");
})();
</script>
</html>
```<file_sep>const CONTEXT_MENU_TEXT_FILL_KEY = 'fillerTextFillContext';
const CONTEXT_MENU_UTILS = 'fillerUtilsContext';
function setContexts(contexts){
return new Promise((resolve) => {
chrome.storage.local.set({'contexts': contexts}, () =>{
resolve('Done');
});
});
}
function getContexts(){
return new Promise((resolve) => {
chrome.storage.local.get(['contexts'], (result)=>{
resolve((result) ? result.contexts : null);
});
});
}
function createContextMenu(context){
if(context){
let contextDef = {id: context.id, title: context.title, contexts: context.contextTypes};
if(context.parentId){
contextDef['parentId'] = context.parentId;
}
if(context.enabled!==null){
contextDef['enabled'] = context.enabled;
}
chrome.contextMenus.create(contextDef);
if(context.children){
Object.entries(context.children).forEach(([key, value]) => {
value.contextTypes = (!value.contextTypes) ? context.contextTypes : value.contextTypes;
value.parentId = context.id;
createContextMenu(value);
});
}
}
}
function buildBaseContextMenus(contexts){
if(contexts){
contexts.forEach(context => createContextMenu(context));
}
}
async function handleModelContextMenus(){
let model = await getModel();
if(model) {
for(const key in model){
await addChildrenToContextMenu(CONTEXT_MENU_TEXT_FILL_KEY, CONTEXT_MENU_TEXT_FILL_KEY +'-'+ key, key, key);
}
}
}
async function addChildrenToContextMenu(parentId, childId, title, variable){
if(parentId){
let contexts = await getContexts();
let contextMenu = (contexts) ? contexts.find(x => x.id === parentId) : null;
if(contextMenu) {
let contextTypes = (contextMenu && contextMenu.contextTypes) ? contextMenu.contextTypes : ["all"];
let contextChildren = (contextMenu.hasOwnProperty('children')) ? contextMenu.children : [];
let child = {"id": childId, "parentId": parentId, "title": title, "contexts": contextTypes};
contextChildren.push(child);
contextMenu['children'] = contextChildren;
chrome.contextMenus.create(child);
if(contextMenu.action){
child['action'] = contextMenu.action;
}
if(variable){
child['variable'] = variable;
}
await setContexts(contexts);
}
}
}
async function resetContextMenus() {
let contexts = await getContexts();
if (!contexts) {
contexts = [
{
'id': CONTEXT_MENU_TEXT_FILL_KEY,
'title': 'Fill',
'type': 'normal',
"contextTypes": ["editable"],
"enabled": true,
"action": "fill"
},
{
'id': CONTEXT_MENU_UTILS,
'title': 'Utils',
'type': 'normal',
"contextTypes": ["editable"],
"enabled": true,
"action": "fill"
}
];
await setContexts(contexts);
}
chrome.contextMenus.removeAll(async () => {
let found = contexts.find(x => x.id = CONTEXT_MENU_TEXT_FILL_KEY);
if (found && found.children) {
delete found.children;
await setContexts(contexts);
}
buildBaseContextMenus(contexts);
handleModelContextMenus();
});
}
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
let model = await getModel();
let contexts = await getContexts();
if(info && tab && contexts && model){
if(info.menuItemId){
let menuItemIdArr = info.menuItemId.split('-');
let parentKey = (menuItemIdArr.length === 2) ? menuItemIdArr[0] : null;
if(parentKey){
let menuItemContext = contexts.find(x => x.id === parentKey);
let childMenuItemContext = (menuItemContext && menuItemContext.children) ? menuItemContext.children.find(x => x.id === info.menuItemId) : null;
if(childMenuItemContext && childMenuItemContext.variable) {
let variable = model[childMenuItemContext.variable];
chrome.tabs.sendMessage(tab.id, {messageName: 'fillerContextHandler', variable});
}
}
}
}
});
chrome.runtime.onInstalled.addListener(() =>resetContextMenus());<file_sep>async function setModelAndResetContextMenus(model){
await setModel(model);
await resetContextMenus();
}
function setModel(model){
return new Promise((resolve) =>{
chrome.storage.local.set({'model': model}, ()=>{
resolve('Done');
});
});
}
function getModel(){
return new Promise((resolve) => {
chrome.storage.local.get(['model'], (result)=>{
resolve((result) ? result.model : null);
});
});
}
chrome.tabs.onRemoved.addListener((tabId, removeInfo) =>{
if(apiPorts && tabId && apiPorts[tabId]!=null){
delete apiPorts[tabId];
}
});
chrome.browserAction.onClicked.addListener(tab => {
chrome.tabs.query({url: 'chrome-extension://*/fillerConfig/fillerConfig.html'}, (tabs)=> {
if(tabs && tabs.length!=0){
chrome.windows.update(tabs[0].windowId, {"focused": true});
}else{
chrome.windows.create({
url: chrome.runtime.getURL("../fillerConfig/fillerConfig.html"),
type: "popup",
width: 750
}, async (win) => {
let tabId = (win && win.tabs && win.tabs.length) ? win.tabs[0].id : null;
let model = await getModel();
if (tabId) {
chrome.tabs.sendMessage(tabId, {'messageName': 'showFillerConfig', model});
}
});
}
});
});<file_sep>let model;
let editing = false;
function buildModelDefinition(withAnimation) {
editing = false;
if (model!=null) {
let modelDefinition = document.getElementById('model-definition');
if (modelDefinition) {
modelDefinition.innerHTML = '';
Object.entries(model).forEach((entry, index) =>{
modelDefinition.innerHTML +=
((withAnimation!=null && withAnimation === true) ? "<div class='model-definition-item-container animated zoomInDown' style='animation-delay: "+Number(.1*index)+"s;'>" :
"<div class='model-definition-item-container'>")+
"<div class='model-definition-item' data-key='"+entry[0]+"'>"+
"<div class='model-definition-item-key'>"+entry[0].splitCamelCase().capitalizeFirstLetter()+"</div>"+
"<div class='model-definition-item-value'>"+entry[1]+"</div>"+
"<div class='model-definition-item-actions'><i class='fas fa-wrench' style='margin-right:10px;cursor: pointer;'></i></div>"+
"</div>"+
"<div class='horizontal-line model-definition-item-splitter'></div>"+
"</div>";
});
addClickEventListenersByClassName('fa-wrench', editModelItem);
addDoubleClickEventListenersByClassName('model-definition-item', editModelItem);
}
}
}
function editModelItem(event) {
if (!editing) {
let element = (event && event.target) ? event.target : null;
if (element && element.parentElement && model) {
let modelElement = (element.parentElement.getAttribute("data-key")) ? element.parentElement : null;
modelElement = (!modelElement && element.parentElement.parentElement && element.parentElement.parentElement.getAttribute("data-key")) ? element.parentElement.parentElement : modelElement;
if (modelElement) {
let key = modelElement.getAttribute("data-key");
let value = (key) ? model[key] : null;
if (key && value) {
editing = true;
modelElement.innerHTML = "<input id='model-definition-item-edit-value' class='model-definition-item-key model-definition-item-edit' value='" + key.splitCamelCase().capitalizeFirstLetter() + "'</input>" +
"<input class='model-definition-item-value model-definition-item-edit' value='" + value + "'</input>" +
"<div class='model-definition-item-edit model-definition-item-edit-buttons'>" +
"<button id='model-definition-item-edit-delete' class='button button-error edit-button' style='margin-right: 5px;'>Delete</button>" +
"<button id='model-definition-item-edit-cancel' class='button button-warning edit-button' style='margin-right: 5px;'>Cancel</button>"+
"<button id='model-definition-item-edit-done' class='button button-success edit-button' style='margin-right: 5px;'>Done</button>" +
"</div>";
addClickEventListenersById('model-definition-item-edit-delete', handleEditDeleteButton);
addClickEventListenersById('model-definition-item-edit-cancel', buildModelDefinition);
addClickEventListenersById('model-definition-item-edit-done', handleEditDoneButton);
addFocusAndSelectById('model-definition-item-edit-value');
}
}
}
}
}
function handleEditDeleteButton(event) {
editing = false;
let element = (event && event.target) ? event.target : null;
let key = (element && element.parentElement && element.parentElement.parentElement) ? element.parentElement.parentElement.getAttribute("data-key") : null;
if (key && model) {
delete model[key];
buildModelDefinition();
}
}
function handleEditDoneButton(event) {
editing = false;
let element = (event && event.target) ? event.target : null;
if (element && element.parentElement && element.parentElement.parentElement && element.parentElement.parentElement.children.length >= 2) {
let key = element.parentElement.parentElement.getAttribute("data-key");
let newKey = element.parentElement.parentElement.children[0].value;
let newValue = element.parentElement.parentElement.children[1].value;
if (key && newKey && newValue && model) {
delete model[key];
model[newKey] = newValue;
buildModelDefinition();
}
}
}
function handleImport(e) {
let content = e.target['result'];
if (content) {
try {
model = JSON.parse(content);
buildModelDefinition(true);
} catch (err) {
console.log(`Error parsing file, ${err}`)
}
}
}
document.addEventListener('DOMContentLoaded', () => {
addClickEventListenersById('filler-config-cancel-button', () => {
window.close();
});
addClickEventListenersById('filler-config-done-button', () => {
window.close();
chrome.runtime.sendMessage({'messageName': 'setModel', model});
});
addClickEventListenersById('filler-config-add-button', () => {
if (model) {
model['New Key'] = 'New Value';
buildModelDefinition();
let element = [... document.querySelectorAll('.model-definition-item')].find(x => x.getAttribute("data-key") === 'New Key');
if (element) {
element.firstChild.dispatchEvent(new MouseEvent('dblclick', {
'view': window,
'bubbles': true,
'cancelable': true
}))
}
}
});
document.getElementById('choose-file').addEventListener("change", (event) => {
if (event) {
let file = event.target.files[0];
if (file) {
let reader = new FileReader();
reader.onload = this.handleImport.bind(this);
reader.readAsText(file);
}
}
});
});
chrome.runtime.onMessage.addListener(function (message) {
if (message && 'showFillerConfig' === message.messageName) {
model = (message.model!=null) ? message.model : {};
buildModelDefinition(true);
}
}); | 118b1e2479c0864b37e018bd247a03ba0d2d9d51 | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | karachee/filler | cbb1bdd5682e0f1b40b6e75d2c64fe66f9aa1a1b | 4894a98ced59fbc6ba059e7a73df998f796c0636 |
refs/heads/master | <file_sep>{
"version":"1.2",
"md5":"06a142fa626a78c5faee3f0ba012535f",
"home_url":"Module_wifiboost.asp",
"title":"wifi boost",
"description":"wifi boost 路由器功率增强,强过澳大利亚",
"changelog":"",
"build_date":"2020-06-20_22:59:31"
}
| 9965aca99b4a05c793ff18b4a0a7618b36bd6052 | [
"JavaScript"
] | 1 | JavaScript | sy19890515/rogsoft | 9b7f766e76183d64e7398ed9b5d7ecaa5c5c7336 | 3110587380859efb553e7d142fca6a1132f6794d |
refs/heads/master | <file_sep>// main.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "Human.h"
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
Human human;
Student student;
Tutor tutor;
Student students(15);
Human people(4);
human = tutor;
cout << human;
cout << tutor;
cout << student;
cout << "Human " << human.objects_count() << endl;
cout << "Student " << student.objects_count() << endl;
system("PAUSE");
return 0;
}
//Wirtualne destruktory należy stosować w klasach bazowych, które mogą być dziedziczone przez inne klasy.
//Destruktor wirtualny w klasie bazowej zapewnia wywołanie wszystkich destruktorów klas potomnych podczas niszczenia obiektu.
| 3b0b349d784edb8a095c1ba03e4f823c7310fbfa | [
"C++"
] | 1 | C++ | Magda-K/lab4 | 75f580e1007f67d73168ad8d92a560566f28d14c | e50e00cd0729d155f9a13bc507d728ad5cca53ac |
refs/heads/master | <repo_name>shubham4522/Solved-Problems<file_sep>/timeConverter.cpp
#include<iostream>
#include<cstring>
using namespace std;
string intToString(int i)
{
std::string s = std::to_string(i);
return s;
}
string timeConverter(string s)
{
string hour = s.substr(0,2);
int h=stoi(hour);
if(s[8]=='A')
{
if(h==12)
{
s[0] ='0';
s[1]='0';
}
}else
{
if(h!=12)
{
h=h+12;
string temp= intToString(h);
s[0] =temp[0];
s[1]=temp[1];
}
}
return s.substr(0,8);
}
int main()
{
cout<<timeConverter("12:40:22AM");
}
| 367ca5c613420982167b4ad1dcfce5b8a406b412 | [
"C++"
] | 1 | C++ | shubham4522/Solved-Problems | 70e5b2a7c979ae7e3c2b912280b0ceb08a0d3121 | 9ceae5ffb3bfe9762ccecab32ffaf4883cbf41ad |
refs/heads/master | <file_sep>// Use this hook to manipulate incoming or outgoing data.
// For more information on hooks see: http://docs.feathersjs.com/api/hooks.html
const hooks = require('feathers-authentication-hooks');
// eslint-disable-next-line no-unused-vars
module.exports = function (options = {}) {
return hooks.restrictToOwner({ idField: 'id', ownerField: 'userId' })
};
<file_sep>/* eslint-disable no-console */
const logger = require('winston');
const app = require('./app');
const port = app.get('port');
const server = app.listen(port);
const requestExternalAPI = require('./hooks/calling-external-service');
process.on('unhandledRejection', (reason, p) =>
logger.error('Unhandled Rejection at: Promise ', p, reason)
);
// queryParamters={id:"1"}
// const optionss = {
// port: '80',
// host: 'jsonplaceholder.typicode.com',
// method: 'GET',
// path: '/posts'
// };
// console.log(requestExternalAPI(optionss,queryParamters));
server.on('listening', () =>
logger.info('Feathers application started on http://%s:%d', app.get('host'), port)
);
<file_sep>
const { disallow, iff } = require('feathers-hooks-common');
const hooks = require('feathers-authentication-hooks');
const preventUserFromCreateHimSelfAsAdmin = require('../../hooks/prevent-user-from-create-him-self-as-admin');
const preventUserFromUpdateHimSelfAsAdmin = require('../../hooks/prevent-user-from-update-him-self-as-admin');
const { authenticate } = require('feathers-authentication').hooks;
const {keep, isProvider} = require('feathers-hooks-common');
const {
hashPassword, protect
} = require('@feathersjs/authentication-local').hooks;
const populateUserSubDate = require('../../hooks/populate-user-sub-date');
module.exports = {
before: {
all: [populateUserSubDate()],
find: [],
get: [],
create: [preventUserFromCreateHimSelfAsAdmin(),hashPassword()],
update: [/*
authenticate('jwt'),
hashPassword(),
hooks.restrictToRoles({
roles: [1],
fieldName: 'level',
idField: 'id',
ownerField: 'id',
owner: true
}),
preventUserFromUpdateHimSelfAsAdmin(),
*/
disallow()
],
patch: [
authenticate('jwt'),
hashPassword(),
hooks.restrictToRoles({
roles: [1],
fieldName: 'level',
idField: 'id',
ownerField: 'id',
owner: true
}),
preventUserFromUpdateHimSelfAsAdmin()
],
remove: [authenticate('jwt'),
hooks.restrictToRoles({
roles: [1],
fieldName: 'level',
idField: 'id',
ownerField: 'id',
owner: true
})]
},
after: {
all: [],
find: [ protect('password') ],
get: [ /*iff(isProvider('external'), keep('id', 'email', 'firstName', 'lastName')),*/ protect('password') ],
create: [ protect('password') ],
update: [ protect('password') ],
patch: [ protect('password') ],
remove: [ protect('password') ]
},
error: {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
}
};
<file_sep>
const associateCurrentUserToField = require('../../hooks/associate-current-user-to-field');
const { disallow, iff } = require('feathers-hooks-common');
const authentication = require('../../hooks/authentication');
const restrictToOwner= require('../../hooks/restrict-to-owner');
module.exports = {
before: {
all: [],
find: [],
get: [],
create: [authentication(),associateCurrentUserToField()],
update: [disallow()/*authentication()*/],
patch: [disallow()/*authentication()*/],
remove: [authentication(),restrictToOwner()]
},
after: {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
},
error: {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
}
};
<file_sep>// Use this hook to manipulate incoming or outgoing data.
// For more information on hooks see: http://docs.feathersjs.com/api/hooks.html
const { authenticate } = require('feathers-authentication').hooks;
// eslint-disable-next-line no-unused-vars
module.exports = function (options = {}) {
return authenticate('jwt');
};
<file_sep>// See http://docs.sequelizejs.com/en/latest/docs/models-definition/
// for more of what you can do here.
const Sequelize = require('sequelize');
const DataTypes = Sequelize.DataTypes;
module.exports = function (app) {
const sequelizeClient = app.get('sequelizeClient');
const userTypes = sequelizeClient.define('user_types', {
description: {
type: DataTypes.STRING,
allowNull: false,
validate: {
is: ["^[a-z]+$",'i'],
// won't allow null
notEmpty: true, // don't allow empty strings
}
},
level: {
type: DataTypes.INTEGER,
allowNull: false,
unique: true
}
},{
hooks: {
beforeCount(options) {
options.raw = true;
}
}
});
// eslint-disable-next-line no-unused-vars
userTypes.associate = function (models) {
// Define associations here
// See http://docs.sequelizejs.com/en/latest/docs/associations/
};
return userTypes;
};
<file_sep>// Use this hook to manipulate incoming or outgoing data.
// For more information on hooks see: http://docs.feathersjs.com/api/hooks.html
const hooks = require('feathers-authentication-hooks');
// eslint-disable-next-line no-unused-vars
module.exports = function (options = {}) {
return hooks.restrictToRoles({
roles: [1],
fieldName: 'level',
idField: 'id'
})
};
<file_sep># API problemsolutios
## About
- "problem solutions" is a REST APIs that helps the people to post their problems or ideas and developers solve them by technical solutions. you can use it as a forum.
- This project uses [Feathers](http://feathersjs.com). An open source web framework for building modern real-time applications.
## Getting Started
Getting up and running is as easy as 1, 2, 3, 4, 5.
1. Make sure you have [NodeJS](https://nodejs.org/) and [npm](https://www.npmjs.com/) installed.
2. Install your dependencies
```
cd path/to/problemsolutios; npm install
```
3. Make sure you have [mysql](https://www.mysql.com/) installed and "problemsolutions" database created
4. Go to "./problemsolutios/config/default.json" and update "mysql" key with your connection string.
5. Start your app
```
npm start
```
The system will generate default admin and default user-type to configure your application you can update it later.
```
email:<EMAIL>
password:<PASSWORD>
```
## REST Services APIs
To know how to request the services and know the response, download [postman](https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en) from your chrome browser and use this [collection](https://www.getpostman.com/collections/f59a77529b9f02a5e46f)
### login
- After login to the system the system response with "accessToken".
- The system tracks the user via this token.
- The token will be expired after 24 hours.
### users
Available parameters for query parameters **(name, email, mobile, createdAt, updatedAt, level)**
| API Name | Allowed Users | HTTP Method |
| :------------: | :-----------------------------------------: | :---------: |
| create user | all | Post |
| list all users | all | get |
| get user | all | get |
| delete user | admin or owner | delete |
| update user | owner "only admin can update him ass admin" | patch |
### user-types
Available parameters for query parameters **(description, level, createdAt, updatedAt)**
| API Name | Allowed Users | HTTP Method |
| :-----------------: | :-----------: | :---------: |
| create user-type | admin | post |
| list all user-types | all | get |
| get user-type | all | get |
| delete user-type | admin | delete |
| update user-type | admin | patch |
### problem-types
Available parameters for query parameters **(description, createdAt, updatedAt)**
| Ali Name | Allowed Users | HTTP Method |
| :--------------------: | :-----------: | :---------: |
| create problem-type | admin | post |
| list all problem-types | all | get |
| get problem-type | all | get |
| delete problem-type | admin | delete |
| update problem-type | admin | patch |
### Problems
Available parameters for query parameters **(title, userId, body, createdAt, updatedAt, problemTypeId)**
| API Name | Allowed Users | HTTP Method |
| :---------------: | :----------------: | :---------: |
| create problem | Authenticated user | post |
| list all problems | all | get |
| get problem | all | get |
| delete problem | admin, owner | delete |
| update problem | owner | patch |
### problem-likes
Available parameters for query parameters **(createdAt, updatedAt, userId, problemId)**
| API Name | Allowed Users | HTTP Methods |
| :---------: | :----------------: | :----------: |
| add like | authenticated user | post |
| delete like | owner | delete |
### problem-solutions
Available parameters for query parameters **(body, createdAt, updatedAt, problemId, userId)**
| API Name | Allowed Users | HTTP Method |
| :------------------------: | :----------------: | :---------: |
| create problem-solution | authenticated user | post |
| list all problem-solutions | all | get |
| get problem-solution | all | get |
| delete problem-solution | admin, owner | delete |
| update problem-solution | owner | patch |
### solution-likes
Available parameters for query parameters **(createdAt, updatedAt, userId, problemSolutionId)**
| API Name | Allowed Users | HTTP Method |
| :---------: | :----------------: | :---------: |
| add like | authenticated user | post |
| delete like | owner | delete |
### solution-replies
Available parameters for query parameters **(body, createdAt, updatedAt, userId, problemSolutionId)**
| API Name | Allowed Users | HTTP Method |
| :-----------------------: | :----------------: | :---------: |
| create solution-reply | authenticated user | post |
| list all solution-replies | all | get |
| get solution-reply | all | get |
| delete solution-reply | admin, owner | delete |
| update solution-reply | owner | patch |
## General Query Paramters
### Equality
All fields that do not contain special query parameters are compared directly for equality.
```
GET /problems?problemTypeId=1&userId=2...
```
### `$limit`
`$limit` will return only the number of results you specify:
```
GET /problems?$limit=2&problemTypeId=1
```
> **Pro tip:** With [pagination enabled](common.md#pagination), to just get the number of available records set `$limit` to `0`. This will only run a (fast) counting query against the database and return a page object with the `total` and an empty `data` array.
### `$skip`
`$skip` will skip the specified number of results:
```
GET /problems?$limit=2&$skip=2
```
### `$sort`
`$sort` will sort based on the object you provide. It can contain a list of properties by which to sort mapped to the order (`1` ascending, `-1` descending).
```
/problems?$limit=10&$sort[createdAt]=-1
```
### `$select`
`$select` allows to pick which fields to include in the result. This will work for any service method.
```
GET /problems?$select[]=title&$select[]=userId
GET /problems/1?$select[]=title
```
### `$in`, `$nin`
Find all records where the property does (`$in`) or does not (`$nin`) match any of the given values.
```
GET /problems?userId[$in]=2&problemTypeId[$in]=5
```
### `$lt`, `$lte`
Find all records where the value is less (`$lt`) or less and equal (`$lte`) to a given value.
```
GET /problems?createdAt[$lt]=1479664146607
```
### `$gt`, `$gte`
Find all records where the value is more (`$gt`) or more and equal (`$gte`) to a given value.
```
GET /problems?createdAt[$gt]=1479664146607
```
### `$ne`
Find all records that do not equal the given property value.
```
GET /problems?userId[$ne]=1
```
### `$or`
Find all records that match any of the given criteria.
```
GET /problems?$or[0][userId][$ne]=1&$or[1][problemTypeId]=1
```
### Search
Search about entity using **like**
```
$like: '%hat', // LIKE '%hat'
$notLike: '%hat' // NOT LIKE '%hat'
$iLike: '%hat' // ILIKE '%hat' (case insensitive) (PG only)
$notILike: '%hat' // NOT ILIKE '%hat' (PG only)
```
```
GET /users?name[$like]=%moha%
```
<file_sep>
const { disallow, iff } = require('feathers-hooks-common');
const restrictToAdmin = require('../../hooks/restrict-to-admin');
const authentication = require('../../hooks/authentication');
module.exports = {
before: {
all: [],
find: [],
get: [],
create: [authentication(),restrictToAdmin()],
update: [disallow()/*authentication(),restrictToAdmin()*/ ],
patch: [authentication(),restrictToAdmin()],
remove: [authentication(),restrictToAdmin()]
},
after: {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
},
error: {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
}
};
<file_sep>// See http://docs.sequelizejs.com/en/latest/docs/models-definition/
// for more of what you can do here.
const Sequelize = require('sequelize');
const DataTypes = Sequelize.DataTypes;
module.exports = function (app) {
const sequelizeClient = app.get('sequelizeClient');
const solutionReplies = sequelizeClient.define('solution_replies', {
body: {
type: DataTypes.TEXT,
allowNull: false,
validate: {
// won't allow null
notEmpty: true, // don't allow empty strings
}
}
}, {
hooks: {
beforeCount(options) {
options.raw = true;
}
}
});
// eslint-disable-next-line no-unused-vars
solutionReplies.associate = function (models) {
solutionReplies.belongsTo(models.users);
solutionReplies.belongsTo(models.problem_solutions);
};
return solutionReplies;
};
<file_sep>const http = require('http');
module.exports = function (options = {},queryParamters={}) {
// make a request to a tunneling proxy
let response={body:null,success:null};
queryParamtersString="?";
for (var key in queryParamters) {
if( queryParamters.hasOwnProperty(key) ) {
queryParamtersString += key + "=" + queryParamters[key]+"&" ;
}
}
options.path +=queryParamtersString;
const req = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
response.body= JSON.parse(chunk);
response.success=true;
console.log("response",response)
});
});
req.Wait();
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
response.success=false;
});
// write data to request body
req.end();
return response;
};
| e6aeb32088a117b51babea63611e0da932e4f408 | [
"JavaScript",
"Markdown"
] | 11 | JavaScript | MohammedGomaaS/problemsolutions | 98b06259d4d7f14d7b2506641a8dbae66c51f4f1 | 7dfb8abac8d4d0ecb2dfba034d05f4ea080021a2 |
refs/heads/master | <repo_name>jhonson1jr/angular_apis_material<file_sep>/frontend/src/app/directives/for.directive.ts
import { Directive, Input, OnInit, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[myFor]'
})
export class ForDirective implements OnInit {
// Pegando o que vem após a palavra "em" do elemento myFor
@Input('myForEm') numbers: number[];
constructor(
private container: ViewContainerRef, // para usar o emelento setado como referencia
private template: TemplateRef<any> // usa o elemento de refefencia como "template"
){
// console.info("myFor");
}
ngOnInit(): void {
// console.info(this.numbers)
for (let number of this.numbers) {
// container referencia o elemento modelo; template o elemento atual, number o loop for:
this.container.createEmbeddedView(this.template, { $implicit: number });
}
}
}
<file_sep>/README.md
## Angular CRUD APIs
### Necessários: Npm, Angular, Angular Material UI, Orientação a Objetos
Projeto Angular com consumo de APIs, organizado em módulos, componentes e diretivas.
<br>
Uso do Two Way Databinding
<br>
Frontend com Material Design
<br>
Backend gerenciado pelo Json-Server, pois o foco desse projeto é o uso do Angular para consumo de APIs
<hr>
Instalar as dependências do projeto:<br>
Abrir um terminal dentro de cada diretório (frontend e backend), e executar:
```
npm install
```
Após a instalação das dependências, executar as aplicações:
<br><br>
Dentro de frontend:
```
ng server
```
Dentro de backend:
```
npm run start
```
<file_sep>/frontend/src/app/components/product/product.model.ts
// Interface dos produtos (model da base)
export interface Product {
id?: number, // ID é opcional (novo cadastro nao tem id, nisso colocamos ?)
name: string,
price: number
}<file_sep>/frontend/src/app/components/product/product.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar'; // mensagens tipo alerta
import { Observable } from 'rxjs';
import { Product } from './product.model';
@Injectable({
providedIn: 'root' // Ficará disponivel para toda a aplicacao (Design pattern Singleton)
})
// Controller
export class ProductService {
baseURL = 'http://localhost:3001/products/';
constructor( private snackBar: MatSnackBar, private http: HttpClient) { }
// Modal para por mensagens na tela ao usuario:
showMessage(msg: string): void {
this.snackBar.open(msg, 'x', {
duration: 3000,
horizontalPosition: 'right',
verticalPosition: 'top'
});
}
// Salvar produto na API usando a Model Interface:
// Envia (POST) um Produto e retorna um Observable do tipo Produto:
create (product: Product): Observable<Product> {
return this.http.post<Product>(this.baseURL, product);
}
// Pegando os produtos da API:
// Será retornado um array de produtos do backend:
read(): Observable<Product[]>{
return this.http.get<Product[]>(this.baseURL);
}
// Pegando um produto pelo ID:
readById(id: string): Observable<Product>{
const url = `${this.baseURL}/${id}`; // concatenando a URL base com o ID do produto
return this.http.get<Product>(url);
}
// Atualizando produto:
update(product: Product): Observable<Product> {
const url = `${this.baseURL}/${product.id}`; // concatenando a URL base com o ID do produto
return this.http.put<Product>(url, product); // URL, Objeto a atualizar
}
// Deletando um produto pelo ID:
deleteById(id: string): Observable<Product>{
const url = `${this.baseURL}/${id}`; // concatenando a URL base com o ID do produto
return this.http.delete<Product>(url);
}
}
| 8f0753ad351c2a0f2c6e7a92d2659b772ac60950 | [
"Markdown",
"TypeScript"
] | 4 | TypeScript | jhonson1jr/angular_apis_material | e3fd90273c998d9053a4e5b4deef791e2afd542c | a1bc9f53caaf003825513a551710fd9490d0b3de |
refs/heads/master | <file_sep>var express = require('express');
var router = express.Router();
const cont = require('../controller/admin');
/* GET home page. */
router.get('/', cont.index );
router.get('/add', cont.addGet );
router.post('/', cont.addPost );
router.get('/edit/:id', cont.editGet );
router.put('/update/:id', cont.updatePost );
router.delete('/:id',cont.delete,cont.index );
module.exports = router;
<file_sep># expsql
# expmongo
# exp-curd
# exp-curd
# exp-curd
<file_sep>const mongoose = require('mongoose');
var moment = require('moment');
const event_schema = mongoose.Schema({
name:String,
date:Date,
image:String
});
event_schema.path('date').get(function (d) {
return moment(d.date).format('YYYY-MM-DD');
});
module.exports= mongoose.model('event',event_schema) | 900624444dbca62a2600a8836696db5dc84f3cfa | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | mishradhirajmishra/exp-curd | b9e63858cad24ded7eae671d1d8d637b65e710a0 | edd9fb650a9f62c68b9e5f0c68759f5ae8aeeb8d |
refs/heads/master | <repo_name>jorgecosta06/Projecto-1<file_sep>/EasterEgg.js
class EasterEgg {
constructor(x,y) {
this.x = x
this.y = y
this.radius = 30
this.width = 10
this.height = 100
}
draw(ctx) {
ctx.save()
ctx.save()
// ctx.globalAlpha = 0.7
ctx.fillStyle = "red"
ctx.beginPath()
ctx.arc(this.x, this.y, this.radius, 0, 2*Math.PI)
// ctx.rect(this.x, this.y, this.width,this.height)
// ctx.fill()
ctx.restore()
ctx.restore()
}
}<file_sep>/Platform.js
class Platform {
constructor(x, y, width) {
this.x = x;
this.y = y;
this.width = width;
this.height = 20;
}
draw(ctx) {
ctx.save()
ctx.beginPath();
ctx.fillStyle = "#f9bc20bf";
ctx.fillRect(this.x, this.y, this.width, this.height)
ctx.restore()
}
top() {
return this.y
}
left() {
return this.x
}
right() {
return this.x + this.width
}
}<file_sep>/main.js
const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')
// Constants
const CANVAS_WIDTH = canvas.width
const CANVAS_HEIGHT = canvas.height
const DEBUG = true
const GRAVITY = 0.5
const BOUNCING_SPEED = -13
let frame = 0
let bg = new Background()
let enemies = [new Enemy()]
let platforms = [new Platform(0, 450, 300),new Platform(290, 300, 500),new Platform(750, 150, 300)]
let player = new Player()
let key = new Key(500,250)
let door = new Door(890,5,100)
let minnie = new Minnie()
let easterEgg = new EasterEgg()
let level = 1
let isGameWon = false
let bandeira = false
playerImg = new Image();
playerImg.src = './images/Mickey2.png'
playerImgLeft = new Image();
playerImgLeft.src = './images/MickeyLeft2.png'
playerImgRight = new Image();
playerImgRight.src = './images/MickeyRight2.gif'
playerImgUp = new Image();
playerImgUp.src = '/images/MickeyJump.png'
let doorSound = new Audio()
doorSound.src = "./Sounds/doorSound.mp3"
let scream = new Audio()
scream.src = "./Sounds/scream.mp3"
let music = new Audio()
music.src = "./Sounds/Not As It Seems.mp3"
// --- Calling ---
var stop = false
function animation() {
if (stop){
if (bandeira) {
// --- EasterEgg ---
ctx.fillRect(0,0,CANVAS_WIDTH, CANVAS_HEIGHT)
ctx.drawImage(easterEggImg, 0, 0, CANVAS_WIDTH, CANVAS_HEIGHT)
}
else {
ctx.fillStyle = "#0c0d29"
ctx.fillRect(0,0,CANVAS_WIDTH, CANVAS_HEIGHT)
ctx.drawImage(WinImg, 0, 0 , CANVAS_WIDTH, CANVAS_HEIGHT )
}
return
}
if (isGameWon) {
// displayGameWon()
stop = true
// stop the function
}
if (player.y > CANVAS_HEIGHT) {
displayGameLost()
return
}
else {
updateEverything()
drawEverything()
window.requestAnimationFrame(animation)
}
}
// --- Draw ---
function drawEverything(){
ctx.clearRect(0,0,CANVAS_WIDTH,CANVAS_HEIGHT)
bg.draw(ctx)
for (let i = 0; i < platforms.length; i++){
platforms[i].draw(ctx)
}
for (let i = 0; i < enemies.length; i++){
enemies[i].draw(ctx)
}
player.draw(ctx)
if (key){key.draw(ctx)}
door.draw(ctx)
if (level === 3){
minnie.draw(ctx)
}
if (level === 2 || level === 3)
{easterEgg.draw(ctx)}
}
// --- Update ---
function updateEverything() {
frame++
if (frame % 200 === 0){ // When the frame is multiple of 120
enemies.push(new Enemy())
// console.log('enemies push')
// console.log(enemies)
}
player.update()
for (let i = 0; i < enemies.length; i++){
enemies[i].update()
}
for (let i = 0 ; i < enemies.length; i++){
if (checkCollision(player,enemies[i])){
// player.score += enemies[i].score
// console.log(enemies[i])
enemies.splice(i,1)
player.life--
scream.play()
}
}
for (let i = 0 ; i < platforms.length; i++){
if (checkCollisionPlatform(player,platforms[i])){
player.y = platforms[i].top() - player.height + player.radius
player.vy = 0
player.alreadyJumped = false
}
}
if (key && checkCollisionKey(player, key)){
// player.score += key.score
key = undefined
door.open()
doorSound.play()
minnie.happy()
}
if (checkCollisionDoor(player, door) && door.isOpened){
goToNextLevel()
}
if (checkCollisionMinnie(player, minnie)){
isGameWon = true
}
if (checkCollisionEasterEgg(player, easterEgg)){
bandeira = true
}
}
// --- Collisions ---
function checkCollision(player, enemies) {
let distance= Math.sqrt((enemies.x-player.x)**2+(enemies.y-player.y)**2)
return player.radius+enemies.radius > distance
}
function checkCollisionPlatform(player, platform) {
if (player.life === 0) return false
let formerPlayerBottom = player.bottom() - player.vy
return formerPlayerBottom < platform.top() && player.bottom() > platform.top() && platform.left() < player.x && player.x < platform.right()
}
function checkCollisionKey(player, key) {
let distance = Math.sqrt((key.x-player.x)**2+(key.y-player.y)**2)
// console.log(checkCollisionKey)
return player.radius+key.radius > distance
}
function checkCollisionDoor(player, door){
let distance= Math.sqrt((door.x-player.x)**2+(door.y-player.y)**2)
// console.log(checkCollisionDoor)
return player.radius+door.width/3 > distance
}
function checkCollisionMinnie(player, minnie){
let distance= Math.sqrt((minnie.x-player.x)**2+(minnie.y-player.y)**2)
// console.log(checkCollisionMinnie)
return player.radius+minnie.radius > distance
}
function checkCollisionEasterEgg(player, easterEgg){
let distance= Math.sqrt((easterEgg.x-player.x)**2+(easterEgg.y-player.y)**2)
if(player.radius+easterEgg.radius > distance){
bandeira = true
}
}
// --- Go to next Level ---
function goToNextLevel() {
level++
player.y = CANVAS_HEIGHT
player.x = 500
enemies = []
platforms = []
if (level === 2) {
platforms = [new Platform(0,160,300),new Platform(0,330,700),new Platform(700,160,500), new Platform(800,430,500)]
key = new Key(140,280)
door = new Door(900,10,100)
}
if (level === 3) {
door = new Door(0,-500,100)
platforms = [new Platform(0,300,300),new Platform(700,300,300),new Platform(280,150,450), new Platform(280,450,450)]
key = new Key(900,250)
minnie = new Minnie(500,30)
easterEgg = new EasterEgg(150,250)
}
}
// --- Start Game Button ---
let playid = document.getElementById('playid')
playid.onclick = function(){
document.getElementById('startid').style.display = "none"
music.play()
animation()
}
// --- Win Game ---
let WinImg = new Image()
WinImg.src = './images/Win.png'
let easterEggImg = new Image()
easterEggImg.src = './images/127.png'
function displayGameWon(){
if (bandeira) {
// --- EasterEgg ---
ctx.fillRect(0,0,CANVAS_WIDTH, CANVAS_HEIGHT)
ctx.drawImage(easterEggImg, 0, 0, CANVAS_WIDTH, CANVAS_HEIGHT)
}
else {
ctx.fillStyle = "#0c0d29"
ctx.fillRect(0,0,CANVAS_WIDTH, CANVAS_HEIGHT)
ctx.drawImage(WinImg, 0, 0 , CANVAS_WIDTH, CANVAS_HEIGHT )
}
}
// --- Lose Game ---
let gameOverImg = new Image()
gameOverImg.src = './images/Lose.png'
function displayGameLost(){
ctx.fillStyle = "#0c0d29"
ctx.fillRect(0,0,CANVAS_WIDTH, CANVAS_HEIGHT)
ctx.drawImage(gameOverImg, 150, 100, CANVAS_WIDTH/1.5, CANVAS_HEIGHT/1.5)
}
<file_sep>/Door.js
class Door {
constructor(x, y, width) {
this.x = x;
this.y = y;
this.width = width;
this.height = 140;
this.doorImageClosed = new Image();
this.doorImageClosed.src = './images/ClosedDoor2.png'
this.doorImageOpened = new Image();
this.doorImageOpened.src = './images/OpenDoor2.png'
this.isOpened = false
}
draw(ctx) {
ctx.beginPath();
// ctx.fillRect(this.x, this.y, this.width, this.height)
if (!this.isOpened)
ctx.drawImage(this.doorImageClosed,this.x,this.y,this.width,this.height)
else {
ctx.drawImage(this.doorImageOpened,this.x,this.y,this.width,this.height)
// ctx.fillRect(this.x,this.y,this.width,this.height)
}
// ctx.fill();
}
open(){
this.isOpened = true
}
}<file_sep>/Background.js
class Background{
constructor(){
this.level = 0
this.imgs = [new Image(), new Image(), new Image()]
this.imgs[0].src = './images/livingromm2.jpg'
this.imgs[1].src = './images/kitchen.jpeg'
this.imgs[2].src = './images/room2.jpeg'
}
draw(ctx){
if (level == 1) {
ctx.drawImage(this.imgs[0], 0, 0, CANVAS_WIDTH, CANVAS_HEIGHT)
} else if (level == 2) {
ctx.drawImage(this.imgs[1], 0, 0, CANVAS_WIDTH, CANVAS_HEIGHT)
} else {
ctx.drawImage(this.imgs[2], 0, 0, CANVAS_WIDTH, CANVAS_HEIGHT)
}
}
}<file_sep>/Minnie.js
class Minnie {
constructor(x,y) {
this.x = x
this.y = y
this.radius = 50
this.speed = 6
this.width = 120
this.height = 120
this.minnieScared = new Image();
this.minnieScared.src = './images/MinnieScared.png'
this.minnieHappy = new Image();
this.minnieHappy.src = './images/Minnie.png'
this.isScared = false
this.cageImg = new Image();
this.cageImg.src = './images/cage.png'
}
draw(ctx) {
ctx.save()
if (DEBUG) {
ctx.save()
// ctx.globalAlpha = 0.7
ctx.fillStyle = "red"
ctx.beginPath()
ctx.arc(this.x, this.y, this.radius, 0, 2*Math.PI)
// ctx.rect(this.x, this.y, this.width,this.height)
// ctx.fill()
ctx.restore()
}
if (!this.isScared){
ctx.drawImage(this.minnieScared, this.x-this.radius, this.y, 2*this.radius, this.height)
ctx.drawImage(this.cageImg, this.x-this.radius, this.y, 2.5*this.radius, this.height)
}
else {
ctx.drawImage(this.minnieHappy, this.x-this.radius, this.y, 2*this.radius, this.height)
}
ctx.restore()
}
happy(){
this.isScared = true
}
}<file_sep>/Enemy.js
class Enemy {
constructor(){
this.radius = 30
this.y = this.radius+Math.floor((CANVAS_HEIGHT-2*this.radius)*Math.random())
this.x = -10;
this.vx = 2 // Velocity y
// console.log(this.x, this.y);
this.ghostImg = new Image();
this.ghostImg.src = './images/ghostright.png'
}
draw(ctx){
ctx.save()
if (DEBUG) {
ctx.save()
ctx.beginPath()
ctx.arc(this.x, this.y, this.radius, 0, 2*Math.PI)
// ctx.fill()
ctx.restore()
}
ctx.drawImage(this.ghostImg, this.x-this.radius*2.5/2, this.y-this.radius*2.5/2, this.radius*2.5,this.radius*2.5)
ctx.restore()
}
update(){
this.x += this.vx
}
}
| ac26810536878af75f9854e0b22f759348e6a4d0 | [
"JavaScript"
] | 7 | JavaScript | jorgecosta06/Projecto-1 | 5838b22ca468325ac1f3a36d69e80cb6c6e89c29 | 0c39ec4ea6e779a4216f7e91d19ff0bb1758e057 |
refs/heads/main | <repo_name>thisudre/nlw-compliments<file_sep>/src/controllers/ListUsersController.ts
import IController from "./IController";
import { Request, Response } from 'express';
import ListUsersService from "../services/ListUsersService";
export default class ListUsersController implements IController{
async handle(request: Request, response: Response) {
const listUsersService = new ListUsersService();
const users = await listUsersService.execute();
return response.json(users);
}
}<file_sep>/src/controllers/ListUserReceivedComplimentsController.ts
import IController from "./IController";
import { Request, Response } from 'express';
import ListUserReceivedComplimentsService from "../services/ListUserReceivedComplimentsService";
export default class ListUserReceivedComplimentsController implements IController{
async handle(request: Request, response: Response) {
const listUserReceivedComplimentsService = new ListUserReceivedComplimentsService();
const { user_id } = request;
const compliment = await listUserReceivedComplimentsService.execute(user_id);
return response.json(compliment);
}
}<file_sep>/src/services/ListUserSentComplimentsService.ts
import { getCustomRepository } from "typeorm";
import ComplimentsRepository from "../repositories/ComplimentsRepository";
import IService from "./IService";
export default class ListUserSentComplimentsService implements IService {
async execute(user_id: string) {
const complimentsRepository = getCustomRepository(ComplimentsRepository);
const compliments = await complimentsRepository.find({
where: {user_sender: user_id}
});
return compliments;
}
}<file_sep>/src/controllers/IController.ts
import { Request, Response } from 'express';
export default interface IController {
handle(request: Request, response: Response);
}<file_sep>/src/controllers/ListUserSentComplimentsController.ts
import IController from "./IController";
import { Request, Response } from 'express';
import ListUserSentComplimentsService from "../services/ListUserSentComplimentsService";
export default class ListUserSentComplimentsController implements IController {
async handle(request: Request, response: Response) {
const listUserSentComplimentsService = new ListUserSentComplimentsService();
const {user_id} = request;
const compliments = await listUserSentComplimentsService.execute(user_id);
return response.json(compliments);
}
}<file_sep>/src/services/CreateComplimentService.ts
import { getCustomRepository } from "typeorm";
import ComplimentsRepository from "../repositories/ComplimentsRepository";
import UsersRepository from "../repositories/UsersRepository";
import IService from "./IService";
interface ICompliment {
user_sender: string;
user_receiver: string;
tag_id: string;
message: string
}
export default class CreateComplimentService implements IService {
async execute({ user_sender, user_receiver, tag_id, message }: ICompliment) {
const complimentRepository = getCustomRepository(ComplimentsRepository);
const userRepository = getCustomRepository(UsersRepository);
if(user_sender === user_receiver) {
throw new Error('Cannot create self compliments');
}
const user_exists = await userRepository.findOne(user_receiver);
if(!user_exists) {
throw new Error('User not found');
}
const compliment = complimentRepository.create({
user_sender,
user_receiver,
tag_id,
message
});
await complimentRepository.save(compliment);
return compliment;
}
}<file_sep>/src/controllers/CreateComplimentController.ts
import IController from "./IController";
import { Request, Response } from "express";
import CreateComplimentService from "../services/CreateComplimentService";
export default class CreateComplimentController implements IController {
async handle(request: Request, response: Response) {
const { user_receiver, tag_id, message} = request.body;
const user_sender = request.user_id;
const createComplimentService = new CreateComplimentService();
const compliment = await createComplimentService.execute({
user_sender,
user_receiver,
tag_id,
message
});
return response.json(compliment);
}
}<file_sep>/src/services/ListUsersService.ts
import { getCustomRepository } from "typeorm";
import UsersRepository from "../repositories/UsersRepository";
import IService from "./IService";
export default class ListUsersService implements IService {
async execute() {
const usersRepository = getCustomRepository(UsersRepository);
const users = await usersRepository.find();
return users;
}
}<file_sep>/src/services/AuthenticateUserService.ts
import { compare } from 'bcryptjs';
import { sign } from 'jsonwebtoken';
import { getCustomRepository } from 'typeorm';
import UsersRepository from '../repositories/UsersRepository';
import IService from "./IService";
interface IAuthenticate {
email: string;
password: string;
}
export default class AuthenticateUserService implements IService{
async execute({email, password}: IAuthenticate) {
const userRepository = getCustomRepository(UsersRepository);
// verificar o email
const user = await userRepository.findOne({
email
});
if(!user) {
throw new Error('Invalid Email/Password');
}
// verificar a senha
const validPassword = compare(password, user.password);
if(!validPassword) {
throw new Error('Invalid Email/Password');
}
// gerar o token
const token = sign({
email: user.email
}, "<PASSWORD>", {
subject: user.id,
expiresIn: '1d'
});
return token;
}
}<file_sep>/README.md
# NLW Compliments
## Regras
- Cadastro de Usuários
[x] Não é permitido cadastrar mais de um usuário com o mesmo email;
[x] Não é permitido cadastrar sem email;
- Cadastro de TAGs
[x] Não é permitido cadastrar mais de uma TAG com o mesmo nome;
[x] Não é permitido cadastrar TAG sem nome;
[x] Não é permitido o cadastro por usuarios que não sejam administradores;
- Cadastro de Elogios
[] Não é permitido um usuario cadastrar um elogio pra si;
[] Não é permitido cadastrar elogios para usuários invalidos;
[] O usuário precisa estar autenticado;
<file_sep>/src/services/CreateTagService.ts
import { getCustomRepository } from "typeorm";
import TagsRepository from "../repositories/TagsRepository";
import IService from "./IService";
interface ITag {
name: string
}
export default class CreateTagService implements IService {
async execute({name}: ITag) {
const tagsRepository = getCustomRepository(TagsRepository);
if(!name) {
throw new Error('Name is required');
}
const tagAlreadyExists = await tagsRepository.findOne({
name
});
if(!!tagAlreadyExists) {
throw new Error('Tag already exists');
}
const tag = tagsRepository.create({
name
});
await tagsRepository.save(tag);
return tag;
}
}<file_sep>/src/controllers/AuthenticateUserController.ts
import { Request, Response } from "express";
import AuthenticateUserService from "../services/AuthenticateUserService";
import IController from "./IController";
export default class AuthenticateUserController implements IController {
async handle(request: Request, response: Response) {
const authenticateUserService = new AuthenticateUserService();
const {email, password} = request.body;
const token = await authenticateUserService.execute({email, password});
return response.json(token);
}
}<file_sep>/src/services/IService.ts
export default interface IService {
execute({});
}<file_sep>/src/services/ListUserReceivedComplimentsService.ts
import { getCustomRepository } from "typeorm";
import ComplimentsRepository from "../repositories/ComplimentsRepository";
import IService from "./IService";
export default class ListUserReceivedComplimentsService implements IService{
async execute(user_id: string) {
const complimentsRepository = getCustomRepository(ComplimentsRepository);
const compliments = await complimentsRepository.find({
where: {user_receiver: user_id}
});
return compliments;
}
} | 36d43ddd22e12e41ca39fb1d41f93222f2787211 | [
"Markdown",
"TypeScript"
] | 14 | TypeScript | thisudre/nlw-compliments | 43992a33d3f240672db85554395de999e2365164 | 66cc22b58709b86e0397d11cd7536d7e5afd4fb4 |
refs/heads/master | <repo_name>maviswongkl/MyCalculator<file_sep>/app/src/main/java/com/example/mycalculator/MainActivity.kt
package com.example.mycalculator
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
var last = false
var add = false
var subtract = false
var multiply = false
var divide = false
var calculate = 0.0;
var operation = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun btnOnClick(view: View) {
var tvNum = tvResults.text.toString()
val btnSelected = view as Button
when (btnSelected.id) {
buttonClear.id -> {
tvResults.text = "0"
calculate = 0.0
}
button1.id -> {
if (tvNum.equals("0") || last) {
tvResults.text = "1"
last = false
} else {
tvResults.text = tvNum + "1"
add = false
subtract = false
}
}
button2.id -> {
if (tvNum.equals("0") || last) {
tvResults.text = "2"
last = false
} else {
tvResults.text = tvNum + "2"
}
}
button3.id -> {
if (tvNum.equals("0") || last) {
tvResults.text = "3"
last = false
} else {
tvResults.text = tvNum + "3"
}
}
button4.id -> {
if (tvNum.equals("0") || last) {
tvResults.text = "4"
last = false
} else {
tvResults.text = tvNum + "4"
}
}
button5.id -> {
if (tvNum.equals("0") || last) {
tvResults.text = "5"
last = false
} else {
tvResults.text = tvNum + "5"
}
}
button6.id -> {
if (tvNum.equals("0") || last) {
tvResults.text = "6"
last = false
} else {
tvResults.text = tvNum + "6"
}
}
button7.id -> {
if (tvNum.equals("0") || last) {
tvResults.text = "7"
last = false
} else {
tvResults.text = tvNum + "7"
}
}
button8.id -> {
if (tvNum.equals("0") || last) {
tvResults.text = "8"
last = false
} else {
tvResults.text = tvNum + "8"
}
}
button9.id -> {
if (tvNum.equals("0") || last) {
tvResults.text = "9"
last = false
} else {
tvResults.text = tvNum + "9"
}
}
button0.id -> {
if (tvNum.equals("0") || last) {
tvResults.text = "0"
last = false
} else {
tvResults.text = tvNum + "0"
}
}
buttonDeci.id -> {
if (tvResults.text.toString().contains(".")) {
} else {
if (tvNum.equals("0") || last) {
tvResults.text = "0."
last = false
} else if (!last) {
tvResults.text = tvNum + "."
}
}
}
}
}
fun buttonOperationOnClick(view: View) {
var tvResult = tvResults.text.toString()
val btnSelected = view as Button
when (btnSelected.id) {
buttonAdd.id -> {
if (operation.equals("")) {
calculate = tvResult.toDouble()
operation = "+"
last = true
add = true
} else {
calculate += tvResult.toDouble()
operation = "+"
last = true
add = true
}
}
buttonSubtract.id -> {
if (operation.equals("")) {
calculate = tvResult.toDouble()
operation = "-"
last = true
subtract = true
} else {
calculate -= tvResult.toDouble()
operation = "-"
last = true
subtract = true
}
}
buttonMultiply.id -> {
if (operation.equals("")) {
calculate = tvResult.toDouble()
operation = "*"
last = true
multiply = true
} else {
calculate *= tvResult.toDouble()
operation = "*"
last = true
multiply = true
}
}
buttonDivide.id -> {
if (operation.equals("")) {
calculate = tvResult.toDouble()
operation = "/"
last = true
divide = true
} else {
calculate = tvResult.toDouble()
operation = "/"
last = true
divide = true
}
}
buttonAddSubtract.id -> {
calculate = tvResult.toDouble() * -1
tvResults.text = calculate.toString()
}
buttonPercent.id -> {
calculate = tvResult.toDouble() / 100
tvResults.text = calculate.toString()
}
buttonEqual.id -> {
if (add) {
calculate += tvResult.toDouble()
tvResults.text = calculate.toString()
operation = ""
add = false
last = true
} else if (subtract) {
calculate -= tvResult.toDouble()
operation = ""
tvResults.text = calculate.toString()
subtract = false
last = true
} else if (multiply) {
calculate *= tvResult.toDouble()
tvResults.text = calculate.toString()
operation = ""
multiply = false
last = true
} else if (divide) {
calculate /= tvResult.toDouble()
tvResults.text = calculate.toString()
operation = ""
divide = false
last = true
} else {
last = true
}
Log.d("Calculate success", calculate.toString() + "")
}
}
}
} | 34e2ed7bf4850cc47ea5d44fb4df5116cf21b859 | [
"Kotlin"
] | 1 | Kotlin | maviswongkl/MyCalculator | 8f98812dcec750d5ee376bde5d06e36d7ca665f3 | f9e10b3f3e7672246d8ab8e6d996393ff67a02e5 |
refs/heads/master | <file_sep>package Algorithmen.sort;
import Algorithmen.comparator.Comparator;
public class Bubblesort<T> extends Swapper<T> implements Sortable<T> {
@Override
public void sort(T[] students, Comparator<T> comparator) {
for (int i = 1; i < students.length; i++) {
for (int e = 0; e < students.length - i; e++) {
if (comparator.compare(students[e], students[e + 1]) > 0) {
swap(students, e, e + 1);
}
}
}
}
}
<file_sep>/*
* This Java source file was generated by the Gradle 'init' task.
*/
package Algorithmen;
import Algorithmen.hash.Hash;
import Algorithmen.hash.IHash;
import Algorithmen.main.ADSHashTable;
import Algorithmen.main.App;
import Algorithmen.main.HashInvoker;
import Algorithmen.probing.QuadraticProbing;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.*;
public class AppTest {
private static final int TEST_SIZE = 5;
ADSHashTable test_table = new ADSHashTable(TEST_SIZE, new Hash(TEST_SIZE), new QuadraticProbing());
@Test
public void insertTest() {
HashInvoker.insert(test_table, 55);
HashInvoker.insert(test_table, 13);
//expecting collision. The key will be found at 4
HashInvoker.insert(test_table, 23);
Assert.assertEquals(55, test_table.getHashArray().get(0));
Assert.assertEquals(13, test_table.getHashArray().get(3));
Assert.assertEquals(23, test_table.getHashArray().get(4));
}
@Test
public void removeTest() {
HashInvoker.insert(test_table, 55);
HashInvoker.remove(test_table, 55);
//was deleted and I can add a new number there
HashInvoker.insert(test_table, 35);
Assert.assertEquals(35, test_table.getHashArray().get(0));
}
}
<file_sep>package Algorithmen.sort;
public class Swapper<T> {
protected void swap(T[] students, int i, int j) {
T memorizedObject = students[i];
students[i] = students[j];
students[j] = memorizedObject;
}
}
<file_sep>package Algorithmen.probing;
public class LinearProbing implements IProbing {
@Override
public int probe(int key, int j) {
return j;
}
}
<file_sep>package Algorithmen.sort;
import Algorithmen.comparator.Comparator;
public class Quicksort<T> extends Swapper<T> implements Sortable<T> {
@Override
public void sort(T[] students, Comparator<T> comparator) {
quickSort(students, 0, students.length - 1, comparator);
}
public void quickSort(T[] students, int start, int end, Comparator<T> comparator) {
int partition = partition(students, start, end, comparator);
if (partition - 1 > start) {
quickSort(students, start, partition - 1, comparator);
}
if (partition + 1 < end) {
quickSort(students, partition + 1, end, comparator);
}
}
public int partition(T[] students, int start, int end, Comparator<T> comparator) {
T pivot = students[end];
for (int i = start; i < end; i++) {
if (comparator.compare(students[i], pivot) < 0) {
swap(students, start, i);
start++;
}
}
T temp = students[start];
students[start] = pivot;
students[end] = temp;
return start;
}
}
<file_sep>package Algorithmen.menu;
import Algorithmen.main.ADSHashTable;
import Algorithmen.main.HashInvoker;
public class Menu {
public static void mainMenu() {
System.out.println();
System.out.println("1.Add a number to hash table");
System.out.println("2.Get a number from hash table");
System.out.println("3.Search for a number in hash table");
System.out.println("4.Delete a number from hash table");
System.out.println("5.Clear the hash table");
System.out.println("6.Sort students by matriculation number");
System.out.println("0.Exit");
System.out.println();
}
public static void choice(ADSHashTable table) {
int choice = 1;
int input;
while (choice != 0) {
mainMenu();
choice = Console.readIntFromStdin("Please enter a number for an option: ");
switch (choice) {
case 1:
input = Console.readIntFromStdin("Please enter a number for adding: ");
HashInvoker.insert(table, input);
break;
case 2:
input = Console.readIntFromStdin("Please enter an index:");
HashInvoker.getValue(table, input);
break;
case 3:
input = Console.readIntFromStdin("Please enter a number for searching: ");
HashInvoker.search(table, input);
break;
case 4:
input = Console.readIntFromStdin("Please enter a number for deleting: ");
HashInvoker.remove(table, input);
break;
case 5:
HashInvoker.clear(table);
break;
case 6:
SortMenu.executeSortMenu();
break;
case 0:
break;
default:
System.out.println("Wrong input. Try again!");
}
}
}
}
| 66388c5b279b07de785315ba92ca32807467442c | [
"Java"
] | 6 | Java | Krysenkova/Algorithms-5 | 2562b8208178e38506d748ee29bd38382d4917a0 | ff2acff33c5b081429ba4cdb4661291a2231b9ea |
refs/heads/main | <repo_name>AnnabelleEllis/LearningJava-Week1<file_sep>/README.md
# LearningJava-Week1
Learning Java with Princeton University Through Coursera
Started this course but I need to be "commit"ted -- lol-- so I started a version control to track my progress.
<file_sep>/src/HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
String t = "Hello World ";
System.out.println(t.repeat(10));
}
}
<file_sep>/src/EuclideanFormulae.java
public class EuclideanFormulae {
public static void main(String[] args) {
int origin1 = 0;
int origin2 = 0;
int p1 = Integer.parseInt(args[0]);
int p2 = Integer.parseInt(args[1]);
int distance = (int) Math.pow((origin1 - p1), 2) + (int) Math.pow((origin2 - p2), 2);
int d = (int) Math.sqrt(distance);
System.out.println(d);
}
}
| 56b6bbfe3081ada32c799d5564dab6bfd0becec8 | [
"Markdown",
"Java"
] | 3 | Markdown | AnnabelleEllis/LearningJava-Week1 | 17bde7498457134ec647fef26cd8f09f53f853b3 | 8a521d72ba2bcd0a9cfacb56ba05be6205585a5e |
refs/heads/master | <file_sep># QR_CODE STUDY
1. [node.js로 QR코드 생성하기](<https://github.com/jungjai/QR_CODE/blob/master/QRcode_nodejs/README.md>)
2. [jQuery로 QR코드 생성하기](<https://github.com/jungjai/QR_CODE/blob/master/QRcode_jquery/README.md>)
3. [JSP로 QR코드 생성하기](<https://github.com/jungjai/QR_CODE/blob/master/QRcode_JSP/README.md>)
## 사용 스택
- [Node.js](https://nodejs.org/ko/) - Chrome V8 자바스크립트 엔진으로 빌드된 자바스크립트 런타임
- [Express.js](http://expressjs.com/ko/) - Node.js 웹 애플리케이션 프레임워크
- [Atom](https://atom.io/) - 편집기
- [NPM](<https://www.npmjs.com/>) - 자바스크립트 프로그래밍 언어 위한 패키지 관리자
- [jQuery](<https://jquery.com/>) - HTML의 클라이언트 사이드 조작을 단순화 하도록 설계된 자바스크립트 라이브러리
- [JSP](<https://www.oracle.com/technetwork/java/index-jsp-138231.html>) - HTML 내에 자바 코드를 삽입하여 웹 서버에서 동적으로 웹 페이지를 생성하여 웹 브라우저에 돌려주는 언어
- [Tomcat](<http://tomcat.apache.org/>) - 서블릿 컨테이너, 웹컨테이너만 있는 웹 애플리케이션 서버
- [intelliJ](<https://www.jetbrains.com/idea/>) - 자바 통합 개발 환경
## 개발자
- [이정재](https://github.com/jungjai)
<file_sep># JSP로 QR코드 생성하기
모든 소스코드는 IntelliJ + Windows10 환경에서 작성되었습니다.
## 사용법
```
URL QRcode Generate
Input URL :
```
- Input URL 우측에 있는 Input BOX에 문자열을 입력한후 Generate 버튼을 클릭
- QR코드 생성 (Wrong URL이면 오류처리)
- Again 누르면 처음 페이지로 돌아감
### 설치하기
- JDK 설치 - JAVA 개발환경 세팅을 위한 JDK 설치
- Tomcat 서버 설치 - JSP를 실행할 수 있는 웹서버를 구축하기 위해 JSP 웹서버인 Tomcat 설치
## 사용된 도구
- [JSP](<https://www.oracle.com/technetwork/java/index-jsp-138231.html>) - HTML 내에 자바 코드를 삽입하여 웹 서버에서 동적으로 웹 페이지를 생성하여 웹 브라우저에 돌려주는 언어
- [Tomcat](<http://tomcat.apache.org/>) - 서블릿 컨테이너, 웹컨테이너만 있는 웹 애플리케이션 서버
- [intelliJ](<https://www.jetbrains.com/idea/>) - 자바 통합 개발 환경<file_sep># jQuery로 QR코드 생성하기
## 사용법
```
<script>
jQuery('#gcDiv').qrcode({ // Start QR코드
render : "table", // table, canvas 형식 2개
width : 300, // 넓이
height : 300, // 높이
text : "jungjai" // qr코드를 생성할 문자열
});
</script>
```
- render : table, carvas 형식 구분
- width : 넓이
- height : 높이
- text : QR코드 생성할 문자열
## 사용된 도구
- [jQuery](<https://jquery.com/>) - 자바스크립트의 생상성을 향상시켜주는 자바스크립트 라이브러리<file_sep>var express = require('express')
var qrcode = require('qrcode');
var app = express()
app.get('/qrcode', function(req, res) =>{
let input = req.params.qrcode;
qrcode.toDataURL(inputStr, function (err, url) {
//res.send(url);
let data = url.replace(/.*,/,'')
let img = new Buffer(data,'base64') // base64 : encodeing
// response header
res.writeHead(200,{
'Content-Type' : 'image/png',
'Content-Length' : img.length
})
res.end(img)
})
})
app.listen(3000, function(){
console.log("start! server on 3000")
})
<file_sep># Node.js로 QR코드 생성하기
## 의존성
```
"dependencies": {
"express": "^4.16.4",
"qrcode": "^1.3.3"
}
```
## 시작하기
모든 소스코드는 Atom + Windows10 + Node.js 8 환경에서 작성되었습니다.
### 설치하기
- `nodejs` 와 `npm` 을 설치합니다. 설치 방법은 [nodejs.org](https://nodejs.org/) 를 참고하세요.
- Node.js 8 LTS 버전을 설치합니다.
```
npm install --save express
npm install --save qrcode
```
## 사용된 도구
- [Node.js](https://nodejs.org/ko/) - Chrome V8 자바스크립트 엔진으로 빌드된 자바스크립트 런타임
- [Express.js](http://expressjs.com/ko/) - Node.js 웹 애플리케이션 프레임워크
- [Atom](https://atom.io/) - 편집기 | 0c0670b10cb76d411235009d6f45145dcc084a00 | [
"Markdown",
"JavaScript"
] | 5 | Markdown | jungjai/QR_CODE | 6550264b6f10718d9c70082c5a8a729320d5e4c5 | 08b0cf2662a9e1d3b3a4d1c100850228acf7dfac |
refs/heads/master | <file_sep>import React from 'react'
import { Route, IndexRoute } from 'react-router'
import App from './components/App'
import About from './components/about/About'
import CoursesPage from './components/CoursesPage'
import ManageCoursePage from './components/ManageCoursePage'
export default (
<Route path="/" component={App} >
<IndexRoute component={CoursesPage} />
<Route path="course" component={ManageCoursePage} />
<Route path="course/:id" component={ManageCoursePage} />
<Route path="about" component={About} />
</Route>
)<file_sep>import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as courseActions from '../actions/courseActions'
import CourseList from './CourseList'
import { Grid, Row, Col } from 'react-bootstrap'
class CoursesPage extends Component {
courseRow(course, index) {
return <div key={index}>{course.title}</div>
}
render() {
const { courses } = this.props
return (
<Grid>
<Row>
<Col xs={12}>
<h1>Courses</h1>
<CourseList courses={courses} />
</Col>
</Row>
</Grid>
)
}
}
CoursesPage.propTypes = {
actions: PropTypes.object.isRequired,
courses: PropTypes.array.isRequired
}
const mapStateToProps = (state, ownProps) => ({ courses: state.courses })
const mapDispatchToProps = dispatch => ({ actions: bindActionCreators(courseActions, dispatch) })
export default connect(mapStateToProps, mapDispatchToProps)(CoursesPage)
<file_sep>
import React from 'react'
import ReactDOM from 'react-dom'
import { Router, browserHistory } from 'react-router'
import routes from './routes'
import configureStore from './store/configureStore'
import { Provider } from 'react-redux'
import { loadCourses } from './actions/courseActions'
import 'bootstrap/dist/css/bootstrap.css'
const store = configureStore()
store.dispatch( loadCourses() )
ReactDOM.render(
<Provider store={store}>
<Router history={browserHistory} routes={routes} />
</Provider>,
document.getElementById('root')
)
<file_sep>// This component handles the App template used on every page
import React, { Component, PropTypes } from 'react'
import Header from './common/Header'
import { Grid } from 'react-bootstrap'
class App extends Component {
courseRow(course, index) {
return <div key={index}>{course.title}</div>
}
render() {
return (
<Grid>
<Header />
{this.props.children}
</Grid>
)
}
}
App.propTypes = {
children: PropTypes.object.isRequired
}
export default App
| cfb53f15cfc2cf13014576400425b0f23343936c | [
"JavaScript"
] | 4 | JavaScript | navarrorc/ejected-courses-app | d33c5ee90d2e1da9147396961fdcd7aa7ac94719 | c37984de5a315ad5b5b96324bdae0679a804bb34 |
refs/heads/master | <file_sep>package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.util.ElapsedTime;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer;
import org.firstinspires.ftc.teamcode.vision.MasterVision;
import org.firstinspires.ftc.teamcode.vision.SampleRandomizedPositions;
@Autonomous(name="Auto Drive By Encoder From Ground", group="Pushbot")
//@Disabled
public class AutoDriveByEncoder_From_Ground extends LinearOpMode {
/* Declare OpMode members. */
HardwareTest robot = new HardwareTest(); // Use a Pushbot's hardware
private ElapsedTime runtime = new ElapsedTime();
private double COUNTS_PER_MOTOR_REV = 2240; // eg: Neverest 40
private double DRIVE_GEAR_REDUCTION = 1.0; // This is < 1.0 if geared UP
private double WHEEL_DIAMETER_INCHES = 3.54; // For figuring circumference
private double COUNTS_PER_INCH = (COUNTS_PER_MOTOR_REV * DRIVE_GEAR_REDUCTION) /
(WHEEL_DIAMETER_INCHES * Math.PI);
private static double DRIVE_SPEED = 0.6;
private static double TURN_SPEED = 0.5;
MasterVision vision;
SampleRandomizedPositions goldPosition;
@Override
public void runOpMode() throws InterruptedException {
VuforiaLocalizer.Parameters parameters = new VuforiaLocalizer.Parameters();
parameters.cameraDirection = VuforiaLocalizer.CameraDirection.BACK;// recommended camera direction
parameters.vuforiaLicenseKey = "<KEY>";
/*
* Initialize the drive system variables.
* The init() method of the hardware class does all the work here
*/
robot.init(hardwareMap);
// Send telemetry message to signify robot waiting;
telemetry.addData("Status", "Resetting Encoders"); //
telemetry.update();
robot.leftDrive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
robot.rightDrive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
robot.lift.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
robot.lift.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
//robot.armExtend.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
robot.leftDrive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
robot.lift.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
robot.rightDrive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
//robot.armExtend.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
// Send telemetry message to indicate successful Encoder reset
telemetry.addData("Path0", "Starting at %7d :%7d :%7d",
robot.leftDrive.getCurrentPosition(),
robot.rightDrive.getCurrentPosition(),
robot.lift.getCurrentPosition());
telemetry.update();
vision = new MasterVision(parameters, hardwareMap, true, MasterVision.TFLiteAlgorithm.INFER_LEFT);
vision.init();
vision.enable();
goldPosition = vision.getTfLite().getLastKnownSampleOrder();
while ((goldPosition.toString() == "UNKNOWN")||(runtime.seconds() == 10)){
goldPosition = vision.getTfLite().getLastKnownSampleOrder();
telemetry.addLine(goldPosition.toString());
telemetry.update();}
// Wait for the game to start (driver presses PLAY)
waitForStart();
vision.disable();
robot.lift.setPower(-0.6);
runtime.reset();
while (opModeIsActive() && (runtime.seconds() < 0.8)) {
telemetry.addData("Path", "Leg 1: %2.5f S Elapsed", runtime.seconds());
telemetry.update();
}
sleep(250);
encoderDrive(DRIVE_SPEED, 1.5,1.5,4.0);
sleep(250);
robot.lift.setPower(0.6);
encoderDrive(TURN_SPEED, 7.2, -7.2 , 5.0);
runtime.reset();
while (opModeIsActive() && (runtime.seconds() < 0.75)) {
telemetry.addData("Path", "Leg 1: %2.5f S Elapsed", runtime.seconds());
telemetry.update();
}
// Drive from lander center position
//encoderDrive(TURN_SPEED, 5, 5, 4.0); // S2: Turn Right 12 Inches with 4 Sec timeout
switch (goldPosition){ // using for things in the autonomous program
case LEFT:
telemetry.addLine("going to the left");
telemetry.update();
encoderDrive(TURN_SPEED, -3.0, 3.0, 5.0);
encoderDrive(DRIVE_SPEED, 15, 15, 5.0);
encoderDrive(TURN_SPEED, 5, -5, 5.0);
encoderDrive(DRIVE_SPEED, 10, 10, 8.0);
servo();
//servo
//encoderDrive(DRIVE_SPEED, -50, -50, 10.0);
break;
case CENTER:
telemetry.addLine("going straight");
telemetry.update();
encoderDrive(DRIVE_SPEED, 23, 23, 5.0);
sleep(5000);
servo();
//encoderDrive(TURN_SPEED, 6, -6, 5.0);
//encoderDrive(TURN_SPEED, -50, -50, 10.0);
break;
case RIGHT:
telemetry.addLine("going to the right");
telemetry.update();
encoderDrive(TURN_SPEED, 4, -4, 5.0);
encoderDrive(DRIVE_SPEED, 18, 18, 5.0);
encoderDrive(TURN_SPEED, -7, 7, 5.0);
encoderDrive(DRIVE_SPEED, 5, 5, 5.0);
servo();
//encoderDrive(TURN_SPEED, -8, 8, 5.0);
//encoderDrive(DRIVE_SPEED, 50, 50, 10.0);
break;
case UNKNOWN:
telemetry.addLine("staying put");
telemetry.addLine("going straight");
telemetry.update();
encoderDrive(DRIVE_SPEED, 23, 23, 5.0);
servo();
break;
}
sleep(1000); // pause for servos to move
//telemetry.addData("Path", "Complete");
//telemetry.update();
vision.shutdown();
}
/*
* Method to perfmorm a relative move, based on encoder counts.
* Encoders are not reset as the move is based on the current position.
* Move will stop if any of three conditions occur:
* 1) Move gets to the desired position
* 2) Move runs out of time
* 3) Driver stops the opmode running.
*/
public void encoderDrive(double speed,
double leftInches, double rightInches,
double timeoutS) {
int newLeftTarget;
int newRightTarget;
// Ensure that the opmode is still active
if (opModeIsActive()) {
// Determine new target position, and pass to motor controller
newLeftTarget = robot.leftDrive.getCurrentPosition() + (int) (leftInches * COUNTS_PER_INCH);
newRightTarget = robot.rightDrive.getCurrentPosition() + (int) (rightInches * COUNTS_PER_INCH);
robot.leftDrive.setTargetPosition(newLeftTarget);
robot.rightDrive.setTargetPosition(newRightTarget);
// Turn On RUN_TO_POSITION
robot.leftDrive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
robot.rightDrive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
// reset the timeout time and start motion.
runtime.reset();
robot.leftDrive.setPower(Math.abs(speed));
robot.rightDrive.setPower(Math.abs(speed));
// keep looping while we are still active, and there is time left, and both motors are running.
// Note: We use (isBusy() && isBusy()) in the loop test, which means that when EITHER motor hits
// its target position, the motion will stop. This is "safer" in the event that the robot will
// always end the motion as soon as possible.
// However, if you require that BOTH motors have finished their moves before the robot continues
// onto the next step, use (isBusy() || isBusy()) in the loop test.
while (opModeIsActive() &&
(runtime.seconds() < timeoutS) &&
(robot.leftDrive.isBusy() && robot.rightDrive.isBusy() && robot.leftDrive.isBusy() && robot.rightDrive.isBusy())) {
// Display it for the driver.
telemetry.addData("Path1", "Running to %7d :%7d", newLeftTarget, newRightTarget);
telemetry.addData("Path2", "Running at %7d :%7d",
robot.leftDrive.getCurrentPosition(),
robot.rightDrive.getCurrentPosition()
);
telemetry.update();
}
// Stop all motion;
robot.leftDrive.setPower(0);
robot.rightDrive.setPower(0);
// Turn off RUN_TO_POSITION
robot.leftDrive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
robot.rightDrive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
// sleep(250); // optional pause after each move
}
}
public void servo () {
robot.marker.setPosition(0.5);
sleep(1000);
}
}
<file_sep>package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorSimple;
import com.qualcomm.robotcore.hardware.Servo;
import com.qualcomm.robotcore.util.ElapsedTime;
import com.qualcomm.robotcore.util.Range;
@TeleOp(name="Just_Drive", group="Linear Opmode")
public class Just_drive extends LinearOpMode {
public DcMotor right = null;
public DcMotor left = null;
@Override
public void runOpMode() {
right = hardwareMap.get(DcMotor.class, "right");
right.setDirection(DcMotorSimple.Direction.REVERSE);
left = hardwareMap.get(DcMotor.class, "left");
waitForStart();
while (opModeIsActive()){
double Rpower = Range.clip(gamepad1.left_stick_y + gamepad1.left_stick_x, -0.7, 0.7);
double Lpower = Range.clip(gamepad1.left_stick_y - gamepad1.left_stick_x, -0.7, 0.7);
right.setPower(Rpower);
left.setPower(Lpower);
}
}
}
<file_sep>package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.util.ElapsedTime;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer;
import org.firstinspires.ftc.teamcode.vision.MasterVision;
import org.firstinspires.ftc.teamcode.vision.SampleRandomizedPositions;
@Autonomous(name="Auto Drive By Encoder TFLite", group="Pushbot")
//@Disabled
public class AutoDriveByEncoder_TFLite extends LinearOpMode {
/* Declare OpMode members. */
HardwareTest robot = new HardwareTest(); // Use a Pushbot's hardware
private ElapsedTime runtime = new ElapsedTime();
private double COUNTS_PER_MOTOR_REV = 2240; // eg: Neverest 40
private double DRIVE_GEAR_REDUCTION = 1.0; // This is < 1.0 if geared UP
private double WHEEL_DIAMETER_INCHES = 3.54; // For figuring circumference
private double COUNTS_PER_INCH = (COUNTS_PER_MOTOR_REV * DRIVE_GEAR_REDUCTION) /
(WHEEL_DIAMETER_INCHES * Math.PI);
private static double DRIVE_SPEED = 0.7;
private static double TURN_SPEED = 0.5;
MasterVision vision;
SampleRandomizedPositions goldPosition;
@Override
public void runOpMode() throws InterruptedException {
VuforiaLocalizer.Parameters parameters = new VuforiaLocalizer.Parameters();
parameters.cameraDirection = VuforiaLocalizer.CameraDirection.BACK;// recommended camera direction
parameters.vuforiaLicenseKey = "<KEY>";
/*
* Initialize the drive system variables.
* The init() method of the hardware class does all the work here
*/
robot.init(hardwareMap);
// Send telemetry message to signify robot waiting;
telemetry.addData("Status", "Resetting Encoders"); //
telemetry.update();
robot.leftDrive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
robot.rightDrive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
robot.lift.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
robot.lift.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
//robot.armExtend.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
robot.leftDrive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
robot.lift.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
robot.rightDrive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
//robot.armExtend.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
// Send telemetry message to indicate successful Encoder reset
telemetry.addData("Path0", "Starting at %7d :%7d",
robot.leftDrive.getCurrentPosition(),
robot.rightDrive.getCurrentPosition());
telemetry.update();
vision = new MasterVision(parameters, hardwareMap, true, MasterVision.TFLiteAlgorithm.INFER_RIGHT);
vision.init();
vision.enable();
sleep(5000);
goldPosition = vision.getTfLite().getLastKnownSampleOrder();
telemetry.addLine(goldPosition.toString());
telemetry.update();
// Wait for the game to start (driver presses PLAY)
waitForStart();
vision.disable();
// Step through each leg of the path,
// Note: Reverse movement is obtained by setting a negative distance (not speed)
robot.lift.setTargetPosition(-200);
robot.lift.setMode(DcMotor.RunMode.RUN_TO_POSITION);
robot.lift.setPower(Math.abs(0.6));
while (robot.lift.isBusy()) {
telemetry.addData("Lift",Integer.toString(robot.lift.getCurrentPosition()));
telemetry.update();
}
robot.lift.setPower(Math.abs(0));
robot.lift.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
/*
robot.lift.setTargetPosition(-500);
robot.lift.setMode(DcMotor.RunMode.RUN_TO_POSITION);
robot.lift.setPower(Math.abs(0.6));
while (robot.lift.isBusy()) {
telemetry.update();
}
robot.lift.setPower(Math.abs(0));
robot.lift.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
*/
}
}
<file_sep>package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.util.Range;
@TeleOp
public class MecanumTeleOp extends LinearOpMode {
private double maxPower1 = 0.5;
double rotate;
boolean grab = true;
private double armPos = 0.0;
private int conditional = 1;
private double maxPower = maxPower1 + 0.2 * conditional;
TeleopHard ht = new TeleopHard();
@Override
public void runOpMode() {
ht.init(hardwareMap);
waitForStart();
//ht.armFlip.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
//ht.armFlip.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
ht.lift.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
//double run = ht.armFlip.getCurrentPosition();
while (opModeIsActive()) {
double Rpower = Range.clip(gamepad1.left_stick_y + gamepad1.left_stick_x, -maxPower, maxPower);
double Lpower = Range.clip(gamepad1.left_stick_y - gamepad1.left_stick_x, -maxPower, maxPower);
double liftPower = Range.clip(gamepad1.left_trigger - gamepad1.right_trigger, -0.75, 0.75);
double flipPower = Range.clip(gamepad1.right_stick_y, -0.75, 0.75);
if (gamepad1.y) {
flipPower = 0.3;
} else if (gamepad1.x) {
flipPower = -0.3;
} else {
flipPower = 0;
}
//ht.armFlip.setPower(flipPower);
//if (gamepad1.right_bumper) {
// ht.armExtend.setPower(0.3);
//}
//else if (gamepad1.left_bumper) {
// ht.armExtend.setPower(-0.3);
//}
//else{
// ht.armExtend.setPower(0);
//}
//if (gamepad1.a) {
// if (grab) {
// ht.grabServo.setPower(.75);
// } else {
// ht.grabServo.setPower(0);
// }
//grab = !grab;
//}
telemetry.update();
ht.leftDrive.setPower(Lpower);
ht.rightDrive.setPower(Rpower);
ht.lift.setPower(liftPower);
String messge = "Right Power: " + Double.toString(Rpower) + "Left Power: " + Double.toString(Lpower);
telemetry.addData("Info:", messge);
telemetry.update();
conditional = gamepad1.left_stick_button ? 1 : 0;
maxPower = maxPower1 + conditional * 0.2;
telemetry.update();
}
}
}<file_sep>package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.HardwareMap;
import com.qualcomm.robotcore.hardware.Servo;
import com.qualcomm.robotcore.util.ElapsedTime;
public class HardwareTest
{
/* Public OpMode members. */
public DcMotor leftDrive = null;
public DcMotor rightDrive = null;
public DcMotor lift = null;
//public DcMotor armExtend = null;
//public DcMotor armFlip = null;
//public CRServo grabServo = null;
public Servo marker = null;
public static final double MID_SERVO = 0.5 ;
public static final double ARM_UP_POWER = 0.45 ;
public static final double ARM_DOWN_POWER = -0.45 ;
/* local OpMode members. */
HardwareMap hwMap = null;
private ElapsedTime period = new ElapsedTime();
/* Constructor */
public HardwareTest(){
}
/* Initialize standard Hardware interfaces */
public void init(HardwareMap ahwMap) {
// Save reference to Hardware map
hwMap = ahwMap;
// Define and Initialize Motors
leftDrive = hwMap.get(DcMotor.class, "Left");
rightDrive = hwMap.get(DcMotor.class, "Right");
lift = hwMap.get(DcMotor.class, "Lift");
//armExtend = hwMap.get(DcMotor.class, "armExtend");
//armFlip = hwMap.get(DcMotor.class, "armFlip");
//grabServo = hwMap.get(CRServo.class, "grabServo");
marker = hwMap.get(Servo.class, "Marker");
//grabServo = hwMap.get(CRServo.class, "Grab");
//armMotor = hwMap.get(DcMotor.class, "Arm");
leftDrive.setDirection(DcMotor.Direction.REVERSE); // Set to REVERSE if using AndyMark motors
rightDrive.setDirection(DcMotor.Direction.FORWARD);// Set to FORWARD if using AndyMark motors
// Set all motors to zero power
leftDrive.setPower(0);
rightDrive.setPower(0);
//lift.setPower(0);
//leftArm.setPower(0);
// Set all motors to run without encoders.
// May want to use RUN_USING_ENCODERS if encoders are installed.
leftDrive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
rightDrive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
//armExtend.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
//armFlip.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
//lift.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
//leftArm.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
// Define and initialize ALL installed servos.
//leftClaw = hwMap.get(Servo.class, "left_hand");
//rightClaw = hwMap.get(Servo.class, "right_hand");
//marker.setPosition(1);
//rightClaw.setPosition(MID_SERVO);
}
} | 40fee777b0120055413f6c98cb598224352d39a5 | [
"Java"
] | 5 | Java | taborrobotics12667/ftc_app | 92056161bba76143a4691a1866a5e262a3289695 | e78955901cb1b145a7610552b6a4e75414f7de5c |
refs/heads/main | <repo_name>alphagov/notifications-node-client<file_sep>/client/authentication.js
var jwt = require('jsonwebtoken');
function createGovukNotifyToken(request_method, request_path, secret, client_id) {
return jwt.sign(
{
iss: client_id,
iat: Math.round(Date.now() / 1000)
},
secret,
{
header: {typ: "JWT", alg: "HS256"}
}
);
}
module.exports = createGovukNotifyToken;
<file_sep>/spec/integration/test.js
const fs = require('fs');
const NotifyClient = require('../../client/notification.js').NotifyClient;
const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const chaiJsonSchema = require('chai-json-schema');
const chaiBytes = require('chai-bytes');
chai.use(chaiAsPromised);
chai.use(chaiJsonSchema);
chai.use(chaiBytes);
const should = chai.should();
const expect = chai.expect;
// will not run unless flag provided `npm test --integration`
const describer = process.env.npm_config_integration ? describe.only : describe.skip;
function make_random_id() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
describer('notification api with a live service', function () {
// default is 2000 (ms) - api is sometimes slower than this :(
this.timeout(40000)
let notifyClient;
let teamNotifyClient;
let emailNotificationId;
let smsNotificationId;
let letterNotificationId;
const personalisation = { name: 'Foo' };
const clientRef = 'client-ref';
const email = process.env.FUNCTIONAL_TEST_EMAIL;
const phoneNumber = process.env.FUNCTIONAL_TEST_NUMBER;
const letterContact = {
address_line_1: make_random_id(),
address_line_2: 'Foo',
postcode: 'SW1 1AA',
};
const smsTemplateId = process.env.SMS_TEMPLATE_ID;
const smsSenderId = process.env.SMS_SENDER_ID || undefined;
const emailTemplateId = process.env.EMAIL_TEMPLATE_ID;
const emailReplyToId = process.env.EMAIL_REPLY_TO_ID || undefined;
const letterTemplateId = process.env.LETTER_TEMPLATE_ID;
beforeEach(() => {
const urlBase = process.env.NOTIFY_API_URL;
const apiKeyId = process.env.API_KEY
const inboundSmsKeyId = process.env.INBOUND_SMS_QUERY_KEY;
const teamApiKeyId = process.env.API_SENDING_KEY;
notifyClient = new NotifyClient(urlBase, apiKeyId);
teamNotifyClient = new NotifyClient(urlBase, teamApiKeyId);
receivedTextClient = new NotifyClient(urlBase, inboundSmsKeyId);
var definitions_json = require('./schemas/v2/definitions.json');
chai.tv4.addSchema('definitions.json', definitions_json);
});
describe('notifications', () => {
it('send email notification', () => {
var postEmailNotificationResponseJson = require('./schemas/v2/POST_notification_email_response.json'),
options = {personalisation: personalisation, reference: clientRef};
return notifyClient.sendEmail(emailTemplateId, email, options).then((response) => {
response.status.should.equal(201);
expect(response.data).to.be.jsonSchema(postEmailNotificationResponseJson);
response.data.content.body.should.equal('Hello Foo\r\n\r\nFunctional test help make our world a better place');
response.data.content.subject.should.equal('Functional Tests are good');
response.data.reference.should.equal(clientRef);
emailNotificationId = response.data.id;
})
});
it('send email notification with email_reply_to_id', () => {
var postEmailNotificationResponseJson = require('./schemas/v2/POST_notification_email_response.json'),
options = {personalisation: personalisation, reference: clientRef, emailReplyToId: emailReplyToId};
should.exist(emailReplyToId);
return notifyClient.sendEmail(emailTemplateId, email, options).then((response) => {
response.status.should.equal(201);
expect(response.data).to.be.jsonSchema(postEmailNotificationResponseJson);
response.data.content.body.should.equal('Hello Foo\r\n\r\nFunctional test help make our world a better place');
response.data.content.subject.should.equal('Functional Tests are good');
response.data.reference.should.equal(clientRef);
emailNotificationId = response.data.id;
})
});
it('send email notification with document upload', () => {
var postEmailNotificationResponseJson = require('./schemas/v2/POST_notification_email_response.json'),
options = {personalisation: { name: 'Foo', documents:
notifyClient.prepareUpload(Buffer.from("%PDF-1.5 testpdf"))
}, reference: clientRef};
return notifyClient.sendEmail(emailTemplateId, email, options).then((response) => {
response.status.should.equal(201);
expect(response.data).to.be.jsonSchema(postEmailNotificationResponseJson);
response.data.content.body.should.equal('Hello Foo\r\n\r\nFunctional test help make our world a better place');
response.data.content.subject.should.equal('Functional Tests are good');
response.data.reference.should.equal(clientRef);
emailNotificationId = response.data.id;
})
});
it('send email notification with CSV document upload', () => {
var postEmailNotificationResponseJson = require('./schemas/v2/POST_notification_email_response.json'),
options = {personalisation: { name: 'Foo', documents:
notifyClient.prepareUpload(Buffer.from("a,b"), true)
}, reference: clientRef};
return notifyClient.sendEmail(emailTemplateId, email, options).then((response) => {
response.status.should.equal(201);
expect(response.data).to.be.jsonSchema(postEmailNotificationResponseJson);
response.data.content.body.should.equal('Hello Foo\r\n\r\nFunctional test help make our world a better place');
response.data.content.subject.should.equal('Functional Tests are good');
response.data.reference.should.equal(clientRef);
emailNotificationId = response.data.id;
})
});
it('send sms notification', () => {
var postSmsNotificationResponseJson = require('./schemas/v2/POST_notification_sms_response.json'),
options = {personalisation: personalisation};
return notifyClient.sendSms(smsTemplateId, phoneNumber, options).then((response) => {
response.status.should.equal(201);
expect(response.data).to.be.jsonSchema(postSmsNotificationResponseJson);
response.data.content.body.should.equal('Hello Foo\n\nFunctional Tests make our world a better place');
smsNotificationId = response.data.id;
});
});
it('send sms notification with sms_sender_id', () => {
var postSmsNotificationResponseJson = require('./schemas/v2/POST_notification_sms_response.json'),
options = {personalisation: personalisation, reference: clientRef, smsSenderId: smsSenderId};
should.exist(smsSenderId);
return teamNotifyClient.sendSms(smsTemplateId, phoneNumber, options).then((response) => {
response.status.should.equal(201);
expect(response.data).to.be.jsonSchema(postSmsNotificationResponseJson);
response.data.content.body.should.equal('Hello Foo\n\nFunctional Tests make our world a better place');
smsNotificationId = response.data.id;
});
});
it('send letter notification', () => {
var postLetterNotificationResponseJson = require('./schemas/v2/POST_notification_letter_response.json'),
options = {personalisation: letterContact};
return notifyClient.sendLetter(letterTemplateId, options).then((response) => {
response.status.should.equal(201);
expect(response.data).to.be.jsonSchema(postLetterNotificationResponseJson);
response.data.content.body.should.equal('Hello ' + letterContact.address_line_1);
letterNotificationId = response.data.id;
});
});
it('send a precompiled letter notification', () => {
var postPrecompiledLetterNotificationResponseJson = require(
'./schemas/v2/POST_notification_precompiled_letter_response.json'
);
fs.readFile('./spec/integration/test_files/one_page_pdf.pdf', function(err, pdf_file) {
return notifyClient.sendPrecompiledLetter("my_reference", pdf_file, "first")
.then((response) => {
response.status.should.equal(201);
expect(response.data).to.be.jsonSchema(postPrecompiledLetterNotificationResponseJson);
letterNotificationId = response.data.id;
})
});
});
var getNotificationJson = require('./schemas/v2/GET_notification_response.json');
var getNotificationsJson = require('./schemas/v2/GET_notifications_response.json');
it('get email notification by id', () => {
should.exist(emailNotificationId)
return notifyClient.getNotificationById(emailNotificationId).then((response) => {
response.status.should.equal(200);
expect(response.data).to.be.jsonSchema(getNotificationJson);
response.data.type.should.equal('email');
response.data.body.should.equal('Hello Foo\r\n\r\nFunctional test help make our world a better place');
response.data.subject.should.equal('Functional Tests are good');
});
});
it('get sms notification by id', () => {
should.exist(smsNotificationId)
return notifyClient.getNotificationById(smsNotificationId).then((response) => {
response.status.should.equal(200);
expect(response.data).to.be.jsonSchema(getNotificationJson);
response.data.type.should.equal('sms');
response.data.body.should.equal('Hello Foo\n\nFunctional Tests make our world a better place');
});
});
it('get letter notification by id', () => {
should.exist(letterNotificationId)
return notifyClient.getNotificationById(letterNotificationId).then((response) => {
response.status.should.equal(200);
expect(response.data).to.be.jsonSchema(getNotificationJson);
response.data.type.should.equal('letter');
response.data.body.should.equal('Hello ' + letterContact.address_line_1);
});
});
it('get a letter pdf', (done) => {
should.exist(letterNotificationId)
pdf_contents = fs.readFileSync('./spec/integration/test_files/one_page_pdf.pdf');
var count = 0
// it takes a while for the pdf for a freshly sent letter to become ready, so we need to retry the promise
// a few times, and apply delay in between the attempts. Since our function returns a promise,
// and it's asynchronous, we cannot use a regular loop to do that. That's why we envelop our promise in a
// function which we call up to 7 times or until the promise is resolved.
const tryClient = () => {
return notifyClient.getPdfForLetterNotification(letterNotificationId)
.then((file_buffer) => {
expect(pdf_contents).to.equalBytes(file_buffer);
done();
})
.catch((err) => {
if (err.constructor.name === 'AssertionError') {
done(err);
}
if (err.response.data && (err.response.data.errors[0].error === "PDFNotReadyError")) {
count += 1
if (count < 7) {
setTimeout(tryClient, 5000)
} else {
done(new Error('Too many PDFNotReadyError errors'));
}
};
})
};
tryClient()
});
it('get all notifications', () => {
chai.tv4.addSchema('notification.json', getNotificationJson);
return notifyClient.getNotifications().then((response) => {
response.should.have.property('status', 200);
expect(response.data).to.be.jsonSchema(getNotificationsJson);
});
});
});
describe('templates', () => {
var getTemplateJson = require('./schemas/v2/GET_template_by_id.json');
var getTemplatesJson = require('./schemas/v2/GET_templates_response.json');
var postTemplatePreviewJson = require('./schemas/v2/POST_template_preview.json');
var getReceivedTextJson = require('./schemas/v2/GET_received_text_response.json');
var getReceivedTextsJson = require('./schemas/v2/GET_received_texts_response.json');
it('get sms template by id', () => {
return notifyClient.getTemplateById(smsTemplateId).then((response) => {
response.status.should.equal(200);
expect(response.data).to.be.jsonSchema(getTemplateJson);
response.data.name.should.equal('Client Functional test sms template');
should.not.exist(response.data.subject);
should.not.exist(response.data.letter_contact_block);
});
});
it('get email template by id', () => {
return notifyClient.getTemplateById(emailTemplateId).then((response) => {
response.status.should.equal(200);
expect(response.data).to.be.jsonSchema(getTemplateJson);
response.data.body.should.equal('Hello ((name))\r\n\r\nFunctional test help make our world a better place');
response.data.name.should.equal('Client Functional test email template');
response.data.subject.should.equal('Functional Tests are good');
should.not.exist(response.data.letter_contact_block);
});
});
it('get letter template by id', () => {
return notifyClient.getTemplateById(letterTemplateId).then((response) => {
response.status.should.equal(200);
expect(response.data).to.be.jsonSchema(getTemplateJson);
response.data.body.should.equal('Hello ((address_line_1))');
response.data.name.should.equal('Client functional letter template');
response.data.subject.should.equal('Main heading');
response.data.letter_contact_block.should.equal(
'Government Digital Service\nThe White Chapel Building\n' +
'10 Whitechapel High Street\nLondon\nE1 8QS\nUnited Kingdom'
);
});
});
it('get sms template by id and version', () => {
return notifyClient.getTemplateByIdAndVersion(smsTemplateId, 1).then((response) => {
response.status.should.equal(200);
expect(response.data).to.be.jsonSchema(getTemplateJson);
response.data.name.should.equal('Example text message template');
should.not.exist(response.data.subject);
response.data.version.should.equal(1);
should.not.exist(response.data.letter_contact_block);
});
});
it('get email template by id and version', () => {
return notifyClient.getTemplateByIdAndVersion(emailTemplateId, 1).then((response) => {
response.status.should.equal(200);
expect(response.data).to.be.jsonSchema(getTemplateJson);
response.data.name.should.equal('Client Functional test email template');
response.data.version.should.equal(1);
});
});
it('get letter template by id and version', () => {
return notifyClient.getTemplateByIdAndVersion(letterTemplateId, 1).then((response) => {
response.status.should.equal(200);
expect(response.data).to.be.jsonSchema(getTemplateJson);
response.data.name.should.equal('Untitled');
response.data.version.should.equal(1);
// version 1 of the template had no letter_contact_block
should.not.exist(response.data.letter_contact_block);
});
});
it('get all templates', () => {
return notifyClient.getAllTemplates().then((response) => {
response.status.should.equal(200);
expect(response.data).to.be.jsonSchema(getTemplatesJson);
});
});
it('get sms templates', () => {
return notifyClient.getAllTemplates('sms').then((response) => {
response.status.should.equal(200);
expect(response.data).to.be.jsonSchema(getTemplatesJson);
});
});
it('get email templates', () => {
return notifyClient.getAllTemplates('email').then((response) => {
response.status.should.equal(200);
expect(response.data).to.be.jsonSchema(getTemplatesJson);
});
});
it('get letter templates', () => {
return notifyClient.getAllTemplates('letter').then((response) => {
response.status.should.equal(200);
expect(response.data).to.be.jsonSchema(getTemplatesJson);
});
});
it('preview sms template', () => {
var personalisation = { "name": "Foo" }
return notifyClient.previewTemplateById(smsTemplateId, personalisation).then((response) => {
response.status.should.equal(200);
expect(response.data).to.be.jsonSchema(postTemplatePreviewJson);
response.data.type.should.equal('sms');
should.not.exist(response.data.subject);
});
});
it('preview email template', () => {
var personalisation = { "name": "Foo" }
return notifyClient.previewTemplateById(emailTemplateId, personalisation).then((response) => {
response.status.should.equal(200);
expect(response.data).to.be.jsonSchema(postTemplatePreviewJson);
response.data.type.should.equal('email');
should.exist(response.data.subject);
});
});
it('preview letter template', () => {
var personalisation = { "address_line_1": "Foo", "address_line_2": "Bar", "postcode": "SW1 1AA" }
return notifyClient.previewTemplateById(letterTemplateId, personalisation).then((response) => {
response.status.should.equal(200);
expect(response.data).to.be.jsonSchema(postTemplatePreviewJson);
response.data.type.should.equal('letter');
should.exist(response.data.subject);
});
});
it('get all received texts', () => {
chai.tv4.addSchema('receivedText.json', getReceivedTextJson);
return receivedTextClient.getReceivedTexts().then((response) => {
response.status.should.equal(200);
expect(response.data).to.be.jsonSchema(getReceivedTextsJson);
expect(response.data["received_text_messages"]).to.be.an('array').that.is.not.empty;
});
});
});
});
<file_sep>/spec/authentication.js
var expect = require('chai').expect,
MockDate = require('mockdate'),
jwt = require('jsonwebtoken'),
createGovukNotifyToken = require('../client/authentication.js');
describe('Authentication', function() {
beforeEach(function() {
MockDate.set(1234567890000);
});
afterEach(function() {
MockDate.reset();
});
describe('tokens', function() {
it('can be generated and decoded', function() {
var token = createGovukNotifyToken("POST", "/v2/notifications/sms", "SECRET", 123),
decoded = jwt.verify(token, 'SECRET');
expect(token).to.equal('<KEY>');
expect(decoded.iss).to.equal(123);
expect(decoded.iat).to.equal(1234567890);
});
});
});
<file_sep>/scripts/test_send.js
var argv = require('optimist')
.usage('Usage: $0' +
' -b [baseUrl]' +
' -s [notify secret]' +
' -t [templateId]' +
' -d [destination (email address or phone number, not needed for letters]' +
' -p [personalisation (required for letter {"address_line_1": "mrs test", "address_line_2": "1 test street", "postcode": "SW1 1AA"})]' +
' -m [type (email, sms or letter, default email)]')
.demand(['s', 't'])
.argv,
NotifyClient = require('../client/notification').NotifyClient,
notifyClient,
baseUrl = argv.b || 'https://api.notifications.service.gov.uk',
secret = argv.s,
templateId = argv.t,
destination = argv.d,
personalisation = argv.p ? JSON.parse(argv.p) : null,
type = argv.m || 'email';
notifyClient = new NotifyClient(baseUrl, secret);
switch(type) {
case 'email':
notifyClient.sendEmail(templateId, destination, personalisation)
.then(function(response) {
console.log('Notify response: ' + JSON.stringify(response));
})
.catch(function(error) {
console.log('Error ' + error);
});
break;
case 'sms':
notifyClient.sendSms(templateId, String(destination), personalisation)
.then(function(response) {
console.log('Notify response: ' + JSON.stringify(response));
})
.catch(function(error) {
console.log('Error ' + error);
});
break;
case 'letter':
notifyClient.sendLetter(templateId, personalisation)
.then(function(response) {
console.log('Notify response: ' + JSON.stringify(response));
})
.catch(function(error) {
console.log('Error ' + error);
});
break;
default:
console.log('Unrecognised notification type');
}
<file_sep>/Dockerfile
FROM ghcr.io/alphagov/notify/node:18-slim
ENV DEBIAN_FRONTEND=noninteractive
RUN \
echo "Install base packages" \
&& apt-get update \
&& apt-get install -y --no-install-recommends \
make \
gnupg \
&& echo "Clean up" \
&& rm -rf /var/lib/apt/lists/* /tmp/*
WORKDIR /var/project
<file_sep>/client/api_client.js
var restClient = require('axios').default,
createGovukNotifyToken = require('../client/authentication.js'),
notifyProductionAPI = 'https://api.notifications.service.gov.uk',
version = require('../package.json').version;
/**
* @param urlBase
* @param serviceId
* @param apiKeyId
*
* @constructor
*/
function ApiClient() {
this.proxy = null;
if (arguments.length === 1) {
this.urlBase = notifyProductionAPI;
this.apiKeyId = arguments[0].substring(arguments[0].length - 36, arguments[0].length);
this.serviceId = arguments[0].substring(arguments[0].length - 73, arguments[0].length - 37);
}
if (arguments.length === 2) {
if (arguments[0].startsWith('http')) {
this.urlBase = arguments[0];
this.apiKeyId = arguments[1].substring(arguments[1].length - 36, arguments[1].length);
this.serviceId = arguments[1].substring(arguments[1].length - 73, arguments[1].length - 37);
} else {
this.urlBase = notifyProductionAPI;
this.serviceId = arguments[0];
this.apiKeyId = arguments[1].substring(arguments[1].length - 36, arguments[1].length);
}
}
if (arguments.length === 3) {
this.urlBase = arguments[0];
this.serviceId = arguments[1];
this.apiKeyId = arguments[2].substring(arguments[2].length - 36, arguments[2].length);
}
}
/**
*
* @param {string} requestMethod
* @param {string} requestPath
* @param {string} apiKeyId
* @param {string} serviceId
*
* @returns {string}
*/
function createToken(requestMethod, requestPath, apiKeyId, serviceId) {
return createGovukNotifyToken(requestMethod, requestPath, apiKeyId, serviceId);
}
Object.assign(ApiClient.prototype, {
/**
*
* @param {string} path
*
* @returns {Promise}
*/
get: function(path, additionalOptions) {
var options = {
method: 'get',
url: this.urlBase + path,
headers: {
'Authorization': 'Bearer ' + createToken('GET', path, this.apiKeyId, this.serviceId),
'User-Agent': 'NOTIFY-API-NODE-CLIENT/' + version
}
};
Object.assign(options, additionalOptions)
if(this.proxy !== null) options.proxy = this.proxy;
return restClient(options);
},
/**
*
* @param {string} path
* @param {object} data
*
* @returns {Promise}
*/
post: function(path, data){
var options = {
method: 'post',
url: this.urlBase + path,
data: data,
headers: {
'Authorization': 'Bearer ' + createToken('GET', path, this.apiKeyId, this.serviceId),
'User-Agent': 'NOTIFY-API-NODE-CLIENT/' + version
}
};
if(this.proxy !== null) options.proxy = this.proxy;
return restClient(options);
},
/**
*
* @param {object} an axios proxy config
*/
setProxy: function(proxyConfig){
this.proxy = proxyConfig
}
});
module.exports = ApiClient;
<file_sep>/CHANGELOG.md
## 7.0.3 - 2023-07-21
* Bump word-wrap from 1.2.3 to 1.2.4 to address CVE-2023-26115.
## 7.0.2 - 2023-07-13
* Bump semver from 5.7.1 to 5.7.2
## 7.0.1 - 2023-07-13
* Fix a bug with default behaviour for `confirmEmailBeforeDownload`, which coalesced false to null.
## 7.0.0 - 2023-01-12
* Remove support for node versions below v14.17.3.
## 6.0.0 - 2022-12-22
* Bump jsonwebtokens from 8.5.1 to 9.0.0 to mitigate CVE-2022-23529. We don't believe this CVE affects any use-cases of notifications-node-client; this update is out of best-practice rather than any direct concern.
* Remove support for node versions below v12.
## 5.2.3 - 2022-11-22
* Bump follow-redirects from 1.14.7 to 1.15.2
## 5.2.2 - 2022-11-16
* Upgrade ansi-regex dependencies to mitigate CVE-2021-3807.
## 5.2.1 - 2022-10-19
* Support strings in calls to `prepareUpload`. `fs.readFile` can return strings if an encoding is provided, and the client didn't handle these correctly.
## 5.2.0 - 2022-09-27
* Add support for new security features when sending a file by email:
* `confirmEmailBeforeDownload` can be set to `true` to require the user to enter their email address before accessing the file.
* `retentionPeriod` can be set to `<1-78> weeks` to set how long the file should be made available.
* The `isCsv` parameter to `prepareUpload` has now been replaced by an `options` parameter. The implementation has been done in a backwards-compatible way, so if you are just sending `true/false` values as the seecond parameter, that will continue to work. Though we still recommend updating to use the new options format.
## 5.1.2 - 2022-09-23
Remove underscore.js dependencyr new send a file features)
## 5.1.1 - 2022-01-18
Upgrade axios version from ^0.21.1 to ^0.25.0
## 5.1.0 - 2020-12-30
### Changed
* Upgrade axios version from 0.19.2 to 0.21.1
* Allow any compatible version of axios to be used (0.21.1 to <1.0.0)
* Allow any compatible version of jsonwebtoken to be used (8.2.1 to <9.0.0)
## 5.0.2 - 2020-11-20
### Changed
Correct incorrect description of parameter to be used by `NotifyClient.setProxy`
## 5.0.1 - 2020-11-18
### Changed
Remove unintentional global nature of variable `version`
## 5.0.0 - 2020-09-02
### Changed
We have replaced the use of the npm [request-promise](https://www.npmjs.com/package/request-promise) package with [axios](https://www.npmjs.com/package/axios) as the npm [request](https://www.npmjs.com/package/request) package has been deprecated. This makes the following breaking changes:
1. The `response` `object` returned by a successful API call is now in the form of an [axios response](https://www.npmjs.com/package/axios#response-schema). This has a different interface to a [request response](https://nodejs.org/api/http.html#http_class_http_incomingmessage). For example:
* `response.body` becomes `response.data`
* `response.statusCode` becomes `response.status`
2. The `err` `object` returned by an unsuccessful API call has a different interface. For example, `err.error` becomes `err.response.data`. See the axios documentation for further details on [error handling](https://www.npmjs.com/package/axios#handling-errors).
3. To configure the use of a proxy you should pass the proxy configuration as an `object` rather than a URL. For details, see the [axios client](https://github.com/axios/axios).
4. We now return native [promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises) rather than [bluebird promises](http://bluebirdjs.com). You will not need to make any changes unless you are using some of the additional methods found on bluebird promises that do not exist on native promises.
## 4.9.0 - 2020-08-19
### Changed
* Added `letter_contact_block` to the responses for `getTemplateById`, `getTemplateByIdAndVersion` and `getAllTemplates`.
## 4.8.0 - 2020-06-18
### Changed
* Add support for an optional `isCsv` parameter in the `prepareUpload` function. This fixes a bug when sending a CSV file by email. This ensures that the file is downloaded as a CSV rather than a TXT file.
## [4.7.3] - 2020-04-03
### Changed
* Remove `__dirname` global call from api client
## [4.7.2] - 2020-01-31
### Changed
* Add homepage to package.json
## [4.7.1] - 2020-01-27
### Changed
* Refer to files, not documents, in error messages
## [4.7.0] - 2019-11-01
### Changed
* Add `notifyClient.getPdfForLetterNotification(notificationId)`
* Returns a Buffer with pdf data
* Will raise a BadRequestError if the PDF is not available
## [4.6.0] - 2019-02-01
### Changed
* Added an optional postage argument to `sendPrecompiledLetter`
## [4.5.2] - 2018-11-05
### Changed
* Moved documentation to https://docs.notifications.service.gov.uk/node.html (generated from DOCUMENTATION.md)
## [4.5.1] - 2018-09-14
### Changed
* Made formatting consistent across documentation.
## [4.5.0] - 2018-09-13
### Changed
* Added a function to send precompiled letter through the client.
* the new function uses a helper function to check if the file size is within the 5MB limit and to encode the file using base64. Then a POST request to our API is made with the file data and user reference.
* instructions for the new functionality added to the documentation.
## [4.4.0] - 2018-09-05
### Changed
* Added instructions for uploading a document to be linked to from an email notification.
* Created a helper function `prepareUpload` as a part of this development. This function encodes the document that is to be uploaded with base64 and returns a dictionary with prepared document as a value (the way our API is prepared to receive it). It also checks if the provided file is not larger than 2MB. The function throws an error if the file is too big.
## [4.3.0] - 2018-09-04
* Added `name` to the response for `getTemplateById()` and `getTemplateByIdAndVersion()`
* These functions now return the name of the template as set in Notify
## [4.2.0] - 2018-07-24
### Changed
* Added `created_by_name` to the response for `.getNotificationById()` and `.getNotifications()`:
* If the notification was sent manually this will be the name of the sender. If the notification was sent through the API this will be `null`.
## [4.1.0] - 2017-11-23
### Changed
* Added new method:
* `getReceivedTexts` - get one page of text messages (250) per call
## [4.0.0] - 2017-11-07
### Changed
* Updated `sendSms`, `sendEmail` and `sendLetter` to take an `options` object as a parameter.
* `personalisation`, `reference`, `smsSenderId` and `emailReplyToId` now need to be passed to these functions inside `options`.
* Removed the unused `Crypto` dependency
## [3.5.0] - 2017-11-01
### Changed
* Updated `sendSms` method with optional argument:
* `smsSenderId` - specify the identifier of the sms sender (optional)
## [3.4.0] - 2017-10-19
### Changed
* Added new method:
* `sendLetter` - send a letter
## [3.3.0] - 2017-10-13
### Changed
* Updated `sendEmail` method with optional argument:
* `emailReplyToId` - specify the identifier of the email reply-to address (optional)
## [3.2.0] - 2017-09-22
### Changed
* Added new method:
* `setProxy(proxyUrl)` - specify the URL of a proxy for the client to use (optional)
## [3.1.0] - 2017-05-10
### Changed
* Added new methods for managing templates:
* `getTemplateById` - retrieve a single template
* `getTemplateByIdAndVersion` - retrieve a specific version for a desired template
* `getAllTemplates` - retrieve all templates (can filter by type)
* `previewTemplateById` - preview a template with personalisation applied
* Update README to describe how to catch errors
## [3.0.0] - 2016-12-16
### Changed
* Using v2 of the notification-api.
* Update to `notifyClient.sendSms()`:
* Added `reference`: an optional identifier you generate if you don’t want to use Notify’s `id`. It can be used to identify a single notification or a batch of notifications.
* Updated method signature:
```javascript
notifyClient.sendSms(templateId, phoneNumber, personalisation, reference);
```
* Where `personalisation` and `reference` can be `undefined`.
* Update to `notifyClient.sendEmail()`:
* Added `reference`: an optional identifier you generate if you don’t want to use Notify’s `id`. It can be used to identify a single notification or a batch of notifications.
* Updated method signature:
```javascript
notifyClient.sendEmail(templateId, emailAddress, personalisation, reference);
```
* Where `personalisation` and `reference` can be `undefined`.
* `NotificationClient.getAllNotifications()`
* Notifications can now be filtered by `reference` and `olderThanId`, see the README for details.
* Updated method signature:
```javascript
notifyClient.getNotifications(templateType, status, reference, olderThanId);
```
* Each one of these parameters can be `undefined`
# Prior versions
Changelog not recorded - please see pull requests on github.
<file_sep>/spec/notification.js
const chai = require('chai');
const chaiBytes = require('chai-bytes');
chai.use(chaiBytes);
let expect = require('chai').expect,
NotifyClient = require('../client/notification.js').NotifyClient,
MockDate = require('mockdate'),
nock = require('nock'),
createGovukNotifyToken = require('../client/authentication.js');
MockDate.set(1234567890000);
const baseUrl = 'http://localhost';
const serviceId = 'c745a8d8-b48a-4b0d-96e5-dbea0165ebd1';
const apiKeyId = '<KEY>';
function getNotifyClient() {
let baseUrl = 'http://localhost';
let notifyClient = new NotifyClient(baseUrl, serviceId, apiKeyId);
return notifyClient;
}
function getNotifyAuthNock() {
let notifyNock = nock(baseUrl, {
reqheaders: {
'Authorization': 'Bearer ' + createGovukNotifyToken('POST', '/v2/notifications/', apiKeyId, serviceId)
}
})
return notifyNock;
}
describe('notification api', () => {
beforeEach(() => {
MockDate.set(1234567890000);
});
afterEach(() => {
MockDate.reset();
});
let notifyClient = getNotifyClient();
let notifyAuthNock = getNotifyAuthNock();
describe('sendEmail', () => {
it('should send an email', () => {
let email = '<EMAIL>',
templateId = '123',
options = {
personalisation: {foo: 'bar'},
},
data = {
template_id: templateId,
email_address: email,
personalisation: options.personalisation
};
notifyAuthNock
.post('/v2/notifications/email', data)
.reply(200, {hooray: 'bkbbk'});
return notifyClient.sendEmail(templateId, email, options)
.then(function (response) {
expect(response.status).to.equal(200);
});
});
it('should send an email with email_reply_to_id', () => {
let email = '<EMAIL>',
templateId = '123',
options = {
personalisation: {foo: 'bar'},
emailReplyToId: '456',
},
data = {
template_id: templateId,
email_address: email,
personalisation: options.personalisation,
email_reply_to_id: options.emailReplyToId
};
notifyAuthNock
.post('/v2/notifications/email', data)
.reply(200, {hooray: 'bkbbk'});
return notifyClient.sendEmail(templateId, email, options)
.then((response) => {
expect(response.status).to.equal(200);
});
});
it('should send an email with document upload', () => {
let email = '<EMAIL>',
templateId = '123',
options = {
personalisation: {documents:
notifyClient.prepareUpload(Buffer.from("%PDF-1.5 testpdf"))
},
},
data = {
template_id: templateId,
email_address: email,
personalisation: options.personalisation,
};
notifyAuthNock
.post('/v2/notifications/email', data)
.reply(200, {hooray: 'bkbbk'});
return notifyClient.sendEmail(templateId, email, options)
.then((response) => {
expect(response.status).to.equal(200);
expect(response.config.data).to.include('"is_csv":false');
});
});
it('should send an email with CSV document upload', () => {
let email = '<EMAIL>',
templateId = '123',
options = {
personalisation: {documents:
notifyClient.prepareUpload(Buffer.from("a,b"), true)
},
},
data = {
template_id: templateId,
email_address: email,
personalisation: options.personalisation,
};
notifyAuthNock
.post('/v2/notifications/email', data)
.reply(200, {hooray: 'bkbbk'});
return notifyClient.sendEmail(templateId, email, options)
.then((response) => {
expect(response.status).to.equal(200);
expect(response.config.data).to.include('"is_csv":true');
});
});
it('should send an email with non CSV document upload', () => {
let email = '<EMAIL>',
templateId = '123',
options = {
personalisation: {documents:
notifyClient.prepareUpload(Buffer.from("%PDF-1.5 testpdf"), false)
},
},
data = {
template_id: templateId,
email_address: email,
personalisation: options.personalisation,
};
notifyAuthNock
.post('/v2/notifications/email', data)
.reply(200, {hooray: 'bkbbk'});
return notifyClient.sendEmail(templateId, email, options)
.then((response) => {
expect(response.status).to.equal(200);
expect(response.config.data).to.include('"is_csv":false');
});
});
it('should reject options dicts with unknown options', () => {
let email = '<EMAIL>',
templateId = '123',
// old personalisation dict
options = {
firstname: 'Fred',
surname: 'Smith',
reference: 'ABC123'
};
return notifyClient.sendEmail(templateId, email, options)
.catch((err) => expect(err.message).to.include('["firstname","surname"]'));
});
});
describe('prepareUpload', () => {
it('should throw error when file bigger than 2MB is supplied', () => {
let file = Buffer.alloc(3*1024*1024)
expect(function(){
notifyClient.prepareUpload(file);
}).to.throw("File is larger than 2MB.")
});
it('should accept files as buffers (from fs.readFile with no encoding)', () => {
let fs = require('fs');
let file = fs.readFileSync('./spec/test_files/simple.csv');
expect(typeof(file)).to.equal('object')
expect(Buffer.isBuffer(file)).to.equal(true);
expect(
notifyClient.prepareUpload(file, true)
).contains({file: 'MSwyLDMKYSxiLGMK', is_csv: true})
});
it('should accept files as strings (from fs.readFile with an encoding)', () => {
let fs = require('fs');
let file = fs.readFileSync('./spec/test_files/simple.csv', 'binary');
expect(typeof(file)).to.equal('string')
expect(Buffer.isBuffer(file)).to.equal(false);
expect(
notifyClient.prepareUpload(file, true)
).contains({file: 'MSwyLDMKYSxiLGMK', is_csv: true})
});
it('should allow isCsv to be set with the old method (directly into options)', () => {
let file = Buffer.alloc(2*1024*1024)
expect(
notifyClient.prepareUpload(file, true)
).contains({is_csv: true, confirm_email_before_download: null, retention_period: null})
});
it('should allow isCsv to be set as part of the options object', () => {
let file = Buffer.alloc(2*1024*1024)
expect(
notifyClient.prepareUpload(file, {isCsv: true})
).contains({is_csv: true, confirm_email_before_download: null, retention_period: null})
});
it('should imply isCsv=false from empty options', () => {
let file = Buffer.alloc(2*1024*1024)
expect(
notifyClient.prepareUpload(file, {})
).contains({is_csv: false, confirm_email_before_download: null, retention_period: null})
});
it('should allow send a file email confirmation to be disabled', () => {
let file = Buffer.alloc(2*1024*1024)
expect(
notifyClient.prepareUpload(file, {confirmEmailBeforeDownload: false})
).contains({is_csv: false, confirm_email_before_download: false, retention_period: null})
});
it('should allow send a file email confirmation to be set', () => {
let file = Buffer.alloc(2*1024*1024)
expect(
notifyClient.prepareUpload(file, {confirmEmailBeforeDownload: true})
).contains({is_csv: false, confirm_email_before_download: true, retention_period: null})
});
it('should allow custom retention periods to be set', () => {
let file = Buffer.alloc(2*1024*1024)
expect(
notifyClient.prepareUpload(file, {retentionPeriod: "52 weeks"})
).contains({is_csv: false, confirm_email_before_download: null, retention_period: '52 weeks'})
});
});
describe('sendSms', () => {
it('should send an sms', () => {
let phoneNo = '07525755555',
templateId = '123',
options = {
personalisation: {foo: 'bar'},
},
data = {
template_id: templateId,
phone_number: phoneNo,
personalisation: options.personalisation
};
notifyAuthNock
.post('/v2/notifications/sms', data)
.reply(200, {hooray: 'bkbbk'});
return notifyClient.sendSms(templateId, phoneNo, options)
.then(function (response) {
expect(response.status).to.equal(200);
});
});
it('should send an sms with smsSenderId', () => {
let phoneNo = '07525755555',
templateId = '123',
options = {
personalisation: {foo: 'bar'},
smsSenderId: '456',
},
data = {
template_id: templateId,
phone_number: phoneNo,
personalisation: options.personalisation,
sms_sender_id: options.smsSenderId,
};
notifyAuthNock
.post('/v2/notifications/sms', data)
.reply(200, {hooray: 'bkbbk'});
return notifyClient.sendSms(templateId, phoneNo, options)
.then(function (response) {
expect(response.status).to.equal(200);
});
});
it('should reject options dicts with unknown options', () => {
let phoneNumber = '07123456789',
templateId = '123',
// old personalisation dict
options = {
firstname: 'Fred',
surname: 'Smith',
reference: 'ABC123'
};
return notifyClient.sendSms(templateId, phoneNumber, options)
.catch((err) => expect(err.message).to.include('["firstname","surname"]'));
});
});
describe('sendLetter', () => {
it('should send a letter', () => {
let templateId = '123',
options = {
personalisation: {
address_line_1: 'Mr Tester',
address_line_2: '1 Test street',
postcode: 'NW1 2UN'
},
},
data = {
template_id: templateId,
personalisation: options.personalisation
};
notifyAuthNock
.post('/v2/notifications/letter', data)
.reply(200, {hooray: 'bkbbk'});
return notifyClient.sendLetter(templateId, options)
.then(function (response) {
expect(response.status).to.equal(200);
});
});
it('should reject options dicts with unknown options', () => {
let templateId = '123',
// old personalisation dict
options = {
address_line_1: 'Mr Tester',
address_line_2: '1 Test street',
postcode: 'NW1 2UN',
reference: 'ABC123'
};
return notifyClient.sendLetter(templateId, options)
.catch((err) => expect(err.message).to.include('["address_line_1","address_line_2","postcode"]'));
});
});
it('should get notification by id', () => {
let notificationId = 'wfdfdgf';
notifyAuthNock
.get('/v2/notifications/' + notificationId)
.reply(200, {hooray: 'bkbbk'});
return notifyClient.getNotificationById(notificationId)
.then(function (response) {
expect(response.status).to.equal(200);
});
});
it('should get letter pdf by id', () => {
let pdf_file = Buffer.from("%PDF-1.5 testpdf")
let notificationId = 'wfdfdgf';
notifyAuthNock
.get('/v2/notifications/' + notificationId + '/pdf')
.reply(200, pdf_file.toString());
return notifyClient.getPdfForLetterNotification(notificationId)
.then(function (response_buffer) {
expect(response_buffer).to.equalBytes(pdf_file)
});
});
describe('sendPrecompiledLetter', () => {
it('should send a precompiled letter', () => {
let pdf_file = Buffer.from("%PDF-1.5 testpdf"),
reference = "HORK",
data = {"reference": reference, "content": pdf_file.toString('base64')}
notifyAuthNock
.post('/v2/notifications/letter', data)
.reply(200, {hiphip: 'hooray'});
return notifyClient.sendPrecompiledLetter(reference, pdf_file)
.then(function (response) {
expect(response.status).to.equal(200);
});
});
it('should be able to set postage when sending a precompiled letter', () => {
let pdf_file = Buffer.from("%PDF-1.5 testpdf"),
reference = "HORK",
postage = "first"
data = {"reference": reference, "content": pdf_file.toString('base64'), "postage": postage}
notifyAuthNock
.post('/v2/notifications/letter', data)
.reply(200, {hiphip: 'hooray'});
return notifyClient.sendPrecompiledLetter(reference, pdf_file, postage)
.then(function (response) {
expect(response.status).to.equal(200);
});
});
it('should throw error when file bigger than 5MB is supplied', () => {
let file = Buffer.alloc(6*1024*1024),
reference = "HORK"
expect(function(){
notifyClient.sendPrecompiledLetter(reference, file);
}).to.throw("File is larger than 5MB.")
});
});
describe('getNotifications', () => {
it('should get all notifications', () => {
notifyAuthNock
.get('/v2/notifications')
.reply(200, {hooray: 'bkbbk'});
return notifyClient.getNotifications()
.then(function (response) {
expect(response.status).to.equal(200);
});
});
it('should get all notifications with a reference', () => {
let reference = 'myref';
notifyAuthNock
.get('/v2/notifications?reference=' + reference)
.reply(200, {hooray: 'bkbbk'});
return notifyClient.getNotifications(undefined, undefined, reference)
.then(function (response) {
expect(response.status).to.equal(200);
});
});
it('should get all failed notifications', () => {
let status = 'failed';
notifyAuthNock
.get('/v2/notifications?status=' + status)
.reply(200, {hooray: 'bkbbk'});
return notifyClient.getNotifications(undefined, 'failed')
.then(function (response) {
expect(response.status).to.equal(200);
});
});
it('should get all failed sms notifications', () => {
let templateType = 'sms';
let status = 'failed';
notifyAuthNock
.get('/v2/notifications?template_type=' + templateType + '&status=' + status)
.reply(200, {hooray: 'bkbbk'});
return notifyClient.getNotifications(templateType, status)
.then(function (response) {
expect(response.status).to.equal(200);
});
});
it('should get all delivered sms notifications with a reference', () => {
let templateType = 'sms';
let status = 'delivered';
let reference = 'myref';
notifyAuthNock
.get('/v2/notifications?template_type=' + templateType + '&status=' + status + '&reference=' + reference)
.reply(200, {hooray: 'bkbbk'});
return notifyClient.getNotifications(templateType, status, reference)
.then(function (response) {
expect(response.status).to.equal(200);
});
});
it('should get all failed email notifications with a reference older than a given notification', () => {
let templateType = 'sms';
let status = 'delivered';
let reference = 'myref';
let olderThanId = '35836a9e-5a97-4d99-8309-0c5a2c3dbc72';
notifyAuthNock
.get('/v2/notifications?template_type=' + templateType +
'&status=' + status +
'&reference=' + reference +
'&older_than=' + olderThanId
)
.reply(200, {hooray: 'bkbbk'});
return notifyClient.getNotifications(templateType, status, reference, olderThanId)
.then(function (response) {
expect(response.status).to.equal(200);
});
});
});
describe('template funtions', () => {
it('should get template by id', () => {
let templateId = '35836a9e-5a97-4d99-8309-0c5a2c3dbc72';
notifyAuthNock
.get('/v2/template/' + templateId)
.reply(200, {foo: 'bar'});
return notifyClient.getTemplateById(templateId)
.then(function (response) {
expect(response.status).to.equal(200);
});
});
it('should get template by id and version', () => {
let templateId = '35836a9e-5a97-4d99-8309-0c5a2c3dbc72';
let version = 10;
notifyAuthNock
.get('/v2/template/' + templateId + '/version/' + version)
.reply(200, {foo: 'bar'});
return notifyClient.getTemplateByIdAndVersion(templateId, version)
.then(function (response) {
expect(response.status).to.equal(200);
});
});
it('should get all templates with unspecified template type', () => {
notifyAuthNock
.get('/v2/templates')
.reply(200, {foo: 'bar'});
return notifyClient.getAllTemplates()
.then(function (response) {
expect(response.status).to.equal(200);
});
});
it('should get all templates with unspecified template type', () => {
let templateType = 'sms'
notifyAuthNock
.get('/v2/templates?type=' + templateType)
.reply(200, {foo: 'bar'});
return notifyClient.getAllTemplates(templateType)
.then(function (response) {
expect(response.status).to.equal(200);
});
});
it('should preview template by id with personalisation', () => {
let templateId = '35836a9e-5a97-4d99-8309-0c5a2c3dbc72';
let payload = {name: 'Foo' }
let expectedPersonalisation = {personalisation: payload };
notifyAuthNock
.post('/v2/template/' + templateId + '/preview', expectedPersonalisation)
.reply(200, {foo: 'bar'});
return notifyClient.previewTemplateById(templateId, payload)
.then(function (response) {
expect(response.status).to.equal(200);
});
});
it('should preview template by id without personalisation', () => {
let templateId = '35836a9e-5a97-4d99-8309-0c5a2c3dbc72';
notifyAuthNock
.post('/v2/template/' + templateId + '/preview')
.reply(200, {foo: 'bar'});
return notifyClient.previewTemplateById(templateId)
.then(function (response) {
expect(response .status).to.equal(200);
});
});
});
it('should get latest 250 received texts', function() {
notifyAuthNock
.get('/v2/received-text-messages')
.reply(200, {"foo":"bar"});
return notifyClient.getReceivedTexts()
.then(function(response){
expect(response.status).to.equal(200);
});
});
it('should get up to next 250 received texts with a reference older than a given message id', function() {
var olderThanId = '35836a9e-5a97-4d99-8309-0c5a2c3dbc72';
notifyAuthNock
.get('/v2/received-text-messages?older_than=' + olderThanId)
.reply(200, {"foo":"bar"});
return notifyClient.getReceivedTexts(olderThanId)
.then(function(response){
expect(response.status).to.equal(200);
});
});
});
MockDate.reset();
<file_sep>/CONTRIBUTING.md
# Contributing
Pull requests welcome.
## Setting Up
### Docker container
This app uses dependencies that are difficult to install locally. In order to make local development easy, we run app commands through a Docker container. Run the following to set this up:
```shell
make bootstrap-with-docker
```
### `environment.sh`
In the root directory of the repo, run:
```
notify-pass credentials/client-integration-tests > environment.sh
```
Unless you're part of the GOV.UK Notify team, you won't be able to run this command or the Integration Tests. However, the file still needs to exist - run `touch environment.sh` instead.
## Tests
There are unit and integration tests that can be run to test functionality of the client.
### Unit tests
To run the unit tests:
```
make test-with-docker
```
### Integration Tests
To run the integration tests:
```
make integration-test-with-docker
```
## Working on the client locally
```
npm install --save notifications-node-client
```
## Testing JavaScript examples in Markdown
We automatically test that the JavaScript in the documentation examples matches [our linting standards](https://gds-way.cloudapps.digital/manuals/programming-languages/nodejs/#source-formatting-and-linting). This also catches some issues that could stop an example from running when copied.
You can fix issues automatically by running:
```
npm run test:markdown:standard -- --fix
```
<file_sep>/Makefile
.DEFAULT_GOAL := help
SHELL := /bin/bash
.PHONY: help
help:
@cat $(MAKEFILE_LIST) | grep -E '^[a-zA-Z_-]+:.*?## .*$$' | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'
.PHONY: bootstrap
bootstrap: ## Install build dependencies
npm ci
.PHONY: build
build: bootstrap ## Build project (dummy task for CI)
.PHONY: test
test: ## Run tests
npm test
.PHONY: integration-test
integration-test: ## Run integration tests
npm test --integration
.PHONY: bootstrap-with-docker
bootstrap-with-docker: ## Prepare the Docker builder image
docker build -t notifications-node-client .
./scripts/run_with_docker.sh make bootstrap
.PHONY: test-with-docker
test-with-docker: ## Run tests inside a Docker container
./scripts/run_with_docker.sh make test
.PHONY: integration-test-with-docker
integration-test-with-docker: ## Run integration tests inside a Docker container
./scripts/run_with_docker.sh make integration-test
.PHONY: get-client-version
get-client-version: ## Retrieve client version number from source code
@node -p "require('./package.json').version"
clean:
rm -rf .cache venv
<file_sep>/index.js
var NotifyClient = require("./client/notification.js").NotifyClient;
module.exports = {
NotifyClient: NotifyClient
}; | bb6c899b465f10ffcb10bb5334a3c6dab44695d8 | [
"JavaScript",
"Makefile",
"Dockerfile",
"Markdown"
] | 11 | JavaScript | alphagov/notifications-node-client | c88447a10c270c17f1614532c3809d578faa5341 | 1388f79aa34e407356bd71541f21c19e1f674a2e |
refs/heads/master | <file_sep>'use strict';
var part = {
etc: ':',
childIndent: '│ ',
childSiblings: '├── ',
childLast: '└── ',
spaces: ' '
};
function walkOnDirectories (crumb, state) {
var keys = Object.keys(crumb);
if (state === void 0) {
state = {
steps: [],
indent: ''
};
}
keys.forEach(function (key, i) {
var node = crumb[key];
var last = i === keys.length - 1;
if (key === '$files') {
walkOnFiles(node, state, last);
} else {
state.indent += last ? part.childLast : part.childSiblings;
push(state, '', key);
outdent(state);
state.indent += last ? part.spaces : part.childIndent;
walkOnDirectories(node, state);
outdent(state);
}
});
return state.steps;
}
function walkOnFiles (files, state, last) {
var relationship = part.childSiblings;
files.forEach(function (file, i) {
if (i === files.length - 1) {
relationship = last ? part.childLast : part.childSiblings;
}
if (file === '$etc') {
push(state, part.etc, '');
push(state, part.etc, '');
} else {
push(state, relationship, file);
}
});
}
function outdent (state) {
state.indent = state.indent.substr(0, state.indent.length - 4);
}
function push (state, relationship, name) {
state.steps.push(state.indent + relationship + name);
}
module.exports = function (input) {
if (typeof input === 'string') {
input = JSON.parse(input);
}
var result = walkOnDirectories(input);
var tree = result.join('\n');
return tree;
};
<file_sep># hierarchy
> Convert JSON object to a beautiful string representation of a directory structure
Like [archy](https://github.com/substack/node-archy), but easier. Inspired in the text-tree [found in an answer on StackOverflow](http://stackoverflow.com/a/20408498/389745).
# Installation
```shell
npm i --save hierarchyjs
```
# Usage
Considering the `input.json` file:
```json
{
"foo": {
"bar": {
"$files": ["baz.js", "piece.js"]
},
"paz": {}
},
"baz": {
"$files": ["taz.js"]
},
"$files": ["Gruntfile.js", "package.json"]
}
```
## From the command line
```shell
hierarchy input.json
```
## In code
```js
var hierarchy = require('hierarchy');
var input = require('input.json');
var tree = hierarchy(input);
console.log(tree);
```
# Notation
The input is expected to be a tree-like object with optional `$files` arrays that describe a list of files in a directory. The `$files` construct can actually be avoided by treating files as empty directories, but its a little convenience sugar.
The following has the exact same output as the previous example.
```json
{
"foo": {
"bar": {
"$files": {
"baz.js": {},
"piece.js": {}
},
},
"paz": {}
},
"baz": {
"taz.js": {}
},
"Gruntfile.js": {},
"package.json": {}
}
```
A file named `$etc` might be used to include a "and more.." `'....'` kind of message.
# License
MIT
<file_sep>#!/usr/bin/env node
'use strict';
var fs = require('fs');
var path = require('path');
var hierarchy = require('../index.js');
var arg = process.argv[2];
var file = path.resolve(process.cwd(), arg);
fs.readFile(file, { encoding: 'utf8' }, function (err, data) {
if (err) {
throw err;
}
var tree = hierarchy(data);
console.log(tree);
});
| 75ff352eb6b8191debf36138e40cc58e4e539539 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | nvdnkpr/hierarchy | 89a9417716349856e2b1ace3b6a94b1315f764ef | 8c9b6932ecfdd5a98dba4f6a6ea46d41dbd05de1 |
refs/heads/master | <file_sep>require 'math'
require 'os'
GameOverState = {}
function GameOverState.load()
sprites.gameoveroverlay = love.graphics.newImage('assets/gameoveroverlay.png')
end
function GameOverState.setup(args)
math.randomseed(os.time())
fact = FACTS[math.random(1, #FACTS)]
score = args.score
ready = false
end
function GameOverState.update(delta)
if love.keyboard.isDown('r') then
ready = true
elseif ready then
enterState('game')
end
end
function GameOverState.draw()
states.game.draw()
love.graphics.draw(sprites.gameoveroverlay, 0, 0)
love.graphics.printf(score .. ' POINTS',
MONKEY_X_COORD + 10, 10,
WINDOW_WIDTH - MONKEY_X_COORD - 20, 'right')
love.graphics.printf('Game Over', 0, 200, WINDOW_WIDTH, 'center')
love.graphics.setFont(smallfont)
love.graphics.printf('Press [R] to restart.', 0, 250, WINDOW_WIDTH, 'center')
love.graphics.printf('Deforestion Fact:', 0, 300, WINDOW_WIDTH, 'center')
love.graphics.printf(fact, 150, 325, WINDOW_WIDTH - 300, 'center')
love.graphics.setFont(font)
end<file_sep>require 'constants'
require 'game'
require 'gameover'
currentState = nil
states = {
game = GameState,
gameover = GameOverState
}
sprites = {}
function love.load()
love.graphics.setDefaultFilter('nearest')
love.window.setMode(WINDOW_WIDTH, WINDOW_HEIGHT)
love.window.setFullscreen(false) -- just for debugging
love.window.setTitle("Forest Invaders")
love.window.setIcon(love.graphics.newImage('assets/icon.png'):getData())
love.mouse.setVisible(false)
for _,v in pairs(states) do
v.load()
end
font = love.graphics.newFont('assets/upheavtt.ttf', 48)
smallfont = love.graphics.newFont('assets/upheavtt.ttf', 24)
love.graphics.setFont(font)
enterState('game', {})
end
function enterState(state, args)
states[state].setup(args)
currentState = state
end
function love.update(delta)
states[currentState].update(delta)
end
function love.draw()
states[currentState].draw()
end<file_sep>require 'math'
require 'os'
require 'constants'
GameState = {}
local monkey = {}
local bananas = {}
local tractors = {}
local vars = {}
function GameState.load()
-- load sprites
sprites.monkey = love.graphics.newImage('assets/monkey.png')
sprites.grass = love.graphics.newImage('assets/grass.png')
sprites.banana = love.graphics.newImage('assets/banana.png')
sprites.tractor = love.graphics.newImage('assets/tractor.png')
sprites.forest = {
love.graphics.newImage('assets/forest1.png'),
love.graphics.newImage('assets/forest2.png'),
love.graphics.newImage('assets/forest3.png'),
love.graphics.newImage('assets/forest4.png'),
love.graphics.newImage('assets/forest5.png'),
}
sprites.forest[0] = love.graphics.newImage('assets/forest0.png')
end
function GameState.setup()
math.randomseed(os.time())
monkey = {}
bananas = {}
tractors = {}
vars = {}
monkey.y = 300
vars.bananaCooldown = 0
vars.bananaCount = MAX_BANANAS
vars.bananaRegen = 0
vars.tractorTrySpawn = 0
vars.lives = 5
vars.score = 0
end
function GameState.update(delta)
-- move the monkey
if love.keyboard.isDown('up') and monkey.y > 0 then
monkey.y = monkey.y - MONKEY_MOVE_SPEED * delta
end
if love.keyboard.isDown('down') and monkey.y + (sprites.monkey:getHeight() * MONKEY_SPRITE_SCALE) < WINDOW_HEIGHT then
monkey.y = monkey.y + MONKEY_MOVE_SPEED * delta
end
-- calculate banana cooldown and regen
vars.bananaCooldown = vars.bananaCooldown - delta
vars.bananaRegen = vars.bananaRegen + delta
if vars.bananaRegen >= BANANA_REGEN_RATE then
vars.bananaRegen = 0
if vars.bananaCount < MAX_BANANAS then
vars.bananaCount = vars.bananaCount + 1
end
end
-- shoot bananas
if love.keyboard.isDown(' ') and vars.bananaCooldown <= 0 and vars.bananaCount > 0 then
vars.bananaCooldown = BANANA_MAX_COOLDOWN
vars.bananaCount = vars.bananaCount - 1
table.insert(bananas, {x = MONKEY_X_COORD + (sprites.monkey:getWidth() * MONKEY_SPRITE_SCALE),
y = monkey.y + ((sprites.monkey:getHeight() * MONKEY_SPRITE_SCALE) / 2),
r = 0})
end
-- move existing bananas
for i,v in ipairs(bananas) do
v.x = v.x + BANANA_MOVE_SPEED * delta
v.r = v.r + BANANA_ROTATE_SPEED * delta
if v.x > WINDOW_WIDTH + 50 then -- 50 pixel buffer off the edge of the screen
table.remove(bananas, i)
end
end
-- try to spawn a tractor
vars.tractorTrySpawn = vars.tractorTrySpawn + delta
if vars.tractorTrySpawn > TRACTOR_SPAWN_TRY_RATE then
vars.tractorTrySpawn = 0
if math.random() <= TRACTOR_SPAWN_CHANCE then
table.insert(tractors, {x = WINDOW_WIDTH,
y = math.random(0, WINDOW_HEIGHT - (sprites.tractor:getHeight() * TRACTOR_SPRITE_SCALE)),
s = math.random(TRACTOR_MOVE_SPEED * TRACTOR_MIN_MOVE_SPEED_FACTOR,
TRACTOR_MOVE_SPEED * TRACTOR_MAX_MOVE_SPEED_FACTOR)})
end
end
-- move existing tractors
for _,v in ipairs(tractors) do
v.x = v.x - v.s * delta
end
-- check for losing lives
for i,v in ipairs(tractors) do
if v.x <= MONKEY_X_COORD then
table.remove(tractors, i)
vars.lives = vars.lives - 1
if vars.lives == 0 then
enterState('gameover', {score = vars.score})
end
end
end
-- check for collisions
for ti,t in ipairs(tractors) do
for bi,b in ipairs(bananas) do
local tx = t.x + COLLISION_PADDING
local ty = t.y + COLLISION_PADDING
local tw = sprites.tractor:getWidth() * TRACTOR_SPRITE_SCALE - COLLISION_PADDING
local th = sprites.tractor:getHeight() * TRACTOR_SPRITE_SCALE - COLLISION_PADDING
local bx = b.x - ((sprites.banana:getWidth() * BANANA_SPRITE_SCALE) / 2) + COLLISION_PADDING
local by = b.y - ((sprites.banana:getHeight() * BANANA_SPRITE_SCALE) / 2) + COLLISION_PADDING
local bw = sprites.banana:getWidth() * BANANA_SPRITE_SCALE - COLLISION_PADDING
local bh = sprites.banana:getWidth() * BANANA_SPRITE_SCALE - COLLISION_PADDING
if tx < bx + bw and bx < tx + tw and ty < by + bh and by < ty + th then
table.remove(bananas, bi)
table.remove(tractors, ti)
vars.score = vars.score + 1
if vars.score % 100 == 0 and vars.lives < 5 then
vars.lives = vars.lives + 1
end
end
end
end
end
function GameState.draw()
-- draw the background
love.graphics.draw(sprites.grass, 0, 0)
-- draw the forest
love.graphics.draw(sprites.forest[vars.lives], 0, 0)
-- draw the monkey
love.graphics.draw(sprites.monkey, MONKEY_X_COORD, monkey.y, 0, MONKEY_SPRITE_SCALE)
-- draw the tractors
for _,v in ipairs(tractors) do
love.graphics.draw(sprites.tractor, v.x, v.y, 0, TRACTOR_SPRITE_SCALE)
end
-- draw the moving bananas
for _,v in ipairs(bananas) do
love.graphics.draw(sprites.banana, v.x, v.y, v.r, BANANA_SPRITE_SCALE, BANANA_SPRITE_SCALE,
sprites.banana:getWidth() / 2,
sprites.banana:getHeight() / 2)
end
-- draw the banana count in the top left
for i = 1, vars.bananaCount do
love.graphics.draw(sprites.banana, MONKEY_X_COORD + 10 +
((i - 1) * sprites.banana:getWidth() * BANANA_SPRITE_SCALE), 10, 0,
BANANA_SPRITE_SCALE) -- 10 pixel padding from top left of screen
end
-- draw the current score
love.graphics.printf(vars.score .. " POINTS",
MONKEY_X_COORD + 10, 10,
WINDOW_WIDTH - MONKEY_X_COORD - 20, 'right')
end
<file_sep>WINDOW_HEIGHT = 600
WINDOW_WIDTH = 800
MONKEY_X_COORD = 100
MONKEY_SPRITE_SCALE = 3
MONKEY_MOVE_SPEED = 400
MAX_BANANAS = 5
BANANA_REGEN_RATE = 0.9
BANANA_MAX_COOLDOWN = 0.3
BANANA_SPRITE_SCALE = 3
BANANA_MOVE_SPEED = 500
BANANA_ROTATE_SPEED = 2 * 2 * (22/7) -- 22/7 is close enough to pi for us
TRACTOR_SPAWN_TRY_RATE = 0.5
TRACTOR_SPAWN_CHANCE = 0.4
TRACTOR_MOVE_SPEED = 200
TRACTOR_MIN_MOVE_SPEED_FACTOR = 0.5
TRACTOR_MAX_MOVE_SPEED_FACTOR = 1.5
TRACTOR_SPRITE_SCALE = 1.5
COLLISION_PADDING = 7
FACTS = {
'Over 75% of deforestation in Indonesia is illegal.',
'Jess cries when orangutans die.',
'Nutella is made up of 20% Palm Oil.',
'Orangutans are intelligent; they are able to create and use tools.',
'300 football fields worth of forest is cleared every hour.',
} | f85f8f35c3fa9f68f9d10e7bf907948ff6c25447 | [
"Lua"
] | 4 | Lua | lachy-xe/forest-invaders | 660cb255ef26278552cefbde9e40a12157c44215 | 3f97bf06fd7f212cd5637da601898c6db14bc323 |
refs/heads/master | <file_sep>x, y = map(int, input().split())
x_list = [x]
y_list = [y]
while x > 1:
x = x//2
y = y*2
x_list.append(x)
y_list.append(y)
ans = 0
for i in range(len(x_list)):
if x_list[i]%2 != 0:
ans += y_list[i]
print(ans)
<file_sep>#C:Capacity, I:Items, v:value of items, s:size of items
#Caution!! c:current size of capacity, not C
def max_value(c, I, v, s):
if c <= min(s):
return 0
else:
value = 0
f = 0
for item in I:
if c >= s[item]:
f = max_value(c-s[item], I, v, s) + v[item]
value = max(f, value)
return value
def KnapDP(C, I, v, s):
f = [0 for i in range(C+1)]
for c in range(C+1):
for item in I:
if c + s[item] <= C and f[c+s[item]] < f[c] + v[item]:
f[c+s[item]] = f[c] + v[item]
print(f[c+s[item]])
return max(f)
print("C, I(4), v, s")
C = int(input())
I = []
for i in range(4):
I.append(int(input()))
v = []
for i in range(4):
v.append(int(input()))
s = []
for i in range(4):
s.append(int(input()))
print(KnapDP(C, I, v, s))
<file_sep>def HanoiCounter(n):
if n == 1:
return 1
if n > 1:
return 2*HanoiCounter(n-1)+1
n = int(input())
print(HanoiCounter(n))
<file_sep>def EnumeratePrime(x):
P = []
for i in range(2, x):
if isPrime(i):
P.append(i)
return P
def isPrime(p):
for q in range(p-1):
if p%q == 0:
return False
return True
<file_sep>//なんか動かない...
//隣接するエリアが何箇所あるか
/*
例えばN*M = 10*12のwが水たまりのところ
w........ww.
.www.....www
....ww...ww.
.........ww.
.........ww.
.........w..
..w......w..
.w.w.....ww.
w.w.w.....w.
.w.w......w.
..w.......w.
*/
#include <iostream>
using namespace std;
void isWaterArea(int x, int y){
field[x][y] = ".";
for (int dx = -1; dx <= 1; dx++){
for (int dy = -1; dy <= 1; dy++){
int nx = x+dx, ny = y+dy;
if (0 <= nx && nx < N && 0 <= ny && ny < M && field[nx][ny] == "w"){
isWaterArea(nx, ny);
}
}
}
return ;
}
void solve(){
int res = 0;
for (int i=0; i< N; i++){
for (int j=0; j<M; j++){
if (field[i][j] == "w"){
isWaterArea(i, j);
res++;
}
}
}
printf("%d\n", res);
}
int main(){
int N, M;
cin >> N >> M;
char field[N][M];
for (int i=0; i< N; i++){
cin >> field[i];
}
solve();
}
<file_sep>def Heapsize(array):
return len(array)
def heap1st(array):
return array[0]
def push(array, v):
array.append(v)
ShiftUpRecursive(array, len(array))
def ShiftUpRecursive(array, i):
if i == 1:
return None
elif array[i] <= array[i//2]:
return None
else:
array[i], array[i//2] = array[i//2], array[i]
ShiftUpRecursive(array, i//2)
def pop(array):
array[0] = array[-1]
del array[-1]
ShiftDownRecursive(array, 1)
def ShiftDownRecursive(array, i):
if 2*i > len(array):
return None
elif 2*i + 1 > len(array):
#なんかよくわからないので後で
<file_sep># algorithm
テスト勉強および競技プログラミングの勉強として各種アルゴリズムをここに書いて行こうと思ってます。
GitやGitHub連携の練習にも使おうと思ってます
<file_sep>def bfs(start):
C = [] #visited
queue = [start]
while len(queue) > 0:
v = queue.pop()
for w in neighbour[v]:
if w not in C:
C.append(w)
queue.append(w)
return C
#ほとんどdfsと同じなんだな
#早くデータ構造を実装して見ないと何もわかったことにならないことがわかった
<file_sep>#全ての男女がフリー
num = int(input())
men = ["" for i in range(num)]
wom = ["" for i in range(num)]
#男女のマッチングを実現させるためのデータ構造
rank = [(0, 0) for i in range(num)] #[man][woman][0]:man -> woman, [man][woman][1]:woman -> man
men_state = ["waiting" for i in range(num)]
wom_state = ["waiting" for i in range(num)]
#ここまで入力すべし
flag = True
married_pair = [() for i in range(num)]
#example: men = ["Tom", "Bob", "John"]
#マッチング
while flag:
crt1 = 0
for i in range(num): #choose a man
if men_state[i] == "waiting":
crt1 = i #store the man number
break
first = 0
crt2 = 0
for i in range(num): #choose the best woman for the man
if rank[crt1][i][0] >= first:
first = rank[crt1][i][0]
crt2 = i #store the woman number
if wom_state[crt2] == "waiting":
married_pair[crt2] = (crt1, crt2)
wom_state[crt2] = "married"
else: #compare which man fasinates the woman
enem, crt2 = wom_state[crt2]
love1 = rank[crt1][crt2][1]
love2 = rank[enem][crt2][1]
if love1 > love2:
married_pair[crt2] = (crt1, crt2)
men_state[crt1] = "married"
men_state[enem] = "waiting"
rank[crt1][crt2][0] = 0 # means the man(crt1) proposed the woman(crt2)
#本当か??????
flag = False
for i in range(num):
if man_state[i] != "married":
flag = True
break
for male, madm in married_pair:
print(men[male] + ", " + wom[madm], end = "")
<file_sep>def BacketSort(array):
min_ = min(array)
max_ = max(array)
S = [[] for i in range(max_ - min_ +1)]
for x in array:
S[x-1].append(x)
Y = []
for s in S:
Y = Y + s
return Y
lis = []
for i in range(10):
lis.append(int(input()))
print(BacketSort(lis))
<file_sep>'''
def EditDistDP(S, T):
f = [[float('inf') for i in range(len(S)+1)] for j in range(len(T)+1)]
f[0][0] = 0
for i in range(len(S)+1):
for j in range(len(T)+1):
if i < len(S)+1
f[i+1][j] = min(f[i+1][j], f[i][j]+1)
elif j < len(T)+1
f[i][j+1] = min(f[i][j+1], f[i][j]+1)
elif i < len(S)+1 and j < len(T)+1:
f[i+1][j+1] = min(f[i+1][j+1], f[i][j]+D(S[i], T[j]))
return f[len(S)][len(T)]
授業のコードをコピペしたらバグはいたので自分のコードでやることにした
'''
def D(s, t):
if s == t:
return 0
else:
return 1
def MyEditDist(S, T):
f = [[0 for j in range(len(T)+1)] for i in range(len(S)+1)]
for i in range(len(S)+1):
f[i][0] = i
for j in range(len(T)+1):
f[0][j] = j
for i in range(1, len(S)+1):
for j in range(1, len(T)+1):
f[i][j] = min(f[i][j-1]+1, f[i-1][j]+1, f[i-1][j-1]+D(S[i-1], T[j-1]))
return f[len(S)][len(T)]
return dp[n][m]
#S = input()
#T = input()
#print(MyEditDist(S, T))
<file_sep>x, p = map(int, input().split())
a = 0
b = x
while b-a > p:
m = int((a+b)/2)
if m**2 > x:
b = m
else:
a = m
print("a = " + str(a))
print("b = " + str(b))
<file_sep>def Merge(array1, array2):
if len(array1) == 0:
return array2
elif len(array2) == 0:
return array1
elif array1[0] < array2[0]:
return array1[0:1] + Merge(array1[1:], array2)
else:
return array2[0:1] + Merge(array1, array2[1:])
def MergeSort(array):
if len(array) == 1:
return array
else:
x = len(array)
left_ = MergeSort(array[:x//2])
right = MergeSort(array[x//2:])
return Merge(left_, right)
<file_sep>#Qiitaを参考
#木のrootを-1として表現
class unionfind():
def __init__(self, size):
self.table = [-1 for i in range(size)] #それぞれ高さが1の独立な木
def find(self, x):
while self.table[x] >= 0:
x = self.table[x] #rootのindexを返すようにする
return x
#unionがよくわからんのでもうちょっと考える必要あり
def union(self, x, y):
rt1 = self.find(x)
rt2 = self.find(y)
if rt1 != rt2:
if self.table[rt1] != self.table[rt2]: #グラフの高さが異なるなら
if self.table[rt1] < self.table[rt2]: #1の方が根が浅いなら
self.table[rt2] = rt1
else:
self.table[rt1] = rt2
else:
self.table[rt1] += -1 #1の方の高さを減らす?
self.table[rt2] = rt1 #2の方の根を1にする
return
<file_sep>def eratosthenes(n):
P = []
q = [True for i in range(n)]
for i in range(1, n):
if q[i]:
prime = i+1
P.append(prime)
for j in range(i, n+1):
if j%prime == 0:
q[j-1] = False
return P
<file_sep>def dfs(start):
stack = [start]
C = [] #visited
while len(stack) > 0:
v = stack.pop()
for w in neighbour[v]:
if w not in visited:
C.append(w)
stack.append(w)
return C
def neighbour():
hoge
#隣接行列をneighbourとして実装しないといけない
#頂点iとjが隣接しているかどうかを01で表現
#後で実装しよう
<file_sep>def recursiveDfs(v, C):
C.append(v)
for w in neighbour[v]:
if w not in C:
C = recursiveDfs(w, C)
return C
<file_sep>x, y = map(int, input().split())
if x <= y:
x, y = y, x
while y > 0:
x, y = y, x%y
print(x)
<file_sep>def EuclidRecursive(x, y):
if y == 0:
return x
if y > 0:
return EuclidRecursive(y, x%y)
<file_sep>#行列サイズは2のべき乗
def Strassen(X, Y):
if len(X) == 1:
return X[0][0]*Y[0][0]
half = len(X)/2
#行列を分解
A = X[half:][half:]
B = X[:half][half:]
C = X[half:][:half]
D = X[:half][:half]
E = Y[half:][half:]
F = Y[:half][half:]
G = Y[half:][:half]
H = Y[:half][:half]
#わからんティウス
<file_sep>import math
def Multiply(x, y):
x_digit = int(math.log10(x) + 1)
y_digit = int(math.log10(y) + 1)
if x_digit == 1 and y_digit == 1:
return x*y
else:
n = x_digit
if y_digit >= x_digit: n = y_digit
B = math.ceil(10**(n/2) -1)
u = Multiply(math.ceil(x/B) -1, math.ceil(y/B) -1)
v = Multiply(math.ceil(x/B) -1 + x%B, math.ceil(y/B -1) + y%B)
w = Multiply(x%B, y%B)
return u*(B**n) + (v-u-w)*B + w
#x, y = map(int, input().split())
#print(Multiply(x, y))
#なんかバグがある
#18 18とかでやるとエラーが
#100000とかだとValue domain errorが
<file_sep>#Vは頂点集合, lは各距離, sはstartノードの番号
def Dijkstra(V, l, s):
d = [float('inf') for i in range(len(V))]
d[s] = 0
C = [] #visited
while len(C) != len(V):
min_ = float('inf')
v = 0
for i in range(V):
if d[i] < min_ and i not in C:
v = i
min_ = d[i]
C.append(v)
for w in V:
if d[w] > d[v] + l[v][w]:
d[w] = d[v] + l[v][w]
return d
<file_sep>def Modulo(x, y):
if x == 0:
return (0, 0)
q, r = Modulo(x//2, y)
q = 2*q
r = 2*r
if x%2 == 1: r += 1
if r >= y:
r = r-y
q += 1
return (q, r)
x, y = map(int, input().split())
print(Modulo(x, y))
<file_sep>def CircleMethod(T):
n = len(T)
for i in range(1, n+1):
c[i-1] = t[i]
for day in range(n-1):
# 後で書く
<file_sep>import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
G.add_node(1, position=(0, 1))
G.add_node(2, position=(1, 2))
G.add_node(3, position=(3, 2))
G.add_node(4, position=(1, 0))
G.add_node(5, position=(3, 0))
G.add_node(6, position=(4, 1))
G.add_edge(1, 2, capacity=5)
G.add_edge(1, 4, capacity=20)
G.add_edge(2, 3, capacity=15)
G.add_edge(2, 5, capacity=3)
G.add_edge(3, 5, capacity=10)
G.add_edge(3, 6, capacity=15)
G.add_edge(4, 2, capacity=7)
G.add_edge(4, 5, capacity=13)
G.add_edge(5, 6, capacity=10)
def draw_graph_with_capacity(G, node_position, title = "A network"):
plt.title(title)
nx.draw_networkx(G, pos = node_position, node_color = "w")
capacity = nx.get_edge_attributes(G, 'capacity')
edge_labels = nx.draw_networkx_edge_labels(G, pos = node_position, edge_labels=capacity, label_pos = 0.3)
return
node_position = nx.get_node_attributes(G, 'position')
draw_graph_with_capacity(G, node_position, 'An instance of the maximum flow problem')
| 631ea166843fc0b5470da66395a506f4a59eadd3 | [
"Markdown",
"Python",
"C++"
] | 25 | Python | ymaquarium/algorithm | bba7ce003e7be9d49d1c3dfee1d6c3d314e71d8c | 678f0d71eaf3ebbc9cd9febc5a9ffaccaf767968 |
refs/heads/master | <repo_name>rw251/pvr<file_sep>/src/htsp/index.js
const fs = require('fs');
const net = require('net');
const crypto = require('crypto');
var HOST = 'media';
var PORT = 9982;
// MESSAGES FROM SERVER
/*
"{"method":"subscriptionGrace","subscriptionId":0,"graceTimeout":5}"
"{"method":"subscriptionStatus","subscriptionId":0}"
"{"method":"signalStatus","subscriptionId":0,"feStatus":"GOOD","feBER":0,"feUNC":0}"
"{"method":"signalStatus","subscriptionId":0,"feStatus":"GOOD","feBER":0,"feUNC":0}"
"{"meta":"...","streams":[{"index":1,"type":"MPEG2VIDEO","width":704,"height":576,"duration":40000,"aspect_num":16,"aspect_den":9},{"index":2,"type":"MPEG2AUDIO","language":"eng","audio_type":0,"audio_version":2,"channels":2,"rate":3},{"index":4,"type":"DVBSUB","language":"eng","composition_id":1,"ancillary_id":1}],"sourceinfo":{"adapter_uuid":"e5654b738c9affaed65fcb330e4d1f26","mux_uuid":"25de5e59f340374f20c848bc6ce499f3","network_uuid":"c639ab59f8c8c9e8511c06440908d5bd","adapter":"Sony CXD2880 #0 : DVB-T #0","mux":"706MHz","network":"DVB-T Network","network_type":"DVB-T","service":"BBC ONE N West"},"method":"subscriptionStart","subscriptionId":0}"
"{"method":"queueStatus","subscriptionId":0,"packets":2,"bytes":768,"delay":0,"Bdrops":0,"Pdrops":0,"Idrops":0}"
"{"method":"muxpkt","subscriptionId":0,"stream":2,"com":0,"pts":0,"dts":0,"duration":24000,"payload":"..."}"
"{"method":"muxpkt","subscriptionId":0,"stream":2,"com":0,"pts":24000,"dts":24000,"duration":24000,"payload":"..."}"
"{"method":"muxpkt","subscriptionId":0,"frametype":73,"stream":1,"com":0,"pts":1297144,"dts":1177144,"duration":40000,"payload":"..."}"
*/
const HMF_MAP = 1;
const HMF_S64 = 2;
const HMF_STR = 3;
const HMF_BIN = 4;
const HMF_LIST = 5;
//JS Doesn't provide chr/ord.. wrapper functions for readaibility/consistency with the python example
function chr(i) {
return String.fromCharCode(i);
}
function ord(c) {
c = '' + c;
return c.charCodeAt(0);
}
function bin2int(d) {
return (ord(d[0]) << 24) + (ord(d[1]) << 16)+ (ord(d[2]) << 8) + ord(d[3]);
}
class hmf_bin {}
class HTSPMessage {
hmf_type(f) {
if (Array.isArray(f)) return HMF_MAP;
else if (f instanceof hmf_bin) return HMF_BIN;
else if (typeof f == 'object') return HMF_LIST;
else if (typeof f == 'string') return HMF_STR;
else if (typeof f == 'number') return HMF_S64;
}
_binary_count(f) {
var ret = 0;
if (typeof f == 'string' || f instanceof hmf_bin || f instanceof Buffer) {
ret += f.length;
}
else if (typeof(f) == 'number') {
while (f) {
ret += 1;
f = f >> 8;
}
}
else if (typeof(f) == 'object' || Array.isArray(f)) {
ret += this.binary_count(f);
}
else throw new Error('invalid data type');
return ret;
}
binary_count(msg) {
var ret = 0;
var list = Array.isArray(msg)
for (var f in msg) {
ret += 6;
if (!list) {
//for objects add on the length of the key
ret += f.length;
//Python treats for ... in differently for objects and lists. for..in works like JS for..of for lists
//but the same for objects! So for js ignore this line
//f = msg[f]
}
ret += this._binary_count(msg[f]);
}
return ret;
}
int2bin(i) {
return chr(i >> 24 & 0xFF) + chr(i >> 16 & 0xFF) + chr(i >> 8 & 0xFF) + chr(i & 0xFF);
}
binary_write(msg) {
var ret = '';
var list = Array.isArray(msg);
for (var f in msg) {
var na = '';
if (!list) {
na = f;
//Python treats for ... in differently for objects and lists. for..in works like JS for..of for lists
//but the same for objects! ignore this line
//f = msg[f]
}
//set f to value rather than key
f = msg[f];
ret += chr(this.hmf_type(f));
ret += chr(na.length & 0xFF);
var l = this._binary_count(f);
ret += this.int2bin(l);
ret += na;
if (f instanceof Buffer) {
ret += f;
}
else if (f instanceof hmf_bin || typeof f == 'string') ret += f;
else if (typeof(f) == 'object' || Array.isArray(f)) ret += this.binary_write(f);
else if (typeof(f) == 'number') {
while (f) {
ret += chr(f & 0xFF);
f = f >> 8;
}
}
else throw new Error('invalid type');
}
return ret;
}
serialize(msg) {
var cnt = this.binary_count(msg);
return Buffer.from(this.int2bin(cnt) + this.binary_write(msg), 'binary');
}
deserialize0(data, type = HMF_MAP) {
var isList = false;
var msg = {};
if (type == HMF_LIST) {
isList = true;
msg = [];
}
while (data.length > 5) {
//data type
var typ = ord(data[0]);
//length of the name
var nlen = ord(data[1]);
//length of the data for name/key in nlen
var dlen = bin2int(data.slice(2,6));
data = data.slice(6);
var name = data.slice(0, nlen);
data = data.slice(nlen);
var item = null;
if (typ == HMF_STR) {
item = data.slice(0, dlen).toString();
}
else if (typ == HMF_BIN) {
//not sure why there's a dummy wrapper for this in the python example..
// item = new Buffer(data.slice(0, dlen), 'binary');
item = data.slice(0, dlen);
}
else if (typ == HMF_S64) {
item = 0;
var i = dlen-1;
while (i >= 0) {
item = (item << 8) | ord(data[i]);
i = i -1;
}
}
else if (typ == HMF_LIST || typ == HMF_MAP) {
item = this.deserialize0(data.slice(0, dlen), typ);
}
if (isList) msg.push(item);
else msg[name] = item;
data = data.slice(dlen);
}
return msg;
}
}
class HTSPClient {
constructor(host, port, onConnect) {
this.sock = new net.Socket();
this.sock.setEncoding('binary');
this.videoSock = new net.Socket();
this.videoSock.setEncoding('binary');
var self = this;
this.sock.connect(port, host, function() {
onConnect(self);
});
this.videoSock.connect(port, host, () => {
console.log('video sock up');
});
this.onData = function(x) {
console.log('this.onData: ' + x);
};
this.onVideoData = function(x) {
console.log('this.onVideoData: ' + x);
};
this.sock.on('data', function(data) {
//var msg = new HTSPMessage().deserialize0(data.slice(4));
self.onData(data);
});
this.sock.on('error', function(err) {
console.log('ERRROR!!!');
console.log(err);
});
this.sock.on('close', function(had_error) {
console.log('closed - error = '+had_error)
});
this.sock.on('end', function() {
console.log('sock end');
})
this.videoSock.on('data', function(data) {
//var msg = new HTSPMessage().deserialize0(data.slice(4));
self.onVideoData(data);
});
this.videoSock.on('error', function(err) {
console.log('videoSock ERRROR!!!');
console.log(err);
});
this.videoSock.on('close', function(had_error) {
console.log('videoSock closed - error = '+had_error)
});
this.videoSock.on('end', function() {
console.log('videoSock end');
})
}
send(func, args, callback, isVideo, debug) {
if (!args) args = {};
args['method'] = func;
if (debug) {
console.log(args);
}
var s = new HTSPMessage().serialize(args);
this[isVideo ? 'videoSock' : 'sock'].write(s, 'binary', callback);
}
onServerVideoData(data) {
if(!this.resp) {
this.bytesExpected = bin2int(data.slice(0,4));
this.resp = data.slice(4);
} else {
this.resp += data;
}
if(this.resp.length >= this.bytesExpected) {
const firstMessage = this.resp.slice(0, this.bytesExpected);
const msg = new HTSPMessage().deserialize0(firstMessage);
const secondMessage = this.resp.slice(this.bytesExpected);
this.resp = null;
if(secondMessage.length > 0) this.onServerVideoData(secondMessage);
}
}
long(func, args, callback, isVideo) {
args.htspversion = 27;
args.clientname = 'node-htsp';
let resp;
let bytesExpected = 0;
this[isVideo ? 'onVideoData' : 'onData'] = function(data) {
if(!resp) {
bytesExpected = bin2int(data.slice(0,4));
resp = data.slice(4);
} else {
resp += data;
}
if(resp.length === bytesExpected) {
const msg = new HTSPMessage().deserialize0(resp);
this.onVideoData = this.onServerVideoData;
callback(msg);
}
};
this.send(func, args, null, isVideo);
}
hello(callback) {
this.long('hello', {}, callback);
}
videoHello(callback) {
this.long('hello', {}, callback, true);
}
getDiskSpace(callback) {
this.long('getDiskSpace', {}, (msg) => {
const {error, freediskspace = 0, totaldiskspace = 0} = new HTSPMessage().deserialize0(data);
callback({freediskspace ,totaldiskspace});
});
}
/**
* @returns {Object} time - UNIX time / gmtoffset - minutes east of gmt
*/
getSystemTime(callback) {
this.long('getSysTime', {}, (msg) => {
const {error, time, gmtoffset} = new HTSPMessage().deserialize0(data);
callback({time, gmtoffset});
});
}
/**
* @returns {Object} time - UNIX time / gmtoffset - minutes east of gmt
*/
getEvents(callback) {
this.long('getEvents', {}, callback);
}
/**
* @returns {Object} time - UNIX time / gmtoffset - minutes east of gmt
*/
getChannel(channelId, callback) {
this.long('getChannel' , { channelId }, callback);
}
getEpgObject(id, callback) {
this.long('getEpgObject', { id }, callback);
}
epgQuery(query, callback) {
this.long('epgQuery', { query, full: 1 }, callback);
}
getDvrConfigs(callback) {
this.long('getDvrConfigs', {}, callback);
}
subscribe(channelId, callback) {
this.subId = Math.random();
this.long('subscribe', { channelId, subscriptionId: this.subId }, callback, true);
}
end() {
this.sock.end();
}
}
new HTSPClient('192.168.1.5', 9982, (client) => {
client.subscribe(229602236,(x) => {
//cbbc?
console.log(x);
//client.end();
});
// client.subscribe(2093271676,(x) => {
// //cbbc?
// console.log(x);
// //client.end();
// });
// client.epgQuery('bbc news', (x) => {
// console.log(x);
// });
});
| 15d496be5e6b8b70ff4f672f2c6518c817b2e68b | [
"JavaScript"
] | 1 | JavaScript | rw251/pvr | 8c4a93a0d041422a0d18612caaacab41f9c30076 | b1260a49fa25b0925e33933bfa667b1d184341b1 |
refs/heads/master | <repo_name>donsale/klotski<file_sep>/Makefile
IDIR = headers
CC = gcc
CFLAGS=-I $(IDIR) -Wall
VPATH = source;headers
DEPS = position.h queue.h
OBJ = main.o position.o queue.o
%.o: %.c $(DEPS)
$(CC) -c -o $@ $< $(CFLAGS)
klotski: $(OBJ)
$(CC) -o $@ $^ $(CFLAGS)
clean:
del klotski* $(OBJ)
<file_sep>/README.md
# klotski
Klotski solver in C
<file_sep>/headers/queue.h
#ifndef QUEUE_H
#define QUEUE_H
#include "position.h"
typedef struct queue
{
POSITION *arr;
int front;
int rear;
} QUEUE;
int is_full(struct queue *q);
int is_empty(struct queue *q);
int add(struct queue *q, POSITION value);
int get(struct queue *q, POSITION *value);
#endif // QUEUE_H
<file_sep>/headers/position.h
#ifndef POSITION_H
#define POSITION_H
#define BLOCKS_IN_PIECE 4
#define PIECES_IN_POSITION 10
#define MAX_POSSIBLE_NEIGHBOURS 10
#define MAX 65536
#define BOARD_X 5
#define BOARD_Y 4
#include <stdio.h>
#include <stdlib.h>
typedef struct block
{
signed char x, y;
} BLOCK;
typedef struct piece
{
unsigned char id; //unique id (each piece has its own id)
unsigned char mat_id; //size id (pieces of the same size have the same mat_id)
unsigned char n; //number of blocks in piece
BLOCK blocks[BLOCKS_IN_PIECE];
} PIECE;
typedef struct position
{
unsigned char mat[BOARD_X][BOARD_Y];
PIECE pieces[PIECES_IN_POSITION];
struct position *parent;
} POSITION;
int is_good(POSITION *pos);
void print_position(POSITION *pos);
int is_visited(POSITION *pos);
void add_to_visited(POSITION *pos);
POSITION * all_neighbours(POSITION *p, int *n);
BLOCK right (BLOCK b);
BLOCK left (BLOCK b);
BLOCK down (BLOCK b);
BLOCK up (BLOCK b);
POSITION move_piece(POSITION *pos, PIECE *p, BLOCK (*d) (BLOCK));
void matrix_from_pieces(POSITION *pos);
int can_move(POSITION *pos, PIECE *piece, BLOCK (*d) (BLOCK));
int is_block_in_range(BLOCK b);
int is_block_in_any_piece(BLOCK b, POSITION *p);
int is_block_in_piece(BLOCK b, PIECE *p);
void print_solution(POSITION *p);
#endif // POSITION_H
<file_sep>/source/queue.c
#include "queue.h"
int is_full(struct queue *q)
{
return q->rear == MAX;
}
int is_empty(struct queue *q)
{
return q->front == -1 || q->front == q->rear;
}
int add(struct queue *q, POSITION value)
{
if (is_full(q))
return 0;
if (q->front == -1)
q->front = 0;
q->arr[q->rear++] = value;
return 1;
}
int get(struct queue *q, POSITION *value)
{
if (is_empty(q))
return 0;
*value = q->arr[q->front++];
return 1;
}
<file_sep>/source/main.c
#include "position.h"
#include "queue.h"
void bfs(POSITION root, int max_depth);
int main()
{
POSITION root =
{
{ { 2, 4, 4, 2},
{ 2, 4, 4, 2},
{ 2, 3, 3, 2},
{ 2, 1, 1, 2},
{ 1, 0, 0, 1}
},
{ {1, 2, 2, {{0, 0}, {1, 0}}},
{2, 4, 4, {{0, 1}, {0, 2}, {1, 1}, {1, 2}}},
{3, 2, 2, {{0, 3}, {1, 3}}},
{4, 2, 2, {{2, 0}, {3, 0}}},
{5, 3, 2, {{2, 1}, {2, 2}}},
{6, 2, 2, {{2, 3}, {3, 3}}},
{7, 1, 1, {{3, 1}}},
{8, 1, 1, {{3, 2}}},
{9, 1, 1, {{4, 0}}},
{10, 1, 1, {{4, 3}}}
}, NULL
};
bfs(root, 200);
return 0;
}
void bfs(POSITION root, int max_depth)
{
QUEUE q = { NULL, -1, 0 };
q.arr = malloc(MAX * sizeof(POSITION));
POSITION u;
add(&q, root);
add_to_visited(&root);
int n, real_n;
int current_depth = 0;
int elements_till_next_level = 1;
int elements_for_next_level = 0;
while(get(&q, &u))
{
if(is_good(&u))
{
printf("Success!!\n");
print_solution(&u);
free(q.arr);
exit(0);
}
POSITION *arr = all_neighbours(&u, &n);
real_n = 0;
for(int i = 0; i < n; i++)
{
if(!is_visited(&arr[i]))
{
arr[i].parent = &q.arr[q.front - 1];
add(&q, arr[i]);
add_to_visited(&arr[i]);
real_n++;
}
}
free(arr);
elements_for_next_level += real_n;
if(--elements_till_next_level == 0)
{
if(++current_depth > max_depth)
return;
printf("Current level: %d\n", current_depth);
printf("New positions for level: %d\n", elements_for_next_level);
elements_till_next_level = elements_for_next_level;
elements_for_next_level = 0;
}
}
}
<file_sep>/source/position.c
#include "position.h"
int is_block_in_piece(BLOCK b, PIECE *p)
{
for(int i = 0; i < p->n; i++)
{
BLOCK tmp = p->blocks[i];
if(tmp.x == b.x && tmp.y == b.y)
return 1;
}
return 0;
}
int is_block_in_any_piece(BLOCK b, POSITION *p)
{
for(int i = 0; i < PIECES_IN_POSITION; i++)
{
if(is_block_in_piece(b, &p->pieces[i]))
return 1;
}
return 0;
}
int is_block_in_range(BLOCK b)
{
if(b.x < 0 || b.y < 0 || b.x > BOARD_X - 1 || b.y > BOARD_Y - 1)
return 0;
return 1;
}
int can_move(POSITION *pos, PIECE *piece, BLOCK (*d) (BLOCK))
{
for(int i = 0; i < piece->n; i++)
{
BLOCK b = piece->blocks[i];
BLOCK next_block = d(b);
if(!is_block_in_range(next_block) || (is_block_in_any_piece(next_block, pos) && !is_block_in_piece(next_block, piece)))
return 0;
}
return 1;
}
void matrix_from_pieces(POSITION *pos)
{
int mat[BOARD_X][BOARD_Y] = {};
for(int i = 0; i < PIECES_IN_POSITION; i++)
{
PIECE *p = &pos->pieces[i];
for(int j = 0; j < p->n; j++)
{
BLOCK *b = &p->blocks[j];
mat[b->x][b->y] = p->mat_id;
}
}
for(int i = 0; i < BOARD_X; i++)
{
for(int j = 0; j < BOARD_Y; j++)
pos->mat[i][j] = mat[i][j];
}
}
POSITION move_piece(POSITION *pos, PIECE *p, BLOCK (*d) (BLOCK))
{
POSITION new_pos = *pos;
for(int i = 0; i < PIECES_IN_POSITION; i++)
{
PIECE *tmp = &new_pos.pieces[i];
if(tmp->id == p->id)
{
for(int j = 0; j < tmp->n; j++)
{
BLOCK b = d(tmp->blocks[j]);
tmp->blocks[j] = b;
}
break;
}
}
matrix_from_pieces(&new_pos);
return new_pos;
}
BLOCK up (BLOCK b)
{
BLOCK tmp = {b.x - 1, b. y};
return tmp;
}
BLOCK down (BLOCK b)
{
BLOCK tmp = {b.x + 1, b. y};
return tmp;
}
BLOCK left (BLOCK b)
{
BLOCK tmp = {b.x, b.y - 1};
return tmp;
}
BLOCK right (BLOCK b)
{
BLOCK tmp = {b.x, b. y + 1};
return tmp;
}
POSITION * all_neighbours(POSITION *p, int *n)
{
POSITION * arr = malloc(MAX_POSSIBLE_NEIGHBOURS * sizeof(POSITION));
*n = 0;
for(int i = 0; i < PIECES_IN_POSITION; i++)
{
PIECE *piece = &p->pieces[i];
if (can_move(p, piece, up))
{
arr[*n] = move_piece(p, piece, up);
*n = *n + 1;
}
if (can_move(p, piece, down))
{
arr[*n] = move_piece(p, piece, down);
*n = *n + 1;
}
if (can_move(p, piece, left))
{
arr[*n] = move_piece(p, piece, left);
*n = *n + 1;
}
if (can_move(p, piece, right))
{
arr[*n] = move_piece(p, piece, right);
*n = *n + 1;
}
}
return arr;
}
unsigned char visited[MAX][BOARD_X][BOARD_Y];
int n_visited = 0;
void add_to_visited(POSITION *pos)
{
for(int i = 0; i < BOARD_X; i++)
for(int j = 0; j < BOARD_Y; j++)
visited[n_visited][i][j] = pos->mat[i][j];
n_visited++;
}
int is_visited(POSITION *pos)
{
int equal = 1;
for(int i = 0; i < n_visited; i++)
{
equal = 1;
for(int j = 0; j < BOARD_X && equal; j++)
for(int k = 0; k < BOARD_Y && equal; k++)
if(visited[i][j][k] != pos->mat[j][k])
equal = 0;
if(equal)
return 1;
}
return 0;
}
void print_position(POSITION *pos)
{
for(int i = 0; i < BOARD_X; i++)
{
for(int j = 0; j < BOARD_Y; j++)
printf("%d ", pos->mat[i][j]);
printf("\n");
}
printf("\n");
}
int is_good(POSITION *pos)
{
BLOCK b1 = {3, 1};
BLOCK b2 = {4, 2};
if(is_block_in_piece(b1, &pos->pieces[1]) && is_block_in_piece(b2, &pos->pieces[1]))
return 1;
return 0;
}
void print_solution(POSITION *p)
{
while(p->parent)
{
print_position(p);
p = p->parent;
}
print_position(p);
}
| b45969415a59a760b0b5afbedbabf0128338a05c | [
"Markdown",
"C",
"Makefile"
] | 7 | Makefile | donsale/klotski | ab61cbf40e8dfd5acbe705f06bc426a1ab5ed0ac | 96a390de67575371e414e82cb99e572367e0bfbf |
refs/heads/master | <repo_name>jerald-devOfficial/NoteApp<file_sep>/client/src/components/Header.jsx
import React from "react";
import GitHubIcon from "@material-ui/icons/GitHub";
import InfoIcon from "@material-ui/icons/Info";
function Header() {
return (
<header>
<a href="/">
<h1>Notes</h1>
</a>
<ul className="nav">
<li>
<a href="https://github.com/jerald-devOfficial/NoteApp">
<GitHubIcon
fontSize="large"
style={{ color: "#fff" }}
href="https://github.com/jerald-devOfficial/NoteApp"
/>
</a>
</li>
<li>
<a href="/about">
<InfoIcon fontSize="large" style={{ color: "#fff" }} />
</a>
</li>
</ul>
</header>
);
}
export default Header;
<file_sep>/client/src/components/About.jsx
import React from "react";
function About() {
return (
<div className="about-container">
<h2 className="about">
<b>About Notes App</b>
</h2>
<p className="about">
"Notes" is a note-taking CRUD application built with with React.js,
Node.js, and Express.
</p>
<p className="about">
This application allows you to add and delete notes. Based on Google's
Keeper app.
</p>
</div>
);
}
export default About;
<file_sep>/client/src/components/App.jsx
import React, { useState } from "react";
import { BrowserRouter, Route } from "react-router-dom";
import Header from "./Header";
import Footer from "./Footer";
import NotesList from "./NotesList";
import About from "./About";
function App() {
const [notes, setNotes] = useState([]);
function addNote(newNote) {
setNotes((prevNotes) => {
return [...prevNotes, newNote];
});
}
return (
<BrowserRouter>
<div>
<Header />
<Route exact path="/about" component={About} />
<Route exact path="/" component={NotesList} />
<Footer />
</div>
</BrowserRouter>
);
}
export default App;
| 66645f219a5e4fa0e6f5ad9a081a668faafed3d4 | [
"JavaScript"
] | 3 | JavaScript | jerald-devOfficial/NoteApp | 953e71738023186d8a534970c7199cfe0806dcc4 | fee13997fb034ef382f353ffc5199a0ffd024046 |
refs/heads/master | <repo_name>fabriciosmatos/sensebit-app<file_sep>/src/pages/sensor-detail/sensor-detail.html
<ion-header>
<ion-navbar>
<ion-title>{{ sensor.tipoNome }}</ion-title>
<ion-buttons end>
<button ion-button icon-only (click)="resetSensor()">
<ion-icon name="refresh"></ion-icon>
</button>
</ion-buttons>
</ion-navbar>
</ion-header>
<ion-content>
<!-- <div class="sensor-profile" text-center #profilePic [style.background-image]="'url(' + sensor.imagem + ')'">
</div> -->
<ion-card>
<ion-card-header>
<ion-icon name="speedometer" item-start large></ion-icon>
<b>Log do Sensor {{sensor.nome}}</b>
</ion-card-header>
<ion-list >
<ion-item>
<b item-start>
Data / Hora
</b>
<b item-end>
{{sensor.unidade}}
</b>
</ion-item>
<ion-item *ngFor="let logSensor of currentLogSensor">
<div item-start>
{{logSensor.data | date: 'dd/MM/yyyy hh:mm:ss'}}
</div>
<div item-end>
{{logSensor.valor | number:'1.3-3'}}
</div>
</ion-item>
</ion-list>
</ion-card>
</ion-content><file_sep>/src/providers/sensores/sensores.ts
import { Injectable } from '@angular/core';
import { Api } from '../api/api';
import { StorageService } from './../storage/storageService';
import { Sensor } from '../../models/sensor';
import { LogSensor } from './../../models/logSensor';
@Injectable()
export class Sensores {
usuarioLogado: any;
sensorList: Sensor[] = new Array<Sensor>();
logSensorList: LogSensor[] = new Array<LogSensor>();
constructor(public api: Api
, public storage: StorageService) {
}
query(params?: any) {
if (!params) {
return this.sensorList;
}
return this.sensorList.filter((sensor) => {
for (let key in params) {
let field = sensor[key];
if (typeof field == 'string' && field.toLowerCase().indexOf(params[key].toLowerCase()) >= 0) {
return sensor;
} else if (field == params[key]) {
return sensor;
}
}
return null;
});
}
getAllSensores(funcao: any){
this.storage.get('usuario').then(user => {
let seq = this.api.get('sensores',
{filter: '{"where":{"usuarioId":'+user.id+'}}'}).share();
seq.subscribe((res: any) => {
let novoSensorList: Sensor[] = new Array<Sensor>();
res.forEach(sensor => {
sensor = Sensor.preencheAtributos(sensor);
novoSensorList.push(sensor);
});
this.sensorList = novoSensorList;
funcao(this.sensorList);
}, err => {
console.error('ERROR', err);
});
});
}
add(sensor: Sensor) {
sensor.status = 0;
let obj: {data: Sensor} = {data: sensor};
alert(JSON.stringify(obj));
return this.api.post('sensores/registerSensor', obj);
}
delete(sensor: Sensor) {
}
getLastLogs(sensor: Sensor, funcao: any){
let novoLogSensorList: LogSensor[] = new Array<LogSensor>(); ;
let seq = this.api.get('logsensores/getlastlogs', {guid: sensor.guid}).share();
this.sensorList.length = 0;
seq.subscribe((res: any)=>{
res['data'].forEach(logSensor => {
novoLogSensorList.push(logSensor);
});
this.logSensorList = novoLogSensorList;
funcao(this.logSensorList);
});
}
resetSensor(sensor: Sensor){
//alert(JSON.stringify(sensor));
return this.api.post('sensores/registerSensor', sensor);
}
buscaPorId(id: number, funcao: any){
let seq = this.api.get('sensores',
{filter: '{"where":{"id":'+id+'}}'}).share();
seq.subscribe((res: any) => {
funcao(res);
}, err => {
console.error('ERROR_REGRA', err);
});
}
}
<file_sep>/src/pages/regra-create/regra-create.ts
import { FormGroup} from '@angular/forms';
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ViewController } from 'ionic-angular';
import { Sensor } from './../../models/sensor';
import { Regra } from './../../models/regra';
import { Sensores } from './../../providers/sensores/sensores';
import { Regras } from './../../providers/regras/regras';
@IonicPage()
@Component({
selector: 'page-regra-create',
templateUrl: 'regra-create.html',
})
export class RegraCreatePage {
isReadyToSave: boolean;
form: FormGroup;
currentSensor: Sensor[];
regra: Regra = new Regra();
constructor(public navCtrl: NavController
, public navParams: NavParams
, public viewCtrl: ViewController
, public sensores: Sensores
, public regras: Regras) {
this.sensores.getAllSensores((resp) => {
this.currentSensor = resp;
});
}
ionViewDidLoad() {
}
inverteBoolean(variavel: string){
if(variavel = ''){
}
}
/**
* O usuário cancelou, então descartamos sem enviar os dados de volta.
*/
cancel() {
this.viewCtrl.dismiss();
}
/**
* O usuário está pronto e quer criar o item, então devolva-o ao apresentador.
*/
done() {
this.navCtrl.pop();
}
add() {
this.regra.sensorId = this.regra.sensor.id;
this.regras.add(this.regra).subscribe((resp) => {
this.viewCtrl.dismiss(this.regra);
}, (err) => {
console.log(err);
});
}
}
<file_sep>/src/models/sensor.ts
import { Wifi } from './wifi';
export class Sensor {
tipo: number;
tipoNome: string;
nome: string;
guid: string;
status: number;
usuarioId: number;
id: number;
sensorId: number;
imagem: string;
unidade: string;
wifis: Wifi[] = [new Wifi('','','')];
constructor(){}
static preencheAtributos(sensor: Sensor){
if(sensor.tipo == 1){
sensor.imagem = 'assets/img/sensor-energia.jpg';
sensor.tipoNome = 'Sensor de Energia';
sensor.unidade = 'Wh';
}else if(sensor.tipo == 2){
sensor.imagem = 'assets/img/sensor-temperatura.jpg';
sensor.tipoNome = 'Sensor de Temperatura';
sensor.unidade = '°C';
}else if(sensor.tipo == 3){
sensor.imagem = 'assets/img/sensor-pressao.jpg';
sensor.tipoNome = 'Sensor de Pressão';
sensor.unidade = 'hPa';
}else if(sensor.tipo == 4){
sensor.imagem = 'assets/img/sensor-movimento.jpg';
sensor.tipoNome = 'Sensor de Movimento';
sensor.unidade = '';
}
return sensor;
}
}<file_sep>/src/mocks/providers/sensores.ts
import { Injectable } from '@angular/core';
import { Sensor } from '../../models/sensor';
@Injectable()
export class Sensores {
sensores: Sensor[] = [];
defaultSensor: any = {
"sensorId": "1",
"tipo": "Sensor de Energia",
"guid": "111",
"status": "1",
"usuarioId":"1",
"imagem":"assets/img/sensor-energia.jpg"
};
constructor() {
let sensores = [
{
"sensorId": "1",
"tipo": "Sensor de Energia",
"guid": "111",
"status": "1",
"usuarioId":"1",
"imagem":"assets/img/sensor-energia.jpg"
},
{
"sensorId": "1",
"tipo": "Sensor de movimento",
"guid": "222",
"status": "1",
"usuarioId":"1",
"imagem":"assets/img/sensor-movimento.jpg"
},
{
"sensorId": "1",
"tipo": "Sensor de Temperatura",
"guid": "333",
"status": "1",
"usuarioId":"1",
"imagem":"assets/img/sensor-temperatura.jpg"
}
];
for (let sensor of sensores) {
// this.sensores.push(new Sensor(sensor));
}
}
query(params?: any) {
if (!params) {
return this.sensores;
}
return this.sensores.filter((sensor) => {
for (let key in params) {
let field = sensor[key];
if (typeof field == 'string' && field.toLowerCase().indexOf(params[key].toLowerCase()) >= 0) {
return sensor;
} else if (field == params[key]) {
return sensor;
}
}
return null;
});
}
add(sensor: Sensor) {
this.sensores.push(sensor);
}
delete(sensor: Sensor) {
this.sensores.splice(this.sensores.indexOf(sensor), 1);
}
}
<file_sep>/src/pages/sensor-create/sensor-create.ts
import { StorageService } from './../../providers/storage/storageService';
import { Component, ViewChild } from '@angular/core';
import { Camera } from '@ionic-native/camera';
import { IonicPage, NavController, ViewController, ToastController, LoadingController, DateTime } from 'ionic-angular';
import { BarcodeScanner } from '@ionic-native/barcode-scanner';
import { BluetoothSerial } from '@ionic-native/bluetooth-serial';
import { AlertController } from 'ionic-angular';
import { Subscription } from 'rxjs/Subscription';
import { Wifi } from '../../models/wifi';
import { Sensores } from './../../providers/sensores/sensores';
import { Sensor } from './../../models/sensor';
import { areIterablesEqual } from '@angular/core/src/change_detection/change_detection_util';
@IonicPage()
@Component({
selector: 'page-sensor-create',
templateUrl: 'sensor-create.html'
})
export class SensorCreatePage {
@ViewChild('fileInput') fileInput;
isReadyToSave: boolean;
unpairedDevices: any;
gettingDevices: Boolean = false;
eventoRecebe: Subscription;
recebido: string = "";
//recebidoDoSensor: string = '{"wifi":[ {"nome":"Fabricio", "seguranca":"aberta", "sinal":-90 }, {"nome":"Mably", "seguranca":"fechada", "sinal":-70 }, {"nome":"Larissa", "seguranca":"texto_seguranca3", "sinal":-40 } ] } ';
wifiList: object;
timerRecebe: number = 0;
currentWifis: Wifi[]= [];
sensor: Sensor = new Sensor();
loading: any = null;
constructor(public navCtrl: NavController
, public viewCtrl: ViewController
, public camera: Camera
, public barcodeScanner: BarcodeScanner
, private bluetoothSerial: BluetoothSerial
, private alertCtrl: AlertController
, public sensores: Sensores
, public storage: StorageService
, public toastCtrl: ToastController
, public loadingCtrl: LoadingController) {
this.storage.get('usuario').then(user => {
this.sensor.usuarioId = user.id;
});
this.loading = this.loadingCtrl.create({
content: 'Conectando ao sensor ...'
});
}
ionViewDidLoad() {
}
// ************* Capturar imagem
getPicture() {
if (Camera['installed']()) {
this.camera.getPicture({
destinationType: this.camera.DestinationType.DATA_URL,
targetWidth: 96,
targetHeight: 96
}).then((data) => {
// this.form.patchValue({ 'imagem': 'data:image/jpg;base64,' + data });
}, (err) => {
alert('Unable to take photo');
})
} else {
this.fileInput.nativeElement.click();
}
}
processWebImage(event) {
let reader = new FileReader();
reader.onload = (readerEvent) => {
let imageData = (readerEvent.target as any).result;
// this.form.patchValue({ 'imagem': imageData });
};
reader.readAsDataURL(event.target.files[0]);
}
getProfileImageStyle() {
// return 'url(' + this.form.controls['imagem'].value + ')'
}
/**
* O usuário cancelou, então descartamos sem enviar os dados de volta.
*/
cancel() {
this.viewCtrl.dismiss();
}
/**
* O usuário está pronto e quer criar o item, então devolva-o ao apresentador.
*/
done() {
this.viewCtrl.dismiss();
}
/**
* Le QRCODE
*/
scanCode(){
// this.gettingDevices = true;
this.barcodeScanner.scan().then(barcodeData => {
this.bluetoothSerial.enable();
this.conectaBluetooth(barcodeData.text);
// this.gettingDevices = false;
}).catch(err => {
console.log('Error', err);
});
}
/**
* Chama a função de conectar no sensor com o QRCODE
*/
createSensor(){
let obj: {parametro: string, operacao:string, conteudo:any };
this.sensores.add(this.sensor).subscribe((resp) => {
this.sensor.guid = resp['status']['guid'];
//this.viewCtrl.dismiss(this.sensor);
obj = {parametro:"configuracao",operacao:"definicao",conteudo: { guid: this.sensor.guid}};
this.enviaMensagem(JSON.stringify(obj)).then((resp) =>{
obj = { parametro: "wifi", operacao: "definicao", conteudo: { redes: this.sensor.wifis }};
this.enviaMensagem(JSON.stringify(obj)).then((resp) => {});
const toast = this.toastCtrl.create({
message: 'Sensor cadastrado com sucesso!',
duration: 3000
});
toast.present();
this.desconectaBluetooth();
this.viewCtrl.dismiss(this.sensor);
});
},
(err) => {
alert('erro: ' + err);
});
}
fail = (error) => alert('falhou: '+error);
success = (data) => alert('sucesso: ' +data);
/**
* Conectar ao bluetooth
* @param address mac do bluettoth do sensor
* Cso sucesso chama a função send() que envia mensagem para o sensor
*/
conectaBluetooth(address: any) {
let alerta = this.alertCtrl.create({
title: 'Conectar',
message: 'Você quer se conectar ao Sensor?',
buttons: [
{
text: 'Cancelar',
role: 'cancelar',
handler: () => {
console.log('Cancelar clicado');
}
},
{
text: 'Conectar',
handler: () => {
this.loading.present();
setTimeout(() => {
this.loading.dismiss();
}, 10000);
this.bluetoothSerial.connect(address).subscribe(() => {
this.enviaMensagem('{"parametro": "wifi","operacao": "pergunta"}').then((data : string) => {
this.currentWifis = this.toWifis(data);
this.enviaMensagem('{"parametro": "configuracao","operacao": "pergunta"}').then((data : string) => {
let jsonData = JSON.parse(data);
this.sensor.tipo = jsonData['conteudo']['tipo'];
this.defineImagem();
this.loading.dismiss();
});
});
},
this.fail);
}
}
]
});
alerta.present();
}
/**
* disconecta do bluettoth
*/
desconectaBluetooth() {
let alerta = this.alertCtrl.create({
title: 'Disconnect?',
message: 'Do you want to Disconnect?',
buttons: [
{
text: 'Cancel',
role: 'cancel',
handler: () => {
console.log('Cancel clicked');
}
},
{
text: 'Disconnect',
handler: () => {
this.bluetoothSerial.disconnect();
}
}
]
});
alerta.present();
}
/**
* envia mensagem para o bluetooth
* @param texto é o que será enviado
* @param funcao
*/
enviaMensagem(texto:string) {
return new Promise((resolve, reject) => {
//let timeout = setTimeout(() => {
//reject('timeout ao receber inicio');
//},10000);
//this.bluetoothSerial.subscribe('\x02').subscribe((data : string) => {
//clearTimeout(timeout);
this.bluetoothSerial.subscribe('\x03').subscribe((data) => {
resolve(data.slice(1,-1));
});
//});
this.bluetoothSerial.write('\x02' + texto + '\x03');
});
}
isEmpty(obj: object){
for (var i in obj) {
if(obj.hasOwnProperty(i)) {
return false;
}
}
return true;
}
toWifis(data: string){
let jsonData = JSON.parse(data);
let conteudo = jsonData['conteudo'];
let currentWifis: Wifi[] = [];
for (let key in conteudo) {
for (let i=0; i< conteudo[key].length ; i=i+1){
let potenciaSinal: string = '';
if(conteudo[key][i].sinal > -60){
potenciaSinal = ' (Forte)';
}else if (conteudo[key][i].sinal <= -60
&& conteudo[key][i].sinal > -85){
potenciaSinal = ' (Medio)';
}else if (conteudo[key][i].sinal <= -85){
potenciaSinal = ' (Fraco)';
}
let wifi: Wifi = new Wifi(conteudo[key][i].nome
,conteudo[key][i].senha
, potenciaSinal);
currentWifis.push(wifi);
}
}
return currentWifis;
}
defineImagem(){
if(this.sensor.tipo == 1){
this. sensor.imagem = 'assets/img/sensor-energia.jpg';
this.sensor.tipoNome = 'Sensor de Energia';
}else if(this.sensor.tipo == 2){
this.sensor.imagem = 'assets/img/sensor-temperatura.jpg';
this.sensor.tipoNome = 'Sensor de Temperatura';
}else if(this.sensor.tipo == 3){
this.sensor.imagem = 'assets/img/sensor-pressao.jpg';
this.sensor.tipoNome = 'Sensor de Pressão';
}else if(this.sensor.tipo == 4){
this.sensor.imagem = 'assets/img/sensor-movimento.jpg';
this.sensor.tipoNome = 'Sensor de Movimento';
}
}
}
<file_sep>/src/models/regra.ts
import { Sensor } from "./sensor";
export class Regra {
id: number;
sensorId: number;
sensor: Sensor;
acaoId: number;
descricao: string;
periodo: number;
operadorMinimo: string;
valorMinimo: number;
operadormaximo: number;
valorMaximo: number;
constructor(){
}
// constructor(id: number,
// sensorId: number,
// acaoId: number,
// descricao: string,
// periodo: number,
// operadorMinimo: string,
// valorMinimo: number,
// operadormaximo: number,
// valorMaximo: number) {
// this.id = id;
// this.sensorId = sensorId;
// this.acaoId = acaoId;
// this.descricao = descricao;
// this.periodo = periodo;
// this.operadorMinimo = operadorMinimo;
// this.valorMinimo = valorMinimo;
// this.operadormaximo = operadormaximo;
// this.valorMaximo = valorMaximo;
// }
}
<file_sep>/src/pages/settings/settings.ts
import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { User } from './../../providers/user/user';
import { IonicPage, NavController, NavParams, ToastController } from 'ionic-angular';
import { StorageService } from './../../providers/storage/storageService';
import { Settings } from '../../providers';
@IonicPage()
@Component({
selector: 'page-settings',
templateUrl: 'settings.html'
})
export class SettingsPage {
account: { id: number,
nome: string,
telefone: string,
login: string,
email: string,
password: string,
emailVerified: boolean } = {
id: null ,
nome: '',
telefone: '',
login: '',
email: '',
password: '',
emailVerified: true
};
constructor(public navCtrl: NavController,
public settings: Settings,
public navParams: NavParams,
public translate: TranslateService,
public user: User,
public toastCtrl: ToastController,
public storage: StorageService) {
this.storage.get('usuario').then(user => {
console.log(user);
this.account.id = user.id;
this.account.nome = user.nome;
this.account.telefone = user.telefone;
this.account.login = user.login;
this.account.email = user.email;
this.account.password = <PASSWORD>;
this.account.emailVerified = user.emailVerified;
});
}
salvarAlterações() {
this.user.signup(this.account).subscribe((resp) => {
}, (err) => {
let toast = this.toastCtrl.create({
message: 'Erro ao editar o usuario',
duration: 3000,
position: 'top'
});
toast.present();
});
}
}
<file_sep>/src/providers/index.ts
export { Api } from './api/api';
export { Sensores } from '../providers/sensores/sensores';
import { Regras } from './regras/regras';
export { Settings } from './settings/settings';
export { User } from './user/user';
<file_sep>/src/pages/list-regra/list-regra.ts
import { Component } from '@angular/core';
import { IonicPage, ModalController, NavController, NavParams } from 'ionic-angular';
import { Regra } from '../../models/regra';
import { Regras } from './../../providers/regras/regras';
import { Sensores } from './../../providers/sensores/sensores';
@IonicPage()
@Component({
selector: 'page-list-regra',
templateUrl: 'list-regra.html',
})
export class ListRegraPage {
currentRegras: Regra[];
comunicaListaVazia: boolean = false;
constructor(public navCtrl: NavController,
public navParams: NavParams,
public regras: Regras,
public sensores: Sensores,
public modalCtrl: ModalController) {
//this.carregaRegras();
}
ionViewWillEnter(){
this.carregaRegras();
}
carregaRegras(){
this.sensores.getAllSensores((resp) => {
this.regras.getAllRegras((resp2) => {
if(resp2.length>0){
this.comunicaListaVazia = true;
this.currentRegras = resp2;
}
},resp);
});
}
addRegra() {
let addModal = this.modalCtrl.create('RegraCreatePage');
addModal.onDidDismiss(regra => {
if (regra) {
this.currentRegras.push(regra);
this.comunicaListaVazia = true;
}
})
addModal.present();
}
deleteRegra(regra) {
this.regras.delete(regra);
}
openRegra(regra: Regra) {
this.navCtrl.push('RegraDetailPage', {
regra: regra
});
}
getSensores(ev) {
let val = ev.target.value;
if (!val || !val.trim()) {
this.currentRegras = this.regras.query();
return;
}
this.currentRegras = this.regras.query({
descricao: val
});
}
}
<file_sep>/src/pages/regra-detail/regra-detail.module.ts
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { RegraDetailPage } from './regra-detail';
@NgModule({
declarations: [
RegraDetailPage,
],
imports: [
IonicPageModule.forChild(RegraDetailPage),
],
})
export class RegraDetailPageModule {}
<file_sep>/src/pages/regra-detail/regra-detail.ts
import { Sensores } from './../../providers/sensores/sensores';
import { Regras } from './../../providers/regras/regras';
import { Regra } from './../../models/regra';
import { Component } from '@angular/core';
import { Tab2Root } from '../';
import { IonicPage, NavController, NavParams, ViewController } from 'ionic-angular';
@IonicPage()
@Component({
selector: 'page-regra-detail',
templateUrl: 'regra-detail.html',
})
export class RegraDetailPage {
regra: Regra;
constructor(public navCtrl: NavController
, public navParams: NavParams
, public viewCtrl: ViewController
, public regras: Regras
, public sensores: Sensores) {
this.regra = navParams.get('regra');
// console.log(this.regra.sensorId);
this.sensores.buscaPorId(this.regra.sensorId , (resp) => {
this.regra.sensor = resp[0];
});
}
ionViewDidLoad() {
}
update() {
this.regras.update(this.regra).subscribe((resp) => {
this.navCtrl.push(Tab2Root);
}, (err) => {
console.log(err);
});
}
}
<file_sep>/src/pages/sensor-detail/sensor-detail.ts
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams} from 'ionic-angular';
import { LogSensor } from './../../models/logSensor';
import { Sensores } from './../../providers/sensores/sensores';
@IonicPage()
@Component({
selector: 'page-sensor-detail',
templateUrl: 'sensor-detail.html'
})
export class SensorDetailPage {
sensor: any;
currentLogSensor: LogSensor[];
timerAtualiza: number = 0;
constructor(public navCtrl: NavController, navParams: NavParams, public sensores: Sensores) {
this.sensor = navParams.get('sensor');
sensores.getLastLogs(this.sensor, (resp)=>{
this.currentLogSensor = resp;
});
this.timerAtualiza = setInterval(() => {
sensores.getLastLogs(this.sensor, (resp)=>{
this.currentLogSensor = resp;
});
},10000);
}
ionViewWillLeave(){
clearInterval(this.timerAtualiza);
}
resetSensor(){
this.sensores.resetSensor(this.sensor);
}
}
<file_sep>/src/providers/user/user.ts
import 'rxjs/add/operator/toPromise';
import { Injectable } from '@angular/core';
import { Api } from '../api/api';
import { StorageService } from '../storage/storageService';
/**
Most apps have the concept of a User. This is a simple provider
with stubs for login/signup/etc.
This User provider makes calls to our API at the `login` and `signup` endpoints.
By default, it expects `login` and `signup` to return a JSON object of the shape:
*
* ```json
* {
* status: 'success',
* user: {
* // User fields your app needs, like "id", "name", "email", etc.
* }
* }Ø
* ```
*
* Se o campo `status` não for` success`, um erro será detectado e retornado.
*/
@Injectable()
export class User {
_user: any;
constructor(public api: Api, private storage: StorageService) { }
/**
Envie uma solicitação POST para nosso endpoint de login com os dados
que o usuário inseriu no formulário.
*/
login(accountInfo: any) {
let seq = this.api.post('usuarios/login', accountInfo).share();
seq.subscribe((res: any) => {
this._loggedIn(res);
}, err => {
console.error('ERROR', err);
});
return seq;
}
/**
Envie uma solicitação POST ao nosso endpoint de inscrição com
os dados que o usuário inseriu no formulário.
*/
signup(accountInfo: any) {
let seq = this.api.post('usuarios', accountInfo).share();
seq.subscribe((res: any) => {
this._loggedIn(res);
}, err => {
console.error('ERROR', err);
});
return seq;
}
/**
* Log the user out, which forgets the session
*/
logout() {
this._user = null;
this.storage.remove('usuario');
}
/**
* Process a login/signup response to store user data
*/
_loggedIn(resp) {
this._user = resp;
this.api.get('usuarios/'+this._user.userId).share().subscribe(res=>{
this.storage.add('usuario', res);
});
}
buscaPorId(resp) {
this._user = resp;
this.storage.add('usuario', this._user);
}
}
<file_sep>/src/pages/list-master/list-master.ts
import { Component } from '@angular/core';
import { IonicPage, ModalController, NavController, NavParams } from 'ionic-angular';
import { Sensor } from '../../models/sensor';
import { Sensores } from '../../providers';
@IonicPage()
@Component({
selector: 'page-list-master',
templateUrl: 'list-master.html'
})
export class ListMasterPage {
currentSensores: Sensor[];
constructor(public navCtrl: NavController, public navParams: NavParams, public sensores: Sensores, public modalCtrl: ModalController) {
this.sensores.getAllSensores((resp) => {
this.currentSensores = resp;
});
}
ionViewWillEnter(){
this.sensores.getAllSensores((resp) => {
this.currentSensores = resp;
});
}
/**
* Prompt the user to add a new item. This shows our ItemCreatePage in a
* modal and then adds the new item to our data source if the user created one.
*/
addSensor() {
let addModal = this.modalCtrl.create('SensorCreatePage');
addModal.onDidDismiss(sensor => {
if (sensor) {
this.currentSensores.push(sensor);
}
})
addModal.present();
}
/**
* Delete an item from the list of items.
*/
deleteSensor(sensor) {
this.sensores.delete(sensor);
}
/**
* Navigate to the detail page for this item.
*/
openSensor(sensor: Sensor) {
this.navCtrl.push('SensorDetailPage', {
sensor: sensor
});
}
/**
* Perform a service for the proper items.
*/
getSensores(ev) {
let val = ev.target.value;
if (!val || !val.trim()) {
this.currentSensores = this.sensores.query();
return;
}
this.currentSensores = this.sensores.query({
tipoNome: val
});
}
}
<file_sep>/src/models/logSensor.ts
export class LogSensor {
sesnorid: number;
data: string;
valor: string;
id: number;
valido: boolean;
constructor() {
}
}
<file_sep>/src/providers/regras/regras.ts
import { Injectable } from '@angular/core';
import { Regra } from '../../models/regra';
import { Api } from '../api/api';
import { User } from '../user/user';
import { StorageService } from './../storage/storageService';
@Injectable()
export class Regras {
usuarioLogado: any;
regraList: Regra[] = new Array<Regra>();
constructor(public api: Api,
public user: User,
public storage: StorageService) {
}
query(params?: any) {
if (!params) {
return this.regraList;
}
return this.regraList.filter((regra) => {
for (let key in params) {
let field = regra[key];
if (typeof field == 'string' && field.toLowerCase().indexOf(params[key].toLowerCase()) >= 0) {
return regra;
} else if (field == params[key]) {
return regra;
}
}
return null;
});
}
getAllRegras(funcao: any, sensores: any){
let novaRegraList: Regra[] = new Array<Regra>();
sensores.forEach(sensor => {
let seq = this.api.get('parametros',
{filter: '{"where":{"sensorId":'+sensor.id+'}}'}).share();
seq.subscribe((res: any) => {
res.forEach(regra => {
regra.sensor = sensor;
novaRegraList.push(regra);
});
this.regraList = novaRegraList;
funcao(this.regraList);
}, err => {
console.error('ERROR_REGRA', err);
});
});
}
add(regra: Regra) {
return this.api.post('parametros', regra);
}
update(regra: Regra) {
return this.api.put('parametros', regra);
}
delete(regra: Regra) {
}
}
<file_sep>/src/models/wifi.ts
export class Wifi {
nome: string;
senha: string;
sinal: string;
constructor(nome: string
, senha: string
, sinal: string) {
this.nome = nome;
this.senha =senha;
this.sinal = sinal;
}
}
<file_sep>/src/pages/list-regra/list-regra.module.ts
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { ListRegraPage } from './list-regra';
@NgModule({
declarations: [
ListRegraPage,
],
imports: [
IonicPageModule.forChild(ListRegraPage),
],
exports: [
ListRegraPage
]
})
export class SrcPagesListRegraPageModule {}
<file_sep>/src/providers/storage/storageService.ts
import { Storage } from "@ionic/storage";
import { Injectable } from '@angular/core';
@Injectable()
export class StorageService {
constructor(public storage: Storage) {
}
public add(key: string, value: any): void{
this.storage.set(key, value);
}
public get(key: string){
return this.storage.get(key).then((value) => {
if(value){
return value;
}else{
return '';
}
});
}
public remove(key: string): void {
this.storage.remove(key);
}
}
| 31e0b8f9c6eea644678b0db1e179a8577c69ab9f | [
"TypeScript",
"HTML"
] | 20 | HTML | fabriciosmatos/sensebit-app | 864ea8ddf1c00b1a6576c2f8534abd7cb3ab370c | 7c71d8321421820b244f821c208ebbb6d1baf83a |
refs/heads/master | <file_sep>import {app} from 'hyperapp';
import {textarea, div, h1, h2, form, button, p} from '@hyperapp/html';
import {preventDefault, targetValue} from '@hyperapp/events';
import REST from './hyperapp-rest';
// VIEWS
const Note = note => div({class: 'note'}, [h2(note.id), p(note.content)]);
app({
init: [
REST.init(
{title: 'My notes'},
{
resources: {notes: ['collection', 'create']},
endpoint: 'http://localhost:3000',
},
),
REST.collection('notes'),
],
view: state => {
console.log({state});
return div({}, [
h1(state.title),
form({onsubmit: preventDefault([REST.actions.create, 'note'])}, [
textarea({
oninput: [REST.setNewProp('note', 'content'), targetValue],
value: REST.newProp('note', 'content', state),
}),
button('Create Note'),
]),
state.notes && state.notes.map(Note),
]);
},
node: document.getElementById('app'),
});
<file_sep>// UTILITIES
const capitalize = word => word.charAt(0).toUpperCase() + word.slice(1);
// Currying from https://gist.github.com/branneman/4ffb7ec3fc4a2091849ba5d56742960c
const curryN = (fn, arity, accIn = []) => (...args) => {
const len = args.length;
const accOut = accIn.concat(args);
if (len + accIn.length >= arity) {
return fn.apply(this, accOut);
}
return curryN(fn, arity, accOut);
};
const curry = fn => curryN(fn, fn.length);
// omit :: (k, {k: v}) -> {k: v}
const omit = (k, obj) =>
Object.fromEntries(Object.entries(obj).filter(([key, _]) => key !== k));
const pluralize = word => (word.endsWith('s') ? word : word.concat('s'));
const set = curry((prop, value, source) => {
var result = {},
i;
for (i in source) result[i] = source[i];
result[prop] = value;
return result;
});
const append = (x, xs) => xs.concat([x]);
const includes = (x, xs) => xs.indexOf(x) > -1;
export {curry, set, append, omit, includes, capitalize, pluralize};
| f9c3104934df650257f81a7210d1b5338094a9e6 | [
"JavaScript"
] | 2 | JavaScript | adamdawkins/hyperapp-rest | e250e0fa6e2eb3b79dcf15011ed60611fca8e14b | 27f00096eef5895cdba522decd25154a71ea35a2 |
refs/heads/master | <repo_name>DevMyong/webscrapper<file_sep>/internal/scrapper.go
package scrapper
import (
"encoding/csv"
"fmt"
"github.com/PuerkitoBio/goquery"
"log"
"net/http"
"os"
"strconv"
"strings"
)
type extractedJob struct{
link string
title string
company string
location string
salary string
summary string
}
func Scrape(searchWord string){
var baseURL = "https://kr.indeed.com/"
URL := baseURL+"jobs?q="+searchWord+"&limit=50"
var jobs []extractedJob
c:= make(chan []extractedJob)
totalPages := getTotalPages(URL)
for i:=0;i<totalPages;i++{
go getPage(URL, i, c)
}
for i:=0;i<totalPages;i++{
jobs = append(jobs, <-c...)
}
writeFile(jobs)
fmt.Println("Done, extracted", len(jobs))
}
// getTotalPages from recruitment site
func getTotalPages (URL string) int{
totalPages := 0
res, err := http.Get(URL)
checkErr(err)
checkStatusCode(res)
defer res.Body.Close()
doc, err := goquery.NewDocumentFromReader(res.Body)
checkErr(err)
doc.Find(".pagination").Each(func(i int, s *goquery.Selection){
totalPages = s.Find("a").Length()
})
if totalPages == 0 {
return 1
}
return totalPages
}
// getPage from recruitment site
func getPage(baseURL string, page int, mainC chan<- []extractedJob) {
var jobs []extractedJob
c:= make(chan extractedJob)
URL := baseURL +"&start="+strconv.Itoa(page*50)
fmt.Println("Requesting", URL)
res, err:= http.Get(URL)
checkErr(err)
checkStatusCode(res)
defer res.Body.Close()
doc, err := goquery.NewDocumentFromReader(res.Body)
checkErr(err)
searchCards := doc.Find(".jobsearch-SerpJobCard")
searchCards.Each(func(i int, card *goquery.Selection){
go extractJob(card, c)
})
for i:=0;i<searchCards.Length();i++{
jobs = append(jobs, <-c)
}
mainC <- jobs
}
// extractJob detail from recruitment site
func extractJob(card *goquery.Selection, c chan<- extractedJob) {
id,_ := card.Attr("data-jk")
title := CleanString(card.Find(".title>a").Text())
company := CleanString(card.Find(".company").Text())
location := CleanString(card.Find(".location").Text())
salary := CleanString(card.Find("salary").Text())
summary := CleanString(card.Find(".summary").Text())
c <- extractedJob{"https://kr.indeed.com/viewjob?jk="+id,title,company,location,salary,summary}
}
func writeFile(jobs []extractedJob){
c := make(chan []string)
file, err := os.Create("jobs.csv")
checkErr(err)
w := csv.NewWriter(file)
defer w.Flush()
headers := []string{"Link", "Title", "Company", "Location", "Salary", "Summary"}
wErr:= w.Write(headers)
checkErr(wErr)
for _, job := range jobs{
go writeJob(job, c)
}
for i:=0;i<len(jobs);i++{
wErr := w.Write(<-c)
checkErr(wErr)
}
}
func writeJob(job extractedJob, c chan<- []string){
c<- []string{job.link, job.title, job.company, job.location, job.salary, job.summary}
}
func checkErr (err error) {
if err != nil{
log.Fatalln(err)
}
}
func checkStatusCode (res *http.Response){
if res.StatusCode != 200 {
log.Fatalln("Request failed with Status :", res.StatusCode)
}
}
func CleanString (str string) string{
return strings.Join(strings.Fields(strings.TrimSpace(str)), " ")
} | 999f0b32b745da4212ba6d6b72b43244c87fa82e | [
"Go"
] | 1 | Go | DevMyong/webscrapper | 7df6da425c15427ff4078316ba2f89a005a6292b | d3cb1c9178f0a20c186005839acc5070212aa08d |
refs/heads/master | <repo_name>PaulBratslavsky/REACT-reactStoreHooks<file_sep>/src/utils/getData.js
import axios from 'axios';
import URL from './URL';
// Get Data Function
export const getData = data => axios.get(`${URL}/${data}`);
<file_sep>/src/utils/local.js
const LocalCtr = (function () {
function get(key) {
return localStorage.getItem(key)
? JSON.parse(localStorage.getItem(key))
: []
}
function set(key, item) {
localStorage.setItem(key, JSON.stringify(item))
}
function clear(key) {
localStorage.getItem(key) && localStorage.clear()
}
return {
set,
get,
clear,
}
})()
export default LocalCtr<file_sep>/src/components/Products/ProductList.js
/***********************************************
PRODUCT LIST COMPONENT IMPORTS
***********************************************/
import React from 'react';
import Product from './Product';
/***********************************************
PRODUCT LIST COMPONENT
***********************************************/
export default function ProductList({ title, products }) {
console.log(products);
return <section className="section">
<h1 className="section-title">{title}: we have {products.length} items.</h1>
<div className="products-center">
{products.map(product => <Product key={product.id} {...product} />)}
</div>
</section>;
}
<file_sep>/src/components/PrivateRoute.js
/***********************************************
PRIVATE ROUTE COMPONENT IMPORTS
***********************************************/
import React from "react";
/***********************************************
PRIVATE ROUTE COMPONENT
***********************************************/
export default function PrivateRoute() {
return <h1>hello from private route</h1>;
}
<file_sep>/src/pages/Products.js
/***********************************************
PRODUCTS COMPONENT IMPORTS
***********************************************/
import React from 'react';
import { ProductContext } from '../context/products';
import Loading from '../components/Loading';
import ProductList from '../components/Products/ProductList';
/***********************************************
PRODUCTS COMPONENT
***********************************************/
export default function Products() {
const { productsState, loadingState, productsErrorState } = React.useContext(ProductContext);
return <> { loadingState
? <Loading productsErrorState={productsErrorState} />
: <ProductList title="All Products" products={productsState} />
} </>
}
<file_sep>/src/components/Hero.js
/***********************************************
HERO COMPONENT IMPORTS
***********************************************/
import React from 'react';
/***********************************************
HeRO COMPONENT IMPORTS
***********************************************/
export default function Hero({ children }) {
return (
<div className="hero">
<div className="banner">
<h1>Reac Hero</h1>
<p>Embrace your inner hero</p>
{children}
</div>
</div>
);
}
<file_sep>/src/context/products.js
// products context
import React from 'react';
import { getData } from '../utils/getData';
export const ProductContext = React.createContext();
export default function ProductProvider({ children }) {
// Use Effect
React.useEffect(() => {
getData('products')
.then(response => {
setProductsState(response.data);
setFeaturedProductsState(getFeaturedProducts(response.data));
setLoadingState(false);
})
.catch(err => {
console.error('FETCH PRODUCT ERROR: ', err);
setProductsErrorState(err);
});
return () => {
// Clean up function
};
}, []);
const getFeaturedProducts = products =>
products.filter(item => item.featured === true);
// SET LOGIC IN CONTEXT
const [loadingState, setLoadingState] = React.useState(true);
const [productsState, setProductsState] = React.useState([]);
const [featuredProductsState, setFeaturedProductsState] = React.useState([]);
const [productsErrorState, setProductsErrorState] = React.useState(null);
const products = {
productsState,
featuredProductsState,
loadingState,
productsErrorState
};
return (
<ProductContext.Provider value={products}>
{children}
</ProductContext.Provider>
);
}
<file_sep>/src/components/Products/Product.js
/***********************************************
PRODUCT COMPONENT IMPORTS
***********************************************/
import React from 'react';
import { Link } from 'react-router-dom'
/***********************************************
PRODUCT COMPONENT IMPORTS
***********************************************/
export default function Product({ id, title, price, image }) {
const imageUrl = image.url;
return <article className="product">
<div className="img-container">
<img src={imageUrl} alt={title} />
<Link className="btn btn-primary product-link" to={`products/${id}`}>More Info</Link>
</div>
<div className="product-footer">
<p className="product-title">{title}</p>
<p className="product-price">{price}</p>
</div>
</article>
}
| 506627af89d2b67cf667b2dd70537f94e1ea6314 | [
"JavaScript"
] | 8 | JavaScript | PaulBratslavsky/REACT-reactStoreHooks | 1b95cdfc7b0824d9792ea8c227cd504cf70edc35 | f32a2496c3c3de79ea87d39560359da9cf700c31 |
refs/heads/master | <repo_name>jxr9234/GetYourNailsOut<file_sep>/loadPage.php
<?php include 'navigation.php' ?>
<div id="load-header">
</div>
<div id="load-area">
</div>
<?php include 'footer-section.php' ?><file_sep>/README.md
# GetYourNailsOut
A made up nail salon website!
Sectioning off sections of a page into separate php files so it can be loaded with jquery. However, when the user refreshes it
will redirect the user back to the index page.
<file_sep>/main.js
$(document).ready(function(){
$('.hero-text > h1').hide().fadeIn(800).effect( "bounce", { distance: 80,times: 3 },900);
$('#hero-tabs , .slogan, .business-info').hide().fadeIn(1100);
$('#hero-tabs > a').click(function(e){
event.preventDefault();
if(this.id == "service"){
$('#load-test').load('loadPage.php', function(){
$("#load-area").load('services.php');
$("#load-header").addClass('service-jumbo');
});
}
else if(this.id == "product"){
$('#load-test').load('loadPage.php', function(){
/* $("#load-area").load('products.php');
$("#load-header").addClass('product-jumbo');
*/
createProduct();
});
}
else{
$('#load-test').load('loadPage.php', function(){
$("#load-area").load('contact.php');
$("#load-header").addClass('contact-jumbo');
});
}
});
$('#servicePage').click(function(){
$('#load-area').load('services.php');
$("#load-header").removeClass().addClass('service-jumbo');
return false;
});
$('#productPage').click(function(){
createProduct();
return false;
});
let createProduct=()=>{
$('#load-area').load('products.php');
$("#load-header").removeClass().addClass('product-jumbo');
$.getJSON('productlist.json', (data)=>{
console.log(data);
$('#all-products').append(`<h1>Nail Products</h1><div id='nail-products'></div><h1>Beauty Products</h1><div id='beauty-products'></div>`);
let nails = data.nails;
for(let nProd in nails){
$('#nail-products').append(
`<div class='product_card' data-prod_id='${nails[nProd].prod_id}'><h2>${nails[nProd].prod_name}</h2>
<div class='product_image'>
<img src="${nails[nProd].image}" alt="${nails[nProd].prod_name}"/>
</div>
<p>${nails[nProd].description}</p>
<p class='product_price'>$${nails[nProd].price}</p>
</div>`
);
}
let beauty = data.beauty;
for(let bProd in beauty){
$('#beauty-products').append(
`<div class='product_card' data-prod_id='${beauty[bProd].prod_id}'><h2>${beauty[bProd].prod_name}</h2>
<div class='product_image'>
<img src="${beauty[bProd].image}" alt="${beauty[bProd].prod_name}"/>
</div>
<p>${beauty[bProd].description}</p>
<p class='product_price'>$${beauty[bProd].price}</p>
</div>`
);
}
});
}
$('#contactPage').click(function(){
$('#load-area').load('contact.php');
$("#load-header").removeClass().addClass('contact-jumbo');
return false;
});
function pageSlideshow(){
let imageArray =
["media/beauty-conceptual-nail-polish.jpg",
"media/cacti-cactus-cactus.jpg,",
"media/adult-beauty-cosmetic.jpg"];
}
});<file_sep>/footer.php
<footer id="main-footer">
<p>© Get Your Nails Out! <?php echo date('Y'); ?></p>
</footer>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="<KEY> crossorigin="anonymous"></script>
<script
src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"
integrity="<KEY>
crossorigin="anonymous"></script>
<script src="main.js" async defer></script>
</body>
</html> | 0f762acd4ba2704d1a7a178f614486969c1a7c85 | [
"Markdown",
"JavaScript",
"PHP"
] | 4 | PHP | jxr9234/GetYourNailsOut | 2f401b5ebd2a3ff0aa53ea21d7788258f4d46d8e | 0f1804f2bc34be2b0f153f6a6377628add2f9290 |
refs/heads/master | <file_sep>### Spring as backend and SPA(Vue in this project) as frontend both in a project.
#### This repository shows how to deal with spring and SPA in aspect of structure of project using webpack.
##### See how it works
`./gradlew bootRun`
`npm install && npm start`
Open browser, then go `localhost:3000`
### Backend API
For further works, API uri behind spring can be started with `/api` which can be found in configuration against proxy `webpack.dev.config.js`.
> e.g.) `GET /api/users/{userId}/devices`<file_sep>const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackHarddiskPlugin = require('html-webpack-harddisk-plugin');
const isRunningServer = process.env.npm_lifecycle_event.includes('start');
module.exports = {
mode: 'development',
devtool: 'inline-cheap-module-eval-source-map',
devServer: {
disableHostCheck: true,
historyApiFallback: true,
compress: true,
hot: true,
host: '0.0.0.0',
port: 3000,
publicPath: '/script/',
contentBase: [path.resolve(__dirname, 'front-vue'), path.resolve(__dirname, 'src/main/resources/static')],
proxy: [
{
context: ['/api', '/login', '/logout'],
target: 'http://localhost:8080',
secure: false, // SSL verification
proxyTimeout: 1000 * 60 * 10
}
] // proxy options 에 대하여 잘 정리된 문서 = https://github.com/chimurai/http-proxy-middleware#context-matching
},
plugins: [
new HtmlWebpackPlugin({
template: './front-vue/template-index.html',
filename: isRunningServer ? 'index.html' : '../../templates/index.html', // 개발 서버를 구동할 땐 ./front-vue/index.html 로 결과물이 나오도록 설정. webpack-dev-server 의 index 가 index.html 이고 실제 serve 하는 파일이기 때문
alwaysWriteToDisk: isRunningServer
}),
new HtmlWebpackHarddiskPlugin({
outputPath: path.resolve(__dirname, 'front-vue')
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin()
]
};<file_sep>'use strict'
const path = require('path');
const webpack = require('webpack');
const webpackMerge = require('webpack-merge');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { VueLoaderPlugin } = require('vue-loader')
const target = process.env.npm_lifecycle_event; // npm run dev || npm run prod 로 build 해야 함
const isProd = target === 'prod'; // [chunkhash] 는 prod 에서만 사용함
const common = {
cache: true, // 캐시를 사용하지 않으면 매번 full build 를 한다. (webpack-dev-server 에서도)
entry: { // key 이름이 entry point 의 이름이 되고, chunk 의 [name]으로 매핑된다.
main: [path.join(__dirname, '/front-vue/index.js')]
},
output: {
path: path.join(__dirname, '/src/main/resources/static/script/'), // 번들한 결과물이 위치할 실제 물리적인 파일 경로
filename: isProd ? 'bundle.[name].[chunkhash].js' : 'dev-bundle.[name].js', // 번들한 결과물의 파일 이름
chunkFilename: isProd ? 'bundle.[name].[chunkhash].js' : 'dev-bundle.[name].js', // entry 를 제외한 청크의 파일 이름
publicPath: '/script/' // 번들한 결과물이 위치할 URL 경로
},
module: {
rules: [
{
test: /\.vue$/,
use: 'vue-loader',
exclude: /node_modules/
},
{
test: /\.js$/,
loader: ['babel-loader?cacheDirectory'],
exclude: /node_modules/
},
{
test: /\.css$/,
loader: 'style-loader!css-loader'
},
{
test: /\.(png|woff|woff2|eot|ttf|svg|gif|jpg)$/,
loader: 'url-loader?limit=1024'
}
]
},
optimization: {
splitChunks: {
chunks: 'all'
}
},
plugins: [
new VueLoaderPlugin(),
new HtmlWebpackPlugin({ // template-index.html 을 기본으로 번들된 결과물을 </body> 태그 전에 삽입하고 spring boot 가 serve 할 수 있도록 경로를 바꿔서 저장(chunkhash 를 미리 알 수 없음)
template: './front-vue/template-index.html',
filename: '../../templates/index.html'
}),
new webpack.DefinePlugin({
'process.env.npm_lifecycle_event': JSON.stringify(target)
})
]
};
const prodConfig = {
mode: 'production'
};
let config = {};
console.log('target: ', target);
if (target === 'prod') {
console.log('### !!! production build... !!!');
config = webpackMerge(common, prodConfig);
} else {
console.log('### development build...');
config = webpackMerge(common, require('./webpack.dev.config.js'));
}
module.exports = config; | 894977f5f88dd8a5f36f7d576c8dae39703f5f0a | [
"Markdown",
"JavaScript"
] | 3 | Markdown | starrybleu/spring-spa-demo | 15c4688a2fd73726e86ff4b9897fe398fbafb289 | b84f9de2dd40f87a3bbc0d57e6cc8de4def37880 |
refs/heads/master | <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;
using LibGit2Sharp.Core;
using LibGit2Sharp.Handlers;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//LibGit2Sharp.Handlers.
LibGit2Sharp.Configuration cfg = new LibGit2Sharp.Configuration();
cfg.First();
}
}
}
| 1b5fa44e715a22bd167477b9d60ace6d2b4dd1fa | [
"C#"
] | 1 | C# | wangrenjay/gittest | 56ec8a753f259f3505ad08c7274cd52acea139da | e172bd4e939937915a1cc72e4545da3d226caada |
refs/heads/master | <file_sep>/*
* Copyright (c) 2018 Uber Technologies, 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.
*/
package terraform
import (
"bytes"
"errors"
"io/ioutil"
"os"
"github.com/romanwozniak/astro/astro/logger"
"github.com/hashicorp/hcl"
"github.com/hashicorp/hcl/hcl/ast"
"github.com/hashicorp/hcl/hcl/printer"
)
// astGet gets the node from l at key.
func astGet(l *ast.ObjectList, key string) ast.Node {
for i := range l.Items {
for j := range l.Items[i].Keys {
if l.Items[i].Keys[j].Token.Text == key {
return l.Items[i].Val
}
}
}
return nil
}
// astDel deletes the node at key from l. Returns an error if the key does not
// exist.
func astDel(l *ast.ObjectList, key string) error {
for i := range l.Items {
for j := range l.Items[i].Keys {
if l.Items[i].Keys[j].Token.Text == key {
l.Items = append(l.Items[:i], l.Items[i+1:]...)
return nil
}
}
}
return errors.New("cannot delete key %v: does not exist")
}
func deleteTerraformBackendConfig(in []byte) (updatedConfig []byte, err error) {
config, err := parseTerraformConfig(in)
if err != nil {
return nil, err
}
terraformConfigBlock, ok := astGet(config, "terraform").(*ast.ObjectType)
if !ok {
return nil, errors.New("could not parse \"terraform\" block in config")
}
if err := astDel(terraformConfigBlock.List, "backend"); err != nil {
return nil, err
}
buf := &bytes.Buffer{}
printer.Fprint(buf, config)
return buf.Bytes(), nil
}
func deleteTerraformBackendConfigFromFile(file string) error {
logger.Trace.Printf("terraform: deleting backend config from %v", file)
b, err := ioutil.ReadFile(file)
if err != nil {
return err
}
updatedConfig, err := deleteTerraformBackendConfig(b)
if err != nil {
return err
}
// Unlink the file before writing a new one; this is because we're working
// with a hardlinked file and we don't want to modify the original.
os.Remove(file)
newFile, err := os.Create(file)
if err != nil {
return err
}
_, err = newFile.Write(updatedConfig)
if err != nil {
return err
}
newFile.Close()
return nil
}
func parseTerraformConfig(in []byte) (*ast.ObjectList, error) {
astFile, err := hcl.ParseBytes(in)
if err != nil {
return nil, err
}
rootNodes, ok := astFile.Node.(*ast.ObjectList)
if !ok {
return nil, errors.New("unable to parse config")
}
return rootNodes, nil
}
<file_sep>#!/bin/bash
exec go run $GOPATH/src/github.com/romanwozniak/astro/astro/tvm/cli/tvm/main.go "$@"
<file_sep>/*
* Copyright (c) 2018 Uber Technologies, 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.
*/
package utils
import (
"sync"
)
// Parallel runs at most maxConcurrent functions in parallel.
func Parallel(maxConcurrent int, fns ...func()) {
wg := sync.WaitGroup{}
guard := make(chan struct{}, maxConcurrent)
for _, fn := range fns {
guard <- struct{}{}
wg.Add(1)
go func(fn func()) {
defer wg.Done()
fn()
<-guard
}(fn)
}
wg.Wait()
}
<file_sep>/*
* Copyright (c) 2018 Uber Technologies, 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.
*/
package tests
import (
"io/ioutil"
"os"
"path/filepath"
"regexp"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// getSessionDirs returns a list of the sessions inside a session repository.
// This excludes other directories that might have been created in there, e.g.
// the shared plugin cache directory.
func getSessionDirs(sessionBaseDir string) ([]string, error) {
sessionRegexp, err := regexp.Compile("[0-9A-Z]{26}")
if err != nil {
return nil, err
}
dirs, err := ioutil.ReadDir(sessionBaseDir)
if err != nil {
return nil, err
}
sessionDirs := []string{}
for _, dir := range dirs {
if sessionRegexp.MatchString(dir.Name()) {
sessionDirs = append(sessionDirs, dir.Name())
}
}
return sessionDirs, nil
}
func TestProjectApplyChangesSuccess(t *testing.T) {
for _, version := range terraformVersionsToTest {
t.Run(version, func(t *testing.T) {
err := os.RemoveAll("/tmp/terraform-tests/apply-changes-success")
require.NoError(t, err)
err = os.MkdirAll("/tmp/terraform-tests/apply-changes-success", 0775)
require.NoError(t, err)
result := RunTest(t, []string{"apply"}, "fixtures/apply-changes-success", version)
assert.Contains(t, result.Stdout.String(), "foo: [32mOK")
assert.Empty(t, result.Stderr.String())
assert.Equal(t, 0, result.ExitCode)
})
}
}
func TestProjectPlanSuccessNoChanges(t *testing.T) {
for _, version := range terraformVersionsToTest {
t.Run(version, func(t *testing.T) {
result := RunTest(t, []string{"plan", "--trace"}, "fixtures/plan-success-nochanges", version)
assert.Equal(t, "foo: \x1b[32mOK\x1b[0m\x1b[37m No changes\x1b[0m\x1b[37m (0s)\x1b[0m\nDone\n", result.Stdout.String())
assert.Equal(t, 0, result.ExitCode)
})
}
}
func TestProjectPlanSuccessChanges(t *testing.T) {
for _, version := range terraformVersionsToTest {
t.Run(version, func(t *testing.T) {
result := RunTest(t, []string{"plan"}, "fixtures/plan-success-changes", version)
assert.Contains(t, result.Stdout.String(), "foo: [32mOK[0m[33m Changes[0m[37m")
assert.Regexp(t, `\+.*null_resource.foo`, result.Stdout.String())
assert.Equal(t, 0, result.ExitCode)
})
}
}
func TestProjectPlanError(t *testing.T) {
for _, version := range terraformVersionsToTest {
t.Run(version, func(t *testing.T) {
result := RunTest(t, []string{"plan"}, "fixtures/plan-error", version)
assert.Contains(t, result.Stderr.String(), "foo: [31mERROR")
assert.Contains(t, result.Stderr.String(), "Error parsing")
assert.Equal(t, 1, result.ExitCode)
})
}
}
func TestProjectPlanDetachSuccess(t *testing.T) {
for _, version := range terraformVersionsToTest {
t.Run(version, func(t *testing.T) {
err := os.RemoveAll("/tmp/terraform-tests/plan-detach")
require.NoError(t, err)
err = os.MkdirAll("/tmp/terraform-tests/plan-detach", 0775)
require.NoError(t, err)
result := RunTest(t, []string{"plan", "--detach"}, "fixtures/plan-detach", version)
require.Empty(t, result.Stderr.String())
require.Equal(t, 0, result.ExitCode)
require.Equal(t, "foo: \x1b[32mOK\x1b[0m\x1b[37m No changes\x1b[0m\x1b[37m (0s)\x1b[0m\nDone\n", result.Stdout.String())
sessionDirs, err := getSessionDirs("/tmp/terraform-tests/plan-detach/.astro")
require.NoError(t, err)
require.Equal(t, 1, len(sessionDirs), "unable to find session: expect only a single session to have been written, found multiple")
_, err = os.Stat(filepath.Join("/tmp/terraform-tests/plan-detach/.astro", sessionDirs[0], "foo/sandbox/terraform.tfstate"))
assert.NoError(t, err)
})
}
}
<file_sep>/*
* Copyright (c) 2018 Uber Technologies, 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.
*/
package exec2_test
import (
"io/ioutil"
"os"
"testing"
"github.com/romanwozniak/astro/astro/exec2"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func newHelloWorld() *exec2.Process {
return exec2.NewProcess(exec2.Cmd{
Command: "/bin/sh",
Args: []string{"-c", "echo Hello, world!"},
})
}
func TestProcess(t *testing.T) {
process := newHelloWorld()
err := process.Run()
require.NoError(t, err)
assert.True(t, process.Success())
assert.Equal(t, 0, process.ExitCode())
assert.Equal(t, "Hello, world!\n", process.Stdout().String())
}
func TestProcessError(t *testing.T) {
process := exec2.NewProcess(exec2.Cmd{
Command: "/bin/sh",
Args: []string{"-c", "echo Houston, we have a problem >&2; exit 23"},
})
err := process.Run()
assert.Error(t, err)
assert.False(t, process.Success())
assert.Equal(t, 23, process.ExitCode())
assert.Equal(t, "", process.Stdout().String())
assert.Equal(t, "Houston, we have a problem\n", process.Stderr().String())
}
func TestCombinedOutputLog(t *testing.T) {
tmpLogFile, err := ioutil.TempFile("", "")
require.NoError(t, err)
defer os.Remove(tmpLogFile.Name())
// This process writes something to stdout and stderr
process := exec2.NewProcess(exec2.Cmd{
Command: "/bin/sh",
Args: []string{"-c", "echo Hello, world!; echo uhoh! >&2"},
CombinedOutputLogFile: tmpLogFile.Name(),
})
err = process.Run()
require.NoError(t, err)
// Read contents back from log file
logFileContents, err := ioutil.ReadAll(tmpLogFile)
require.NoError(t, err)
// Log file should be stdout/stderr combined; but we can't be sure
// of the order.
assert.Contains(t, string(logFileContents), "+ /bin/sh [-c echo Hello, world!; echo uhoh! >&2]")
assert.Contains(t, string(logFileContents), "Hello, world")
assert.Contains(t, string(logFileContents), "uhoh!")
// Check that stdout/stderr are still captured correctly
assert.Equal(t, "Hello, world!\n", process.Stdout().String())
assert.Equal(t, "uhoh!\n", process.Stderr().String())
}
func TestExited(t *testing.T) {
process := newHelloWorld()
assert.False(t, process.Exited())
process.Run()
assert.True(t, process.Exited())
}
<file_sep>#!/bin/bash
exec go run $GOPATH/src/github.com/romanwozniak/astro/astro/cli/astro/main.go "$@"
<file_sep>module github.com/romanwozniak/astro
require (
github.com/burl/go-version v0.0.0-20160609042920-758edfbba225
github.com/fsnotify/fsnotify v1.4.7 // indirect
github.com/ghodss/yaml v1.0.0
github.com/hashicorp/errwrap v1.0.0 // indirect
github.com/hashicorp/go-multierror v0.0.0-20171204182908-b7773ae21874
github.com/hashicorp/hcl v0.0.0-20180404174102-ef8a98b0bbce
github.com/hashicorp/terraform v0.11.7
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51
github.com/logrusorgru/aurora v0.0.0-20180419164547-d694e6f975a9
github.com/magiconair/properties v1.8.1 // indirect
github.com/mitchellh/go-homedir v0.0.0-20161203194507-b8bc1bf76747
github.com/mitchellh/mapstructure v1.1.2 // indirect
github.com/oklog/ulid v0.3.0
github.com/pelletier/go-toml v1.4.0 // indirect
github.com/spf13/afero v1.2.2 // indirect
github.com/spf13/cast v1.3.0 // indirect
github.com/spf13/cobra v0.0.3
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.1
github.com/spf13/viper v1.0.2
github.com/stretchr/testify v1.2.2
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a // indirect
)
| 9a9262bca79d79da89f4ef3f902332680cddfa40 | [
"Go Module",
"Go",
"Shell"
] | 7 | Go | romanwozniak/astro | 8766ea4397b912df9e2811c38fdd2ee161163eb5 | 999e59e26cee2267d52071d695f068f8197f4ba1 |
refs/heads/main | <repo_name>Troothe/CPSC349-HW3<file_sep>/scripts/payment_main.js
(function (window) {
'use strict';
var FORM_SELECTOR = '[data-payment="form"]';
var App = window.App;
var FormHandler = App.FormHandler;
var formHandler = new FormHandler(FORM_SELECTOR);
formHandler.addSubmitHandler(function (data) {
console.log('Handling?');
console.log(data);
$('#open-modal-link').click();
$('#modal-text')[0].innerText = "Thank you for your payment, " + data.title + " " + data.username;
});
})(window); | 7866271620e0034a826f1b061faf87efab86088d | [
"JavaScript"
] | 1 | JavaScript | Troothe/CPSC349-HW3 | bd17187ac541e060ef707970dc35a6cf72bf82b9 | 27c1818bbfee6a9aaaacd5d3d342c94eec8ac4bb |
refs/heads/main | <file_sep>import multiprocessing
import time
from random import random
def random_log_entry_generator():
name = multiprocessing.current_process().name
print(name, 'Starting')
count = 0
while count < 5:
number = round(random() * 10, 5)
random_number = "%d" % number
entry = 'The new random entry is : ' + random_number
time.sleep(3)
count += 1
print(entry)
print(name, 'Exiting')
def my_service():
name = multiprocessing.current_process().name
print name, 'Starting'
time.sleep(3)
print name, 'Exiting'
if __name__ == '__main__':
service = multiprocessing.Process(name='my_service', target=my_service)
random_log_entry_generator = multiprocessing.Process(name='random_log_entry_generator', target=random_log_entry_generator())
worker_2 = multiprocessing.Process(target=random_log_entry_generator()) # use default name
random_log_entry_generator.start()
worker_2.start()
service.start()
<file_sep># Determining-the-Current-Process-in-Multiprocessing-in-Python
Passing arguments to identify or name the process is cumbersome, and unnecessary. Each Process instance has a name with a default value that can be changed as the process is created. Naming processes is useful for keeping track of them, especially in applications with multiple types of processes running simultaneously.
| e2742e7ec92746cd4ab408a9a0d17df240203cba | [
"Markdown",
"Python"
] | 2 | Python | handeyildirim/Determining-the-Current-Process-in-Multiprocessing-in-Python | d69e99ceeee9e8390e613ce710ea80b7ffb455f1 | b9ed0cea6f54ddde99ffc880111dbeac7b02c958 |
refs/heads/master | <file_sep>Title: Activity Menu
Desc: Activity Menu
---
## Mobile
```
<!--demo1-->
<div class='mobile_wt_con flex_none'>
<div class='mobile_wt_status_bar mobile_wt_status_bar_absolute'></div>
<div class='mobile_wt_title_bar mobile_wt_title_bar_absolute'>
<a class='transpart_back' ></a>
<span id='mobile_wt_title_bg' class='space_title'><h1 class="sub_call"></h1>Prototype Team<i class='arrow' id='mobile_wt_title_arrow'></i></span>
</div>
<div class='mobile_wt_card' id='mobile_wt_card'></div>
<div class='mobile_wt_card_shadow' id='mobile_wt_card_shadow'></div>
<div class='mobile_wt_message_content' id='mobile_wt_message_content'></div>
</div>
<div id="demo1" class='flex_none'></div>
<!--demo1-->
```
```
//demo1
var mobile_tBg= document.getElementById('mobile_wt_title_bg'),
mobile_tArrow = document.getElementById('mobile_wt_title_arrow'),
mobile_card = document.getElementById('mobile_wt_card'),
mobile_shadow = document.getElementById('mobile_wt_card_shadow'),
mobile_content = document.getElementById('mobile_wt_message_content');
var ashArgs = [{
tag:'ball_container',
dom:mobile_card,
css:[{top:'-641px'},{top:'0px'}],
time:30,
tween:"easeOut"
},{
tag:'title_container',
dom:mobile_tBg,
css:[{'background-color':'rgba(255,255,255,0.4)'},{'background-color':'rgba(231,235,235,1)'}],
time:30,
tween:'rgbaLinear'
},{
tag:'ball_container',
dom:mobile_card,
css:[{opacity:0},{opacity:1}],
time:20
},{
tag:'arrow',
dom:mobile_tArrow,
css:[{'transform':'rotateX(0deg)'},{'transform':'rotateX(180deg)'}],
time:10
},{
tag:'call_panel',
dom:mobile_content,
css:[{transform:'scale(1)'},{transform:'scale(0.96)'}],
time:20,
delay:10,
tween:"easeIn"
},{
tag:'shadow',
dom:mobile_shadow,
css:[{opacity:0},{opacity:1}],
delay:10,
time:20
}];
/*
,{
notRender:true,
tag:'shadow',
dom:mobile_shadow,
css:[{opacity:0},{opacity:0}],
time:0
},{
notRender:true,
tag:'arrow',
dom:mobile_tArrow,
css:[{'transform':'rotateX(0deg)'},{}],
time:0
}
*/
var ashChartInstance = new AshChart('demo1',ashArgs,{
canvasWidth:900,
IfRow:true,
actionsCon:mobile_tBg,
actions:{
click:[{
delay:0,
position:{
x:50,
y:6
}
}]
}
});
ashChartInstance.sync();
ashChartInstance.start();
//demo1
```
demo1
## Desktop
```
<!--demo2-->
<div class='desktop_wt_con fake_chat_con'>
<div class='desktop_title_con' id='desktop_title_con'>
<span class='space_title' id='desktop_space_title'><h1 class="sub_chat"></h1>Prototype Team<i class='arrow' id='desktop_space_title_arrow'></i></span>
<h1>Engineering</h1>
</div>
<div class='fake_activity_con' id='fake_activity_con'></div>
</div>
<div id="demo2"></div>
<!--demo2-->
```
```
//demo2
var desktop_title_con= document.getElementById('desktop_title_con'),
desktop_space_title = document.getElementById('desktop_space_title'),
desktop_tArrow = document.getElementById('desktop_space_title_arrow'),
desktop_activity_con = document.getElementById('fake_activity_con');
var ashArgs2 = [{
tag:'ball_container',
dom:desktop_activity_con,
css:[{top:'-576px'},{top:'0px'}],
time:30,
tween:"easeOut"
},{
tag:'title_container',
dom:desktop_space_title,
css:[{'background-color':'rgba(255,255,255,0.4)'},{'background-color':'rgba(231,235,235,1)'}],
time:30,
tween:'rgbaLinear'
},{
tag:'ball_container',
dom:desktop_activity_con,
css:[{opacity:0},{opacity:1}],
time:20
},{
tag:'arrow',
dom:desktop_tArrow,
css:[{'transform':'rotateX(0deg)'},{'transform':'rotateX(180deg)'}],
time:10
},{
tag:'title_bar',
dom:desktop_title_con,
css:[{'border-bottom-color':'rgba(0,0,0,0.08)'},{'border-bottom-color':'rgba(0,0,0,0)'}],
time:10,
tween:"rgbaLinear"
}];
var ashChartInstance2 = new AshChart('demo2',ashArgs2,{
actionsCon:desktop_space_title,
actions:{
click:[{
delay:0,
position:{
x:80,
y:6
}
}]
}
});
ashChartInstance2.sync();
ashChartInstance2.start();
//demo2
```
demo2<file_sep>Title: Chrome's Mobile Simulator
SortIndex: 3
Cover: guide/ChromeSimulator1.png
Author: <NAME>
---
The Chrome on Mac OS / Windows offers a mobile simulator. You can preview how the prototype is on the real mobile devices according to this simlator.
# Open the simulator
The following steps show how to open the mobile simulator in Chrome
1) Open the develtop tools

2) Click the simulator button

# Select the device
The simulator allows user to change its size and rotate the device.

<file_sep>Title: Welcome Page's Animation on IOS
Desc: This prototype is try to explore the welcome page's animation on IOS.
Date: 2014-12-1
Cover: prototypes/cover/Welcome Page Animation on IOS.png
Author: <NAME>
---
#### Web Pages
[https://uxprototype.cisco.com/projects/Reskin/wap/ios7/pages/welcome.php](https://uxprototype.cisco.com/projects/Reskin/wap/ios7/pages/welcome.php)
[https://uxprototype.cisco.com/projects/Reskin/wap/ios7/pages/welcomeA.php](https://uxprototype.cisco.com/projects/Reskin/wap/ios7/pages/welcomeA.php)
[https://uxprototype.cisco.com/projects/Reskin/wap/ios7/pages/welcomeG.php](https://uxprototype.cisco.com/projects/Reskin/wap/ios7/pages/welcomeG.php)
[https://uxprototype.cisco.com/projects/Reskin/wap/ios7/pages/welcomeP.php](https://uxprototype.cisco.com/projects/Reskin/wap/ios7/pages/welcomeP.php)
# Instuctions

1) Make sure you are under Cisco's network, otherwise please use **VPN**.
2) You can launch this prototype through the following ways:
a. Open the prototype in Chrome's mobile simulator. Click [here](../guide/chrome's-mobile-simulator.html) to get more.
b. Install the prototype on your iPhone as a web app. Click [here](../guide/install-web-app.html) to learn more about this method.
3) Try to swipe on the screen.
# Goals
This prototype is try to explore the welcome page's animation on IOS.
<file_sep>Title: Video animation
Desc: This prototype is to explore the animation when new people enter the people.
Date: 2016-1-8
Cover: prototypes/cover/Video animation.png
Author: <NAME>
---
#### Web Pages
[https://uxprototype.cisco.com/projects/Reskin/wap/thin/views/queue.php](https://uxprototype.cisco.com/projects/Reskin/wap/thin/views/queue.php)
[https://uxprototype.cisco.com/projects/Reskin/wap/thin/views/queue2.php](https://uxprototype.cisco.com/projects/Reskin/wap/thin/views/queue2.php)
[https://uxprototype.cisco.com/projects/Reskin/wap/thin/views/queue3.php](https://uxprototype.cisco.com/projects/Reskin/wap/thin/views/queue3.php)
[https://uxprototype.cisco.com/projects/Reskin/wap/thin/views/queue4.php](https://uxprototype.cisco.com/projects/Reskin/wap/thin/views/queue4.php)
# Instuctions

1) Make sure you are under Cisco's network, otherwise please use **VPN**.
2) Please use Chrome to view the prototype.
3) Use the hidden '+' or '-' button on the top left corner to add/remove people.
# Goals
This prototype is to explore the animation when new people enter the people.
<file_sep>Title: Guide
Desc: Guide
---
# Activity Menu
TBD<file_sep>Title: Install Web App
SortIndex: 2
Cover: guide/InstallWebAppIOS1.PNG
Author: <NAME>
---
To achieve the best experience of our mobile prototypes, we recommand you installing the prototypes as web apps on your mobile devices.
# Install web apps on iPhone
The following steps show how you can install web apps on your iPhone.
1) Open the prototype in Safari.

2) Click the share button on the bottom-middle of Safari. Then click the button 'Add to Home Screen'.

3) You can update the web app's name if you want. Then click 'Add'.

4) Now you can find the web app on the desktop.

5) Play the prototype just as the native app.<file_sep>Title: (Desktop) IA User Testing
Desc: User testing for multiple features in the new IA
Date: 2018-01-23
Cover: prototypes/cover/IA-user-testing.png
---
# Summary
With the desktop prototype, we tested the following features in different user testing sessions, each with 4 to 6 participants. All participants have prior experience with web conferencing tools such as Skype for Business, Webex, and Gotomeetings. The tasks including Frist time experiece (FTE), use phone for audio (PSTN), scheduling flow, and the filter functions
We also tested the idea of "team" and "space" to see whether the design fits the users mental model. Most users were able to utilize the filter to facilitate the Team, but the "team" v.s. "space" idea still seemed confusing to others.
In tasks testing whether the users understand the global scheduling function v.s. the in-space scheduling function, we found that most users tend to schedule the meeting from existing spaces, rather than starting with the global activity button.
In the task testing the invite people function, most users first clicked on the global action button since that was the most familiar button to them right after the FTE. No users thought about finding the invite function under "Mystuff" in the first try. The in-meeting panel and roster seemed to also match users' mental model without much struggle. The filter was however not an easy to find feature, that almost all testee missed it on the first try.
# Links

### Desktop
[https://uxprototype.cisco.com/projects/Reskin/wap/IA/IA-UserTesting.html](https://uxprototype.cisco.com/projects/Reskin/wap/IA/IA-UserTesting.html)
# Platform

# Instructions
## On Desktop
1) Use Chrome browser to view the prototype to see the self-view video working
2) Choose Day 1 to test first time experience (FTE)
3) Choose Day 2 to experience OBPT, PSTN (press 1 to trigger OBTP), and joining a team space
# Key Findings
1) Users defined Cisco Spark as a collaboration tool
2) Confusion still exists in diffrienciating "Space" v.s. "Activities"
3) Switching spaces during a call caused confusion for first time users
4) Join meeting with video fits the users' mental model
5) Join with audio, especially in PSTN situation confused the users
6) Team v.s. Space concept is confusing to some users
7) Global scheduling didn't get to utilize as much as the users tend to schedule the meetings within space
8) The users understand where to find "meetings" under "My Stuff" on desktop
9) Filter under search was hard to find for the testees
10) Most users clicked on global action button first when being asked to invite more users to join Cisco Spark
# User Testing
## Tested Features:
**Desktop**
1) Coachmarks (First use scenario) - whether people read the coachmarks and whether the coachmarks help them to navigate through the app easier **(feature not shown in this current PT)**
2) Global v.s. Local activities concept
3) Getting to understand how easy/difficult it is for the users to contact someone through the app as a first-time user
4) Overall experience for OBTP and PSTN
5) OBTP Toast - Whether the toast makes sense to the users
6) Filters - Discoverablility and whether the user understand the concept differences between teams and spaces
7) Scheduling - Global scheduling v.s. In-space scheduling
8) Meeting List / My Stuff
9) New In-meeting panel
10) Invite people to Cisco Spark
11) New Search/Filter Interface
## Test 1 Session Recording Links (Main focus: FTE)
* [Findings Report](https://cisco.box.com/s/rcqgx7ka4i5rtcaus9smu39uqr1qfd8f)
1. [https://go.webex.com/go/lsr.php?RCID=b595e0d316d841c3b6b13840a6cb294c](https://go.webex.com/go/lsr.php?RCID=b595e0d316d841c3b6b13840a6cb294c)
2. [https://go.webex.com/go/lsr.php?RCID=bcd2e8e9bd5249f9a9995f8baaab2858](https://go.webex.com/go/lsr.php?RCID=bcd2e8e9bd5249f9a9995f8baaab2858)
3. [https://go.webex.com/go/lsr.php?RCID=6e3b417673304e6faf438049554f1870](https://go.webex.com/go/lsr.php?RCID=6e3b417673304e6faf438049554f1870)
4. [https://go.webex.com/go/lsr.php?RCID=fde8d0c24de5447ca3bf63befde4d2f2](https://go.webex.com/go/lsr.php?RCID=fde8d0c24de5447ca3bf63befde4d2f2)
5. [https://go.webex.com/go/lsr.php?RCID=9b2955deca28446a8972ab888d971277](https://go.webex.com/go/lsr.php?RCID=9b2955deca28446a8972ab888d971277)
6. [https://go.webex.com/go/lsr.php?RCID=4cf90d3b58a34afc84264d497ecdef70](https://go.webex.com/go/lsr.php?RCID=4cf90d3b58a34afc84264d497ecdef70)
## Test 2 Session Recording Links (Main Focus: OBPT and PSTN)
* [Findings Report](https://cisco.box.com/s/big9wpavpcl8mrw78b17vi4o5pbky4cm)
1. [https://go.webex.com/go/lsr.php?RCID=49d0cfe29ca8434b9b167e8600cf3aaa](https://go.webex.com/go/lsr.php?RCID=49d0cfe29ca8434b9b167e8600cf3aaa)
2. [https://go.webex.com/go/lsr.php?RCID=12cd885009574440b1b41b74c4df9d92](https://go.webex.com/go/lsr.php?RCID=12cd885009574440b1b41b74c4df9d92)
3. [https://go.webex.com/go/lsr.php?RCID=00f33893c79747f4a8fe2a34d2252b98](https://go.webex.com/go/lsr.php?RCID=00f33893c79747f4a8fe2a34d2252b98)
4. [https://go.webex.com/go/lsr.php?RCID=6181271aaeba44a39f926e62783e946f](https://go.webex.com/go/lsr.php?RCID=6181271aaeba44a39f926e62783e946f)
## Test 3 Desktop Filters/Scheduling/Meeting List
(password: <PASSWORD>)
1. [https://cisco.webex.com/cisco/lsr.php?RCID=55f93b3bec7910f34a9c6bb826eb640f](https://cisco.webex.com/cisco/lsr.php?RCID=55f93b3bec7910f34a9c6bb826eb640f)
2. [https://cisco.webex.com/cisco/lsr.php?RCID=2a1c7b8d75176cceccf0ce9f66f9dc0c](https://cisco.webex.com/cisco/lsr.php?RCID=2a1c7b8d75176cceccf0ce9f66f9dc0c)
3. [https://cisco.webex.com/cisco/lsr.php?RCID=ee902ef41a0b8a661ce7b2a3d542a95e](https://cisco.webex.com/cisco/lsr.php?RCID=ee902ef41a0b8a661ce7b2a3d542a95e)
4. [https://cisco.webex.com/cisco/lsr.php?RCID=1a4d22cda1852fb9569557ba6a3bc569](https://cisco.webex.com/cisco/lsr.php?RCID=1a4d22cda1852fb9569557ba6a3bc569)
5. [https://cisco.webex.com/cisco/lsr.php?RCID=3064010ee4c7608b93eb60e478815511](https://cisco.webex.com/cisco/lsr.php?RCID=3064010ee4c7608b93eb60e478815511)
6. [https://cisco.webex.com/cisco/lsr.php?RCID=590a18ac8948dbf8abd734c2eaf3cfbb](https://cisco.webex.com/cisco/lsr.php?RCID=590a18ac8948dbf8abd734c2eaf3cfbb)
## Test 4 FTE / Invite New User / Search and Filter / New In-meeting Panel
1. [https://cisco.box.com/s/ldhtxqf2bynb73zytzb44vtckdp0z9t1](https://cisco.box.com/s/ldhtxqf2bynb73zytzb44vtckdp0z9t1)
2. [https://cisco.box.com/s/vxs66ayr0dm8wpy3po64s0pjejjpqmko](https://cisco.box.com/s/vxs66ayr0dm8wpy3po64s0pjejjpqmko)
3. [https://cisco.box.com/s/n2eg9es3qqlmpyohs9jjnlnesl7k0ur7](https://cisco.box.com/s/n2eg9es3qqlmpyohs9jjnlnesl7k0ur7)
4. [https://cisco.box.com/s/6x2jlhscqh85hchscqqtbkyly927t4fe](https://cisco.box.com/s/6x2jlhscqh85hchscqqtbkyly927t4fe)
5. [https://cisco.box.com/s/sot7v9n9i6boydh7c22xozkz9atmbib9](https://cisco.box.com/s/sot7v9n9i6boydh7c22xozkz9atmbib9)
6. [https://cisco.box.com/s/cr7dw41ec5feuygfxs8b0edq8cre6qiz](https://cisco.box.com/s/cr7dw41ec5feuygfxs8b0edq8cre6qiz)
7. [https://cisco.box.com/s/qbc10kldvncarxxobl2qghk1ayh42jc6](https://cisco.box.com/s/qbc10kldvncarxxobl2qghk1ayh42jc6)
<file_sep>Title: Search
Desc: Search
---
## Search Bar
### Focus on input box
```
<!--demo1-->
<div class='search_con flex_none' id='search_con'>
<a id='search_avatar' class='avatar'></a>
<input id='search_input' disabled="disabled" type='text' />
<a id='search_add' class='search_add'></a>
<span id='search_cancel'>cancel</span>
<i id='search_magnifier' class='search_magnifier'></i>
</div>
<div id="demo1" class='flex_none'></div>
<!--demo1-->
```
```
/*demo1*/
.search_con{width:375px; height:56px; position:relative; background:#3F3943;}
.search_con>a{position: absolute; top: 6px; display: block; height: 44px; line-height: 44px; text-align: center; width: 44px; border-radius: 50%;}
.search_con .avatar{left:12px;background:url('../../img/motion/Barbara German.png') no-repeat center; background-size:cover;}
.search_con .search_add{right:12px; background: transparent url('../../img/motion/global_add.svg') no-repeat center;}
.search_con input{border:none; width: 239px; height: 36px; line-height: 36px; position: absolute; top: 10px; right: 68px; background-color: rgba(255,255,255,0.24); border: none; text-indent: 18px; border-radius: 18px; color: white; text-align: left; user-select:none;outline:none;}
.search_con .search_magnifier{ display: block; width: 18px; height: 18px; background: url('../../img/motion/h_search.svg') no-repeat center; position: absolute; top: 19px; left: 178px;}
.search_con>span{display: block; width: 60px; height: 56px; line-height: 56px; position: absolute; top: 0px; right: 4px; color: white;text-align: center; font-size: 17px; opacity:0;}
/*demo1*/
```
```
//demo1
var search_con = document.getElementById('search_con'),
search_avatar = document.getElementById('search_avatar'),
search_input = document.getElementById('search_input'),
search_add = document.getElementById('search_add'),
search_cancel = document.getElementById('search_cancel'),
search_magnifier = document.getElementById('search_magnifier');
var ashArgs = [{
tag:'avatar',
dom:search_avatar,
css:[{opacity:1},{opacity:0}],
time:10
},{
tag:'input',
dom:search_input,
css:[{'width':'239px'},{'width':'295px'}],
time:10
},{
tag:'magnifier',
dom:search_magnifier,
css:[{left:'178px'},{left:'21px'}],
time:10,
tween:"easeInOut"
},{
tag:'icon_more',
dom:search_add,
css:[{'opacity':1},{'opacity':0}],
time:10,
tween:"easeInOut"
},{
tag:'btn_cancel',
dom:search_cancel,
css:[{opacity:0},{opacity:1}],
time:10,
tween:"easeInOut"
}];
var ashSearchInstance = new AshChart('demo1',ashArgs,{
actionsCon:search_con,
actions:{
click:[{
delay:0,
position:{
dom:search_input,
x:10,
y:6
}
}]
}
});
ashSearchInstance.sync();
ashSearchInstance.start();
//demo1
```
demo1
<file_sep>Title: Waiting Experience
Desc: This prototype is to explore the waiting experience for WebEx Personal Meeting Room.
Date: 2015-11-8
Cover: prototypes/cover/Waiting Experience.png
Author: <NAME>
---
#### Web Pages
[https://uxprototype.cisco.com/projects/Reskin/wap/waitingbc/pages/PR_V1_2.php](https://uxprototype.cisco.com/projects/Reskin/wap/waitingbc/pages/PR_V1_2.php)
[https://uxprototype.cisco.com/projects/Reskin/wap/waitingbc/pages/PR_V2.php](https://uxprototype.cisco.com/projects/Reskin/wap/waitingbc/pages/PR_V2.php)
[https://uxprototype.cisco.com/projects/Reskin/wap/waitingbc/pages/PR_V1_2.php](https://uxprototype.cisco.com/projects/Reskin/wap/waitingbc/pages/PR_V1_2.php)
[https://uxprototype.cisco.com/projects/Reskin/wap/waitingbc/pages/video.php](https://uxprototype.cisco.com/projects/Reskin/wap/waitingbc/pages/video.php)
# Instuctions

1) Make sure you are under Cisco's network, otherwise please use **VPN**.
2) Please use Chrome to view the prototype.
# Goals
This prototype is to explore the waiting experience for WebEx Personal Meeting Room.
<file_sep>Title: WebEx on WP8
Desc: This prototype is the first prototype for Webex on WP8.
Date: 2014-12-1
Cover: prototypes/cover/WebEx on WP8.png
---
#### Web Page
[https://uxprototype.cisco.com/projects//wp8/v2/](https://uxprototype.cisco.com/projects//wp8/v2/)
# Instuctions

1) Make sure you are under Cisco's network, otherwise please use **VPN**.
2) You can launch this prototype through the following ways:
a. Open the prototype in Chrome's mobile simulator. Click [here](../guide/chrome's-mobile-simulator.html) to get more.
b. Install the prototype on your iPhone or Window Phone as a web app. Click [here](../guide/install-web-app.html) to learn more about this method.
# Goals
This prototype is the first prototype for Webex on WP8.
<file_sep>Title: (Mobile) IA User Testing
Desc: User testing for notification and meeting list for mobile new IA
Date: 2018-01-24
Cover: prototypes/cover/IA Notification And Meeting.png
IS_DRAFT: true
---
# Summary
For the mobile prototype, we had on-site testees to test the new IA navigation. With a lot less elements available in the new IA (comparing to the existing app), some users found it took them longer to navigate through the app smoothly. We also tested the idea of jumping in and out of a spaces for different tasks.
We also updated the latest mobile prototype (first link below) to MVVM (Model–View–ViewModel) mode. This update allows more than one user to interact with each other using the chat function.
# Links

### Mobile
[https://uxprototype.cisco.com/projects/Reskin/wap/IAM_P2/page/spark.html](https://uxprototype.cisco.com/projects/Reskin/wap/IAM_P2/page/spark.html)
Phase 1 version
[https://uxprototype.cisco.com/projects/Reskin/wap/IAM_P2/page/spark.html](https://uxprototype.cisco.com/projects/Reskin/wap/IA2-P1/page/spark.html)
## Sign in as different users
Change the parameter 'user' to switch user. Default value is ‘<NAME>’. Available user account list is at the buttom of the page.
eg. sign in as ‘<NAME>’ (%20 = space)
[https://uxprototype.cisco.com/projects/Reskin/wap/IAM_P2/page/spark.html?**user=Linda%20Sinu**](https://uxprototype.cisco.com/projects/Reskin/wap/IAM_P2/page/spark.html?user=Linda%20Sinu)
## Use private session to test prototype
Change the parameter 'key' to switch session. Default value is ‘public’. You can use any text string as for 'key' value.
When using a specified session, the conversation will not be viewable to the public session (or any other sessions that don't share the same key name).
eg. use session 'private'
[https://uxprototype.cisco.com/projects/Reskin/wap/IAM_P2/page/spark.html?user=<NAME>**&key=private**](https://uxprototype.cisco.com/projects/Reskin/wap/IAM_P2/page/spark.html?user=Linda%20Sinu&key=private)
## Choose the initial data
Use the parameter 'initMode' to force the data to update
If the parameter 'initMode' equals 1, the prototype will init the data for day1
If the parameter 'initMode' equals 2, the prototype will init the data for day2
If you do not use the parameter 'initMode', the prototype will use the data from database or init the data for day1
eg. init the data for day1
[https://uxprototype.cisco.com/projects/Reskin/wap/IAM_P2/page/spark.html?**initMode=1**](https://uxprototype.cisco.com/projects/Reskin/wap/IAM_P2/page/spark.html?initMode=1)
# Platform

# Instructions
## On Mobile
1) You can visit this prototype by using Chrome(Mobile Simulator) or installing it as a web app on iOS devices (The prototype currently only works for 4.7" and 5.5" devices)
*[How to use Chrome Mobile Simulator](https://uxccds.github.io/prototypes/faq/chrome's-mobile-simulator.html)*
*[How to Install Web App](https://uxccds.github.io/prototypes/faq/install-web-app.html)*
* For phase 1 version
1) The users can experience the brief sign-on flow and get to the Day1 Scenario.
2) Long tap (at least 2 seconds) on the empty space in Day 1 view (or move cursor if using a browser Simulator) to get to the Day 2 flow.
3) Note to Simulator users: element alignment might be slightly off in the simuulator, as we modified the prototype to adapt to a better experience on iOS devices.
# Key Findings
1) The users knows where to find "meetings" under "My Stuff" on the mobile interface
2) Mobile navigation seemed confusing at times when the users were asked to perform out-of-space tasks (e.g. chat) during a call
## Tested Features:
1) Navigation
2) Global v.s In-Space activities
3) My Stuff and teams
## Test 1 Mobile Navigation
* [Findings Report](https://cisco.box.com/s/1hwhuw38s1yty9tqdz1thee214dfylli)
1. [https://cisco.box.com/s/bvb5bt3q12zrfj8bzeuhhrdr2tg5pf0h](https://cisco.box.com/s/bvb5bt3q12zrfj8bzeuhhrdr2tg5pf0h)
2. [https://cisco.box.com/s/mty0mkiqdw3y9usul22pzu1nf55gzu67](https://cisco.box.com/s/mty0mkiqdw3y9usul22pzu1nf55gzu67)
3. [https://cisco.box.com/s/zcp226m80k72s0a0avq2bhnz607dx8kp](https://cisco.box.com/s/zcp226m80k72s0a0avq2bhnz607dx8kp)
4. [https://cisco.box.com/s/utftbss2vlnoqafi2n7huttizlzii6ko](https://cisco.box.com/s/utftbss2vlnoqafi2n7huttizlzii6ko)
5. [https://cisco.box.com/s/pzc71oezu0zxa7r9w335ypnb1dxkoe6q](https://cisco.box.com/s/pzc71oezu0zxa7r9w335ypnb1dxkoe6q)
## Test 2 Navigation / Meeting List / Schadule Meeting
1. [https://cisco.box.com/s/ezp9a5uhkdoayttd8wo4z0ya3iepdt12](https://cisco.box.com/s/ezp9a5uhkdoayttd8wo4z0ya3iepdt12)
2. [https://cisco.box.com/s/ladpqrebtz197keq5q5r06bukhpk0evh](https://cisco.box.com/s/ladpqrebtz197keq5q5r06bukhpk0evh)
3. [https://cisco.box.com/s/jq7uym0rcocjgbrysaqjcxwz0n9zzg0e](https://cisco.box.com/s/jq7uym0rcocjgbrysaqjcxwz0n9zzg0e)
4. [https://cisco.box.com/s/2m06w7qhvgo1w4a8cfpllvy761gsge48](https://cisco.box.com/s/2m06w7qhvgo1w4a8cfpllvy761gsge48)
5. [https://cisco.box.com/s/lvyzjubx6imc65o0u83sink22fpdpp1m](https://cisco.box.com/s/lvyzjubx6imc65o0u83sink22fpdpp1m)
6. [https://cisco.box.com/s/crwgmut8q883cb7ocranl1htf16demq3](https://cisco.box.com/s/crwgmut8q883cb7ocranl1htf16demq3)
# Available User Account list
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<file_sep>Title: Spark OBTP 2017
Desc: OBTP prototype.
Date: 2017-1-20
---
# Mobile
## link
[https://uxccds.github.io/SparkMobile/SparkMobileP5/](https://uxccds.github.io/SparkMobile/SparkMobileP5/)
## usage
1) Please use Chrome (mobile mode) or IPhone (webapp mode) to view the prototype.
2) Clear browser cache first if you see any issues.
3) Choose a version to continue.
# Desktop
## link
[https://uxprototype.cisco.com/projects/Reskin/wap/hype/OBTP-Prototype.html](https://uxprototype.cisco.com/projects/Reskin/wap/hype/OBTP-Prototype.html)
## usage
1) Please use Chrome to view this prototype.
# MX
## link
[https://uxccds.github.io/SparkMobile/pair/page/mx.html](https://uxccds.github.io/SparkMobile/pair/page/mx.html)
## usage
1) Please use Chrome to view this prototype.
2) the MX logic for hot key
'0' - go to step 0
'1' - go to step 1 and update the mobile/desktop prototype
'd' - change the scenario to desktop mode
'm' - change the scenario to mobile mode
3) You need add a parameter after the url for both MX prototype and mobile/desktop prototype.
eg:
The link for mobile index page
[https://uxccds.github.io/SparkMobile/SparkMobileP5/?room=public](https://uxccds.github.io/SparkMobile/SparkMobileP5/?room=public)
The link for MX
[https://uxccds.github.io/SparkMobile/pair/page/mx.html?room=public](https://uxccds.github.io/SparkMobile/pair/page/mx.html?room=public)
The parameter's name is 'room'.
The parameter's value should be 'CCDS', 'UE', 'UT', 'private' or 'public'.
4) Only when the mx prototype and mobile/desktop prototype use the same name will they be paired.
<file_sep>Title: WebEx ThinClient
Desc: This prototype is try to explore the full experience for WebEx ThinClient.
Date: 2016-3-1
Cover: prototypes/cover/WebEx ThinClient.png
---
#### With FTE
[https://uxprototype.cisco.com/projects/Reskin/wap/ThinClient/pages/cmr18.php](https://uxprototype.cisco.com/projects/Reskin/wap/ThinClient/pages/cmr18.php)
#### With Waiting Page
[https://uxprototype.cisco.com/projects/Reskin/wap/ThinClient/pages/one.php](https://uxprototype.cisco.com/projects/Reskin/wap/ThinClient/pages/one.php)
# Instuctions

1) Make sure you are under Cisco's network, otherwise please use **VPN**.
2) Please use Chrome to view the prototype.
3) You can press 'shift' + 'enter' to enter the thin client in the waiting page.
4) Hover you mouse onto the top left corner, there are some hidden buttons there.
1. Button '+' and button '-' are used to remove or add people.
2. The other buttons are used in chat panel.
# Goals
This prototype is try to explore the full experience for WebEx ThinClient.
<file_sep>Title: WebEx dashboard on IOS
Desc: This prototype is try to explore the dash for WebEx.
Date: 2015-12-1
Cover: prototypes/cover/WebEx dashboard on IOS.png
---
#### Web Pages
[https://uxprototype.cisco.com/projects/Reskin/wap/ios8/pages/dashboard.php](https://uxprototype.cisco.com/projects/Reskin/wap/ios8/pages/dashboard.php)
[https://uxprototype.cisco.com/projects/Reskin/wap/ios8/pages/dashboard2.php](https://uxprototype.cisco.com/projects/Reskin/wap/ios8/pages/dashboard2.php)
[https://uxprototype.cisco.com/projects/Reskin/wap/ios8/pages/dashboardNF.php](https://uxprototype.cisco.com/projects/Reskin/wap/ios8/pages/dashboardNF.php)
# Instuctions

1) Make sure you are under Cisco's network, otherwise please use **VPN**.
2) You can launch this prototype through the following ways:
a. Open the prototype in Chrome's mobile simulator. Click [here](../guide/chrome's-mobile-simulator.html) to get more.
b. Install the prototype on your iPhone as a web app. Click [here](../guide/install-web-app.html) to learn more about this method.
# Goals
This prototype is try to explore the dash for WebEx.
<file_sep>Title: (Desktop) Design Flagpole
Desc: Our ultimate goal of future design can be found here
Date: 2018-03-27
Cover: prototypes/cover/IA-flagPole01.png
IS_DRAFT: true
---
# Summary
This page marks the latest design goals for Webex Teams (formerly Cisco Spark) desktop app. Our intention is to use this page to serve as a reference of how we plan to design the future Webex Teams.
The link content will be updated regularly.
# Links
### Desktop
[https://uxprototype.cisco.com/projects/Reskin/wap/hype/IA-flagPole.html](https://uxprototype.cisco.com/projects/Reskin/wap/hype/IA-flagPole.html)
Alternative Design (with in-meeting call control interaction exploration):
[https://uxprototype.cisco.com/projects/Reskin/wap/hype/IA-InMeetingNav.html](https://uxprototype.cisco.com/projects/Reskin/wap/hype/IA-InMeetingNav.html)
# Instructions
1) Press key 1 to trigger OBTP
2) Press Alt + P to trigger auto pairing
# Change logs
Date | Section | Notes
--- | --- | ---
Jun-04-2018 | Alternative In Meeting Interaction | New link added for an alternative design where the call controls are laid out differently.
May-10-2018 | Call Flow | Update call flow to work with calling phone number on both global menu and search field
Apr-23-2018 | Onboarding Flow | onboarding flow removed awaiting new updates
Mar-26-2018 | Meeting List | Update meeting details popup to include accordions
Mar-26-2018 | In-meeting roster| Changed in-meeting roster layout and panel behaviors (opens only 1 panel at a time)
Mar-15-2018 | Interstitial | Added avatar bubble heads
Mar-02-2018 | Copy edits | Wording updated to latest copy
Mar-02-2018 | Pairing | Style and behavior update
<file_sep>Title: Spark Space Privacy
Desc: Mobile prototype for space privacy in chatting involved with expernal participants.
Date: 2017-5-11
Cover: prototypes/cover/Spark Space Privacy_Cover.png
---
#### Mobile Prototype
[https://uxccds.github.io/SparkMobile/ExternalParticipant/SpacePrivacy.html](https://uxccds.github.io/SparkMobile/ExternalParticipant/SpacePrivacy.html)
# Instructions

### On Mobile
1) For the most optimal experience, use Chrome (mobile mode) or IPhone (webapp mode) to view this prototype.
2) Select a scenario and continue.
3) If you encounter any issues, clear the browser cache and reload page.
# Goals
This prototype demonstrates when the "external participants" and "privacy" icons are hidden.
1) In scenario A, the "external participants" and "privacy icons" are hidden only when text is near the icons.
2) In scenario B, the "external participants" and "privacy icons" are hidden immediately after the users start typing.<file_sep>Title: Spark OBTP
Desc: Mobile and Desktop OBTP (One Button to Push) prototype.
Date: 2017-1-20
Cover: prototypes/cover/Spark OBTP_Cover.png
---
#### Mobile Prototype
[https://uxccds.github.io/SparkMobile/SparkMobileP5/](https://uxccds.github.io/SparkMobile/SparkMobileP5/)
#### Desktop Prototype
[https://uxprototype.cisco.com/projects/Reskin/wap/hype/OBTP-Prototype.html](https://uxprototype.cisco.com/projects/Reskin/wap/hype/OBTP-Prototype.html)
#### MX800 Prototype
[https://uxccds.github.io/SparkMobile/pair/page/mx.html](https://uxccds.github.io/SparkMobile/pair/page/mx.html)
# Instructions



### On Mobile
1. For the most optimal experience, use Chrome (mobile mode) or IPhone (webapp mode) to view this prototype.
2. Select a scenario and continue.
3. If you encounter any issues, clear the browser cache and reload page.
### On Desktop
1. Please use Chrome browser to view this prototype.
### On MX800
*Disclaimer: This is simulating an experience on the Sparkboard by using a secondary desktop (e.g. Laptop)*
1. From the laptop, run the prototype in Chrome browser and pair/screen shared to a Spark Board
2. Use the following hot keys to navigate through the steps:
* '1' - Trigger the greeting and update the mobile/desktop prototype
* 'd' - Switch to desktop user (Brandon)
* 'm' - Switch to mobile user (Catherine)
3. Add a parameter after the url for both MX prototype and mobile/desktop prototype.
e.g.:
The link for mobile index page
[SparkMobileP5/?room=public](https://uxccds.github.io/SparkMobile/SparkMobileP5/?room=public)
The link for MX
[mx.html?room=public](https://uxccds.github.io/SparkMobile/pair/page/mx.html?room=public)
In this example, the parameter added is 'room'.
The parameter's value can be 'CCDS', 'UE', 'UT', 'private' or 'public'.
4. Only when the mx prototype and mobile/desktop prototype use the same name will they be paired.
<file_sep>Title: Write music with HTML5
Desc: This article will tell you how to write a tune with pure Javascript and introduce an interesting Javascript framework to you.
Date: 2015-2-11
Cover: research/Write a music score by HTML51.jpg
Author: <NAME>
SortIndex: 1
---
## Background
Before a baby opens his eyes, he knows the word by his ears at the very begining. This shows that sound is a very improtant element of interaction. But designers and engineers usually pay more attention to the visual than the sound. As we all know, sound wave is a kind of mechanical wave. By the physical propreties of wave, we can do many interesting things.
## Compose Music
Software engineers are tinking with 1 and 0 to build their utopia while musicians play with music notes to construct their Garden of Eden. It should be fantastical when coding meets with music. Music will enrich the user experience of software, and coding will make people learn more about the struct of music.
A melody consists of a variety of music notes, while time value and pitch are the most important propreties of music notes. In the following paragraph, I will introduce how to create a music note with Javascript.
People can identify music notes of different pitches because every music note has its own frequency. According to the Web Audio Api, we can create an oscillator node. This node can create a sound wave with a specified frequency. You can do some tests refer to the following code.
```
var context = new webkitAudioContext(),
osc = context.createOscillator();
osc.frequency.value = 440;
osc.connect(context.destination);
osc.start(0);
```
The code above created an osicallator with a freqency of 440 hz. According to equal temperament, 440 hz is the frequency of 'LA'. In twelve-tone equal temperament, which divides the octave into 12 equal parts, the width of a semitone, i.e. the frequency ratio of the interval between two adjacent notes, is the twelfth root of two. So we can get the freqency of other notes refer to the following code.
```
var MusicalAlphabet = ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B'],
freqChat={},
freqRange=3,
i,j,base;
for(i=1;i<freqRange;i++){
freqChat[i]={};
base = (i-1)*12;
for(j=0;j<12;j++){
freqChat[i][MusicalAlphabet[j]]=440*Math.pow(2,(base+j-9)/12);
}
}
```
I recommend to calculate all the notes' frequency at the beginning of script. Now, we can get the pitch of every note. The next step is to deal with the time value. The most simple way is to use the function 'stop' and 'start' of the instance of the oscillator node. You can refer to the following code.
```
var context = new webkitAudioContext();
var osc = context.createOscillator();
osc.frequency.value = 440;
osc.connect(context.destination);
var _c = context.currentTime;
osc.start(_c+1);
osc.stop(_c+2);
```
You may have noticed the variable _c . In the context of web audio, it has its own timeline. The property 'currentTime' of context is the only way to access to this timeline. All the nodes of the context play according to this timeline. The funtion 'start' need an argument to define the start time of the oscillator node. If this argument is smaller than contecxt.currentTime, the function 'start' will execute immediately.
Unfortunately, the function 'start' of each instance can only be called only once. It means that once you have called the function 'stop', you will have to create a new instance to play the same note. So I recommand another solution to you. The key is the gain node. With gain node, you can control the signal strength of the osciallator node. If you have ever played the guitar amp, you can understand this node better.

Let's back to the coding world.
```
var context = new webkitAudioContext(),
gain = _ctx.createGain(),
osc = context.createOscillator(),
_c= context.currentTime;
osc.frequency.value =440;
gain.gain.value=0;
osc.connect(gain);
gain.connect(context .destination);
osc.start(_c);
gain.gain.setValueAtTime(1,_c+1);
gain.gain.setValueAtTime(0,_c+2);
```
The code above can play a music note 'La' (at c major) from 1s to 2s. You can set the value of gain.gain.value from 0 to 1. When this value is set to 0, it works like that you call the function 'stop'. The following picture shows the change of the signal.

Besides the function 'setValueAtTime' , gain node has some other methods to change its value. You can find them in the web audio api.
By now, you should be able to play a music note during some time by javascript. But it still has a lot of things to do to achieve a music score. In the following part of this article, I will teach you how to create a music score with a javascript framework named 'Jsonic'.
Play a music score with Jsonic
Jsonic is a small and feature-rich javascript library. With Jsonic, you can compose music, transfer data by ultrasound, make sound wave visualible, do speech recognition and so on. You can get Jsonic from [jsonic.net](https://jsonic.net) jsonic.net or [github](https://github.com/ArthusLiang/jsonic).

The picture above shows the struct of Jsonic's melody module. You need create an instance of Track of TrackGain to play a music score. The music score consists of many notes. Let's move on to the detail code.
### create notes
```
var note = new Jsonic.Melody.Note(1,1/4,0,false);
```
You can create a music note according to the code above. In Jsonic, every instance of Jsonic.Melody.Note refers to a music note. The constructor of Note could accept 4 arguments. The first one is rollcall while the third argument defined which octave this note is in. Jsonic.Melody.Note use rollcall (0,1,2,3,4,5,6,7) to create instances so that you can change the tone in MusicScore easily. If you want to get a central C, the third argument should be 0. The second argument defines the time value(1,1/2,1/4,1/8,1/16) of notes. The speed of MusicScore is another element which affects the real time value of the note .The 4th argument defines whether this note has a dot.
### create music score
```
var musicScore = new Jsonic.Melody.MusicScore('C','major','4/4');
```
When you create an instance of MusicScore, you can define it's tone and beat. The code above create a 4/4 c major music score. You should use musical alphabet here.
After you have created a music score, you could add notes to the music score according to the following code.
```
musicScore.w(new Jsonic.Melody.Note(3),new Jsonic.Melody.Note(4));
```
The function 'w' will append all its arguments to the end of the music score. The next step is to create an instance of Track or TrackGain to play the music score. But you should call the function 'compile' firstly.
```
musicScore.compile();
```
### play music
As what I mentioned at the begining of this atricle, we have two ways to control the time value of notes. Track and TrackGain are corresponding to these two ways.
```
var track = new Jsonic.Melody.Track();
track.play(musicScore,90);
```
The code above created a track and played a music score with the speed 90. The value of the speed refers to the data in metronome.
If you still feel confuse, please click the [demo](http://jsonic.net/demo/index.html). (Click the start button)
## Summary
Web audio offers a lot of nodes. You can connect them to here and there. It is like playing the guitar amp. Hope you can find some interesting effects with web audio.<file_sep>Title: Activity Menu Mobile
Desc: Activity Menu Mobile
---
## Open Activity Menu
```
<!--demo1-->
<div class='mobile_wt_con flex_none' id='mobile_con'>
<div class='mobile_bg_call'></div>
<div class="mobile_wt_status_bar mobile_wt_status_bar_absolute"></div>
<div class='mobile_activity_balls_con' id='mobile_activity_balls_con' style='opacity:0'>
<div class='mobile_activity_balls_message'><a><i></i></a><span>Message</span></div>
<div class='mobile_activity_balls_call'><a><i></i></a><span>Call</span></div>
<div class='mobile_activity_balls_whiteboard'><a><i></i></a><span>Whiteboard</span></div>
<div class='mobile_activity_balls_meetings'><a><i></i></a><span>Meetings</span></div>
<div class='mobile_activity_balls_files'><a><i></i></a><span>Files</span></div>
<div class='mobile_activity_balls_info'><a><i></i></a><span>Info</span></div>
</div>
<div class='btn_activity_back' id='btn_activity_back'></div>
<div class='btn_activity_menu' id='btn_activity_menu'></div>
</div>
<div id="demo1" class='flex_none'></div>
<!--demo1-->
```
```
//demo1
var btn_activity_menu = $('#btn_activity_menu'),
btn_activity_back = $('#btn_activity_back'),
mobile_activity_balls_con = $('#mobile_activity_balls_con'),
ballsCon = mobile_activity_balls_con.find('>DIV'),
balls = mobile_activity_balls_con.find('>DIV>A'),
ballsText = mobile_activity_balls_con.find('>DIV>SPAN'),
mobile_con = $('#mobile_con')[0],
ballsTag = ['message','call','whiteboard','meetings','files','info'];
var AshBallsEnter = [],
_delay=0,
_ballDelay={
0:2,
1:1,
2:0,
3:3,
4:2,
5:1
};
for(var _i=0 ;_i<ballsTag.length;_i++){
_delay = _ballDelay[_i]*4;
AshBallsEnter = AshBallsEnter.concat([{
tag:ballsTag[_i]+'_ball',
dom:balls[_i],
css:[{transform:'scale(0.4)'},{transform:'scale(1)'}],
time:16,
delay:_delay,
tween:'easeIn'
},{
tag:ballsTag[_i]+'_container',
dom:balls[_i],
css:[{opacity:0},{opacity:1}],
delay:_delay,
time:4
},{
notRender:true,
dom:balls[_i],
css:[{opacity:0},{opacity:0}],
time:1
}]);
}
var MenuBtn = function(dom,closeDelay,needRender){
this.Dom = dom;
this.Dot =[];
this.CloseDelay = closeDelay || 0;
this.W = 44;
this.H = 44;
this.DotR = 2;
this.DotD = 4;
this.DotMargin = 4;
this.Margin = this.DotD+this.DotMargin;
this.NeedRender = !needRender;
this.XLen = Math.ceil((this.DotD*3+this.DotMargin*2)*Math.sqrt(2));
var areaLine = 3*this.DotD+2*this.DotMargin;
this.X = (this.W-areaLine)/2>>0;
this.Y = (this.H-areaLine)/2>>0;
this.init();
};
MenuBtn.prototype={
init:function(){
var me = this;
for(var i=0;i<9;i++){
this.createDot(i);
}
this.AshArrayEnter = this.getAshE(1).concat(this.getAshE(3)).concat(this.getAshE(5)).concat(this.getAshE(7)).concat([{
dom:me.Dom,
tag:'dot_container',
notRender:me.NeedRender,
time:8,
css:[{transform:'rotate(0deg)'},{transform:'rotate(90deg)'}]
}]);
this.AshArrayLeave = this.getAshE(1,true).concat(this.getAshE(3,true)).concat(this.getAshE(5,true)).concat(this.getAshE(7,true)).concat([{
dom:me.Dom,
time:8,
notRender:me.NeedRender,
tag:'dot_container',
delay:me.CloseDelay,
css:[{transform:'rotate(90deg)'},{transform:'rotate(0deg)'}]
}]);
},
getAshE:function(i,ifRerverse){
var me = this,
dom = me.Dot[i],
isOnTop = i===1 || i===7,
t1=10,
t2=10,
ret=[],
func,
arr1;
if(isOnTop){
arr1=[{top:me.getDotTop(i)+'px',opacity:1},{top:me.getDotTop(4)+'px',opacity:0.4}];
}else{
arr1=[{left:me.getDotLeft(i)+'px',opacity:1},{left:me.getDotLeft(4)+'px',opacity:0.4}];
}
if(ifRerverse){
arr1.reverse();
ret.push({
tag:'dot_'+i,
notRender:me.NeedRender,
dom:dom,
css:arr1,
time:t1,
delay:t2+me.CloseDelay,
tween:'cubicEaseOut'
});
if(isOnTop){
ret.push({
notRender:me.NeedRender,
tag:'dot_'+i,
dom:dom,
css:[{width:this.XLen+'px'},{width:this.DotD+'px',transform:'translate(0%,0%) rotate(0deg)',top:me.getDotTop(4)+'px',left:me.getDotLeft(4)+'px'}],
time:t2,
delay:me.CloseDelay,
tween:'cubicEaseOut'
});
}
}else{
ret.push({
notRender:me.NeedRender,
dom:dom,
css:arr1,
time:t1,
tag:'dot_'+i,
tween:'cubicEaseOut'
});
if(isOnTop){
var angle = i===1 ? 45:-45;
ret.push({
notRender:me.NeedRender,
tag:'dot_'+i,
dom:dom,
css:[{transform:'translate(-50%, -50%) rotate('+angle+'deg)',opacity:1,top:me.getDotTop(4)+this.DotR+'px',left:me.getDotLeft(4)+this.DotR+'px',width:this.DotD+'px'},{width:this.XLen+'px'}],
time:t2,
delay:t1,
tween:'cubicEaseOut'
});
ret.push({
tag:'dot_'+i,
notRender:me.NeedRender,
dom:dom,
css:[{top:me.getDotTop(i)+this.DotR+'px',left:me.getDotLeft(i)+this.DotR+'px'},{top:me.getDotTop(i)+this.DotR+'px',left:me.getDotLeft(i)+this.DotR+'px'}],
time:1
});
}
}
return ret;
},
resetDot:function(i){
var dom = $(this.Dot[i]);
dom.css('width','4px').css('transform','translate(0%,0%) rotate(0deg)').css('top',this.getDotTop(i)+'px').css('left',this.getDotLeft(i)+'px').css('opacity',1);
},
reset:function(){
this.Dom.css('transform','rotate(0deg)');
this.resetDot(1);
this.resetDot(3);
this.resetDot(5);
this.resetDot(7);
},
createDot:function(i){
var domI = document.createElement('I'),
jDomI = $(domI);
this.Dom[0].appendChild(domI);
this.Dot.push(jDomI);
jDomI.css('top',this.getDotTop(i)+'px').css('left',this.getDotLeft(i)+'px');
},
getDotTop:function(i){
return this.Y+(i/3>>0)*this.Margin;
},
getDotLeft:function(i){
return this.X+(i%3)*this.Margin;
}
};
var SecondClickTime = 60;
var MBTN = new MenuBtn(btn_activity_menu,SecondClickTime);
var ashOpen = MBTN.AshArrayEnter.concat(AshBallsEnter).concat([{
tag:'button_back',
dom:btn_activity_back,
css:[{opacity:1},{opacity:0}],
time:4
},{
tag:'container_balls',
dom:mobile_activity_balls_con,
css:[{opacity:0},{opacity:1}],
time:4
}]);
var ashClose = MBTN.AshArrayLeave.concat([{
tag:'button_back',
dom:btn_activity_back,
css:[{opacity:0},{opacity:1}],
time:4,
delay:SecondClickTime
},{
tag:'container_balls',
dom:mobile_activity_balls_con,
css:[{opacity:1},{opacity:0}],
time:4,
delay:SecondClickTime
}]);
var ashArgs = ashOpen.concat(ashClose);
var ashChartInstance = new AshChart('demo1',ashArgs,{
canvasWidth:1000,
IfRow:true,
actionsCon:mobile_con,
actions:{
click:[{
delay:0,
position:{
x:339,
y:30
}
},{
delay:SecondClickTime,
position:{
x:339,
y:30
}
}]
}
});
ashChartInstance.sync({},undefined,true);
ashChartInstance.start();
//demo1
```
demo1
## Motion for the button
```
<!--demo2-->
<div class='mobile_wt_con flex_none' style='height:64px;'>
<div class='mobile_bg_call'></div>
<div class="mobile_wt_status_bar mobile_wt_status_bar_absolute"></div>
<div class='btn_activity_back' id='btn_activity_back2'></div>
<div class='btn_activity_menu' id='btn_activity_menu2'></div>
</div>
<div id="demo2" class='flex_none'></div>
<!--demo2-->
```
```
//demo2
var btn_activity_menu2 = $('#btn_activity_menu2'),
btn_activity_back2 = $('#btn_activity_back2');
var MBTN2 = new MenuBtn(btn_activity_menu2,SecondClickTime,true);
var _ashExtra = [{
tag:'button_back',
dom:btn_activity_back2,
css:[{opacity:1},{opacity:0}],
time:4
},{
tag:'button_back',
dom:btn_activity_back2,
css:[{opacity:0},{opacity:1}],
time:4,
delay:SecondClickTime
}];
var ashChartInstance2 = new AshChart('demo2',MBTN2.AshArrayEnter.concat(MBTN2.AshArrayLeave).concat(_ashExtra),{});
ashChartInstance2.sync({},undefined,true);
ashChartInstance2.start();
//demo2
```
demo2
## Select Activity Menu
```
<!--demo3-->
<div class='mobile_wt_con flex_none' id='mobile_con3'>
<div class='mobile_bg_call'></div>
<div class="mobile_wt_status_bar mobile_wt_status_bar_absolute"></div>
<div class='mobile_activity_balls_con' id='mobile_activity_balls_con3'>
<div class='mobile_activity_balls_message'><a><i></i></a><span>Message</span></div>
<div class='mobile_activity_balls_call'><a id='mobile_activity_balls_call' style='z-index:9999'><i></i></a><span id='mobile_activity_balls_call_txt'>Call</span></div>
<div class='mobile_activity_balls_whiteboard'><a><i></i></a><span>Whiteboard</span></div>
<div class='mobile_activity_balls_meetings'><a><i></i></a><span>Meetings</span></div>
<div class='mobile_activity_balls_files'><a><i></i></a><span>Files</span></div>
<div class='mobile_activity_balls_info'><a><i></i></a><span>Info</span></div>
</div>
<div class='btn_activity_back' id='btn_activity_back3' style='opacity:0'></div>
<div class='btn_activity_menu' id='btn_activity_menu3'></div>
<div class='btn_activity_menu' id='btn_activity_menu3_2' style='opacity:0'></div>
</div>
<div id="demo3" class='flex_none'></div>
<!--demo3-->
```
```
//demo3
var btn_activity_menu3 = $('#btn_activity_menu3'),
btn_activity_menu3_2 = $('#btn_activity_menu3_2'),
btn_activity_back3 = $('#btn_activity_back3'),
mobile_con3 = $('#mobile_con3'),
mobile_activity_balls_con3 = $('#mobile_activity_balls_con3');
var MBTN3 = new MenuBtn(btn_activity_menu3,SecondClickTime,true),
_ashTemp3 = new Ash.S(MBTN3.AshArrayEnter),
_ball3 = $('#mobile_activity_balls_call'),
_ball3Icon = _ball3.find('i'),
_ball3Txt = $('#mobile_activity_balls_call_txt');
var MBTN3_2 = new MenuBtn(btn_activity_menu3_2,SecondClickTime,true);
var BigR = Math.ceil(Math.sqrt(375*375+667*667)),
_r0 = BigR/2>>0,
_x0 = 375/2-_r0-136>>0,
_y0 = 667/2-_r0-234>>0;
_ashTemp3.state(_ashTemp3.DeadTime);
var ashArgs3 = [{
tag:'ball_icon',
dom:_ball3Icon,
css:[{opacity:1},{opacity:0}],
time:10
},{
tag:'ball_txt',
dom:_ball3Txt,
css:[{opacity:1},{opacity:0}],
time:10
},{
tag:'ball',
dom:_ball3,
css:[{'background-color':'rgba(46,213,87,1)'},{'background-color':'rgba(255,255,255,1)'}],
tween:'rgbaLinear',
time:20,
},{
tag:'ball',
dom:_ball3,
css:[{width:'68px',height:'68px',left:'13px'},{width:BigR+'px',height:BigR+'px',left:_x0+'px'}],
time:20
},{
tag:'ball',
dom:_ball3,
css:[{top:'0px'},{top:_y0+'px'}],
tween:'easeOut',
delay:4,
time:20
},{
tag:'balls_con',
dom:mobile_activity_balls_con3,
css:[{opacity:1},{opacity:0}],
delay:24,
time:10
},{
notRender:true,
dom:btn_activity_back3,
css:[{opacity:0},{opacity:1}],
delay:24,
time:1
},{
notRender:true,
dom:btn_activity_menu3,
css:[{opacity:1},{opacity:0}],
delay:24,
time:1
},{
notRender:true,
dom:btn_activity_menu3_2,
css:[{opacity:0},{opacity:1}],
delay:24,
time:1
}];
var ashChartInstance3 = new AshChart('demo3',ashArgs3,{
canvasWidth:1000,
IfRow:true,
actionsCon:mobile_con3[0],
actions:{
click:[{
delay:0,
position:{
x:184,
y:264
}
}]
}
});
ashChartInstance3.sync();
ashChartInstance3.start();
//demo3
```
demo3
<file_sep>Title: Activity Menu Desktop
Desc: Activity Menu Desktop
---
## Open Activity Menu
```
<!--demo1-->
<div class='desktop_wt_con flex_none' id='desktop_con'>
<div class='desktop_bg_call'></div>
<div class="desktop_wt_status_bar desktop_wt_status_bar_absolute"></div>
<div class='desktop_activity_balls_con' id='desktop_activity_balls_con'>
<div class='desktop_activity_balls_message'><a><i></i></a><span>Message</span></div>
<div class='desktop_activity_balls_call'><a><i></i></a><span>Call</span></div>
<div class='desktop_activity_balls_whiteboard'><a><i></i></a><span>Whiteboard</span></div>
<div class='desktop_activity_balls_meetings'><a><i></i></a><span>Meetings</span></div>
<div class='desktop_activity_balls_people'><a><i></i></a><span>People</span></div>
<div class='desktop_activity_balls_files'><a><i></i></a><span>Files</span></div>
</div>
<div class='desktop_btn_activity_bg' id='desktop_btn_activity_bg'></div>
<div class='desktop_btn_activity_back' id='desktop_btn_activity_back'></div>
<div class='desktop_btn_activity_menu' id='desktop_btn_activity_menu'></div>
</div>
<div id="demo1" class='flex_none'></div>
<!--demo1-->
```
```
//demo1
var desktop_btn_activity_menu = $('#desktop_btn_activity_menu'),
desktop_btn_activity_back = $('#desktop_btn_activity_back'),
desktop_activity_balls_con = $('#desktop_activity_balls_con'),
ballsCon = desktop_activity_balls_con.find('>DIV'),
balls = desktop_activity_balls_con.find('>DIV>A'),
ballsText = desktop_activity_balls_con.find('>DIV>SPAN'),
desktop_con = $('#desktop_con')[0],
ballsTag = ['message','call','whiteboard','meetings','people','files'];
var AshBallsEnter = [],
_delay=0,
_ballDelay={
0:2,
1:1,
2:0,
3:3,
4:2,
5:1
};
for(var _i=0 ;_i<ballsTag.length;_i++){
_delay = _ballDelay[_i]*4+16;
AshBallsEnter = AshBallsEnter.concat([{
tag:ballsTag[_i]+'_ball',
dom:balls[_i],
css:[{transform:'scale(0.4)'},{transform:'scale(1)'}],
time:72,
delay:_delay,
tween:'elasticEaseOut'
},{
tag:ballsTag[_i]+'_container',
dom:balls[_i],
css:[{opacity:0},{opacity:1}],
time:24,
delay:_delay,
},{
notRender:true,
dom:ballsText[_i],
css:[{opacity:0},{opacity:1}],
time:24,
delay:_delay,
},{
notRender:true,
dom:balls[_i],
css:[{opacity:0},{opacity:0}],
time:1
},{
notRender:true,
dom:ballsText[_i],
css:[{opacity:0},{opacity:0}],
time:1
}]);
}
var MenuBtn = function(dom,closeDelay,needRender){
this.Dom = dom;
this.init();
};
MenuBtn.prototype={
init:function(){
var me = this;
},
};
var SecondClickTime = 120;
var ashOpen = AshBallsEnter.concat([{
notRender:true,
tag:'button_menu',
dom:desktop_btn_activity_menu,
css:[{opacity:0},{opacity:1}],
time:1
},{
notRender:true,
tag:'button_back',
dom:desktop_btn_activity_back,
css:[{opacity:1},{opacity:0}],
time:1
},{
tag:'container_balls',
dom:desktop_activity_balls_con,
css:[{right:'-346px'},{right:'0px'}],
time:20,
tween:'easeInOut'
}]);
var ashClose = [{
notRender:true,
tag:'button_menu',
dom:desktop_btn_activity_menu,
css:[{opacity:1},{opacity:0}],
time:1,
delay:SecondClickTime
},{
notRender:true,
tag:'button_back',
dom:desktop_btn_activity_back,
css:[{opacity:0},{opacity:1}],
time:1,
delay:SecondClickTime
},{
tag:'container_balls',
dom:desktop_activity_balls_con,
css:[{right:'0px'},{right:'-346px'}],
time:20,
tween:'easeInOut',
delay:SecondClickTime
}];
var ashArgs = ashOpen.concat(ashClose);
var ashChartInstance = new AshChart('demo1',ashArgs,{
canvasWidth:1000,
IfRow:false,
actionsCon:desktop_con,
actions:{
click:[{
delay:0,
position:{
x:1042,
y:19
}
},{
delay:SecondClickTime,
position:{
x:1042,
y:19
}
}]
}
});
ashChartInstance.sync({},undefined,true);
ashChartInstance.start();
//demo1
```
demo1
<file_sep>Title: Animation Physics
Cover: research/Animation Physics1.jpg
Author: <NAME>
---
## Background
With the development of computer science technology, people are facing more and more information everyday. The traditional static way to display information can't always make our brains excited in the age of information explosion. In this artcile, I will show your the science behind the general animation.
### Persistence of vision
Persistence of vision refers to the optical illusion that occurs when visual perception of an object does not cease for some time after rays of light proceeding from it have ceased to enter the eye. According this phenomenon, people build animation. In ancient China, people draw a bird and a birdcage on different side of a pan. When you twist the pan, you will see the bird in the birdcage. It's the early application of persistence of vision.
### Television broadcasting system and frame
According to the persistence of vision, people can watch animation if we play a series of images in a very short time. But how short the time is? TV in the era of the use of analog signals, television broadcasting system mainly PAL, NTSC, SECAM three, they were using different frame rates. NTSC requires 25 frames in a second while PAL and SECAM require 25 frames in a second. In lastest monitor can play 240 frame a secord, it bring a better experience of watching animation.
### 3D
3D movie technology has improved sharply in the passing years. The following images will show you why we can see 3d movies.
Red and blue glasses

LCD shutter glasses

Naked eye 3D screen

Whatever the technology we use, the key why we can see 3d movied is our brain. Our brain can merge 2 images into one!
### Acoustics
The early movies are black and white and silent, but the sound is clearly indispensable. The sound also has its 3D world! Our brain can also composite the sound you hear from left ear and right ear. I believe the acoustics is a very big topic so that I'd like to further this topic in the other articles.
## Summary
Thanks to our brains, we can see and hear the 3d world. It is also our brains that give us the feeling of the world.
<file_sep>Title: Firebase
Date: 2016-9-1
Cover: research/Firebase1.png
Author: <NAME>
---
We've done some researchs on how to build connection between devices. Web database is one of the choice. In our current projects, we choose [Firebase](https://firebase.google.com). Firebase saves us a lot of time on coding server end code. So we focus more on the front end coding.
# Prototype
Here is demo with Firebase.
## Desktop
### link
[wall.html](https://uxccds.github.io/SparkMobile/pair/page/wall.html)
### usage
1) Please use Chrome to open this prototype.
2) Wait for the loading and open the mobile protoype when you see the following screen.

## Mobile
### link
[phone.html](https://uxccds.github.io/SparkMobile/pair/page/phone.html)
### usage
1) Use [Chrome mobile simulator](../guide/chrome's-mobile-simulator.html) to view the prototype. You can also install the prototype as [web app](../guide/install-web-app.html) on your iPhone.

2) Click 'All Boards' to the selection page.
3) Select one board.
4) When you do step 2 and step 3, the desktop prototype will do the same thing automatically.
<file_sep>Title: VR View In Meeting
Desc: This prototype is to explore the VR View in WebEx thin client
Date: 2016-6-8
Cover: prototypes/cover/VR View In Meeting.png
Author: <NAME>
---
#### VR for equal view
[https://uxprototype.cisco.com/projects/Reskin/wap/thin/views/equalVR.php](https://uxprototype.cisco.com/projects/Reskin/wap/thin/views/equalVR.php)
#### VR for big video
[https://uxprototype.cisco.com/projects/Reskin/wap/thin/views/equalVRroom.php](https://uxprototype.cisco.com/projects/Reskin/wap/thin/views/equalVRroom.php)
# Instuctions

1) Make sure you are under Cisco's network, otherwise please use **VPN**.
2) Please use Chrome to view the prototype.
3) Use the hidden '+' button on the top left corner to add people. (to 7 videos)
4) Click the play button on video and try to change the view with your mouse.
# Goals
This prototype is to explore the VR View in WebEx thin client
<file_sep>Title: WebGL
Date: 2017-4-19
Cover: research/WebGL2.png
Author: <NAME>
---
WebGL let browsers have the ablility to render 3D things.
# Prototype for WebEx on iwatch
Years ago, Apple was going to publish the iwatch. Our company was asked to build the WebEx app on iwatch. However, we did not have the real iwatch at the early time. So we used WebGL to render a 3D model to display the prototype.
## link (Cisco VPN Required)
[iwatch3d.php](https://uxprototype.cisco.com/projects/Reskin/wap/iwatch_draft/pages/3d.php)
## usage
1) Open the prototype in Chrome.
2) Waiting for loading the 3d model.

3) After the prototype is loaded, you can zoom in/out or turn the iwatch. Drag or Wheel your mouse on the top left corner.

4) Click the WebEx Ball on the iwatch and try to experience it.
# Further More
After that I made a prototype to display all the prototypes I made for windows phone, iPhone, Car, Mac ...
## link (Cisco VPN Required)
[3d.php](https://uxprototype.cisco.com/projects/Reskin/wap/3D/pages/3d.php)
## usage
1) Use the navigation tool on the top left corner to switch models and prototypes.

2) Try to experience the protoypes inside the models.<file_sep>Title: Speech Recognition
Date: 2017-2-19
Cover: research/WebGL3.png
Author: <NAME>
---
#Summary
Speech recognition helps people to free up their hands. It became more and more popular after iPhone 4s has been published.
#### Prototype
We applied speech recongnition to our sparkboard prototypes. Learn more about how this prototype works in normal mode [here](../prototypes/spark-pairing.html).
#### link
[sparkboardpair.html](https://uxccds.github.io/SparkMobile/pair/page/sparkboardpair.html)
# Instructions
1) Open the prototype in Chrome. (Make sure you can connect to Google's server.)
2) Enable Chrome to use your micphone.
3) Try to use the following command. (Just speak!)
| Action | Command |
|:------------------------------------------------|:------------------------------------|
| Reload the prototype and go to the black screen | 'zero','reload','close','sleep' |
| Go to 'Hello' screen | 'one','hello','wake up','hi spark' |
| Go to dashboard | 'two','dashboard','menu','home' |
| Share files | 'three','files','share files' |
| Call | 'four','call' |
| Whiteboard | 'five','whiteboard' |
| Share screen | 'six','share screen' |
4) There may be some lag after you say something.<file_sep>Title: Face Detection.
Desc: This prototype is try to apply the technology of face detection to our product.
Date: 2016-11-1
Cover: research/Face Detection1.png
Author: <NAME>
---
### Web Page
[https://uxprototype.cisco.com/projects/Reskin/wap/PR/views/face.php](https://uxprototype.cisco.com/projects/Reskin/wap/PR/views/face.php)
# Instuctions

1) Make sure you are under Cisco's network, otherwise please use **VPN**.
2) Please use chrome to open this website.
3) Try to click 'Fix' buttons.
### Goals
This prototype is try to apply the technology of face detection to our product.
<file_sep>Title: Spark Message List
Desc: Desktop prototype for Spark message list
Date: 2017-5-11
Cover: prototypes/cover/Spark Message List.png
---
#### Desktop Prototype
[https://uxprototype.cisco.com/projects/Reskin/wap/hype/message-list.html](https://uxprototype.cisco.com/projects/Reskin/wap/hype/message-list.html)
# Instructions

1) Use Chrome browser to view the prototype for the best results.
2) Select "Regular" or "Condensed" view to continue.
3) If you encounter any issues, clear the browser cache and reload page
# Goals
The purpose of the prototype is displaying regular and condensed views of the Spark message list. The following features are:
1) **Pin to top** - Right click on people/spaces conversations to see this function. All pinned messages will show at the top of the list
2) **Tag filters** - These filters only show when relevant conversation status (e.g. unread, @mention, or draft) are available.
3) **Notification settings** - @mentions or All messages
<file_sep>Title: Spark 2017.1.24
Desc: These spark prototypes were designed for release on 2017.1.24
Date: 2017-1-15
Cover: prototypes/cover/Spark20170124_Cover.png
---
#### Mobile Prototype
[spark.html](https://uxccds.github.io/SparkMobile/SparkMobileP5/spark.html)
#### Desktop Prototype
[Spark-MVO-Prototype-currentBuild.html](https://uxprototype.cisco.com/projects/Reskin/wap/hype/Spark-MVO-Prototype-currentBuild.html)
# Instructions


### On Mobile
1) Please use Chrome (mobile mode) or iPhone (webapp mode) to view the prototype.
2) Try clear browser cache first if you encounter any issue.
### On Desktop
1) Please use Chrome to view this prototype.
<file_sep>Title: WebEx & Spark Help
Desc: This prototype is try to explore scrolling experience of the page.
Date: 2016-4-1
Cover: prototypes/cover/WebEx & Spark Help.png
---
#### Web Page
[https://uxprototype.cisco.com/projects/Reskin/wap/waitingbc/pages/SparkWebEx.html](https://uxprototype.cisco.com/projects/Reskin/wap/waitingbc/pages/SparkWebEx.html)
# Instuctions

1) Make sure you are under Cisco's network, otherwise please use **VPN**.
2) Please use Chrome to view the prototype.
3) Try scroll down or up.
# Goals
This prototype is try to explore scrolling experience of the page.
<file_sep>Title: IA (Phase 1)
Desc: Information Architecture for phase 1 release of Cisco Spark
Date: 2017-8-01
Cover: prototypes/cover/IA phase1.png
IS_DRAFT: true
---

#### Mobile Prototype
[https://uxprototype.cisco.com/projects/Reskin/wap/IA2/page/spark.html](https://uxprototype.cisco.com/projects/Reskin/wap/IA2/page/spark.html)
#### Desktop Prototype
[https://uxprototype.cisco.com/projects/Reskin/wap/IA/IA-phase1.html](https://uxprototype.cisco.com/projects/Reskin/wap/IA/IA-phase1.html)
# Instructions


### On Mobile
1) For the most optimal experience, use Chrome (mobile mode) or IPhone (web app mode) to view this prototype.
2) If you encounter any issues, clear the browser cache and reload page.
3) Input the accout to sign in. (empty or refer to the people list)
4) If there is no space under the accout, you will have to schedule a meeting in a new space.
5) If there are already some spaces under the accout, you can see the space list directly.
6) Use space balls to switch screens in the space.
7) Press 'Enter' after inputting something to send messages in the chat panel.
8) See the meetings you scheduled in the meeting panel.
### On Desktop
1) Use Chrome browser to view the prototype for the best results.
# Goals
To test new design for Spark.
### People list
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<file_sep>Title: Spark P5 2016
Desc: This prototype demonstrates a more defined app style to help the users to adopt the new design more smoothly.
Date: 2016-9-20
Cover: prototypes/cover/Spark P5 2016_Cover.png
---
# Summary
To let the users adapt to our new Spark design more smoothly, the UXCCDS team defined 5 steps to update the Spark app's style. This is the P5 prototype. We use react.js to build this prototype and many parts of this prototypes are based on dynamic data.
#### Prototype Link
[https://uxccds.github.io/SparkMobile/v2/page/p5.html](https://uxccds.github.io/SparkMobile/v2/page/p5.html)
#### Screen shot

# Launching the prototype
You can launch this prototype through the following ways:
1) Open the prototype in Chrome's mobile simulator. Click [here](../guide/chrome's-mobile-simulator.html) to learn more.
2) Install the prototype on your iPhone as a web app. Click [here](../guide/install-web-app.html) to learn more.
# Instructions
1) Click the 'Branding team' 's line to enter its room.
2) Click the activity board's icon on the top-right corner to open it.
3) Click each ball on the activity board to experience each feature.
4) Each room has its own data for the chat panel. You can send messages here and the bot may respond to certain specific terms.
# Goals
This prototype aims to demostrate the following goals:
1) Demostrate the full experience of Spark app.
2) Smoonther transition animation between pages.
3) Apply PIP to Spark.
<file_sep>Title: Collapse List
Desc: Collapse List
---
#### Desktop
```
<!--demo3-->
<video preload="auto" autoplay loop src='../../img_data/motion/realization/CollapseList-MacOS.mov' ></video>
<!--demo3-->
```
demo3
# Description
## Hover On Hand
```
<!--demo2-->
<div id="demo2"></div>
<!--demo2-->
```
```
//demo2
var ashArgs2 = [{
tag: 'List',
dom: {},
css:[{'Position X':'0px'},
{'Position X':'13px'}],
time:30,
msTime:500,
tween:'easeInOut'
}];
var ashChartInstance2 = new AshChart('demo2',ashArgs2,{
IfToMS:true,
waitTime:40
});
ashChartInstance2.start();
//demo2
```
demo2
## Collapse List
```
<!--demo1-->
<div id="demo1"></div>
<!--demo1-->
```
```
//demo1
var ashArgs = [{
tag: 'List',
dom: {},
css:[{width:'400px'},
{width:'0px'}],
time:18,
msTime:300,
tween:'easeOut'
}];
var ashChartInstance = new AshChart('demo1',ashArgs,{
IfToMS:true,
colors:['#BD10E0','#4A90E2'],
waitTime:60
});
ashChartInstance.start();
//demo1
```
demo1<file_sep>Title: (Mobile) Design Flagpole
Desc: Our ultimate goal of future mobile design can be found here
Date: 2018-05-15
Cover: prototypes/cover/IA-flagpole-M.png
IS_DRAFT: true
---

# Summary
This page marks the latest design goals for Webex Teams (formerly Cisco Spark) mobile app. Our intention is to use this page to serve as a reference of how we plan to design the future Webex Teams.
The link content will be updated regularly.
# Links
### Mobile
[https://uxprototype.cisco.com/projects/Reskin/wap/WebexTeams/page/spark.html](https://uxprototype.cisco.com/projects/Reskin/wap/WebexTeams/page/spark.html)
# Change logs
Date | Section | Notes
--- | --- | ---
May-15-2018 | Style update | 1) Visual style update 2) added button for call
May-15-2018 | Call flow | 1) Capability to search people 2) switch tabs
<file_sep>(function(){
var DOC,WIN;
var MapItem = function(dom){
this.Dom = $(dom);
this.DomFloat = $('#tf_'+this.Dom .attr('data-tf'));
this.init();
};
MapItem.prototype={
init:function(){
var me = this;
this.Dom.bind('mouseenter',function(){
me.DomFloat.css('display','');
});
this.Dom.bind('mouseleave',function(){
me.DomFloat.css('display','none');
});
}
};
var WorldMap = function(){
this.Dom = $('#svg_map');
this.Items = $('[data-tf]');
this.init();
};
WorldMap.prototype={
init:function(){
var me = this;
me.resize();
WIN.bind('resize',function(){
me.resize();
});
me.initItems();
},
initItems:function(){
for(var i=0,l=this.Items.length;i<l;i++){
new MapItem(this.Items[i]);
}
},
resize:function(){
var w = this.Dom.width(),
h = 650 / 1008 * w >>0;
this.Dom.css('height',h+'px');
}
};
$(function(){
DOC = $(document);
WIN = $(window);
new WorldMap();
});
})();<file_sep>Title: WebEx Personal Room Page
Desc: This prototype is try to explore the experience when people are waiting for the meeting.
Date: 2016-1-1
Cover: prototypes/cover/WebEx Personal Room Page.png
---
#### Host View
[https://uxprototype.cisco.com/projects/Reskin/wap/PR/views/home.php](https://uxprototype.cisco.com/projects/Reskin/wap/PR/views/home.php)
#### Attendee View
[https://uxprototype.cisco.com/projects/Reskin/wap/PR/views/attendee.php](https://uxprototype.cisco.com/projects/Reskin/wap/PR/views/attendee.php)
# Instuctions

1) Make sure you are under Cisco's network, otherwise please use **VPN**.
2) Please use Chrome to view the prototype.
3) Try to client any button in the prototype.
# Goals
This prototype is try to explore the experience when people are waiting for the meeting.
<file_sep>Title: (Desktop) WebEx Meeting Client
Desc: Testing for new WebEx Meeting Client design
Date: 2018-03-19
Cover: prototypes/cover/WebEx Meeting Client.png
IS_DRAFT: true
---
# Summary
In this user testing session, we tested the WebEx Meeting Client with new UI design and functions.
# Links
### Desktop
Option 1
[https://uxccds.github.io/WebExClient/page/webex.html?usertesting=1](https://uxccds.github.io/WebExClient/page/webex.html?usertesting=1)
Option 2 (Keep the video view switch open)
[https://uxccds.github.io/WebExClient/page/webex.html?usertesting=1&switchon=1](https://uxccds.github.io/WebExClient/page/webex.html?usertesting=1&switchon=1)
# Platform

# Instructions
## On Desktop
1) Press key "+" to add people.
2) Press key "Alt+S" (Win), "Option+S" (Mac) to start/stop sharing.
3) Press key "Alt+C" (Win), "Option+C" (Mac) to show chat messages.
# User Testing
(Coming soon)
<file_sep>Title: Spark Device Pairing
Desc: Mobile and Desktop Spark Prototype featuring the pairing functions
Cover: prototypes/cover/Spark Pairing_Cover.png
---
#### Mobile Prototype
[https://uxccds.github.io/SparkMobile/SparkMobilePairing/sparkMobilePair.html](https://uxccds.github.io/SparkMobile/SparkMobilePairing/sparkMobilePair.html)
#### Desktop Prototype
[https://uxprototype.cisco.com/projects/Reskin/wap/devicepairing-desktop.html](https://uxprototype.cisco.com/projects/Reskin/wap/hype/devicepairing-desktop.html)
#### SparkBoard Prototype
[https://uxccds.github.io/SparkMobile/pair/page/sparkboardpair.html](https://uxccds.github.io/SparkMobile/pair/page/sparkboardpair.html)
# Instructions



### On Mobile
1) For the most optimal experience, use Chrome (mobile mode) or IPhone (webapp mode) to view this prototype.
2) Open the Spark Board prototype and then open the mobile prototype. Press the plus icon on the top right to begin pairing. Click on the blue bar that says, “connecting…” to mimic the prototypes being paired.
3) Select a scenario and continue.
4) If you encounter any issues, clear the browser cache and reload page.
### On Desktop
1) Please use Chrome browser to view this prototype.
2) Open the Spark Board prototype and then open the desktop prototype. Press the search icon on the top right to begin pairing.
3) Select a scenario and continue.
4) If you encounter any issues, clear the browser cache and reload page.
### On Spark Board
*Disclaimer: This is simulating an experience on the Sparkboard by using a secondary desktop (e.g. Laptop)*
1. From the laptop, run the prototype in Chrome browser and pair/screen shared to a Spark Board
2. You can use the following hot keys to get to the screens:
* key space -> black screen
* key 1 -> the 'hello' screen.
* key 2 -> the screen with activity menu
<file_sep>Title: (Desktop) IA Pairing
Desc: A/B Testing for two pairing function placement on Desktop application
Date: 2018-01-14
Cover: prototypes/cover/IA pairing.png
IS_DRAFT: true
---
# Summary
In this user testing session, we tested two versions of pairing function with different element placement
# Links
### Desktop
[https://uxprototype.cisco.com/projects/Reskin/wap/IA-DevicePairingA.html](https://uxprototype.cisco.com/projects/Reskin/wap/hype/IA-DevicePairingA.html)
[https://uxprototype.cisco.com/projects/Reskin/wap/IA-DevicePairingB.html](https://uxprototype.cisco.com/projects/Reskin/wap/hype/IA-DevicePairingB.html)


# Platform

# Instructions
## On Desktop
1) Version A - click on the pairing icon next to the user Avatar, and follow the flow to connect to a device (Toyshop)
2) Version B - Click on the pairing function button at the bottom of the space list, and follow the flow to connect to a device (Toyshop)
# User Testing
(Coming soon)
<file_sep>(function(){
var WIN;
var Banner = function(dom){
this.Dom = $(dom);
this.Con = $(dom.parentNode);
this.BigSignal = 600;
this.SmallSignal = 350;
this.init();
};
Banner.prototype = {
init:function(){
var me=this,
viewbox = this.Dom[0].viewBox.baseVal,
vw = viewbox.width,
vh = viewbox.height;
this.IsBig = vw >700;
this.wh = vw/vh;
WIN.bind('resize',function(){
me.resize();
});
me.resize();
},
resize:function(){
var cw = this.Con.width(),
ch = this.Con.height(),
w,h,l,t;
if((cw<this.BigSignal && this.IsBig) || cw < this.SmallSignal){
this.resizeCover(cw,ch);
}else{
this.resizeContain(cw,ch);
}
},
resizeContain:function(cw,ch){
if(cw/ch>this.wh){
h = ch;
w = h*this.wh>>0;
}else{
w = cw;
h = w/this.wh>>0;
}
l = (cw-w)/2>>0;
t = (ch-h)/2>>0;
this.Dom.css('width',w+'px').css('height',h+'px').css('left',l+'px').css('top',t+'px');
},
resizeCover:function(cw,ch){
if(cw/ch>this.wh){
w = cw-40;
h = w/this.wh>>0;
}else{
h = ch-30;
w = h*this.wh>>0;
}
l = this.IsBig ? cw * 0.05 >>0 : (cw-w)/2>>0;
t = (ch-h)/2>>0;
this.Dom.css('width',w+'px').css('height',h+'px').css('left',l+'px').css('top',t+'px');
}
};
var BannerAnimation = function(con,initAsh){
this.Con = con;
this.Ashes = initAsh();
this.init();
};
BannerAnimation.prototype={
init:function(){
var me=this;
this.Con.bind('mouseenter',function(){
me.play();
});
this.Con.bind('mouseleave',function(){
me.pause();
});
},
play:function(){
var func;
if(this.HasStart){
func = 'continue';
}else{
this.HasStart = true;
func = 'repeat';
}
for(var i=0,l=this.Ashes.length;i<l;i++){
this.Ashes[i][func](Infinity);
}
},
pause:function(){
for(var i=0,l=this.Ashes.length;i<l;i++){
this.Ashes[i].stop();
}
}
};
window.BannerAnimation = BannerAnimation;
$(function(){
WIN = $(window);
var svgs = document.querySelectorAll('[data-svg]');
for(var i=0,l=svgs.length;i<l;i++){
new Banner(svgs[i]);
}
});
})();<file_sep>Title: 360° Camera and VR
Cover: research/360°VR6.PNG
Date: 2017-2-29
Author: <NAME>
---
We started to learn AR/VR technology years ago. It should be able to improve our meeting experience.
# Camera
In order to get VR video, we should take 360° view video at first. We bought [Giroptic's 360cam](https://www.giroptic.com/us/en/360cam) and its PoE Ethernet Adapter Base to set up the IP camera system.

# Streaming server
You can get a RTSP stream from the IP camera directly. However, lots of media player does not support RTSP stream. RTSP is designed for Flash only, so we need a server to convert the stream to other formats.
[Wowza Streaming Engine](https://www.wowza.com/products) is best solution I can find. Here is the dash board for Wowza Stream Enginer.

# Watch the live on iPhone
## 360° View
You can use Insta360Player to watch the 360° live. It's not a sized video any more. You can swipe to choose best view.
### Normal View

### Full Fcreen View

### Zoom Out View

## VR View
If you have any VR glass, you can watch the life in VR mode.


# HTML prototype
It's also possible to display the 360° View video with HTML5. The following is a screenshot for our simple demo.
<file_sep>Title: Calling in Webex Teams
Desc: We are using the word meet for both a meeting and a call in today’s client. This could be confusing to the end user. Now that calling is becoming a significant part of the client the difference in a call and meeting is even more important.
Date: 2018-08-23
Cover: prototypes/cover/Calling in Webex Teams.png
IS_DRAFT: true
---
# Summary
๏ We are using the word meet for both a meeting and a call in today’s client. This could be confusing to the end user.
๏ Now that calling is becoming a significant part of the client the difference in a call and meeting is even more important.
๏ Use of the video Icon for ‘meet’ is confusing. A call or a meeting can have both video and audio.
Our research objective is to evaluate and understand users perception of what a call versus a meeting is in the Webex Teams app and to gain insight into what direction the Teams client is to take when adopting Unified Calling capabilities.
# Links
[https://uxprototype.cisco.com/projects/Reskin/wap/MeetVsCall/MeetVSCall.html](https://uxprototype.cisco.com/projects/Reskin/wap/MeetVsCall/MeetVSCall.html)
# Instructions
With the desktop prototype, we tested the following features in different user testing sessions, each with 4 to 6 participants. All participants have prior experience with web conferencing tools such as Skype for Business, Webex, and Gotomeetings.
# Results of Testing
• A clear direction of where we should take the Teams client when bringing in calling features
• Identify users mental models around calling and meetings
• Uncover any improvements that can be made for the client itself
• Identify potential gaps in the user experience
<file_sep>Title: Clear Cache
IndexPage: true
SortIndex: 1
Cover: guide/clearCache1.png
Author: <NAME>
---
Browers usually cache datas to speed up loading web pages. This is why sometimes you can not see the latest version of the web pages. And cache sometimes will cause some bugs.
We list some ways to clear the cache so that you can get the
# Clear cache in Chrome
The following steps show how to clear cache in Chrome on Mac OS. You can do similar things in other browers on different platforms.
1) Open the history tab

2) Click 'Clear browsing data'

3) Select 'Cached images and files' and choose the 'the beginning of time'

4) Click button 'Clear browsing data' to clear the cache.
# Clear cache for web apps
1) Clear the brower's cache. (system's native browser, such as Safari for IOS)
2) Remove the web apps from the desktop and reinstall it. <file_sep>(function(){
var List = function(){
this.Con = $('#article_con');
this.BtnList = $('#btn_list');
this.BtnThumbnail = $('#btn_thumbnail');
this.init();
};
List.prototype={
init:function(){
var me = this;
me.BtnList.bind('click',function(){
me.switchClass(me.Con[0],'article_con_list');
});
me.BtnThumbnail.bind('click',function(){
me.switchClass(me.Con[0],'article_con_thumbnail');
});
me.initClass();
},
switchClass:function(dom,className){
if(dom.className !== className){
dom.className = className;
this.localData('listView',className);
}
},
initClass:function(){
var _val = this.localData('listView');
if(_val){
this.switchClass(this.Con[0],_val);
}
},
localData:function(key,value){
if(localStorage && localStorage.setItem){
if(value!==undefined){
return localStorage.setItem(key,value);
}else{
return localStorage.getItem(key);
}
}
return none;
}
};
//Dom ready
$(function(){
new List();
});
})();<file_sep>Title: Spark P1 2016
Desc: Spark P1 prototype.
Date: 2016-9-1
Cover: prototypes/cover/Spark P1 2016_Cover.png
---
#Summary
To let users to adapt to our new Sparl desogm more smoothly, UXCCDS team defined 5 steps to update spark app's style. This is the P1 prototype.
#### Prototype Link
[p1.html](https://uxccds.github.io/SparkMobile/v2/page/p1.html)
#### Screen shot

# Launching the prototype
You can launch this prototype through the following ways:
1) Open the prototype in Chrome's mobile simulator. Click [here](../guide/chrome's-mobile-simulator.html) to get more.
2) Install the prototype on your iPhone as a web app. Click [here](../guide/install-web-app.html) to learn more about this method.
# Instructions
1) Click the 'Branding team' 's line to enter its room.
2) Click the activity board's icon on the top-right corner to open it.
3) Click on each ball on the activity board to experience the different features.
# Goals
This prototype aims to displays the following designs:
1) The navigation for the P1 version.
2) Smoonth trasition effects in between pages
3) Add activity board to spark.
<file_sep>Title: Sound Wave
Desc: This prototype is to explore the sound field and make avatars more active.
Date: 2017-5-8
Cover: prototypes/cover/Sound Wave.png
Author: <NAME>
---
#### Ways to show sound
[https://uxccds.github.io/SparkMobile/webrtc/page/wave.html](https://uxccds.github.io/SparkMobile/webrtc/page/wave.html)
#### Sound wave in Spark
[https://uxccds.github.io/SparkMobile/webrtc/page/wave2.html](https://uxccds.github.io/SparkMobile/webrtc/page/wave2.html)
# Instuctions

1) Please use Chrome to view the prototype.
2) Enable Chrome to use your Microphone.
3) Try say something and watch the wave's change.
# Goals
This prototype is to explore the sound field and make avatars more active.
<file_sep>Title: Animation in browser
Cover: research/Animation in browser.jpg
Author: <NAME>
---
## Background
October 2014m HTML5 standard officially released. In the ealier time, the only officially standard was the HTML 4.01 which was released in 1999. Obviously, the HTML4 has been out of data for a long time. At the begining of the 21st century is a period of rapid development of the internet. In order to meet the increasingly complex requirements of the interaction, Java Applet, ActiveX, Flash, Microsoft Silverlight, SVG and the other front-end technology bloom in that era. Then we went through a battle of browser. In that time, developers have to write one style 4 times (-o, -webkit, -moz, -ms). Of course, there are still many ways to avoid writting 4 times. Sass, Less and some other solutions came to the world. Almost at this time, the internet for mobile rose. Because Android and IOS's native browser both use the webkit core, it is more convenient to coding HTML5 for mobile.

The diversity of technology must lead to the increase in learning. Apple killed flash when it delivered the IPhone4. HTML5 standrad came to the word eventually.
HTML5 defines simple animation, excessive, browser storage, multi-threaded, websocket and some other features which only appeared in the native system in the past. However the battle of browsers never ends. The barriers always exists in the latest technology field. After few years of PhoneGap, a wind of React Native blows up. Web Audio is still a draft, it's still hard to apply 3D TV technology in browser. The good news is that we have more and more technoloy for our creation.
### GPU&CPU
In the early browser, the task is single-threaded. All the work for graphic, network and calculation is done in one thread. In the absence of WebGL and CSS3 era, engineers never think about the GPU in front-end programming. With the development of HTML5, graphics technology has been rapid improved. Hardware acceleration went into thr front-end engineers' eye sight.
Before diving in the browser, let's figure out the difference between CPU and GPU. According to <NAME>'s computer system, the computer consists of operator, controller, memory, input device and output device. CPU is known as the operator of the computer while GPU slowly went the public eye in the current years. Modern CPU using multi-core design, each core has a large enough cache, you can handle a variety of complex operations. GPU has more cores compared to each, but each core cache is smaller relative to the CPU. GPU is more suitable for 3D rendering calculations.
In the browser, CPU does the the traditional DOM operation and 2D animation calculation while GPU take the response of rendering WebGL and 3D things. There are many APIs in the traditional DOM for Javascript calls, Dom's data structure can be repeatedly read and modified, which is more dependent on the cache. In WebGl, the content of the Canvas can not be read once it is rendered, and the programmer usually creates other data structures to store the data model, and each rendering is relatively independent. The real scence of browser's rendering, CPU and GPU are usually used together.

### CSS animiation
In CSS3, there are 2 new properties, transition and animation. We can only use CSS3 to build some simple animation. But more importantly, we can get a glimpse of some of the basic elements of animation. Duration, delay, time-function, and property are necessary elements. Compared to Javascript animation, CSS3 animation rendering process is the browser automatically, the code level of the control ability is more weak. In a browser that supports matrix transformations, transform's animated browser optimizes itself and the browser automatically use GPU to do the hardware acceleration .
### Dom animation
DOM animation relative to the Canvas animation, which are elements can be directly interactive, more consumption of CPU resources. In the process of rendering the browser interface, redraw and rearrangement has been happening, and will produce greater performance consumption. The redraw occurs when the style attribute of the element changes, and the rearrangement occurs when the element's position property or the DOM tree changes. In the DOM tree, the rearrangement of the parent node causes the rearrangement of the child nodes, and the absolute positioning elements that get rid of the document flow are relatively more suitable for DOM animations.
### Canvas animation
Canvas has 3D and 2D rendering modes. Different from the DOM element, Canvas inside the graphics can not be drawn after the need to clear the drawing board to redraw. If you need to store any information, you need to use Javascript to create some other objects to save. Because the redraw of the entire Canvas will bring a lot of performance consumption, the common optimization method is part of the redraw Canvas and multiple canvas to achieve animation.
### SVG animation
SVG is an extensible markup language used to describe vector graphics. In early browsers, SVG existed as a plugin, and modern browsers built support for SVG. SVG also has some of the features of the DOM and Canvas elements. First, all SVG elements can be assigned an ID and then operated directly via the Javascript API. By changing the element properties, you can change its appearance. Compared to DOM elements, SVG elements can show more richer images, and almost all vector graphics can be represented by various Bessel curves. Bessel curves can be converted directly to each other, a lot of irregular graphics transition animation is based on SVG.
### Timeline
Animation is based on the art of time, no matter what technology you use to achieve animation, time is a very important element. In the browser, there are two kinds of basic units of time, natural time and frame number of two units. The two units can be converted to each other, but will be subject to the calculation of the thread resources. Animals in natural time are animations such as CSS animations, SVG animations, and Javascript in APIs such as setTimeout, setInterval, and so on. And requestAnimationFrame is based on the number of computer frames to achieve animation. Relatively speaking requestAnimationFrame is more suitable for drawing animation, better performance. SetTimeout and setInterval Although the same function can be implemented on a surface with different APIs, the browser is not the same in the threading mechanism of the browser. The difference here is especially true when the browser resources are tight.
## Summary
With the knowledge of browser, we can focus more on the detail of animation. It meams both better experience and more smooth communication with the engineers.<file_sep>Title: PSTN
Desc: Interstitial page exploration with PSTN implementation
Date: 2018-02-20
Cover: prototypes/cover/PSTN.png
IS_DRAFT: true
---
#### Desktop Prototype
**Phase 2 (New IA)**
1. [https://uxprototype.cisco.com/projects/Reskin/wap/hype/IA-PSTN.html](https://uxprototype.cisco.com/projects/Reskin/wap/hype/IA-PSTN.html)

2. [https://uxprototype.cisco.com/projects/Reskin/wap/hype/IA-PSTN110117.html](https://uxprototype.cisco.com/projects/Reskin/wap/hype/IA-PSTN110117.html)
3. 

**Phase 1 (Currnet Spark Release)**
1. [https://uxprototype.cisco.com/projects/Reskin/wap/hype/PSTN-Interstitial.html](https://uxprototype.cisco.com/projects/Reskin/wap/hype/PSTN-Interstitial.html)
2. 
#### Mobile Prototype
[https://uxccds.github.io/SparkMobile/PSTN/pstn.html](https://uxccds.github.io/SparkMobile/PSTN/pstn.html)
# Instructions


### On Desktop
1) Use Chrome browser to view the prototype for the best results.
2) In the phase 2 (New IA version), seclect an option (1 or 2) before continuing to Day 1 or Day 2 Scenarios
3) Press key "1" to trigger meeting sessions (OBTP)
4) Press key "1" a second time to trigger the second OBTP
### On Mobile
1) For the most optimal experience, use Chrome (mobile mode) or IPhone (webapp mode) to view this prototype.
2) If you encounter any issues, clear the browser cache and reload page.
# Goals
The purpose of the prototype is to test PSTN Scenarios, where the users need to call in to a meeting with their phone. The purpose of this testing is to see whehter this function is clear/obvious to the users, and whether they can compelete the task without too many trial and errors.
# User Testing
## 2/20/2018 Testing
* [Finding Report](https://cisco.box.com/s/oodohdbdmz6abu6iiyv2q0fnfp7gvm26)
* [Testing Video 1](https://cisco.box.com/s/nk8v5t2o9esvwdjrhlmi99rxw784dbwa)
* [Testing Video 2](https://cisco.box.com/s/v5s7plav713ofais3dbh2lfpu3pps8p9)
* [Testing Video 3](https://cisco.box.com/s/q1j8ecs96a8asfb0n6lg4hawqt5u9g1x)
* [Testing Video 4](https://cisco.box.com/s/g2043nu84r4szzluchhr7xxcoqli8t4w)
* [Testing Video 5](https://cisco.box.com/s/k7dzwkhzvkeacy8pmkqrf0yn1g2tey5r)
* [Testing Video 6](https://cisco.box.com/s/ywr8ydsesk81fr6ue1p1w3vrdj1qi29u)
## 11/17/2017 Testing
* [Findings Report](https://cisco.box.com/s/<KEY>)
<file_sep>Title: Easing
Desc: Easing
---
# Easing
```
<!--demo1-->
<div id="demo1"></div>
<!--demo1-->
```
```
//demo1
var arr=[],
regTest = /int|rgb/gi,
regCaps = /\b(\w)|\s(\w)/,
fnCaps=function(m){
return m.toUpperCase();
};
for(var name in Ash.Tween){
if(!regTest.test(name)){
arr.push({
tag:name.replace(regCaps,fnCaps),
dom:{},
css:[{width:0},{width:100}],
time:100,
tween:name
});
}
}
var ashChartInstance = new AshChart('demo1',arr,{});
ashChartInstance.start();
//demo1
```
### Arguments
demo1<file_sep>Title: Interstitial Page
Desc: New interstitial structure before users join a meeting
Date: 2017-10-25
Cover: prototypes/cover/Interstitial.png
IS_DRAFT: true
---

#### Desktop
* New IA Version 2 (Most recent)
[https://uxprototype.cisco.com/projects/Reskin/wap/hype/IA-UserTesting.html](https://uxprototype.cisco.com/projects/Reskin/wap/hype/IA-UserTesting.html)
This version compares 3 different interaction elements with either 1 or 2 action buttons



* New IA version 1
[https://uxprototype.cisco.com/projects/Reskin/wap/hype/IA-interstitial.html](https://uxprototype.cisco.com/projects/Reskin/wap/hype/IA-interstitial.html)
This version compares 3 differnt visual layouts with 2 action buttons



# Instructions

### On Desktop
1) Use Chrome browser to view the prototype to see the self-view video working
2) Choose an experience option (#2, #3, or #4)
3) Choose the "Day 2" experience to skip onboarding process, then press 1 to trigger OBTP
4) Hover over the "Join meeting with video" button to see an un-blurred self view
5) Hover over the "Join meeting with audio" button to see the self-view video background disappear
# Goals
We aim to utilize this prototype to study how clear each layout presents that matches the users' mental model when joining a meering via Cisco Spark.
<file_sep>(function(){
var APrototype = function() {
var initPdot = function() {
var dots = $('[data-pDot]'),
i=0,l=dots.length,
arr=[],
delay,
t= 20;
for(;i<l;i++){
delay = i*t;
arr.push({
dom:dots[i],
attr:[{'fill':'rgb(255,255,255)'},{'fill':'rgb(22,198,204)'}],
time:t,
delay:delay,
tween:'easeInOutInt'
});
arr.push({
dom:dots[i],
attr:[{'fill':'rgb(22,198,204)'},{'fill':'rgb(255,255,255)'}],
time:t,
delay:delay+t,
tween:'easeInOutInt'
});
}
return new Ash.S(arr);
};
new BannerAnimation($('#sectionBlock_prototype'),function() {
var Ashes=[];
var tWheel = 300;
Ashes.push(new Ash.S([{
dom:$('#wheel'),
attr:[{'transform':'translate(40,32) rotate(0,35,35)'},{'transform':'translate(40,32) rotate(360,35,35)'}],
time:tWheel
},{
dom:$('#wheel2'),
attr:[{'transform':'translate(91,0) rotate(0,24,24)'},{'transform':'translate(91,0) rotate(360,24,24)'}],
time:tWheel
},{
dom:$('#wheel3'),
attr:[{'transform':'translate(128,41) rotate(0,15,15)'},{'transform':'translate(128,41) rotate(360,15,15)'}],
time:tWheel
}]));
var eye = $('#eye'),
tEye = 30;
Ashes.push(new Ash.S([{
dom:eye,
attr:[{'fill':'rgb(22,198,204)'},{'fill':'rgb(241,84,36)'}],
time:tEye,
tween:'easeInOutInt'
},{
dom:eye,
attr:[{'fill':'rgb(241,84,36)'},{'fill':'rgb(22,198,204)'}],
delay:tEye,
time:tEye,
tween:'easeInOutInt'
}]));
Ashes.push(initPdot());
return Ashes;
});
};
var AResearch = function() {
new BannerAnimation($('#sectionBlock_research'),function() {
var Ashes=[];
var point = $('#svgPoint'),
t1 = 100,
t2= 40;
Ashes.push(new Ash.S([{
dom:point,
attr:[{'transform':'translate(425.535156, 93.144531) scale(-1, 1) rotate(-270.000000) translate(-425.535156, -93.144531) translate(378.535156, 25.644531)'},{'transform':'translate(441.535156, 93.144531) scale(-1, 1) rotate(-270.000000) translate(-425.535156, -93.144531) translate(378.535156, 25.644531)'}],
time:t1,
tween:'bounceEaseIn'
},{
dom:point,
attr:[{'transform':'translate(441.535156, 93.144531) scale(-1, 1) rotate(-270.000000) translate(-425.535156, -93.144531) translate(378.535156, 25.644531)'},{'transform':'translate(425.535156, 93.144531) scale(-1, 1) rotate(-270.000000) translate(-425.535156, -93.144531) translate(378.535156, 25.644531)'}],
time:t1,
delay:t1
}]));
var svgMicroscope = $('#svgMicroscope');
Ashes.push(new Ash.S([{
dom:svgMicroscope,
attr:[{'transform':'rotate(0,120,63)'},{'transform':'rotate(30,120,63)'}],
time:t2
},{
dom:svgMicroscope,
attr:[{'transform':'rotate(30,120,63)'},{'transform':'rotate(0,120,63)'}],
time:t2,
delay:t2
}]));
return Ashes;
});
};
var ATeam = function() {
new BannerAnimation($('#sectionBlock_team'),function() {
var Ashes=[];
var svgBrain = $('#svgBrain'),
t1 = 80,
t2= 16;
Ashes.push(new Ash.S([{
dom:svgBrain,
attr:[{'fill':'rgb(240,84,36)'},{'fill':'rgb(22,198,204)'}],
time:t1,
tween:'easeInOutInt'
},{
dom:svgBrain,
attr:[{'fill':'rgb(22,198,204)'},{'fill':'rgb(255,216,92)'}],
time:t1,
tween:'easeInOutInt'
},{
dom:svgBrain,
attr:[{'fill':'rgb(255,216,92)'},{'fill':'rgb(240,84,36)'}],
delay:t1,
time:t1,
tween:'easeInOutInt'
}]));
var svgLight = $('[data-light]');
Ashes.push(new Ash.S([{
dom:svgLight,
attr:[{'fill':'rgb(255,255,255)'},{'fill':'rgb(255,216,92)'}],
time:t2,
tween:'easeInOutInt'
},{
dom:svgLight,
attr:[{'fill':'rgb(255,216,92)'},{'fill':'rgb(255,255,255)'}],
delay:t2,
time:t2,
tween:'easeInOutInt'
}]));
return Ashes;
});
};
$(function(){
new APrototype();
new AResearch();
new ATeam();
});
})();<file_sep>Title: Personal Meeting Room
Desc: This prototype is the first prototype to import Personal Meeting Room to WebEx.
Date: 2014-11-1
Cover: prototypes/cover/Personal Meeting Room.png
---
#### Prototype Link
[https://uxprototype.cisco.com/projects/PMR/](https://uxprototype.cisco.com/projects/PMR/)
# Instuctions

1) Make sure you are under Cisco's network, otherwise please use **VPN**.
2) Please use Chrome to view the prototype.
# Goals
This prototype is the first prototype to import Personal Meeting Room to WebEx.
<file_sep>Title: 3D Gyroscope
Cover: research/Firebase1.png
Date: 2017-1-19
Author: <NAME>
---
Most of the model mobile has a 3D [Gyroscope](https://en.wikipedia.org/wiki/Gyroscope) in it. With the Gyroscope, we can trace the movement of the device to some extent.
# Prototype
## Desktop
### link
[wall.html](https://uxccds.github.io/SparkMobile/pair/page/wall.html)
### usage
1) Please use Chrome to open this prototype.
2) Wait for the loading and open the mobile protoype when you see the following screen.

## Mobile
### link
[phone.html](https://uxccds.github.io/SparkMobile/pair/page/phone.html)
### usage
1) Please install the prototype as [web app](../guide/install-web-app.html) on your iPhone.

2) Tap and hold on the area marked on the prototype.
3) Then turn your wrist.
4) You will see a dot moving on the desktop prototype.
<file_sep>Title: Motion
Desc: This prototype is try to explore the motion design.
Date: 2016-12-1
Cover: research/Motion1.png
Author: <NAME>
---
### Web Page
[https://uxprototype.cisco.com/projects/Reskin/wap/ash/page/tween.php](https://uxprototype.cisco.com/projects/Reskin/wap/ash/page/tween.php)
# Instuctions

1) Make sure you are under Cisco's network, otherwise please use **VPN**.
2) Please use chrome to visit this website.
### Goals
This prototype is try to explore the motion design.
<file_sep>(function(){
var AExperimental = function() {
new BannerAnimation($('#con_experimental'),function() {
var Ashes=[];
var svgEye = $('#svgEye'),
t1 = 80;
Ashes.push(new Ash.S([{
dom:svgEye,
attr:[{'fill':'rgb(22,198,204)'},{'fill':'rgb(241,84,36)'}],
time:t1,
tween:'easeInOutInt'
},{
dom:svgEye,
attr:[{'fill':'rgb(241,84,36)'},{'fill':'rgb(22,198,204)'}],
delay:t1,
time:t1,
tween:'easeInOutInt'
}]));
return Ashes;
});
};
var ACurrent = function() {
new BannerAnimation($('#con_current'),function() {
var Ashes=[];
var editBg = $('#editBg'),
svgr = $('[data-svgr]'),
svgl = $('[data-svgl]');
t1 = 80,
t2 = 80;
Ashes.push(new Ash.S([{
dom:editBg,
attr:[{'fill':'rgb(36,45,60)'},{'fill':'rgb(0,0,0)'}],
time:t1,
tween:'easeInOutInt'
},{
dom:editBg,
attr:[{'fill':'rgb(0,0,0)'},{'fill':'rgb(36,45,60)'}],
delay:t1,
time:t1,
tween:'easeInOutInt'
}]));
Ashes.push(new Ash.S([{
dom:svgr,
css:[{transform: 'translate(0px)'},{transform: 'translate(20px)'}],
time:t2
},{
dom:svgr,
css:[{transform: 'translate(20px)'},{transform: 'translate(-20px)'}],
delay:t2,
time:t2*2
},{
dom:svgr,
css:[{transform: 'translate(-20px)'},{transform: 'translate(0px)'}],
delay:t2*3,
time:t2
}]));
Ashes.push(new Ash.S([{
dom:svgl,
css:[{transform: 'translate(0px)'},{transform: 'translate(-20px)'}],
time:t2
},{
dom:svgl,
css:[{transform: 'translate(-20px)'},{transform: 'translate(20px)'}],
delay:t2,
time:t2*2
},{
dom:svgl,
css:[{transform: 'translate(20px)'},{transform: 'translate(0px)'}],
delay:t2*3,
time:t2
}]));
return Ashes;
});
};
var AAchiving = function() {
new BannerAnimation($('#con_archiving'),function() {
var Ashes=[];
var svgST = $('#svgST'),
t1 = 80;
Ashes.push(new Ash.S([{
dom:svgST,
attr:[{'fill':'rgb(240,84,36)'},{'fill':'rgb(22,198,204)'}],
time:t1,
tween:'easeInOutInt'
},{
dom:svgST,
attr:[{'fill':'rgb(22,198,204)'},{'fill':'rgb(240,84,36)'}],
delay:t1,
time:t1,
tween:'easeInOutInt'
}]));
var lines = $('[data-line]'),
t2= 50;
Ashes.push(new Ash.S([{
dom:lines,
attr:[{'fill':'rgb(71,79,89)'},{'fill':'rgb(22,198,204)'}],
time:t2,
tween:'easeInOutInt'
},{
dom:lines,
attr:[{'fill':'rgb(22,198,204)'},{'fill':'rgb(71,79,89)'}],
delay:t2,
time:t2,
tween:'easeInOutInt'
}]));
return Ashes;
});
};
var AFaq = function() {
new BannerAnimation($('#con_faq'),function() {
var Ashes=[];
var svgST = $('#svg_faq_bar1'),
svg_faq_bg1 = $('#svg_faq_bg1')
t1 = 80,
t2 = 40;
Ashes.push(new Ash.S([{
dom:svgST,
attr:[{'fill':'rgb(255,109,59)'},{'fill':'rgb(22,198,204)'}],
time:t1,
tween:'easeInOutInt'
},{
dom:svgST,
attr:[{'fill':'rgb(22,198,204)'},{'fill':'rgb(255,109,59)'}],
delay:t1,
time:t1,
tween:'easeInOutInt'
}]));
Ashes.push(new Ash.S([{
dom:svg_faq_bg1,
attr:[{'fill':'rgb(242,242,242)'},{'fill':'rgb(255,109,59)'}],
time:t2,
tween:'easeInOutInt'
},{
dom:svg_faq_bg1,
attr:[{'fill':'rgb(255,109,59)'},{'fill':'rgb(255,187,51)'}],
delay:t2,
time:t2,
tween:'easeInOutInt'
},{
dom:svg_faq_bg1,
attr:[{'fill':'rgb(255,187,51)'},{'fill':'rgb(22,198,204)'}],
delay:t2*2,
time:t2,
tween:'easeInOutInt'
},{
dom:svg_faq_bg1,
attr:[{'fill':'rgb(22,198,204)'},{'fill':'rgb(242,242,242)'}],
delay:t2*3,
time:t2,
tween:'easeInOutInt'
}]));
return Ashes;
});
};
$(function(){
new ACurrent();
new AExperimental();
new AAchiving();
new AFaq();
});
})(); | 44d6085c369881db8f506f14ffb4913954f7ab7d | [
"Markdown",
"JavaScript"
] | 54 | Markdown | uxCCDS/uxCCDS.github.io | 5cdd7c743ffbf4812465403c0ba51d6fc539cbb7 | 33f7633e9ac406fac94c21dd228b1ba72c8d07f8 |
refs/heads/master | <repo_name>JimmyBryant/Tank<file_sep>/UI.js
/****************************************
* 游戏场景模块
****************************************/
var Scene = Class(
{
static:{className:"Scene"},
Tanks: null, // 所有坦克 new Array(MAX_TANK)
Bonus: null, // 奖励实例
/**
* 本游戏地图大小(13*13),共169地块格子。
*
* 每个地块格子32*32px,用 4 个block标记障碍。
*
* ||============||
* || b1 || b2 ||
* ||=====||=====||
* || b3 || b4 ||
* ||============||
*
*
* 砖块的block又可分 4 小块,
* block值 = 1 + 2 + 4 + 8
* |-----|-----|
* | 1 | 2 |
* |-----|-----|
* | 4 | 8 |
* |—————|—————|
*
* 每个bit代表各个碎片块
*/
Block: null, // Array(26*26)
_arrStageData: null, // 游戏数据
_arrEnemyData: null,
_curStgMap: null, // 当前关数据
_curStgEnemy: null,
_tickWater: null, // 更新水的动画
_statWater: null,
_oMapLayer: null, // 地砖层(WebPlay.TiledLayer)
_oBoomBase: null, // 总部爆炸对象
_arrGrass: null, // 草地精灵数组
_numGrass: 0,
_arrFragMap: null, // 碎片精灵数组
_arrFragFree: null,
/**
* 构造函数 - 初始化场景
*/
constructor: function()
{
this._tickWater = new Tick(60);
this._statWater = new Tick(2);
this._arrGrass = [];
//
// 初始化障碍物数组,碎片数组
//
this._arrFragMap = [];
this._arrFragFree = [];
this.Block = [];
for(i = 0; i < 26; ++i)
{
this._arrFragMap[i] = [];
this.Block[i] = [];
}
//
// 创建地砖层
//
this._oMapLayer = new TiledLayer(13, 13, "res/Terr.png", 32, 32);
this._oMapLayer.setZ(Const.Z_MAP);
this._oMapLayer.CreateAniTile(4);
this._oMapLayer.setBG("#000");
this._oMapLayer.move(Const.POS_X, Const.POS_Y);
App.GameUI.append(this._oMapLayer);
//
// 初始化坦克对象
//
this.Tanks = [new (MyTank())]; // 玩家坦克
for(i = 1; i < Const.MAX_TANK; ++i) // 敌人坦克
{
this.Tanks[i] = new (NPCTank());
}
//奖励对象
this.Bonus = new Bonus();
//总部爆炸对象
this._oBoomBase = new Boom(true);
//载入数据资源(map.dat)
this._LoadData(RES_DATA);
},
BaseBoom: function()
{
this._oBoomBase.Start(176, 368);
// 报废的鹰 (Terr.png:3)
this.SetMapCell(6, 12, 3);
},
/**
* 更新场景画面
*/
Update: function()
{
this.Bonus.Update();
this._oBoomBase.Update();
//
// 更新水的动画
//
if(this._tickWater.On())
this._oMapLayer.SetAniTile(-1, this._statWater.On()? 4 : 5);
},
/**
* 创建玩家坦克
*/
CreatePlayer: function()
{
var tank = this.Tanks[0];
tank.SetPos(128, 384); // 总部左边
tank.SetDir(0); // 玩家坦克方向默认向上
tank.StartBulProof(Const.TIME_BULPRF_DEF); // 开启防弹衣
tank.Birth();
},
/**
* 创建敌人坦克
*/
CreateEnemy: function(id)
{
var pos, i, tank;
//
// 找出一个空闲的坦克对象
//
for(i = 1; i < Const.MAX_TANK; ++i)
{
tank = this.Tanks[i];
if(tank.IsIdle())
break;
}
pos = id % 3;
pos = (pos + 1) % 3; // 敌人位置(0:中,1:右,2:左,...)
this.SetMapCell(pos * 6, 0, 0); // 出生地为空
tank.SetPos(192 * pos, 0); // 地图顶端
tank.SetDir(2); // 默认朝下
tank.SetType(this._curStgEnemy[id]); // 设置类型
// 隐藏一个敌人标志
App.GameUI.EnemyFlag[19 - id].hide();
//
// 是否为带奖励的红坦克
//
if(Const.BONUS_MAP[id])
{
tank.HasBonus();
// 清除存在的奖励
this.Bonus.Clear();
}
// 生产坦克
tank.Birth();
},
/**
* 构造地图(每一关开始前)
*/
BuildMap: function()
{
var id = App.Game.Stage - 1;
this._curStgMap = this._arrStageData[id];
this._curStgEnemy = this._arrEnemyData[id];
// 草地计数
this._numGrass = 0;
//
// 填充地图每一格
//
var r, c;
for(r = 0; r < 13; r++)
for(c = 0; c < 13; c++)
{
this.SetMapCell(c, r, this._curStgMap[r][c]);
}
//
// 隐藏多余的草地
//
var i, l = this._arrGrass.length;
for(i = this._numGrass; i < l; ++i)
this._arrGrass[i].Hide();
// 设置总部鹰图标 (Terr.png:2)
this.SetMapCell(6, 12, 2);
// 玩家出生位置为空
this.SetMapCell(4, 12, 0);
},
/**
* 清空地图(游戏结束后)
*/
ClearMap: function()
{
this._oMapLayer.FillCells(0, 0, 13, 13, 0);
var i, l = this._arrGrass.length;
for(i = 0; i < l; ++i)
this._arrGrass[i].Hide();
},
/**
* 清空坦克
*/
ClearTank: function()
{
this.Bonus.Reset();
for(var i = 0; i < Const.MAX_TANK; ++i)
this.Tanks[i].Reset();
},
/**
* 获取4x4 block的内容
* 如果有一个不相同则返回-1
*/
GetBlock4x4: function(c, r)
{
var B = this.Block;
var b = B[r][c];
if (b == B[r ][c+1] &&
b == B[r+1][c ] &&
b == B[r+1][c+1])
{
return b;
}
return -1;
},
/**
* 设置地图格子内容
*/
SetMapCell: function(c, r, cellID)
{
//
// 清除该位置可能的碎砖层
//
var x = c * 2;
var y = r * 2;
this._ClearFrag(x , y );
this._ClearFrag(x+1, y );
this._ClearFrag(x , y+1);
this._ClearFrag(x+1, y+1);
//
// cellID 对应 res/Terr.png 的图标
//
if(cellID == 1) // 草
{
var spt = this._arrGrass[this._numGrass];
//
// 草地位于坦克上层
// 用精灵代替地砖渲染
//
if(!spt)
{
spt = this._arrGrass[this._numGrass] = new Sprite("res/Terr.png", 32, 32);
spt.SetZ(Const.Z_GRASS);
App.GameUI.Append(spt);
}
spt.Move(Const.POS_X + c * 32, Const.POS_Y + r * 32);
spt.Show();
this._numGrass++;
// 清空之前遗留的地形
cellID = 0;
}
else if(cellID == 2) // 鹰
{
this._SetCellBlock(6, 12, Const.BLOCK_BASE1, 0xF);
}
else if(cellID == 3) // 摧毁的鹰
{
this._SetCellBlock(6, 12, Const.BLOCK_BASE2, 0xF);
}
else if(cellID == 4) // 水
{
this._SetCellBlock(c, r, Const.BLOCK_WATER, 0xF);
// 水为动态砖
cellID = -1;
}
else if(cellID == 6) // 冰
{
this._SetCellBlock(c, r, Const.BLOCK_ICE, 0xF);
}
else if(7 <= cellID && cellID <= 21) // 钢
{
this._SetCellBlock(c, r, Const.BLOCK_IRON, cellID - 6);
}
else if(cellID >= 22) // 砖
{
this._SetCellBlock(c, r, Const.BLOCK_TILE, cellID - 21);
}
if(cellID == 0) // 空
this._SetCellBlock(c, r, Const.BLOCK_NONE, 0xF);
// 渲染格子
this._oMapLayer.SetCell(c, r, cellID);
},
/**
* 设置砖块碎片
*/
SetTileFrag: function(col, row, val)
{
var B = this.Block;
var x1 = col - col % 2;
var y1 = row - row % 2;
var x2 = x1 + 1;
var y2 = y1 + 1;
var x, y;
B[row][col] = val;
/**
* 如果4个block中出现一个或多个空块,
* 那么隐藏这几个碎片精灵,
* 直接设置相应位置为空的大砖块。
*/
var i, tile = 0;
for(i = 0; i < 4; ++i)
{
x = i % 2? x2 : x1;
y = i < 2? y1 : y2;
if(B[y][x])
tile += (1 << i); //tile = tile + 2^i
else
this._ClearFrag(x, y);
}
/**
* 设置合并后的大砖块
* 21 + 砖块序列 => Terr.png中砖块的具体位置
*/
this._oMapLayer.SetCell(x1/2, y1/2, tile? tile+21 : 0);
if(val)
this._DrawFrag(col, row, val);
},
/**
* 设置铁块碎片
*/
SetIronFrag: function(col, row, val)
{
var B = this.Block;
B[row][col] = val;
var x1 = col - col % 2;
var y1 = row - row % 2;
var x2 = x1 + 1;
var y2 = y1 + 1;
var x, y;
var i, tile = 0;
//
// 计算碎铁块的形状
//
for(i = 0; i < 4; ++i)
{
x = i % 2? x2 : x1;
y = i < 2? y1 : y2;
if(B[y][x])
tile += (1 << i); //tile = tile + 2^i
}
this._oMapLayer.SetCell(x1/2, y1/2, tile? tile+6 : 0);
},
/**
* 砖块碎片 - 渲染
*/
_DrawFrag: function(col, row, val)
{
var spt = this._arrFragMap[row][col];
if(!spt)
spt = this._arrFragFree.pop();
if(!spt)
{
spt = new Sprite("res/Frag.png", 16, 16);
spt.SetZ(Const.Z_FRAG);
App.GameUI.Append(spt);
}
spt.Show();
spt.Move(Const.POS_X + col * 16, Const.POS_Y + row * 16);
spt.SetFrame(val - 1);
this._arrFragMap[row][col] = spt;
},
/**
* 砖块碎片 - 清除
*/
_ClearFrag: function(col, row)
{
var spt = this._arrFragMap[row][col];
if(spt)
{
spt.Hide();
this._arrFragFree.push(spt);
this._arrFragMap[row][col] = null;
}
},
/**
* 设置每个格子障碍。
* 每个格子占用4个block,用1bit表示
* mask = 1 + 2 + 4 + 8
*/
_SetCellBlock: function(col, row, v, mask)
{
var B = this.Block;
var x1 = col * 2;
var x2 = x1 + 1;
var y1 = row * 2;
var y2 = y1 + 1;
B[y1][x1] = (mask & 1)? v:0;
B[y1][x2] = (mask & 2)? v:0;
B[y2][x1] = (mask & 4)? v:0;
B[y2][x2] = (mask & 8)? v:0;
},
/**
* 游戏数据载入
*/
_LoadData: function(v) //载入游戏地图 arrStageData以及 arrEnemyData
{
var Map, Enemy;
var i, r, c;
var t, n = 0;
var ch;
this._arrStageData = [];
this._arrEnemyData = [];
for(i = 0; i < Const.MAX_STAGE; ++i)
{
Map = [];
Enemy = [];
for(r = 0; r < 13; r++)
{
t = Map[r] = [];
for(c = 0; c < 13; c++)
t[c] = v.charCodeAt(n++) - 65;
}
for(r = 0; r < 20; r++)
Enemy[r] = v.charCodeAt(n++) - 65;
this._arrStageData[i] = Map;
this._arrEnemyData[i] = Enemy;
}
}
});
/****************************************
* 开场界面模块
****************************************/
var UIOpen = Class(Layer,
{
_lalScore: null, // 顶端分数
_sptSel: null, // 选择图标
_tickSel: null,
/**
* 构造函数 - 创建开场界面
*/
constructor: function()
{
//this.Layer();
this._tickSel = new Tick(5);
var spt, lal;
// 分数文字
this._lalScore = new Lable();
this._lalScore.move(36, 48);
this._lalScore.setColor("#FFF");
this.append(this._lalScore);
this.DispScore();
// LOGO
spt = new Sprite("res/UI.png", 376, 160);
spt.move(56, 96);
this.append(spt);
// 选择文字
lal = new Lable();
lal.move(178, 272);
lal.setText("1 PLAYER\n2 PLAYERS\nCONSTRUCTION");
lal.setColor("#FFF");
this.append(lal);
// 选择图标
this._sptSel = new Sprite("res/Tank.png", 32, 32);
this._sptSel.move(130, 272);
this._sptSel.setFrameSeq([28, 42]);
this.append(this._sptSel);
},
OnEnter: function()
{
// 显示-开场层
this.show();
this.setX(-512);
// 滚动过程中不显示坦克图标
this._sptSel.hide();
},
OnLeave: function()
{
// 隐藏-开场界面
this.hide();
this._sptSel.hide();
},
OnUpdate: function(T)
{
if(T <= 256)
{
//
// 按START跳过滚动画面
//
if(Input.IsPressed(InputAction.START))
T = 256;
this.setX(-512+T * 2);
}
else if(T == 257)
{
// 显示-坦克图标
this._sptSel.show();
}
else
{
//
// 坦克图标动画
//
if(this._tickSel.On())
this._sptSel.nextFrame();
}
//
//选择游戏人数
//
if((Input.IsPressed(InputAction.UP)||Input.IsPressed(InputAction.AUP))&&App.Player==2){
App.Player=1;
this._sptSel.move(130, 272);
}
if((Input.IsPressed(InputAction.DOWN)||Input.IsPressed(InputAction.ADOWN))&&App.Player==1){
App.Player=2;
this._sptSel.move(130, 305);
}
//
// 按START进入游戏
//
if(Input.IsPressed(InputAction.START))
return App.MyApp.Go(App.GameUI);
return T;
},
DispScore: function()
{
//
// "I- 当前分 HI- 最高分"
//
//var sCur = Misc.StrN(App.Game.Score? App.Game.Score : "00", 11);
//this._lalScore.SetText("I-" + sCur + " HI- " + App.Game.ScoreHi);
}
});
/****************************************
* 游戏界面模块
****************************************/
var UIGame = Class(Layer,
{
static:{className:"UIGame"},
EnemyFlag: null, // 电脑坦克标记
LableLife: null, // 生命数标签
LableStg: null, // 关数标签
_lalStage: null, // 银幕上的关数层
_arrMask: null,
_layInfo: null, // 右侧信息栏
_lalGameOver: null, // 游戏结束升起的字
_timerOver: 0,
//_oSound: null,
/**
* 构造函数 - 创建游戏界面
*/
constructor: function()
{
this.Layer(); // super
this._tickWater = new Tick(60);
this._statWater = new Tick(2);
this._tickStgClr = new Tick(200);
//this._oSound = new Sound("res/Open.mid");
var spt, lal, lay;
var i;
//
// 右边信息栏
//
this._layInfo = new Layer();
this._layInfo.move(452, 0);
this._layInfo.setSize(64, 448);
this.append(this._layInfo);
//
// 创建敌人数标志
//
this.EnemyFlag = [];
for(i = 0; i < 20; ++i)
{
spt = this.EnemyFlag[i] = new Sprite("res/Misc.png", 16, 16);
spt.setFrame(10);
spt.move(18 + 16 * (i%2), 34 + 16 * (i >> 1));
this._layInfo.append(spt);
}
//
// "1P"文字
//
lal = new Lable();
lal.setText("I P");
lal.move(14, 252);
this._layInfo.append(lal);
//
// 生命图标
//
spt = new Sprite("res/Misc.png", 16, 16);
spt.setFrame(11);
spt.move(14, 280);
this._layInfo.append(spt);
//
// 生命数-标签
//
this.LableLife = new Lable();
this.LableLife.setText("2");
this.LableLife.move(32, 272);
this._layInfo.append(this.LableLife);
//
// 旗帜图标
//
spt = new Sprite("res/Misc.png", 32, 32);
spt.setFrame(4);
spt.move(14, 352);
this._layInfo.append(spt);
//
// 关数-标签
//
this.LableStg = new Lable();
this.LableStg.setAlign("right");
this.LableStg.setSize(48, 30);
this.LableStg.move(0, 380);
this._layInfo.append(this.LableStg);
//
// 开幕层
//
this._arrMask = [];
for(i = 0; i < 2; ++i)
{
lay = this._arrMask[i] = new Layer();
lay.setSize(512, 224);
lay.setBG("#666");
lay.setZ(Const.Z_UI);
this.append(lay);
}
//
// 选关文字
//
this._lalStage = new Lable();
this._lalStage.setSize(512, 25);
this._lalStage.setY(210);
this._lalStage.setZ(Const.Z_UI);
this._lalStage.setAlign("center");
this.append(this._lalStage);
//
// "GAME OVER"文字
//
this._lalGameOver = new Lable("GAME\nOVER");
this._lalGameOver.move(212, 448);
this._lalGameOver.setColor("#B53120");
this._lalGameOver.setZ(Const.Z_UI);
this._lalStage.setAlign("center");
this._lalGameOver.hide();
this.append(this._lalGameOver);
},
OnEnter: function()
{
// 显示-游戏界面
this.show();
this._arrMask[0].move(0, -240);
this._arrMask[1].move(0, 464);
//
// 第一次开始隐藏信息栏
//
if(App.Game.FirstStart)
this._layInfo.hide();
},
OnLeave: function()
{
// 隐藏-游戏界面
this.hide();
//
// 复位相关对象
//
this._timerOver = 0;
// 清空场景内对象
App.Scene.ClearTank();
},
OnUpdate: function(T)
{
//
// 主流程
//
if(T > 101)
{
var pass = App.Game.Update();
if(pass)
return App.MyApp.Go(App.ScoreUI);
if(!App.Game.GameOver)
{
App.Game.Command();
return T;
}
/*
* Game Over流程
*
* 触发条件:
* 1.总部被打 -更新显示爆炸效果
* 2.命没了
*
* 在Game Over的过程中,
* 玩家无法控制,但NPC仍然继续.
*
* 游戏结束也有可能发生在过关倒计时中,
* 这时无需升起Game Over文字。
*/
if(++this._timerOver <= 30)
{
//
// 总部被打掉玩家仍可以控制一小会
//
App.Game.Command();
}
else if(this._timerOver <= 156)
{
//
// 升起Game Over
//
if(!App.Game.StgClr)
{
this._lalGameOver.show();
this._lalGameOver.setY(508 - this._timerOver*2);
}
}
else if(this._timerOver <= 300)
{
// 进入记分前等待
}
else
{
this._lalGameOver.hide();
// 进入计分流程
return App.MyApp.Go(App.ScoreUI);
}
return T;
}
//
// 界面流程
//
if(T < 20)
{
this._arrMask[0].moveBy(0, +12); // 银幕合拢
this._arrMask[1].moveBy(0, -12);
}
else if(T == 20)
{
this.setBG("#666"); // 当前关数界面
this._lalStage.show();
}
else if(T == 21)
{
this._lalStage.setText("STAGE" + Misc.StrN(App.Game.Stage, 5));
//
// 第一次开始,停住选关
//
if(!App.Game.FirstStart)
return T;
--T;
switch(true)
{
//
// 加关数 (按住GAME_A或GAME_A键)
//
case Input.IsPressed(InputAction.GAME_A):
case Input.IsPressed(InputAction.GAME_C):
if(App.Game.Stage < Const.MAX_STAGE)
{
App.Game.Stage++;
}
break;
//
// 减关数 (按住GAME_B或GAME_D键)
//
case Input.IsPressed(InputAction.GAME_B):
case Input.IsPressed(InputAction.GAME_D):
if(App.Game.Stage > 1)
{
--App.Game.Stage;
}
break;
//
// 开始 (START键)
//
case Input.IsPressed(InputAction.START):
++T;
break;
}
}
else if(T == 22)
{
//
// 恢复显示敌人标志
//
for(var i = 0; i < 20; ++i)
this.EnemyFlag[i].show();
App.Game.FirstStart = false;
App.Game.NewStage(); // 创建新关
}
else if(T < 80)
{
// 稍作停顿
}
else if(T == 80)
{
this._lalStage.hide(); // 隐藏 -关数界面
this._layInfo.hide(); // 暂时隐藏信息栏
}
else if(T <= 100)
{
this._arrMask[0].moveBy(0, -12); // 银幕拉开
this._arrMask[1].moveBy(0, +12);
}
else if(T == 101)
{
this._layInfo.show(); // 显示 -信息栏
//this._oSound.Play();
}
return T;
}
});
<file_sep>/Tank.js
var Misc =
{
/**
* 将数组的每个成员加上base值
* 方便帧序号的相对值计算
*/
ARR: function(base)
{
var i, n, arr = [];
for(i=1, n=arguments.length; i<n; ++i)
arr[i-1] = base + arguments[i];
return arr;
},
StrN: function(str, len)
{
return (" " + str).slice(-len);
}
};
/****************************************
* 子弹类
****************************************/
/**
* 子弹状态机
* @enum {number}
*/
var BullState =
{
NONE: 0,
FIRE: 1,
BOOM: 2,
RESET: 3
};
/**
* 子弹移动状态
* @enum {number}
*/
var HitState =
{
NONE: 0,
HIT: 1,
MISS: 2
};
var Bullet = Class(
{
_state: BullState.NONE, // 状态机
_team: 0, // 队伍
_sptBul: null,
_boom: null,
X:0, Y:0, // 位置
Dir:0, // 方向
Speed:0, // 速度
Pow:0, // 是否加强子弹
static :{className:"Bullet"},
constructor: function(team)
{
//
// 创建子弹精灵
//
this._sptBul = new Sprite("res/Misc.png", 8, 8);
this._sptBul.hide();
this._sptBul.setZ(Const.Z_BULL);
App.GameUI.append(this._sptBul);
// 子弹所属的队伍
this._team = team;
// 小型爆炸
this._boom = new Boom(false);
},
/**
* 子弹逻辑更新
*/
Update: function()
{
switch(this._state)
{
case BullState.NONE: // -空闲状态
break;
case BullState.FIRE: // -发射状态
for(var i = 0; i < this.Speed; ++i)
{
switch(this._Go())
{
//
// 击中物体,子弹爆炸
//
case HitState.HIT:
this._boom.Start(this.X - 28, this.Y - 28);
this._state = BullState.BOOM;
return;
//
// 子弹消失
//
case HitState.MISS:
this._state = BullState.RESET;
return;
}
switch(this.Dir)
{
case 0: //上
this.y -= 2;
break;
case 1: //右
this.x += 2;
break;
case 2: //下
this.y += 2;
break;
case 3: //左
this.x -= 2;
break;
}
// 更新子弹位置
this._sptBul.move(Const.POS_X + this.x, Const.POS_Y+ this.y);
}
break;
case BullState.BOOM: // -爆炸状态
if(this._boom.Update())
this._state = BullState.RESET;
break;
case BullState.RESET: // -重置状态
this._sptBul.Hide();
this._state = BullState.NONE;
break;
}
},
/**
* 返回子弹是否为空闲
*/
IsIdle: function()
{
return this._state == BullState.NONE;
},
/**
* 发射子弹
*/
Shot: function(x, y, dir)
{
//
// 调整子弹到坦克前方的位置
//
switch(dir)
{
case 0: //上
x += 12;
y -= 8;
break;
case 1: //右
x += 32;
y += 12;
break;
case 2: //下
x += 12;
y += 32;
break;
case 3: //左
x -= 8;
y += 12;
break;
}
this._sptBul.move(Const.POS_X + x, Const.POS_Y + y);
this._sptBul.setFrame(dir); //设置方向
this._sptBul.show();
this.X = x;
this.Y = y;
this.Dir = dir;
this._state = BullState.FIRE;
},
/**
* 重置子弹
*/
Reset: function()
{
this._sptBul.Hide();
this._boom.Reset();
this._state = BullState.NONE;
},
/**
* 子弹移动
*/
_Go: function()
{
/**
* 返回值
* 0:子弹继续前进
* 1: 子弹碰到物体
* 2:子弹抵消
*/
var ret = HitState.NONE;
var p, q, r;
var b1, b2;
var B = App.Scene.Block;
var x = this.X;
var y = this.Y;
/**
* 子弹击中砖块(向上的情况):
*
* ||===========||===========||
* || | || | ||
* ||---- ? ----||---- ? ----||
* || | || | ||
* ||===========||===========||
* || 1 | 2 || 1 | 2 ||
* ||---- L ----||---- R ----||
* || 4 | 8 || 4 | 8 ||
* ||===========||===========||
* /\
* / \
* |__|
*
* L => block[r][p] (左边的block)
* R => block[r][q] (右边的block)
*
* 击中砖块的同时,
* 可以消去同方向的另一砖块。
*
* 普通子弹:
* 击中L的8号砖,则L的4号砖也同时消去(如果存在的话);
* 如果不存在8号,4号则不受影响;
*
* 击中L的8号砖之后,如果R是铁块,子弹停止;
* 否则子弹继续向上,检测L的2号和1号。
* (一次打掉半个block砖)
*
* 加强子弹:
* ...
*
* 击中L的8号砖之后,不论R是否为铁块,子弹都将继续。
* (一次可以打掉一个block砖)
*
*
* 另一边同理。
* 其他方向的子弹同理。
*/
switch(this.Dir)
{
/******************************************
* 子弹: 上
*****************************************/
case 0:
// 以子弹尾部为准
y += 8;
// 飞出视野
if(y <= 0)
return 1;
// 没有和地块接触
if(y % 16)
break;
r = y / 16 - 1;
p = x >> 4; // p = Math.floor(x / 16)
q = p + 1;
b1 = B[r][p]; // 左
b2 = B[r][q]; // 右
if(b1 & 0xF)
ret = this._TileHit(b1, b2, p, r, 8, 4, 2, 1);
if(b2 & 0xF)
ret |= this._TileHit(b2, b1, q, r, 4, 8, 1, 2);
break;
/******************************************
* 子弹: 右
*****************************************/
case 1:
if(x >= 416)
return 1;
if(x % 16)
break;
r = x / 16;
p = y >> 4;
q = p + 1;
b1 = B[p][r]; // 上
b2 = B[q][r]; // 下
if(b1 & 0xF)
ret = this._TileHit(b1, b2, r, p, 4, 1, 8, 2);
if(b2 & 0xF)
ret |= this._TileHit(b2, b1, r, q, 1, 4, 2, 8);
break;
/******************************************
* 子弹: 下
*****************************************/
case 2:
if(y >= 416)
return 1;
if(y % 16)
break;
r = y / 16;
p = x >> 4;
q = p + 1;
b1 = B[r][p]; // 左
b2 = B[r][q]; // 右
if(b1 & 0xF)
ret = this._TileHit(b1, b2, p, r, 2, 1, 8, 4);
if(b2 & 0xF)
ret |= this._TileHit(b2, b1, q, r, 1, 2, 4, 8);
break;
/******************************************
* 子弹: 左
*****************************************/
case 3:
x += 8;
if(x <= 0)
return 1;
if(x % 16)
break;
r = x / 16 - 1;
p = y >> 4;
q = p + 1;
b1 = B[p][r]; // 上
b2 = B[q][r]; // 下
if(b1 & 0xF)
ret = this._TileHit(b1, b2, r, p, 8, 2, 4, 1);
if(b2 & 0xF)
ret |= this._TileHit(b2, b1, r, q, 2, 8, 1, 4);
break;
}
//
// 检测铁块是否能打掉
//
if(b1 == Const.BLOCK_IRON)
{
ret = HitState.HIT;
if(this.Pow)
{
if(this.Dir==1 || this.Dir==3)
App.Scene.SetIronFrag(r, p, Const.BLOCK_NONE); // 横向
else
App.Scene.SetIronFrag(p, r, Const.BLOCK_NONE); // 纵向
}
}
if(b2 == Const.BLOCK_IRON)
{
ret = HitState.HIT;
if(this.Pow)
{
if(this.Dir==1 || this.Dir==3)
App.Scene.SetIronFrag(r, q, Const.BLOCK_NONE); // 横向
else
App.Scene.SetIronFrag(q, r, Const.BLOCK_NONE); // 纵向
}
}
//
// 是否打到总部
//
if(b1 == Const.BLOCK_BASE1 || b2 == Const.BLOCK_BASE1)
{
App.Game.BaseDestroy();
ret = HitState.HIT;
}
//
// 碰撞检测
//
var tanks = App.Scene.Tanks;
var tank, bul;
var i, j;
for(i = 0; i < Const.MAX_TANK; ++i)
{
tank = tanks[i];
//
// 跳过同一队伍的
//
if(tank.Team == this._team || !tank.IsLive())
continue;
//
// 子弹与坦克的碰撞
//
if(tank.CheckColl(this._sptBul))
{
if(HitState.MISS == tank.Hit()) // 打到防弹衣
return HitState.MISS;
else // 打到坦克(不一定要打爆)
return HitState.HIT;
}
//
// 与对方坦克的子弹碰撞
//
for(j = 0; j < tank.BulMax; j++)
{
bul = tank.Bullets[j];
if(bul._state == BullState.FIRE)
{
if(bul._sptBul.collidesWith(this._sptBul))
{
// 对家的子弹也消失
bul._state = BullState.RESET;
return HitState.MISS;
}
}
}
}
return ret;
},
/**
* 子弹与砖块的撞击
*/
_TileHit: function(b1, b2, col, row, p1, p2, q1, q2)
{
var hit = 0;
if(b1 & p1)
{
b1 &= ~p1; // 当前块
if(b1 & p2) // 同方向扩散
b1 &= ~p2;
hit = 1;
}
if(b1 & q1) // 后面块
{
/**
* 加强子弹可以一次打两层砖。
* 普通子弹只有前面块不存在,
* 并且旁边不是铁块,
* 才可以打后面块。
*/
if(this.Pow || (hit == 0 && b2 != Const.BLOCK_IRON))
{
b1 &= ~q1;
if(b1 &= q2) // 同方向扩散
b1 &= ~q2;
hit = 1;
}
}
if(hit)
App.Scene.SetTileFrag(col, row, b1);
return hit;
}
});
/**
* 游戏常量声明
* @enum
*/
var Const =
{
//
// 游戏常量
//
MAX_STAGE: 35, // 总关数
MAX_TANK: 5, // 最大坦克数
TIME_BULPRF_DEF: 250, // 出生防弹时间
TIME_BULPRF_BONUS: 1200, // 奖励防弹时间
TIME_WALL_IRON: 1200, // 总部铁墙保护时间
//
// 带奖励的红坦克(默认:4号,11号,18号)
//
// ------- 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20
BONUS_MAP: [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0],
//
// 场景位置
//
POS_X: 34,
POS_Y: 18,
//
// 场景图层深度
//
Z_MAP: 0, // 地图
Z_FRAG: 1, // 碎片砖
Z_BULL: 2, // 子弹
Z_TANK: 3, // 坦克
Z_GRASS: 4, // 草
Z_SCORE: 5, // 分数(与坦克共用一个层)
Z_BONUS: 6, // 奖励图标
Z_BOOM: 7, // 爆炸
Z_UI: 8, // 相关界面
//
// block障碍值
//
BLOCK_NONE: 0,
BLOCK_TILE: 15,
BLOCK_ICE: 16,
BLOCK_IRON: 32,
BLOCK_WATER: 64,
BLOCK_BASE1: 128,
BLOCK_BASE2: 256,
//
// 精灵帧序列基值
//
FR_BIRTH: 112,
FR_SCORE: 116,
FR_BONUS: 121,
FR_BULPRF: 11
};
/****************************************
* 坦克类
****************************************/
/**
* 坦克状态机
* @enum {number}
*/
var TankState =
{
NONE: 0,
BIRTH: 1,
LIVE: 2,
BOOM: 3,
SCORE: 4,
RESET: 5
};
var Tank = Class({
static:
{
BIRTH: Misc.ARR(Const.FR_BIRTH, 0,1,2,3,2,1,0,1,2,3,2,1,0),
BULPRF: Misc.ARR(Const.FR_BULPRF, 0, 0, 1, 1),
className:"Tank"
},
_state: TankState.NONE, // 状态机
_icon: 0, // 坦克图标
_wheel: 0, // 轮子状态 (0 -> 1 -> 0)
_type: 0, // 类型
_tickBirth: null, // 生产动画计时器
_sptTank: null, // 坦克精灵
_boom: null, // 爆炸
_timerFire: 0, // 开火计时器
_fireDelay: 16, // 开火最短间隔
_tickMove: null, // 移动计时器
X:0, Y:0, // 坐标
Speed: 0, // 移动速度
Dir: -1, // 当前方向
Team: 0, // 队伍
Bullets: null, // 子弹数组
BulMax: 0, // 最大子弹数
constructor: function(team)
{
//
// 创建坦克精灵
//
this._sptTank = new Sprite("res/Tank.png", 32, 32);
this._sptTank.hide();
App.GameUI.append(this._sptTank);
// 队伍
this.Team = team;
// 子弹数组
this.Bullets = [];
// 大的爆炸对象
this._boom = new Boom(true);
// 定时器
this._tickMove = new Tick(2);
},
Update: function()
{
this._timerFire--;
//
// 更新发出的子弹
//
for(var i = 0; i < this.BulMax; ++i)
this.Bullets[i].Update();
//
// 坦克状态机
//
switch(this._state)
{
/*========================================
* 状态: 无
========================================*/
case TankState.NONE:
break;
/*========================================
* 状态: 坦克生产过程
========================================*/
case TankState.BIRTH:
if(!this._tickBirth.On())
return;
//
// 显示坦克精灵
//
if(!this._sptTank.Visible)
{
this._sptTank.show();
this._sptTank.setZ(Const.Z_TANK);
}
// 播放生产动画
this._sptTank.nextFrame();
//
// 生产完成,进入运行状态
//
if(this._sptTank.getFrame() == 0)
{
// 撤销生产动画的帧序列
this._sptTank.setFrameSeq();
this._state = TankState.LIVE;
this.SetType(this._type);
}
break;
/*========================================
* 状态: 坦克生运行中
========================================*/
case TankState.LIVE:
this._UpdateUI();
break;
/*========================================
* 状态: 坦克爆炸
========================================*/
case TankState.BOOM:
if(this._boom.Update())
this._Boom();
break;
/*========================================
* 状态: 显示得分
========================================*/
case TankState.SCORE:
if(this._tickScore.On())
this._state = TankState.RESET;
break;
/*========================================
* 状态: 销毁
========================================*/
case TankState.RESET:
this._sptTank.Hide(); // 隐藏坦克精灵
this._state = TankState.NONE;
break;
}
},
/**
* 返回坦克是否活动
*/
IsLive: function()
{
return this._state == TankState.LIVE;
},
/**
* 返回坦克对象是否空闲
*/
IsIdle: function()
{
return this._state == TankState.NONE;
},
/**
* 检测坦克精灵是否与指定的层重叠
*/
CheckColl: function(layer)
{
return this._sptTank.collidesWith(layer);
},
/**
* 子弹击中坦克
*/
Hit: function(force)
{
var ret = this._Hit(force);
if(HitState.HIT == ret)
{
//
// 坦克开始爆炸
//
this._boom.Start(this.X - 16, this.Y - 16);
this._state = TankState.BOOM;
}
return ret;
},
/**
* 设置坦克类型
*/
SetType: function(t)
{
this._type = t;
if(this._state != TankState.LIVE)
return;
this._SetType(t);
this._UpdateFrame();
},
/**
* 设置坐标
*/
SetPos: function(x, y)
{
// 设置坦克位置
this._sptTank.move(Const.POS_X + x, Const.POS_Y + y);
this.x = x;
this.y = y;
},
/**
* 设置方向
*/
SetDir: function(val)
{
if(this.Dir == val)
return;
//
// 转弯时调整位置,使更灵活
//
var fix;
switch(this.Dir)
{
case 0: // 当前处于上下方向,调整y值到最近block单元位置
case 2:
if(this.Y % 16)
{
this.Y = Math.round(this.Y / 16) * 16;
fix = true;
}
break;
case 1: // 当前处于左右方向,调整x值到最近block单元位置
case 3:
if(this.X % 16)
{
this.X = Math.round(this.X / 16) * 16;
fix = true;
}
break;
}
this.Dir = val;
if(fix)
{
this._sptTank.move(Const.POS_X + this.X, Const.POS_Y + this.Y);
this._UpdateFrame();
}
},
/**
* 发射一枚子弹
*/
Fire: function()
{
if(this._timerFire > 0)
return;
//
// 找出一空闲子弹并发射
//
var i, bul;
for(i = 0; i < this.BulMax; ++i)
{
bul = this.Bullets[i];
if(bul.IsIdle())
{
bul.Shot(this.X, this.Y, this.Dir);
this._timerFire = this._fireDelay;
break;
}
}
},
/**
* 当前方向前进一步
*/
Go: function()
{
//
// 移动间隔计时器
//
if(!this._tickMove.On())
return true;
this._tickMove.Reset(3 - this.Speed);
var tanks = App.Scene.Tanks;
var x = this.X;
var y = this.Y;
var x2, y2;
var col = x >> 4; // Math.floor(x / 16)
var row = y >> 4; // Math.floor(y / 16)
var offset, i;
var tank;
// 切换轮子的状态 0->1->0
this._wheel = +!this._wheel;
this._UpdateFrame();
switch(this.Dir)
{
/******************************
* 上移
*****************************/
case 0:
if(y == 0)
return false;
//
// 检测上方是否有阻碍块
//
if(y % 16 == 0)
{
if(!this._MoveTest(col, row-1, col+1, row-1))
return false;
}
/*
* 坦克与坦克的碰撞检测。
*
* 如果诞生时该位置已存在坦克,
* 此时可以重叠,并且可以移动,
* 一旦分开后就不可再重叠。
*/
for(i = 0; i < Const.MAX_TANK; ++i)
{
tank = tanks[i];
if(tank != this && tank.IsLive())
{
offset = tank.Y + 32 - y;
x2 = tank.X;
if(0 <= offset && offset <= 6 && x2 - 32 < x && x < x2 + 32)
return false;
}
}
y -= 2;
break;
/******************************
* 右移
*****************************/
case 1:
if(x == 384) //12*32
return false;
if(x % 16 == 0)
{
if(!this._MoveTest(col+2, row, col+2, row+1))
return false;
}
for(i = 0; i < Const.MAX_TANK; ++i)
{
tank = tanks[i];
if(tank != this && tank.IsLive())
{
offset = x + 32 - tank.X;
y1 = tank.Y;
if(0 <= offset && offset <= 6 && y1 - 32 < y && y < y1 + 32)
return false;
}
}
x += 2;
break;
/******************************
* 下移
*****************************/
case 2:
if(y == 384)
return false;
if(y % 16 == 0)
{
if(!this._MoveTest(col, row+2, col+1, row+2))
return false;
}
for(i = 0; i < Const.MAX_TANK; ++i)
{
tank = tanks[i];
if(tank != this && tank.IsLive())
{
offset = y + 32 - tank.Y;
x1 = tank.X;
if(0 <= offset && offset <= 6 && x1 - 32 < x && x < x1 + 32)
return false;
}
}
y += 2;
break;
/******************************
* 左移
*****************************/
case 3:
if(x == 0)
return false;
if(x % 16 == 0)
{
if(!this._MoveTest(col-1, row, col-1, row+1))
return false;
}
for(i = 0; i < Const.MAX_TANK; ++i)
{
tank = tanks[i];
if(tank != this && tank.IsLive())
{
offset = tank.X + 32 - x;
y1 = tank.Y;
if(0 <= offset && offset <= 6 && y1 - 32 < y && y < y1 + 32)
return false;
}
}
x -= 2;
break;
}
this.X = x;
this.Y = y;
this._sptTank.move(Const.POS_X + x, Const.POS_Y + y);
return true;
},
/**
* 生产坦克
*/
Birth: function()
{
// 进入产生状态
this._state = TankState.BIRTH;
this._sptTank.setFrameSeq(Tank.BIRTH);
},
/**
* 重置坦克对象
*/
Reset: function()
{
this._Reset();
//
// 复位所有子弹
//
for(var i = 0; i < this.BulMax; ++i)
this.Bullets[i].Reset();
// 复位爆炸对象
this._boom.Reset();
//
// 计时器复位
//
this._tickMove.Reset(2);
this._timerFire = 0;
// 隐藏精灵
this._sptTank.Hide();
// 状态复位
this._state = TankState.NONE;
},
/**
* 更新坦克界面
*/
_UpdateFrame: function()
{
this._sptTank.setFrame(this.Dir * 28 + this._wheel * 14 + this._icon);
},
/**
* 配置子弹参数
*/
_SetBullets: function(max, speed, pow)
{
var i, bul;
//
// 将属性配置到每一个子弹对象
//
for(i = 0; i < max; ++i)
{
bul = this.Bullets[i];
if(!bul)
bul = this.Bullets[i] = new Bullet(this.Team);
bul.Speed = speed;
bul.Pow = pow;
}
this.BulMax = max;
},
/**
* 前进时地形障碍检测
*/
_MoveTest: function(c1, r1, c2, r2)
{
var B = App.Scene.Block;
var b1 = B[r1][c1];
var b2 = B[r2][c2];
/*
return (b1 == Const.BLOCK_NONE || b1 == Const.BLOCK_ICE) &&
(b2 == Const.BLOCK_NONE || b2 == Const.BLOCK_ICE);
*/
// BLOCK_NONE=0;
// BLOCK_ICE=16; =>
return (b1|16)==16 && (b2|16)==16;
}
});
/****************************************
* 玩家坦克类
****************************************/
var MyTank =function(){return Class(Tank,
{ static:{className:"MyTank"},
_sptBulprf: null, // 防弹衣精灵
_timerBulprf: 0, // 防弹时间
constructor: function()
{
this.Tank(0); // super
//
// 创建防弹衣精灵
//
this._sptBulprf = new Sprite("res/Misc.png", 32, 32);
this._sptBulprf.hide();
this._sptBulprf.setFrameSeq(Tank.BULPRF);
this._sptTank.append(this._sptBulprf);
this._tickBirth = new Tick(2);
},
/**
* 覆盖 -- 界面更新
*/
_UpdateUI: function()
{
--this._timerBulprf;
//
// 更新防弹衣动画
//
if(this._timerBulprf > 0)
{
this._sptBulprf.show();
this._sptBulprf.nextFrame();
}
else if(this._timerBulprf == 0)
{
this._sptBulprf.hide();
}
},
/**
* 覆盖 -- 设置类型
*/
_SetType: function(t)
{
this.Speed = 2;
switch(t)
{
case 0: // 普通
this._fireDelay = 13;
this._SetBullets(1, 2, false);
break;
case 1: // 快速
this._fireDelay = 11;
this._SetBullets(1, 3, false);
break;
case 2: // 连发
this._fireDelay = 7;
this._SetBullets(2, 3, false);
break;
case 3: // 威力
this._fireDelay = 7;
this._SetBullets(2, 3, true);
break;
}
this._icon = t;
},
/**
* 覆盖 -- 坦克被击中
*/
_Hit: function()
{
if(this._timerBulprf > 0)
{
return HitState.MISS;
}
else
{
this._sptTank.hide();
return HitState.HIT;
}
},
/**
* 覆盖 -- 坦克爆炸
*/
_Boom: function()
{
this.SetType(0);
// 减少1条命
App.Game.LifeDec();
this._state = TankState.RESET;
},
/**
* 覆盖 -- 坦克重置
*/
_Reset: function()
{
//
// 停止防弹状态
//
if(this._timerBulprf > 0)
{
this._timerBulprf = 0;
this._sptBulprf.Hide();
}
},
/**
* 开启防弹衣
*/
StartBulProof: function(t)
{
this._timerBulprf = t;
},
/**
* 坦克升级
*/
Upgrade: function()
{
if(this._type < 3)
this.SetType(this._type + 1);
},
/**
* 返回是否位于冰上
*/
OnIce: function()
{
// Math.floor(x / 16)
return Const.BLOCK_ICE ==
App.Scene.GetBlock4x4(this.X >> 4, this.Y >> 4);
}
});
};
/****************************************
* 电脑坦克类
****************************************/
var NPCTank =function(){ return Class(Tank,
{ static:{className:"NPCTank"},
_bonus: false, // 是否带奖励
_HP: 0, // 生命值
_tickRed: null, // 奖励闪烁计时器
_statRed: null,
_tickFlash: null,
_tickScore: null, // 奖励加分计时器
constructor: function()
{
this.Tank(1); // super
this._tickRed = new Tick(10);
this._statRed = new Tick(2);
this._tickScore = new Tick(10);
this._tickFlash = new Tick(2);
this._tickBirth = new Tick(5);
},
/**
* 覆盖 -- 界面更新
*/
_UpdateUI: function()
{
//
// 更新带奖励的NPC颜色
//
if(this._bonus)
{
if(this._tickRed.On())
{
this._statRed.On()? --this._icon : ++this._icon;
this._UpdateFrame();
}
return;
}
//
// 加强型坦克颜色
//
if(this._type == 3)
{
switch(this._HP)
{
case 1: //白
this._icon = 10;
break;
case 2: //黄-绿
this._icon = this._tickFlash.On()? 13 : 12;
break;
case 3: //黄-白
this._icon = this._tickFlash.On()? 13 : 10;
break;
case 4: //绿-白
this._icon = this._tickFlash.On()? 12 : 10;
break;
}
}
this._UpdateFrame();
},
/**
* 覆盖 -- 设置类型
*/
_SetType: function(t)
{
this.Speed = 1;
switch(t)
{
case 0: // 普通型
this._icon = 4;
this._HP = 1;
this._SetBullets(1, 2, false);
break;
case 1: // 灵活型
this._icon = 6;
this.Speed = 2;
this._HP = 1;
this._SetBullets(1, 2, false);
break;
case 2: // 威力型
this._icon = 8;
this._HP = 1;
this._SetBullets(1, 3, false);
break;
case 3: // 加强型
this._icon = 10;
this._HP = 4;
this._SetBullets(1, 2, false);
break;
}
},
/**
* 覆盖 -- 坦克被击中
*/
_Hit: function(force)
{
//
// 接到炸弹强制爆炸
// 如果带奖励则丢失
//
if(force)
{
this._HP = -1;
this._bonus = false;
this._sptTank.Hide();
return HitState.HIT;
}
//
// 显示奖励
//
if(this._bonus)
{
this._bonus = false;
App.Scene.Bonus.Show();
}
if(--this._HP == 0)
{
//
// 加分(100,200,300,400)
//
App.Game.SocreAdd(100 * (this._type + 1));
//
// 显示得分(分数图标位于草的上层)
//
this._sptTank.SetFrame(Const.FR_SCORE + this._type);
this._sptTank.SetZ(Const.Z_SCORE);
return HitState.HIT;
}
return HitState.NONE;
},
/**
* 覆盖 -- 坦克爆炸
*/
_Boom: function()
{
//
// 被炸掉的不显示分数,也不类型计数
//
if(this._HP == -1)
{
this._state = TankState.RESET;
App.Game.KillEnemy(-1);
}
else
{
this._state = TankState.SCORE;
App.Game.KillEnemy(this._type);
}
},
/**
* 覆盖 -- 坦克重置
*/
_Reset: function()
{
// 撤销奖励
this._bonus = false;
this._tickRed.Reset();
this._tickScore.Reset();
},
/**
* 设置是否带奖励
*/
HasBonus: function()
{
this._bonus = true;
this._statRed.Reset();
}
});
};
/****************************************
* 爆炸类
****************************************/
var Boom = Class(
{
_big: false,
_start: false,
_sptBoom: null,
_tickBoom: null,
static:{className:Boom},
constructor: function(big)
{
// 创建爆炸精灵
this._sptBoom = new Sprite("res/Boom.png", 64, 64);
this._sptBoom.hide();
this._sptBoom.setZ(Const.Z_BOOM);
this._sptBoom.setFrameSeq(big ? [0,1,2,3,4,1] : [0,1]);
App.GameUI.append(this._sptBoom);
this._big = big;
this._tickBoom = new Tick(4);
},
Update: function()
{
if(!this._start)
return;
// 大的爆炸过程中稍作延时
if(this._big && !this._tickBoom.On())
return;
// 显示爆炸动画帧
this._sptBoom.nextFrame();
// 爆炸结束
if(this._sptBoom.GetFrame() == 0)
{
this._sptBoom.Hide();
this._start = false;
return true;
}
},
Start: function(x, y)
{
// 定位爆炸精灵
this._sptBoom.Move(Const.POS_X + x, Const.POS_Y + y);
// 开始播放爆炸动画
this._sptBoom.Show();
this._start = true;
},
Reset: function()
{
// 重置爆炸对象
this._sptBoom.Hide();
this._tickBoom.Reset();
this._start = false;
}
});
/****************************************
* 技能奖励类
****************************************/
/**
* 奖励状态机
* @enum {number}
*/
var BonusState =
{
NONE: 0,
SHOW: 1,
SCORE: 2
};
var Bonus = Class(
{
_sptIcon: null, // 奖励精灵
_state: BonusState.NONE, // 状态机
_type: 0, // 0-铲子 1-五角星 2-加命 3-防弹 4-炸弹 5-定时
_tickFlash: null, // 图标闪烁间隔
_statFlash: null, // 图标闪烁状态
_tickToggle: null, // 总部切换间隔
_statToggle: null, // 总部切换状态
_tickScore: null, // 分数显示时间
_timerProtect: 0, // 总部防护时间计时
_timerFreeze: 0, // 定时技能计时
static:{className:Bonus},
constructor: function()
{
//
// 创建精灵
//
this._sptIcon = new Sprite("res/Tank.png", 32, 32);
this._sptIcon.hide();
this._sptIcon.setZ(Const.Z_BONUS);
App.GameUI.append(this._sptIcon);
//
// 相关定时器
//
this._tickFlash = new Tick(10);
this._statFlash = new Tick(2); // 2态计数器,在true和false间切换。
this._tickToggle = new Tick(30);
this._statToggle = new Tick(2);
this._tickScore = new Tick(20);
},
/**
* 逻辑更新
*/
Update: function()
{
this._timerProtect--;
this._timerFreeze--;
/*
* 铁锹保护倒计时
*
* 在快结束前时间内,
* 总部围墙在 铁块 和 砖块 间切换。
* 即使已没有围墙,也补上
*/
if(0 <= this._timerProtect && this._timerProtect < 330)
{
// 切换定时器
if(this._tickToggle.On())
this._SetBaseWall(this._statToggle.On());
}
//
// 更新状态机
//
switch(this._state)
{
case BonusState.NONE: // -奖励没有出现
break;
case BonusState.SHOW: // -奖励出现,等待玩家去接
// 奖励闪烁定时器
if(this._tickFlash.On())
this._sptIcon.SetVisible(this._statFlash.On());
this._CheckBonus();
break;
case BonusState.SCORE: // -显示奖励分数
if(this._tickScore.On())
this.Clear();
break;
}
},
/**
* 显示奖励
*/
Show: function()
{
var rnd = Math.random;
this._type = rnd() * 6 >> 0;
//
// 奖励出现在地图上可进入的位置
//
var c, r;
do
{
c = rnd() * 24 >> 0;
r = rnd() * 24 >> 0;
}
while(App.Scene.GetBlock4x4(c, r) >= Const.BLOCK_IRON)
//
// 显示奖励图标
//
this._sptIcon.setFrame(Const.FR_BONUS + this._type);
this._sptIcon.move(Const.POS_X + c * 16, Const.POS_Y + r * 16);
this._sptIcon.show();
this._state = BonusState.SHOW;
},
/**
* 当前是否处于定时
*/
IsFreezed: function()
{
return this._timerFreeze > 0;
},
/**
* 清空奖励
*/
Clear: function()
{
this._sptIcon.hide();
this._state = BonusState.NONE;
},
/**
* 重置奖励
*/
Reset: function()
{
this.Clear();
// 复位计数器
this._tickScore.Reset();
this._timerFreeze = 0;
this._timerProtect = 0;
},
/**
* 获得奖励
*/
_CheckBonus: function()
{
var i, player = App.Scene.Tanks[0];
//
// 玩家是否碰到奖励
//
if(!player.IsLive() || !player.CheckColl(this._sptIcon))
return;
switch(this._type)
{
case 0: // 铲子
this._timerProtect = Const.TIME_WALL_IRON;
this._statToggle.Reset();
this._SetBaseWall(true);
break;
case 1: // 升级
player.Upgrade();
break;
case 2: // 加命
App.Game.LifeInc();
break;
case 3: // 防弹
player.StartBulProof(Const.TIME_BULPRF_BONUS);
break;
case 4: // 炸弹
for(i = 1; i < Const.MAX_TANK; ++i)
{
if(App.Scene.Tanks[i].IsLive())
App.Scene.Tanks[i].Hit(true); //强制爆炸
}
break;
case 5: // 定时
this._timerFreeze = 1000;
break;
}
// 奖励500分
App.Game.SocreAdd(500);
// 取消闪烁
this._sptIcon.Show();
this._sptIcon.SetFrame(Const.FR_SCORE + 4);
this._state = BonusState.SCORE;
},
/**
* 设置总部围墙
*/
_SetBaseWall: function(iron)
{
var skip = iron? 0 : 0xF;
//-------------------x--y---tile
App.Scene.SetMapCell(5, 11, 14 + skip); // 上-左
App.Scene.SetMapCell(6, 11, 18 + skip); // 上-中
App.Scene.SetMapCell(7, 11, 10 + skip); // 上-右
App.Scene.SetMapCell(5, 12, 16 + skip); // 左
App.Scene.SetMapCell(7, 12, 11 + skip); // 右
}
});
<file_sep>/README.md
Tank
====
通过实现一个坦克游戏,加深自己对javascript OOP的理解 | 7e81cb26e5f2610022448e41185f4fe9d60b437f | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | JimmyBryant/Tank | 0ea7ac377bfcd1acdfd5435aa252785903b49cfa | cbfb476f3cd84d4154864ce229e295c2e1885afc |
refs/heads/master | <file_sep>//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
var someTrueThing = true
someTrueThing == true
var someInt = 10
while someInt < 20 {
// run the same code
someInt += 1
print("hello")
}
someInt
var numLoops = 0
runTheLoop: while someInt < 10 {
numLoops += 1
someInt += 3
// println(someInt)
switch numLoops {
case 0...100:
print(someInt)
if someInt % 2 == 0 {
print("\(someInt) is even")
continue runTheLoop
} else if someInt % 5 == 0 {
print("\(someInt) is divisible by 5")
// break runTheLoop
}
case 101...1000:
print("something else")
default:
print("this is the default")
}
}
var abc = 3
while abc < 1000000000 {
print("\(abc)")
abc = abc * abc * abc
}
var theList = ["The", "List", "is", "full", "of", "names"]
theList.count
while theList.count < 10 {
theList.append("Another Name")
}
print(theList)
print(theList[0..<4])
print(theList[0...3])
<file_sep>//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
var userStatus:Bool = false
userStatus == true
userStatus == false
str == "Hello, playground"
str == "Hello playground"
var temp = 75
if temp < 80 {
print("It is cold outside")
}
else {
print("It is warm outside")
}
temp <= 80
temp == 80
temp >= 80
temp != 80
!userStatus
if userStatus {
print("User is logged in")
}
else if !userStatus {
print("user is not logged in")
}
else {
print("something went wrong")
}
var userStringStatus = "Some_String"
if userStringStatus == "Some_String" {
print("User is logged in")
}
else if userStringStatus == "Abc" {
print("user is not logged in")
}
else {
print("something went wrong")
}
<file_sep>//: Playground - noun: a place where people can play
import UIKit
// Strings are encloses in "" and not ''
var str = "Hello, playground"
str = "Changing the value of the string "
// String concatination
str + str + str
var hello = "Hi, there "
var name = "kan1shka9"
hello + name
name = "Random"
hello + name
// Multiplication does not work with strings
// hello * 5
4 * 6
var some_num = 3
var message = "\(some_num) is the number that was wanted"<file_sep>//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
// var abc = 10.0
var abc:Double = 1000
abc
abc + 100
abc * 100
abc / 10
abc / 10.0
10 % 4
10 % 2 == 0
abc / (20*(40/22))
// Modulo
abc.truncatingRemainder(dividingBy: 3)
var i = 0
i += 1
abc += 1
i -= 1
abc -= 1
abc += 21
abc -= 21
// Round
floor(123.21)
floor(123.78)
ceil(123.21)
ceil(123.78)
var var_1:Double = 1515
var to_round = var_1 * 0.01
floor(to_round) * 100
<file_sep>//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
var str2:String
str2 = "hello there"
"\(str) hi"
func helloThere(name:String, favNum:Int)->String {
return "Hello There, \(name)! Your favourite number is: \(favNum) and you use the currency \u{1F496}"
}
var str3 = helloThere(name: "kan1shka9", favNum: 99)
var myName = "Kanishka"
var myJob = "Jobless"
var rain = "R@1n"
"Hi, my name is \(myName) and I am currently \(myJob)"
"But I am still making it \(rain) \u{24}" | 95d75b169460eef77b147f3b66e16a9572bbc558 | [
"Swift"
] | 5 | Swift | Kan1shka9/Learning-Swift | 3fe565174ae0a4404deaaef0be584db3a053639d | ffc0e8ad7d68a0dd39234be0aa0f900832b2754c |
refs/heads/master | <repo_name>brydon1/developers-against-humanity<file_sep>/README.md
# Developers Against Humanity
Developers Against Humanity: an online card game for terrible developers and system administrators.
## Language
Idk, Node.js, PHP, C#, C++?
## Dependencies
Hell if I know.
## Main Objective
Make a multi-player Cards Against Humanity game with a custom deck of cards (in JSON form) with support for:
- Different decks
- Multiple "rooms" and the ability to give those rooms custom names
- A way to track points
- Maybe some spiffy animations
- Easy installation to an Apache or Nginx web server (so, no funky ports)
- Rando Cardissian mode
<file_sep>/other/githelp.md
# Developers Against Humanity
# Git Help Document
## Who is this document for?
This is a very superficial document for beginners to Git and GitHub. If you already know how to use GitHub or you've used it in another software engineering course, you probably won't find this very useful.
If this is your first time using Git and GitHub, then this document will show you the fundamentals of committing, pulling, pushing, and branches.
## What is Git?
Git is a repository-based version control system. It's used as a unified place for source code, and its collaborative nature fosters open-source development. Git isn't to be confused with GitHub. GitHub provides Git as a service. GitHub isn't the only Git provider; GitLab, BitBucket, and Microsoft Azure Pipelines are all GAAS tools, and they have their own advantages and disadvantages.
Think of it like a shared Google Drive. You can share that folder with others, and they can contribute code. Git is like the protocol that allows you to upload and edit files to your Google Drive, but GitHub is like Google Drive itself.
However, Git differs from Google Drive in several key ways.
1. There's no real-time synchronization. This might seem like a disadvantage, but it is critical in ensuring that everyone has the same version of the code as a starting point, and when people create solutions, they can replace the existing code base with a tested and working solution. If it were real-time, people would end up pushing code that could be untested, unstable, or poorly written.
2. Git is open-source itself. Unlike Google Drive, the underlying technology behind Git is open-source, originally created by the same person behind the Linux family of operating systems: Linus Torvalds.
3. Git is designed for plaintext files (`*.txt`, `*.cpp`, `*.js`, `*.R`, `*.py`), not interpreted files (`*.docx`, `*.pdf`, `*.jpg`, `*.mp4`).
4. Git is designed for small files, generally under 100MB per file. Larger files often require additional software to "lazy-load" them, like Git Large File Support (LFS). GitHub warns you if you try to update or add a file larger than 50MB and blocks files larger than 100MB.
Git uses a local-remote model. When you clone (download) a repository to your computer, you create a local version of the repository on your computer, based off of the remote repository, like the one on GitHub. You then make changes to your local version and use your local version to update the remote repository.
However, sending entire files every time would be wasteful of network and server resources, so Git, by design, only transfers the differences in the files that you've updated, referred to as deltas. So, say you were editing a file and you added a couple of lines to the end of the file. Git would notice that all you've done is add a couple of lines, so it'd only send those couple of lines to the remote repository, rather than copying the entire file again. Nifty, huh!
## How to use Git
### Accounts
If you are working with the Developers Against Humanity project, you'll need to have a GitHub account, as we're using GitHub for our version control remote repository. You need not pay to upgrade your subscription, however, you can enable some special features for free by joining [GitHub's education program](https://education.github.com).
### Installing Git
If you don't already have it, you'll need to install Git on your computer. If you have a Mac, you might already have it, but if you haven't explicitly installed it on Windows, you'll need to.
**For all of this to work properly, you'll also want to install Atom, a fairly feature-rich text-editor.** To get Atom, go to [this link](https://atom.io/).
#### On a Mac
You have it easy. Open up a new Terminal window. Attempt to run `git status`. If Git is installed, it will report that the current directory is not a valid Git repository. If Git is not installed, it will report that the command `git` cannot be found. Your Mac should automatically prompt you to install Git from the developer tools.
#### On Windows
1. Go to [the Git SCM downloads page](https://git-scm.com/downloads). Download the latest stable version of Git to your computer.
2. Launch the installer. You might need to provide UAC permission to allow the installer to run properly.
3. Accept the terms and conditions of use, then click Next.
4. Use the default installation directory (normally `C:\Program Files\Git`), then click Next.
5. Under Windows Explorer integration, make sure that Git Bash Here is enabled, Git LFS is enabled, that `.git*` configuration files are associated with the default text editor, and that `.sh` files are to be run with Bash. Click Next.
6. Leave the program shortcuts in the default location, then click Next.
7. When asked what editor you would like Git to use, select **Atom** as the default editor, NOT Vim!
8. When asked how you want to use Git from the command line, select "Git from the command line and also from 3rd-party software." Click Next.
9. Ensure that you're using the OpoenSSL library, then click Next.
10. Ensure that Git treats line endings in text files by checking out Windows-style, but commits Unix-style endings. This ensures that collaborators who are not using Windows see the text files correctly. Click Next.
11. Select MinTTY as the default terminal emulator for Git Bash, then click Next.
12. Ensure that the checkbox for "Enable Git Credential Manager" is checked, and optionally enable file system caching. Click Install.
13. Git might take a while to install. Just be patient.
14. Once completed, uncheck the box to view the release notes, then close the setup wizard by clicking Next.
15. To use Git, right-click on the Start menu, then select the Windows PowerShell. You can now navigate directories just the same as your Unix counterparts.
#### On Linux
Git should be installed by default.
### Cloning the Remote Repository
To clone a remote repository, such as one on GitHub, navigate to the GitHub repository. On the right-side, you should see a green button to Clone/Download. Click it, then copy the URL that's shown under Clone via HTTPS.
On your local computer, open a new PowerShell or Terminal window (depending on whether you're on Windows or macOS) and navigate to the desired directory. To go up a directory, use `cd ..` (change directory) and to enter a directory, use `cd <directoryName>`. To list the contents of the current directory, use `ls` (list).
Once you're in the desired directory in your terminal, say `~/kim3/development`, type `git clone <remote repository URL` and strike Return. For example, if I wanted to copy this repository, I could use `git clone https://github.com/kim3-sudo/developers-against-humanity.git`. To paste in a terminal window, do NOT use Ctrl+C or Cmd+C! Instead, **right-click on the mouse inside of the terminal window to paste**. Ctrl+C is the standard keyboard interrupt and will cancel the current operation!
After the clone from remote repository completes, you can enter that repository by using `cd <repository name>`.
### Making a New File
Now that you're in the new directory, you can open up a Windows Explorer or macOS Finder window and navigate to that same directory that you were in above, such as your Documents folder or a special development folder. There, you'll see the repository that you cloned as a directory, and you can enter it.
In the text editor of your choice (Atom is a pretty good one), you can write out a plaintext file, such as a C++, Python, JavaScript, or text file. Save (Ctrl+S/Cmd+S) in the desired location in the git directory that you cloned earlier.
By default, Git does not track new files. Tracking means that Git is actively following the changes that a file undergoes. An untracked file will not ever get put in the remote repository. To add the file, you need to go back to your terminal. To see if there are files that are untracked, use `git status`. Any untracked files will show up in green, while newly tracked files will show up in green. To track a file, you'll need to add it to the Git configuration file. To do so, run `git add <filename>`. You can also add an entire directory (`git add <directoryname>`). If you want to add everything that's not tracked and showing up in red, you can run `git add .`, which will add everything in the current directory and anything deeper.
Once you add a file to the Git configuration file, you shouldn't ever have to re-add it.
*Helpful Hint: Git doesn't support empty directories. If you really want to keep a directory, you can make a new, empty file named `.gitkeep`. It doesn't need to contain anything, but it lets Git know that it shouldn't get rid of that directory.*
### Editing an Existing File
Most of the time, you'll be editing files that already exist. Before you begin editing, you'll want to make sure that you have the latest version of the remote repository. This decreases the chance of a merge conflict bunging things up. A merge conflict occurs when two people try to edit the same file, and one person's edits would overwrite the other person's edits.
To get the latest version of the remote repository, run `git pull`.
Now, in your Windows Explorer or macOS Finder window, you can find the file that you'd like to edit and open it in your text editor of choice. Edit to your heart's content. Pour your soul into it. Baby it and nurture it. Cherish it forever. Edit that document.
Once you're done, save the file (Ctrl+S/Cmd+S) and exit your text editor (or don't, some text editors support live changes, like Atom). Now, go back to your terminal window. To make sure that your changes will be committed, run a `git status`. If you see that your changes are going to be committed (files in green), then you're good to go. If you need to add your file to the tracking list, use the `git add <filename>` thing from above.
Commit your file. Committing your file indicates that you've made changes that you'd like to push to the remote repository for everyone else to use. It's kind of like saving your file to the server (in reality, it's a little bit more complicated than that, but that's a good way to think about it). You can commit as much or as little new material as you want. To commit all of the tracked changes, use `git commit -m "Enter your commit message here."`, where your commit message is a succinct description of what changes you've made. If possible, keep it under 50 characters. Include emojis, as indicated in the [CONTRIBUTING.md document](https://github.com/kim3-sudo/developers-against-humanity/blob/master/CONTRIBUTING.md). Here are some example commit messages:
- :tada: (`:tada:`) Add a function for Rando Cardissian
- :toilet: (`:toilet:`) Cleaned up helperfunction.prog
- :lock: (`:lock:`) Updated npm cards dependency to v5.1.3
Pull the latest version of the remote repository by using `git pull`. Always pull before pushing.
Finally, push your changes up to the remote repository by using `git push`.
### Creating and Merging Branches
A branch is like your own version of the repository. You can make a branch to test a new feature, fix a bug, or update some documentation. Once you're satisifed with the state of your branch, you can re-merge it into the master branch. Making a branch has several effects:
- It prevents anyone else from accidentally messing with your WIP code.
- It provides a safeguard so that your new code doesn't break everything else.
- It makes sure that someone else's newly added work doesn't break your work.
- It allows you to roll back broken code by just deleting the branch.
---
You can make a new branch in one-of-two ways: the GitHub way and the terminal way.
#### The GitHub Way
Log into GitHub and access the repository. On the left side, click on "Branch: master." Start typing in the name of your desired new branch, then click on the button to create the new branch.
#### The Terminal Way
Open your terminal and navigate to the local Git repository on your machine. Use the command `git checkout -b <branch-name>`. Don't use the `-b` flag if you are trying to check out an existing branch.
---
Now, you can switch to the new branch. To switch to your new branch in GitHub, click on the "Branch: master" button (or whatever the current branch is), then on the desired existing branch. To switch to an existing branch in the terminal, use the command `git checkout <branch-name>`. Branch names can never have a space. Please refer to the [CONTRIBUTING.md document](https://github.com/kim3-sudo/developers-against-humanity/blob/master/CONTRIBUTING.md) for instructions on how to name your branches.
To check which branch you're on, you can use the command `git branch` in the terminal.
When you make a change to a branch (like editing a file in a branch), your changes are isolated to that branch only. So, if you were to make a change to the `helloworld.py` file in the `tester-hello-world` branch, those changes would not be shown in the master branch.
Once you're sure that your branch is compatible and you're ready to merge your branch into the master branch, it's time to make a pull request. Do NOT use `git merge` in the terminal, please. To make a pull request, open GitHub in your browser, then go to the repository. Switch over to the branch that you'd like to merge. There should be a button to make a new pull request. Give your pull request a good name, then create the request. Now, you'll negotiate your merges. If there are no merge conflicts, then you'll only have to pass a code review by an administrator. This code review is mandated to ensure high software quality. If there are merge conflicts, then you'll have to resolve those. Look at the two versions of the code (yours and the other, changed code) and decide what should go where. You can use a software like Atom to view the merge conflicts in plaintext.
Once your code has been approved and there are no merge conflicts, you'll be able to merge your branch into the master, all through GitHub. After your branch has been merged, you'll be informed that you can safely delete the branch. Please delete your old branches!
## Try It Yourself
Wow, that was a lot of information. If you'd like to try to use Git now, you can fork [this repository](https://github.com/kim3-sudo/gittutorial). Open this link in a web browser, then click on the "Fork" button in the upper right corner. This will make a version of this repository in your account that you can play with. Try the following:
1. Clone your version of the repository to your local computer
2. Open an existing file in your text editor
3. Edit that file and save
4. Commit your changes
5. Pull, then push your new changes
6. Create a new file
7. Add some text to that file and save
8. Add that new file to the tracking file (`git add`)
9. Commit the file
10. Pull, then push your new changes
Branches
1. Make a new branch
2. Checkout that branch (`git checkout`)
3. Make some changes on your new branch (edits, commits, pulls, pushes)
4. Make a new pull request in GitHub and push your branch to the master
## Questions?
If you have questions about using Git or GitHub, ask me via DM in Slack.
<file_sep>/htmlmover.sh
#!/bin/bash
echo "Copying HTML to HTML directory."
oldassets=/var/www/html/assets
oldindex=/var/www/html/index.html
if [ -d "$oldassets" ]; then
echo "ASSETS DIRECTORY:$oldassets EXISTS!"
echo "ATTEMPTING TO REMOVE $oldassets"
{ # try
sudo rm -rv /var/www/html/assets
} || { # catch
echo "ISSUE REMOVING $oldassets!"
echo "PLEASE CHECK THIS DIRECTORY MANUALLY!"
}
fi
if test -f "$oldindex"; then
echo "index.html EXISTS!"
echo "ATTEMPTING TO REMOVE $oldindex"
{ # try`
sudo rm -v /var/www/html/index.html
} || { # catch
echo "ISSUE REMOVING $oldindex!"
echo "PLEASE CHECK INDEX FILE MANUALLY!"
}
fi
echo "ATTEMPTING COPY OF ASSETS"
{ # try
sudo cp -r web/assets /var/www/html
echo "NEW assets COPY SUCCESSFUL!"
} || { # catch
echo "assets COPY FAILED!"
echo "PLEASE CHECK AND COPY DIRECTORIES MANUALLY!"
}
echo "ATTEMPTING COPY OF index.html"
{ # try
sudo cp index.html /var/www/html &&
echo "NEW index.html COPY SUCCESSFUL!"
} || { # catch
echo "index.html COPY FAILED!"
echo "PLEASE CHECK AND COPY INDEX MANUALLY!"
}
echo "CURRENT CONTENTS OF YOUR /VAR/WWW/HTML DIRECTORY:" ls -la /var/www/html
| 59f26dfa4a8173b9da1aed8850d5a6bd4c400e1c | [
"Markdown",
"Shell"
] | 3 | Markdown | brydon1/developers-against-humanity | 5e8e2bb86c3ab3b1d2dd2e899d94bd7bcd1d27f5 | 76aaab3e34f7ee52eab68431d88e0c16c6c57afe |
refs/heads/master | <file_sep>#pragma once
#include <filesystem>
#include <vector>
#include <GL/glew.h>
#include "../Math/Vector.h"
namespace render
{
struct MeshLoader
{
std::vector<Vector4> vertices;
std::vector<Vector2> tex_coords;
std::vector<Vector4> normals;
std::vector<GLsizei> vert_ids;
std::vector<GLsizei> tex_ids;
std::vector<GLsizei> norm_ids;
bool has_normals, has_textures;
static MeshLoader fromFile(std::filesystem::path const& mesh_file);
GLsizei size() const;
void parseVec(std::istream& in);
void parseTex(std::istream& in);
void parseNorm(std::istream& in);
void parseFace(std::istream& in);
};
class Mesh
{
GLuint vao_id_;
GLsizei vertex_count_;
public:
Mesh(MeshLoader const& loaded);
static Mesh fromFile(std::filesystem::path const& mesh_file);
Mesh(Mesh const& other) = delete;
Mesh& operator=(Mesh const& other) = delete;
Mesh(Mesh&& other) noexcept;
Mesh& operator=(Mesh&& other) noexcept;
~Mesh();
[[nodiscard]] GLuint vaoId() const;
[[nodiscard]] GLsizei vertexCount() const;
};
}
<file_sep>#include "Filter.h"
#include <iostream>
#include <array>
#include <GL/glew.h>
#include "../Callback.h"
#include "../Config.h"
namespace render
{
Filter::Filter(config::Window const& window, Ptr<Pipeline const> const pipeline)
: pipeline_ {pipeline}
{
std::array const quad_vertices {
// vertex attributes for a quad that fills the entire screen in Normalized Device Coordinates.
// positions
-1.0f, 1.0f, 0.0f, 1.0f,
-1.0f, -1.0f, 0.0f, 0.0f,
1.0f, -1.0f, 1.0f, 0.0f,
// texCoords
-1.0f, 1.0f, 0.0f, 1.0f,
1.0f, -1.0f, 1.0f, 0.0f,
1.0f, 1.0f, 1.0f, 1.0f
};
auto const [width, height] = window.size;
GLuint quad_buffer;
// screen quad VAO
glGenVertexArrays(1, &quad_id_);
glBindVertexArray(quad_id_);
{
glGenBuffers(1, &quad_buffer);
glBindBuffer(GL_ARRAY_BUFFER, quad_buffer);
{
glBufferData(GL_ARRAY_BUFFER, sizeof(quad_vertices), &quad_vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(Pipeline::Position);
glVertexAttribPointer(Pipeline::Position, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), nullptr);
glEnableVertexAttribArray(Pipeline::Texture);
glVertexAttribPointer(
Pipeline::Texture,
2,
GL_FLOAT,
GL_FALSE,
4 * sizeof(float),
reinterpret_cast<void*>(2 * sizeof(float))
);
}
}
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glDeleteBuffers(1, &quad_buffer);
glGenFramebuffers(1, &fb_id_);
glBindFramebuffer(GL_FRAMEBUFFER, fb_id_);
{
// create a color attachment texture
glGenTextures(1, &tex_id_);
glBindTexture(GL_TEXTURE_2D, tex_id_);
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex_id_, 0);
}
glGenRenderbuffers(1, &rb_id_);
glBindRenderbuffer(GL_RENDERBUFFER, rb_id_);
{
// create a renderbuffer object for depth and stencil attachment (we won't be sampling these)
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height);
// use a single renderbuffer object for both a depth AND stencil buffer.
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rb_id_);
// now actually attach it
// now that we actually created the framebuffer and added all attachments we want to check if it is actually complete now
}
#if _DEBUG
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
std::cerr << "ERROR::FRAMEBUFFER:: Framebuffer is not complete!" << std::endl;
#endif
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
Filter::Filter(Filter&& other) noexcept
: fb_id_ {std::exchange(other.fb_id_, 0)},
tex_id_ {std::exchange(other.tex_id_, 0)},
rb_id_ {std::exchange(other.rb_id_, 0)},
quad_id_ {std::exchange(other.quad_id_, 0)},
pipeline_ {std::exchange(other.pipeline_, nullptr)}
{}
Filter& Filter::operator=(Filter&& other) noexcept
{
if (this != &other)
{
fb_id_ = std::exchange(other.fb_id_, 0);
tex_id_ = std::exchange(other.tex_id_, 0);
rb_id_ = std::exchange(other.rb_id_, 0);
quad_id_ = std::exchange(other.quad_id_, 0);
pipeline_ = std::exchange(other.pipeline_, nullptr);
}
return *this;
}
Filter::~Filter()
{
if (pipeline_ != nullptr)
{
glDeleteVertexArrays(1, &quad_id_);
glDeleteFramebuffers(1, &fb_id_);
glDeleteRenderbuffers(1, &rb_id_);
glDeleteTextures(1, &tex_id_);
}
}
void Filter::bind()
{
// render
// ------
// bind to framebuffer and draw scene as we normally would to color texture
glBindFramebuffer(GL_FRAMEBUFFER, fb_id_);
glEnable(GL_DEPTH_TEST); // enable depth testing (is disabled for rendering screen-space quad)
// make sure we clear the framebuffer's content
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void Filter::finish()
{
// now bind back to default framebuffer and draw a quad plane with the attached framebuffer color texture
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDisable(GL_DEPTH_TEST); // disable depth test so screen-space quad isn't discarded due to depth test.
// clear all relevant buffers
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(pipeline_->programId());
//usar os shaders aqui
glBindVertexArray(quad_id_);
glBindTexture(GL_TEXTURE_2D, tex_id_); // use the color attachment texture as the texture of the quad plane
glDrawArrays(GL_TRIANGLES, 0, 6);
glUseProgram(0);
glEnable(GL_DEPTH_TEST);
}
void Filter::resize(callback::WindowSize const size)
{
auto const [width, height] = size;
glBindFramebuffer(GL_FRAMEBUFFER, fb_id_);
glBindTexture(GL_TEXTURE_2D, tex_id_);
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex_id_, 0);
}
glBindRenderbuffer(GL_RENDERBUFFER, rb_id_);
{
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height);
}
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
}
<file_sep>#include "JsonFile.h"
#include <filesystem>
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <ctime>
#include "../Math/Matrix.h"
#include "../Math/Quaternion.h"
#include "../Math/Vector.h"
#include "../lib/json/json.hpp"
#include "../Engine/Engine.h"
#include "../Render/Scene.h"
using json = nlohmann::json;
namespace jsonFile
{
json* j;
std::filesystem::path default_dir_ = "JSON/";
//render::Scene& saveScene;
std::string input, saveInput;
bool saving = false, loading = false;
bool saveFile(config::Settings settings, std::filesystem::path planeMesh, std::filesystem::path pieceMesh) {
json FileToSave;
FileToSave["Settings"]["Version"]["Major"] = settings.version.major;
FileToSave["Settings"]["Version"]["Minor"] = settings.version.minor;
FileToSave["Settings"]["Window"]["Title"] = settings.window.title;
FileToSave["Settings"]["Window"]["Size"]["Width"] = settings.window.size.width;
FileToSave["Settings"]["Window"]["Size"]["Height"] = settings.window.size.height;
FileToSave["Settings"]["Window"]["Mode"] = settings.window.mode;
FileToSave["Settings"]["Window"]["VSync"] = settings.window.vsync;
std::string planeMeshDir{ planeMesh.u8string() };
FileToSave["Meshes"]["Plane"] = planeMeshDir;
std::string pieceMeshDir{ pieceMesh.u8string() };
FileToSave["Meshes"]["Piece"] = pieceMeshDir;
time_t rawtime = time(NULL);
tm timeinfo = {};
char buffer[80];
localtime_s(&timeinfo, &rawtime);
//asctime_s(buffer, 80, &timeinfo);
strftime(buffer, sizeof(buffer), "%Y-%m-%d-%H-%M-%S", &timeinfo);
std::string timestamp(buffer);
std::string filePath = default_dir_.u8string() + timestamp + ".json";
std::ofstream file(filePath);
file << FileToSave;
std::cout << "File has been saved to " << filePath << std::endl;
return true;
// An attempt to implement filename input.
/*saving = true;
while (saving) {
std::cout << "Type the name of the file to save (enter c to cancel): ";
std::cin >> saveInput;
if (saveInput == "c") {
saving = false;
return false;
}
if (input.substr(input.size() - 5) != ".json") {
saveInput += ".json";
}
std::ifstream checkForFile(default_dir_ / saveInput);
std::string overCheck;
if (checkForFile.good()) {
bool overwrite = true;
while (overwrite) {
std::cout << "This file already exists, do you wish to overwrite it? (y/n) ";
std::cin >> overCheck;
if (overCheck != "y" || overCheck != "n")
std::cout << "Your input is invalid, please try again.";
else if (overCheck == "n")
overwrite = false;
else if (overCheck == "y") {
std::ofstream file(saveInput, std::ofstream::trunc);
file << FileToSave;
overwrite = false;
saving = false;
return true;
}
}
}
else {
std::ofstream file(saveInput);
file << FileToSave;
saving = false;
return true;
}
}*/
//return false;
}
bool loadFile() {
std::ifstream file(default_dir_ / "2021-01-19-21-24-18.json");
json jf = json::parse(file);
config::Settings settings;
settings.version.major = jf["Settings"]["Version"]["Major"];
settings.version.minor = jf["Settings"]["Version"]["Minor"];
std::string title = jf["Settings"]["Window"]["Title"];
const char* ctitle = title.c_str();
settings.window.title = ctitle;
settings.window.size.width = jf["Settings"]["Window"]["Size"]["Width"];
settings.window.size.height = jf["Settings"]["Window"]["Size"]["Height"];
int mode = jf["Settings"]["Window"]["Mode"];
settings.window.mode = static_cast<config::Mode>(mode);
int vsync = jf["Settings"]["Window"]["VSync"];
settings.window.vsync = static_cast<config::VSync>(vsync);
//planeMesh /= jf["Meshes"]["Plane"];
//pieceMesh /= jf["Meshes"]["Piece"];
loading = false;
std::cout << "Version: " <<settings.version.major << "." << settings.version.minor << std::endl;
std::cout << "Title: " << settings.window.title << std::endl;
std::cout << "Size: " << settings.window.size.width << ", " << settings.window.size.height << std::endl;
std::cout << "Mode: " << mode << std::endl;
std::cout << "VSync: " << vsync << std::endl;
return true;
// An attempt to implement filename input.
/*while (loading) {
std::cout << "Type the name of the file to load (make sure it's in the JSON folder): ";
std::cin >> input;
if (input.size() >= 6 && input.substr(input.size() - 5) == ".json") {
std::ifstream file(default_dir_ / input);
std::ifstream file(default_dir_ / input);
json jf = json::parse(file);
config::Settings settings;
settings.version.major = jf["Settings"]["Version"]["Major"];
settings.version.minor = jf["Settings"]["Version"]["Minor"];
std::string title = jf["Settings"]["Window"]["Title"];
char* ctitle = new char[title.length() + 1];
settings.window.title = ctitle;
settings.window.size.width = jf["Settings"]["Window"]["Size"]["Width"];
settings.window.size.height = jf["Settings"]["Window"]["Size"]["Height"];
int mode = jf["Settings"]["Window"]["Mode"];
settings.window.mode = static_cast<config::Mode>(mode);
int vsync = jf["Settings"]["Window"]["VSync"];
settings.window.vsync = static_cast<config::VSync>(vsync);
//planeMesh /= jf["Meshes"]["Plane"];
//pieceMesh /= jf["Meshes"]["Piece"];
loading = false;
return true;
}
else
std::cout << "The file name you entered is invalid.";
}*/
return false;
}
}
<file_sep>#include "Quaternion.h"
Quaternion Quaternion::identity()
{
return {1, 0, 0, 0};
}
Quaternion Quaternion::fromComponents(Vector4 const components)
{
auto const [t, x, y, z] = components;
return {t, x, y, z};
}
Quaternion Quaternion::fromRotationMatrix(Matrix4 const& rotation)
{
auto const [a, b, c, _] = rotation.trace();
auto const w = std::sqrt(std::max(0.f, 1 + a + b + c)) / 2;
auto const tx = std::sqrt(std::max(0.f, 1 + a - b - c)) / 2;
auto const ty = std::sqrt(std::max(0.f, 1 - a + b - c)) / 2;
auto const tz = std::sqrt(std::max(0.f, 1 - a - b + c)) / 2;
auto const x = std::copysign(tx, rotation[9] - rotation[6]);
auto const y = std::copysign(ty, rotation[2] - rotation[8]);
auto const z = std::copysign(tz, rotation[4] - rotation[1]);
return {w, x, y, z};
}
Quaternion Quaternion::fromParts(float const t, Vector3 const vec)
{
auto const [x, y, z] = vec;
return {t, x, y, z};
}
Quaternion Quaternion::fromAngleAxis(Radians const angle, Axis const axis)
{
auto const t = cos(angle / 2.f);
auto const v = sin(angle / 2.f);
switch (axis)
{
case Axis::X: return Quaternion {t, v, 0, 0}.cleaned().normalized();
case Axis::Y: return Quaternion {t, 0, v, 0}.cleaned().normalized();
case Axis::Z: return Quaternion {t, 0, 0, v}.cleaned().normalized();
default:
throw std::invalid_argument("Invalid axis provided for quaternion");
}
}
Quaternion Quaternion::fromAngleAxis(Radians const angle, Vector3 const axis)
{
auto const t = cos(angle / 2.f);
auto const scale = sin(angle / 2.f);
auto const [x, y, z] = axis.normalized() * scale;
Quaternion const res = {t, x, y, z};
return res.cleaned().normalized();
}
Quaternion Quaternion::angleBetween(Vector3 const vec1, Vector3 const vec2)
{
auto const norm = std::sqrt(vec1.quadrance() * vec2.quadrance());
auto const real_part = norm + vec1 * vec2;
return fromParts(real_part, vec1 % vec2).cleaned().normalized();
}
std::pair<Radians, Vector4> Quaternion::toAngleAxis() const
{
auto const [t, v] = normalized().toParts();
auto const angle = 2.f * std::acos(t);
auto const scale = std::sqrt(1.f - t * t);
auto const [x, y, z] = scale < Epsilon ? Vector3 {1.f, 0.f, 0.f} : v * (1 / scale);
return {angle, {x, y, z, 1}};
}
std::pair<float, Vector3> Quaternion::toParts() const { return {t, {x, y, z}}; }
Vector4 Quaternion::toComponents() const { return {t, x, y, z}; }
Matrix4 Quaternion::toRotationMatrix() const
{
auto const [t, x, y, z] = normalized();
auto const tx = 2.f * t * x;
auto const ty = 2.f * t * y;
auto const tz = 2.f * t * z;
auto const xx = 2.f * x * x;
auto const xy = 2.f * x * y;
auto const xz = 2.f * x * z;
auto const yy = 2.f * y * y;
auto const yz = 2.f * y * z;
auto const zz = 2.f * z * z;
return {
1.f - yy - zz, xy - tz, xz + ty, 0,
xy + tz, 1.f - xx - zz, yz - tx, 0,
xz - ty, yz + tx, 1.f - xx - yy, 0,
0, 0, 0, 1
};
}
float Quaternion::quadrance() const { return toComponents().quadrance(); }
float Quaternion::magnitude() const { return std::sqrt(quadrance()); }
Quaternion Quaternion::absolute() const { return fromComponents(toComponents().absolute()); }
Quaternion Quaternion::normalized() const { return fromComponents(toComponents().normalized()); }
Quaternion Quaternion::cleaned() const { return fromComponents(toComponents().cleaned()); }
Quaternion Quaternion::conjugated() const { return {t, -x, -y, -z}; }
Quaternion Quaternion::inverted() const { return conjugated() * (1.f / quadrance()); }
Quaternion Quaternion::lerp(float const scale, Quaternion const start, Quaternion end)
{
auto const dot = start.toComponents() * end.toComponents();
if (dot < 0) { end = -end; }
return (start + scale * (end - start)).cleaned().normalized();
}
Quaternion Quaternion::slerp(float const scale, Quaternion const start, Quaternion end)
{
constexpr auto DotThreshold = 0.9995;
auto dot = start.toComponents() * end.toComponents();
if (dot < 0)
{
end = -end;
dot = -dot;
}
if (dot > DotThreshold)
return (start + scale * (end - start)).cleaned().normalized();
auto const total = std::acos(dot);
auto const angle = total * scale;
auto const ratio = std::sin(angle) / std::sin(total);
auto const start_scale = std::cos(angle) - dot * ratio;
auto const end_scale = ratio;
return (start_scale * start + end_scale * end).cleaned().normalized();
}
Quaternion operator-(Quaternion const qtrn)
{
return Quaternion::fromComponents(-qtrn.toComponents());
}
Quaternion operator+(Quaternion const left, Quaternion const right)
{
return Quaternion::fromComponents(left.toComponents() + right.toComponents());
}
Quaternion operator-(Quaternion const left, Quaternion const right)
{
return Quaternion::fromComponents(left.toComponents() - right.toComponents());
}
Quaternion operator*(Quaternion const left, Quaternion const right)
{
return {
left.t * right.t - left.x * right.x - left.y * right.y - left.z * right.z,
left.t * right.x + left.x * right.t + left.y * right.z - left.z * right.y,
left.t * right.y - left.x * right.z + left.y * right.t + left.z * right.x,
left.t * right.z + left.x * right.y - left.y * right.x + left.z * right.t,
};
}
Quaternion operator*(Quaternion const left, float const right)
{
return Quaternion::fromComponents(left.toComponents() * right);
}
Quaternion operator*(float const left, Quaternion const right) { return right * left; }
bool operator==(Quaternion const left, Quaternion const right) { return left.toComponents() == right.toComponents(); }
bool operator!=(Quaternion const left, Quaternion const right) { return !(left == right); }
std::ostream& operator<<(std::ostream& os, Quaternion const q)
{
return os << '(' << q.t << ", " << q.x << "i, " << q.y << "j, " << q.z << "k)";
}
<file_sep>#pragma once
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include "Controller.h"
#include "GlfwHandle.h"
#include "../Render/Object.h"
#include "../Render/Scene.h"
namespace engine
{
class Engine
{
GlfwHandle glfw_;
callback::WindowSize size_;
std::filesystem::path snapshot_dir_;
int snap_num_;
public:
render::Scene scene;
MeshController mesh_controller;
TextureController texture_controller;
PipelineController pipeline_controller;
FilterController filter_controller;
ObjectController object_controller;
FileController file_controller;
private:
Engine(GlfwHandle glfw, render::Scene scene, config::Settings const& settings);
public:
static std::unique_ptr<Engine> init(GlfwHandle glfw, render::Scene scene, config::Settings const& settings);
Engine(Engine const&) = delete;
Engine& operator=(Engine const&) = delete;
Engine(Engine&&) = delete;
Engine& operator=(Engine&&) = delete;
[[nodiscard]] Ptr<GLFWwindow> window();
[[nodiscard]] callback::WindowSize windowSize() const;
void resize(callback::WindowSize size);
void resetControllers();
void setControllers(Ptr<render::Object const> object);
void snapshot();
void run();
void terminate();
};
}
<file_sep>#include "Matrix.h"
//identity
Matrix2 Matrix2::identity()
{
return {
1, 0,
0, 1
};
}
Matrix3 Matrix3::identity()
{
return {
1, 0, 0,
0, 1, 0,
0, 0, 1
};
}
Matrix4 Matrix4::identity()
{
return {
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
};
}
//dual
Matrix3 Matrix3::dual(Vector3 const of)
{
return {
0, -of.z, of.y,
of.z, 0, -of.x,
-of.y, of.x, 0
};
}
//scaling
Matrix4 Matrix4::scaling(Vector3 const by)
{
return {
by.x, 0, 0, 0,
0, by.y, 0, 0,
0, 0, by.z, 0,
0, 0, 0, 1
};
}
//translation
Matrix4 Matrix4::translation(Vector3 const by)
{
return {
1, 0, 0, by.x,
0, 1, 0, by.y,
0, 0, 1, by.z,
0, 0, 0, 1
};
}
//rotation
Matrix4 Matrix4::rotation(Axis const ax, Radians const angle)
{
auto const cos = std::cos(angle);
auto const sin = std::sin(angle);
switch (ax)
{
case Axis::X:
return {
1, 0, 0, 0,
0, cos, -sin, 0,
0, sin, cos, 0,
0, 0, 0, 1
};
case Axis::Y:
return {
cos, 0, sin, 0,
0, 1, 0, 0,
-sin, 0, cos, 0,
0, 0, 0, 1
};
case Axis::Z:
return {
cos, -sin, 0, 0,
sin, cos, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
};
default:
throw std::invalid_argument("Invalid axis provided for rotation matrix");
}
}
Matrix4 Matrix4::rotation(Vector3 const axis, Radians const angle)
{
auto const [x, y, z] = axis;
auto const sine = sin(angle);
auto const cosine = cos(angle);
auto const inv_cos = 1 - cosine;
return {
cosine + powf(x, 2) * inv_cos,
x * y * inv_cos - z * sine,
x * z * inv_cos + y * sine,
0,
x * y * inv_cos + z * sine,
cosine + powf(y, 2) * inv_cos,
y * z * inv_cos - x * sine,
0,
x * z * inv_cos - y * sine,
z * y * inv_cos + x * sine,
cosine + powf(z, 2) * inv_cos,
0,
0, 0, 0, 1
};
}
Matrix4 Matrix4::view(Vector3 const eye, Vector3 const center, Vector3 const up)
{
auto const v = (center - eye).normalized();
auto const s = (v % up).normalized();
auto const u = s % v;
Matrix4 const camera {
s.x, s.y, s.z, 0,
u.x, u.y, u.z, 0,
-v.x, -v.y, -v.z, 0,
0, 0, 0, 1
};
return (camera * translation(-eye)).transposed();
}
Matrix4 Matrix4::orthographic(
float const left,
float const right,
float const bottom,
float const top,
float const near,
float const far
)
{
auto const scale = scaling({2 / (right - left), 2 / (top - bottom), 2 / (far - near)});
auto const translate = translation({-(left + right) / 2, -(bottom + top) / 2, -(near + far) / 2});
auto res = scale * translate;
res[10] = 2 / (near - far);
return res.transposed();
}
Matrix4 Matrix4::perspective(Degrees const fov, float const aspect, float const near, float const far)
{
auto const d = 1 / tan(fov * DegToRad / 2);
return Matrix4 {
d / aspect, 0, 0, 0,
0, d, 0, 0,
0, 0, (near + far) / (near - far), (2 * near * far) / (near - far),
0, 0, -1, 0
}.transposed();
}
//determinat
float Matrix2::determinant() const { return inner[0] * inner[3] - inner[1] * inner[2]; }
float Matrix3::determinant() const
{
return inner[0] * (inner[4] * inner[8] - inner[5] * inner[7])
- inner[1] * (inner[3] * inner[8] - inner[5] * inner[6])
+ inner[2] * (inner[3] * inner[7] - inner[4] * inner[6]);
}
//transpose
Matrix2 Matrix2::transposed() const
{
Matrix2 res;
for (auto i = 0; i < N; i++)
for (auto j = 0; j < N; j++)
{
res[i * N + j] = inner[i + j * N];
}
return res;
}
Matrix3 Matrix3::transposed() const
{
Matrix3 res;
for (auto i = 0; i < N; i++)
for (auto j = 0; j < N; j++)
{
res[i * N + j] = inner[i + j * N];
}
return res;
}
Matrix4 Matrix4::transposed() const
{
Matrix4 res;
for (auto i = 0; i < N; i++)
for (auto j = 0; j < N; j++)
{
res[i * N + j] = inner[i + j * N];
}
return res;
}
// trace
Vector4 Matrix4::trace() const { return {inner[0], inner[5], inner[10], inner[15]}; }
//inverse
Matrix2 Matrix2::inverted() const
{
auto const det = determinant();
if (std::abs(det) < Epsilon) throw std::invalid_argument("Singular matrix can't have an inverse");
Matrix2 const r {inner[3], -inner[1], -inner[2], inner[0]};
return r * (1 / det);
}
Matrix3 Matrix3::inverted() const
{
auto const det = determinant();
if (std::abs(det) < Epsilon) throw std::invalid_argument("Singular matrix can't have an inverse");
auto const trans = transposed();
Matrix2 const m0 {trans[4], trans[5], trans[7], trans[8]};
Matrix2 const m1 {trans[3], trans[5], trans[6], trans[8]};
Matrix2 const m2 {trans[3], trans[4], trans[6], trans[7]};
Matrix2 const m3 {trans[1], trans[2], trans[7], trans[8]};
Matrix2 const m4 {trans[0], trans[2], trans[6], trans[8]};
Matrix2 const m5 {trans[0], trans[1], trans[6], trans[7]};
Matrix2 const m6 {trans[1], trans[2], trans[4], trans[5]};
Matrix2 const m7 {trans[0], trans[2], trans[3], trans[5]};
Matrix2 const m8 {trans[0], trans[1], trans[3], trans[4]};
Matrix3 const res = {
m0.determinant(),
-m1.determinant(),
m2.determinant(),
-m3.determinant(),
m4.determinant(),
-m5.determinant(),
m6.determinant(),
-m7.determinant(),
m8.determinant()
};
return res * (1 / det);
}
//operator[]
float Matrix2::operator[](size_t const index) const { return inner[index]; }
float Matrix3::operator[](size_t const index) const { return inner[index]; }
float Matrix4::operator[](size_t const index) const { return inner[index]; }
float& Matrix2::operator[](size_t const index) { return inner[index]; }
float& Matrix3::operator[](size_t const index) { return inner[index]; }
float& Matrix4::operator[](size_t const index) { return inner[index]; }
//operator ==
inline bool eps_eq(float const a, float const b)
{
return std::abs(a - b) < Epsilon;
}
bool operator==(Matrix2 const& left, Matrix2 const& right)
{
for (auto i = 0; i < left.Len; i++) if (!eps_eq(left[i], right[i])) return false;
return true;
}
bool operator==(Matrix3 const& left, Matrix3 const& right)
{
for (auto i = 0; i < left.Len; i++) if (!eps_eq(left[i], right[i])) return false;
return true;
}
bool operator==(Matrix4 const& left, Matrix4 const& right)
{
for (auto i = 0; i < left.Len; i++) if (!eps_eq(left[i], right[i])) return false;
return true;
}
//operator +
Matrix2 operator+(Matrix2 const& left, Matrix2 const& right)
{
Matrix2 res;
for (auto i = 0; i < left.Len; i++) { res[i] = left[i] + right[i]; }
return res;
}
Matrix3 operator+(Matrix3 const& left, Matrix3 const& right)
{
Matrix3 res;
for (auto i = 0; i < left.Len; i++) { res[i] = left[i] + right[i]; }
return res;
}
Matrix4 operator+(Matrix4 const& left, Matrix4 const& right)
{
Matrix4 res;
for (auto i = 0; i < left.Len; i++) { res[i] = left[i] + right[i]; }
return res;
}
//operator -
Matrix2 operator-(Matrix2 const& left, Matrix2 const& right)
{
Matrix2 res;
for (auto i = 0; i < left.Len; i++) { res[i] = left[i] - right[i]; }
return res;
}
Matrix3 operator-(Matrix3 const& left, Matrix3 const& right)
{
Matrix3 res;
for (auto i = 0; i < left.Len; i++) { res[i] = left[i] - right[i]; }
return res;
}
Matrix4 operator-(Matrix4 const& left, Matrix4 const& right)
{
Matrix4 res;
for (auto i = 0; i < left.Len; i++) { res[i] = left[i] - right[i]; }
return res;
}
//operator * scalar
Matrix2 operator*(Matrix2 const& left, float const right)
{
Matrix2 res;
for (auto i = 0; i < left.Len; i++) { res[i] = left[i] * right; }
return res;
}
Matrix3 operator*(Matrix3 const& left, float const right)
{
Matrix3 res;
for (auto i = 0; i < left.Len; i++) { res[i] = left[i] * right; }
return res;
}
Matrix4 operator*(Matrix4 const& left, float const right)
{
Matrix4 res;
for (auto i = 0; i < left.Len; i++) { res[i] = left[i] * right; }
return res;
}
Matrix2 operator*(float const left, Matrix2 const& right) { return right * left; }
Matrix3 operator*(float const left, Matrix3 const& right) { return right * left; }
Matrix4 operator*(float const left, Matrix4 const& right) { return right * left; }
//operator * matrix
Matrix2 operator*(Matrix2 const& left, Matrix2 const& right)
{
constexpr auto N = left.N;
Matrix2 res;
for (auto i = 0; i < N; i++)
for (auto j = 0; j < N; j++)
{
res[i * N + j] = left[i * N] * right[j] + left[i * N + 1] * right[j + N];
}
return res;
}
Matrix3 operator*(Matrix3 const& left, Matrix3 const& right)
{
constexpr auto N = left.N;
Matrix3 res;
for (auto i = 0; i < N; i++)
for (auto j = 0; j < N; j++)
{
res[i * N + j] =
left[i * N] * right[j] +
left[i * N + 1] * right[j + N] +
left[i * N + 2] * right[j + 2 * N];
}
return res;
}
Matrix4 operator*(Matrix4 const& left, Matrix4 const& right)
{
constexpr auto N = left.N;
Matrix4 res;
for (auto i = 0; i < N; i++)
for (auto j = 0; j < N; j++)
{
res[i * N + j] =
left[i * N] * right[j] +
left[i * N + 1] * right[j + N] +
left[i * N + 2] * right[j + 2 * N] +
left[i * N + 3] * right[j + 3 * N];
}
return res;
}
//operator * Vector
Vector2 operator*(Matrix2 const& left, Vector2 const right)
{
auto const [x, y] = right;
return {
left[0] * x + left[1] * y,
left[2] * x + left[3] * y
};
}
Vector3 operator*(Matrix3 const& left, Vector3 const right)
{
auto const [x, y, z] = right;
return {
left[0] * x + left[1] * y + left[2] * z,
left[3] * x + left[4] * y + left[5] * z,
left[6] * x + left[7] * y + left[8] * z
};
}
Vector4 operator*(Matrix4 const& left, Vector4 const right)
{
auto const [x, y, z, w] = right;
return {
left[0] * x + left[1] * y + left[2] * z + left[3] * w,
left[4] * x + left[5] * y + left[6] * z + left[7] * w,
left[8] * x + left[9] * y + left[10] * z + left[11] * w,
1
};
}
std::ostream& operator<<(std::ostream& os, Matrix2 const& mat)
{
for (auto i = 0; i < mat.Len; i += mat.N)
{
os << '(' << mat[i] << ", " << mat[i + 1] << ")\n";
}
return os;
}
std::ostream& operator<<(std::ostream& os, Matrix3 const& mat)
{
for (auto i = 0; i < mat.Len; i += mat.N)
{
os << '(' << mat[i] << ", " << mat[i + 1] << ", " << mat[i + 2] << ")\n";
}
return os;
}
std::ostream& operator<<(std::ostream& os, Matrix4 const& mat)
{
for (auto i = 0; i < mat.Len; i += mat.N)
{
os << '(' << mat[i] << ", " << mat[i + 1] << ", " << mat[i + 2] << ", " << mat[i + 3] << ")\n";
}
return os;
}
<file_sep>#include "Error.h"
#include <iostream>
#include <GL/glew.h>
namespace
{
std::string_view errorSource(GLenum const source)
{
switch (source)
{
case GL_DEBUG_SOURCE_API: return "API";
case GL_DEBUG_SOURCE_WINDOW_SYSTEM: return "window system";
case GL_DEBUG_SOURCE_SHADER_COMPILER: return "shader compiler";
case GL_DEBUG_SOURCE_THIRD_PARTY: return "third party";
case GL_DEBUG_SOURCE_APPLICATION: return "application";
case GL_DEBUG_SOURCE_OTHER: return "other";
default: exit(EXIT_FAILURE);
}
}
std::string_view errorType(GLenum const type)
{
switch (type)
{
case GL_DEBUG_TYPE_ERROR: return "error";
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: return "deprecated behavior";
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: return "undefined behavior";
case GL_DEBUG_TYPE_PORTABILITY: return "portability issue";
case GL_DEBUG_TYPE_PERFORMANCE: return "performance issue";
case GL_DEBUG_TYPE_MARKER: return "stream annotation";
case GL_DEBUG_TYPE_PUSH_GROUP: return "push group";
case GL_DEBUG_TYPE_POP_GROUP: return "pop group";
case GL_DEBUG_TYPE_OTHER_ARB: return "other";
default: exit(EXIT_FAILURE);
}
}
std::string_view errorSeverity(GLenum const severity)
{
switch (severity)
{
case GL_DEBUG_SEVERITY_HIGH: return "high";
case GL_DEBUG_SEVERITY_MEDIUM: return "medium";
case GL_DEBUG_SEVERITY_LOW: return "low";
case GL_DEBUG_SEVERITY_NOTIFICATION: return "notification";
default: exit(EXIT_FAILURE);
}
}
void error(
GLenum const source,
GLenum const type,
[[maybe_unused]] GLuint id,
GLenum const severity,
[[maybe_unused]] GLsizei length,
Ptr<char const> message,
[[maybe_unused]] Ptr<void const> user_param
)
{
std::cerr << "GL ERROR:" << std::endl;
std::cerr << " source: " << errorSource(source) << std::endl;
std::cerr << " type: " << errorType(type) << std::endl;
std::cerr << " severity: " << errorSeverity(severity) << std::endl;
std::cerr << " debug call: " << message << std::endl;
if (auto const engine = (engine::Engine*) user_param; engine && severity == GL_DEBUG_SEVERITY_HIGH)
{
engine->terminate();
}
}
}
namespace engine
{
void setupErrorCallback(Engine* engine)
{
glEnable(GL_DEBUG_OUTPUT);
glDebugMessageCallback(error, engine);
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE);
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_NOTIFICATION, 0, nullptr, GL_FALSE);
// params: source, type, severity, count, ids, enabled
}
void glfwErrorCallback(int error, const char* description)
{
std::cerr << "GLFW Error: " << description << std::endl;
std::cerr << "Press <return>.";
std::cin.ignore();
}
}
<file_sep>#include "Scene.h"
#include <cassert>
#include <filesystem>
#include <optional>
#include "../Engine/Engine.h"
namespace render
{
Scene::Scene(Builder&& builder)
: meshes_ {std::move(builder.meshes)},
shaders_ {std::move(builder.shaders)},
textures_ {std::move(builder.textures)},
filters_ {std::move(builder.filters)},
root_ {std::move(builder.root)},
default_shader_ {builder.default_shader},
light_position {builder.light_position},
camera_controller {*std::move(builder.camera)}
{ }
Scene Scene::setup([[maybe_unused]] engine::GlInit gl_init, config::Settings const& settings)
{
Builder b;
config::hooks::setupScene(b, settings);
assert(b.camera.has_value());
assert(b.default_shader != nullptr);
return b;
}
void Scene::render(engine::Engine& engine, double const elapsed_sec)
{
config::hooks::beforeRender(*this, engine, elapsed_sec);
camera_controller.update(engine.windowSize(), elapsed_sec);
scene_block_.update(camera_controller.camera.position(), light_position);
root_->update(elapsed_sec);
glUseProgram(default_shader_->programId());
root_->draw(Matrix4::identity(), default_shader_, *this);
config::hooks::afterRender(*this, engine, elapsed_sec);
}
void Scene::animate()
{
root_->animate();
}
void Scene::resizeFilters(callback::WindowSize const size)
{
for (auto& filter : filters_) { filter.resize(size); }
}
Texture const& Scene::defaultTexture() const { return default_texture_; }
}
<file_sep>#include <array>
#include <iostream>
#include <ostream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include "Utils.h"
#include "Engine/Engine.h"
#include "Engine/GlInit.h"
#include "Render/Mesh.h"
#include "Render/Object.h"
#include "Render/Shader.h"
#include "JSON/JsonFile.h"
namespace config::hooks
{
#pragma region Callbacks
Settings currentSettings;
std::filesystem::path currentPlaneMesh, currentPieceMesh;
void onWindowClose([[maybe_unused]] engine::Engine& engine) {}
void onWindowResize([[maybe_unused]] engine::Engine& engine, callback::WindowSize const size)
{
engine.resize(size);
}
void onMouseButton(engine::Engine& engine, callback::MouseButton const button)
{
if (button.button != GLFW_MOUSE_BUTTON_1) return;
if (button.action == GLFW_PRESS)
{
double x_pos, y_pos;
glfwGetCursorPos(engine.window(), &x_pos, &y_pos);
engine.scene.camera_controller.startDrag({x_pos, y_pos});
#if _DEBUG
std::cerr << "start pos: " << x_pos << ", " << y_pos << std::endl;
#endif
}
else if (button.action == GLFW_RELEASE)
{
engine.scene.camera_controller.finishDrag();
}
}
void onMouseMove(engine::Engine& engine, callback::MousePosition const position)
{
auto const button_state = glfwGetMouseButton(engine.window(), GLFW_MOUSE_BUTTON_1);
if (button_state == GLFW_PRESS)
{
#if _DEBUG
std::cerr << "position: " << position.x << ", " << position.y << std::endl;
#endif
engine.scene.camera_controller.rotateDrag(position);
}
}
void onMouseScroll([[maybe_unused]] engine::Engine& engine, double const scroll)
{
#if _DEBUG
std::cerr << "zoom: " << scroll << std::endl;
#endif
engine.scene.camera_controller.scroll(scroll);
}
void onKeyboardButton(engine::Engine& engine, callback::KeyboardButton const button)
{
if (button.action == GLFW_PRESS)
switch (button.key)
{
case GLFW_KEY_ESCAPE:
engine.terminate();
break;
#pragma region Function Keys
// Keybindings for functions not related with the scene.
case GLFW_KEY_F2:
engine.snapshot();
break;
case GLFW_KEY_F3:
engine.file_controller.set(engine::FileController::AssetType::Mesh);
std::cout << "set to load meshes" << std::endl;
break;
case GLFW_KEY_F4:
engine.file_controller.set(engine::FileController::AssetType::Texture);
std::cout << "set to load textures" << std::endl;
break;
case GLFW_KEY_F5:
if (const auto path = engine.file_controller.prev(); path != nullptr)
std::cout << "current selected asset: " << *path << std::endl;
else
std::cout << "no asset selected" << std::endl;
break;
case GLFW_KEY_F6:
if (const auto path = engine.file_controller.next(); path != nullptr)
std::cout << "current selected asset: " << *path << std::endl;
else
std::cout << "no asset selected" << std::endl;
break;
case GLFW_KEY_F7:
if (const auto path = engine.file_controller.get(); path != nullptr)
{
if (engine.file_controller.loadingMeshes())
{
try { engine.mesh_controller.load(render::MeshLoader::fromFile(*path)); }
catch (...) { }
}
else if (engine.file_controller.loadingTextures())
{
try { engine.texture_controller.load(render::TextureLoader::fromFile(*path)); }
catch (...) { }
}
else
{
std::cerr << "cannot load unknown asset" << std::endl;
}
}
else
{
std::cerr << "cannot load asset: none is selected" << std::endl;
}
break;
case GLFW_KEY_F11:
engine.scene.animate();
break;
case GLFW_KEY_F12:
engine.scene.camera_controller.camera.swapRotationMode();
break;
#pragma endregion Function Keys
#pragma region Object Movement
// Keybindings for moving the selected object, if any.
case GLFW_KEY_W:
if (auto const obj = engine.object_controller.get(); obj)
obj->transform.position.z -= 0.5;
break;
case GLFW_KEY_S:
if (auto const obj = engine.object_controller.get(); obj)
obj->transform.position.z += 0.5;
break;
case GLFW_KEY_A:
if (auto const obj = engine.object_controller.get(); obj)
obj->transform.position.x -= 0.5;
break;
case GLFW_KEY_D:
if (auto const obj = engine.object_controller.get(); obj)
obj->transform.position.x += 0.5;
break;
case GLFW_KEY_Q:
if (auto const obj = engine.object_controller.get(); obj)
obj->transform.position.y -= 0.5;
break;
case GLFW_KEY_E:
if (auto const obj = engine.object_controller.get(); obj)
obj->transform.position.y += 0.5;
break;
#pragma endregion Object Movement
#pragma region Object Lifetime
// Keybindings for creating a child on the selected object or deleting the selected object.
case GLFW_KEY_X:
engine.object_controller.remove();
engine.resetControllers();
break;
case GLFW_KEY_C:
engine.object_controller.create();
engine.resetControllers();
break;
#pragma endregion Object Lifetime
#pragma region Row1
// Keybindings for navigating the scene graph and selecting filters.
case GLFW_KEY_T:
engine.object_controller.recurse();
engine.resetControllers();
break;
case GLFW_KEY_Y:
engine.setControllers(engine.object_controller.parent());
break;
case GLFW_KEY_U:
engine.setControllers(engine.object_controller.prev());
break;
case GLFW_KEY_I:
engine.setControllers(engine.object_controller.next());
break;
case GLFW_KEY_O:
engine.filter_controller.prev();
break;
case GLFW_KEY_P:
engine.filter_controller.next();
break;
#pragma endregion Row1
#pragma region Row2
// Keybindings for manipulating the selected object's shaders, texture or mesh.
case GLFW_KEY_G:
if (auto const obj = engine.object_controller.get(); obj != nullptr)
engine.object_controller.get()->shaders = engine.pipeline_controller.prev();
break;
case GLFW_KEY_H:
if (auto const obj = engine.object_controller.get(); obj != nullptr)
engine.object_controller.get()->shaders = engine.pipeline_controller.next();
break;
case GLFW_KEY_J:
if (auto const obj = engine.object_controller.get(); obj != nullptr)
engine.object_controller.get()->texture = engine.texture_controller.prev();
break;
case GLFW_KEY_K:
if (auto const obj = engine.object_controller.get(); obj != nullptr)
engine.object_controller.get()->texture = engine.texture_controller.next();
break;
case GLFW_KEY_L:
if (auto const obj = engine.object_controller.get(); obj != nullptr)
engine.object_controller.get()->mesh = engine.mesh_controller.prev();
break;
case GLFW_KEY_SEMICOLON:
if (auto const obj = engine.object_controller.get(); obj != nullptr)
engine.object_controller.get()->mesh = engine.mesh_controller.next();
break;
case GLFW_KEY_N:
jsonFile::saveFile(currentSettings, currentPlaneMesh, currentPieceMesh);
break;
case GLFW_KEY_M:
jsonFile::loadFile();
break;
#pragma endregion Row2
}
}
#pragma endregion Callbacks
#pragma region OpenGl
void setupOpenGl(Settings const& settings)
{
auto const [width, height] = settings.window.size;
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glEnable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glDepthMask(GL_TRUE);
glDepthRange(0.0, 1.0);
glClearDepth(1.0);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glFrontFace(GL_CCW);
glViewport(0, 0, width, height);
}
#pragma endregion OpenGl
#pragma region Scene
void setupScene(render::Scene::Builder& builder, Settings const& settings)
{
using namespace std::filesystem;
using namespace render;
constexpr auto CubeMargin = 0.9f;
auto const Scale = Vector3::filled(CubeMargin);
auto const& [meshes, textures, shaders, filters, _] = settings.paths;
Ptr<Pipeline const> bp_pipeline, cel_pipeline;
std::array<Ptr<Pipeline const>, 12> filter_pipelines;
Ptr<Mesh const> plane_mesh, piece_mesh;
currentSettings = settings;
logTimeTaken(
"Loading Assets",
[&]()
{
plane_mesh = &builder.meshes.emplace_back(MeshLoader::fromFile(meshes / "Plane.obj"));
&builder.meshes.emplace_back(MeshLoader::fromFile(meshes / "Cube.obj"));
piece_mesh = &builder.meshes.emplace_back(MeshLoader::fromFile(meshes / "Sphere16.obj"));
currentPlaneMesh = meshes / "Plane.obj";
currentPieceMesh = meshes / "Sphere16.obj";
&builder.textures.emplace_back(TextureLoader::fromFile(textures / "awesomeface.png"));
}
);
logTimeTaken(
"Loading Shaders",
[&]()
{
bp_pipeline = &builder.shaders.emplace_back(
false,
Shader::fromFile(Shader::Vertex, shaders / "bp_vert.glsl"),
Shader::fromFile(Shader::Fragment, shaders / "bp_frag.glsl")
);
cel_pipeline = &builder.shaders.emplace_back(
false,
Shader::fromFile(Shader::Vertex, shaders / "cel_vert.glsl"),
Shader::fromFile(Shader::Fragment, shaders / "cel_frag.glsl")
);
builder.shaders.emplace_back(
true,
Shader::fromFile(Shader::Vertex, filters / "red_vert.glsl"),
Shader::fromFile(Shader::Fragment, filters / "red_frag.glsl")
);
builder.shaders.emplace_back(
true,
Shader::fromFile(Shader::Vertex, filters / "green_vert.glsl"),
Shader::fromFile(Shader::Fragment, filters / "green_frag.glsl")
);
builder.shaders.emplace_back(
true,
Shader::fromFile(Shader::Vertex, filters / "blue_vert.glsl"),
Shader::fromFile(Shader::Fragment, filters / "blue_frag.glsl")
);
builder.shaders.emplace_back(
true,
Shader::fromFile(Shader::Vertex, filters / "grayscale_vert.glsl"),
Shader::fromFile(Shader::Fragment, filters / "grayscale_frag.glsl")
);
builder.shaders.emplace_back(
true,
Shader::fromFile(Shader::Vertex, filters / "sepia_vert.glsl"),
Shader::fromFile(Shader::Fragment, filters / "sepia_frag.glsl")
);
builder.shaders.emplace_back(
true,
Shader::fromFile(Shader::Vertex, filters / "invert_vert.glsl"),
Shader::fromFile(Shader::Fragment, filters / "invert_frag.glsl")
);
builder.shaders.emplace_back(
true,
Shader::fromFile(Shader::Vertex, filters / "sharpen_vert.glsl"),
Shader::fromFile(Shader::Fragment, filters / "sharpen_frag.glsl")
);
builder.shaders.emplace_back(
true,
Shader::fromFile(Shader::Vertex, filters / "edge_vert.glsl"),
Shader::fromFile(Shader::Fragment, filters / "edge_frag.glsl")
);
builder.shaders.emplace_back(
true,
Shader::fromFile(Shader::Vertex, filters / "emboss_vert.glsl"),
Shader::fromFile(Shader::Fragment, filters / "emboss_frag.glsl")
);
builder.shaders.emplace_back(
true,
Shader::fromFile(Shader::Vertex, filters / "blur_vert.glsl"),
Shader::fromFile(Shader::Fragment, filters / "blur_frag.glsl")
);
builder.shaders.emplace_back(
true,
Shader::fromFile(Shader::Vertex, filters / "sketch_vert.glsl"),
Shader::fromFile(Shader::Fragment, filters / "sketch_frag.glsl")
);
builder.shaders.emplace_back(
true,
Shader::fromFile(Shader::Vertex, filters / "oilPainting_vert.glsl"),
Shader::fromFile(Shader::Fragment, filters / "oilPainting_frag.glsl")
);
std::transform(
builder.shaders.begin() + 2,
builder.shaders.end(),
filter_pipelines.begin(),
[](auto const& pipeline) { return &pipeline; }
);
}
);
logTimeTaken(
"Creating Filters",
[&]()
{
for (auto const pipeline : filter_pipelines)
builder.filters.emplace_back(settings.window, pipeline);
}
);
logTimeTaken(
"Setting up scene",
[&]()
{
builder.light_position = Vector3 {4, 4, 4};
builder.camera = Camera(20, Vector3::filled(0), Pipeline::Camera);
builder.default_shader = bp_pipeline;
auto& plane = builder.root->emplaceChild(plane_mesh, Vector4 {0.6, 0.6, 0.6, 1});
plane.shininess = 128.f;
auto& figure = plane.emplaceChild(cel_pipeline);
figure.transform = {{0.5, 0.5, 0}};
auto& l = figure.emplaceChild();
l.transform = {{1, 0, 0}, Quaternion::fromAngleAxis(Pi, Axis::Y)};
l.animation = {
l.transform, {{1, 1, 1}, Quaternion::fromAngleAxis(2, {0.7, 0.2, 0.7})}
};
{
auto const color = Vector4 {0.7, 0, 0, 1};
auto& c1 = l.emplaceChild(piece_mesh, color);
auto& c2 = l.emplaceChild(piece_mesh, color);
auto& c3 = l.emplaceChild(piece_mesh, color);
auto& c4 = l.emplaceChild(piece_mesh, color);
c1.transform.position = {0, 0, 0};
c2.transform.position = {1, 0, 0};
c3.transform.position = {0, 1, 0};
c4.transform.position = {0, 2, 0};
for (auto element : {&c1, &c2, &c3, &c4})
element->transform.scaling = Scale;
}
auto& t1 = figure.emplaceChild();
t1.transform = {{-1, 1, 0}, Quaternion::fromAngleAxis(Pi * 3 / 2, Axis::Z)};
t1.animation = {
t1.transform, {{0, 0, -2}, Quaternion::fromAngleAxis(-Pi * 2, Axis::Z)}
};
auto& t2 = figure.emplaceChild();
t2.transform = {{0, 3, 0}, Quaternion::fromAngleAxis(Pi, Axis::Z)};
t2.animation = {
t2.transform, {{3, 4, 0}, Quaternion::fromAngleAxis(Pi / 2, Axis::X)}
};
{
constexpr auto color1 = Vector4 {0, 0.7, 0, 1};
constexpr auto color2 = Vector4 {0, 0, 0.7, 1};
for (auto [t, color] : std::array {std::pair {&t1, color1}, std::pair {&t2, color2}})
{
auto& c1 = t->emplaceChild(piece_mesh, color);
auto& c2 = t->emplaceChild(piece_mesh, color);
auto& c3 = t->emplaceChild(piece_mesh, color);
auto& c4 = t->emplaceChild(piece_mesh, color);
c1.transform.position = {0, 0, 0};
c2.transform.position = {-1, 0, 0};
c3.transform.position = {1, 0, 0};
c4.transform.position = {0, 1, 0};
for (auto element : {&c1, &c2, &c3, &c4})
element->transform.scaling = Scale;
}
}
auto& line = figure.emplaceChild();
line.transform = {{-2, 0, 0}};
line.animation = {
line.transform, {{0, 0, 0}, Quaternion::fromAngleAxis(Pi / 4, Axis::Y)}
};
{
constexpr auto color = Vector4 {0.7, 0, 0.7, 1};
auto& c1 = line.emplaceChild(piece_mesh, color);
auto& c2 = line.emplaceChild(piece_mesh, color);
auto& c3 = line.emplaceChild(piece_mesh, color);
auto& c4 = line.emplaceChild(piece_mesh, color);
c1.transform.position = {0, 0, 0};
c2.transform.position = {0, 1, 0};
c3.transform.position = {0, 2, 0};
c4.transform.position = {0, 3, 0};
for (auto element : {&c1, &c2, &c3, &c4})
element->transform.scaling = Scale;
}
}
);
}
void beforeRender(render::Scene& scene, engine::Engine& engine, double const elapsed_sec)
{
if (auto filter = engine.filter_controller.get(); filter != nullptr)
filter->bind();
}
void afterRender(render::Scene& scene, engine::Engine& engine, double const elapsed_sec)
{
if (auto filter = engine.filter_controller.get(); filter != nullptr)
filter->finish();
}
#pragma endregion Scene
}
int main()
{
using namespace config;
auto const settings = Settings {
Version {4, 3},
Window {
u8"Tetris 3D",
WindowSize {640, 480},
Mode::Windowed,
VSync::On
},
Paths {
"Assets/Meshes",
"Assets/Textures",
"Assets/Shaders",
"Assets/Shaders/Filters",
"Snapshots"
}
};
try
{
auto engine = logTimeTaken(
"Initialization",
[&]()
{
auto glfw = engine::GlfwHandle {settings};
auto glew = engine::GlInit {settings};
auto scene = render::Scene::setup(std::move(glew), settings);
return engine::Engine::init(std::move(glfw), std::move(scene), settings);
}
);
engine->run();
}
catch (std::exception e)
{
std::cerr << e.what() << std::endl;
exit(EXIT_FAILURE);
}
}
<file_sep>#pragma once
#include <chrono>
#include <iostream>
template <class T>
using OptPtr = T*;
template <class T>
using Ptr = T*;
template <bool Pred, class F>
using ReturnsVoid = std::enable_if_t<std::is_void_v<std::invoke_result_t<F>> == Pred>;
template <class Run, typename = ReturnsVoid<false, Run>>
auto logTimeTaken(std::string_view const name, Run run)
{
using namespace std::chrono;
auto const start = steady_clock::now();
auto temp = run();
auto const end = steady_clock::now();
auto const diff = end - start;
std::cerr << name << " took " << duration_cast<milliseconds>(diff).count() << " ms." << std::endl;
return temp;
}
template <class Run, typename = ReturnsVoid<true, Run>>
void logTimeTaken(std::string_view const name, Run run)
{
using namespace std::chrono;
auto const start = steady_clock::now();
run();
auto const end = steady_clock::now();
auto const diff = end - start;
std::cerr << name << " took " << duration_cast<milliseconds>(diff).count() << " ms." << std::endl;
}
<file_sep>#include "Vector.h"
#include "Matrix.h"
Vector2 Vector2::filled(float const fill) { return {fill, fill}; }
Vector3 Vector3::filled(float const fill) { return {fill, fill, fill}; }
Vector4 Vector4::filled(float const fill) { return {fill, fill, fill, fill}; }
Vector2 Vector2::from(float const array[2]) { return {array[0], array[1]}; }
Vector3 Vector3::from(float const array[3]) { return {array[0], array[1], array[2]}; }
Vector4 Vector4::from(float const array[4]) { return {array[0], array[1], array[2], array[3]}; }
Vector3::operator Vector2() const { return {x, y}; }
Vector4::operator Vector2() const { return {x, y}; }
Vector2::operator Vector3() const { return {x, y, 0}; }
Vector4::operator Vector3() const { return {x, y, z}; }
Vector2::operator Vector4() const { return {x, y, 0, 0}; }
Vector3::operator Vector4() const { return {x, y, z, 0}; }
Vector2 Vector2::absolute() const { return {std::abs(x), std::abs(y)}; }
Vector3 Vector3::absolute() const { return {std::abs(x), std::abs(y), std::abs(z)}; }
Vector4 Vector4::absolute() const { return {std::abs(x), std::abs(y), std::abs(z), std::abs(w)}; }
Vector2 Vector2::normalized() const
{
auto const m = magnitude();
return {x / m, y / m};
}
Vector3 Vector3::normalized() const
{
auto const m = magnitude();
return {x / m, y / m, z / m};
}
Vector4 Vector4::normalized() const
{
auto const m = magnitude();
return {x / m, y / m, z / m, w / m};
}
Vector2 Vector2::cleaned() const
{
auto const abs = absolute();
auto const nx = abs.x > Epsilon ? x : 0;
auto const ny = abs.y > Epsilon ? y : 0;
return {nx, ny};
}
Vector3 Vector3::cleaned() const
{
auto const abs = absolute();
auto const nx = abs.x > Epsilon ? x : 0;
auto const ny = abs.y > Epsilon ? y : 0;
auto const nz = abs.z > Epsilon ? z : 0;
return {nx, ny, nz};
}
Vector4 Vector4::cleaned() const
{
auto const abs = absolute();
auto const nx = abs.x > Epsilon ? x : 0;
auto const ny = abs.y > Epsilon ? y : 0;
auto const nz = abs.z > Epsilon ? z : 0;
auto const nw = abs.w > Epsilon ? w : 0;
return {nx, ny, nz, nw};
}
float Vector2::quadrance() const { return *this * *this; }
float Vector3::quadrance() const { return *this * *this; }
float Vector4::quadrance() const { return *this * *this; }
float Vector2::magnitude() const { return std::sqrt(quadrance()); }
float Vector3::magnitude() const { return std::sqrt(quadrance()); }
float Vector4::magnitude() const { return std::sqrt(quadrance()); }
Vector2 operator-(Vector2 const vec) { return {-vec.x, -vec.y}; }
Vector3 operator-(Vector3 const vec) { return {-vec.x, -vec.y, -vec.z}; }
Vector4 operator-(Vector4 const vec) { return {-vec.x, -vec.y, -vec.z, -vec.w}; }
Vector2 operator+(Vector2 const left, Vector2 const right) { return {left.x + right.x, left.y + right.y}; }
Vector3 operator+(Vector3 const left, Vector3 const right)
{
return {left.x + right.x, left.y + right.y, left.z + right.z};
}
Vector4 operator+(Vector4 const left, Vector4 const right)
{
return {left.x + right.x, left.y + right.y, left.z + right.z, left.w + right.w};
}
Vector2 operator+(Vector2 const vec, float const scalar) { return vec + Vector2::filled(scalar); }
Vector3 operator+(Vector3 const vec, float const scalar) { return vec + Vector3::filled(scalar); }
Vector4 operator+(Vector4 const vec, float const scalar) { return vec + Vector4::filled(scalar); }
Vector2 operator+(float const scalar, Vector2 const vec) { return vec + scalar; }
Vector3 operator+(float const scalar, Vector3 const vec) { return vec + scalar; }
Vector4 operator+(float const scalar, Vector4 const vec) { return vec + scalar; }
Vector2 operator-(Vector2 const left, Vector2 const right) { return {left.x - right.x, left.y - right.y}; }
Vector3 operator-(Vector3 const left, Vector3 const right)
{
return {left.x - right.x, left.y - right.y, left.z - right.z};
}
Vector4 operator-(Vector4 const left, Vector4 const right)
{
return {left.x - right.x, left.y - right.y, left.z - right.z, left.w - right.w};
}
Vector2 operator-(Vector2 const vec, float const scalar) { return vec - Vector2::filled(scalar); }
Vector3 operator-(Vector3 const vec, float const scalar) { return vec - Vector3::filled(scalar); }
Vector4 operator-(Vector4 const vec, float const scalar) { return vec - Vector4::filled(scalar); }
Vector2 operator-(float const scalar, Vector2 const vec) { return Vector2::filled(scalar) - vec; }
Vector3 operator-(float const scalar, Vector3 const vec) { return Vector3::filled(scalar) - vec; }
Vector4 operator-(float const scalar, Vector4 const vec) { return Vector4::filled(scalar) - vec; }
Vector2 operator*(Vector2 const vec, float const scalar) { return {vec.x * scalar, vec.y * scalar}; }
Vector3 operator*(Vector3 const vec, float const scalar) { return {vec.x * scalar, vec.y * scalar, vec.z * scalar}; }
Vector4 operator*(Vector4 const vec, float const scalar)
{
return {vec.x * scalar, vec.y * scalar, vec.z * scalar, vec.w * scalar};
}
Vector2 operator*(float const scalar, Vector2 const vec) { return vec * scalar; }
Vector3 operator*(float const scalar, Vector3 const vec) { return vec * scalar; }
Vector4 operator*(float const scalar, Vector4 const vec) { return vec * scalar; }
float operator*(Vector2 const left, Vector2 const right) { return left.x * right.x + left.y * right.y; }
float operator*(Vector3 const left, Vector3 const right)
{
return left.x * right.x + left.y * right.y + left.z * right.z;
}
float operator*(Vector4 const left, Vector4 const right)
{
return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
}
Vector3 operator%(Vector3 const left, Vector3 const right) { return Matrix3::dual(left) * right; }
Vector4 operator%(Vector4 const left, Vector4 const right) { return Matrix3::dual(left) * Vector3(right); }
bool operator==(Vector2 const left, Vector2 const right)
{
auto const [x, y] = (left - right).absolute();
return x < Epsilon && y < Epsilon;
}
bool operator==(Vector3 const left, Vector3 const right)
{
auto const [x, y, z] = (left - right).absolute();
return x < Epsilon && y < Epsilon && z < Epsilon;
}
bool operator==(Vector4 const left, Vector4 const right)
{
auto const [x, y, z, w] = (left - right).absolute();
return x < Epsilon && y < Epsilon && z < Epsilon && w < Epsilon;
}
bool operator!=(Vector2 const left, Vector2 const right) { return !(left == right); }
bool operator!=(Vector3 const left, Vector3 const right) { return !(left == right); }
bool operator!=(Vector4 const left, Vector4 const right) { return !(left == right); }
std::ostream& operator<<(std::ostream& os, Vector2 const v)
{
return os << '{' << v.x << ", " << v.y << '}';
}
std::ostream& operator<<(std::ostream& os, Vector3 const v)
{
return os << '{' << v.x << ", " << v.y << ", " << v.z << '}';
}
std::ostream& operator<<(std::ostream& os, Vector4 const v)
{
return os << '{' << v.x << ", " << v.y << ", " << v.z << ", " << v.w << '}';
}
std::istream& operator>>(std::istream& is, Vector2& v) { return is >> v.x >> v.y; }
std::istream& operator>>(std::istream& is, Vector3& v) { return is >> v.x >> v.y >> v.z; }
std::istream& operator>>(std::istream& is, Vector4& v) { return is >> v.x >> v.y >> v.z >> v.w; }
<file_sep>#include "GlfwHandle.h"
#include <iostream>
#include <stdexcept>
#include "Error.h"
namespace
{
GLFWwindow* setupWindow(config::Window const& window)
{
auto const [title, size, fullscreen, vsync] = window;
auto const monitor = static_cast<bool>(fullscreen) ? glfwGetPrimaryMonitor() : nullptr;
auto const win = glfwCreateWindow(size.width, size.height, title, monitor, nullptr);
if (!win)
throw std::runtime_error("Unable to create Window");
glfwMakeContextCurrent(win);
glfwSetInputMode(win, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
glfwSetCursor(win, glfwCreateStandardCursor(GLFW_HAND_CURSOR));
glfwSwapInterval(static_cast<bool>(vsync));
return win;
}
}
namespace engine
{
GlfwHandle::GlfwHandle(config::Settings const& settings)
{
auto const& [version, window, _] = settings;
glfwSetErrorCallback(glfwErrorCallback);
if (!glfwInit())
throw std::runtime_error("Failed to initialize GLFW");
try
{
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, version.major);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, version.minor);
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE);
window_ = setupWindow(window);
#if _DEBUG
std::cerr << "GLFW " << glfwGetVersionString() << std::endl;
#endif
}
catch (...)
{
glfwTerminate();
throw;
}
}
GlfwHandle::GlfwHandle(GlfwHandle&& other) noexcept
: window_ {std::exchange(other.window_, nullptr)} {}
GlfwHandle& GlfwHandle::operator=(GlfwHandle&& other) noexcept
{
if (this != &other)
{
window_ = std::exchange(other.window_, nullptr);
}
return *this;
}
GlfwHandle::~GlfwHandle()
{
if (window_)
{
glfwDestroyWindow(window_);
glfwTerminate();
}
}
double GlfwHandle::getTime() const { return glfwGetTime(); }
bool GlfwHandle::windowClosing() const { return glfwWindowShouldClose(window_); }
void GlfwHandle::registerEngine(Engine* engine)
{
callback::setupCallbacks(window_, engine);
}
void GlfwHandle::closeWindow()
{
callback::onManualWindowClose(window_);
glfwSetWindowShouldClose(window_, GLFW_TRUE);
}
void GlfwHandle::swapBuffers() { glfwSwapBuffers(window_); }
void GlfwHandle::pollEvents() { glfwPollEvents(); }
}
<file_sep>#pragma once
#include <filesystem>
#include "FreeImage.h"
#include "GL/glew.h"
namespace render
{
struct TextureLoader
{
struct Deleter
{
void operator()(FIBITMAP* data) const;
};
using Buffer = std::unique_ptr<FIBITMAP, Deleter>;
static TextureLoader fromFile(std::filesystem::path const& texture_file);
static TextureLoader white(unsigned len);
unsigned width, height;
Buffer data;
};
class Texture
{
GLuint tex_id_;
public:
Texture(TextureLoader&& texture);
static Texture fromFile(std::filesystem::path const& texture_file);
static Texture white();
Texture(Texture const& other) = delete;
Texture& operator=(Texture const& other) = delete;
Texture(Texture&& other) noexcept;
Texture& operator=(Texture&& other) noexcept;
~Texture();
[[nodiscard]] GLuint texId() const;
};
}
<file_sep>#include "Engine.h"
#include "Error.h"
#include <FreeImage.h>
#include <string>
namespace engine
{
Engine::Engine(GlfwHandle glfw, render::Scene scene, config::Settings const& settings)
: glfw_ {std::move(glfw)},
scene {std::move(scene)},
mesh_controller {&this->scene.meshes_},
texture_controller {&this->scene.textures_},
pipeline_controller {&this->scene.shaders_},
filter_controller {&this->scene.filters_},
object_controller {this->scene.root_.get()},
file_controller {settings.paths}
{
auto const [width, height] = settings.window.size;
size_ = {width, height};
snapshot_dir_ = settings.paths.snapshot;
snap_num_ = 1;
create_directory(snapshot_dir_);
glfw_.registerEngine(this);
setupErrorCallback(this);
}
std::unique_ptr<Engine> Engine::init(GlfwHandle glfw, render::Scene scene, config::Settings const& settings)
{
return std::unique_ptr<Engine> {new Engine(std::move(glfw), std::move(scene), settings)};
}
Ptr<GLFWwindow> Engine::window() { return glfw_.window_; }
callback::WindowSize Engine::windowSize() const { return size_; }
void Engine::resize(callback::WindowSize const size)
{
glViewport(0, 0, size.width, size.height);
scene.resizeFilters(size);
size_ = size;
}
void Engine::resetControllers()
{
mesh_controller.reset();
texture_controller.reset();
pipeline_controller.reset();
}
void Engine::setControllers(Ptr<render::Object const> const object)
{
if (object != nullptr)
{
mesh_controller.set(object->mesh);
texture_controller.set(object->texture);
pipeline_controller.set(object->shaders);
}
}
void Engine::snapshot()
{
#if FREEIMAGE_COLORORDER == FREEIMAGE_COLORORDER_BRG
constexpr auto Format = GL_BGR;
#else
constexpr auto Format = GL_RGB;
#endif
auto const [width, height] = size_;
auto const stride = width * 3;
std::vector<BYTE> pixels(stride * height);
glReadPixels(0, 0, width, height, Format, GL_UNSIGNED_BYTE, pixels.data());
// Convert to FreeImage format & save to file
auto const image = FreeImage_ConvertFromRawBits(pixels.data(), width, height, stride, 24, 0, 0, 0, false);
auto const filename = "snapshot" + std::to_string(snap_num_) + ".png";
auto const path = snapshot_dir_ / filename;
#ifdef _DEBUG
std::cerr << "saving snapshot to " << path << std::endl;
auto const res = FreeImage_SaveU(FIF_PNG, image, path.c_str(), PNG_DEFAULT);
std::cerr << (res ? "succeeded" : "failed") << std::endl;
#else
FreeImage_SaveU(FIF_PNG, image, path.c_str(), PNG_DEFAULT);
#endif
snap_num_++;
// Free resources
FreeImage_Unload(image);
}
void Engine::run()
{
auto last_time = glfw_.getTime();
while (!glfw_.windowClosing())
{
auto const now = glfw_.getTime();
auto const delta = now - last_time;
last_time = now;
////////////////////////////////
// Render scene
// Double Buffers
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
scene.render(*this, delta);
///////////////////////////////
glfw_.swapBuffers();
glfw_.pollEvents();
}
}
void Engine::terminate() { glfw_.closeWindow(); }
}
<file_sep>#pragma once
#include "Mesh.h"
#include "Shader.h"
#include "Texture.h"
#include "Transform.h"
#include "../Utils.h"
namespace render
{
class Scene;
struct Object
{
[[nodiscard]] explicit Object(
OptPtr<Object> parent,
OptPtr<Mesh const> mesh,
Vector4 color,
OptPtr<Pipeline const> shaders = nullptr,
OptPtr<Texture const> texture = nullptr
);
[[nodiscard]] explicit Object(
OptPtr<Object> parent = nullptr,
OptPtr<Pipeline const> shaders = nullptr,
OptPtr<Texture const> texture = nullptr
);
void animate();
void update(double elapsed_sec);
void draw(Matrix4 const& parent_transform, OptPtr<Pipeline const> parent_shaders, Scene const& scene) const;
Object& emplaceChild(
OptPtr<Mesh const> mesh,
Vector4 color,
OptPtr<Pipeline const> shaders = nullptr,
OptPtr<Texture const> texture = nullptr
);
Object& emplaceChild(
OptPtr<Pipeline const> shaders = nullptr,
OptPtr<Texture const> texture = nullptr
);
bool removeChild(Ptr<Object> child);
OptPtr<Object> parent;
OptPtr<Mesh const> mesh;
OptPtr<Pipeline const> shaders;
OptPtr<Texture const> texture;
Vector4 color;
Vector3 ambient_color = Vector3::filled(0.11f);
Vector3 specular_color = Vector3::filled(0.15f);
float shininess = 32;
Transform transform;
std::optional<Animation> animation;
std::list<Object> children;
};
}
<file_sep>#pragma once
#include "Utils.h"
struct Vector3;
struct Vector4;
struct Vector2
{
static Vector2 filled(float fill);
static Vector2 from(float const array[2]);
operator Vector3() const;
operator Vector4() const;
float quadrance() const;
float magnitude() const;
Vector2 absolute() const;
Vector2 normalized() const;
Vector2 cleaned() const;
float x, y;
};
Vector2 operator-(Vector2 vec);
Vector2 operator+(Vector2 left, Vector2 right);
Vector2 operator+(float scalar, Vector2 vec);
Vector2 operator+(Vector2 vec, float scalar);
Vector2 operator-(Vector2 left, Vector2 right);
Vector2 operator-(float scalar, Vector2 vec);
Vector2 operator-(Vector2 vec, float scalar);
Vector2 operator*(Vector2 vec, float scalar);
Vector2 operator*(float scalar, Vector2 vec);
float operator*(Vector2 left, Vector2 right);
bool operator==(Vector2 left, Vector2 right);
bool operator!=(Vector2 left, Vector2 right);
std::ostream& operator<<(std::ostream& os, Vector2 v);
std::istream& operator>>(std::istream& is, Vector2& v);
struct Vector3
{
static Vector3 filled(float fill);
static Vector3 from(float const array[3]);
operator Vector2() const;
operator Vector4() const;
float quadrance() const;
float magnitude() const;
Vector3 absolute() const;
Vector3 normalized() const;
Vector3 cleaned() const;
float x, y, z;
};
Vector3 operator-(Vector3 vec);
Vector3 operator+(Vector3 left, Vector3 right);
Vector3 operator+(float scalar, Vector3 vec);
Vector3 operator+(Vector3 vec, float scalar);
Vector3 operator-(Vector3 left, Vector3 right);
Vector3 operator-(float scalar, Vector3 vec);
Vector3 operator-(Vector3 vec, float scalar);
Vector3 operator*(Vector3 vec, float scalar);
Vector3 operator*(float scalar, Vector3 vec);
float operator*(Vector3 left, Vector3 right);
Vector3 operator%(Vector3 left, Vector3 right);
bool operator==(Vector3 left, Vector3 right);
bool operator!=(Vector3 left, Vector3 right);
std::ostream& operator<<(std::ostream& os, Vector3 v);
std::istream& operator>>(std::istream& is, Vector3& v);
struct Vector4
{
static Vector4 filled(float fill);
static Vector4 from(float const array[4]);
operator Vector2() const;
operator Vector3() const;
float quadrance() const;
float magnitude() const;
Vector4 absolute() const;
Vector4 normalized() const;
Vector4 cleaned() const;
float x, y, z, w;
};
Vector4 operator-(Vector4 vec);
Vector4 operator+(Vector4 left, Vector4 right);
Vector4 operator+(float scalar, Vector4 vec);
Vector4 operator+(Vector4 vec, float scalar);
Vector4 operator-(Vector4 left, Vector4 right);
Vector4 operator-(float scalar, Vector4 vec);
Vector4 operator-(Vector4 vec, float scalar);
Vector4 operator*(Vector4 vec, float scalar);
Vector4 operator*(float scalar, Vector4 vec);
float operator*(Vector4 left, Vector4 right);
Vector4 operator%(Vector4 left, Vector4 right);
bool operator==(Vector4 left, Vector4 right);
bool operator!=(Vector4 left, Vector4 right);
std::ostream& operator<<(std::ostream& os, Vector4 v);
std::istream& operator>>(std::istream& is, Vector4& v);
<file_sep>#pragma once
#include <filesystem>
#include "Utils.h"
namespace config
{
struct WindowSize
{
int width, height;
};
struct Version
{
int major, minor;
};
enum class Mode : bool
{
Windowed = false,
Fullscreen = true,
};
enum class VSync: bool
{
Off = false,
On = true,
};
struct Window
{
Ptr<char const> title;
WindowSize size;
Mode mode;
VSync vsync;
};
struct Paths
{
std::filesystem::path meshes;
std::filesystem::path textures;
std::filesystem::path shaders;
std::filesystem::path filters;
std::filesystem::path snapshot;
};
struct Settings
{
Version version;
Window window;
Paths paths;
};
}
<file_sep>#include "Object.h"
#include <cassert>
#include "Scene.h"
namespace render
{
Object::Object(
OptPtr<Object> parent,
OptPtr<Mesh const> const mesh,
Vector4 const color,
OptPtr<Pipeline const> const shaders,
OptPtr<Texture const> const texture
) : parent {parent},
mesh {mesh},
shaders {shaders},
texture {texture},
color {color}
{}
Object::Object(
OptPtr<Object> const parent,
OptPtr<Pipeline const> const shaders,
OptPtr<Texture const> const texture
) : parent {parent},
mesh {nullptr},
shaders {shaders},
texture {texture},
color {Vector4::filled(1.0f)}
{}
void Object::animate()
{
if (animation)
{
if (animation->active()) { animation->reverse(); }
else { animation->activate(); }
}
for (auto& child : children) { child.animate(); }
}
void Object::update(double const elapsed_sec)
{
if (animation && animation->active())
transform = animation->advance(elapsed_sec);
for (auto& child : children) { child.update(elapsed_sec); }
}
void Object::draw(
Matrix4 const& parent_transform,
OptPtr<Pipeline const> const parent_shaders,
Scene const& scene
) const
{
auto const shaders = this->shaders != nullptr ? this->shaders : parent_shaders;
assert(shaders != nullptr);
if (shaders != parent_shaders) { glUseProgram(shaders->programId()); }
{
auto const model_matrix = parent_transform * transform.toMatrix();
if (auto const [r, g, b, alpha] = color; mesh != nullptr && alpha != 0)
{
glUniform4f(shaders->colorId(), r, g, b, alpha);
if (auto const [r, g, b] = ambient_color; shaders->ambientId() != -1)
{
glUniform3f(shaders->ambientId(), r, g, b);
}
if (auto const [r, g, b] = specular_color; shaders->specularId() != -1)
{
glUniform3f(shaders->specularId(), r, g, b);
glUniform1f(shaders->shininessId(), shininess);
}
auto const texture_bind = texture != nullptr ? texture->texId() : scene.defaultTexture().texId();
glUniform1i(shaders->textureId(), 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture_bind);
glUniformMatrix4fv(shaders->modelId(), 1, GL_TRUE, model_matrix.inner);
glBindVertexArray(mesh->vaoId());
glDrawArrays(GL_TRIANGLES, 0, mesh->vertexCount());
}
for (auto const& child : children) { child.draw(model_matrix, shaders, scene); }
}
if (shaders != parent_shaders && parent_shaders != nullptr) { glUseProgram(parent_shaders->programId()); }
}
Object& Object::emplaceChild(
OptPtr<Mesh const> mesh,
Vector4 color,
OptPtr<Pipeline const> shaders,
OptPtr<Texture const> texture
)
{
return children.emplace_back(this, mesh, color, shaders, texture);
}
Object& Object::emplaceChild(OptPtr<Pipeline const> shaders, OptPtr<Texture const> texture)
{
return children.emplace_back(this, shaders, texture);
}
bool Object::removeChild(Ptr<Object> const child)
{
for (auto iter = children.begin(), end = children.end(); iter == end; ++iter)
{
if (&*iter == child)
{
children.erase(iter);
return true;
}
}
return false;
}
}
<file_sep>#pragma once
#include <variant>
#include <GL/glew.h>
#include "../Math/Matrix.h"
#include "../Math/Quaternion.h"
#include "../Math/Vector.h"
#include "../Callback.h"
namespace render
{
class CameraController;
class Camera
{
public:
using Rotation = std::variant<Matrix4, Quaternion>;
private:
GLuint cam_matrices_id_;
Vector3 focus_;
float distance_;
Rotation rotation_;
Vector3 position_ = {};
public:
Camera(float distance, Vector3 focus, GLuint view_id);
Camera(Camera const&) = delete;
Camera& operator=(Camera const&) = delete;
Camera(Camera&& other) noexcept;
Camera& operator=(Camera&&) noexcept;
~Camera();
void swapRotationMode();
void rotate(CameraController const& controller);
void rotate(double frame_delta);
void update(callback::WindowSize size, Vector2 drag_delta, float zoom);
[[nodiscard]] Vector3 position() const { return position_; }
private:
[[nodiscard]] Matrix4 rotationMatrix(Vector2 drag_delta) const;
[[nodiscard]] Rotation fullRotation(Vector2 drag_delta) const;
};
class CameraController
{
bool dragging_;
Vector2 drag_start_, drag_now_;
double scroll_;
public:
Camera camera;
CameraController(Camera camera);
void startDrag(callback::MousePosition mouse_position);
void rotateDrag(callback::MousePosition mouse_position);
void finishDrag();
void scroll(double by);
void update(callback::WindowSize size, double frame_delta);
[[nodiscard]] Vector2 dragDelta() const;
[[nodiscard]] bool isDragging() const;
[[nodiscard]] float scrollDelta(double frame_delta);
};
}
<file_sep>#include "Callback.h"
namespace
{
using namespace config::hooks;
[[nodiscard]] engine::Engine* getEngine(GLFWwindow* win)
{
return static_cast<engine::Engine*>(glfwGetWindowUserPointer(win));
}
void windowCloseCallback(GLFWwindow* win)
{
onWindowClose(*getEngine(win));
}
void windowSizeCallback(GLFWwindow* win, int const width, int const height)
{
onWindowResize(*getEngine(win), {width, height});
}
void mouseCallback(GLFWwindow* win, int const button, int const action, int const mods)
{
onMouseButton(*getEngine(win), {button, action, mods});
}
void cursorCallback(GLFWwindow* win, double const x_pos, double const y_pos)
{
onMouseMove(*getEngine(win), {x_pos, y_pos});
}
void scrollCallback(GLFWwindow* win, [[maybe_unused]] double const _, double const y_pos)
{
onMouseScroll(*getEngine(win), y_pos);
}
void keyCallback(GLFWwindow* win, int const key, int const scancode, int const action, int const mods)
{
onKeyboardButton(*getEngine(win), {key, scancode, action, mods});
}
}
namespace callback
{
MousePosition::operator Vector2() const { return {static_cast<float>(x), static_cast<float>(y)}; }
void setupCallbacks(GLFWwindow* window, engine::Engine* engine)
{
glfwSetWindowCloseCallback(window, windowCloseCallback);
glfwSetWindowSizeCallback(window, windowSizeCallback);
glfwSetMouseButtonCallback(window, mouseCallback);
glfwSetScrollCallback(window, scrollCallback);
glfwSetCursorPosCallback(window, cursorCallback);
glfwSetKeyCallback(window, keyCallback);
glfwSetWindowUserPointer(window, engine);
}
void onManualWindowClose(GLFWwindow* window) { windowCloseCallback(window); }
}
<file_sep>#include "Mesh.h"
#include <filesystem>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include "Shader.h"
namespace render
{
namespace
{
void parseLine(std::istringstream& line, MeshLoader& mesh)
{
std::string s;
line >> s;
if (s == "v") mesh.parseVec(line);
else if (s == "vt") mesh.parseTex(line);
else if (s == "vn") mesh.parseNorm(line);
else if (s == "f") mesh.parseFace(line);
}
MeshLoader parseMeshFile(std::ifstream& in)
{
MeshLoader mesh;
std::string line;
while (std::getline(in, line))
{
std::istringstream line_in(line);
parseLine(line_in, mesh);
}
return mesh;
}
GLuint createVao(MeshLoader const& mesh)
{
auto const vert_count = mesh.size();
GLuint vao_id, vbo_vt, vbo_tx, vbo_n;
std::vector<Vector3> vs;
std::vector<Vector2> ts;
std::vector<Vector3> ns;
vs.reserve(vert_count);
for (auto const vert_id : mesh.vert_ids)
vs.push_back(mesh.vertices[vert_id - 1]);
if (mesh.has_textures)
{
ts.reserve(vert_count);
for (auto const tex_id : mesh.tex_ids)
ts.push_back(mesh.tex_coords[tex_id - 1]);
}
if (mesh.has_normals)
{
ns.reserve(vert_count);
for (auto const norm_id : mesh.norm_ids)
ns.push_back(mesh.normals[norm_id - 1]);
}
glGenVertexArrays(1, &vao_id);
glBindVertexArray(vao_id);
{
glGenBuffers(1, &vbo_vt);
glBindBuffer(GL_ARRAY_BUFFER, vbo_vt);
glBufferData(GL_ARRAY_BUFFER, vs.size() * sizeof(Vector3), vs.data(), GL_STATIC_DRAW);
glEnableVertexAttribArray(Pipeline::Position);
glVertexAttribPointer(Pipeline::Position, 3, GL_FLOAT, GL_FALSE, sizeof(Vector3), nullptr);
if (mesh.has_textures)
{
glGenBuffers(1, &vbo_tx);
glBindBuffer(GL_ARRAY_BUFFER, vbo_tx);
glBufferData(GL_ARRAY_BUFFER, ts.size() * sizeof(Vector2), ts.data(), GL_STATIC_DRAW);
glEnableVertexAttribArray(Pipeline::Texture);
glVertexAttribPointer(Pipeline::Texture, 2, GL_FLOAT, GL_FALSE, sizeof(Vector2), nullptr);
}
if (mesh.has_normals)
{
glGenBuffers(1, &vbo_n);
glBindBuffer(GL_ARRAY_BUFFER, vbo_n);
glBufferData(GL_ARRAY_BUFFER, ns.size() * sizeof(Vector3), ns.data(), GL_STATIC_DRAW);
glEnableVertexAttribArray(Pipeline::Normal);
glVertexAttribPointer(Pipeline::Normal, 3, GL_FLOAT, GL_FALSE, sizeof(Vector3), nullptr);
}
}
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glDeleteBuffers(1, &vbo_vt);
glDeleteBuffers(1, &vbo_tx);
glDeleteBuffers(1, &vbo_n);
return vao_id;
}
}
MeshLoader MeshLoader::fromFile(std::filesystem::path const& mesh_file)
{
if (!exists(mesh_file))
throw std::invalid_argument("File not found: " + mesh_file.string());
try
{
std::ifstream in;
in.exceptions(std::ios_base::badbit);
in.open(mesh_file);
return parseMeshFile(in);
}
catch (...)
{
std::cerr << "Error loading mesh at " << mesh_file << '.' << std::endl;
throw;
}
}
GLsizei MeshLoader::size() const { return vert_ids.size(); }
void MeshLoader::parseVec(std::istream& in)
{
Vector3 v;
in >> v;
vertices.push_back(v);
}
void MeshLoader::parseTex(std::istream& in)
{
Vector2 v;
in >> v;
tex_coords.push_back(v);
}
void MeshLoader::parseNorm(std::istream& in)
{
Vector3 v;
in >> v;
normals.push_back(v);
}
void MeshLoader::parseFace(std::istream& in)
{
if (normals.empty()) has_normals = true;
if (tex_coords.empty()) has_textures = true;
if (std::string token; !has_normals && !has_textures)
{
for (int i = 0; i < 3; i++)
{
in >> token;
vert_ids.push_back(std::stoi(token));
}
}
else
{
for (int i = 0; i < 3; i++)
{
std::getline(in, token, '/');
if (!token.empty()) vert_ids.push_back(std::stoi(token));
std::getline(in, token, '/');
if (!token.empty()) tex_ids.push_back(std::stoi(token));
std::getline(in, token, ' ');
if (!token.empty()) norm_ids.push_back(std::stoi(token));
}
}
}
Mesh Mesh::fromFile(std::filesystem::path const& mesh_file)
{
return MeshLoader::fromFile(mesh_file);
}
Mesh::Mesh(MeshLoader const& loaded)
: vao_id_ {createVao(loaded)},
vertex_count_ {loaded.size()}
{}
Mesh::Mesh(Mesh&& other) noexcept
: vao_id_ {std::exchange(other.vao_id_, 0)},
vertex_count_ {other.vertex_count_}
{}
Mesh& Mesh::operator=(Mesh&& other) noexcept
{
if (this != &other)
{
vao_id_ = std::exchange(other.vao_id_, 0);
vertex_count_ = other.vertex_count_;
}
return *this;
}
Mesh::~Mesh()
{
if (vao_id_ != 0)
{
glDeleteVertexArrays(1, &vao_id_);
}
}
GLuint Mesh::vaoId() const { return vao_id_; }
GLsizei Mesh::vertexCount() const { return vertex_count_; }
}
<file_sep>#pragma once
#include <filesystem>
#include <optional>
#include <GL/glew.h>
#include "Shader.h"
namespace render
{
class Shader
{
public:
enum Type : GLenum
{
Vertex = GL_VERTEX_SHADER,
TesselationControl = GL_TESS_CONTROL_SHADER,
TesselationEvaluation = GL_TESS_EVALUATION_SHADER,
Geometry = GL_GEOMETRY_SHADER,
Fragment = GL_FRAGMENT_SHADER,
Compute = GL_COMPUTE_SHADER
};
private:
Type shader_type_;
GLuint shader_id_;
public:
Shader(Type shader_type, std::string_view);
static Shader fromFile(Type shader_type, std::filesystem::path const& shader_file);
Shader(Shader const&) = delete;
Shader& operator=(Shader const&) = delete;
Shader(Shader&& other) noexcept;
Shader& operator=(Shader&&) noexcept;
~Shader();
[[nodiscard]] Type type() const;
[[nodiscard]] GLuint id() const;
};
class Pipeline
{
public:
constexpr static GLuint Position = 0;
constexpr static GLuint Texture = 1;
constexpr static GLuint Normal = 2;
constexpr static GLuint Camera = 0;
constexpr static GLuint Scene = 1;
private:
GLuint program_id_, model_id_, color_id_, texture_id_, ambient_id_, specular_id_, shininess_id_;
bool is_filter_;
public:
Pipeline(Pipeline const&) = delete;
Pipeline& operator=(Pipeline const&) = delete;
Pipeline(Pipeline&& other) noexcept;
Pipeline& operator=(Pipeline&&) noexcept;
Pipeline(std::initializer_list<Shader> shaders, bool is_filter = true);
~Pipeline();
template <class... Shaders>
explicit Pipeline(bool is_filter, Shaders ...shaders) : Pipeline({std::move(shaders) ...}, is_filter)
{
static_assert((std::is_same_v<Shader, Shaders> && ...));
}
[[nodiscard]] bool isFilter() const;
[[nodiscard]] GLuint programId() const;
[[nodiscard]] GLuint modelId() const;
[[nodiscard]] GLuint colorId() const;
[[nodiscard]] GLuint textureId() const;
[[nodiscard]] GLuint ambientId() const;
[[nodiscard]] GLuint specularId() const;
[[nodiscard]] GLuint shininessId() const;
};
}
bool operator==(render::Pipeline const& lhs, render::Pipeline const& rhs);
bool operator!=(render::Pipeline const& lhs, render::Pipeline const& rhs);
<file_sep>#include "Camera.h"
#include "../Math/Matrix.h"
#include <iostream>
namespace render
{
constexpr auto AngleScale = static_cast<float>(DPi / 1000);
constexpr auto Facing = Vector3 {0, 0, 1};
namespace
{
Matrix4 projectionMatrix(callback::WindowSize const size)
{
return Matrix4::perspective(30.f, size.width / static_cast<float>(size.height), 0.5f, 100.f);
}
}
Camera::Camera(float const distance, Vector3 const focus, GLuint const view_id)
: focus_ {focus},
distance_ {distance},
rotation_ {Matrix4::identity()}
{
glGenBuffers(1, &cam_matrices_id_);
glBindBuffer(GL_UNIFORM_BUFFER, cam_matrices_id_);
{
glBufferData(GL_UNIFORM_BUFFER, sizeof(Matrix4) * 2, nullptr, GL_STREAM_DRAW);
glBindBufferBase(GL_UNIFORM_BUFFER, view_id, cam_matrices_id_);
}
glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
Camera::Camera(Camera&& other) noexcept
: cam_matrices_id_ {std::exchange(other.cam_matrices_id_, 0)},
focus_ {other.focus_},
distance_ {other.distance_},
rotation_ {std::exchange(other.rotation_, {})}
{}
Camera& Camera::operator=(Camera&& other) noexcept
{
if (this != &other)
{
cam_matrices_id_ = std::exchange(other.cam_matrices_id_, 0);
focus_ = other.focus_;
distance_ = other.distance_;
rotation_ = std::exchange(other.rotation_, {});
}
return *this;
}
Camera::~Camera()
{
if (cam_matrices_id_ != 0)
{
glDeleteBuffers(1, &cam_matrices_id_);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
}
void Camera::swapRotationMode()
{
if (auto const mat = std::get_if<Matrix4>(&rotation_))
{
rotation_ = Quaternion::fromRotationMatrix(*mat);
#ifdef _DEBUG
std::cerr << "swapped rotation mode to Quaternion (Post Mult)" << std::endl;
#endif
}
else if (auto const quat = std::get_if<Quaternion>(&rotation_))
{
rotation_ = quat->toRotationMatrix();
#if _DEBUG
std::cerr << "swapped rotation mode to Euler (Pre Mult)" << std::endl;
#endif
}
}
void Camera::rotate(CameraController const& controller) { rotation_ = fullRotation(controller.dragDelta()); }
void Camera::rotate(double const frame_delta)
{
constexpr auto Spin = Vector2 {50.f, 0};
rotation_ = fullRotation(Spin * static_cast<float>(frame_delta));
}
void Camera::update(callback::WindowSize const size, Vector2 const drag_delta, float const zoom)
{
distance_ = std::max(0.f, distance_ + zoom);
auto const projection_matrix = projectionMatrix(size);
auto const rotation_matrix = rotationMatrix(drag_delta);
auto const view_matrix =
Matrix4::translation({0, 0, -distance_}) * rotation_matrix.transposed() * Matrix4::translation(-focus_);
glBindBuffer(GL_UNIFORM_BUFFER, cam_matrices_id_);
{
glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(Matrix4), view_matrix.transposed().inner);
glBufferSubData(GL_UNIFORM_BUFFER, sizeof(Matrix4), sizeof(Matrix4), projection_matrix.inner);
}
glBindBuffer(GL_UNIFORM_BUFFER, 0);
position_ = rotation_matrix * Vector3 {0, 0, distance_};
}
Matrix4 Camera::rotationMatrix(Vector2 const drag_delta) const
{
if (auto const rotation = fullRotation(drag_delta); auto const mat = std::get_if<Matrix4>(&rotation))
return *mat;
else
return std::get<Quaternion>(rotation).toRotationMatrix();
}
Camera::Rotation Camera::fullRotation(Vector2 const drag_delta) const
{
auto const [dx, dy] = drag_delta * -AngleScale;
if (auto const orientation = std::get_if<Matrix4>(&rotation_))
{
auto const drag = Matrix4::rotation(Axis::X, dy) * Matrix4::rotation(Axis::Y, dx);
return *orientation * drag;
}
auto const orientation = std::get<Quaternion>(rotation_);
auto const drag =
Quaternion::fromAngleAxis(dy, Axis::X) *
Quaternion::fromAngleAxis(dx, Axis::Y);
return drag * orientation;
}
CameraController::CameraController(Camera camera)
: dragging_ {},
drag_start_ {},
drag_now_ {},
scroll_ {},
camera {std::move(camera)} {}
void CameraController::startDrag(callback::MousePosition const mouse_position)
{
dragging_ = true;
drag_start_ = drag_now_ = mouse_position;
}
void CameraController::rotateDrag(callback::MousePosition const mouse_position) { drag_now_ = mouse_position; }
void CameraController::finishDrag()
{
camera.rotate(*this);
dragging_ = false;
drag_start_ = drag_now_ = Vector2 {};
}
void CameraController::scroll(double const by) { scroll_ += by; }
void CameraController::update(callback::WindowSize const size, double const frame_delta)
{
camera.update(size, dragDelta(), scrollDelta(frame_delta));
}
Vector2 CameraController::dragDelta() const { return drag_now_ - drag_start_; }
bool CameraController::isDragging() const { return dragging_; }
float CameraController::scrollDelta(double const frame_delta)
{
constexpr auto Min = 1.5;
constexpr auto Scale = 0.75;
constexpr auto Speed = 5.0;
auto const magnitude = std::min(std::abs(scroll_ * Speed * frame_delta), Min);
auto const change = std::copysign(magnitude, scroll_);
scroll_ -= change;
return static_cast<float>(-change * Scale);
}
}
<file_sep>#pragma once
#include <cstdint>
#include <cmath>
#include <limits>
#include <ostream>
#include <istream>
constexpr double DPi = 3.141592653589793238463;
constexpr float Pi = 3.14159265358979f;
constexpr float DegToRad = Pi / 180;
constexpr float Epsilon = std::numeric_limits<float>::epsilon();
enum class Axis: uint8_t { X, Y, Z };
using Radians = float;
using Degrees = float;
<file_sep>#include "Controller.h"
namespace
{
using namespace std::filesystem;
template <class Container, class Iter>
OptPtr<typename Iter::value_type> rerefImpl(Container& cs, Iter& iter)
{
return std::end(cs) == iter ? nullptr : &*iter;
}
template <class Container, class Iter>
OptPtr<typename Iter::value_type> nextImpl(Container& cs, Iter& iter)
{
if (iter == std::end(cs)) { iter = std::begin(cs); }
else { ++iter; }
return rerefImpl(cs, iter);
}
template <class Container, class Iter>
OptPtr<typename Iter::value_type> prevImpl(Container& cs, Iter& iter)
{
if (iter == std::begin(cs)) { iter = std::end(cs); }
else { --iter; }
return rerefImpl(cs, iter);
}
template <class Container, class Type>
typename Container::iterator findImpl(Container& cs, Ptr<Type> ptr)
{
return std::find_if(std::begin(cs), std::end(cs), [&](Type const& it) { return &it == ptr; });
}
template <class Iter, class Container, class Loader>
OptPtr<typename Iter::value_type> loadImpl(Container& cs, Iter& iter, Loader&& loader)
{
cs.emplace_back(std::move(loader));
iter = --std::end(cs);
return rerefImpl(cs, iter);
}
std::vector<path>::iterator scanImpl(std::vector<path>& files, path const& dir, std::wstring_view const extension)
{
files.clear();
for (auto& entry : recursive_directory_iterator(dir, directory_options::skip_permission_denied))
if (auto& p = entry.path(); entry.is_regular_file() && p.extension() == extension)
files.push_back(p);
return files.end();
}
}
namespace engine
{
MeshController::MeshController(Ptr<Collection> const items)
: items_ {items},
iter_ {items->end()}
{}
TextureController::TextureController(Ptr<Collection> const items)
: items_ {items},
iter_ {items->end()}
{}
PipelineController::PipelineController(Ptr<Collection> const items)
: items_ {items},
iter_ {items->end()}
{}
FilterController::FilterController(Ptr<Collection> const items)
: items_ {items},
iter_ {items->end()}
{}
ObjectController::ObjectController(Ptr<Type> const root)
: obj_ {root},
iter_ {root->children.end()}
{}
FileController::FileController(config::Paths const& paths)
: iter_ {files_.end()},
meshes_ {paths.meshes},
textures_ {paths.textures}
{}
void MeshController::reset() { iter_ = items_->end(); }
void TextureController::reset() { iter_ = items_->end(); }
void PipelineController::reset() { iter_ = items_->end(); }
void FilterController::reset() { iter_ = items_->end(); }
void ObjectController::reset() { iter_ = obj_->children.end(); }
void FileController::reset()
{
iter_ = files_.erase(files_.begin(), files_.end());
current_ = std::nullopt;
}
void MeshController::set(Ptr<Type const> const mesh) { iter_ = findImpl(*items_, mesh); }
void PipelineController::set(Ptr<Type const> const pipeline) { iter_ = findImpl(*items_, pipeline); }
void TextureController::set(Ptr<Type const> const texture) { iter_ = findImpl(*items_, texture); }
auto FileController::set(AssetType const assets) -> void
{
switch (assets)
{
case AssetType::Mesh:
iter_ = scanImpl(files_, meshes_, L".obj");
break;
case AssetType::Texture:
iter_ = scanImpl(files_, textures_, L".png");
break;
default:
throw std::invalid_argument("Invalid AssetType enum variant.");
}
current_ = assets;
}
void ObjectController::recurse()
{
if (std::end(obj_->children) != iter_)
{
obj_ = &*iter_;
iter_ = obj_->children.end();
}
}
Ptr<ObjectController::Type> ObjectController::parent()
{
if (obj_->parent)
{
iter_ = findImpl(obj_->parent->children, obj_);
obj_ = obj_->parent;
}
return rerefImpl(obj_->children, iter_);
}
OptPtr<MeshController::Type> MeshController::next() { return nextImpl(*items_, iter_); }
OptPtr<TextureController::Type> TextureController::next() { return nextImpl(*items_, iter_); }
OptPtr<FilterController::Type> FilterController::next() { return nextImpl(*items_, iter_); }
OptPtr<ObjectController::Type> ObjectController::next() { return nextImpl(obj_->children, iter_); }
OptPtr<PipelineController::Type> PipelineController::next()
{
OptPtr<Type> out;
do { out = nextImpl(*items_, iter_); }
while (out != nullptr && out->isFilter());
return out;
}
OptPtr<FileController::Type> FileController::next() { return nextImpl(files_, iter_); }
OptPtr<MeshController::Type> MeshController::prev() { return prevImpl(*items_, iter_); }
OptPtr<TextureController::Type> TextureController::prev() { return prevImpl(*items_, iter_); }
OptPtr<FilterController::Type> FilterController::prev() { return prevImpl(*items_, iter_); }
OptPtr<ObjectController::Type> ObjectController::prev() { return prevImpl(obj_->children, iter_); }
OptPtr<PipelineController::Type> PipelineController::prev()
{
OptPtr<Type> out;
do { out = prevImpl(*items_, iter_); }
while (out != nullptr && out->isFilter());
return out;
}
OptPtr<FileController::Type> FileController::prev() { return prevImpl(files_, iter_); }
OptPtr<MeshController::Type> MeshController::load(Loader&& loader)
{
return loadImpl(*items_, iter_, std::move(loader));
}
OptPtr<TextureController::Type> TextureController::load(Loader&& loader)
{
return loadImpl(*items_, iter_, std::move(loader));
}
OptPtr<ObjectController::Type> ObjectController::create()
{
obj_->emplaceChild();
iter_ = --obj_->children.end();
return &*iter_;
}
void ObjectController::remove()
{
obj_->children.erase(iter_);
iter_ = obj_->children.end();
}
OptPtr<MeshController::Type const> MeshController::get() const { return rerefImpl(*items_, iter_); }
OptPtr<TextureController::Type const> TextureController::get() const { return rerefImpl(*items_, iter_); }
OptPtr<PipelineController::Type const> PipelineController::get() const { return rerefImpl(*items_, iter_); }
OptPtr<FilterController::Type const> FilterController::get() const { return rerefImpl(*items_, iter_); }
OptPtr<FilterController::Type> FilterController::get() { return rerefImpl(*items_, iter_); }
OptPtr<ObjectController::Type const> ObjectController::get() const { return rerefImpl(obj_->children, iter_); }
OptPtr<ObjectController::Type> ObjectController::get() { return rerefImpl(obj_->children, iter_); }
OptPtr<FileController::Type const> FileController::get() const { return rerefImpl(files_, iter_); }
OptPtr<FileController::Type> FileController::get() { return rerefImpl(files_, iter_); }
bool FileController::loadingMeshes() const { return current_.has_value() && current_ == AssetType::Mesh; }
bool FileController::loadingTextures() const { return current_.has_value() && current_ == AssetType::Texture; }
}
<file_sep>#include "SceneBlock.h"
#include "../Math/Vector.h"
namespace render
{
SceneBlock::SceneBlock(GLuint const bind_id)
{
glGenBuffers(1, &scene_block_id_);
glBindBuffer(GL_UNIFORM_BUFFER, scene_block_id_);
{
glBufferData(GL_UNIFORM_BUFFER, sizeof(Vector3) * 2, nullptr, GL_STREAM_DRAW);
glBindBufferBase(GL_UNIFORM_BUFFER, bind_id, scene_block_id_);
}
glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
SceneBlock::SceneBlock(SceneBlock&& other) noexcept
: scene_block_id_ {std::exchange(other.scene_block_id_, 0)}
{}
SceneBlock& SceneBlock::operator=(SceneBlock&& other) noexcept
{
if (this != &other)
{
scene_block_id_ = std::exchange(other.scene_block_id_, 0);
}
return *this;
}
SceneBlock::~SceneBlock()
{
if (scene_block_id_ != 0)
{
glDeleteBuffers(1, &scene_block_id_);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
}
void SceneBlock::update(Vector3 camera_position, Vector3 light_position)
{
glBindBuffer(GL_UNIFORM_BUFFER, scene_block_id_);
{
glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(Vector3), &camera_position);
glBufferSubData(GL_UNIFORM_BUFFER, sizeof(Vector3), sizeof(Vector3), &light_position);
}
glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
}
<file_sep>#pragma once
#include "Vector.h"
#include "Matrix.h"
struct Quaternion
{
static Quaternion identity();
static Quaternion fromComponents(Vector4 components);
static Quaternion fromRotationMatrix(Matrix4 const& rotation);
static Quaternion fromParts(float t, Vector3 vec);
static Quaternion fromAngleAxis(Radians angle, Axis axis);
static Quaternion fromAngleAxis(Radians angle, Vector3 axis);
static Quaternion angleBetween(Vector3 vec1, Vector3 vec2);
std::pair<Radians, Vector4> toAngleAxis() const;
std::pair<float, Vector3> toParts() const;
Vector4 toComponents() const;
Matrix4 toRotationMatrix() const;
float quadrance() const;
float magnitude() const;
Quaternion absolute() const;
Quaternion normalized() const;
Quaternion cleaned() const;
Quaternion conjugated() const;
Quaternion inverted() const;
static Quaternion lerp(float scale, Quaternion start, Quaternion end);
static Quaternion slerp(float scale, Quaternion start, Quaternion end);
float t, x, y, z;
};
Quaternion operator-(Quaternion qtrn);
Quaternion operator+(Quaternion left, Quaternion right);
Quaternion operator-(Quaternion left, Quaternion right);
Quaternion operator*(Quaternion left, Quaternion right);
Quaternion operator*(Quaternion left, float right);
Quaternion operator*(float left, Quaternion right);
bool operator==(Quaternion left, Quaternion right);
bool operator!=(Quaternion left, Quaternion right);
std::ostream& operator<<(std::ostream& os, Quaternion q);
<file_sep>#pragma once
#include "Engine.h"
namespace engine
{
void setupErrorCallback(Engine* engine);
void glfwErrorCallback(int error, const char* description);
}
<file_sep>#pragma once
#include <deque>
#include "Camera.h"
#include "Mesh.h"
#include "Object.h"
#include "Filter.h"
#include "SceneBlock.h"
#include "Shader.h"
#include "../Engine/GlInit.h"
namespace render
{
class Scene
{
public:
friend class engine::Engine;
struct Builder
{
std::deque<Mesh> meshes;
std::deque<Pipeline> shaders;
std::deque<Filter> filters;
std::deque<Texture> textures;
Vector3 light_position;
std::optional<CameraController> camera;
std::unique_ptr<Object> root = std::make_unique<Object>(nullptr);
Ptr<Pipeline const> default_shader;
};
private:
std::deque<Mesh> meshes_;
std::deque<Pipeline> shaders_;
std::deque<Texture> textures_;
std::deque<Filter> filters_;
std::unique_ptr<Object> root_;
Ptr<Pipeline const> default_shader_;
Texture default_texture_ = Texture::white();
SceneBlock scene_block_ = SceneBlock(Pipeline::Scene);
public:
Vector3 light_position;
CameraController camera_controller;
private:
Scene(Builder&& builder);
public:
static Scene setup(engine::GlInit gl_init, config::Settings const& settings);
void render(engine::Engine&, double elapsed_sec);
void animate();
void resizeFilters(callback::WindowSize size);
[[nodiscard]] Texture const& defaultTexture() const;
};
}
namespace config::hooks
{
void setupScene(render::Scene::Builder& builder, Settings const& settings);
void beforeRender(render::Scene& scene, engine::Engine& engine, double elapsed_sec);
void afterRender(render::Scene& scene, engine::Engine& engine, double elapsed_sec);
}
<file_sep>#pragma once
#include "../Math/Matrix.h"
#include "../Math/Quaternion.h"
#include "../Math/Vector.h"
namespace render
{
struct Transform
{
Matrix4 toMatrix() const;
Vector3 position = Vector3::filled(0);
Quaternion rotation = Quaternion::identity();
Vector3 scaling = Vector3::filled(1);
[[nodiscard]] static Transform interpolate(float scale, Transform const& start, Transform const& end);
};
class Animation
{
Transform start_;
Transform target_;
double state_;
bool active_;
bool reversed_;
public:
Animation(Transform start, Transform target);
Transform advance(double elapsed_sec);
[[nodiscard]] bool active() const;
[[nodiscard]] bool reversed() const;
void activate();
void reverse();
};
}
<file_sep>#pragma once
#include <deque>
#include "../Utils.h"
#include "../Render/Filter.h"
#include "../Render/Mesh.h"
#include "../Render/Object.h"
#include "../Render/Texture.h"
namespace engine
{
class MeshController
{
public:
using Type = render::Mesh;
using Loader = render::MeshLoader;
using Collection = std::deque<Type>;
private:
Ptr<Collection> items_;
Collection::iterator iter_;
public:
explicit MeshController(Ptr<Collection> items);
void reset();
void set(Ptr<Type const> mesh);
OptPtr<Type> next();
OptPtr<Type> prev();
OptPtr<Type> load(Loader&& loader);
OptPtr<Type const> get() const;
};
class TextureController
{
public:
using Type = render::Texture;
using Loader = render::TextureLoader;
using Collection = std::deque<Type>;
private:
Ptr<Collection> items_;
Collection::iterator iter_;
public:
explicit TextureController(Ptr<Collection> items);
void reset();
void set(Ptr<Type const> texture);
OptPtr<Type> next();
OptPtr<Type> prev();
OptPtr<Type> load(Loader&& loader);
OptPtr<Type const> get() const;
};
class PipelineController
{
public:
using Type = render::Pipeline;
using Collection = std::deque<Type>;
private:
Ptr<Collection> items_;
Collection::iterator iter_;
public:
explicit PipelineController(Ptr<Collection> items);
void reset();
void set(Ptr<Type const> pipeline);
OptPtr<Type> next();
OptPtr<Type> prev();
OptPtr<Type const> get() const;
};
class FilterController
{
public:
using Type = render::Filter;
using Collection = std::deque<Type>;
private:
Ptr<Collection> items_;
Collection::iterator iter_;
public:
explicit FilterController(Ptr<Collection> items);
void reset();
OptPtr<Type> next();
OptPtr<Type> prev();
OptPtr<Type const> get() const;
OptPtr<Type> get();
};
class ObjectController
{
public:
using Type = render::Object;
using Collection = std::list<Type>;
private:
Ptr<Type> obj_;
Collection::iterator iter_;
public:
explicit ObjectController(Ptr<Type> root);
void reset();
void recurse();
OptPtr<render::Object> parent();
OptPtr<Type> next();
OptPtr<Type> prev();
OptPtr<Type> create();
void remove();
OptPtr<Type const> get() const;
OptPtr<Type> get();
};
class FileController
{
public:
using Type = std::filesystem::path;
using Collection = std::vector<Type>;
enum class AssetType: bool
{
Mesh = false,
Texture = true
};
private:
Collection files_;
Collection::iterator iter_;
Type meshes_, textures_;
std::optional<AssetType> current_;
public:
explicit FileController(config::Paths const& paths);
void reset();
void set(AssetType assets);
OptPtr<Type> next();
OptPtr<Type> prev();
OptPtr<Type const> get() const;
OptPtr<Type> get();
bool loadingMeshes() const;
bool loadingTextures() const;
};
}
<file_sep>#include "Shader.h"
#include <filesystem>
#include <fstream>
#include <iostream>
namespace render
{
namespace
{
void checkCompilation(GLuint const shader_id)
{
GLint compiled;
glGetShaderiv(shader_id, GL_COMPILE_STATUS, &compiled);
if (compiled == GL_FALSE)
{
GLint length;
glGetShaderiv(shader_id, GL_INFO_LOG_LENGTH, &length);
std::string log = "Failed to compile shader: ";
log.resize(length + log.size());
glGetShaderInfoLog(shader_id, length, &length, log.data());
throw std::runtime_error(log);
}
}
void checkLinkage(GLuint const program_id)
{
GLint linked;
glGetProgramiv(program_id, GL_LINK_STATUS, &linked);
if (linked == GL_FALSE)
{
GLint length;
glGetProgramiv(program_id, GL_INFO_LOG_LENGTH, &length);
std::string log = "Failed to link program: ";
log.resize(length + log.size());
glGetProgramInfoLog(program_id, length, &length, log.data());
throw std::runtime_error(log);
}
}
std::string readShaderFile(std::filesystem::path const& shader_path)
{
if (!exists(shader_path))
throw std::invalid_argument("File not found: " + shader_path.string());
auto const size = file_size(shader_path);
std::ifstream in;
in.exceptions(std::ios_base::badbit);
in.open(shader_path);
std::string program;
program.resize(size);
in.read(program.data(), size);
return program;
}
}
Shader::Shader(Type const shader_type, std::string_view const program)
: shader_type_ {shader_type},
shader_id_ {glCreateShader(static_cast<GLenum>(shader_type))}
{
auto const src = program.data();
auto const len = static_cast<GLint>(program.length());
glShaderSource(shader_id_, 1, &src, &len);
glCompileShader(shader_id_);
checkCompilation(shader_id_);
}
Shader Shader::fromFile(Type const shader_type, std::filesystem::path const& shader_file)
{
try
{
auto const program = readShaderFile(shader_file);
return Shader {shader_type, program};
}
catch (...)
{
std::cerr << "Error loading shader at " << absolute(shader_file) << '.' << std::endl;
throw;
}
}
Shader::Shader(Shader&& other) noexcept
: shader_type_ {other.shader_type_},
shader_id_ {std::exchange(other.shader_id_, 0)} {}
Shader& Shader::operator=(Shader&& other) noexcept
{
if (this != &other)
{
shader_type_ = other.shader_type_;
shader_id_ = std::exchange(other.shader_id_, 0);
}
return *this;
}
Shader::~Shader()
{
if (shader_id_ != 0)
{
glDeleteShader(shader_id_);
}
}
Shader::Type Shader::type() const { return shader_type_; }
GLuint Shader::id() const { return shader_id_; }
Pipeline::Pipeline(Pipeline&& other) noexcept
: program_id_ {std::exchange(other.program_id_, 0)},
model_id_ {std::exchange(other.model_id_, 0)},
color_id_ {std::exchange(other.color_id_, 0)},
texture_id_ {std::exchange(other.texture_id_, 0)},
ambient_id_ {std::exchange(other.ambient_id_, 0)},
specular_id_ {std::exchange(other.specular_id_, 0)},
shininess_id_ {std::exchange(other.shininess_id_, 0)},
is_filter_ {std::exchange(other.is_filter_, false)}
{}
Pipeline& Pipeline::operator=(Pipeline&& other) noexcept
{
if (this != &other)
{
program_id_ = std::exchange(other.program_id_, 0);
model_id_ = std::exchange(other.model_id_, 0);
color_id_ = std::exchange(other.color_id_, 0);
texture_id_ = std::exchange(other.texture_id_, 0);
ambient_id_ = std::exchange(other.ambient_id_, 0);
specular_id_ = std::exchange(other.specular_id_, 0);
shininess_id_ = std::exchange(other.shininess_id_, 0);
is_filter_ = std::exchange(other.is_filter_, false);
}
return *this;
}
Pipeline::~Pipeline()
{
if (program_id_ != 0)
{
glDeleteProgram(program_id_);
}
}
Pipeline::Pipeline(std::initializer_list<Shader> shaders, bool const is_filter)
: program_id_ {glCreateProgram()},
is_filter_ {is_filter}
{
for (auto const& shader : shaders)
{
glAttachShader(program_id_, shader.id());
}
glBindAttribLocation(program_id_, Position, "in_Position");
glBindAttribLocation(program_id_, Texture, "in_Texcoord");
glBindAttribLocation(program_id_, Normal, "in_Normal");
glLinkProgram(program_id_);
checkLinkage(program_id_);
model_id_ = glGetUniformLocation(program_id_, "ModelMatrix");
color_id_ = glGetUniformLocation(program_id_, "Color");
texture_id_ = glGetUniformLocation(program_id_, "Texture");
ambient_id_ = glGetUniformLocation(program_id_, "Ambient");
specular_id_ = glGetUniformLocation(program_id_, "Specular");
shininess_id_ = glGetUniformLocation(program_id_, "Shininess");
auto const camera_id = glGetUniformBlockIndex(program_id_, "CameraMatrices");
glUniformBlockBinding(program_id_, camera_id, Camera);
auto const scene_id = glGetUniformBlockIndex(program_id_, "SceneGlobals");
glUniformBlockBinding(program_id_, scene_id, Scene);
for (auto const& shader : shaders)
{
glDetachShader(program_id_, shader.id());
}
}
bool Pipeline::isFilter() const { return is_filter_; }
GLuint Pipeline::programId() const { return program_id_; }
GLuint Pipeline::modelId() const { return model_id_; }
GLuint Pipeline::colorId() const { return color_id_; }
GLuint Pipeline::textureId() const { return texture_id_; }
GLuint Pipeline::ambientId() const { return ambient_id_; }
GLuint Pipeline::specularId() const { return specular_id_; }
GLuint Pipeline::shininessId() const { return shininess_id_; }
}
bool operator==(render::Pipeline const& lhs, render::Pipeline const& rhs)
{
return lhs.programId() == rhs.programId();
}
bool operator!=(render::Pipeline const& lhs, render::Pipeline const& rhs) { return !(lhs == rhs); }
<file_sep>#pragma once
#include "Utils.h"
#include "Vector.h"
struct Matrix2
{
static constexpr auto N = 2;
static constexpr auto Len = N * N;
static Matrix2 identity();
float determinant() const;
Matrix2 transposed() const;
Matrix2 inverted() const;
float operator[](size_t index) const;
float& operator[](size_t index);
float inner[Len];
};
bool operator==(Matrix2 const& left, Matrix2 const& right);
Matrix2 operator+(Matrix2 const& left, Matrix2 const& right);
Matrix2 operator-(Matrix2 const& left, Matrix2 const& right);
Matrix2 operator*(Matrix2 const& left, float right);
Matrix2 operator*(Matrix2 const& left, Matrix2 const& right);
Vector2 operator*(Matrix2 const& left, Vector2 right);
std::ostream& operator<<(std::ostream& os, Matrix2 const& mat);
struct Matrix3
{
static constexpr auto N = 3;
static constexpr auto Len = N * N;
static Matrix3 identity();
static Matrix3 dual(Vector3 of);
float determinant() const;
Matrix3 transposed() const;
Matrix3 inverted() const;
float operator[](size_t index) const;
float& operator[](size_t index);
float inner[Len];
};
bool operator==(Matrix3 const& left, Matrix3 const& right);
Matrix3 operator+(Matrix3 const& left, Matrix3 const& right);
Matrix3 operator-(Matrix3 const& left, Matrix3 const& right);
Matrix3 operator*(Matrix3 const& left, float right);
Matrix3 operator*(float left, Matrix3 const& right);
Matrix3 operator*(Matrix3 const& left, Matrix3 const& right);
Vector3 operator*(Matrix3 const& left, Vector3 right);
std::ostream& operator<<(std::ostream& os, Matrix3 const& mat);
struct Matrix4
{
static constexpr auto N = 4;
static constexpr auto Len = N * N;
static Matrix4 identity();
static Matrix4 scaling(Vector3 by);
static Matrix4 translation(Vector3 by);
static Matrix4 rotation(Axis ax, Radians angle);
static Matrix4 rotation(Vector3 axis, Radians angle);
static Matrix4 view(Vector3 eye, Vector3 center, Vector3 up);
static Matrix4 orthographic(float left, float right, float bottom, float top, float near, float far);
static Matrix4 perspective(Degrees fov, float aspect, float near, float far);
Matrix4 transposed() const;
Vector4 trace() const;
float operator[](size_t index) const;
float& operator[](size_t index);
float inner[Len];
};
bool operator==(Matrix4 const& left, Matrix4 const& right);
Matrix4 operator+(Matrix4 const& left, Matrix4 const& right);
Matrix4 operator-(Matrix4 const& left, Matrix4 const& right);
Matrix4 operator*(Matrix4 const& left, float right);
Matrix4 operator*(Matrix4 const& left, Matrix4 const& right);
Vector4 operator*(Matrix4 const& left, Vector4 right);
std::ostream& operator<<(std::ostream& os, Matrix4 const& mat);<file_sep>#pragma once
#include "../Math/Vector.h"
#include "GL/glew.h"
namespace render
{
class SceneBlock
{
GLuint scene_block_id_;
public:
explicit SceneBlock(GLuint bind_id);
SceneBlock(SceneBlock const& other) = delete;
SceneBlock& operator=(SceneBlock const& other) = delete;
SceneBlock(SceneBlock&& other) noexcept;
SceneBlock& operator=(SceneBlock&& other) noexcept;
~SceneBlock();
void update(Vector3 camera_position, Vector3 light_position);
};
}
<file_sep>#pragma once
#include "../Config.h"
namespace engine
{
class GlInit
{
public:
explicit GlInit(config::Settings const& settings);
};
}
namespace config::hooks
{
void setupOpenGl(Settings const& settings);
}<file_sep>#include "GlInit.h"
#include <iostream>
#include <stdexcept>
#include <GL/glew.h>
namespace engine
{
namespace
{
void setupGlew()
{
glewExperimental = true;
// Allow extension entry points to be loaded even if the extension isn't
// present in the driver's extensions string.
if (auto const result = glewInit(); result != GLEW_OK)
{
std::string message = "ERROR glewInit: ";
message += reinterpret_cast<Ptr<char const>>(glewGetString(result));
throw std::runtime_error(message);
}
glGetError(); // You might get GL_INVALID_ENUM when loading GLEW. Consume it if it is there.
}
void logOpenGlInfo()
{
auto const renderer = glGetString(GL_RENDERER);
auto const vendor = glGetString(GL_VENDOR);
auto const version = glGetString(GL_VERSION);
auto const glsl_version = glGetString(GL_SHADING_LANGUAGE_VERSION);
std::cerr << "OpenGL Renderer: " << renderer << " (" << vendor << ")" << std::endl;
std::cerr << "OpenGL version " << version << std::endl;
std::cerr << "GLSL version " << glsl_version << std::endl;
}
}
GlInit::GlInit(config::Settings const& settings)
{
setupGlew();
#ifdef _DEBUG
logOpenGlInfo();
#endif
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
config::hooks::setupOpenGl(settings);
}
}
<file_sep>#pragma once
#include "../Config.h"
#include <GL/glew.h>
#include <GLFW/glfw3.h>
namespace engine
{
class GlfwHandle
{
friend class Engine;
GLFWwindow* window_;
public:
[[nodiscard]] explicit GlfwHandle(config::Settings const& settings);
GlfwHandle(GlfwHandle const&) = delete;
GlfwHandle& operator=(GlfwHandle const&) = delete;
GlfwHandle(GlfwHandle&& other) noexcept;
GlfwHandle& operator=(GlfwHandle&& other) noexcept;
~GlfwHandle();
[[nodiscard]] double getTime() const;
[[nodiscard]] bool windowClosing() const;
private:
void registerEngine(Engine* engine);
void closeWindow();
void swapBuffers();
void pollEvents();
};
}
<file_sep>#pragma once
#include <filesystem>
#include <vector>
#include "../Math/Matrix.h"
#include "../Math/Quaternion.h"
#include "../Math/Vector.h"
#include "../lib/json/json.hpp"
#include "../Engine/Engine.h"
using json = nlohmann::json;
namespace jsonFile
{
struct JsonFile
{
JsonFile();
json* j;
std::filesystem::path default_dir_;
render::Scene scene;
};
bool saveFile(config::Settings settings, std::filesystem::path planeMesh, std::filesystem::path pieceMesh);
bool loadFile();
}
<file_sep>#include "Transform.h"
namespace render
{
Matrix4 Transform::toMatrix() const
{
return Matrix4::translation(position) * rotation.toRotationMatrix() * Matrix4::scaling(scaling);
}
Transform Transform::interpolate(float const scale, Transform const& start, Transform const& end)
{
auto const pos = start.position + (end.position - start.position) * scale;
auto const rot = Quaternion::slerp(scale, start.rotation, end.rotation);
auto const sca = start.scaling + (end.scaling - start.scaling) * scale;
return {pos, rot, sca};
}
Animation::Animation(Transform start, Transform target)
: start_ {std::move(start)},
target_ {std::move(target)},
state_ {0.0},
active_ {false},
reversed_ {false}
{}
Transform Animation::advance(double const elapsed_sec)
{
constexpr auto Speed = 0.5;
if (reversed_)
{
state_ -= elapsed_sec * Speed;
if (state_ <= 0)
{
state_ = 0;
active_ = false;
reversed_ = false;
return start_;
}
return Transform::interpolate(state_, start_, target_);
}
state_ += elapsed_sec * Speed;
if (state_ >= 1)
{
state_ = 1;
active_ = false;
reversed_ = true;
return target_;
}
return Transform::interpolate(state_, start_, target_);
}
bool Animation::active() const { return active_; }
bool Animation::reversed() const { return reversed_; }
void Animation::activate() { active_ = true; }
void Animation::reverse() { reversed_ = !reversed_; }
}
<file_sep>#include "Texture.h"
#include <iostream>
#include "FreeImage.h"
namespace render
{
void TextureLoader::Deleter::operator()(FIBITMAP* data) const { FreeImage_Unload(data); }
TextureLoader TextureLoader::fromFile(std::filesystem::path const& texture_file)
{
try
{
if (!exists(texture_file))
throw std::invalid_argument("File not found: " + texture_file.string());
auto const filename = texture_file.c_str();
auto const loaded = FreeImage_LoadU(FreeImage_GetFileTypeU(filename), filename);
if (loaded == nullptr)
throw std::invalid_argument("Cannot open texture file: " + texture_file.generic_string());
auto const image = FreeImage_ConvertTo32Bits(loaded);
if (image == nullptr)
throw std::invalid_argument("Cannot use texture file: " + texture_file.generic_string());
FreeImage_FlipVertical(image);
auto const width = FreeImage_GetWidth(image);
auto const height = FreeImage_GetHeight(image);
return TextureLoader {width, height, Buffer {image}};
}
catch (...)
{
std::cerr << "Error loading texture at " << texture_file << '.' << std::endl;
throw;
}
}
TextureLoader TextureLoader::white(unsigned const len)
{
auto const color = RGBQUAD {0xFF, 0xFF, 0xFF, 0xFF};
auto const data = FreeImage_AllocateEx(len, len, 32, &color);
return {len, len, Buffer {data}};
}
Texture::Texture(TextureLoader&& texture)
{
#if FREEIMAGE_COLORORDER == FREEIMAGE_COLORORDER_BGR
constexpr auto Format = GL_BGRA;
#else
constexpr auto Format = GL_RGBA;
#endif
auto const [width, height, data] = std::move(texture);
glGenTextures(1, &tex_id_);
glBindTexture(GL_TEXTURE_2D, tex_id_);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
auto const pixels = FreeImage_GetBits(data.get());
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, Format, GL_UNSIGNED_BYTE, pixels);
glGenerateMipmap(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
}
Texture Texture::fromFile(std::filesystem::path const& texture_file)
{
return Texture {TextureLoader::fromFile(texture_file)};
}
Texture Texture::white()
{
constexpr auto Size = 4;
return TextureLoader::white(Size);
}
Texture::Texture(Texture&& other) noexcept: tex_id_ {std::exchange(other.tex_id_, 0)} {}
Texture& Texture::operator=(Texture&& other) noexcept
{
if (this != &other)
{
std::exchange(other.tex_id_, 0);
}
return *this;
}
Texture::~Texture()
{
if (tex_id_ != 0)
{
glDeleteTextures(1, &tex_id_);
}
}
GLuint Texture::texId() const { return tex_id_; }
}
<file_sep>#pragma once
#include "Shader.h"
#include "../Callback.h"
#include "../Config.h"
#include "GL/glew.h"
namespace render
{
class Filter
{
GLuint fb_id_, tex_id_, rb_id_, quad_id_;
Ptr<Pipeline const> pipeline_;
public:
Filter(config::Window const& window, Ptr<Pipeline const> pipeline);
Filter(Filter const& other) = delete;
Filter& operator=(Filter const& other) = delete;
Filter(Filter&& other) noexcept;
Filter& operator=(Filter&& other) noexcept;
~Filter();
void bind();
void finish();
void resize(callback::WindowSize size);
};
}
<file_sep>#pragma once
#include "Math/Vector.h"
#include <Gl/glew.h>
#include <GLFW/glfw3.h>
namespace engine
{
class Engine; // Forward declaration to avoid circular dependencies
}
namespace callback
{
struct WindowSize
{
int width, height;
};
struct MouseButton
{
int button, action, mods;
};
struct MousePosition
{
double x, y;
operator Vector2() const;
};
struct KeyboardButton
{
int key, scancode, action, mods;
};
void setupCallbacks(GLFWwindow* window, engine::Engine* engine);
void onManualWindowClose(GLFWwindow* window);
}
namespace config::hooks
{
void onWindowClose(engine::Engine& engine);
void onWindowResize(engine::Engine& engine, callback::WindowSize size);
void onMouseButton(engine::Engine& engine, callback::MouseButton button);
void onMouseMove(engine::Engine& engine, callback::MousePosition position);
void onMouseScroll(engine::Engine& engine, double scroll);
void onKeyboardButton(engine::Engine& engine, callback::KeyboardButton button);
}
| 27eb0b7d16ed25281c40806f9d50075f7032c164 | [
"C++"
] | 42 | C++ | francisco-mendes/cgj-project | e08c939719dbd5b8da5ec4f3180fc9c1f994b979 | a1dc71bbc80d6b00316efde76f682e3f07b2071b |
refs/heads/master | <file_sep>class Hello_World
{
public static void main()
{
System.out.println("Hello World!!");
System.out.println("Welcome to Google Code In 2018");
System.out.println("I am changing file in the new branch");
}
}
<file_sep>import java.io.*;
class movieMagic extends hello //creation of class // inheritence of parent class to child class
{
private int a ;private String title;private float rating;//encapsulation of variables and data
void accept()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter year,title,rating out of 5");
a=Integer.parseInt(br.readLine());
String title=br.readLine();
rating=Float.parseFloat(br.readLine());
}
void display()
{if(rating>=0.0 && rating<=2.0)
System.out.println("flop");
else if(rating>=2.1 && rating<=3.4)
System.out.println("semi hit");
else if(rating>=3.5 && rating<=4.5)
System.out.println("hit");
else if(rating>=4.6 && rating<=5)
System.out.println("super hit");
}
public static void main()throws IOException //polymorphism (capability of a method to do different things based on the object that it is acting upon.)
{
movieMagic obj= new movieMagic();
obj.accept();
obj.display();
}
}
class hello
{
public static void main()throws IOException
{
InputStreamReader A = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(A);
int a;double c=0.0;String z; //inherited variable "a" from the "movieMagic" class.
System.out.println("enters hours rode");
a= Integer.parseInt(br.readLine());
z=br.readLine();
if(a<=3)
c=a*125;
else if(a>3&&a<=7)
c=(3*125)+(a-3)*110;
else if(a>7&&a<=15)
c=(3*125)+(4*110)+(a-3-4)*100;
else if(a>15)
c=(3*125)+(4*110)+(8*100)*(a-3-4-8)*75;
System.out.println("charges"+c+"thank you for riding with us"+z);
}
}
<file_sep>#Google Code-In 2018
JBOSS COMMUNITY
Task: Setup Git and a GitHub account.
| 4b3d7aafbda06827e8c0014e755caeae1895e8af | [
"Markdown",
"Java"
] | 3 | Java | chiranjeev13/Google-Code-In-2018 | 1659d2eadb3d6cce22d39210953e7dd01ccea97f | 998260d17b66b92a981437d12590303757284b33 |
refs/heads/master | <file_sep>import json
import sys
import argparse
from collections import OrderedDict
def parse():
parser = argparse.ArgumentParser(description='To merge multiple json files')
parser.add_argument('-f', '--folder_path', help='Folder path for json files')
parser.add_argument('-i', '--input_prefix', help='Folder path for json files')
parser.add_argument('-o', '--output_prefix', help='Folder path for json files')
parser.add_argument('-m', '--max_file_size', help='Folder path for json files')
return parser
def size(file1,file2):
return sys.getsizeof(file1)+sys.getsizeof(file2)
def Read(s):
with open(s) as f:
data = json.load(f, object_pairs_hook=OrderedDict)
return data
def Write(s,d):
with open(s, 'w') as f:
json.dump(d, f)
def merge_json(folder,Input,Output,max_size):
input_index=1
temp_list=[]
output_index=1
while(1):
s=folder+Input+str(input_index)+'.json'
input_index=input_index+1
try:
data=Read(s)
key=data.keys()
if(size(temp_list,data[key[0]])<max_size):
temp_list.extend(data[key[0]])
else:
s=folder+Output+str(output_index)+'.json'
output_index=output_index+1
d={}
d[key[0]]=temp_list
Write(s,d)
temp_list=[]
temp_list.extend(data[key[0]])
except IOError:
s=folder+Input+str(1)+'.json'
data = Read(s)
key=data.keys()
s=folder+Output+str(output_index)+'.json'
d={}
d[key[0]]=temp_list
Write(s,d)
return
"""folder=str(input('Enter the file path or folder directory :'))
Input=str(input('Enter the Input Prefix'))
Output=str(input('Enter the '))
max_size=200
fun(folder,Input,Output,max_size)"""
parser = parse()
args = parser.parse_args()
folder=args.folder_path
Input=args.input_prefix
output=args.output_prefix
max_size=args.max_file_size
merge_json(folder,Input,output,int(max_size)) <file_sep>## Merge JSON file ##
### Description ###
The implemented program is to merge multiple json files
The program gets Folder path,Prefix of the input file,Prefix of the output file and maximum length of the output file
### Time Complexity ###
The time complexity of the program is O(n)
### How to Run ###
python merge_json.py -f #directory path# -i #input prefix# -o #output prefix# -m #Maximum Length of the Output file#
| 5ef0befe9a080c402d71f8ec836b52ef6af6218a | [
"Markdown",
"Python"
] | 2 | Python | VishakVeerasamy/Freshworks | 15b5267010c8b689aeefb5809b71ccc7f05d578a | f8f19b73a319e369d5c2d45af9acbed7baa05583 |
refs/heads/master | <file_sep>require 'spec_helper'
describe Execution do
subject { FactoryGirl.build(:execution) }
it "should require name" do
subject.name = ""
expect(subject).to_not be_valid
end
it { expect(subject.running?).to be_false }
it "run, wait and parse results" do
subject.should_receive(:create_taverna_run).and_return("taverna_id_1234")
subject.run!
expect(subject.initialized?).to be_true
expect(subject.taverna_id).to eq "taverna_id_1234"
subject.should_receive(:server_run).twice.and_return(double({status: :finished}))
subject.should_receive(:update_results)
subject.wait
expect(subject.status).to eq :finished
end
it "should serialize correcly results" do
subject.status = :finished
results = {:output_1 => [{value: 1, description: 1}, {value: 2, description: 2}]}
subject.results = results
subject.save
subject.reload
expect(subject.results.class).to eq results.class
expect(subject.results).to eq results
end
end
<file_sep>module ExecutionsHelper
def execution_status_class(execution)
case execution.status
when :initialized then "label-warning"
when :running then "label-warning"
when :finished then "label-success"
when :error then "label-important"
end
end
def execution_status_name(execution)
return t(:finished) if execution.finished?
t(:counting)
end
end
<file_sep>class AddWorkflowToExecution < ActiveRecord::Migration
def change
add_column :executions, :workflow_id, :integer
end
end
<file_sep>require 'spec_helper'
describe FilesController do
include_context "controller_spec"
include_context "with_current_user"
include_context "with_ability"
before do
sign_in current_user
end
let(:current_user) { create(:user) }
let(:show_params) {{:id => a_file.id}}
let(:update_params) {{:id => a_file.id, :uploaded_file => {:name => "New name" }}}
let(:a_file) { current_user.uploaded_files.first }
let(:file) {a_file.file}
let(:create_params) do
{:uploaded_file => {:name => "New file", :file => fixture_file_upload('/workflow_example.t2flow', 'image/jpg') } }
end
let(:destroy_params) { {:id => a_file.id} }
context "with permissions" do
describe "#index" do
before { get_index }
it { expect(assigns(:files)) }
it { expect(response).to be_success }
end
describe "#new" do
before { get :new }
it { expect(assigns(:file)) }
it { expect(response).to render_template('show') }
it { expect(response).to be_success }
end
describe "#show" do
before { get_show }
it { expect(assigns(:file)) }
it { expect(response).to be_success }
end
describe "#create" do
context "with valid data" do
before do
post_create
end
it { expect(assigns(:file)) }
it { expect(response).to redirect_to(files_path) }
end
context "with invalid data" do
before do
post_create
end
let(:create_params) {{:uploaded_file => {:name => ""}}}
it { expect(response).to render_template('') }
it { expect(assigns(:file)) }
end
end
describe "#update" do
context "with valid data" do
before do
put_update
end
it { expect(assigns(:file)) }
it { expect(response).to render_template('show') }
end
context "with invalid data" do
before do
put_update
end
let(:update_params) {{:id => a_file.id, :uploaded_file => {:name => "" }}}
it { expect(response).to render_template('show') }
end
end
describe "destroy" do
before do
delete_destroy
end
it { expect(response).to redirect_to(files_path) }
end
end
context "without persmissions" do
describe "#show" do
before { ability.cannot :read, UploadedFile }
it_behaves_like "show_access_forbidden"
end
describe "#create" do
before { ability.cannot :create, UploadedFile }
it_behaves_like "create_access_forbidden"
end
describe "#update" do
before { ability.cannot :update, UploadedFile }
it_behaves_like "update_access_forbidden"
end
describe "#destroy" do
before { ability.cannot :destroy, UploadedFile }
it_behaves_like "destroy_access_forbidden"
end
end
end
<file_sep>Servitoros::Application.routes.draw do
root :to => 'home#index'
#devise_for :admin_users, ActiveAdmin::Devise.config
#ActiveAdmin.routes(self)
get "home/index"
get "more_info", :to => "home#more_info"
get "faq", :to => "home#faq"
get "credits", :to => "home#credits"
devise_for :users
#ActiveAdmin.routes(self)
resources :executions do
member { post 'notify' }
collection do
post 'notify'
get 'executions_list'
end
end
resources :uploaded_files, :path => "files", :controller => :files
resources :files
end
<file_sep>require 'spec_helper'
describe Workflow do
subject { FactoryGirl.create(:workflow) }
it "should return the correct input params" do
correct_input_descriptor = {'input_urls' => OpenStruct.new({ 'example' => "http://nlp.ilsp.gr/panacea/D4.3/data/201109/ENV_ES/1.xml\nhttp://nlp.ilsp.gr/panacea/D4.3/data/201109/ENV_ES/2.xml",
'description' => 'A list of URL to BasicXces files. It can also work with "file://" urls.' }),
'language' => OpenStruct.new({ 'example' => "es", 'description' => "Language" })}
expect(subject.input_descriptor).to eq OpenStruct.new(correct_input_descriptor)
end
end
<file_sep>class AddAttachmentTavernaWorkflowToWorkflows < ActiveRecord::Migration
def self.up
change_table :workflows do |t|
t.attachment :taverna_workflow
end
end
def self.down
drop_attached_file :workflows, :taverna_workflow
end
end
<file_sep>class ExecutionsController < ApplicationController
load_and_authorize_resource :except => [:notify]
protect_from_forgery :except => [:notify]
helper_method :current_or_guest_user
def index
@execution = Execution.new()
@execution.workflow = Workflow.last
@execution.set_example_inputs
@files = current_or_guest_user.uploaded_files.order("name DESC")
#@files.delete_all
@input_descriptor = @execution.workflow.input_descriptor
@input_ports = @execution.workflow.input_ports
@executions = current_or_guest_user.executions.order("created_at DESC").page params[:page]
#@executions.destroy_all
end
def create
param = {}
if upload_file_input? && params[:upload_files].nil?
flash[:error] = t(:error_select_input)
elsif params[:execution][:input_parameters][:inputs][:language].empty?
flash[:error] = t(:error_select_lang)
else
@execution = Execution.new(post_params)
@execution.workflow = Workflow.last
if @execution.save
@execution.run!
end
param = {:running => true}
end
redirect_to executions_path(param)
end
def notify
find_execution_from_notification
unless @execution.finished?
@execution.update_status
if @execution.finished?
@execution.update_results
end
@execution.save
end
redirect_to execution_path(@execution)
end
def executions_list
@executions = current_or_guest_user.executions.order("created_at DESC").page params[:page]
render :partial => 'list'
end
private
def find_execution_from_notification
taverna_id = params[:id] || params[:content].scan(/ID=(\S+)/).flatten.first
@execution = Execution.find_by_taverna_id(taverna_id)
end
def upload_file_input?
params[:execution][:type] == "upload_files"
end
def join_file_urls
files = params[:upload_files]
file_urls = UploadedFile.find(files).map { |file| URI.join("http://#{UPLOADED_FILES_BASE_URL}", file.file.url).to_s }.join("\n")
params[:execution][:input_parameters][:inputs][:input_urls] = file_urls
end
def post_params
join_file_urls if upload_file_input?
attributes = params[:execution].slice(:input_parameters)
attributes[:user_id] = current_or_guest_user.id
attributes
end
def session_id
request.session_options[:id]
end
end
<file_sep>require 'spec_helper'
describe ExecutionsController do
include_context "controller_spec"
include_context "with_current_user"
include_context "with_ability"
before do
sign_in current_user
end
let(:current_user) { create(:user) }
let(:show_params) {{:id => an_execution.id}}
let(:update_params) {{:id => an_execution.id, :execution => {:name => "New name" }}}
let(:an_execution) { current_user.executions.first }
let(:workflow) {an_execution.workflow}
let(:create_params) do
{:execution => {:name => "New execution", :workflow_id => workflow.id, :input_parameters => input_parameters } }
end
let(:input_parameters) do
{"inputs"=> {"input_urls"=>
"http://nlp.ilsp.gr/panacea/D4.3/data/201109/ENV_ES/1.xml\r\nhttp://nlp.ilsp.gr/panacea/D4.3/data/201109/ENV_ES/2.xml",
"language"=>"es",
"workflow_id" => workflow.id.to_s }}
end
context "with permissions" do
describe "#index" do
before { get_index }
it { expect(assigns(:executions)) }
it { expect(response).to be_success }
end
describe "#new" do
before { get :new, :workflow_id => workflow.id }
it { expect(assigns(:execution)) }
it { expect(assigns(:workflow)) }
it { expect(assigns(:input_descriptor)) }
it { expect(assigns(:input_ports)) }
it { expect(response).to render_template('show') }
it { expect(response).to be_success }
end
describe "#show" do
before { get_show }
it { expect(assigns(:execution)) }
it { expect(response).to be_success }
end
describe "#create" do
context "with valid data" do
before do
Execution.any_instance.should_receive(:run!)
post_create
end
it { expect(assigns(:execution)) }
it { expect(assigns(:execution).input_parameters).to eq input_parameters }
it { expect(response).to redirect_to(executions_path) }
end
context "with invalid data" do
before do
post_create
end
let(:create_params) {{:execution => {:name => "", :workflow_id => workflow.id }}}
it { expect(response).to render_template('show') }
end
context "with invalid input_parameters" do
before do
Execution.any_instance.should_receive(:run!)
post_create
end
let(:input_parameters) do
{"inputs"=> {"input_urls"=>
"",
"language"=>"",
"workflow_id" => ""}}
end
it { expect(assigns(:input_description)) }
it { expect(assigns(:input_ports)) }
end
end
describe "#update" do
context "with valid data" do
before do
Execution.stub(:find).and_return(an_execution)
an_execution.should_receive(:update_attributes).with((update_params[:execution].merge({:user_id => current_user.id}).stringify_keys))
put_update
end
it { expect(assigns(:input_descriptor)) }
it { expect(assigns(:input_ports)) }
it { expect(assigns(:execution)) }
it { expect(response).to render_template('show') }
end
context "with invalid data" do
before do
put_update
end
let(:update_params) {{:id => an_execution.id, :execution => {:name => "" }}}
it { expect(response).to render_template('show') }
end
end
describe "#notify with id" do
before do
Execution.should_receive(:find_by_taverna_id).and_return(an_execution)
an_execution.should_receive(:update_status)
an_execution.should_receive(:finished?).twice.and_return(false)
an_execution.should_receive(:save)
post :notify, :id => "96368d3b-3055-400d-89c1-2ead439230bf"
end
it { expect(assigns(:execution)) }
end
describe "#notify without" do
before do
Execution.should_receive(:find_by_taverna_id).and_return(an_execution)
an_execution.should_receive(:update_status)
an_execution.should_receive(:finished?).twice.and_return(false)
an_execution.should_receive(:save)
post :notify, :content => "96368d3b-3055-400d-89c1-2ead439230bf"
end
it { expect(assigns(:execution)) }
end
end
context "without persmissions" do
describe "#show" do
before { ability.cannot :read, Execution }
it_behaves_like "show_access_forbidden"
end
describe "#create" do
before { ability.cannot :create, Execution }
it_behaves_like "create_access_forbidden"
end
describe "#update" do
before { ability.cannot :update, Execution }
it_behaves_like "update_access_forbidden"
end
end
end
<file_sep>class AddTypeToExecution < ActiveRecord::Migration
def change
add_column :executions, :type, :string
end
end
<file_sep>ActiveAdmin.register User do
index do
column :id
column :email
column :current_sign_in_at
column :last_sign_in_at
column :created_at
column :updated_at
default_actions
end
end
<file_sep>require 'spec_helper'
describe "executions/show.html.erb" do
let(:user) { create(:user) }
let(:execution) { user.executions.first }
let(:workflow) { execution.workflow }
let(:input_descriptor) { workflow.input_descriptor }
let(:input_ports) { workflow.input_ports }
before do
assign(:execution, execution)
assign(:workflow, workflow)
assign(:input_ports, input_ports)
assign(:input_descriptor, input_descriptor)
end
it "should show input fields for workflow paramters" do
render
expect(rendered).to have_selector("textarea[name='execution[input_parameters][inputs][input_urls]']")
expect(rendered).to have_selector("textarea[name='execution[input_parameters][inputs][language]']")
end
it "show properties when available" do
execution.taverna_id = "taverna_id_1234"
render
expect(rendered).to have_selector("textarea[name='execution[input_parameters][inputs][input_urls]']")
expect(rendered).to have_content("taverna_id_1234")
expect(rendered).to have_content("Execution Properties")
end
it "should hide properties when not available" do
execution.taverna_id = nil
render
expect(rendered).to_not have_content("Execution Properties")
end
it "show execution results" do
execution.status = :finished
execution.taverna_id = "taverna_id_1234"
render
expect(rendered).to have_content("Results")
expect(rendered).to have_content("Output1")
expect(rendered).to have_content("Download")
expect(rendered).to have_selector("ol>li>a", :count => 2)
end
it "should hide execution results" do
execution.status = :initialized
execution.taverna_id = "taverna_id_1234"
render
expect(rendered).to_not have_content("Results")
expect(rendered).to_not have_selector("ol>li>a", :count => 2)
expect(rendered).to_not have_content("Ouput1")
end
end
<file_sep>FactoryGirl.define do
factory :user do
id 10
email "<EMAIL>"
password "<PASSWORD>"
ignore do
executions_count 5
workflow_count 3
files_count 2
end
after(:create) do |user, evaluator|
FactoryGirl.create_list(:execution, evaluator.executions_count, user_id: user.id)
end
after(:create) do |user, evaluator|
FactoryGirl.create_list(:workflow, evaluator.workflow_count, user_id: user.id)
end
after(:create) do |user, evaluator|
FactoryGirl.create_list(:uploaded_file, evaluator.files_count, user_id: user.id)
end
end
end
<file_sep>require 'spec_helper'
require 'cancan/matchers'
describe "Abilities" do
let(:ability) { Ability.new(user) }
let(:user) { create(:user) }
subject { ability }
describe "Basic user" do
let(:own_execution) { user.executions.first }
let(:others_execution) { create(:execution, :user_id => -1) }
let(:own_workflow) { user.workflows.first }
let(:others_workflow) { create(:workflow, :user_id => -1) }
it { should be_able_to(:manage, own_execution) }
it { should_not be_able_to(:manage, others_execution) }
it { should be_able_to(:manage, own_workflow) }
it { should_not be_able_to(:manage, others_workflow) }
end
end
<file_sep>shared_context "controller_spec" do
render_views
let(:get_index) { get :index }
let(:get_show) { get :show, show_params }
let(:post_create) { post :create, create_params }
let(:put_update) { put :update, update_params }
let(:delete_destroy) { delete :destroy, destroy_params }
end
shared_context "with_current_user" do
before { controller.stub(:current_user) { current_user } }
end
shared_context "with_ability" do
before do
controller.stub(:current_ability).and_return(ability)
ability.can :manage, :all
end
let(:ability) { Object.new.extend(CanCan::Ability) }
end
shared_examples "create_access_forbidden" do
before { post_create }
it { expect(response).to redirect_to :root }
end
shared_examples "show_access_forbidden" do
before { get_show }
it { expect(response).to redirect_to :root }
end
shared_examples "update_access_forbidden" do
before { put_update }
it { expect(response).to redirect_to :root }
end
shared_examples "destroy_access_forbidden" do
before { delete_destroy }
it { expect(response).to redirect_to :root }
end
<file_sep>class AddOutputToExecution < ActiveRecord::Migration
def change
add_column :executions, :results, :text
end
end
<file_sep>require 'spec_helper'
describe "workflows/index.html.erb" do
let(:user) { create(:user) }
let(:workflows) { user.workflows.page(1) }
it "list executions" do
assign(:workflows, workflows)
render
rendered.should have_selector("tr", :count => 4)
rendered.should have_selector("a.btn>i.icon-play", :count => 3)
end
end
<file_sep>require 'spec_helper'
describe "layouts/_navigation.html.erb" do
let(:user) { create(:user) }
describe "menu" do
it "shows options when user is signed_in" do
view.stub(:user_signed_in?).and_return(true)
view.stub(:current_user).and_return(user)
render
rendered.should have_selector("ul.nav li", :count => 3)
end
it "does not show options when user is not signed_in" do
view.stub(:user_signed_in?).and_return(false)
render
rendered.should_not have_selector("ul.nav li")
end
end
end
<file_sep>module ApplicationHelper
def bootstrap_class_for flash_type
case flash_type
when :success
"alert-success"
when :error
"alert-error"
when :alert
"alert-block"
when :notice
"alert-info"
else
flash_type.to_s
end
end
def clippy(text, bgcolor='#FFFFFF')
relative_path = ENV['RAILS_RELATIVE_URL_ROOT']
html = <<-EOF
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
width="110"
height="14"
id="clippy" >
<param name="movie" value="#{relative_path}/flash/clippy.swf"/>
<param name="allowScriptAccess" value="always" />
<param name="quality" value="high" />
<param name="scale" value="noscale" />
<param NAME="FlashVars" value="text=#{text}">
<param name="bgcolor" value="#{bgcolor}">
<embed src="#{relative_path}/flash/clippy.swf"
width="110"
height="14"
name="clippy"
quality="high"
allowScriptAccess="always"
type="application/x-shockwave-flash"
pluginspage="http://www.macromedia.com/go/getflashplayer"
FlashVars="text=#{text}"
bgcolor="#{bgcolor}"
/>
</object>
EOF
html.html_safe
end
def lang_selector
select_tag :language, options_for_select(I18n.available_locales.to_a.map{ |locale| [t('name', :locale => locale), locale] }, I18n.locale.to_sym)
end
def hidden_if condition
" hidden " if condition
end
def humanize_lang(lang)
case lang
when "es" then t(:spanish)
when "en" then t(:english)
when "ca" then t(:catalan)
when "pt" then t(:portuguese)
when "it" then t(:italian)
end
end
def lang_options
[[t(:tell_document_lang), ""]] + %w{es en ca pt it}.map { |lang| [humanize_lang(lang), lang] }
end
end
<file_sep>FactoryGirl.define do
factory :workflow do
name "My workflow"
description "Workflow description text"
taverna_workflow { File.new(File.join(Rails.root, 'spec', 'fixtures', 'workflow_example.t2flow')) }
end
end
<file_sep>FactoryGirl.define do
factory :uploaded_file do
name "My uploaded file"
description "uploaded file description text"
file { File.new(File.join(Rails.root, 'spec', 'fixtures', 'workflow_example.t2flow')) }
end
end
<file_sep>class Workflow < ActiveRecord::Base
attr_accessor :input_params
attr_accessible :name, :description, :taverna_workflow
has_attached_file :taverna_workflow
belongs_to :user
validates :name, :presence => true
validates_attachment_presence :taverna_workflow
def input_descriptor
@input_descriptor ||= parse_input_descriptor
end
def input_ports
input_descriptor.marshal_dump.keys
end
def xml_content
File.read(File.open(taverna_workflow.path))
end
def example_inputs_parameters
examples = {:inputs => {}, :files => {}}
input_ports.each do |port|
examples[:inputs][port] = input_descriptor.send(port).example
end
examples
end
def filename
File.basename(taverna_workflow.path)
end
private
def xml_document
@xml_document ||= Nokogiri::XML(File.read(taverna_workflow.path))
end
def parse_input_descriptor
input_params = {}
xml_document.xpath("xmlns:workflow/xmlns:dataflow/xmlns:inputPorts/xmlns:port").each do |port|
port_name = port.xpath('xmlns:name').first.content
port_description = port.xpath('.//annotationBean[@class="net.sf.taverna.t2.annotation.annotationbeans.FreeTextDescription"]/text').first
port_example = port.xpath('.//annotationBean[@class="net.sf.taverna.t2.annotation.annotationbeans.ExampleValue"]/text').first
values = {}
values[:description] = port_description.content if port_description
values[:example] = port_example.content if port_example
input_params[port_name] = OpenStruct.new(values)
end
OpenStruct.new(input_params)
end
end
<file_sep>require 'spec_helper'
describe "executions/index.html.erb" do
let(:user) { create(:user) }
let(:executions) { user.executions.page(1) }
it "list executions" do
assign(:executions, executions)
render
rendered.should have_selector("tr", :count => 6)
end
end
<file_sep>class AddWorkflow < ActiveRecord::Migration
def up
Workflow.create(:name => "First Workflow", :description => "First workflow", :taverna_workflow => File.new(File.join(Rails.root, 'db', 'data', 'txt_corpus_freeling3_with_corpus_analysis_v01.t2flow')))
end
def down
Workflow.destroy_all
end
end
<file_sep>outputs = {:output1 => [{value: "https://link.com/1", size: 123}, {value: "http://link.com/2", size: 1032}]}
inputs = {:inputs => {'input_urls' => "http://link.com/input1\nhttp://link.com/input2", 'language' => "en"}, :files => {}}
FactoryGirl.define do
factory :execution do
status :new
name 'New execution'
description 'Nex execution description'
input_parameters inputs
results outputs
workflow {FactoryGirl.create(:workflow)}
end
end
<file_sep># Contawords
ContaWords counts the words of any texts.
It can be used in contawords.iula.upf.edu
## Installation
Requirements:
* Ruby 1.9.3 or later
* Mysql
* Taverna server 2.4 installed (http://www.taverna.org.uk/documentation/taverna-2-x/server/)
* Feed Buzzer (https://github.com/landtax/feed_buzzer)
All required gems are specified in Gemfile, so just type
> bundle install
like any other rails app.
Create the DB
> rake db:schema:load
The app needs a workflow to run. Just one. It will take the first in the DB.
The workflow is already in the db/data folder.
Open the rails console and create a workflow
```
> w = Workflow.new
> w.taverna_workflow = File.open(Rails.root.join("db/data/workflow.t2flow"))
> w.save
```
## What it does
On every new word count, it connects to taverna server and sends the workflow with the parameters.
In the background, feed buzzer is suposed to ask to taverna server when the job is done and notify the app.
<file_sep>class AddNameAndDescriptionToExecution < ActiveRecord::Migration
def change
add_column :executions, :name, :string
add_column :executions, :description, :text
end
end
<file_sep>require 'spec_helper'
describe User do
subject {FactoryGirl.build(:user)}
its(:email){ "<EMAIL>"}
end
<file_sep>ActiveAdmin.register Workflow do
index do
column :id
column :user
column :name
column :taverna_workflow_file_name
column :created_at
column :updated_at
default_actions
end
end
| 695dd98b6c4d04ef2b2315ab2427f8f7d6c86da1 | [
"Markdown",
"Ruby"
] | 29 | Ruby | upf-iula-trl/servitoros_lite | 6d0d3a8e1d1e005df2d657c5e3641c6796fb3bed | 00c7e3539745fffe2098bb65ff52d6da8b2ebb1e |
refs/heads/master | <repo_name>tvhung83/ibot<file_sep>/show.js
const builder = require('botbuilder');
const request = require('request').defaults({
jar: true,
headers: {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.10 Safari/537.36',
'Ocp-Apim-Subscription-Key': process.env.OCP_APIM
}
});
const cheerio = require('cheerio');
const KEYWORD_LIST = [
'vietnam hot girls',
'<NAME>inh',
'Midu'
];
module.exports = exports = function(session) {
var keyword = KEYWORD_LIST[Math.round(Math.random() * (KEYWORD_LIST.length - 1))];
console.log('Searching %s ...', keyword);
request.post('https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=' + keyword, (error, response, body) => {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
console.log(info.totalEstimatedMatches);
var result = info.value[Math.round(Math.random() * 10)];
session.send(result.name);
var msg = new builder.Message(session)
.addAttachment({
contentUrl: result.contentUrl,
contentType: "image/jpeg",
name: "image.jpg"
});
session.send(msg);
} else {
console.error(body);
}
});
};
<file_sep>/app.js
var restify = require('restify');
var builder = require('botbuilder');
var QRCode = require('qrcode');
//=========================================================
// Bot Setup
//=========================================================
// Setup Restify Server
var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 8080, function() {
console.log('%s listening to %s', server.name, server.url);
});
// Create chat bot
var connector = new builder.ChatConnector({
appId: process.env.APP_ID,
appPassword: <PASSWORD>
});
var bot = new builder.UniversalBot(connector);
server.get(/\/csn\/?.*/, restify.plugins.serveStatic({
directory: __dirname
}));
// send simple notification
function sendProactiveMessage(address) {
var msg = new builder.Message().address(address);
msg.text('Hello, this is a notification');
msg.textLocale('en-US');
bot.send(msg);
}
var savedAddress;
// Do GET this endpoint to delivey a notification
server.get('/api/github', (req, res, next) => {
sendProactiveMessage(savedAddress);
res.send('triggered');
next();
});
server.post('/api/messages', connector.listen());
//Bot on
bot.on('contactRelationUpdate', function(message) {
if (message.action === 'add') {
var name = message.user ? message.user.name : null;
var reply = new builder.Message()
.address(message.address)
.text("Chào anh %s... em rất vui được làm quen với anh, anh gõ 'làm sao' để biết thêm nha!", name || 'ấy');
bot.send(reply);
} else {
// delete their data
}
});
bot.on('typing', function(message) {
// User is typing
});
bot.on('deleteUserData', function(message) {
// User asked to delete their data
});
//=========================================================
// Bots Dialogs
//=========================================================
String.prototype.contains = function(content) {
return this.indexOf(content) !== -1;
};
bot.dialog('/', function(session) {
savedAddress = session.message.address;
console.log('>>> %s', session.message.text);
if (session.message.text.toLowerCase().contains('hello')) {
session.send(`Hey, How are you?`);
} else if (session.message.text.toLowerCase().contains('http://chiasenhac.vn')) {
session.send('Anh ơi, vô rồi đó, anh chờ xíu nha, em ra liền...');
require('./csn')(session);
} else if (session.message.text.toLowerCase().match(/https?:\/\/(www\.)?fshare\.vn\//)) {
session.send('Anh ngồi đây xíu nhe, em đi lấy liền...');
require('./fshare')(session);
} else if (session.message.text.toLowerCase().contains('lột')) {
require('./show')(session);
} else if (session.message.text.toLowerCase().contains('làm sao')) {
var help = `Anh ơiiiiii, muốn "xài" em thì phải làm vầy nè:
1. Anh đưa link Fshare vô em, vầy nè anh: <pre>@vếu (là em đó, hí hí) https://www.fshare.vn/file/2GWXN9YU2ENQ</pre>
2. Hoặc là link ChiaSeNhac cũng được nha anh, thí dụ như: <pre>@vếu http://chiasenhac.vn/nhac-hot/dusk-till-dawn~zayn-sia~tsvd53t0qmhwfn.html</pre>
3. Mai mốt em còn nhiều trò vui lắm, từ từ em chỉ anh nghe!
`;
QRCode.toDataURL(help, (err, url) => {
var msg = new builder.Message(session)
.addAttachment({
contentUrl: url,
contentType: "image/png",
name: "qr_code.png"
});
session.send(msg);
});
// session.send(help);
} else {
session.send(randomQuote());
}
});
const QUOTE_LIST = [
'Anh à, nói gì mà em hổng hiểu, anh nói lại i.',
'Anh nói bậy quá nha!',
'Kì quá đi!',
'Nói gì vậy má!',
'Coi chừng vợ đánh nha anh!',
'Anh hỏi anh Jim kìa!',
'<NAME> đẹp trai ghê!'
];
function randomQuote() {
return QUOTE_LIST[Math.round(Math.random() * (QUOTE_LIST.length - 1))];
}
| 48666de5eb6760ae2ff91bb0abd4198fcaa2a4a5 | [
"JavaScript"
] | 2 | JavaScript | tvhung83/ibot | d6a9ac8c595cc9d4c5de33896ae398a0a1ebaeae | 2ba495ba93b0243708c0ae7c6baaea3adc3b4d41 |
refs/heads/master | <repo_name>derek-silva/my-select-houston-web-071618<file_sep>/lib/my_select.rb
def my_select(collection)
i = 0
array = []
while i < collection.length
if yield collection[i]
array.push(collection[i])
end
i = i + 1
end
array
end
| 8953ea3841c2147a08d3c83a6bce3cb637da751e | [
"Ruby"
] | 1 | Ruby | derek-silva/my-select-houston-web-071618 | 7fba9fe795942f3c7cf5a0e788306a42f1ff7a55 | 2b6c614228bd44c78c49e566d771d19608c0adfb |
refs/heads/master | <repo_name>teddim/bootstrap_app<file_sep>/app/models/welcome.rb
class Welcome
def boostrap_me()
end
end
<file_sep>/app/controllers/welcome_controller.rb
class WelcomeController < ApplicationController
def index
end
def show
@welcome = Welcome.bootstrap_me()
end
end
| 7cd851617f186fe7655661fc9efcf5ed6e69dbcb | [
"Ruby"
] | 2 | Ruby | teddim/bootstrap_app | b31f8bfba611b9f9648ca1d5785bffc84fe20619 | a348f555a1142a01aa8cf281f252fdc77bbd655b |
refs/heads/master | <file_sep># User Guide
Duke is a functional todo-list for managing your all your tasks, using the Command Line Interface (CLI).
* [Quick Start](#quick-start)
* [Features](#features)
+ [1. help](#1-help)
+ [2. list](#2-list)
+ [3. todo](#3-todo)
+ [4. deadline](#4-deadline)
+ [5. event](#5-event)
+ [6. done](#6-done)
+ [7. delete](#7-delete)
+ [8. find](#8-find)
+ [9. dateSearch](#9-dateSearch)
+ [10. bye](#10-bye)
* [Command Summary](#command-summary)
## Quick Start
1. Ensure that you have java *11* installed in your computer
2. Download duke.jar to a convenient folder
3. Navigate to the folder in command prompt and run it with `java -jar duke.jar`
4. Type `help` to see a list of commands for Duke
## Features
Duke can do the following:
* `help`: Provides a list of commands and how to use them
* `list`: List all of your current tasks
* `todo`: Add a todo to your list
* `deadline`: Add a deadline to your list
* `event`: Add an event to your list
* `done`: Mark an available task as done
* `delete`: Deletes a task
* `find`: Finds tasks that contain a keyword or string
* `dateSearch`: Finds tasks that are on that date
* `bye`: Terminates the application
### 1. help
Prints out a list of all available commands
##### Usage
Format: `help`
### 2. list
Prints out the list of all tasks
##### Usage
Format: `list`
### 3. todo
Adds a todo task to the list of tasks
##### Usage
Format: `todo [task description]`
### 4. deadline
Adds a deadline task to the list of tasks
##### Usage
Format: `deadline [task description] /[time limit] [date or string]`
### 5. event
Adds an event task to the list of tasks
##### Usage
Format: `event [task description] /[time limit] [date or string]`
### 6. done
Marks a task as done
##### Usage
Format: `done [task number]`
### 7. delete
Removes a task from the list
##### Usage
Format: `delete [task number]`
### 8. find
Finds tasks with a keyword or string the user inputs
##### Usage
Format: `find [keyword or string]`
### 9. dateSearch
Search through the list of tasks by date
##### Usage
Format: `dateSearch [date]`
### 10. bye
Exits this application
##### Usage
Format: `bye`
## Command Summary
Command | Format | Example
------- | ---------- | ------------
help | `help` | -
list | `list` | -
todo | `todo [task description]` | `todo study for exams`
deadline | `deadline [task description] /[time limit] [date or string]`| `deadline` submit report /before 31/12/2020
event | `event [task description] /[time limit] [date or string]` | `event` TED talk /at 30-12-2020
find | `find [keyword or string]` | `find study`
done | `done [task number]` | `done 3`
delete | `delete [task number]` | `delete 4`
dateSearch | `dateSearch [date]` | dateSearch 2020/12/20
bye | `bye` | -
<file_sep>package duke;
import duke.command.AddDeadlineCommand;
import duke.command.AddEventCommand;
import duke.command.AddTodoCommand;
import duke.command.ByeCommand;
import duke.command.Command;
import duke.command.DateSearchCommand;
import duke.command.DeleteCommand;
import duke.command.DoneCommand;
import duke.command.FindCommand;
import duke.command.HelpCommand;
import duke.command.ListTasksCommand;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
/**
* Parses inputs for other functions to use
*/
public class Parser{
/**
* Interprets the user input then creates a command
*
* @param inputString User input
* @return Command
*/
protected static Command parseCommand(String inputString) {
// limit of 2 splits the string into 2 parts
String[] inputSplit = inputString.trim().split(" ", 2);
Command c = null;
try {
String command = inputSplit[0];
switch (command) {
case "list":
c = new ListTasksCommand();
break;
case "done":
if (inputSplit.length < 2) {
throw new DukeException("done");
}
c = new DoneCommand(inputSplit[1]);
break;
case "todo":
if (inputSplit.length < 2) {
throw new DukeException("todo");
}
c = new AddTodoCommand(inputSplit[1]);
break;
case "deadline":
if (inputSplit.length < 2) {
throw new DukeException("deadline");
}
c = new AddDeadlineCommand(inputSplit[1]);
break;
case "event":
if (inputSplit.length < 2) {
throw new DukeException("event");
}
c = new AddEventCommand(inputSplit[1]);
break;
case "help":
c = new HelpCommand();
break;
case "delete":
if (inputSplit.length < 2) {
throw new DukeException("delete");
}
c = new DeleteCommand(inputSplit[1]);
break;
case "dateSearch":
if (inputSplit.length < 2) {
throw new DukeException("dateSearch");
}
c = new DateSearchCommand(inputSplit[1]);
break;
case "bye":
c = new ByeCommand();
break;
case "find":
if (inputSplit.length < 2) {
throw new DukeException("find");
}
c = new FindCommand(inputSplit[1]);
break;
default:
Ui.invalidCommandMessage();
break;
}
} catch (ArrayIndexOutOfBoundsException e) {
Ui.invalidCommandMessage();
} catch (DukeException e) {
Ui.printLine();
e.getError("error");
Ui.printLine();
}
return c;
}
/**
* Converts the user time input to LocalTime object
*
* @param dateTimeInput Date time input string
* @return LocalTime object
*/
public static LocalTime parseTime(String dateTimeInput) {
String[] dateTimeSplit = dateTimeInput.trim().split(" ", 2);
String timeInput;
// checks if there is a time in the format dd-mm-yyyy HHmm format
if (dateTimeSplit.length == 2) {
timeInput = dateTimeSplit[1];
} else {
return null;
}
// formatter for dates with time
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HHmm");
LocalTime time = null;
try {
time = LocalTime.parse(timeInput, timeFormatter);
} catch (DateTimeParseException e) {
// returns null if input format is wrong
}
return time;
}
/**
* Converts the date and time into a LocalDate object
*
* @param dateTimeInput Date time input string
* @return LocalDate object
*/
public static LocalDate parseDate(String dateTimeInput) {
String[] dateTimeSplit = dateTimeInput.trim().split(" ", 2);
String dateInput;
dateInput = dateTimeSplit[0];
// formatters for dates with time
DateTimeFormatter formatterA = DateTimeFormatter.ofPattern("dd/MM/yyyy");
DateTimeFormatter formatterB = DateTimeFormatter.ofPattern("dd-MM-yyyy");
DateTimeFormatter formatterC = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate date = null;
try {
date = LocalDate.parse(dateInput, formatterA);
} catch (DateTimeParseException e) {
// puts the date and time through all available formatters
}
try {
if (date == null) {
date = LocalDate.parse(dateInput, formatterB);
}
} catch (DateTimeParseException e) {
// puts the date and time through all available formatters
}
try {
if (date == null) {
date = LocalDate.parse(dateInput, formatterC);
}
} catch (DateTimeParseException e) {
// puts the date and time through all available formatters
}
try {
if (date == null) {
// this uses default formatter of yyyy-MM-dd
date = LocalDate.parse(dateInput);
}
} catch (DateTimeParseException e) {
// puts the date and time through all available formatters
}
// returns null if all the available formatters could not be used
return date;
}
}
<file_sep>package duke.command;
import duke.Storage;
import duke.TaskList;
import duke.Ui;
/**
* Contains actions for a deleting a task
*/
public class DeleteCommand extends Command {
String number;
/**
* Constructs a command with numerical user input for deleting task
*/
public DeleteCommand(String number) {
this.number = number;
}
/**
* Calls the add delete task
*
* @param tasks ArrayList of Tasks
* @param ui Ui instantiation
* @param storage Storage instantiation
*/
@Override
public void execute(TaskList tasks, Ui ui, Storage storage) {
tasks.taskDelete(tasks, ui, storage, number);
}
}
<file_sep>package duke.task;
import duke.Parser;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
/**
* Represents an event
*/
public class Event extends Task {
boolean isTimeExist;
LocalTime time;
/**
* Constructs an instantiation of an event
*
* @param description Description of the event
* @param doBy Threshold of when the event is on
*/
public Event(String description, String doBy) {
super(description);
this.doBy = doBy.trim().split(" ", 2);
this.date = Parser.parseDate(this.doBy[1]);
this.time = Parser.parseTime(this.doBy[1]);
this.isDateExist = this.date != null;
this.isTimeExist = this.time != null;
}
/**
* Prints a fully formatted event
*
* @return Returns a fully formatted event string
*/
@Override
public String toString() {
if (isDateExist && isTimeExist) {
return "[E]" + super.toString() + "(" + this.doBy[0] + ": "
+ this.date.format(DateTimeFormatter.ofPattern("MMM d yyyy")) + ", "
+ this.time.format(DateTimeFormatter.ofPattern("hh:mm a")) + ")";
} else if (isDateExist) {
return "[E]" + super.toString() + "(" + this.doBy[0] + ": "
+ this.date.format(DateTimeFormatter.ofPattern("MMM d yyyy"))
+ ")";
} else {
return "[E]" + super.toString() + "(" + this.doBy[0] + ": " + this.doBy[1] + ")";
}
}
}
<file_sep>package duke.command;
import duke.Storage;
import duke.TaskList;
import duke.Ui;
/**
* Contains actions for finding a task
*/
public class FindCommand extends Command {
String searchQuery;
/**
* Constructs a command with user input for search query
*/
public FindCommand (String searchQuery) {
this.searchQuery = searchQuery;
}
/**
* Calls the find command
*
* @param tasks ArrayList of Tasks
* @param ui Ui instantiation
* @param storage Storage instantiation
*/
@Override
public void execute(TaskList tasks, Ui ui, Storage storage) {
ui.taskFind(tasks, ui, storage, searchQuery);
}
}
<file_sep>package duke.command;
import duke.Storage;
import duke.TaskList;
import duke.Ui;
/**
* Contains actions for marking a task as done
*/
public class DoneCommand extends Command {
String number;
/**
* Constructs a command with numerical user input for marking task as done
*/
public DoneCommand(String number) {
this.number = number;
}
/**
* Calls the mark task as done function
*
* @param tasks ArrayList of Tasks
* @param ui Ui instantiation
* @param storage Storage instantiation
*/
@Override
public void execute(TaskList tasks, Ui ui, Storage storage) {
tasks.taskDone(tasks, ui, storage, number);
}
}
<file_sep>package duke;
import duke.task.Deadline;
import duke.task.Event;
import duke.task.Task;
import duke.task.Todo;
import java.util.ArrayList;
/**
* Holds the task list and modifying functions
*/
public class TaskList {
protected static ArrayList<Task> tasks = new ArrayList<>();
/**
* Deletes a task from the list
*
* @param tasks TaskList instantiation
* @param ui Ui instantiation
* @param storage Storage instantiation
* @param s User number input
*/
public void taskDelete(TaskList tasks, Ui ui, Storage storage, String s) {
Ui.printLine();
try {
int taskNumber = Integer.parseInt(s);
// to check if the task exists
if (taskNumber <= 0 || taskNumber > tasks.getTasksSize()) {
throw new DukeException("delete");
}
ui.taskDeleteMessage(taskNumber);
storage.saveTasks(TaskList.tasks);
} catch (DukeException e) {
e.getError("delete");
}
Ui.printLine();
}
/**
* Adds an event into the task list
*
* @param tasks TaskList instantiation
* @param ui Ui instantiation
* @param storage Storage instantiation
* @param s User string input
*/
public void taskAddEvent(TaskList tasks, Ui ui, Storage storage, String s) {
String[] inputSplitAtSlash;
try {
//splits input into task and time
inputSplitAtSlash = s.trim().split("/", 2);
if (inputSplitAtSlash.length == 1) {
throw new DukeException("event");
}
// if input string format does not fit constructor, throw error
String[] constructorFormat = inputSplitAtSlash[1].trim().split(" ", 2);
if (constructorFormat.length == 1) {
throw new DukeException("event");
}
Event temp = new Event(inputSplitAtSlash[0], inputSplitAtSlash[1]);
TaskList.tasks.add(temp);
ui.taskWithTimeAddMessage(tasks);
storage.saveTasks(TaskList.tasks);
} catch (DukeException e) {
Ui.printLine();
e.getError("event");
Ui.printLine();
}
}
/**
* Adds a deadline into the task list
*
* @param tasks TaskList instantiation
* @param ui Ui instantiation
* @param storage Storage instantiation
* @param s User string input
*/
public void taskAddDeadline(TaskList tasks, Ui ui, Storage storage, String s) {
String[] inputSplitAtSlash;
try {
//splits input into task and time
inputSplitAtSlash = s.trim().split("/", 2);
if (inputSplitAtSlash.length == 1) {
throw new DukeException("deadline");
}
// if input string format does not fit constructor, throw error
String[] constructorFormat = inputSplitAtSlash[1].trim().split(" ", 2);
if (constructorFormat.length == 1) {
throw new DukeException("deadline");
}
Deadline temp = new Deadline(inputSplitAtSlash[0], inputSplitAtSlash[1]);
TaskList.tasks.add(temp);
ui.taskWithTimeAddMessage(tasks);
storage.saveTasks(TaskList.tasks);
} catch (DukeException e) {
Ui.printLine();
e.getError("deadline");
Ui.printLine();
}
}
/**
* Adds a todo into the task list
*
* @param tasks TaskList instantiation
* @param ui Ui instantiation
* @param storage Storage instantiation
* @param input User string input
*/
public void taskAddTodo(TaskList tasks, Ui ui, Storage storage, String input) {
try {
Todo temp = new Todo(input);
TaskList.tasks.add(temp);
ui.taskAddMessage(tasks);
storage.saveTasks(TaskList.tasks);
} catch (DukeException e) {
Ui.printLine();
e.getError("todo");
Ui.printLine();
}
}
/**
* Marks a task as done
*
* @param tasks TaskList instantiation
* @param ui Ui instantiation
* @param storage Storage instantiation
* @param inputSplit User numerical input for task
*/
public void taskDone(TaskList tasks, Ui ui, Storage storage, String inputSplit) {
Ui.printLine();
try {
int taskNumber = Integer.parseInt(inputSplit);
// on 0-index based array, location of task is -1
int taskIndex = taskNumber - 1;
// to check if the task exists
if (taskNumber <= 0 || taskNumber > tasks.getTasksSize()) {
throw new DukeException("done");
}
TaskList.tasks.get(taskIndex).markAsDone();
System.out.println("Nice! I've marked this task as done:");
System.out.println(taskNumber + "." + TaskList.tasks.get(taskIndex));
storage.saveTasks(TaskList.tasks);
} catch (DukeException e) {
e.getError("done");
}
Ui.printLine();
}
/**
* Returns size of tasks arraylist
*
* @return ArrayList size
*/
public int getTasksSize() {
return tasks.size();
}
}
| 5ea925664a641798516b4231e0c9755f8e6e11c0 | [
"Markdown",
"Java"
] | 7 | Markdown | CFZeon/ip | 184be3cfc7e63e9e8e8f6576f2435153ecc0f429 | 8db7a149788a6e7f8dd1782e27b372120b83067c |
refs/heads/master | <repo_name>leaf-shinobi/trove<file_sep>/.github/ISSUE_TEMPLATE/component.md
---
name: Component
about: Assigned component
title: ''
labels: "component \U0001F525"
assignees: ''
---
**Description**
Short description of the component
**Paths**
Relevant paths
**Extended Description**
Longer description of the component if needed
**Issue Tracking**
Include issue number (e.g. #2)
<file_sep>/pages/api/[collection_id].js
import { getCollection } from '../../database';
export default (req, res) => {
getCollection((collection) => res.send(collection));
};
<file_sep>/pages/collections/[collection_id]/[item_id].js
import Head from 'next/head';
export default function Collections() {
return (
<div>
<h1>Item Page</h1>
</div>
);
}
//Route to access this page
//localhost:3000/collections/collection_id/item_id<file_sep>/pages/api/collections.js
import { getCollections } from '../../database';
export default (req, res) => {
getCollections(1, (collection) => res.send(collection));
};
| 1d17bbd314f52baedab5818da2b6ba8ca8d369cd | [
"Markdown",
"JavaScript"
] | 4 | Markdown | leaf-shinobi/trove | eb481f24cc63210311841287209294aee66709f5 | f92cba3d469bc1cccb8bbd7b861ef9bb2959b23d |
refs/heads/master | <file_sep>namespace OdeToFood.Migrations
{
using OdeToFood.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<OdeToFood.Models.OdeToFoodDB>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
ContextKey = "OdeToFood.Models.OdeToFoodDB";
}
protected override void Seed(OdeToFood.Models.OdeToFoodDB context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
context.Restaurants.AddOrUpdate(r => r.Name,
new Restaurant { Name = "<NAME>", City = "Mumbai", Country = "India" },
new Restaurant { Name = "<NAME>", City = "Mumbai", Country = "India" },
new Restaurant {
Name="<NAME>",
City="Mumbai",
Country="India",
Reviews= new List<RestaurantReview>
{
new RestaurantReview{Rating=9, Body="teslkjkjs jdla skld",ReviewerName="Aamir"}
}
});
for(int i=0;i<1000;i++)
{
context.Restaurants.AddOrUpdate(r => r.Name,
new Restaurant { Name = i.ToString(), City = "Nowehre", Country = "USA" });
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OdeToFood.Filters;
namespace OdeToFood.Controllers
{
[Log]
public class CuisineController : Controller
{
//
// GET: /Cuisine/
//public ActionResult Index()
//{
// return View();
//}
//public string Index(string a)
//{
// return "";
//}
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Search(string name="french")
{
var message = Server.HtmlEncode(name);
return Content(message);
//return RedirectToAction("Index", "Home", new { name = name });
//return Json(new { Message = message, Name = "Aamir" }, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult Search()
{
return Content("Search!");
//return RedirectToAction("Index", "Home", new { name = name });
//return Json(new { Message = message, Name = "Aamir" }, JsonRequestBehavior.AllowGet);
}
}
} | 962654ce092cf1e5dfd571616683613e1f8aa853 | [
"C#"
] | 2 | C# | aamiransari111/mvclearning | 32f17bebbab350ec154a5c2654d0f79515e681b7 | 4602805fddf67a81a93e04e2d41dc9e65681ce31 |
refs/heads/master | <file_sep>#include<iostream>
#include<cstdio>
#DEFINE SIZE 10
using namespace std;
int getElement(){
int element;
cout<<endl<<"Enter an element(int): ";
cin>>element;
cout<<endl;
return element;
}
char command(){
char inp;
cout<<"\n-Press 'i' to insert an element\n-Press 'x' to delete an element\n-Press 's' to search\n-Press 'd' to display the table\n-Press 'q' to quit\n>>>> ";
cin>>inp;
return inp;
}
class node{
public:
int data;
node *next;
node *previous;
node(int key){
data = key;
next = NULL;
previous = NULL;
}
};
int hash(int key, int m = SIZE){
return key%(m-1);
}
void insert(int key, node *table, int size = SIZE){
int index = hash(key);
if(table[index] == NULL){
table[index] = new node(key);
}
else{
node *ins = new node(key);
ins->next = table[index];
table[index]->previous = ins;
table[index] = ins;
}
}
node* search(int key, node *table, int size = SIZE){
}
void delete(node* target){
}
void display(){
}
int main(){
node table[SIZE];
while(1){
switch(command()){
case 'i':
insert(getElement(),table)
break;
case 'x':
del(search(getElement(),table))
break;
case 's':
node* result = search(getElement(),table);
if(node)cout<<"Element found"<<endl;
else cout<<"Element not found"<<endl;
break;
case 'd':
display()
break;
case 'q':
return 0;
default:
cout<<"Please give a valid input..."<<endl;
break;
}
}
return 0;
}
<file_sep>#include<iostream>
#define size 10 //size of stack is 10
using namespace std;
char command(){ //this fn takes an input from the user to get functionality
char inp;
cout<<"\n-Press 's' to check the status of the stack\n-press 'P' to push\n-Press 'p' to pop\n-Press 'd' to display the stack\n-Press 'q' to quit\n>>>> ";
cin>>inp;
return inp;
}
class stack{
private:
int mem[size]; //declaration of the actual stack memory (size = 10)
int stackPtr; //stackPtr maps to the elements of the stack
public:
stack(){
stackPtr=0; //stackPtr is always mapped to the next empty element in the stack
}
int stackFlow(){ //stackflow checks the status of the stack and returns an int accordingly
if(stackPtr==0)return -1; // -1 for stack underflow
if(stackPtr==size)return 1; // +1 for stack overflow
return 0; //0 for all other cases
}
void display(){ //displays stack from start to end
if(stackPtr==0){
cout<<"Stack is empty"<<endl; //checking for stackunderflow
return;
}
cout<<"Here's your stack: \n";
int x;
cout<<endl;
for(x=0;x<stackPtr;x++)cout<<mem[x]<<" ";
cout<<endl;
}
void PUSH(int x){ //function to implement PUSH
if(stackPtr<size){ //checking for stackoverflow
mem[stackPtr++]=x; //increments stackPtr AFTER pushing an element
return;
}
else{
cout<<"Stack is full"<<endl;
return;
}
}
void POP(){ //function to implement POP
if(stackPtr>0){ //checking for stackunderflow
cout<<mem[--stackPtr]; //stackPtr is decremented before POP
return;
}
else{
cout<<"Stack is empty";
return;
}
}
};
int main(){
stack s;
while(1){
switch(command()){ //takes user input commands and executes respective functions
case 's':
switch(s.stackFlow()){
case -1:
cout<<"\nStack is empty"<<endl;
break;
case 0:
cout<<"\nStack is neither empty nor full"<<endl;
break;
case 1:
cout<<"\nStack is full"<<endl;
break;
}
break;
case 'P':
int ele;
cout<<">>";
cin>>ele;
s.PUSH(ele);
break;
case 'p':
s.POP();
break;
case 'd':
s.display();
break;
case 'q':
return 0;
default:
cout<<"Please give a valid input..."<<endl;
break;
}
}
return 0;
}
<file_sep>#include<iostream>
#include<cstdio>
using namespace std;
class heap{ //heap class
protected:
int heapSize=0,*heapArr=NULL;
public:
heap(){
cout<<"Enter the number of elements in the heap: ";
cin>>heapSize; //user inputs heapsize
heapArr = new int[heapSize];
cout<<"Enter a space separated list of "<<heapSize<<" integers to create a heap: ";
for(int i=0;i<heapSize;i++)cin>>heapArr[i];
buildHeap();
}
void inorder(int index = 0){ //for increasing order traversal
if(index >= heapSize)return;
inorder(left(index)); //recusrive definition
cout<<heapArr[index]<<" ";
inorder(right(index));
return;
}
void heapSort(){ //works by putting first element last
int originalSize = heapSize,temp;
for(int i = heapSize-1; i >0; i--){ //largest element goes to the end after each iteration
temp = heapArr[i];
heapArr[i] = heapArr[0];
heapArr[0] = temp;
heapSize--; //heapsize is reduced to perform operations on remaining heap
heapify(0); //restores heap properties
}
heapSize = originalSize;
for(int i = 0; i< heapSize; i++) cout<<heapArr[i]<<" ";
}
private:
int left(int x){return (2*x + 1);}
int right(int x){return (2*x +2);}
void heapify(int x){ //restores heap properties
int largest, l=left(x), r= right(x);
if(l <heapSize && heapArr[x] < heapArr[l]) largest = l;
else largest = x;
if(r <heapSize && heapArr[largest] < heapArr[r]) largest = r;
if(largest != x){
int temp = heapArr[largest];
heapArr[largest] = heapArr [x];
heapArr[x] = temp;
heapify(largest); //recursive definition
}
}
void buildHeap(){
for(int i = (heapSize-1)/2; i >= 0; i--){
heapify(i); //repeatedly restores heap properties
}
}
};
int main(){
heap A;
A.heapSort();
}
<file_sep>#include<iostream>
using namespace std;
char command(){
char inp;
cout<<"\n-Press 'e' to enter an element\n-Press 'x' to delete an element\n-Press 'd' to display the queue\n-Press 'q' to quit\n>>>> ";
cin>>inp;
return inp;
}
class queue{
private:
int size,front,end, array[10000],checkFull;
public:
queue(){
cout<<"Enter the size of the circular queue: ";
cin>>size;
front=0;
end=0;
checkFull=0;
}
void insert_in_queue(int element){
if(checkFull==0){
array[end]=element;
end++;
end%=size;
if(end==front){
checkFull=1;cout<<"Queue full";
cout<<"Position of end="<<end;
}
} else {cout<<"Queue is full"<<endl;}
}
int delete_from_queue(){
cout<<"The dequeued element is: "<<array[front];
front++;
front%=size;
cout<<"Position of front="<<front;
}
int display_queue(){
if(front==end){
cout<<"The queue is: ";
for(int i=0;i<size;i++){
cout<<array[(front+i)%size]<<" ";
if((front+i)%size==end)return 0;
}
}
}
};
int main(){
queue Q;
while(1){
switch(command()){
case 'e':
int element;
cout<<"Enter an element to enqueue: ";
cin>>element;
Q.insert_in_queue(element);
break;
case 'x':
if(!Q.delete_from_queue())cout<<"Queue is empty"<<endl;
break;
case 'd':
Q.display_queue();
break;
case 'q':
return 0;
default:
cout<<"Please give a valid input..."<<endl;
break;
}
}
return 0;
}
<file_sep>/*
1. Inserting a node at the end of the queue. The value to be put in the node will be passed as a function parameter.
2. Searching for a value in the linked list.
3. Displaying the entire linked list. While displaying, print (a) the value contained in the node and (b) the address of the node.
4. Deleting the entire linked list.
*/
#include<iostream>
#include<string>
using namespace std;
char command(){ //this fn takes an input from the user to get functionality
char inp;
cout<<"\n-Press 'i' to insert an element\n-Press 's' to search for an element\n-Press 'd' to display the list\n-Press 'x' to delete an element\n-Press 'q' to quit\n>>>> ";
cin>>inp;
return inp;
}
struct node{ //definition of the required structure
int Roll,age;
string name,gender;
struct node *next;
};
class queue{
public:
queue();
struct node dequeue(int);
struct node* search(int);
void display();
void enqueue(int);
protected:
struct node *start,*end;
};
int main(){
queue list; //sets the start and end
while(1){
switch(command()){ //user inputs the commands
case 'i':
int element;
cout<<"Enter an integer element to enqueue: ";
cin>>element;
list.enqueue(element);
break;
case 'x':
cout<<"Enter an integer element to dequeue: ";
cin>>element;
if(list.dequeue(element))cout<<"\nElement deleted successfully\n";
else cout<<"\nNo such element exists\n"<<endl;
break;
case 's':
{
int srch;
cout<<"Enter an integer element to search: ";
cin>>srch;
struct node *result=list.search(srch);
if(result)cout<<cout<<"\nThe element was found at:"<<result<<endl;
else cout<<"Element not found."<<endl;
break;
}
case 'd':
list.display();
break;
case 'q':
return 0;
default:
cout<<"Please give a valid input..."<<endl;
break;
}
}
return 0;
}
queue::queue(){ //sets/reserts the start and end pointers
start = new struct node;
start->next=NULL;
end=start;
return;
}
void queue::display(){
struct node *current;
cout<<endl;
for(current=start->next;current!=NULL;current=current->next){ //from starting to ending of the list, current takes the next address in the for loop step itself
cout<<"\t\tValue: "<<current->Roll<<" at Address: "<<current<<endl;
}
cout<<"\n--linked list was printed--\n\n"; //log
return;
}
void queue::enqueue(int newVal){
struct node *newEnd = new struct node; //dynamically allocates memory for accomodating a new node
newEnd->Roll=newVal; //value is stored in the newly created node
end->next=newEnd; //the end is now pointing to the new node
newEnd->next=NULL; //the new node is globally declared as the end of the list
end=newEnd;
this->display();
return;
}
struct node* queue::search(int searchVal){
struct node *current; //current to iterate over the list
for(current=start->next;current!=NULL;current=current->next){
if(current->Roll==searchVal){ //checking for the value
return current; //returns if found
}
}
return NULL;
}
struct node queue::dequeue(){
struct node temp = *(head->next);
delete (head->next);
head->next = temp->next
return temp;
}
<file_sep>#include<iostream>
using namespace std;
void selectionSort(int *arr, int n){
int min,temp;
for (int i=0; i < n-1; i++){
min = i;
for (int j=i+1; j < n; j++){
if (arr[j] < arr[min])
min=j;
}
if (min != i){
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
return;
}
int main(){
int n;
cout<<"Enter number of elements: ";
cin>>n;
int a[n];
cout<<"Enter the "<<n<<" values: ";
int i;
for(i=0;i<n;i++){
cin>>a[i];
}
selectionSort(a,n);
cout<<"The sorted array is:";
for(i=0;i<n;i++){
cout<<a[i]<<" ";
}
return 0;
}
<file_sep>#include<iostream>
#include<string>
using namespace std;
struct node{
string RollNo;
float age;
string name;
string gender;
};
void insertionSort (struct node *a, int n){
int j;
struct node temp;
for (int i = 0; i < n; i++){
j = i;
while ((j > 0) && (a[j].RollNo).compare(a[j-1].RollNo)){ //j>0 and a.RollNo[j] < a.RollNo[j-1])
temp = a[j];
a[j] = a[j-1];
a[j-1] = temp;
j--;
}
}
return;
}
int takeRecord(struct node *arr,int index){
string Roll;
cout<<"\tEnter Roll No: ";
cin>>Roll;
for(int i=0;i<index;i++){
if(arr[i].RollNo==Roll){
cout<<"This roll number already exists, please enter another...\n";
return 1;
}
}
arr[index].RollNo=Roll;
cout<<"\tEnter age: ";
cin>>arr[index].age;
cout<<"\tEnter Name: ";
cin>>arr[index].name;
cout<<"\tEnter gender: ";
cin>>arr[index].gender;
cout<<endl;
return 0;
}
int main(){
int n;
cout<<"Enter the number of records to store: ";
cin>>n;
struct node arr[n];
cout<<"Enter the details of each record\n";
for(int i=0;i<n;i++){
while(takeRecord(arr,i));
}
insertionSort(arr,n);
for(int ix=n-1;ix>=0;ix--){
cout<<arr[ix].RollNo<<endl;
}
}
<file_sep>/*
1. Inserting a node at the end of the list. The value to be put in the node will be passed as a function parameter.
2. Searching for a value in the linked list.
3. Displaying the entire linked list. While displaying, print (a) the value contained in the node and (b) the address of the node.
4. Deleting the entire linked list.
*/
#include<iostream>
#include<string>
using namespace std;
char command(){ //this fn takes an input from the user to get functionality
char inp;
cout<<"\n-Press 'i' to insert an element\n-Press 's' to search for an element\n-Press 'd' to display the list\n-Press 'x' to delete an element\n-Press 'q' to quit\n>>>> ";
cin>>inp;
return inp;
}
struct node{ //definition of the required structure
int Roll,age;
string name,gender;
struct node *next;
};
class linkedList{
public:
linkedList();
int del(int);
struct node* search(int);
void display();
void insertEnd(int);
protected:
struct node *start,*end;
};
int main(){
linkedList list; //sets the start and end
while(1){
switch(command()){ //user inputs the commands
case 'i':
int element;
cout<<"Enter an integer element to add to the end of the list: ";
cin>>element;
list.insertEnd(element);
break;
case 'x':
cout<<"Enter an integer element to delete: ";
cin>>element;
if(list.del(element))cout<<"\nElement deleted successfully\n";
else cout<<"\nNo such element exists\n"<<endl;
break;
case 's':
{
int srch;
cout<<"Enter an integer element to search: ";
cin>>srch;
struct node *result=list.search(srch);
if(result)cout<<cout<<"\nThe element was found at:"<<result<<endl;
else cout<<"Element not found."<<endl;
break;
}
case 'd':
list.display();
break;
case 'q':
return 0;
default:
cout<<"Please give a valid input..."<<endl;
break;
}
}
return 0;
}
linkedList::linkedList(){ //sets/reserts the start and end pointers
start = new struct node;
start->next=NULL;
end=start;
return;
}
void linkedList::display(){
struct node *current;
cout<<endl;
for(current=start->next;current!=NULL;current=current->next){ //from starting to ending of the list, current takes the next address in the for loop step itself
cout<<"\t\tValue: "<<current->Roll<<" at Address: "<<current<<endl;
}
cout<<"\n--linked list was printed--\n\n"; //log
return;
}
void linkedList::insertEnd(int newVal){
struct node *newEnd = new struct node; //dynamically allocates memory for accomodating a new node
newEnd->Roll=newVal; //value is stored in the newly created node
end->next=newEnd; //the end is now pointing to the new node
newEnd->next=NULL; //the new node is globally declared as the end of the list
end=newEnd;
this->display();
return;
}
struct node* linkedList::search(int searchVal){
struct node *current; //current to iterate over the list
for(current=start->next;current!=NULL;current=current->next){
if(current->Roll==searchVal){ //checking for the value
return current; //returns if found
}
}
return NULL;
}
int linkedList::del(int val){
struct node *target=this->search(val);
if(target==NULL)return 0;
else{
struct node* cur;
for(cur=start;cur->next!=target;cur=cur->next)continue;
cur->next=target->next;
delete target;
return 1;
}
}
<file_sep>//Minimum Spanning tree
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
class edge{ //a data tyope to store edges
public:
edge *next; //for the implementation of an adjacency list
int vertex1,vertex2,weight; //3 properties of any edge
edge(){} //default constructor
edge(int v1,int v2, int w){ //initialiser constructor
vertex1 = v1;
vertex2 = v2;
weight = w;
}
};
int partition (edge arr[], int low, int high){ //for quicsort algorithm
int pivot = arr[high].weight;
int i = low - 1;
for (int j = low; j <= high- 1; j++){
if (arr[j].weight <= pivot){
i++;
edge temp = arr[j]; //swap(&arr[i], &arr[j]);
arr[j]=arr[i];
arr[i]= temp;
}
}
edge temp = arr[i+1]; //swap(&arr[i + 1], &arr[high]);
arr[i+1]=arr[high];
arr[high]= temp;
return (i + 1);
}
void quickSort(edge arr[], int low, int high){ //the controlling quickSort function
if (low < high){
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
} //sorts in O(nlogn) time
class graph{ //graph class
protected:
int nVertices;
edge **startPt; //pointer to the first pointer of adjacency list
int nEdges; //number of edges
public:
graph(){ //default initialiser
nVertices = 0;
startPt = NULL;
nEdges = 0;
}
int buildList(){ //this function takes adjacency list input from the user
cout<<endl<<"\tInstructions: \n\tFor each node in the graph, enter a space separated list of adjacent vertices and their weights.\n\tFor every vertex in the adjacency list, enter the respective weight with a ':' character.\n\tWhen a list is complete, press 'enter' for the next node\n\n\tNote:\n\tProgram will only consider valid inputs, e.g. if a total of 10 nodes exist, vertices >= 10 will not be considered\n\n\tSyntax\t\tNode [number]: [vertex]:[weight]\n\tExample\t\tNode 5: 1:2 3:8 7:1 8:2 12:3\n"<<endl; //input specifications. These are the instructions for the user to input adjacency list
cout<<"\nEnter the number of nodes in the graph: ";
cin>>nVertices;
edge** adList = new edge*[nVertices]; //creates an array to store starting addresses for each vertex's likned list
startPt = adList; //beginning of the adjacency list stored in the startPt pointer
for(int i=0;i<nVertices-1;i++){ //for each vertex in the graph
string line;
cout<<"Enter the adjacency list for node "<<i<<" :";
if(cin.peek() =='\n')cin.ignore(100,'\n'); //to check for termination of list according to input format (specified above)
getline(cin, line,'\n'); //extract line from buffer and place in string line
istringstream streamline(line); //this creates a istringstream object from a string. it is easy to perform operations on this object
int vertex,weight;
char temp; //required to validate user input
edge **current = adList+i; //**previous = NULL; //the edge to-be-filled with data
adList[i] = NULL;
while((streamline >> vertex >> temp >> weight) && temp == ':'){ //input validated and stored in respective variables
if(vertex > i && vertex < nVertices){ //this is to make sure no edge gets repeated
*current = new edge(i,vertex,weight); //new edge onject is created
nEdges++; //simultaneously counts the number of edges (which we haven't taken as input, for conveniece)
//*previous = *current;
current = &((*current)->next); //the next element should go into the next field of the current edge. We store is address in current
}
}
*current = NULL; //the last edge must point to NULL to signal the end of the edge linked list
//(*previous)->next = NULL
}
cout<<"Total of "<<nEdges<<" edges were input."<<endl;
return nVertices;
}
void showList(){ //outputs the adjacency list
edge* current;
for(int i=0;i<nVertices-1;i++){
cout<<"Node: "<<i<<endl;
for (current = startPt[i]; current != NULL; current=current->next){
cout<<"\t\tVertices: "<<current->vertex1<<" "<<current->vertex2<<" and its weight is: "<<current->weight<<endl;
}
}
return;
}
edge* sort(){ //before calling quickSort, we must make an array fro ma linked list
edge* toSort = new edge[nEdges]; //this array will store the edges, and quickSort will sort this array
edge *current;
int c1 = 0, c2 = 0;
while(c2 < nEdges){
current = startPt[c1++];
while(current!=NULL){
toSort[c2++] = *current; //for each vertex, put the corresponding vertices in toSort
current = current->next;
}
}
//for(int i=0; i<c2; i++)cout<<toSort[i].vertex1<<" "<<toSort[i].vertex2<<" "<<toSort[i].weight<<endl;
quickSort(toSort,0,c2-1); //this will sort the edges according to their weights
for(int i=0; i<c2; i++)cout<<toSort[i].vertex1<<" "<<toSort[i].vertex2<<" "<<toSort[i].weight<<endl;
return toSort;
}
void caclMST(){ //calculation of MST using union-find data structure
edge* sorted = sort();
int unionFind[nVertices]; //THE unionFind data structure shows graph connections
edge mstEdges[nVertices -1];
int edgeCounter = 0;
for(int i = 0; i< nVertices; i++){
unionFind[i] = i; //initialiser
}
for(int i = 0; i< nVertices; i++){
int v1 = unionFind[sorted[i].vertex2], v2 = unionFind[sorted[i].vertex1];
if(v1 != v2){
mstEdges[edgeCounter++] = sorted[i]; //add to mstEdges if two vertices are not connected
for(int j = 0; j< nVertices; j++){
if(unionFind[j] == v2)unionFind[j] = v1; //update unionFind data structure
}
}
} //print the output
for(int k=0; k< nVertices - 1; k++)cout<<"Edge: "<<mstEdges[k].vertex1<<"-"<<mstEdges[k].vertex2<<": "<<mstEdges[k].weight<<endl;
}
};
int main(){
graph A;
int number = A.buildList();
A.showList();
A.caclMST();
return 0;
}
<file_sep>#include<iostream>
#include<cstdio>
#include<string>
#define MAX_SIZE 1000
using namespace std;
int getElement(){
int element;
cout<<endl<<"Enter an element(int): ";
cin>>element;
cout<<endl;
return element;
}
string getString(){
string element;
cout<<endl<<"Enter a element(string): ";
cin>>element;
cout<<endl;
return element;
}
char command(){
char inp;
cout<<"\n-Press 'i' to insert an element\n-Press 'x' to extract the top of the Priority Queue\n-Press 's' to sort the Priority Queue (and quit)\n-Press 'd' to display the Queue inorder (for debugging)\n-Press 'q' to quit\n>>>> ";
cin>>inp;
return inp;
}
//--------------------------------------------------------------Class Definition------------------------------------------------------------------------
class node{
public:
string el;
int p;
node(){};
node(string element, int priority){
el= element;
p = priority;
}
};
class heap{
protected:
int heapSize=0;
node *heapArr=NULL;
public:
heap(){
heapArr = new node[MAX_SIZE];
//buildHeap();
}
void inorder(int index = 0){
if(index >= heapSize)return;
inorder(left(index));
cout<<heapArr[index].el<<" ";
inorder(right(index));
return;
}
void heapSort(){
int originalSize = heapSize;
node temp;
for(int i = heapSize; i >0; i--){
temp = heapArr[i];
heapArr[i] = heapArr[0];
heapArr[0] = temp;
heapSize--;
heapify(0);
}
heapSize = originalSize;
for(int i = heapSize; i > 0; i--) cout<<heapArr[i].el<<" ";
}
string extTop(){
if(heapSize == 0){
cout<<"Queue empty >>";
return "NULL";
}
node output = heapArr[0];
heapArr[0] = heapArr[heapSize-1];
heapSize--;
heapify(0);
return output.el;
}
void insert(int x,string s){
if(heapSize + 1 >= MAX_SIZE){
cout<<"Heap is full";
return;
}
heapArr[heapSize].p = x;
heapArr[heapSize].el = s;
int index = heapSize;
while(index != 0){
int p;
if(index%2 == 0 )p = index/2 -1;
else p = index/2;
if(heapArr[p].p > heapArr[index].p){
node temp = heapArr[p];
heapArr[p] = heapArr[index];
heapArr[index] = temp;
}
index = p;
}
heapSize++;
}
private:
int left(int x){return (2*x + 1);}
int right(int x){return (2*x +2);}
void heapify(int x){
int smallest, l=left(x), r= right(x);
if(l <heapSize && heapArr[x].p > heapArr[l].p) smallest = l;
else smallest = x;
if(r <heapSize && heapArr[smallest].p > heapArr[r].p) smallest = r;
if(smallest != x){
node temp = heapArr[smallest];
heapArr[smallest] = heapArr [x];
heapArr[x] = temp;
heapify(smallest);
}
}
void buildHeap(){
for(int i = (heapSize-1)/2; i >= 0; i--)heapify(i);
}
};
int main(){
heap A;
while(1){
switch(command()){
case 'i':
A.insert(getElement(),getString());
break;
case 'x':
cout<<A.extTop();
break;
case 's':
A.heapSort();
return 0;
case 'd': //debugging
cout<<endl<<"\t";
A.inorder();
cout<<endl;
break;
case 'q':
return 0;
default:
cout<<"Please give a valid input..."<<endl;
break;
}
}
return 0;
}
<file_sep>/*Binomial heap with
insert
find Minimum
union
delete Minimum
*/
#include<iostream>
#include<cstdio>
using namespace std;
enum state: bool{open,close};
int getElement(){
int element;
cout<<endl<<"Enter an element(int): ";
cin>>element;
cout<<endl;
return element;
}
char command(){
char inp;
cout<<"\n-Press 'i' to insert an element\n-Press 'x' to delete the Minimum\n-Press 'm' to print the Minimum\n-Press 'd' to display the heap\n-Press 'q' to quit\n>>>> ";
cin>>inp;
return inp;
}
class node{
public:
node *child, *right, *parent;
int data, num;
node(int n){
data = n;
child, right, parent = NULL;
num = 0;
}
};
class binomialHeap{
public:
binomialHeap(){
root = NULL;
}
node *getRoot(){return root;}
node* findMin();
int delMin();
void insert(int);
int merge(node*,node*);
void display();
protected:
node *root;
void display(node *);
void replace(node *);
int level(node*)
};
int main(){
binomialHeap H;
while(1){
switch(command()){
case 'i':
H.insert(getElement());
break;
case 'x':
H.delMin();
break;
case 'm':
H.findMin();
break;
case 'd':
H.display();
break;
case 'q':
return 0;
case 'r': //debugging purposes only
//cout<<(H.getRoot())->data;
break;
default:
cout<<"Please give a valid input..."<<endl;
break;
}
}
return 0;
}
void binomialHeap::insert(int n){
node *newNode = new node(n);
newNode->right = root;
root = newNode;
if(root->right != NULL && root->right->num == 0){
cout<<"Merge karra";
merge(root, root->right);
}
}
int binomialHeap::merge(node *n1,node *n2){
if(n1->num != n2->num || n1->right != n2)return -1;
if(n1->data >= n2->data){
n1->right = n2->child;
n2->child = n1;
n1->parent = n2;
n2->num++;
if(n1 == root) root = n2;
} else {
n1->right = n2->right;
n2->right = n1->child;
n1->child = n2;
n1->num++;
}
if(n2 == root && root->right!=NULL)merge(root,root->right);
}
void binomialHeap::display(){
node *current = root;
while(current != NULL){
cout<<"Heap: \n";
display(current);
cout<<"End Heap\n";
current = current->right;
}
}
void binomialHeap::display(node* current){
cout<<current->data<<" ";
for(node *N = current->child; N != NULL; N = N->right){
display(N);
cout<<endl;
}
return;
}
int binomialHeap::delMin(){
node *target = findMin();
//node *place = root;
replace(target->child);
}
void binomialHeap::replace(node *target){
static node* place = NULL;
if(target == NULL)return;
replace(target->right);
target->parent = NULL;
if(place == NULL){
target->right = root;
root = target;
}
else {
target->right = place ->right;
place->right = target;
}
place = target;
if(level(place) == level(place->next))place = place->next;
}
node* binomialHeap::findMin(){
node *current = root,*result = root;
while(current != NULL){
if(result->data <= current->data)result = current;
current = current->right;
}
return result;
}
int binomialHeap::level(node *t){
int out = 0;
while(t != NULL){
out++;
t = t->child;
}
return out;
}
<file_sep>#include<iostream>
#include<cstdlib>
#include<climits>
#include<time.h>
#define MAX_LEVEL 6
using namespace std;
//--------------------------------------------------------------Class Definitions------------------------------------------------------------------------
class node{
public:
int data;
node *left;
node *right;
node *up;
node *down;
node(int x){
data = x;
up = left = right = down = NULL;
}
};
class skipList{
public:
node *header;
int level; //no of levels in current skipList
void insert(int);
void del(int);
node *search(int);
void display();
skipList() //constuctor creates an empty level
:level(0)
{
header = new node(INT_MIN); //analogous to -infinity
header->right = new node(INT_MAX); //analogous to +infinity
header->right->left = header;
}
protected:
node* inject(node*, node*);
node* findClosest(int, int = 0);
};
int getElement(){
int element;
cout<<endl<<"Enter an element(int): ";
cin>>element;
cout<<endl;
return element;
}
char command(){
char inp;
cout<<"\n-Press 'i' to insert an element\n-Press 'x' to delete an element\n-Press 's' to search for an element\n-Press 'd' to display the list\n-Press 'q' to quit\n>>>> ";
cin>>inp;
return inp;
}
//--------------------------------------------------------------Driver Program------------------------------------------------------------------------
int main(){
srand(time(NULL));
skipList list;
while(1){
switch(command()){
case 'i':
list.insert(getElement());
break;
case 'x':
list.del(getElement());
break;
case 's':
list.search(getElement());
break;
case 'd':
list.display();
cout<<endl;
break;
case 'q':
return 0;
case 'h': //debugging purposes only
cout<<list.header->data;
break;
default:
cout<<"Please give a valid input..."<<endl;
break;
}
}
return 0;
}
//----------------------------------------------------------function definitions-----------------------------------------------------
void skipList::insert(int key){
node *link;
node *ins = inject(new node(key),findClosest(key)); //inserts in the right position
if(ins == NULL)return;
int nextLevel = 1;
while(rand()%2){ //a random function to promote keys into the next level
if(nextLevel <= level){ //if current levels are not more than the limit
link = inject(new node(key),findClosest(key,nextLevel++));
link->down = ins;
ins->up = link;
ins = link;
} else if(level <= MAX_LEVEL){ //if a new level can be created
cout<<"Promoting";
node *h;
h = new node(INT_MIN); //creation of a new level
h->right = new node(INT_MAX);
header->up = h;
h->down = header;
header = h;
link = inject(new node(key),header); //inserting in the right place
link->down = ins;
ins->up = link;
ins = link;
nextLevel++;
level++;
}
}
}
node* skipList::inject(node *insert, node* place){ //this fuction injects into the skiplist and sets the left and right nodes accordingly
if(place->data == insert->data)return NULL;
insert->left = place;
insert->right = place->right;
place->right = insert;
insert->right->left = insert;
return insert;
}
node* skipList::search(int key){ //search function, works in O(logn) worst case time
node *current = header;
while(1){ //search from top level until bottom
while(current->right->right != NULL && current->right->data <= key){
current = current->right;
}
if(current->data == key){
cout<<"Data Found."<<endl;
return current;
}
else {
if(current->down != NULL){
current = current->down; //go down one level
} else {
cout<<"Data not found."<<endl;
return NULL;
}
}
}
}
node* skipList::findClosest(int key, int lowLevel){ //finds closest key less than input, and in the specified level
node *current = header;
int l = level;
while(l >= lowLevel){
while(current->right->right != NULL && current->right->data <= key){
current = current->right;
}
if(l == lowLevel)break;
else {
current = current->down;
l--;
}
}
return current;
}
void skipList::display(){ //traversal is from top level upto bottom
node* start = header;
if(header->right->right == NULL){
cout<<"List empty. Please insert some elements."<<endl;
return;
}
while(start != NULL){
node *current = start->right;
cout<<"-∞ --- ";
while(current->right != NULL){
cout<<current->data<<" --- ";
current=current->right;
}
cout<<"+∞"<<endl;
start = start->down;
}
}
void skipList::del(int key){ //deletion is from top level to bottom
node* next, *target = search(key);
while(target != NULL){
target->left->right = target->right;
target->right->left = target->left;
next = target->down;
delete target;
target = next;
}
while(header->right->right == NULL){ //if a level becomes empty
if(header->down == NULL)return;
next = header->down;
delete header->right; //level is removed
delete header;
header = next;
level--; //no of levels decremented
}
}
<file_sep>//redBlackTree with insert, search, delete
//amazing test case i 8 i 10 i 9 i 12 i 11 i 13 i 14 i 15 i 16 i 17 i 4 i 6 i 5 i 7 i 3 i 2 i 1
//followed by x
#include<iostream>
using namespace std;
enum colors: bool{red, black};
struct node{
int data;
colors color;
struct node *left, *right, *parent;
};
int getElement(){
int element;
cout<<endl<<"Enter an element(int): ";
cin>>element;
cout<<endl;
return element;
}
char command(){
char inp;
cout<<"\n-Press 'i' to insert an element\n-Press 'x' to delete an element\n-Press 's' to search for an element\n-Press 'd' to display the tree inorder\n-Press 'q' to quit\n>>>> ";
cin>>inp;
return inp;
}
//--------------------------------------------------------------Class Definition------------------------------------------------------------------------
class redBlackTree{
public:
struct node *sentinel;
redBlackTree(){
sentinel = new struct node;
sentinel->color = black;
sentinel->left = NULL;
sentinel->right = NULL;
root = sentinel;
}
void insert(int);
void search(int key){
struct node* result = search(root,key);
if(result==sentinel)cout<<"\tElement not found"<<endl;
else cout<<"\tElement found at: "<<result<<endl;
}
void del(int key){
struct node* target = search(root,key);
if(target == sentinel){
cout<<"\tNo such element in Tree"<<endl;
return;
}
else {
del(target);
cout<<"\tElement deleted successfully."<<endl;
}
}
void inorder(struct node*);
void preorder(struct node*);
void postorder(struct node*);
struct node *getRoot(){
return root;
}
protected:
struct node *root;
struct node* search(struct node*,int);
int del(struct node *);
void insertFix(struct node*);
void deleteFix(struct node*);
struct node* fill(int y){
struct node *newNode = new struct node;
newNode->data = y;
newNode->left = sentinel;
newNode->right = sentinel;
newNode->parent = sentinel;
newNode->color = red;
return newNode;
}
struct node* min(struct node* x){
while(x->left != sentinel){
x = x->left;
}
return x;
}
void transplant(struct node* x, struct node *y){
if (x->parent == sentinel)root = y;
else if (x == x->parent->left) x->parent->left = y;
else x->parent->right = y;
y->parent = x->parent;
}
void rotate(struct node* target, char direction){
struct node* y;
if(direction == 'l'){
y = target->right;
target->right = y->left;
if(y->left != sentinel)
y->left->parent = target;
y->parent = target->parent;
if(target->parent == sentinel)
root = y;
else {
if(target == target->parent->left)
target->parent->left = y;
else target->parent->right = y;
}
y->left = target;
target->parent = y;
} else if(direction == 'r'){
y = target->left;
target->left = y->right;
if(y->right != sentinel)
y->right->parent = target;
y->parent = target->parent;
if(target->parent == sentinel)
root = y;
else {
if(target == target->parent->right)
target->parent->right = y;
else target->parent->left = y;
}
y->right = target;
target->parent = y;
}
return;
}
};
//-----------------------------------------------------------------------main---------------------------------------------------------------------------
int main(){
redBlackTree tree;
while(1){
switch(command()){
case 'i':
tree.insert(getElement());
break;
case 'x':
tree.del(getElement());
break;
case 's':
tree.search(getElement());
break;
case 'd':
cout<<endl<<"\tInorder"<<endl<<"\t";
tree.inorder(tree.getRoot());
cout<<endl<<"\tPreorder"<<endl<<"\t";
tree.preorder(tree.getRoot());
cout<<endl;
break;
case 'q':
return 0;
case 'r': //debugging purposes only
cout<<(tree.getRoot())->data;
break;
default:
cout<<"Please give a valid input..."<<endl;
break;
}
}
return 0;
}
//----------------------------------------------------------function definitions-----------------------------------------------------
void redBlackTree::insert(int x){
struct node *current = root; struct node *previous = sentinel;
while (current != sentinel) {
previous = current;
if( x < current->data )current = current->left;
else current = current->right;
}
struct node *newNode = fill(x);
newNode->parent = previous;
if(previous == sentinel ){
root = newNode;
}
else if (newNode->data < previous->data) previous->left = newNode;
else previous->right = newNode;
insertFix(newNode);
}
void redBlackTree::insertFix(struct node* target){
while(target->parent->color == red){
if(target->parent == target->parent->parent->left){ //if parent is a left child
struct node *uncle = target->parent->parent->right; //store the uncle
if(uncle->color == red){ //CASE 1 - red uncle
target->parent->color = black;
uncle->color = black;
target->parent->parent->color = red;
target = target->parent->parent;
}
else {
if( target == target->parent->right){ //CASE 2 - uncle black and target is a right child
target = target->parent;
rotate(target,'l'); //this makes target a left child
}
target->parent->color = black; //CASE 3 - uncle black and left child
target->parent->parent->color = red;
rotate(target->parent->parent,'r');
}
} else {
struct node *uncle = target->parent->parent->left; //exactly the mirror image of the upper block of code
if(uncle->color == red){
target->parent->color = black;
uncle->color = black;
target->parent->parent->color = red;
target = target->parent->parent;
}
else {
if( target == target->parent->left){
target = target->parent;
rotate(target,'r');
}
target->parent->color = black;
target->parent->parent->color = red;
rotate(target->parent->parent,'l');
}
}
}
root->color = black;
}
int redBlackTree::del (struct node* target){
struct node* o = target;
struct node* child;
bool originalColor = o->color;
if( target->left == sentinel){
child = target->right;
transplant(target, child);
} else if(target->right == sentinel){
child = target->left;
transplant(target, child);
} else {
o = min(target->right);
originalColor = o->color;
child = o->right;
if(o->parent == target && child != sentinel) child->parent = o;
else {
transplant(o, o->right);
o->right = target->right;
o->right->parent = o;
}
transplant(target,o);
o->left = target->left;
o->left->parent = o;
o->color = target->color;
}
if(originalColor == black) deleteFix(child);
}
void redBlackTree::deleteFix(struct node* target){
while(target != root && target->color == black){
if(target == target->parent->left){
struct node* w = target->parent->right;
if(w->color == red){
w->color = black; //CASE1
target->parent->color = red;
rotate(target->parent, 'l');
w = target->parent->right;
}
if(w->left->color == black && w->right->color == black){
w->color = red; //CASE 2
target = target->parent;
} else {
if(w->right->color == black){
w->left->color = black; //CASE 3
w->color = red;
rotate(w,'r');
w = target->parent->right;
}
w->color = target->parent->color; //CASE 4
target->parent->color = black;
w->right->color = black;
rotate(target->parent,'l');
target = root;
}
} else {
struct node* w = target->parent->left;
if(w->color == red){
w->color = black; //CASE1
target->parent->color = red;
rotate(target->parent, 'r');
w = target->parent->left;
}
if(w->right->color == black && w->left->color == black){
w->color = red; //CASE 2
target = target->parent;
} else {
if(w->left->color == black){
w->left->color = black; //CASE 3
w->color = red;
rotate(w,'l');
w = target->parent->left;
}
w->color = target->parent->color; //CASE 4
target->parent->color = black;
w->left->color = black;
rotate(target->parent,'l');
target = root;
}
}
}
target->color = black;
}
struct node* redBlackTree::search(struct node *current,int x){ //recursively searches using the increasing order property
if(current == sentinel)return sentinel; //same as a regular BST
if(current->data==x)return current;
if(x>current->data && current->right!=sentinel){
return search(current->right,x);
}
else if(current->left!=sentinel){
return search(current->left,x);
}else{
return sentinel;
}
}
//------------traversal methods below-----------
void redBlackTree::inorder (struct node *current){
if(current!=sentinel){
inorder(current->left);
cout<<current->data<<":"<<(current->color?"b":"r")<<" ";
inorder(current->right);
}
return;
}
void redBlackTree::preorder (struct node *current){
if(current!=sentinel){
cout<<current->data<<":"<<(current->color?"b":"r")<<" ";
preorder(current->left);
preorder(current->right);
}
return;
}
void redBlackTree::postorder (struct node *current){
if(current!=sentinel){
postorder(current->left);
postorder(current->right);
cout<<current->data<<" ";
}
return;
}
<file_sep>#include<iostream>
#include<cstdio>
#define ORDER 5 //max degree
using namespace std;
int t = ORDER;
int getElement(){
int element;
cout<<endl<<"Enter an element(int): ";
cin>>element;
cout<<endl;
return element;
}
char command(){
char inp;
cout<<"\n-Press 'i' to insert an element into BTree\n-Press 'x' delete an element\n-Press 's' to search an element in BTree\n-Press 'd' to display the BTree\n-Press 'q' to quit\n>>>> ";
cin>>inp;
return inp;
}
//--------------------------------------------------------------Class Definition------------------------------------------------------------------------
class node{
public:
int *keys; //keys
node **C; //child pointers
int n; //number of keys in node
bool leaf; //is leaf?
node(bool leaf){
this->leaf = leaf;
keys = new int[t-1];
C = new node *[t];
n = 0;
}
};
class BTree{
protected:
node *root; // Pointer to root node
void split(node*,int);
void insertHere(node*, int);
void del(node*, int);
node *parent(node*);
void fix(node*);
void merge(node*, int);
public:
BTree(){
root = new node(true);
root->n = 0;
}
node* getRoot(){
return root;
}
void display(node*);
void display2(node*);
node* search(node*, int);
void insert(int);
void del(int);
};
//-----------------------------------------------------------------------main---------------------------------------------------------------------------
int main(){
BTree tree;
node* result;
while(1){
switch(command()){
case 'i':
tree.insert(getElement());
break;
case 'x':
tree.del(getElement());
break;
case 's':
result = tree.search(tree.getRoot(),getElement());
if(result)cout<<"\tData found in the node at addr:"<<result<<endl;
else cout<<"\tNot found"<<endl;
break;
case 'd':
cout<<endl<<"\t";
tree.display(tree.getRoot());
cout<<endl;
break;
case 'z':
tree.display2(tree.getRoot());
cout<<endl;
break;
case 'q':
return 0;
default:
cout<<"Please give a valid input..."<<endl;
break;
}
}
return 0;
}
//----------------------------------------------------------function definitions-----------------------------------------------------
void BTree::display(node *x){ //traverses this and all children
int i;
for (i = 0; i < x->n; i++){ //inorder recursive traversal
if (x->leaf == false)
display(x->C[i]);
cout << " " << x->keys[i];
}
if (x->leaf == false) //last case that isn't included in the loop
display(x->C[i]);
}
void BTree::display2(node *x){ //traverses this and all children
int i;
cout<<"\t";
node* par = parent(x);
if(par == NULL)
cout<<"Root\t";
else
cout<<"Par: "<<par->keys[0]<<" Keys: ";
for (i = 0; i < x->n; i++){ //inorder recursive traversal
cout<<x->keys[i] << " " ;
}
cout<<endl;
for (i = 0; i <= x->n; i++){ //inorder recursive traversal
if (x->leaf == false){
cout<<"\t"<<"#:"<<i+1;
display2(x->C[i]);
}
}
}
node* BTree::search(node* target,int k){ //searches for key in the specified node (or subtree)
int i = 0;
while (i < target->n && k > target->keys[i]) //find key comparable to k in node
i++;
if (i< target->n && target->keys[i] == k)
return target; //found key is equal to k? return itself
else if (target->leaf == true)
return NULL; //leaf means that k doesn't exist in subtree
else
return search(target->C[i],k); //search for k in ith subtree
}
void BTree::insert(int k){
node* r = root;
insertHere(r,k);
if (root->n == t){
node *s = new node(false);
s->C[0] = root;
root = s;
split(root,0); //split the old root and move 1 key to the new root
} //if root is not full, call insertHere for root
}
// A utility function to insert a new key in this node
// The assumption is, the node must be non-full when this
// function is called
void BTree::insertHere(node* x, int k){
int i = x->n - 1; //index of rightmost element
if (x->leaf == true){
while (i >= 0 && x->keys[i] > k){
x->keys[i+1] = x->keys[i]; //shifts all keys one ahead
i--;
} //this i is the new insert postion
x->keys[i+1] = k; //Insert the new key at found location
x->n = x->n + 1;
}
else {
while (i >= 0 && x->keys[i] > k)
i--; //this i is the new insert postion
insertHere(x->C[i+1],k);
if (x->C[i+1]->n == t){ //child is full? then split it
split(x,i+1);
}
}
}
// A utility function to split the child y of this node
// Note that y must be full when this function is called
void BTree::split(node *x, int i){
node* y = x->C[i]; //y will be split
if(y->n != t){
cout<<"Fault";
return;
}
node *z = new node(y->leaf);
z->n = t/2;
for (int j = 0; j < t/2; j++) // Copy the last t/2 keys of y to z
z->keys[j] = y->keys[j + 1 + t/2];
if (y->leaf == false){ // Copy the last t/2+1 children of y to z
for (int j = 0; j <= t/2; j++)
z->C[j] = y->C[j + t/2 + 1];
}
y->n = t/2; // Reduce the number of keys in y
for (int j = x->n; j >= i+1; j--) //make space for a new child
x->C[j+1] = x->C[j];
x->C[i+1] = z; // Link the new child to this node
for (int j = x->n-1; j >= i; j--) //make space for a new key
x->keys[j+1] = x->keys[j];
x->keys[i] = y->keys[t/2]; // Copy the middle key of y to this node
x->n = x->n + 1; // Increment count of keys in this node
}
void BTree::del(int key){
node* target = search(root,key); //address of node to delete
if(target == NULL){
cout<<"Element not in B-Tree."<<endl;
return;
}
else {
int position = 0;
for(int i = 0; i < target->n; i++){
if(target->keys[i] == key){
position = i; //index of key to be deleted
break;
}
}
del(target, position);
}
}
void BTree::del(node* target, int pos){ //actually performs deletion recursively
if(target->leaf == true){
for(int j = pos; j < target->n - 1 ; j++){
target->keys[j] = target->keys[j+1]; //simple removal and shift of subsequent keys
}
target->n = target->n - 1;
if(target != root && target->n < t/2)fix(target);
}
else { //non leaf target
target->keys[pos] = target->C[pos + 1]->keys[0];
del(target->C[pos + 1],0);
}
}
void BTree::fix(node* target){
node *p = parent(target);
int posT; //child's index in parent
for(int i=0; i <= p->n; i++) //finding the position of child in parent
if(p->C[i]==target){
posT = i;
break;
}
if(posT < p->n){ //target has a right sibling
node* rightSib = p->C[posT + 1]; //right sibling of target
if(rightSib->n > t/2){ //right sibling has enough keys
target->keys[target->n] = p->keys[p->n -1]; //right rotation of keys via parent
p->keys[p->n -1] = rightSib->keys[0];
target->n ++;
for(int j = 0; j < rightSib->n -1; j++){ //left shift of keys in rightSib
rightSib->keys[j] = rightSib->keys[j+1];
}
rightSib->n--;
return;
}
}
if(posT > 0){ //target has a left sibling
node* leftSib = p->C[posT - 1]; //left sibling of target
if(leftSib->n > t/2){ //left sibling has enough keys
for(int j = 0; j < target->n; j++){ //right shift of keys in left sibling
target->keys[j+1] = target->keys[j];
}
target->n ++;
target->keys[0] = p->keys[posT - 1];
p->keys[posT -1] = leftSib->keys[leftSib->n - 1];
leftSib->n--;
return;
}
}
//if program reaches here, it means neither left sibling nor right sibling have enough keys. We must merge
merge(p,posT);
}
void BTree::merge(node* p, int posT){
node* left, *right;
int position;
if(posT > 0){ //left sibling exists
position = posT -1;
left = p->C[posT - 1];
right = p->C[posT];
} else { //right sibling exists
position = posT;
left = p->C[posT];
right = p->C[posT + 1];
}
left->keys[left->n] = p->keys[position]; //demote parent key to leaf
for(int i=position; i< p->n -1; i++){ //shift parent data left
p->keys[i] = p->keys[i+1]; //shift parent keys
p->C[i+1] = p->C[i+2]; //shift parent data
}
p->n --;
for(int i = 0; i < right->n; i++){
left->keys[left->n + 1 + i] = right->keys[i];
}
left-> n = left->n + right->n + 1;
delete right;
if(p == root){
if(p->n == 0){
delete root;
root = left;
}
return;
}
else if(p->n < t/2){
node *_p = parent(p);
int _posT; //child's index in parent
for(int i=0; i <= p->n; i++) //finding the position of child in parent
if(_p->C[i]==p){
_posT = i;
break;
}
merge(_p,_posT);
}
}
node* BTree::parent(node* target){
if(target == root)return NULL;
node* current = root;
node* previous = current;
int k = target->keys[0];
while(1){
int i = 0;
while (i < current->n && k > current->keys[i]) //find key comparable to k in node
i++;
previous = current;
current = current->C[i];
if(current == target)
return previous;
}
}
<file_sep>/*Binomial heap with
insert
find Minimum
union
delete Minimum
*/
#include<iostream>
#include<cstdio>
using namespace std;
enum state: bool{open,close};
int getElement(){
int element;
cout<<endl<<"Enter an element(int): ";
cin>>element;
cout<<endl;
return element;
}
char command(){
char inp;
cout<<"\n-Press 'i' to insert an element\n-Press 'x' to delete the Minimum\n-Press 'm' to print the Minimum\n-Press 'd' to display the heap\n-Press 'q' to quit\n>>>> ";
cin>>inp;
return inp;
}
//--------------------------------------------------------------Class Definitions-----------------------------------------------------------------------
class node{
public:
node *child, *right, *parent;
int data;
node(int n){
data = n;
child = NULL;
right= NULL;
parent = NULL;
}
};
class binomialHeap{
public:
binomialHeap(){ //initialiser empty heap
root = NULL;
}
node *getRoot(){return root;}
node* findMin();
int delMin();
void insert(int);
int merge(node*,node*);
void display();
protected:
static node *root;
void replace(node *);
int level(node*);
};
//--------------------------------------------------------------Driver Program------------------------------------------------------------------------
int main(){
binomialHeap H;
node *result;
while(1){
switch(command()){
case 'i':
H.insert(getElement());
break;
case 'x':
H.delMin();
break;
case 'm':
result = H.findMin();
if(result)cout<<"Minimum is: "<<result->data<<endl;
else cout<<"Heap is empty."<<endl;
break;
case 'd':
H.display();
break;
case 'q':
return 0;
case 'r': //debugging purposes only
cout<<(H.getRoot())->data;
break;
default:
cout<<"Please give a valid input..."<<endl;
break;
}
}
return 0;
}
node* binomialHeap::root;
//--------------------------------------------------------------function Definitions-----------------------------------------------------------------------
void binomialHeap::insert(int n){ //inserts an element
node *newNode = new node(n);
newNode->right = root;
root = newNode;
if(root->right != NULL && level(root->right) == 1){
merge(root, root->right); //merges sizes 1 and 1 only
}
}
int binomialHeap::merge(node *n1 = root, node *n2 = root->right){ //merges any two equal sizes
if(level(n1) != level(n2) || n1->right != n2)return -1;
if(n1->data >= n2->data){ //n2 must end up as the parent
n1->right = n2->child;
n2->child = n1;
n1->parent = n2;
if(n1 == root) root = n2;
if(n2->right!=NULL)merge(n2,n2->right);
} else { //n1 must end up as the parent
n1->right = n2->right;
n2->right = n1->child;
n1->child = n2;
if(n1->right!=NULL)merge(n1,n1->right);
}
return 0;
}
void binomialHeap::display(){ //subheap by subheap traversal and display
node *current = root;
if(root == NULL){
cout<<"Heap is empty, please insert some elements.";
return;
}
while(current != NULL){
cout<<" "<<current->data<<"("<<level(current)<<")";
current = current->right;
}
return;
}
int binomialHeap::delMin(){ //deletes smallest from heap
node *target = findMin(), *current = NULL, *previous = NULL;
if(target != NULL){
replace(target->child);
target->child = NULL;
//display(); //debugging
cout<<endl;
//cout<<"Root: "<<root->data<<endl; //debugging purposes only
if(root != NULL){
current = root;
while(current->data != target->data){
previous = current;
current = current->right;
}
if(previous==NULL){
if(root->right != NULL)
root = root->right;
} else
previous->right = target->right;
delete target;
if(target == root){
root = NULL;
}
else {
current = root;
while(current->right != NULL){
if(merge(current,current->right) == 0)current = root;
else current = current->right;
}
}
}
}
display();
return 0;
}
void binomialHeap::replace(node *target){ //recusrively replaces to fix binomialHeap properties
static node* place = NULL;
if(target == NULL){
place = NULL;
return;
}
replace(target->right);
target->parent = NULL;
if(place == NULL){
target->right = root;
root = target;
place = target;
return;
} else {
target->right = place->right;
place->right = target;
place = target;
}
//cout<<"This is a pass and the current place pointer is at: "<<place->data<<" and the root is: "<<root->data<<endl; //debugging purposes only
while(level(place) >= level(place->right))place = place->right;
}
node* binomialHeap::findMin(){ //returns address of the smallest heap key
node *current = root,*result = root;
while(current != NULL){
if(current->data <= result->data)result = current;
current = current->right;
}
return result;
}
int binomialHeap::level(node *t){ //gives level of subheap
int out = 0;
while(t != NULL){
out++;
t = t->child;
}
return out;
}
<file_sep>#include<iostream>
using namespace std;
struct node{
int data;
struct node *left;
struct node *right;
};
int getElement(){
int element;
cout<<endl<<"Enter an element(int): ";
cin>>element;
cout<<endl;
return element;
}
char command(){
char inp;
cout<<"\n-Press 'i' to insert an element\n-Press 'x' to delete an element\n-Press 's' to search for an element\n-Press 'd' to display the tree inorder\n-Press 'q' to quit\n>>>> ";
cin>>inp;
return inp;
}
//--------------------------------------------------------------Class Definition------------------------------------------------------------------------
class binarySearchTree{
public:
binarySearchTree(){
root=NULL;
}
void insert(int);
void search(int key){ //overloaded definitions for easy code
struct node* result = search(root,key);
if(result==NULL)cout<<"\tElement not found"<<endl;
else cout<<"\tElement found at: "<<result<<endl;
}
void del(int key){ //overloaded definitions for easy code
int result = del(search(root,key));
if(result)cout<<"\tElement deleted successfully."<<endl;
else cout<<"\tNo such element in BST"<<endl;
}
void inorder(){
if( root == NULL){
cout<<"Tree is empty. Please insert elements."<<endl;
}
else inorder(root);
}
struct node *getRoot(){ //resturns the root of BST
return root;
}
protected:
struct node *root;
struct node* search(struct node*,int);
int del(struct node *);
void inorder(struct node*);
struct node* parent(struct node* child, struct node* subtree){ // a function to give parent of specified node
if (child == root || child == NULL || subtree == NULL) return NULL;
if(subtree->left == child || subtree->right == child)return subtree;
else {
if(child->data < subtree-> data)return parent(child, subtree->left);
else return parent(child, subtree->right);
}
}
struct node* parent(struct node* child){
return parent(child,root);
}
void fill(struct node* n,int y){
n->data = y;
n->left = NULL;
n->right = NULL;
return;
}
};
//-----------------------------------------------------------------------main---------------------------------------------------------------------------
int main(){
binarySearchTree tree;
while(1){
switch(command()){
case 'i':
tree.insert(getElement());
break;
case 'x':
tree.del(getElement());
break;
case 's':
tree.search(getElement());
break;
case 'd':
cout<<endl<<"\t";
tree.inorder();
cout<<endl;
break;
case 'q':
return 0;
case 'r': //debugging purposes only
cout<<(tree.getRoot())->data;
break;
default:
cout<<"Please give a valid input..."<<endl;
break;
}
}
return 0;
}
//----------------------------------------------------------function definitions-----------------------------------------------------
void binarySearchTree::insert(int x){
struct node *current = root;
if(current==NULL){
struct node *newNode=new struct node;
fill(newNode,x);
root=newNode; //gets address of prefilled node and stores it as root
return;
}
while(1){
if(current->data==x)return;
if(x>current->data){ //searching the place to store the new node
if(current->right==NULL){
struct node *newNode = new struct node;
current->right = newNode;
fill(newNode,x);
return;
} else {
current = current->right;
}
}
else{
if(current->left==NULL){
struct node *newNode = new struct node;
current->left = newNode;
fill(newNode,x);
return;
} else {
current = current->left;
}
}
}
}
void binarySearchTree::inorder (struct node *current){ //display and traversal
if(current!=NULL){
inorder(current->left); //recursive definition
cout<<current->data<<" ";
inorder(current->right);
}
return;
}
int binarySearchTree::del (struct node* target){
if(target == NULL)return 0;
struct node *par;
if(target->left==NULL && target->right==NULL){ //target has no children
if(target == root
delete target;
root = NULL;
return 1;
}
par=parent(target);
if(par->left == target)par->left = NULL; //parent's pointers must be set
else par-> right = NULL;
delete target; //deleting the target
return 1; //return success
}
par = NULL; //par will finally hold the target's parent
if(target->left != NULL){
struct node *delT = target->left;
while (delT->right != NULL){
par = delT;
delT = delT->right;
}
target->data = delT->data;
if(par != NULL)par->right = delT->left;
else target->left = NULL;
delete delT;
} else {
struct node *delT = target->right;
while (delT->left != NULL){
par = delT;
delT = delT->left;
}
target->data = delT->data;
if(par != NULL)par->left = delT->right;
else target->right = NULL;
delete delT;
}
return 1;
}
struct node* binarySearchTree::search(struct node *current,int x){ //to search the tree for an element
if(current == NULL)return NULL;
if(current->data==x)return current;
if(x>current->data && current->right!=NULL){
return search(current->right,x); //recusrive definition
}
else if(current->left!=NULL){
return search(current->left,x);
}else{
return NULL;
}
}
<file_sep>#include<iostream>
using namespace std;
void bubbleSort (int *arr, int n){
for (int i = 0; i < n; ++i){
for (int j = 0; j < n - i - 1; ++j){
if (arr[j] > arr[j + 1]){
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return;
}
int main(){
int n;
cout<<"Enter number of elements: ";
cin>>n;
int a[n];
cout<<"Enter the "<<n<<" values: ";
int i;
for(i=0;i<n;i++){
cin>>a[i];
}
bubbleSort(a,n);
cout<<"The sorted array is:";
for(i=0;i<n;i++){
cout<<a[i]<<" ";
}
return 0;
}
<file_sep>#include<iostream>
using namespace std;
void insertionSort (int *arr, int n){
int j, temp;
for (int i = 0; i < n; i++){
j = i;
while (j > 0 && arr[j] < arr[j-1]){
temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
j--;
}
}
return;
}
int main(){
int n;
cout<<"Enter number of elements: ";
cin>>n;
int a[n];
cout<<"Enter the "<<n<<" values: ";
int i;
for(i=0;i<n;i++){
cin>>a[i];
}
insertionSort(a,n);
cout<<"The sorted array is:";
for(i=0;i<n;i++){
cout<<a[i]<<" ";
}
return 0;
}
<file_sep>#include<iostream>
#include<string>
#include<sstream>
#include<climits>
using namespace std;
#define MAX_SIZE 200
//--------------------------------------------------------------Class Definition------------------------------------------------------------------------
class edge{ //a data type to store edges
public:
edge *next; //for the implementation of an adjacency list
int vertex1,vertex2,weight; //3 properties of any edge
edge(){} //default constructor
edge(int v1,int v2, int w){ //initialiser constructor
vertex1 = v1;
vertex2 = v2;
weight = w;
}
};
//-------------------------------------------------------------Priority Queue-----------------------------------------------------
class heap{
protected:
edge *heapArr=NULL;
public:
int heapSize=0;
heap(){
heapSize = 0;
heapArr = new edge[MAX_SIZE];
}
edge extTop(){
edge output = heapArr[0];
heapArr[0] = heapArr[heapSize-1];
heapSize--;
heapify(0);
return output;
}
void insert(edge x){
if(heapSize + 1 >= MAX_SIZE){
cout<<"Heap is full";
return;
}
heapArr[heapSize] = x;
int index = heapSize;
while(index != 0){
int p;
if(index%2 == 0 )p = index/2 -1;
else p = index/2;
if(heapArr[p].weight > heapArr[index].weight){
edge temp = heapArr[p];
heapArr[p] = heapArr[index];
heapArr[index] = temp;
}
index = p;
}
heapSize++;
}
private:
int left(int x){return (2*x + 1);}
int right(int x){return (2*x +2);}
void heapify(int x){
int smallest, l=left(x), r= right(x);
if(l <heapSize && heapArr[x].weight > heapArr[l].weight) smallest = l;
else smallest = x;
if(r <heapSize && heapArr[smallest].weight > heapArr[r].weight) smallest = r;
if(smallest != x){
edge temp = heapArr[smallest];
heapArr[smallest] = heapArr [x];
heapArr[x] = temp;
heapify(smallest);
}
}
void buildHeap(){
for(int i = (heapSize-1)/2; i >= 0; i--)heapify(i);
}
};
//---------------------------------------------------------------Graph-----------------------------------------------------------------------------
class graph{ //graph class
protected:
int nVertices;
edge **startPt; //pointer to the first pointer of adjacency list
int nEdges; //number of edges
public:
graph(){ //default initialiser
nVertices = 0;
startPt = NULL;
nEdges = 0;
}
int buildList(){ //this function takes adjacency list input from the user
cout<<endl<<"\tInstructions: \n\tFor each node in the graph, enter a space separated list of adjacent vertices and their weights.\n\tFor every vertex in the adjacency list, enter the respective weight with a ':' character.\n\tWhen a list is complete, press 'enter' for the next node\n\n\tNote:\n\tProgram will only consider valid inputs, e.g. if a total of 10 nodes exist, vertices >= 10 will not be considered\n\n\tSyntax\t\tNode [number]: [vertex]:[weight]\n\tExample\t\tNode 5: 1:2 3:8 7:1 8:2 12:3\n"<<endl; //input specifications. These are the instructions for the user to input adjacency list
cout<<"\nEnter the number of nodes in the graph: ";
cin>>nVertices;
edge** adList = new edge*[nVertices]; //creates an array to store starting addresses for each vertex's likned list
startPt = adList; //beginning of the adjacency list stored in the startPt pointer
for(int i=0;i<nVertices-1;i++){ //for each vertex in the graph
string line;
cout<<"Enter the adjacency list for node "<<i<<" :";
if(cin.peek() =='\n')cin.ignore(100,'\n'); //to check for termination of list according to input format (specified above)
getline(cin, line,'\n'); //extract line from buffer and place in string line
istringstream streamline(line); //this creates a istringstream object from a string. it is easy to perform operations on this object
int vertex,weight;
char temp; //required to validate user input
edge **current = adList+i; //**previous = NULL; //the edge to-be-filled with data
adList[i] = NULL;
while((streamline >> vertex >> temp >> weight) && temp == ':'){ //input validated and stored in respective variables
if(vertex > i && vertex < nVertices){ //this is to make sure no edge gets repeated
*current = new edge(i,vertex,weight); //new edge onject is created
nEdges++; //simultaneously counts the number of edges (which we haven't taken as input, for conveniece)
//*previous = *current;
current = &((*current)->next); //the next element should go into the next field of the current edge. We store is address in current
}
}
*current = NULL; //the last edge must point to NULL to signal the end of the edge linked list
//(*previous)->next = NULL
}
cout<<"Total of "<<nEdges<<" edges were input."<<endl;
return nVertices;
}
void showList(){ //outputs the adjacency list
edge* current;
for(int i=0;i<nVertices-1;i++){
cout<<"Node: "<<i<<endl;
for (current = startPt[i]; current != NULL; current=current->next){
cout<<"\t\tVertices: "<<current->vertex1<<" "<<current->vertex2<<" and its weight is: "<<current->weight<<endl;
}
}
return;
}
void caclMST(){ //calculation of MST using prim's algirithm
int mstEdges[nVertices];
bool inMST[nVertices];
heap priorityQueue;
int key[nVertices]; // Key values used to pick minimum weight edge in cut
// Initialize all keys as INFINITE
for (int i = 0; i < nVertices; i++){
key[i] = INT_MAX;
inMST[i] = false;
}
//-------------------------------------------------------PRIM'S ALGORITHM BEGINS--------------------------------------------------------
//run once to create a non-empty queue
inMST[0] = true; // Include vertex in MST
// 'i' is used to get all adjacent vertices of a vertex
for (edge* i = startPt[0]; i!= NULL; i = i->next){
// Get vertex label and weight of current adjacent
// of u.
int v = i->vertex2;
int weight = i->weight;
// If v is not in MST and weight of (u,v) is smaller
// than current key of v
if (inMST[v] == false && key[v] > weight){
// Updating key of v
key[v] = weight;
priorityQueue.insert(*i);
mstEdges[v] = 0;
}
}
while (priorityQueue.heapSize > 0){
int u = priorityQueue.extTop().vertex2;
inMST[u] = true; // Include vertex in MST
// 'i' is used to get all adjacent vertices of a vertex
for (edge* i = startPt[u]; i!= NULL; i = i->next){
// Get vertex label and weight of current adjacent
// of u.
int v = i->vertex2;
int weight = i->weight;
// If v is not in MST and weight of (u,v) is smaller
// than current key of v
if (inMST[v] == false && key[v] > weight){
// Updating key of v
key[v] = weight;
priorityQueue.insert(*i);
mstEdges[v] = u;
}
}
}
for(int k = 1; k< nVertices; k++)cout<<"Edge: "<<mstEdges[k]<<"-"<<k<<endl; //display the result
}
};
//------------------------------------------------Driver Program--------------------------------------------------------------------------
int main(){
graph A;
int number = A.buildList();
A.showList();
A.caclMST();
return 0;
}
<file_sep>#include<iostream>
#include<cstdio>
#define ORDER 5 //max degree
using namespace std;
int t = ORDER;
int getElement(){
int element;
cout<<endl<<"Enter an element(int): ";
cin>>element;
cout<<endl;
return element;
}
char command(){
char inp;
cout<<"\n-Press 'i' to insert an element into BTree\n-Press 'x' delete an element\n-Press 's' to search an element in BTree\n-Press 'd' to display the BTree\n-Press 'q' to quit\n>>>> ";
cin>>inp;
return inp;
}
//--------------------------------------------------------------Class Definition------------------------------------------------------------------------
class node{
public:
int *keys; //keys
node **C; //child pointers
int n; //number of keys in node
bool leaf; //is leaf?
node(bool leaf){
this->leaf = leaf;
keys = new int[t-1];
C = new node *[t];
n = 0;
}
};
class BTree{
protected:
node *root; // Pointer to root node
void splitChild(node*, int);
void insertNonFull(node*, int);
public:
BTree(){
root = new node(true);
root->n = 0;
}
node* getRoot(){
return root;
}
void display(node*);
void display2(node*);
node* search(node*, int);
void insert(int);
};
//-----------------------------------------------------------------------main---------------------------------------------------------------------------
int main(){
BTree tree;
while(1){
switch(command()){
case 'i':
tree.insert(getElement());
break;
case 'x':
// tree.del(getElement());
break;
case 's':
tree.search(tree.getRoot(),getElement());
break;
case 'd':
cout<<endl<<"\t";
tree.display(tree.getRoot());
cout<<endl;
break;
case 'z':
tree.display2(tree.getRoot());
cout<<endl;
break;
case 'q':
return 0;
default:
cout<<"Please give a valid input..."<<endl;
break;
}
}
return 0;
}
//----------------------------------------------------------function definitions-----------------------------------------------------
void BTree::display(node *x){ //traverses this and all children
int i;
for (i = 0; i < x->n; i++){ //inorder recursive traversal
if (x->leaf == false)
display(x->C[i]);
cout << " " << x->keys[i];
}
if (x->leaf == false) //last case that isn't included in the loop
display(x->C[i]);
}
void BTree::display2(node *x){ //traverses this and all children
int i;
cout<<"\t"<<x->n<<"\t";
for (i = 0; i < x->n; i++){ //inorder recursive traversal
cout << " " << x->keys[i];
}
cout<<endl;
for (i = 0; i <= x->n; i++){ //inorder recursive traversal
if (x->leaf == false)
display2(x->C[i]);
}
}
node* BTree::search(node* target,int k){ //searches for key in specified node (subtree)
int i = 0;
while (i < target->n && k > target->keys[i]) //find key comparable to k in node
i++;
if (i< target->n && target->keys[i] == k)
return target; //found key is equal to k? return itself
else if (target->leaf == true)
return NULL; //leaf means that k doesn't exist in subtree
else
return search(target->C[i],k); //search for k in ith subtree
}
void BTree::insert(int k){
node* r = root;
if (root->n == t-1){
node *s = new node(false);
s->C[0] = root;
root = s;
splitChild(s,0); //split the old root and move 1 key to the new root
insertNonFull(s,k);
} else { //if root is not full, call insertNonFull for root
insertNonFull(r,k);
}
}
// A utility function to insert a new key in this node
// The assumption is, the node must be non-full when this
// function is called
void BTree::insertNonFull(node* x, int k){
int i = x->n - 1; //index of rightmost element
if (x->leaf == true){
while (i >= 0 && x->keys[i] > k){
x->keys[i+1] = x->keys[i]; //shifts all keys one ahead
i--;
} //this i is the new insert postion
x->keys[i+1] = k; //Insert the new key at found location
x->n = x->n + 1;
}
else {
while (i >= 0 && x->keys[i] > k)
i--; //this i is the new insert postion
if (x->C[i+1]->n == t-1){ //child is full? then split it
splitChild(x,i+1);
if (x->keys[i+1] < k)
i++; //this i is the new insert postion
}
insertNonFull(x->C[i+1],k);
}
}
// A utility function to split the child y of this node
// Note that y must be full when this function is called
void BTree::splitChild(node *x, int i){
node* y = x->C[i]; //y will be split
if(y->n != t-1){
cout<<"Fault";
return;
}
node *z = new node(y->leaf);
z->n = t/2 - 1;
for (int j = 0; j < t/2 -1; j++) // Copy the last t/2 -1 keys of y to z
z->keys[j] = y->keys[j + 1 + t/2];
if (y->leaf == false){ // Copy the last t/2 children of y to z
for (int j = 0; j < t/2; j++)
z->C[j] = y->C[j + t/2 + 1];
}
y->n = t/2; // Reduce the number of keys in y
for (int j = x->n; j >= i+1; j--) //make space for a new child
x->C[j+1] = x->C[j];
x->C[i+1] = z; // Link the new child to this node
for (int j = x->n-1; j >= i; j--) //make space for a new key
x->keys[j+1] = x->keys[j];
x->keys[i] = y->keys[t/2]; // Copy the middle key of y to this node
x->n = x->n + 1; // Increment count of keys in this node
}
| 1842210c2caf835204a1e010ee4078b87f9a456f | [
"C++"
] | 20 | C++ | Chait97/DataStructures2 | c27f7bfc7923a8d120ff2d51fc03055695739095 | 2009ae9aa5ad5b5bcaa2548ced88fc648dc65b25 |
refs/heads/master | <repo_name>achourMedHedi/d3otNet_Gmc_bank<file_sep>/GmcBank/Client/Client.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;
namespace GmcBank
{
[DataContract]
public class Client<TAbstractAccount, TTransaction> : IClient<TAbstractAccount, TTransaction>
where TAbstractAccount : AbsctractAccount<TTransaction>
where TTransaction : Transaction
{
[DataMember]
public string name { get; set; }
[DataMember]
public int cin { get; set; }
[DataMember]
public Lazy<Dictionary<long, TAbstractAccount>> accounts;
public Client() { }
public Client(string n , int c)
{
accounts = new Lazy<Dictionary<long, TAbstractAccount>>();
name = n;
cin = c;
}
public IEnumerable<TAbstractAccount> GetAllAccounts ()
{
foreach (KeyValuePair<long , TAbstractAccount> a in accounts.Value )
{
yield return a.Value;
}
}
public void CloseAccount(TAbstractAccount account)
{
accounts.Value[account.accountNumber].state = "Closed";
}
public void CreateAccount(TAbstractAccount a)
{
accounts.Value.Add(a.accountNumber , a);
}
public TAbstractAccount GetAccount(long accountNumber)
{
throw new NotImplementedException();
}
}
}
<file_sep>/GmcBank/Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
namespace GmcBank
{
class Program
{
static void Main(string[] args)
{
Bank <Client<AbsctractAccount<Transaction>,Transaction>, AbsctractAccount<Transaction> , Transaction> bank = new Bank<Client<AbsctractAccount<Transaction>, Transaction>, AbsctractAccount<Transaction>, Transaction>("gmc bank" , 654789);
//string x = bank.Auther();
//bank = bank.LoadFile(@"C:\Users\achou\source\repos\GmcBank\GmcBank\data.json");
bank.Auther();
Client<AbsctractAccount<Transaction>, Transaction> client = new Client<AbsctractAccount<Transaction>, Transaction>("achour", 1500);
bank.Clients.Add(client);
Saving business = new Saving(2154, client);
Business business2 = new Business(1111, client);
client.CreateAccount(business);
client.CreateAccount(business2);
bank.AddAgent();
bank.AddTransaction(new Transaction(2154, 1111, 500));
bank.AddTransaction(new Transaction(2154, 1111, 500));
foreach (Client<AbsctractAccount<Transaction> , Transaction> clients in bank.Clients)
{
Console.WriteLine();
foreach (AbsctractAccount<Transaction> a in clients.GetAllAccounts())
{
Console.WriteLine("hello " + a.balance + " " +a.owner );
foreach (Transaction transaction in a.GetAllTransactions())
{
Console.WriteLine("t = " + transaction.direction + " " + transaction.date );
}
Console.WriteLine("-----");
}
}
bank.SaveFile();
Console.ReadLine();
}
}
}
| a0e9ebd918563ad32396fc2869c6017f2f7990bb | [
"C#"
] | 2 | C# | achourMedHedi/d3otNet_Gmc_bank | d25401f210b6e6ef125898c3c01c4f57b30cdbb6 | 30d53f6c54b28247a3668eae64c31e6855d292e2 |
refs/heads/master | <repo_name>Raghavendra1992/DemoRepo1<file_sep>/src/main/java/com/qa/Login/LoginPage.java
package com.qa.Login;
public class LoginPage
{
public void Loginpage()
{
System.out.println("Login Page");
}
public void LoginSetMethod()
{
System.out.println("Login Set Method");
}
}
| 42cce10a410edb9f1f37bb7021c0129e10458a36 | [
"Java"
] | 1 | Java | Raghavendra1992/DemoRepo1 | 15f3453aad04e8abf2414b0d98da10462b4b7087 | d0ce17d7d731735b4f9e83e8aea6251a9ba22d8c |
refs/heads/master | <repo_name>CrismaruVlad/vpgc<file_sep>/src/app/service/auth.interceptor.ts
import { IHttpInterceptor } from 'angular2-http-interceptor';
import { Request, Response } from '@angular/http';
import { Router } from '@angular/router';
import { Inject } from '@angular/core';
import { Observable } from 'rxjs';
import { UserService } from "./user.service";
export class AuthInterceptor implements IHttpInterceptor {
constructor( @Inject(Router) private router: Router) {
}
before(request: Request): Request {
let token = UserService.token;
if (token) {
request.headers.append('Authorization', `Bearer ${token}`);
}
return request;
}
after(response: Observable<Response>): Observable<any> {
return response.catch(res => {
if (res.status === 403) {
console.log('bad bad bad, forbidden');
//DON'T FORGET TO LOGOUT USER
this.router.navigate(['/login']);
}
return Observable.throw(res);
});
};
}
<file_sep>/src/app/service/user.service.ts
import { Inject, Injectable } from '@angular/core';
import { Http, Response } from "@angular/http";
import { Observable, Subscriber } from "rxjs/Rx";
import "rxjs/add/operator/map";
interface Credentials {
email: string,
password: string
}
@Injectable()
export class UserService {
constructor(@Inject(Http) private http: Http) {
this.refreshToken();
}
login(credentials: Credentials) {
return this.http
.post(
'/auth/login',
JSON.stringify(credentials)
)
.map(res => res.json())
.map((res) => {
if (!res.error) {
return res;
}
return false;
}).flatMap(() => { return this.getToken(credentials) })
.catch((error: any) => Observable.throw(error || 'Server error'));
}
static get token(): string {
return localStorage.getItem('token');
}
static set token(value: string) {
localStorage.setItem('token', value);
}
static get loggedIn() {
return Observable.of(!!UserService.token);
}
private getToken(credentials: Credentials) {
return this.refreshToken(JSON.stringify(credentials));
}
private refreshToken(token?: string) {
if (!token) {
token = UserService.token;
}
return this.http.post('/user/jwt', token, {withCredentials: true})
.map((res: Response) => res.json())
.map(res => {
if (!res.error) {
UserService.token = res.token;
return true;
}
return false;
});
}
public register(credentials: Credentials) {
return this.http.post('/auth/register', credentials)
.map((res: Response) => res.json())
.map(res => {
if (!res.error) {
return res;
}
return false;
}).flatMap((token: string) => this.refreshToken(token))
.catch((error: any) => Observable.throw(error || 'Server error'));
}
logout() {
UserService.token = null;
return Observable.of(true);
}
}
<file_sep>/src/app/app.routes.ts
import { LoginComponent } from './component/login/login.component';
import { HomeComponent } from './component/home/home.component';
import { LoggedInGuard } from "./guard/logged-in.guard";
export const routes = [
{ path: '', component: HomeComponent, canActivate:[LoggedInGuard] },
{ path: 'login', component: LoginComponent }
];
<file_sep>/Dockerfile
# use node alpine with minor version
FROM node:8.1-alpine
# create app directory
RUN mkdir -p /app
WORKDIR /app
RUN apk add --update gcc g++ make python
# install global node requirements
RUN yarn global add nodemon @angular/cli
# copy current package.json and install it
COPY ./package.json ./
RUN npm i
EXPOSE 4200
EXPOSE 1337
# aaaaaand go!!!
CMD nodemon --inspect app.js
<file_sep>/src/app/component/login/login.component.ts
import { Component } from '@angular/core';
import { UserService } from "../../service/user.service";
import { Router } from "@angular/router";
import { AbstractControl, FormBuilder, FormGroup, Validators } from "@angular/forms";
import { ResponseOptionsArgs } from "@angular/http";
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent {
loginForm: FormGroup;
emailStatus: AbstractControl;
passwordStatus: AbstractControl;
passResetFlag: boolean = false;
feedbackMessage: string = null;
constructor(private userService: UserService, private router: Router, private fb: FormBuilder) {
this.loginForm = fb.group({
email: [null, [Validators.required, Validators.email]],
password: [null, [Validators.required, Validators.minLength(8)]]
})
this.emailStatus = this.loginForm.get('email');
this.passwordStatus = this.loginForm.get('password');
}
loginSubmit(form: FormGroup){
this.userService.login({email: form.get('email').value, password: form.get('password').value})
.subscribe(
(result: Response) => {
this.router.navigate(['']);
},
console.log
);
}
registerSubmit(form: FormGroup){
this.userService.register({email: form.get('email').value, password: form.get('password').value})
.subscribe(
(result: Response) => {
this.router.navigate(['']);
},
console.log
)
}
}
| 5372ec40342741d614de2d42d4b0463f9681cdd4 | [
"TypeScript",
"Dockerfile"
] | 5 | TypeScript | CrismaruVlad/vpgc | e45791a697ee4051158b783456b9546790a7b67a | 746828f20af90c55e59d6679968d718ee1f991d7 |
refs/heads/master | <repo_name>mingzhangyong/ssmDemo<file_sep>/web-ssm/src/main/java/com/heitian/ssm/service/impl/UserServiceImpl.java
package com.heitian.ssm.service.impl;
import com.heitian.ssm.dao.DBUserMapper;
import com.heitian.ssm.dao.UserDao;
import com.heitian.ssm.model.DBUser;
import com.heitian.ssm.model.User;
import com.heitian.ssm.service.UserService;
import org.springframework.stereotype.Service;
import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
/**
* Created by Zhangxq on 2016/7/15.
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {
private Logger log = Logger.getLogger(UserServiceImpl.class);
@Resource
private UserDao userDao;
@Resource
private DBUserMapper dbUserMapper;
public User getUserById(Long userId) {
return userDao.selectUserById(userId);
}
public void createUser(DBUser dbUser) {
log.info(dbUser.toString());
dbUserMapper.insert(dbUser);
}
public User getUserByPhoneOrEmail(String emailOrPhone, Short state) {
return userDao.selectUserByPhoneOrEmail(emailOrPhone,state);
}
public List<User> getAllUser() {
return userDao.selectAllUser();
}
public DBUser getAllDBUser(Long id) {
return dbUserMapper.selectByPrimaryKey(id);
}
}
<file_sep>/web-ssm/src/main/java/com/heitian/ssm/controller/UserController.java
package com.heitian.ssm.controller;
import com.alibaba.fastjson.JSONObject;
import com.heitian.ssm.model.DBUser;
import com.heitian.ssm.model.User;
import com.heitian.ssm.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/**
* Created by Zhangxq on 2016/7/15.
*/
@Controller
@RequestMapping("/user")
public class UserController {
private Logger log = Logger.getLogger(UserController.class);
@Resource
private UserService userService;
@RequestMapping("/showUser")
public String showUser(HttpServletRequest request, Model model){
log.info("查询所有用户信息");
List<User> userList = userService.getAllUser();
model.addAttribute("userList",userList);
return "showUser";
}
@RequestMapping("/getUserByPhoneOrEmeil")
public String showUserByPhone(HttpServletRequest request, Model model){
log.info(request.getParameter("phone"));
Short s = 0;
User user = userService.getUserByPhoneOrEmail(request.getParameter("phone"),s);
model.addAttribute("user",user);
return "showUser";
}
@ResponseBody
@RequestMapping(value="/addUser",method= RequestMethod.POST)
public void addUser(@RequestBody DBUser dbUser, HttpServletResponse response)throws IOException {
log.info("sdwsadasdwdasddasd" + dbUser.toString());
try {
userService.createUser(dbUser);
response.getWriter().print("true");
} catch (Exception e) {
log.error("系统异常",e);
response.getWriter().print("false");
}
}
@RequestMapping("/getUserById")
public String showUserById(HttpServletRequest request, Model model){
log.info("request id " + request.getParameter("id"));
DBUser user = userService.getAllDBUser(Long.valueOf(request.getParameter("id")));
log.info("user info " + user.toString());
model.addAttribute("user",user);
return "showUser";
}
}
<file_sep>/README.md
# ssmDemo
学习ssm框架
| 365f5cb973077c5d0627f58936cb686729e851a0 | [
"Markdown",
"Java"
] | 3 | Java | mingzhangyong/ssmDemo | e8e7b72b8269c82ecf19fbdf48065a1dfed7d2ee | 05cf909a3cf15f9399005f7c66216091239f24f2 |
refs/heads/master | <repo_name>Akarshshrivastava/Typewriter-Effect<file_sep>/script.js
const app = document.getElementById("app");
let typewriter = new Typewriter(app, {
strings: ["Developer", "Designer", "Photographer", "Crypto Enthusiast"],
autoStart: true,
loop: true,
delay: 60,
pauseFor: 1000,
});
| 99e577d6166dda9a41a6fc82d3a5b724148e69a9 | [
"JavaScript"
] | 1 | JavaScript | Akarshshrivastava/Typewriter-Effect | fe414dad2b1efaab45b12481d50e7262ef10d0c1 | 3b90019272bb61a02aba1aa1ba3d1971b2d3a6da |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GestionTransporte.clases
{
public class Auditoria
{
DateTime fecha_hs;
Login usuario;//el usuario trae consigo la coneccion a la bd
string accion;
#region encapsulamiento de propiedades
public DateTime Fecha_hs
{
get { return fecha_hs; }
set { fecha_hs = value; }
}
public Login Usuario
{
get { return usuario; }
set { usuario = value; }
}
public string Accion
{
get { return accion; }
set { accion = value; }
}
#endregion
}
}
<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 GestionTransporte.clases;
using System.Data.SqlClient;
using GestionTransporte.vistas;
namespace GestionTransporte
{
public delegate void actualizaTipoAcoplado();
public partial class frmCargaAcoplado : Form
{
clsAcoplado acoplado,acopladoMod;
clsMarca_acoplado marca_acoplado;
clsTipo_acoplado tipo_acoplado;
clsLogin conexion;
actualizaTipoAcoplado delegadoTipoAcoplado;
actualizaTipoAcoplado delegadoMarcaAcoplado;
delegadoActualizaListaAcoplados delegadoActualizaLista;
public frmCargaAcoplado(clsLogin conexion, clsAcoplado acopladoMod,Delegate actualizarLista)
{
InitializeComponent();
this.conexion = conexion;
acoplado = new clsAcoplado(conexion);
marca_acoplado = new clsMarca_acoplado(conexion);
tipo_acoplado = new clsTipo_acoplado(conexion);
this.acopladoMod = acopladoMod;
delegadoTipoAcoplado = new actualizaTipoAcoplado(cargaTipo);
delegadoMarcaAcoplado = new actualizaTipoAcoplado(cargaMarca);
delegadoActualizaLista = (delegadoActualizaListaAcoplados)actualizarLista;
}
private void btnGuardar_unidad_Click(object sender, EventArgs e)
{
if (acoplado.Busqueda_dominio(tbDominio.Text.Trim()).Count > 0 && acopladoMod==null)
{
MessageBox.Show("YA EXISTE UNA UNIDAD CON ESE DOMINIO", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
tbDominio.BackColor = Color.OrangeRed;
}
else if (acoplado.Busqueda_chasis(tbNro_chasis.Text.Trim()).Count > 0 && acopladoMod==null)
{
tbDominio.BackColor = Color.White;
MessageBox.Show("YA EXISTE UNA UNIDAD CON ESE Nº CHASIS YA EXISTE", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
tbNro_chasis.BackColor = Color.OrangeRed;
}
else if( !new clsFunciones().Valida_Controles(this))
{
MessageBox.Show("FALTA LLENAR CAMPOS MARCADOS CON COLOR ROJO", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
if (acopladoMod != null)
{
int marcaID = marca_acoplado.retornaID_marca(cbMarca.SelectedItem.ToString().ToUpper().Trim());
int tipo_acopladoID = tipo_acoplado.retornaID_tipoAcoplado(cbTipo.SelectedItem.ToString().ToUpper().Trim());
acoplado.Dominio = tbDominio.Text.ToUpper().Trim();
acoplado.Marca = marcaID;
acoplado.Modelo = tbModelo.Text.ToUpper().Trim();
acoplado.Año = tbAño.Text.ToUpper().Trim();
acoplado.Tara = float.Parse(tbTara.Text.ToUpper().Trim());
acoplado.Tipo = tipo_acopladoID;
acoplado.Alt_total = float.Parse(tbAlt_total.Text.ToUpper().Trim());
acoplado.Nro_chasis = tbNro_chasis.Text.ToUpper().Trim();
acoplado.Ancho_interior = float.Parse(tbAncho_interior.Text.ToUpper().Trim());
acoplado.Ancho_exterior = float.Parse(tbAncho_exterior.Text.ToUpper().Trim());
acoplado.Long_plataforma = float.Parse(tbLong_plataforma.Text.ToUpper().Trim());
acoplado.Capacidad_carga = float.Parse(tbCapacidad_carga.Text.ToUpper().Trim());
acoplado.Cant_de_ejes = float.Parse(tbCant_de_ejes.Text.ToUpper().Trim());
acoplado.Fecha_alta = DateTime.Now.ToString();
acoplado.Fecha_baja = DateTime.Now.ToString();
acoplado.Observaciones = tbObservaciones.Text.ToUpper().Trim();
acoplado.Estado = acopladoMod.Estado;
acoplado.modificar(acoplado.Dominio.ToString().Trim());
delegadoActualizaLista();
MessageBox.Show("ACOPLADO MODIFICADO CON EXITO", "OK!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
int marcaID = marca_acoplado.retornaID_marca(cbMarca.SelectedItem.ToString().ToUpper().Trim());
int tipo_acopladoID = tipo_acoplado.retornaID_tipoAcoplado(cbTipo.SelectedItem.ToString().ToUpper().Trim());
acoplado.Dominio = tbDominio.Text.ToUpper().Trim();
acoplado.Marca = marcaID;
acoplado.Modelo = tbModelo.Text.ToUpper().Trim();
acoplado.Año = tbAño.Text.ToUpper().Trim();
acoplado.Tara = float.Parse(tbTara.Text.ToUpper().Trim());
acoplado.Tipo = tipo_acopladoID;
acoplado.Alt_total = float.Parse(tbAlt_total.Text.ToUpper().Trim());
acoplado.Nro_chasis = tbNro_chasis.Text.ToUpper().Trim();
acoplado.Ancho_interior = float.Parse(tbAncho_interior.Text.ToUpper().Trim());
acoplado.Ancho_exterior = float.Parse(tbAncho_exterior.Text.ToUpper().Trim());
acoplado.Long_plataforma = float.Parse(tbLong_plataforma.Text.ToUpper().Trim());
acoplado.Capacidad_carga = float.Parse(tbCapacidad_carga.Text.ToUpper().Trim());
acoplado.Cant_de_ejes = float.Parse(tbCant_de_ejes.Text.ToUpper().Trim());
acoplado.Fecha_alta = DateTime.Now.ToString();
acoplado.Fecha_baja = null;
acoplado.Observaciones = tbObservaciones.Text.Trim();
acoplado.Estado = "DISPONIBLE";
acoplado.insertar();
delegadoActualizaLista();
MessageBox.Show("ACOPLADO INSERTADO CON EXITO", "OK!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
acoplado.listar_todo();
tbDominio.Clear();
tbModelo.Clear();
tbAño.Clear();
tbTara.Clear();
tbAlt_total.Clear();
tbNro_chasis.Clear();
tbAncho_exterior.Clear();
tbAncho_interior.Clear();
tbLong_plataforma.Clear();
tbCapacidad_carga.Clear();
tbCant_de_ejes.Clear();
tbObservaciones.Clear();
tbDominio.Enabled = true;
cbMarca.Enabled = true;
tbModelo.Enabled = true;
cbTipo.Enabled = true;
tbAño.Enabled = true;
tbNro_chasis.Enabled = true;
}
private void gestionarTiposDeAcopladoToolStripMenuItem_Click(object sender, EventArgs e)
{
new frmTipoAcoplado(conexion, delegadoTipoAcoplado).ShowDialog();
}
private void cargaMarca()
{
List<String> lista=acoplado.Retorna_marcasComboBox();
cbMarca.Items.Clear();
cbMarca.Items.Add("SELECCIONE MARCA");
foreach (String item in lista)
{
cbMarca.Items.Add(item);
}
cbMarca.SelectedIndex = 0;
}
private void cargaTipo()
{
List<String> lista = acoplado.Retorna_tiposComboBox();
cbTipo.Items.Clear();
cbTipo.Items.Add("SELECCIONE TIPO");
foreach (String item in lista)
{
cbTipo.Items.Add(item);
}
cbTipo.SelectedIndex = 0;
}
private void frmCargaAcoplado_Load(object sender, EventArgs e)
{
cargaTipo();
cargaMarca();
tbDominio.Enabled = true;
if(acopladoMod!=null)
{
string marcaAcop = marca_acoplado.retornaMarca(acopladoMod.Marca);
string tipoAcoplado = tipo_acoplado.retornaTipoAcoplado(acopladoMod.Tipo);
tbDominio.Enabled = false;
cbMarca.Enabled = false;
tbModelo.Enabled = false;
tbAño.Enabled = false;
cbTipo.Enabled = false;
tbNro_chasis.Enabled = false;
tbDominio.Text = acopladoMod.Dominio;
cbMarca.SelectedItem = marcaAcop;
tbModelo.Text = acopladoMod.Modelo.ToString();
tbAño.Text = acopladoMod.Año.ToString();
tbTara.Text = acopladoMod.Tara.ToString();
cbTipo.SelectedItem = tipoAcoplado;
tbAlt_total.Text = acopladoMod.Alt_total.ToString();
tbNro_chasis.Text = acopladoMod.Nro_chasis;
tbAncho_interior.Text = acopladoMod.Ancho_interior.ToString();
tbAncho_exterior.Text = acopladoMod.Ancho_exterior.ToString();
tbLong_plataforma.Text = acopladoMod.Long_plataforma.ToString();
tbCapacidad_carga.Text = acopladoMod.Capacidad_carga.ToString();
tbCant_de_ejes.Text = acopladoMod.Cant_de_ejes.ToString();
tbObservaciones.Text = acopladoMod.Observaciones;
}
}
private void tbAño_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsDigit(e.KeyChar))
{
e.Handled = false;
}
else if (Char.IsControl(e.KeyChar))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
private void tbDominio_TextChanged(object sender, EventArgs e)
{
new clsFunciones().fondoBlanco_Controles(sender);
}
private void gestionarMarcaToolStripMenuItem_Click(object sender, EventArgs e)
{
new frmGestorMarcaAcoplado(conexion, delegadoMarcaAcoplado).ShowDialog();
}
}
}
<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 GestionTransporte.clases;
namespace GestionTransporte
{
public partial class frmTipoAcoplado : Form
{
clsTipo_acoplado tipo;
actualizaTipoAcoplado delegadoActualizaTipoAcoplado;
public frmTipoAcoplado(clsLogin conexion,Delegate actualizar)
{
InitializeComponent();
this.tipo = new clsTipo_acoplado(conexion);
delegadoActualizaTipoAcoplado = (actualizaTipoAcoplado)actualizar;
}
private void btnAgregar_Click(object sender, EventArgs e)
{
string resp;
if (sender == btnAgregar)
{
if (tbAgregar.Text.Trim()==string.Empty)
{
tbAgregar.BackColor = Color.OrangeRed;
MessageBox.Show("FALTA LLENAR CAMPOS MARCADOS CON COLOR ROJO", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
tbAgregar.BackColor = Color.White;
tipo.Tipo = tbAgregar.Text.ToUpper().Trim();
tipo.Estado = "HABILITADO";
resp = tipo.insertar();
delegadoActualizaTipoAcoplado();
if (resp != String.Empty)
MessageBox.Show(resp);
dgvTipo_Acoplado.DataSource = tipo.ver_tipoAcoplado();
tbAgregar.Clear();
tbModificar.Enabled = true;
tbEliminar.Enabled = true;
}
}
if (sender == btnModificar)
{
if (tbModificar.Text.Trim() == string.Empty)
{
tbModificar.BackColor = Color.OrangeRed;
MessageBox.Show("FALTA LLENAR CAMPOS MARCADOS CON COLOR ROJO", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
tbModificar.BackColor = Color.White;
tipo.Tipo = tbModificar.Text.ToUpper().Trim(); ;
resp = tipo.modificar(dgvTipo_Acoplado.SelectedCells[0].Value.ToString());
delegadoActualizaTipoAcoplado();
if (resp != String.Empty)
MessageBox.Show(resp);
dgvTipo_Acoplado.DataSource = tipo.ver_tipoAcoplado();
if (dgvTipo_Acoplado.Rows.Count < 1)
{
tbModificar.Enabled = false;
tbEliminar.Enabled = false;
}
}
}
if (sender == btnEliminar)
{
tipo.Tipo = tbEliminar.Text;
resp = tipo.eliminar(dgvTipo_Acoplado.SelectedCells[0].Value.ToString());
delegadoActualizaTipoAcoplado();
if (resp != String.Empty)
MessageBox.Show(resp);
dgvTipo_Acoplado.DataSource = tipo.ver_tipoAcoplado();
if (dgvTipo_Acoplado.Rows.Count < 1)
{
tbModificar.Enabled = false;
tbEliminar.Enabled = false;
}
}
}
private void dgvTipo_Acoplado_DataSourceChanged(object sender, EventArgs e)
{
if (dgvTipo_Acoplado.RowCount != 0)
{
tbModificar.Text = dgvTipo_Acoplado.SelectedCells[0].Value.ToString();
tbEliminar.Text = dgvTipo_Acoplado.SelectedCells[0].Value.ToString();
}
}
private void dgvTipo_Acoplado_CellClick(object sender, DataGridViewCellEventArgs e)
{
tbModificar.Text = dgvTipo_Acoplado.SelectedCells[0].Value.ToString();
tbEliminar.Text = dgvTipo_Acoplado.SelectedCells[0].Value.ToString();
}
private void frmTipoAcoplado_Load(object sender, EventArgs e)
{
dgvTipo_Acoplado.DataSource = tipo.ver_tipoAcoplado();
if (dgvTipo_Acoplado.Rows.Count < 1)
{
btnModificar.Enabled = false;
btnEliminar.Enabled = false;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
using System.Collections;
namespace GestionTransporte.clases
{
public class clsTipo_acoplado
{
#region Atributos y Propiedades
string tipo;
string estado;
clsLogin usuario;
#region Get y Set
public string Estado
{
get { return estado; }
set { estado = value; }
}
public string Tipo
{
get { return tipo; }
set { tipo = value; }
}
#endregion
#endregion
public clsTipo_acoplado(clsLogin usuario)
{
this.usuario = usuario;
}
public string insertar()
{
string respuesta=string.Empty;
SqlCommand cmd = new SqlCommand();
try
{
cmd.Connection = usuario.cnn;
cmd.CommandText = "insert into tipo_acoplado values ('" + Tipo + "','" + Estado + "');SELECT Scope_Identity();";
cmd.CommandType = CommandType.Text;
usuario.Modo(TipoConexion.Abrir);
string id_insertado = cmd.ExecuteScalar().ToString();
if (id_insertado != null)
{
cmd.CommandText = "insert into auditoria values ('" + (DateTime.Now).ToString() + "','" + usuario.Usuario + "','" + "se inserto tipo de acoplado " + Tipo + "')";
cmd.ExecuteNonQuery();
respuesta = string.Empty;
}
else
{
respuesta = "Error al insertar tipo de acoplado";
}
}
catch (SqlException e)
{
if (e.ErrorCode == -2146232060)
{
respuesta = "YA EXISTE ESE TIPO DE CAMION ";
}
}
usuario.Modo(TipoConexion.Cerrar);
return respuesta;
} //Funcion que inserta un tipo acoplado nuevo
public DataTable ver_tipoAcoplado()
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = usuario.cnn;
cmd.CommandText = "select tipo as TIPO,estado as ESTADO from tipo_acoplado order by tipo asc";
cmd.CommandType = CommandType.Text;
usuario.Modo(TipoConexion.Abrir);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
DataTable datatable = new DataTable();
adapter.Fill(datatable);
usuario.Modo(TipoConexion.Cerrar);
return datatable;
} //Funcion que guarda todos los tipos de acoplados de la BD en un DataTable
public string modificar(string vieja)
{
string respuesta;
SqlCommand cmd = new SqlCommand();
try
{
cmd.Connection = usuario.cnn;
cmd.CommandText = "update tipo_acoplado set tipo='" + Tipo + "' where tipo='" + vieja + "';SELECT Scope_Identity();";
cmd.CommandType = CommandType.Text;
usuario.Modo(TipoConexion.Abrir);
string id_insertado = cmd.ExecuteScalar().ToString();
if (id_insertado != null)
{
cmd.CommandText = "insert into auditoria values ('" + (DateTime.Now).ToString() + "','" + usuario.Usuario + "','" + "se modifico el tipo de acoplado" + vieja + " a " + Tipo + "')";
cmd.ExecuteNonQuery();
respuesta = string.Empty;
}
else
{
respuesta = "Error al modificar tipo de acoplado";
}
}
catch (Exception e)
{
respuesta = e.Message;
}
usuario.Modo(TipoConexion.Cerrar);
return respuesta;
} //Funcion que sirve para modificar un tipo de acoplado
public string eliminar(String tipo)
{
string respuesta;
SqlCommand cmd = new SqlCommand();
try
{
cmd.Connection = usuario.cnn;
cmd.CommandText = "update tipo_acoplado set estado='DESAHABILITADO' where tipo='" + tipo + "';SELECT Scope_Identity();";
cmd.CommandType = CommandType.Text;
usuario.Modo(TipoConexion.Abrir);
int id_insertado = cmd.ExecuteNonQuery();
if (id_insertado != 0)
{
cmd.CommandText = "insert into auditoria values ('" + (DateTime.Now).ToString() + "','" + usuario.Usuario + "','" + "elimino el tipo de acoplado " + Tipo + "')";
cmd.ExecuteNonQuery();
respuesta = string.Empty;
}
else
{
respuesta = "Error al eliminar tipo,ya existe una unidad utilizando este tipo";
}
}
catch (SqlException)
{
respuesta = "Error al eliminar tipo,ya existe una unidad utilizando este tipo";
}
usuario.Modo(TipoConexion.Cerrar);
return respuesta;
} //Funcion para eliminar un tipo de acoplado
public int retornaID_tipoAcoplado(string tipo)
{
int retorno = 1;
SqlCommand cmd = new SqlCommand();
cmd.Connection = usuario.cnn;
usuario.cnn.Open();
cmd.CommandText = "select id from tipo_acoplado where tipo='" + tipo + "' ";
cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
retorno = Convert.ToInt32(dr[0]);
}
usuario.cnn.Close();
return retorno;
} //Funcion que retorna el tipo de acoplado segun sea el ID
public String retornaTipoAcoplado(int id)
{
string retorno = string.Empty;
SqlCommand cmd = new SqlCommand();
usuario.cnn.Open();
cmd.Connection = usuario.cnn;
cmd.CommandText = "select tipo from tipo_acoplado where id='" + id + "' ";
cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
retorno = dr[0].ToString();
}
usuario.cnn.Close();
return retorno;
} //Funcion que retorna el id de un tipo acoplado segun su nombre
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace GestionTransporte.clases
{
public class clsViaje
{
public clsViaje(clsLogin usuario)
{
this.usuario = usuario;
}
#region Encapsulamient de propiedades y Get Set
string id_viaje;
string id_camion;
string id_acoplado1;
string id_acoplado2;
string id_pedido;
DateTime fecha_Sal;
DateTime fecha_Regre;
string estado;
string observaciones;
clsLogin usuario;
DataTable dt;
SqlDataAdapter da;
// (EN MODIFICAR) ESTAS VARIABLES 'VIEJO' SE UTILIZAN CORROBORAR SI SE CAMBIO DE UNIDAD ,EN DICHO CASO SE DEBERA CAMBIAR EL ESTADO LA UNIDAD QUE YA NO ESTA EN EL VIAJE
string id_camion_viejo=string.Empty;
string id_acoplado1_viejo=string.Empty;
string id_acoplado2_viejo=string.Empty;
//*********************************************************************
public string Id_acoplado2
{
get { return id_acoplado2; }
set { id_acoplado2 = value; }
}
public string Id_pedido
{
get { return id_pedido; }
set { id_pedido = value; }
}
public string Id_acoplado1
{
get { return id_acoplado1; }
set { id_acoplado1 = value; }
}
public string Observaciones
{
get { return observaciones; }
set { observaciones = value; }
}
public string Estado
{
get { return estado; }
set { estado = value; }
}
public DateTime Fecha_Regre
{
get { return fecha_Regre; }
set { fecha_Regre = value; }
}
public DateTime Fecha_Sal
{
get { return fecha_Sal; }
set { fecha_Sal = value; }
}
public string Id_camion
{
get { return id_camion; }
set { id_camion = value; }
}
public string Id_viaje
{
get { return id_viaje; }
set { id_viaje = value; }
}
#endregion
public string alta()
{
string respuesta;
SqlTransaction sqlTran;
using (usuario.cnn)
{
usuario.cnn.Open();
sqlTran= usuario.cnn.BeginTransaction();//para manejo de transacciones
try
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = usuario.cnn;
cmd.CommandText = "insert into viaje (id_pedido,id_camion,id_acoplado1,id_acoplado2,fecha_sal,fecha_regre,estado,observaciones) values ('" + id_pedido + "','" + id_camion + "','" + Id_acoplado1 + "','" + Id_acoplado2 + "','" + fecha_Sal + "','" + Fecha_Regre + "','" + estado + "','" + observaciones + "');SELECT Scope_Identity();";
cmd.CommandType = CommandType.Text;
cmd.Transaction = sqlTran;
string id_insertado = cmd.ExecuteScalar().ToString();
if (id_insertado != null)
{
cmd.CommandText = "insert into auditoria values ('" + (DateTime.Now).ToString() + "','" + usuario.Usuario + "','" + "se inserto viaje con id " + id_insertado + "')";
cmd.ExecuteNonQuery();
cmd.CommandText = "update pedido set estado = 'CARGADO' where id_pedido=" + id_pedido + " ;SELECT Scope_Identity();";
cmd.ExecuteNonQuery();
respuesta = string.Empty;
sqlTran.Commit();
}
else
{
sqlTran.Rollback();
respuesta = "Error al insertar viaje";
}
}
catch
{
//sqlTran.Rollback();
respuesta = "Error al insertar viaje";
}
usuario.cnn.Close();
}
return respuesta;
}
public string baja()
{
string respuesta = String.Empty;
if (estado == "DISPONIBLE")
{
SqlCommand cmd = new SqlCommand();
try
{
cmd.Connection = usuario.cnn;
cmd.CommandText = "update viaje set estado='DADO DE BAJA' where id_viaje='" + Id_viaje + "';SELECT Scope_Identity();";
cmd.CommandType = CommandType.Text;
usuario.Modo(TipoConexion.Abrir);
string id_insertado = cmd.ExecuteScalar().ToString();
if (id_insertado != null)
{
cmd.CommandText = "insert into auditoria values ('" + (DateTime.Now).ToString() + "','" + usuario.Usuario + "','" + "se dio de baja viaje id=" + id_insertado + "')";
cmd.ExecuteNonQuery();
}
else
{
respuesta = "Error al dar de baja viaje";
}
}
catch (SqlException ex)
{
respuesta = ex.ErrorCode.ToString();
}
usuario.Modo(TipoConexion.Cerrar);
}
else
respuesta = "Error, no se puede dar de baja. Compruebe que el estado del mismo sea DISPONIBLE";
usuario.cnn.Close();
return respuesta;
}
public string modificar()
{
string respuesta;
SqlTransaction sqlTran;
//COMIENZO DE TRANSACCION
using (usuario.cnn)
{
usuario.cnn.Open();
sqlTran = usuario.cnn.BeginTransaction();
try
{
;
SqlCommand cmd = new SqlCommand();
cmd.Transaction = sqlTran;
cmd.Connection = usuario.cnn;
cmd.CommandText = "update viaje set id_camion='" + Id_camion + "',id_acoplado1='" + Id_acoplado1 + "',id_acoplado2='" + Id_acoplado2 + "',fecha_sal='" + Fecha_Sal + "',fecha_regre='" + Fecha_Regre + "',estado='" + Estado + "',observaciones='" + Observaciones + "' where id_viaje='" + Id_viaje + "';SELECT Scope_Identity();";
cmd.CommandType = CommandType.Text;
string id_insertado = cmd.ExecuteScalar().ToString();
//verifico si el camion,acoplado1,acoplado2
if (id_camion_viejo != Id_camion)
{
cmd.CommandText = "update camion set estado='DISPONIBLE' where id_camion='" + id_camion_viejo + "';SELECT Scope_Identity();";
cmd.ExecuteScalar();
}
if (id_acoplado1_viejo != Id_acoplado1)
{
cmd.CommandText = "update acoplado set estado='DISPONIBLE' where id_acoplado='" + id_acoplado1_viejo + "';SELECT Scope_Identity();";
cmd.ExecuteScalar();
}
if (id_acoplado2_viejo != Id_acoplado2)
{
cmd.CommandText = "update acoplado set estado='DISPONIBLE' where id_acoplado='" + id_acoplado2_viejo + "';SELECT Scope_Identity();";
cmd.ExecuteScalar();
}
if (id_insertado != null)
{
cmd.CommandText = "insert into auditoria values ('" + (DateTime.Now).ToString() + "','" + usuario.Usuario + "','" + "se modifico viaje id :" + id_viaje + "')";
cmd.ExecuteNonQuery();
respuesta = string.Empty;
sqlTran.Commit();
}
else
{
respuesta = "Error al modificar viaje";
}
}
catch (Exception ex)
{
try
{
sqlTran.Rollback();
respuesta = "Error al modificar viaje";
}
catch
{
respuesta = "Error al modificar viaje";
}
}
usuario.Modo(TipoConexion.Cerrar);
}
return respuesta;
}
public string cerrarViaje(clsViaje viajeCerrado)
{
string respuesta=String.Empty;
SqlCommand cmd = new SqlCommand();
cmd.Connection = usuario.cnn;
cmd.CommandText = "insert into auditoria values ('" + (DateTime.Now).ToString() + "','" + usuario.Usuario + "','" + "se cerro el viaje con ID " + viajeCerrado.id_viaje + "')";
cmd.CommandType = CommandType.Text;
usuario.Modo(TipoConexion.Abrir);
usuario.cnn.Close();
clsCamion camion=new clsCamion(usuario);
clsAcoplado acop1 = new clsAcoplado(usuario);
clsAcoplado acop2 = new clsAcoplado(usuario);
if (viajeCerrado.id_camion != null)
{
camion = camion.Busqueda_id(viajeCerrado.id_camion);
camion.Estado = "DISPONIBLE";
}
if (viajeCerrado.id_acoplado1 != null)
{
acop1 = acop1.Busqueda_id(viajeCerrado.id_acoplado1);
acop1.Estado = "DISPONIBLE";
}
if (viajeCerrado.id_acoplado2 != null)
{
acop2 = acop2.Busqueda_id(viajeCerrado.id_acoplado2);
acop2.Estado = "DISPONIBLE";
}
return respuesta;
}
public clsViaje Retorna_Viaje(String id_viaje)
{
try
{
clsViaje viaje = new clsViaje(usuario);
SqlCommand cmd = new SqlCommand();
usuario.cnn.Open();
cmd.Connection = usuario.cnn;
cmd.CommandText = "select v.id_viaje,v.fecha_sal ,v.fecha_regre ,v.estado ,v.observaciones,"
+ "c.id_camion,"
+ "a1.id_acoplado,"
+ "a2.id_acoplado,"
+ "p.id_pedido"
+ " from viaje v INNER JOIN pedido p on p.id_pedido=v.id_pedido INNER JOIN "
+ "camion c on c.id_camion=v.id_camion INNER JOIN marca_camion cm on cm.id=c.marca INNER JOIN tipo_camion ct on ct.id=c.tipo INNER JOIN modelo_camion mc on mc.id=c.modelo LEFT OUTER JOIN "
+ "acoplado a1 on a1.id_acoplado=v.id_acoplado1 LEFT OUTER JOIN marca_acoplado a1m on a1m.id=a1.marca LEFT OUTER JOIN tipo_acoplado a1t on a1t.id=a1.tipo LEFT OUTER JOIN "
+ "acoplado a2 on a2.id_acoplado=v.id_acoplado2 LEFT OUTER JOIN marca_acoplado a2m on a2m.id=a2.marca LEFT OUTER JOIN tipo_acoplado a2t on a2t.id=a2.tipo LEFT OUTER JOIN "
+ "chofer ch on p.id_chofer = ch.num_legajo where v.id_viaje ='" + Convert.ToInt32(id_viaje) + "'";
cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
viaje.Id_viaje = dr[0].ToString();
viaje.Fecha_Sal = Convert.ToDateTime(dr[1]);
viaje.Fecha_Regre = Convert.ToDateTime(dr[2]);
viaje.Estado = dr[3].ToString();
viaje.Observaciones = dr[4].ToString();
viaje.Id_camion = dr[5].ToString();
viaje.id_camion_viejo = dr[5].ToString();//camion viejo
viaje.Id_acoplado1 = dr[6].ToString();
viaje.id_acoplado1_viejo = dr[6].ToString();//acoplado 1 viejo
viaje.Id_acoplado2 = dr[7].ToString();
viaje.id_acoplado2_viejo = dr[7].ToString();//acoplado 2 vijeo
viaje.Id_pedido = dr[8].ToString();
}
usuario.cnn.Close();
return viaje;
}
catch (Exception)
{
return null;
}
}
public DataTable Listar_todos()
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("select v.id_viaje as 'ID',v.fecha_sal 'SALIDA',v.fecha_regre as 'REGRESO',ISNULL(v.observaciones,'-----') as 'OBSERVACIONES VIAJE',"
+ "ISNULL(p.nombre_cliente,'-----') as 'CLIENTE',ISNULL(p.cuil_cliente,'-----') as 'CUIL CLIENTE',p.fecha_sal_aprox as 'SALIDA APROXIMADA',p.fecha_reg_aprox as 'REGRESO APROXIMADO',p.peso_carga_aprox as 'PESO APROX',p.fecha_pedido as 'FECHA PEDIDO',p.observaciones as 'OBSERVACIONES PEDIDO',"
+ "ISNULL(c.dominio,'-----') as 'DOMINIO CAMION',ISNULL(cm.marca,'-----') as 'MARCA CAMION' ,ISNULL(ct.tipo,'-----') as 'TIPO CAMION',ISNULL(mc.modelo,'-----') as 'MODELO CAMION',"
+ "ISNULL(a1.dominio,'-----') as 'DOMINIO ACOPLADO',ISNULL(a1m.marca,'-----') as 'MARCA ACOPLADO',ISNULL(a1t.tipo,'-----') as 'TIPO ACOPLADO',"
+ "ISNULL(a2.dominio,'-----') as 'DOMINIO ACOPLADO',ISNULL(a2m.marca,'-----') as 'MARCA ACOPLADO',ISNULL(a2t.tipo,'-----') as 'TIPO ACOPLADO',"
+ "ISNULL(ch.num_legajo,-1) as 'LEGAJO',ISNULL(ch.nombre,'-----') as 'NOMBRE',ISNULL(ch.apellido,'-----') as 'APELLIDO',ISNULL(ch.direccion,'-----') as 'DIRECCION',ISNULL(ch.telefono1,'-----') 'TELEFONO 1' ,ISNULL(ch.telefono2,'-----') 'TELEFONO 2' "
+ "from viaje v INNER JOIN pedido p on p.id_pedido=v.id_pedido INNER JOIN "
+ "camion c on c.id_camion=v.id_camion INNER JOIN marca_camion cm on cm.id=c.marca INNER JOIN tipo_camion ct on ct.id=c.tipo INNER JOIN modelo_camion mc on mc.id=c.modelo LEFT OUTER JOIN "
+ "acoplado a1 on a1.id_acoplado=v.id_acoplado1 LEFT OUTER JOIN marca_acoplado a1m on a1m.id=a1.marca LEFT OUTER JOIN tipo_acoplado a1t on a1t.id=a1.tipo LEFT OUTER JOIN "
+ "acoplado a2 on a2.id_acoplado=v.id_acoplado2 LEFT OUTER JOIN marca_acoplado a2m on a2m.id=a2.marca LEFT OUTER JOIN tipo_acoplado a2t on a2t.id=a2.tipo LEFT OUTER JOIN "
+ "chofer ch on p.id_chofer = ch.num_legajo"
, usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
}
//public DataTable Listar_Dados_De_Baja()
//{
// try
// {
// usuario.Modo(TipoConexion.Abrir);
// da = new SqlDataAdapter("select v.id_viaje as 'ID',v.fecha_sal 'SALIDA',v.fecha_regre as 'REGRESO',v.observaciones as 'OBSERVACIONES VIAJE',"
// + "p.nombre_cliente as 'CLIENTE',p.cuil_cliente as 'CUIL CLIENTE',p.fecha_sal_aprox as 'SALIDA APROXIMADA',p.fecha_reg_aprox as 'REGRESO APROXIMADO',p.peso_carga_aprox as 'PESO APROX',p.fecha_pedido as 'FECHA PEDIDO',p.observaciones as 'OBSERVACIONES PEDIDO',"
// + "c.dominio as 'DOMINIO CAMION',cm.marca as 'MARCA CAMION' ,ct.tipo as 'TIPO CAMION',"
// + "a1.dominio as 'DOMINIO ACOPLADO',a1m.marca as 'MARCA ACOPLADO', a1t.tipo as 'TIPO ACOPLADO',"
// + "a2.dominio as 'DOMINIO ACOPLADO',a2m.marca as 'MARCA ACOPLADO', a2t.tipo as 'TIPO ACOPLADO',"
// + "ch.num_legajo as 'LEGAJO',ch.nombre as 'NOMBRE',ch.apellido as 'APELLIDO',ch.telefono1 'TELEFONO 1' ,ch.telefono2 'TELEFONO 2' "
// + "from viaje v INNER JOIN pedido p on p.id_pedido=v.id_pedido INNER JOIN "
// + "camion c on c.id_camion=v.id_camion INNER JOIN marca_camion cm on cm.id=c.marca INNER JOIN tipo_camion ct on ct.id=c.tipo LEFT OUTER JOIN "
// + "acoplado a1 on a1.id_acoplado=v.id_acoplado1 LEFT OUTER JOIN marca_acoplado a1m on a1m.id=a1.marca LEFT OUTER JOIN tipo_acoplado a1t on a1t.id=a1.tipo LEFT OUTER JOIN "
// + "acoplado a2 on a2.id_acoplado=v.id_acoplado2 LEFT OUTER JOIN marca_acoplado a2m on a2m.id=a2.marca LEFT OUTER JOIN tipo_acoplado a2t on a2t.id=a2.tipo LEFT OUTER JOIN "
// + "chofer ch on p.id_chofer = ch.num_legajo"
// + "where v.estado='DADO DE BAJA'"
// , usuario.cnn);
// dt = new DataTable();
// da.Fill(dt);
// usuario.Modo(TipoConexion.Cerrar);
// return dt;
// }
// catch (Exception)
// {
// return null;
// }
//}
public DataTable Listar_En_Viaje()
{
DateTime fechaActual = new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day,DateTime.Now.Hour,DateTime.Now.Minute,DateTime.Now.Second);
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("select v.id_viaje as 'ID',v.fecha_sal 'SALIDA',v.fecha_regre as 'REGRESO',ISNULL(v.observaciones,'-----') as 'OBSERVACIONES VIAJE',"
+ "ISNULL(p.nombre_cliente,'-----') as 'CLIENTE',ISNULL(p.cuil_cliente,'-----') as 'CUIL CLIENTE',p.fecha_sal_aprox as 'SALIDA APROXIMADA',p.fecha_reg_aprox as 'REGRESO APROXIMADO',p.peso_carga_aprox as 'PESO APROX',p.fecha_pedido as 'FECHA PEDIDO',p.observaciones as 'OBSERVACIONES PEDIDO',"
+ "ISNULL(c.dominio,'-----') as 'DOMINIO CAMION',ISNULL(cm.marca,'-----') as 'MARCA CAMION' ,ISNULL(ct.tipo,'-----') as 'TIPO CAMION',ISNULL(mc.modelo,'-----') as 'MODELO CAMION',"
+ "ISNULL(a1.dominio,'-----') as 'DOMINIO ACOPLADO',ISNULL(a1m.marca,'-----') as 'MARCA ACOPLADO',ISNULL(a1t.tipo,'-----') as 'TIPO ACOPLADO',"
+ "ISNULL(a2.dominio,'-----') as 'DOMINIO ACOPLADO',ISNULL(a2m.marca,'-----') as 'MARCA ACOPLADO',ISNULL(a2t.tipo,'-----') as 'TIPO ACOPLADO',"
+ "ISNULL(ch.num_legajo,-1) as 'LEGAJO',ISNULL(ch.nombre,'-----') as 'NOMBRE',ISNULL(ch.apellido,'-----') as 'APELLIDO',ISNULL(ch.direccion,'-----') as 'DIRECCION',ISNULL(ch.telefono1,'-----') 'TELEFONO 1' ,ISNULL(ch.telefono2,'-----') 'TELEFONO 2' "
+ "from viaje v INNER JOIN pedido p on p.id_pedido=v.id_pedido INNER JOIN "
+ "camion c on c.id_camion=v.id_camion INNER JOIN marca_camion cm on cm.id=c.marca INNER JOIN tipo_camion ct on ct.id=c.tipo INNER JOIN modelo_camion mc on mc.id=c.modelo LEFT OUTER JOIN "
+ "acoplado a1 on a1.id_acoplado=v.id_acoplado1 LEFT OUTER JOIN marca_acoplado a1m on a1m.id=a1.marca LEFT OUTER JOIN tipo_acoplado a1t on a1t.id=a1.tipo LEFT OUTER JOIN "
+ "acoplado a2 on a2.id_acoplado=v.id_acoplado2 LEFT OUTER JOIN marca_acoplado a2m on a2m.id=a2.marca LEFT OUTER JOIN tipo_acoplado a2t on a2t.id=a2.tipo LEFT OUTER JOIN "
+ "chofer ch on p.id_chofer = ch.num_legajo "
+ "where v.fecha_sal <= try_parse('"+fechaActual.ToString()+"' as datetime) and v.estado like 'PENDIENTE'"
, usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception e)
{
return null;
}
}
public DataTable Listar_Concluidos()
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("select v.id_viaje as 'ID',v.fecha_sal 'SALIDA',v.fecha_regre as 'REGRESO',ISNULL(v.observaciones,'-----') as 'OBSERVACIONES VIAJE',"
+ "ISNULL(p.nombre_cliente,'-----') as 'CLIENTE',ISNULL(p.cuil_cliente,'-----') as 'CUIL CLIENTE',p.fecha_sal_aprox as 'SALIDA APROXIMADA',p.fecha_reg_aprox as 'REGRESO APROXIMADO',p.peso_carga_aprox as 'PESO APROX',p.fecha_pedido as 'FECHA PEDIDO',p.observaciones as 'OBSERVACIONES PEDIDO',"
+ "ISNULL(c.dominio,'-----') as 'DOMINIO CAMION',ISNULL(cm.marca,'-----') as 'MARCA CAMION' ,ISNULL(ct.tipo,'-----') as 'TIPO CAMION',ISNULL(mc.modelo,'-----') as 'MODELO CAMION',"
+ "ISNULL(a1.dominio,'-----') as 'DOMINIO ACOPLADO',ISNULL(a1m.marca,'-----') as 'MARCA ACOPLADO',ISNULL(a1t.tipo,'-----') as 'TIPO ACOPLADO',"
+ "ISNULL(a2.dominio,'-----') as 'DOMINIO ACOPLADO',ISNULL(a2m.marca,'-----') as 'MARCA ACOPLADO',ISNULL(a2t.tipo,'-----') as 'TIPO ACOPLADO',"
+ "ISNULL(ch.num_legajo,-1) as 'LEGAJO',ISNULL(ch.nombre,'-----') as 'NOMBRE',ISNULL(ch.apellido,'-----') as 'APELLIDO',ISNULL(ch.direccion,'-----') as 'DIRECCION',ISNULL(ch.telefono1,'-----') 'TELEFONO 1' ,ISNULL(ch.telefono2,'-----') 'TELEFONO 2' "
+ "from viaje v INNER JOIN pedido p on p.id_pedido=v.id_pedido INNER JOIN "
+ "camion c on c.id_camion=v.id_camion INNER JOIN marca_camion cm on cm.id=c.marca INNER JOIN tipo_camion ct on ct.id=c.tipo INNER JOIN modelo_camion mc on mc.id=c.modelo LEFT OUTER JOIN "
+ "acoplado a1 on a1.id_acoplado=v.id_acoplado1 LEFT OUTER JOIN marca_acoplado a1m on a1m.id=a1.marca LEFT OUTER JOIN tipo_acoplado a1t on a1t.id=a1.tipo LEFT OUTER JOIN "
+ "acoplado a2 on a2.id_acoplado=v.id_acoplado2 LEFT OUTER JOIN marca_acoplado a2m on a2m.id=a2.marca LEFT OUTER JOIN tipo_acoplado a2t on a2t.id=a2.tipo LEFT OUTER JOIN "
+ "chofer ch on p.id_chofer = ch.num_legajo "
+ "where v.estado='CONCLUIDO'"
, usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
}
public DataTable Listar_Cancelados()
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("select v.id_viaje as 'ID',v.fecha_sal 'SALIDA',v.fecha_regre as 'REGRESO',ISNULL(v.observaciones,'-----') as 'OBSERVACIONES VIAJE',"
+ "ISNULL(p.nombre_cliente,'-----') as 'CLIENTE',ISNULL(p.cuil_cliente,'-----') as 'CUIL CLIENTE',p.fecha_sal_aprox as 'SALIDA APROXIMADA',p.fecha_reg_aprox as 'REGRESO APROXIMADO',p.peso_carga_aprox as 'PESO APROX',p.fecha_pedido as 'FECHA PEDIDO',p.observaciones as 'OBSERVACIONES PEDIDO',"
+ "ISNULL(c.dominio,'-----') as 'DOMINIO CAMION',ISNULL(cm.marca,'-----') as 'MARCA CAMION' ,ISNULL(ct.tipo,'-----') as 'TIPO CAMION',ISNULL(mc.modelo,'-----') as 'MODELO CAMION',"
+ "ISNULL(a1.dominio,'-----') as 'DOMINIO ACOPLADO',ISNULL(a1m.marca,'-----') as 'MARCA ACOPLADO',ISNULL(a1t.tipo,'-----') as 'TIPO ACOPLADO',"
+ "ISNULL(a2.dominio,'-----') as 'DOMINIO ACOPLADO',ISNULL(a2m.marca,'-----') as 'MARCA ACOPLADO',ISNULL(a2t.tipo,'-----') as 'TIPO ACOPLADO',"
+ "ISNULL(ch.num_legajo,-1) as 'LEGAJO',ISNULL(ch.nombre,'-----') as 'NOMBRE',ISNULL(ch.apellido,'-----') as 'APELLIDO',ISNULL(ch.direccion,'-----') as 'DIRECCION',ISNULL(ch.telefono1,'-----') 'TELEFONO 1' ,ISNULL(ch.telefono2,'-----') 'TELEFONO 2' "
+ "from viaje v INNER JOIN pedido p on p.id_pedido=v.id_pedido INNER JOIN "
+ "camion c on c.id_camion=v.id_camion INNER JOIN marca_camion cm on cm.id=c.marca INNER JOIN tipo_camion ct on ct.id=c.tipo INNER JOIN modelo_camion mc on mc.id=c.modelo LEFT OUTER JOIN "
+ "acoplado a1 on a1.id_acoplado=v.id_acoplado1 LEFT OUTER JOIN marca_acoplado a1m on a1m.id=a1.marca LEFT OUTER JOIN tipo_acoplado a1t on a1t.id=a1.tipo LEFT OUTER JOIN "
+ "acoplado a2 on a2.id_acoplado=v.id_acoplado2 LEFT OUTER JOIN marca_acoplado a2m on a2m.id=a2.marca LEFT OUTER JOIN tipo_acoplado a2t on a2t.id=a2.tipo LEFT OUTER JOIN "
+ "chofer ch on p.id_chofer = ch.num_legajo "
+ "where v.estado='CANCELADO'"
, usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
}
public DataTable Listar_Pendientes()
{
DateTime fechaActual = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("select v.id_viaje as 'ID',v.fecha_sal 'SALIDA',v.fecha_regre as 'REGRESO',ISNULL(v.observaciones,'-----') as 'OBSERVACIONES VIAJE',"
+ "ISNULL(p.nombre_cliente,'-----') as 'CLIENTE',ISNULL(p.cuil_cliente,'-----') as 'CUIL CLIENTE',p.fecha_sal_aprox as 'SALIDA APROXIMADA',p.fecha_reg_aprox as 'REGRESO APROXIMADO',p.peso_carga_aprox as 'PESO APROX',p.fecha_pedido as 'FECHA PEDIDO',p.observaciones as 'OBSERVACIONES PEDIDO',"
+ "ISNULL(c.dominio,'-----') as 'DOMINIO CAMION',ISNULL(cm.marca,'-----') as 'MARCA CAMION' ,ISNULL(ct.tipo,'-----') as 'TIPO CAMION',ISNULL(mc.modelo,'-----') as 'MODELO CAMION',"
+ "ISNULL(a1.dominio,'-----') as 'DOMINIO ACOPLADO',ISNULL(a1m.marca,'-----') as 'MARCA ACOPLADO',ISNULL(a1t.tipo,'-----') as 'TIPO ACOPLADO',"
+ "ISNULL(a2.dominio,'-----') as 'DOMINIO ACOPLADO',ISNULL(a2m.marca,'-----') as 'MARCA ACOPLADO',ISNULL(a2t.tipo,'-----') as 'TIPO ACOPLADO',"
+ "ISNULL(ch.num_legajo,-1) as 'LEGAJO',ISNULL(ch.nombre,'-----') as 'NOMBRE',ISNULL(ch.apellido,'-----') as 'APELLIDO',ISNULL(ch.direccion,'-----') as 'DIRECCION',ISNULL(ch.telefono1,'-----') 'TELEFONO 1' ,ISNULL(ch.telefono2,'-----') 'TELEFONO 2' "
+ "from viaje v INNER JOIN pedido p on p.id_pedido=v.id_pedido INNER JOIN "
+ "camion c on c.id_camion=v.id_camion INNER JOIN marca_camion cm on cm.id=c.marca INNER JOIN tipo_camion ct on ct.id=c.tipo INNER JOIN modelo_camion mc on mc.id=c.modelo LEFT OUTER JOIN "
+ "acoplado a1 on a1.id_acoplado=v.id_acoplado1 LEFT OUTER JOIN marca_acoplado a1m on a1m.id=a1.marca LEFT OUTER JOIN tipo_acoplado a1t on a1t.id=a1.tipo LEFT OUTER JOIN "
+ "acoplado a2 on a2.id_acoplado=v.id_acoplado2 LEFT OUTER JOIN marca_acoplado a2m on a2m.id=a2.marca LEFT OUTER JOIN tipo_acoplado a2t on a2t.id=a2.tipo LEFT OUTER JOIN "
+ "chofer ch on p.id_chofer = ch.num_legajo "
+ "where v.fecha_sal < try_parse('" + fechaActual.ToString() + "' as datetime) and v.estado LIKE 'PENDIENTE'"
, usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
}
public DataTable Listar_Por_Cliente( string cliente)
{
DateTime fechaActual = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("select v.id_viaje as 'ID',v.fecha_sal 'SALIDA',v.fecha_regre as 'REGRESO',ISNULL(v.observaciones,'-----') as 'OBSERVACIONES VIAJE',"
+ "ISNULL(p.nombre_cliente,'-----') as 'CLIENTE',ISNULL(p.cuil_cliente,'-----') as 'CUIL CLIENTE',p.fecha_sal_aprox as 'SALIDA APROXIMADA',p.fecha_reg_aprox as 'REGRESO APROXIMADO',p.peso_carga_aprox as 'PESO APROX',p.fecha_pedido as 'FECHA PEDIDO',p.observaciones as 'OBSERVACIONES PEDIDO',"
+ "ISNULL(c.dominio,'-----') as 'DOMINIO CAMION',ISNULL(cm.marca,'-----') as 'MARCA CAMION' ,ISNULL(ct.tipo,'-----') as 'TIPO CAMION',ISNULL(mc.modelo,'-----') as 'MODELO CAMION',"
+ "ISNULL(a1.dominio,'-----') as 'DOMINIO ACOPLADO',ISNULL(a1m.marca,'-----') as 'MARCA ACOPLADO',ISNULL(a1t.tipo,'-----') as 'TIPO ACOPLADO',"
+ "ISNULL(a2.dominio,'-----') as 'DOMINIO ACOPLADO',ISNULL(a2m.marca,'-----') as 'MARCA ACOPLADO',ISNULL(a2t.tipo,'-----') as 'TIPO ACOPLADO',"
+ "ISNULL(ch.num_legajo,-1) as 'LEGAJO',ISNULL(ch.nombre,'-----') as 'NOMBRE',ISNULL(ch.apellido,'-----') as 'APELLIDO',ISNULL(ch.direccion,'-----') as 'DIRECCION',ISNULL(ch.telefono1,'-----') 'TELEFONO 1' ,ISNULL(ch.telefono2,'-----') 'TELEFONO 2' "
+ "from viaje v INNER JOIN pedido p on p.id_pedido=v.id_pedido INNER JOIN "
+ "camion c on c.id_camion=v.id_camion INNER JOIN marca_camion cm on cm.id=c.marca INNER JOIN tipo_camion ct on ct.id=c.tipo INNER JOIN modelo_camion mc on mc.id=c.modelo LEFT OUTER JOIN "
+ "acoplado a1 on a1.id_acoplado=v.id_acoplado1 LEFT OUTER JOIN marca_acoplado a1m on a1m.id=a1.marca LEFT OUTER JOIN tipo_acoplado a1t on a1t.id=a1.tipo LEFT OUTER JOIN "
+ "acoplado a2 on a2.id_acoplado=v.id_acoplado2 LEFT OUTER JOIN marca_acoplado a2m on a2m.id=a2.marca LEFT OUTER JOIN tipo_acoplado a2t on a2t.id=a2.tipo LEFT OUTER JOIN "
+ "chofer ch on p.id_chofer = ch.num_legajo "
+ "where p.nombre_cliente like '%"+cliente+"%'"
, usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
}
public DataTable Listar_Rangos_Salida(string desde, string hasta)
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("select v.id_viaje as 'ID',v.fecha_sal 'SALIDA',v.fecha_regre as 'REGRESO',ISNULL(v.observaciones,'-----') as 'OBSERVACIONES VIAJE',"
+ "ISNULL(p.nombre_cliente,'-----') as 'CLIENTE',ISNULL(p.cuil_cliente,'-----') as 'CUIL CLIENTE',p.fecha_sal_aprox as 'SALIDA APROXIMADA',p.fecha_reg_aprox as 'REGRESO APROXIMADO',p.peso_carga_aprox as 'PESO APROX',p.fecha_pedido as 'FECHA PEDIDO',p.observaciones as 'OBSERVACIONES PEDIDO',"
+ "ISNULL(c.dominio,'-----') as 'DOMINIO CAMION',ISNULL(cm.marca,'-----') as 'MARCA CAMION' ,ISNULL(ct.tipo,'-----') as 'TIPO CAMION',ISNULL(mc.modelo,'-----') as 'MODELO CAMION',"
+ "ISNULL(a1.dominio,'-----') as 'DOMINIO ACOPLADO',ISNULL(a1m.marca,'-----') as 'MARCA ACOPLADO',ISNULL(a1t.tipo,'-----') as 'TIPO ACOPLADO',"
+ "ISNULL(a2.dominio,'-----') as 'DOMINIO ACOPLADO',ISNULL(a2m.marca,'-----') as 'MARCA ACOPLADO',ISNULL(a2t.tipo,'-----') as 'TIPO ACOPLADO',"
+ "ISNULL(ch.num_legajo,-1) as 'LEGAJO',ISNULL(ch.nombre,'-----') as 'NOMBRE',ISNULL(ch.apellido,'-----') as 'APELLIDO',ISNULL(ch.direccion,'-----') as 'DIRECCION',ISNULL(ch.telefono1,'-----') 'TELEFONO 1' ,ISNULL(ch.telefono2,'-----') 'TELEFONO 2' "
+ "from viaje v INNER JOIN pedido p on p.id_pedido=v.id_pedido INNER JOIN "
+ "camion c on c.id_camion=v.id_camion INNER JOIN marca_camion cm on cm.id=c.marca INNER JOIN tipo_camion ct on ct.id=c.tipo INNER JOIN modelo_camion mc on mc.id=c.modelo LEFT OUTER JOIN "
+ "acoplado a1 on a1.id_acoplado=v.id_acoplado1 LEFT OUTER JOIN marca_acoplado a1m on a1m.id=a1.marca LEFT OUTER JOIN tipo_acoplado a1t on a1t.id=a1.tipo LEFT OUTER JOIN "
+ "acoplado a2 on a2.id_acoplado=v.id_acoplado2 LEFT OUTER JOIN marca_acoplado a2m on a2m.id=a2.marca LEFT OUTER JOIN tipo_acoplado a2t on a2t.id=a2.tipo LEFT OUTER JOIN "
+ "chofer ch on p.id_chofer = ch.num_legajo "
+ "where v.fecha_sal between try_parse('" + desde.ToString() + "' as datetime) and try_parse('" + hasta.ToString() + "' as datetime)"
, usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
}
public DataTable Listar_Fecha_Regreso(string desde, string hasta)
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("select v.id_viaje as 'ID',v.fecha_sal 'SALIDA',v.fecha_regre as 'REGRESO',ISNULL(v.observaciones,'-----') as 'OBSERVACIONES VIAJE',"
+ "ISNULL(p.nombre_cliente,'-----') as 'CLIENTE',ISNULL(p.cuil_cliente,'-----') as 'CUIL CLIENTE',p.fecha_sal_aprox as 'SALIDA APROXIMADA',p.fecha_reg_aprox as 'REGRESO APROXIMADO',p.peso_carga_aprox as 'PESO APROX',p.fecha_pedido as 'FECHA PEDIDO',p.observaciones as 'OBSERVACIONES PEDIDO',"
+ "ISNULL(c.dominio,'-----') as 'DOMINIO CAMION',ISNULL(cm.marca,'-----') as 'MARCA CAMION' ,ISNULL(ct.tipo,'-----') as 'TIPO CAMION',ISNULL(mc.modelo,'-----') as 'MODELO CAMION',"
+ "ISNULL(a1.dominio,'-----') as 'DOMINIO ACOPLADO',ISNULL(a1m.marca,'-----') as 'MARCA ACOPLADO',ISNULL(a1t.tipo,'-----') as 'TIPO ACOPLADO',"
+ "ISNULL(a2.dominio,'-----') as 'DOMINIO ACOPLADO',ISNULL(a2m.marca,'-----') as 'MARCA ACOPLADO',ISNULL(a2t.tipo,'-----') as 'TIPO ACOPLADO',"
+ "ISNULL(ch.num_legajo,-1) as 'LEGAJO',ISNULL(ch.nombre,'-----') as 'NOMBRE',ISNULL(ch.apellido,'-----') as 'APELLIDO',ISNULL(ch.direccion,'-----') as 'DIRECCION',ISNULL(ch.telefono1,'-----') 'TELEFONO 1' ,ISNULL(ch.telefono2,'-----') 'TELEFONO 2' "
+ "from viaje v INNER JOIN pedido p on p.id_pedido=v.id_pedido INNER JOIN "
+ "camion c on c.id_camion=v.id_camion INNER JOIN marca_camion cm on cm.id=c.marca INNER JOIN tipo_camion ct on ct.id=c.tipo INNER JOIN modelo_camion mc on mc.id=c.modelo LEFT OUTER JOIN "
+ "acoplado a1 on a1.id_acoplado=v.id_acoplado1 LEFT OUTER JOIN marca_acoplado a1m on a1m.id=a1.marca LEFT OUTER JOIN tipo_acoplado a1t on a1t.id=a1.tipo LEFT OUTER JOIN "
+ "acoplado a2 on a2.id_acoplado=v.id_acoplado2 LEFT OUTER JOIN marca_acoplado a2m on a2m.id=a2.marca LEFT OUTER JOIN tipo_acoplado a2t on a2t.id=a2.tipo LEFT OUTER JOIN "
+ "chofer ch on p.id_chofer = ch.num_legajo "
+ "where v.fecha_regre between try_parse('" + desde.ToString() + "' as datetime) and try_parse('" + hasta.ToString() + "' as datetime)"
, usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
}
public DataTable Listar_viajes_por_Unidad(string dominio)
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("select v.id_viaje as 'ID',v.fecha_sal 'SALIDA',v.fecha_regre as 'REGRESO',ISNULL(v.observaciones,'-----') as 'OBSERVACIONES VIAJE',"
+ "ISNULL(p.nombre_cliente,'-----') as 'CLIENTE',ISNULL(p.cuil_cliente,'-----') as 'CUIL CLIENTE',p.fecha_sal_aprox as 'SALIDA APROXIMADA',p.fecha_reg_aprox as 'REGRESO APROXIMADO',p.peso_carga_aprox as 'PESO APROX',p.fecha_pedido as 'FECHA PEDIDO',p.observaciones as 'OBSERVACIONES PEDIDO',"
+ "ISNULL(c.dominio,'-----') as 'DOMINIO CAMION',ISNULL(cm.marca,'-----') as 'MARCA CAMION' ,ISNULL(ct.tipo,'-----') as 'TIPO CAMION',ISNULL(mc.modelo,'-----') as 'MODELO CAMION',"
+ "ISNULL(a1.dominio,'-----') as 'DOMINIO ACOPLADO',ISNULL(a1m.marca,'-----') as 'MARCA ACOPLADO',ISNULL(a1t.tipo,'-----') as 'TIPO ACOPLADO',"
+ "ISNULL(a2.dominio,'-----') as 'DOMINIO ACOPLADO',ISNULL(a2m.marca,'-----') as 'MARCA ACOPLADO',ISNULL(a2t.tipo,'-----') as 'TIPO ACOPLADO',"
+ "ISNULL(ch.num_legajo,-1) as 'LEGAJO',ISNULL(ch.nombre,'-----') as 'NOMBRE',ISNULL(ch.apellido,'-----') as 'APELLIDO',ISNULL(ch.direccion,'-----') as 'DIRECCION',ISNULL(ch.telefono1,'-----') 'TELEFONO 1' ,ISNULL(ch.telefono2,'-----') 'TELEFONO 2' "
+ "from viaje v INNER JOIN pedido p on p.id_pedido=v.id_pedido INNER JOIN "
+ "camion c on c.id_camion=v.id_camion INNER JOIN marca_camion cm on cm.id=c.marca INNER JOIN tipo_camion ct on ct.id=c.tipo INNER JOIN modelo_camion mc on mc.id=c.modelo LEFT OUTER JOIN "
+ "acoplado a1 on a1.id_acoplado=v.id_acoplado1 LEFT OUTER JOIN marca_acoplado a1m on a1m.id=a1.marca LEFT OUTER JOIN tipo_acoplado a1t on a1t.id=a1.tipo LEFT OUTER JOIN "
+ "acoplado a2 on a2.id_acoplado=v.id_acoplado2 LEFT OUTER JOIN marca_acoplado a2m on a2m.id=a2.marca LEFT OUTER JOIN tipo_acoplado a2t on a2t.id=a2.tipo LEFT OUTER JOIN "
+ "chofer ch on p.id_chofer = ch.num_legajo "
+ " where c.dominio like '%"+dominio+ "%' or a1.dominio like '%" + dominio + "%' or a2.dominio like '%" + dominio + "%'"
, usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception e)
{
return null;
}
}
//public DataTable Listar_viajes_por_Acoplado(string dominio)
//{
// try
// {
// usuario.Modo(TipoConexion.Abrir);
// da = new SqlDataAdapter("select v.id_viaje as 'ID',v.fecha_sal 'SALIDA',v.fecha_regre as 'REGRESO',v.observaciones as 'OBSERVACIONES VIAJE' ,"
// + "p.nombre_cliente as 'CLIENTE',p.cuil_cliente as 'CUIL CLIENTE',p.fecha_sal_aprox as 'SALIDA APROXIMADA',p.fecha_reg_aprox as 'REGRESO APROXIMADO',p.peso_carga_aprox as 'PESO APROX',p.fecha_pedido as 'FECHA PEDIDO',p.observaciones as 'OBSERVACIONES PEDIDO',"
// + "c.dominio as 'DOMINIO CAMION',cm.marca as 'MARCA CAMION' ,ct.tipo as 'TIPO CAMION',"
// + "a1.dominio as 'DOMINIO ACOPLADO',a1m.marca as 'MARCA ACOPLADO', a1t.tipo as 'TIPO ACOPLADO',"
// + "a2.dominio as 'DOMINIO ACOPLADO',a2m.marca as 'MARCA ACOPLADO', a2t.tipo as 'TIPO ACOPLADO',"
// + "ch.num_legajo as 'LEGAJO',ch.nombre as 'NOMBRE',ch.apellido as 'APELLIDO',ch.telefono1 'TELEFONO 1' ,ch.telefono2 'TELEFONO 2' "
// + "from viaje v INNER JOIN pedido p on p.id_pedido=v.id_pedido INNER JOIN "
// + "camion c on c.id_camion=v.id_camion INNER JOIN marca_camion cm on cm.id=c.marca INNER JOIN tipo_camion ct on ct.id=c.tipo LEFT OUTER JOIN "
// + "acoplado a1 on a1.id_acoplado=v.id_acoplado1 LEFT OUTER JOIN marca_acoplado a1m on a1m.id=a1.marca LEFT OUTER JOIN tipo_acoplado a1t on a1t.id=a1.tipo LEFT OUTER JOIN "
// + "acoplado a2 on a2.id_acoplado=v.id_acoplado2 LEFT OUTER JOIN marca_acoplado a2m on a2m.id=a2.marca LEFT OUTER JOIN tipo_acoplado a2t on a2t.id=a2.tipo LEFT OUTER JOIN "
// + "chofer ch on p.id_chofer = ch.num_legajo"
// + "where a1.dominio ='" + dominio + "' or a2.dominio ='"+dominio+"'"
// , usuario.cnn);
// dt = new DataTable();
// da.Fill(dt);
// usuario.Modo(TipoConexion.Cerrar);
// return dt;
// }
// catch (Exception)
// {
// return null;
// }
//}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
namespace GestionTransporte.clases
{
public class clsMecanico
{
#region Atributos y Propiedades
clsLogin usuario;
int num_legajo;
string telefono1;
string telefono2;
string direccion;
string apellido;
string nombre;
DataTable dt;
SqlDataAdapter da;
public clsLogin Usuario
{
get { return usuario; }
set { usuario = value; }
}
public int Num_legajo
{
get { return num_legajo; }
set { num_legajo = value; }
}
public string Telefono1
{
get { return telefono1; }
set { telefono1 = value; }
}
public string Telefono2
{
get { return telefono2; }
set { telefono2 = value; }
}
public string Direccion
{
get { return direccion; }
set { direccion = value; }
}
public string Apellido
{
get { return apellido; }
set { apellido = value; }
}
public string Nombre
{
get { return nombre; }
set { nombre = value; }
}
public DataTable Dt
{
get { return dt; }
set { dt = value; }
}
#endregion
public clsMecanico(clsLogin usuario)
{
this.usuario = usuario;
dt = this.cargar_datos_tabla();
} //Constructor clase
public DataTable cargar_datos_tabla()
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("Select num_legajo,apellido,nombre ,telefono1,telefono", usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
} //Funcion que carga datos de la BD en DataTable
public DataView Listar_disponibles()
{
DataView dv = new DataView(dt);
dv.RowFilter = "estado='DISPONIBLE'";
return dv;
} //Funcion que lista todos los mecanicos disponibles
public DataTable Busqueda_Legajo(string legajo)
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("Select num_legajo,apellido,nombre ,telefono1,telefono2 from mecanico where num_legajo=" + legajo, usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
} //Funcion que busca mecanicos por Legajo
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace GestionTransporte.clases
{
public class clsMantemimiento
{
#region ATRIBUTOS
SqlDataAdapter da;
DataTable dt;
public DataTable Dt
{
get { return dt; }
set { dt = value; }
}
string id_taller;
public string Id_taller
{
get { return id_taller; }
set { id_taller = value; }
}
string id_unidad;
public string Id_unidad
{
get { return id_unidad; }
set { id_unidad = value; }
}
string tipo;
public string Tipo
{
get { return tipo; }
set { tipo = value; }
}
string estado;
public string Estado
{
get { return estado; }
set { estado = value; }
}
string num_legajo;
public string Num_legajo
{
get { return num_legajo; }
set { num_legajo = value; }
}
DateTime entrada;
public DateTime Entrada
{
get { return entrada; }
set { entrada = value; }
}
DateTime sal_aprox;
public DateTime Sal_aprox
{
get { return sal_aprox; }
set { sal_aprox = value; }
}
DateTime salida;
clsLogin usuario;
public DateTime Salida
{
get { return salida; }
set { salida = value; }
}
string descripcion;
public string Descripcion
{
get { return descripcion; }
set { descripcion = value; }
}
#endregion
public clsMantemimiento(clsLogin usuario)
{
this.usuario = usuario;
dt = this.cargar_datos_tabla();
} //Constructor de la clase
public string Alta()
{
string respuesta;
SqlTransaction sqlTran = usuario.cnn.BeginTransaction();
try
{
usuario.Modo(TipoConexion.Abrir);
SqlCommand cmd = new SqlCommand();
cmd.Transaction = sqlTran;
cmd.Connection = usuario.cnn;
cmd.CommandText = "insert into taller (num_legajo,entrada_taller,salida_aprox,salida,observaciones,estado,id_unidad,tipo) values ('" + num_legajo + "','" + DateTime.Now.ToString("yyyyMMdd") + "','" + sal_aprox.ToString("yyyyMMdd") + "','" + salida.ToString("yyyyMMdd") + "','" + descripcion + "','EN TALLER','" + id_unidad + "','" + tipo + "');SELECT Scope_Identity();";
cmd.CommandType = CommandType.Text;
string id_insertado = cmd.ExecuteScalar().ToString();
if (id_insertado != null)
{
if (tipo.Equals("CAMION"))//SI EL TIPO DE UNIDAD ES CAMION SE PROCEDE A MODIFICAR EL ESTADO DEL MISMO
{
cmd.CommandText = "update camion set estado='EN TALLER' where dominio='" + Id_unidad + "'";
cmd.ExecuteNonQuery();
}
else//SI EL TIPO DE UNIDAD ES ACOPLADO SE PROCEDE A MODIFICAR EL ESTADO DEL MISMO
{
cmd.CommandText = "update acoplado set estado='EN TALLER' where dominio='" + Id_unidad + "'";
cmd.ExecuteNonQuery();
}
cmd.CommandText = "insert into auditoria values ('" + (DateTime.Now).ToString() + "','" + usuario.Usuario + "','" + "se ingreso a taller el pedido :" + id_insertado + "')";
cmd.ExecuteNonQuery();
respuesta = string.Empty;
}
else
{
respuesta = "Error al dar de alta Mantenimiento";
}
sqlTran.Commit();
}
catch (Exception ex)
{
try
{
sqlTran.Rollback();
respuesta = "Error al dar de alta Mantenimiento";
}
catch
{
respuesta = "Error al dar de alta Mantenimiento";
}
}
usuario.Modo(TipoConexion.Cerrar);
return respuesta;
// todas las funciones de abm y otras se ejecutan con la propiedades y el login q pasamos por constructor
} //Funcion que da alta una unidad al taller
public string Entregar_Unidad()
{
string respuesta;
SqlTransaction sqlTran = usuario.cnn.BeginTransaction();
try
{
usuario.Modo(TipoConexion.Abrir);
SqlCommand cmd = new SqlCommand();
cmd.Transaction = sqlTran;
cmd.Connection = usuario.cnn;
cmd.CommandText = "update taller set estado = 'ENTREGADO' where id_taller='" + Id_taller + "';SELECT Scope_Identity();";
cmd.CommandType = CommandType.Text;
string id_insertado = cmd.ExecuteScalar().ToString();
if (id_insertado != null)
{
if (tipo.Equals("CAMION"))//SI EL TIPO DE UNIDAD ES CAMION SE PROCEDE A MODIFICAR EL ESTADO DEL MISMO
{
cmd.CommandText = "update camion set estado='DISPONIBLE' where dominio='" + Id_unidad + "'";
cmd.ExecuteNonQuery();
}
else//SI EL TIPO DE UNIDAD ES ACOPLADO SE PROCEDE A MODIFICAR EL ESTADO DEL MISMO
{
cmd.CommandText = "update acoplado set estado='DISPONIBLE' where dominio='" + Id_unidad + "'";
cmd.ExecuteNonQuery();
}
cmd.CommandText = "insert into auditoria values ('" + (DateTime.Now).ToString() + "','" + usuario.Usuario + "','" + "se entrego la unidad del pedido :" + id_insertado + "')";
cmd.ExecuteNonQuery();
respuesta = string.Empty;
}
else
{
respuesta = "Error al dar de alta Mantenimiento";
}
sqlTran.Commit();
}
catch (Exception ex)
{
try
{
sqlTran.Rollback();
respuesta = "Error al dar de alta Mantenimiento";
}
catch
{
respuesta = "Error al dar de alta Mantenimiento";
}
}
usuario.Modo(TipoConexion.Cerrar);
return respuesta;
}
public string baja()
{
string respuesta;
try
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = usuario.cnn;
cmd.CommandText ="update taller set estado='DADO DE BAJA' where id_taller='" + Id_taller + "';SELECT Scope_Identity();";
cmd.CommandType = CommandType.Text;
usuario.Modo(TipoConexion.Abrir);
string id_insertado = cmd.ExecuteScalar().ToString();
if (id_insertado != null)
{
cmd.CommandText = "insert into auditoria values ('" + (DateTime.Now).ToString() + "','" + usuario.Usuario + "','" + "elimino taller , registro id :" + id_insertado + "')";
cmd.ExecuteNonQuery();
respuesta = string.Empty;
usuario.cnn.Close();
}
else
{
respuesta = null;
}
}
catch (Exception e)
{
respuesta = null;
}
return respuesta;
// todas las funciones de abm y otras se ejecutan con la propiedades y el login q pasamos por constructor
} //Funcion que da baja una unidad del taller
public string modificacion()//si se cambia de responsable ,entonces se tiene que dar de baja ese pedido y hacer uno nuevo
{
string respuesta;
try
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = usuario.cnn;
cmd.CommandText = "update taller set salida_aprox='" + Sal_aprox + " ', observaciones ='" + Descripcion + "' where id_taller='" + Id_taller + "';SELECT Scope_Identity();";
cmd.CommandType = CommandType.Text;
usuario.Modo(TipoConexion.Abrir);
string id_insertado = cmd.ExecuteScalar().ToString();
if (id_insertado != null)
{
cmd.CommandText = "insert into auditoria values ('" + (DateTime.Now).ToString() + "','" + usuario.Usuario + "','" + "modifico unidad , registro id :" + id_insertado + "')";
cmd.ExecuteNonQuery();
respuesta = string.Empty;
usuario.cnn.Close();
}
else
{
respuesta = null;
}
}
catch (Exception e)
{
respuesta = null;
}
return respuesta;
// todas las funciones de abm y otras se ejecutan con la propiedades y el login q pasamos por constructor
}
public clsMantemimiento Retorna_Taller(string id)
{
try
{
clsMantemimiento taller= new clsMantemimiento(usuario);
SqlCommand cmd = new SqlCommand();
usuario.cnn.Open();
cmd.Connection = usuario.cnn;
cmd.CommandText = "Select * From taller where id_taller = '" + id+ "' ";
cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
taller.id_taller = dr[0].ToString();
taller.num_legajo = dr[1].ToString();
taller.entrada = Convert.ToDateTime(dr[2]);
taller.sal_aprox = Convert.ToDateTime(dr[3]);
taller.salida = Convert.ToDateTime(dr[4]);
taller.descripcion = dr[5].ToString();
taller.estado = dr[6].ToString();
taller.id_unidad = dr[7].ToString();
taller.tipo = dr[8].ToString().Trim();
}
usuario.cnn.Close();
return taller;
}
catch (Exception)
{
return null;
}
} //Funcion que retorna un objeto del tipo taller
public DataTable cargar_datos_tabla()
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("select t.id_taller as ID,t.tipo as 'TIPO',t.entrada_taller as 'INGRESO A TALLER',t.salida_aprox as 'SALIDA ESTIMADA',t.salida 'SALIDA',t.estado 'ESTADO',t.observaciones as 'TAREA',t.id_unidad as 'DOMINIO',"
+ "m.num_legajo as 'LEGAJO',m.telefono1 as 'telefono1',m.telefono2 as 'telefono2',m.estado as 'ESTADO MECANICO',m.direccion as 'DIRECCION',m.apellido + ' , '+ m.nombre as 'nombre'"
+ "from taller as t ,mecanico as m where t.num_legajo=m.num_legajo ", usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
} //Funcion que carga en un DataTable los datos de la BD
public DataTable listar_Todos()
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("select t.id_taller as ID,t.tipo as 'TIPO',t.entrada_taller as 'INGRESO A TALLER',t.salida_aprox as 'SALIDA ESTIMADA',t.salida 'SALIDA',t.estado 'ESTADO',t.observaciones as 'TAREA',t.id_unidad as 'DOMINIO',"
+ "m.num_legajo as 'LEGAJO',m.telefono1 as 'telefono1',m.telefono2 as 'telefono2',m.estado as 'ESTADO MECANICO',m.direccion as 'DIRECCION',m.apellido + ' , '+ m.nombre as 'nombre'"
+ "from taller as t ,mecanico as m where t.num_legajo=m.num_legajo ", usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
} //Funcion que carga todos los datos de DataTable en DataView
public DataTable listar_Proximos__A_Entregar()//listara a las unidades cuya salida_Aprox este en un rango entre la fecha actual y 4 dias posteriores
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("select t.id_taller as ID,t.tipo as 'TIPO',t.entrada_taller as 'INGRESO A TALLER',t.salida_aprox as 'SALIDA ESTIMADA',t.salida 'SALIDA',t.estado 'ESTADO',t.observaciones as 'TAREA',t.id_unidad as 'DOMINIO',"
+ "m.num_legajo as 'LEGAJO',m.telefono1 as 'telefono1',m.telefono2 as 'telefono2',m.estado as 'ESTADO MECANICO',m.direccion as 'DIRECCION',m.apellido + ' , '+ m.nombre as 'nombre'"
+ "from taller as t ,mecanico as m where t.num_legajo=m.num_legajo and t.salida_aprox between '" + DateTime.Now.ToString("yyyy-MM-dd") + "' and '" + DateTime.Now.AddDays(4).ToString("yyyy-MM-dd") + "'", usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
}
public DataTable listar_Entregados()
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("select t.id_taller as ID,t.tipo as 'TIPO',t.entrada_taller as 'INGRESO A TALLER',t.salida_aprox as 'SALIDA ESTIMADA',t.salida 'SALIDA',t.estado 'ESTADO',t.observaciones as 'TAREA',t.id_unidad as 'DOMINIO',"
+ "m.num_legajo as 'LEGAJO',m.telefono1 as 'telefono1',m.telefono2 as 'telefono2',m.estado as 'ESTADO MECANICO',m.direccion as 'DIRECCION',m.apellido + ' , '+ m.nombre as 'nombre'"
+ "from taller as t ,mecanico as m where t.num_legajo=m.num_legajo and t.estado='ENTREGADO' ", usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
} //Funcion que lista todos los entregados
public DataTable listar_En_Taller()
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("select t.id_taller as ID,t.tipo as 'TIPO',t.entrada_taller as 'INGRESO A TALLER',t.salida_aprox as 'SALIDA ESTIMADA',t.salida 'SALIDA',t.estado 'ESTADO',t.observaciones as 'TAREA',t.id_unidad as 'DOMINIO',"
+ "m.num_legajo as 'LEGAJO',m.telefono1 as 'telefono1',m.telefono2 as 'telefono2',m.estado as 'ESTADO MECANICO',m.direccion as 'DIRECCION',m.apellido + ' , '+ m.nombre as 'nombre'"
+ "from taller as t ,mecanico as m where t.num_legajo=m.num_legajo and t.estado='EN TALLER' ", usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
} //Funcion que lista todas las unidades en taller
public DataTable listar_Dados_De_Baja()//listara a las unidades cuya salida_Aprox este en un rango entre la fecha actual y 4 dias posteriores
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("select t.id_taller as ID,t.tipo as 'TIPO',t.entrada_taller as 'INGRESO A TALLER',t.salida_aprox as 'SALIDA ESTIMADA',t.salida 'SALIDA',t.estado 'ESTADO',t.observaciones as 'TAREA',t.id_unidad as 'DOMINIO',"
+ "m.num_legajo as 'LEGAJO',m.telefono1 as 'telefono1',m.telefono2 as 'telefono2',m.estado as 'ESTADO MECANICO',m.direccion as 'DIRECCION',m.apellido + ' , '+ m.nombre as 'nombre'"
+ "from taller as t ,mecanico as m where t.num_legajo=m.num_legajo and t.estado='DADO DE BAJA' ", usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
}
public DataTable Busqueda_fecha_carga(string desde, string hasta)
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("select t.id_taller as ID,t.tipo as 'TIPO',t.entrada_taller as 'INGRESO A TALLER',t.salida_aprox as 'SALIDA ESTIMADA',t.salida 'SALIDA',t.estado 'ESTADO',t.observaciones as 'TAREA',t.id_unidad as 'DOMINIO',"
+ "m.num_legajo as 'LEGAJO',m.telefono1 as 'telefono1',m.telefono2 as 'telefono2',m.estado as 'ESTADO MECANICO',m.direccion as 'DIRECCION',m.apellido + ' , '+ m.nombre as 'nombre'"
+ "from taller as t ,mecanico as m where t.num_legajo=m.num_legajo and TRY_PARSE(t.entrada_taller as datetime) between '" + desde + "' and '" + hasta + "' ", usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
} //Funcion que busca unidades segun fecha de carga
public DataTable Busqueda_fecha_salida_aprox(string desde, string hasta)
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("select t.id_taller as ID,t.tipo as 'TIPO',t.entrada_taller as 'INGRESO A TALLER',t.salida_aprox as 'SALIDA ESTIMADA',t.salida 'SALIDA',t.estado 'ESTADO',t.observaciones as 'TAREA',t.id_unidad as 'DOMINIO',"
+ "m.num_legajo as 'LEGAJO',m.telefono1 as 'telefono1',m.telefono2 as 'telefono2',m.estado as 'ESTADO MECANICO',m.direccion as 'DIRECCION',m.apellido + ' , '+ m.nombre as 'nombre'"
+ "from taller as t ,mecanico as m where t.num_legajo=m.num_legajo and TRY_PARSE(t.salida_aprox as datetime) between '" + desde + "' and '" + hasta + "' ", usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
} //Funcion que busca unidades segun fecha de salida
public DataView Busqueda_dominio(string dominio)
{
DataView dv = new DataView(dt);
dv.RowFilter = "DOMINIO like '" + dominio + "%'";
return dv;
} //Funcion que busca unidades por dominio
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
using System.Collections;
namespace GestionTransporte.clases
{
public class clsMarca_acoplado
{
#region Atributos y Propiedades
string marca;
string estado;
clsLogin usuario;
public string Marca
{
get { return marca; }
set { marca = value; }
}
public string Estado
{
get { return estado; }
set { estado = value; }
}
#endregion
public clsMarca_acoplado(clsLogin usuario)
{
this.usuario = usuario;
} //Constructor de la clase
public string insertar()
{
string respuesta = string.Empty;
SqlCommand cmd = new SqlCommand();
try
{
cmd.Connection = usuario.cnn;
cmd.CommandText = "insert into marca_acoplado values ('" + Marca + "','" + Estado + "');SELECT Scope_Identity();";
cmd.CommandType = CommandType.Text;
usuario.Modo(TipoConexion.Abrir);
string id_insertado = cmd.ExecuteScalar().ToString();
if (id_insertado != null)
{
cmd.CommandText = "insert into auditoria values ('" + (DateTime.Now).ToString() + "','" + usuario.Usuario + "','" + "se inserto la marca de acoplado " + Marca + "')";
cmd.ExecuteNonQuery();
respuesta = string.Empty;
}
else
{
respuesta = "Error al insertar marca";
}
}
catch (SqlException e)
{
if (e.ErrorCode == -2146232060)
{
respuesta = "YA EXISTE ESA MARCA ";
}
}
usuario.Modo(TipoConexion.Cerrar);
return respuesta;
} //Funcion para insertar nueva marca de acoplado
public string modificar(string vieja)
{
string respuesta;
SqlCommand cmd = new SqlCommand();
try
{
cmd.Connection = usuario.cnn;
cmd.CommandText = "update marca_acoplado set marca='" + Marca + "' where marca='" + vieja + "';SELECT Scope_Identity();";
cmd.CommandType = CommandType.Text;
usuario.Modo(TipoConexion.Abrir);
string id_insertado = cmd.ExecuteScalar().ToString();
if (id_insertado != null)
{
cmd.CommandText = "insert into auditoria values ('" + (DateTime.Now).ToString() + "','" + usuario.Usuario + "','" + "se modifico la marca dde acoplado " + vieja + " a " + Marca + "')";
cmd.ExecuteNonQuery();
respuesta = string.Empty;
}
else
{
respuesta = "Error al modificar marca";
}
}
catch (SqlException e)
{
respuesta = e.ErrorCode.ToString();
}
usuario.Modo(TipoConexion.Cerrar);
return respuesta;
} //Funcion para modificar una marca ya insertada
public DataTable ver_marcas()
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = usuario.cnn;
cmd.CommandText = "select marca as MARCAS from marca_acoplado order by marca asc";
cmd.CommandType = CommandType.Text;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
DataTable datatable = new DataTable();
adapter.Fill(datatable);
return datatable;
} //Funcion que retorna las marcas disponibles en BD a un DataTable
public string eliminar(string marca)
{
string respuesta;
SqlCommand cmd = new SqlCommand();
try
{
cmd.Connection = usuario.cnn;
cmd.CommandText = "update marca_acoplado set marca='DESAHABILITADO' where marca='" + marca + "';SELECT Scope_Identity();";
cmd.CommandType = CommandType.Text;
usuario.Modo(TipoConexion.Abrir);
int id_insertado = cmd.ExecuteNonQuery();
if (id_insertado != 0)
{
cmd.CommandText = "insert into auditoria values ('" + (DateTime.Now).ToString() + "','" + usuario.Usuario + "','" + "elimino la marca de acoplado" + Marca + "')";
cmd.ExecuteNonQuery();
respuesta = string.Empty;
}
else
{
respuesta = "Error al eliminar marca,ya existe una unidad utilizando esta marca";
}
}
catch (SqlException)
{
respuesta = "Error al eliminar marca,ya existe una unidad utilizando esta marca";
}
usuario.Modo(TipoConexion.Cerrar);
return respuesta;
} //Funcion que elimina una marca
public int retornaID_marca(string marca)
{
int retorno = -1;
SqlCommand cmd = new SqlCommand();
usuario.cnn.Open();
cmd.Connection = usuario.cnn;
cmd.CommandText = "select id from marca_acoplado where marca='" + marca + "' ";
cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
retorno = Convert.ToInt32(dr[0]);
}
usuario.cnn.Close();
return retorno;
} //Funcion que retorna el ID de marca segun sea su nombre
public String retornaMarca(int id)
{
string retorno = string.Empty;
SqlCommand cmd = new SqlCommand();
usuario.cnn.Open();
cmd.Connection = usuario.cnn;
cmd.CommandText = "select marca from marca_acoplado where id='" + id + "' ";
cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
retorno = dr[0].ToString();
}
usuario.cnn.Close();
return retorno;
} //Funcion que retorna la marca segun su ID
}
}
<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 GestionTransporte.clases;
using System.Data.SqlClient;
namespace GestionTransporte.vistas
{
public partial class frmModificaViaje : Form
{
clsViaje viaje;
clsCamion camion;
clsAcoplado acoplado1;
clsAcoplado acoplado2;
String senderRecibido;
public frmModificaViaje(clsViaje viaje, clsCamion camion, clsAcoplado acoplado1, clsAcoplado acoplado2, String sender)
{
InitializeComponent();
this.viaje = viaje;
this.camion = camion;
this.acoplado1 = acoplado1;
this.acoplado2 = acoplado2;
this.senderRecibido = sender;
}
private void frmModificaViaje_Load(object sender, EventArgs e)
{
if (senderRecibido == "btnModificarViaje")
{
if (this.camion != null)
{
pnlCamion.Enabled = true;
pnlCamion.BackColor = Color.IndianRed;
lblCamion.Text = camion.Dominio;
}
if (this.acoplado1 != null)
{
pnlAcoplado1.Enabled = true;
pnlAcoplado1.BackColor = Color.IndianRed;
lblAcoplado1.Text = acoplado1.Dominio;
}
if (this.acoplado2 != null)
{
pnlAcoplado2.Enabled = true;
pnlAcoplado2.BackColor = Color.IndianRed;
lblAcoplado2.Text = acoplado2.Dominio;
}
//PROBANDO EL FORMATO DE FECHAS
if (viaje.Fecha_Sal == null)
{
dtpFecha_sal.Value = DateTime.Now;
}
else
{
dtpFecha_sal.Value = viaje.Fecha_Sal;
dtpHr_sal.Value = Convert.ToDateTime(viaje.Fecha_Sal.ToShortTimeString());
}
if (dtFecha_reg == null)
{
dtFecha_reg.Value = DateTime.Now;
}
else
{
dtFecha_reg.Value = viaje.Fecha_Regre;
dtpHr_reg.Value = Convert.ToDateTime(viaje.Fecha_Regre.ToShortTimeString());
}
//Observaciones
tbObservaciones.Text = viaje.Observaciones;
}
else
{
if (this.camion != null)
{
pnlCamion.BackColor = Color.IndianRed;
lblCamion.Text = camion.Dominio;
chCamion.Checked = true;
}
if (this.acoplado1 != null)
{
pnlAcoplado1.BackColor = Color.IndianRed;
lblAcoplado1.Text = acoplado1.Dominio;
chAcoplado1.Checked = true;
}
if (this.acoplado2 != null)
{
pnlAcoplado2.BackColor = Color.IndianRed;
lblAcoplado2.Text = acoplado2.Dominio;
chAcoplado2.Checked = true;
}
//PROBANDO EL FORMATO DE FECHAS
if (viaje.Fecha_Sal == null)
{
dtpFecha_sal.Value = DateTime.Now;
dtpFecha_sal.Enabled = false;
}
else
{
dtpFecha_sal.Value = viaje.Fecha_Sal;
dtpHr_sal.Value = Convert.ToDateTime(viaje.Fecha_Sal.ToShortTimeString());
dtpFecha_sal.Enabled = false;
dtpHr_sal.Enabled = false;
}
if (dtFecha_reg == null)
{
dtFecha_reg.Value = DateTime.Now;
dtFecha_reg.Enabled = false;
}
else
{
dtFecha_reg.Value = viaje.Fecha_Regre;
dtpHr_reg.Value = Convert.ToDateTime(viaje.Fecha_Regre.ToShortTimeString());
dtFecha_reg.Enabled = false;
dtpHr_reg.Enabled = false;
}
//Observaciones
tbObservaciones.Text = viaje.Observaciones;
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
DialogResult result;
if (sender == btnCancel) {
result = MessageBox.Show("Seguro desea salir?", "Confirmacion", MessageBoxButtons.YesNoCancel);
if (result == DialogResult.Yes)
{
this.Close();
}
}
if (sender == btnOk)
{
if (senderRecibido == "btnModificarViaje")
{
if (chCamion.Checked)
{
viaje.Id_camion = camion.Id;
}
if (chAcoplado1.Checked)
{
viaje.Id_acoplado1 = acoplado1.Id;
}
if (chAcoplado2.Checked)
{
viaje.Id_acoplado2 = acoplado2.Id;
}
DateTime salida = new DateTime(dtpFecha_sal.Value.Year, dtpFecha_sal.Value.Month, dtpFecha_sal.Value.Day, dtpHr_sal.Value.Hour, dtpHr_sal.Value.Minute, 00);
DateTime regreso = new DateTime(dtFecha_reg.Value.Year, dtFecha_reg.Value.Month, dtFecha_reg.Value.Day, dtpHr_reg.Value.Hour, dtpHr_reg.Value.Minute, 00);
viaje.Observaciones = tbObservaciones.Text;
viaje.modificar();
}
else
{
if (chCamion.Checked)
{
viaje.Id_camion = camion.Id;
if (camion.retorna_Estado()!="RESERVADO")
camion.Estado = "DISPONIBLE";
}
if (chAcoplado1.Checked)
{
viaje.Id_acoplado1 = acoplado1.Id;
if (acoplado1.retorna_Estado() != "RESERVADO")
acoplado1.Estado = "DISPONIBLE";
}
if (chAcoplado2.Checked)
{
viaje.Id_acoplado2 = acoplado2.Id;
if (acoplado2.retorna_Estado() != "RESERVADO")
acoplado2.Estado = "DISPONIBLE";
}
DateTime salida = new DateTime(dtpFecha_sal.Value.Year, dtpFecha_sal.Value.Month, dtpFecha_sal.Value.Day, dtpHr_sal.Value.Hour, dtpHr_sal.Value.Minute, 00);
DateTime regreso = new DateTime(dtFecha_reg.Value.Year, dtFecha_reg.Value.Month, dtFecha_reg.Value.Day, dtpHr_reg.Value.Hour, dtpHr_reg.Value.Minute, 00);
viaje.Observaciones = tbObservaciones.Text;
viaje.baja();
}
}
}
}
}
<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 GestionTransporte.clases;
using System.Data.SqlClient;
namespace GestionTransporte
{
public partial class frmCargaTaller : Form
{
string accion;
clsLogin conexion;
clsMecanico mecanico;
string dominio;
DataTable dt;
clsMantemimiento taller;
string tipo;
delegadoActualizaListaTaller delegadoActualizaLista;
string alta_baja;
public frmCargaTaller(string dominio,string tipo,clsLogin user,clsMantemimiento t,string accion,Delegate actualizarLista,string alta_baja)
{
//alta baja se va a utilizar para por ejemplo,si el pedido va a ser mofigicado para dar de alta un pedido ,osea la unidad esta reparada
//y vuelve al estado disponible,entonces se modifica y al dar el okey la accion se hace desde aqui
InitializeComponent();
this.dominio = dominio;
this.alta_baja = alta_baja;
mecanico = new clsMecanico(user);
this.Enabled = true;
conexion = user;
this.tipo = tipo;
this.taller = t;
this.accion = accion;
delegadoActualizaLista = (delegadoActualizaListaTaller)actualizarLista;
}
private void frmCargaTaller_Load(object sender, EventArgs e)
{
if (taller != null)
{
tbLegajo.Text = taller.Num_legajo;
dt = mecanico.Busqueda_Legajo(tbLegajo.Text);
if (dt != null)
{
lblNombreResponsable.Text = dt.Rows[0][1].ToString() + ", " + dt.Rows[0][2].ToString();
tbLegajo.Text = taller.Num_legajo;
tbDescripcion.Text = taller.Descripcion;
lblDominio.Text = taller.Id_unidad;
dtpSalAprox.Value = taller.Sal_aprox;
tbLegajo.Enabled = false;
btnOkLegajo.Enabled = false;
btnCambiarlegajo.Enabled = true;
}
}
else
{
btnCambiarlegajo.Enabled = false;
}
}
private void button1_Click(object sender, EventArgs e)
{
if (sender == btnOkLegajo)
{
dt = mecanico.Busqueda_Legajo(tbLegajo.Text);
if (dt != null)
{
tbLegajo.Enabled = false;
btnOkLegajo.Enabled = false;
btnCambiarlegajo.Enabled = true;
lblNombreResponsable.Text = dt.Rows[0][1].ToString() + ", " + dt.Rows[0][2].ToString();
}
}
if (sender == btnCambiarlegajo)
{
tbLegajo.Enabled = true;
btnOkLegajo.Enabled = true;
btnCambiarlegajo.Enabled = false;
}
if (sender == btnSalir)
{
DialogResult dialogResult = MessageBox.Show("Salir", "Seguro desea salir ?", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
this.Close();
}
}
if (sender == btnGuardar)
{
if (taller == null)
{
taller = new clsMantemimiento(conexion);
taller.Descripcion = tbDescripcion.Text;
taller.Id_unidad = this.dominio;
taller.Sal_aprox = dtpSalAprox.Value;
taller.Num_legajo = tbLegajo.Text;
taller.Tipo = tipo;
taller.Estado = "DISPONIBLE";
if (taller.Alta() == null)
{
MessageBox.Show("no se inserto nada");
}
else
{
MessageBox.Show("GUARDADO");
}
delegadoActualizaLista();
}
else
{
taller.Descripcion = tbDescripcion.Text;
taller.Id_unidad = this.dominio;
taller.Sal_aprox = dtpSalAprox.Value;
taller.Num_legajo = tbLegajo.Text;
taller.Tipo = tipo;
taller.Estado = "DISPONIBLE";
if (taller.modificacion() != null)
{
if (alta_baja.Equals("ALTA"))
{
if (taller.Entregar_Unidad() == string.Empty)
{
MessageBox.Show("SE MODIFICO Y SE DIO DE ALTA LA UNIDAD");
}
else
{
MessageBox.Show("ERROR AL DAR DE ALTA LA UNIDAD");
}
}
if (alta_baja.Equals("BAJA"))
{
if (taller.baja() == string.Empty)
{
MessageBox.Show("SE MODIFICO Y SE DIO DE BAJA EL PEDIDO");
}
else
{
MessageBox.Show("ERROR AL DAR DE BAJA EL PEDIDO");
}
}
if (alta_baja == null)
{
MessageBox.Show("MODIFICADO");
}
}
else
{
MessageBox.Show("ERROR AL MODIFICAR");
}
delegadoActualizaLista();
}
//id unidad en carga de taller lo tomamos como dominio
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GestionTransporte.CLASES;
namespace GestionTransporte.clases
{
public class CamionAcoplado
{
Login usuario;//el usuario trae consigo la coneccion a la bd
Camion camion;
Acoplado acoplado;
#region encapsulamiento de propiedades
public Camion Camion
{
get { return camion; }
set { camion = value; }
}
public Acoplado Acoplado
{
get { return acoplado; }
set { acoplado = value; }
}
#endregion
}
}
<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.SqlClient;
using GestionTransporte.clases;
using GestionTransporte.vistas;
using System.Threading;
namespace GestionTransporte
{
public delegate void delegadoActualizaListaCamiones();
public delegate void delegadoActualizaListaAcoplados();
public delegate void delegadoActualizaListaTaller();
public delegate void delegado_ALTA_TallerDesdeFormModificar();
public delegate void delegado_BAJA_TallerDesdeFormModificar();
public delegate void seleccionPedido(String id);
public partial class frmAdmin : Form
{
clsLogin conexion;
DataTable dtTaller;
DataTable dtCamion;
DataTable dtAcoplado;
DataTable dtViaje;
clsPedido pedido;
clsCamion camion;
clsAcoplado acoplado;
clsMantemimiento taller;
clsViaje viaje;
delegadoActualizaListaCamiones actualizarCamiones;
delegadoActualizaListaAcoplados actualizarAcoplados;
delegadoActualizaListaTaller actualizarTaller;
string idPedido=null;
string idCamion=null;
string idAcoplado1=null;
string idAcoplado2=null;
//VARIABLES UTILIZADAS (POR BOTONES LLAVE ROJA) PARA CARGA DE UNIDAD (CAMION/ACOPLADO) A MANTENIMIENTO
/////////////////////////////////////////
public frmAdmin(clsLogin conexion)
{
InitializeComponent();
this.conexion = conexion;
camion = new clsCamion(conexion);
acoplado = new clsAcoplado(conexion);
taller = new clsMantemimiento(conexion);
pedido = new clsPedido(conexion);
viaje = new clsViaje(conexion);
Verifica_dgv_vacio_acoplado();
Verifica_dgv_vacio_camion();
actualizarCamiones = delegate()//metodo anonimo para actualizar lista de camiones despues de agregar/modificar una unidad
{
cbCamionListar.SelectedIndex = 0;
cbCamionListar_SelectedIndexChanged(cbCamionListar, null);
};
actualizarAcoplados = delegate()//metodo anonimo para actualizar lista de acoplados despues de agregar/modificar una unidad
{
cbAcopladoListar.SelectedIndex = 0;
cbCamionListar_SelectedIndexChanged(cbAcopladoListar, null);
};
actualizarTaller = delegate()
{
cbMantenimientoListar.SelectedIndex = 0;
cbCamionListar_SelectedIndexChanged(cbMantenimientoListar, null);
cbCamionListar_SelectedIndexChanged(cbAcopladoListar, null);
cbCamionListar_SelectedIndexChanged(cbCamionListar, null);
};
}
private void frmAdmin_Load(object sender, EventArgs e)
{
//inicializa combobox ,hace visible o invisible los objetos segun la busqueda *(por fecha,dominio ,etc )
cbCamionListar.SelectedIndex = 0;
cbCamionBuscar.SelectedIndex = 0;
tbCamionBuscar.Visible = false;
pnlCamionBuscar.Visible = false;
cbAcopladoBuscar.SelectedIndex = 0;
cbAcopladoListar.SelectedIndex = 0;
tbAcopladoBuscar.Visible = false;
pnlAcopladoBuscar.Visible = false;
//dgvViajes.Columns[1].Width = 132;
//dgvViajes.Columns[2].Width = 132;
//dgvViajes.Columns[6].Width = 132;
//dgvViajes.Columns[7].Width = 131;
//dgvViajes.Columns[9].Width = 131;
//MANTENIMIENTO *************************
cbMantenimientoListar.SelectedIndex = 0;
tbMantenimientoBuscar.Visible = false;
pnlMantDtp.Visible = false;
//VIAJE ********************************
cbViajeListar.SelectedIndex = 0;
tbViajeBuscar.Visible = false;
pnlViajeBuscar.Visible = false;
cbViajeBuscar.SelectedIndex = 0;
}
private void frmAdmin_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
}
///funciones que verifican si los DGV estan vacios
#region ACOPLADO
public void Verifica_dgv_vacio_acoplado()//si no hay resultados en la grilla esta funcion deshabilita los botones q se usan para seleccionar o algo de la grilla
{
if (dgvAcoplado.Rows.Count < 1)
{
btnSelecAcoplado1.Enabled = false;
btnSelectManAcoplado.Enabled = false;
btnModificarAcoplado.Enabled = false;
btnBajaAcoplado.Enabled = false;
//MessageBox.Show("NO SE ENCONTRARON RESULTADOS PARA ACOPLADOS");
dgvAcoplado.BackgroundColor = Color.OrangeRed;
Limpia_Objetos_Cargados_Con_Bindings_Acoplado();
}
else
{
btnSelecAcoplado1.Enabled = true;
btnSelectManAcoplado.Enabled = true;
btnModificarAcoplado.Enabled = true;
btnBajaAcoplado.Enabled = true;
dgvAcoplado.BackgroundColor = Color.DarkGray;
}
}
public void carga_acoplados_total()
{//este metodo reune a todos los demas metodos para la caga total de los acoplados
dgvAcoplado.DataSource = acoplado.carga_acoplados_total();
ColumnasInvisiblesAcoplado();
Carga_datos_Acoplado_a_label();
}
private void ColumnasInvisiblesAcoplado()
{
dgvAcoplado.Columns[4].Visible = false;
dgvAcoplado.Columns[6].Visible = false;
dgvAcoplado.Columns[7].Visible = false;
dgvAcoplado.Columns[8].Visible = false;
dgvAcoplado.Columns[9].Visible = false;
dgvAcoplado.Columns[10].Visible = false;
dgvAcoplado.Columns[11].Visible = false;
dgvAcoplado.Columns[12].Visible = false;
dgvAcoplado.Columns[14].Visible = false;
dgvAcoplado.Columns[15].Visible = false;
dgvAcoplado.Columns[16].Visible = false;
dgvAcoplado.Columns[17].Visible = false;
}
void Limpia_Objetos_Cargados_Con_Bindings_Acoplado()
{
lbAcopladoTara.Text = "------";
lbAcopladoCapCarga.Text = "------";
lbAcopladoNroChasis.Text = "------";
lbAcopladoLongPlat.Text = "------";
lbAcopladoAnchoInt.Text = "------";
lbAcopladoAnchoExt.Text = "------";
lbAcopladoAlturaTot.Text = "------";
lbAcopladoCantEjes.Text = "------";
lbAcopladoObservaciones.Text = "------";
lbAcopladoFechaAlta.Text = "------";
lbAcopladoFechaBaja.Text = "------";
}
void Limpia_Bindings_Acoplado()
{
lbAcopladoTara.DataBindings.Clear();
lbAcopladoCapCarga.DataBindings.Clear();
lbAcopladoNroChasis.DataBindings.Clear();
lbAcopladoLongPlat.DataBindings.Clear();
lbAcopladoAnchoInt.DataBindings.Clear();
lbAcopladoAnchoExt.DataBindings.Clear();
lbAcopladoAlturaTot.DataBindings.Clear();
lbAcopladoCantEjes.DataBindings.Clear();
lbAcopladoObservaciones.DataBindings.Clear();
lbAcopladoFechaAlta.DataBindings.Clear();
lbAcopladoFechaBaja.DataBindings.Clear();
}
private void Carga_datos_Acoplado_a_label()
{
Limpia_Bindings_Acoplado();
if (dtAcoplado != null)
{
lbAcopladoTara.DataBindings.Add(new Binding("Text", dtAcoplado, "tara"));
lbAcopladoNroChasis.DataBindings.Add(new Binding("Text", dtAcoplado, "nro_chasis"));
lbAcopladoLongPlat.DataBindings.Add(new Binding("Text", dtAcoplado, "long_plataforma"));
lbAcopladoAnchoInt.DataBindings.Add(new Binding("Text", dtAcoplado, "ancho_interior"));
lbAcopladoAnchoExt.DataBindings.Add(new Binding("Text", dtAcoplado, "ancho_exterior"));
lbAcopladoAlturaTot.DataBindings.Add(new Binding("Text", dtAcoplado, "alt_total"));
lbAcopladoCapCarga.DataBindings.Add(new Binding("Text", dtAcoplado, "capacidad_carga"));
lbAcopladoCantEjes.DataBindings.Add(new Binding("Text", dtAcoplado, "cant_ejes"));
lbAcopladoObservaciones.DataBindings.Add(new Binding("Text", dtAcoplado, "observaciones"));
lbAcopladoFechaAlta.DataBindings.Add(new Binding("Text", dtAcoplado, "fecha_alta"));
lbAcopladoFechaBaja.DataBindings.Add(new Binding("Text", dtAcoplado, "fecha_baja"));
}
}
private void btnNuevoAcoplado_Click(object sender, EventArgs e)
{
new GestionTransporte.frmCargaAcoplado(conexion, null, actualizarAcoplados).ShowDialog();
}
private void btnBajaAcoplado_Click(object sender, EventArgs e)
{
string dom = dgvAcoplado.CurrentRow.Cells[0].Value.ToString();
string estado = dgvAcoplado.CurrentRow.Cells[5].Value.ToString();
string resp = acoplado.dar_baja(dom, estado);
if (resp == String.Empty)
{
this.carga_acoplados_total();
MessageBox.Show("Acoplado dado de baja");
}
else
MessageBox.Show(resp);
}
private void btnModificarAcoplado_Click(object sender, EventArgs e)
{
acoplado = new clsAcoplado(conexion);
if (dgvCamion.RowCount > 0)
{
string dom = dgvAcoplado.CurrentRow.Cells[0].Value.ToString();
acoplado = acoplado.Retorna_acoplado(dom);
new GestionTransporte.frmCargaAcoplado(conexion, acoplado, actualizarAcoplados).ShowDialog();
}
else
MessageBox.Show("NO HAY ACOPLADOS PARA MODIFICAR");
acoplado.listar_todo();
}
#endregion
#region CAMIONES
public void Verifica_dgv_vacio_camion()
{
if (dgvCamion.Rows.Count < 1)
{
btnBajaCamion.Enabled = false;
btnModificarCamion.Enabled = false;
btnSelecCamion.Enabled = false;
btnSelecMantCamion.Enabled = false;
//MessageBox.Show("NO SE ENCONTRARON RESULTADOS PARA CAMIONES");
dgvCamion.BackgroundColor = Color.Red;
Limpia_Objetos_Cargados_Con_Bindings_Camion();
}
else
{
btnBajaCamion.Enabled = true;
btnModificarCamion.Enabled = true;
btnSelecCamion.Enabled = true;
btnSelecMantCamion.Enabled = true;
dgvCamion.BackgroundColor = Color.DarkGray;
}
}
public void carga_camiones_total() {//este metodo reune a todos los demas metodos para la caga total de los camiones
dgvCamion.DataSource = camion.carga_camiones_total();
ColumnasInvisiblesCamion();
Carga_datos_Camion_a_label();
}
private void ColumnasInvisiblesCamion()
{
dgvCamion.Columns[6].Visible = false;
dgvCamion.Columns[7].Visible = false;
dgvCamion.Columns[8].Visible = false;
dgvCamion.Columns[9].Visible = false;
dgvCamion.Columns[10].Visible = false;
dgvCamion.Columns[11].Visible = false;
dgvCamion.Columns[12].Visible = false;
dgvCamion.Columns[13].Visible = false;
dgvCamion.Columns[14].Visible = false;
dgvCamion.Columns[15].Visible = false;
dgvCamion.Columns[16].Visible = false;
}//escondo las columnas q no se tendrian q ver porq se salen del ancho del dgv
private void Limpia_Objetos_Cargados_Con_Bindings_Camion(){
lbCamionTara.Text = "------";
lbCamionNroChasis.Text = "------";
lbCamionNroMotor.Text = "------";
lbCamionAltTotal.Text = "------";
lbCamionAnchoTot.Text = "------";
lbCamionLongTotal.Text = "------";
lbCamionObservaciones.Text = "------";
lbCamionFechaAlta.Text = "------";
lbCamionFechaBaja.Text = "------";
}
private void Limpia_Bindings_Camion()
{
lbCamionTara.DataBindings.Clear();
lbCamionNroChasis.DataBindings.Clear();
lbCamionNroMotor.DataBindings.Clear();
lbCamionAltTotal.DataBindings.Clear();
lbCamionAnchoTot.DataBindings.Clear();
lbCamionLongTotal.DataBindings.Clear();
lbCamionObservaciones.DataBindings.Clear();
lbCamionFechaAlta.DataBindings.Clear();
lbCamionFechaBaja.DataBindings.Clear();
}
private void Carga_datos_Camion_a_label()
{
Limpia_Bindings_Camion();
if (dtCamion!=null)
{
lbCamionTara.DataBindings.Add(new Binding("Text", dtCamion, "tara"));
lbCamionNroChasis.DataBindings.Add(new Binding("Text", dtCamion, "nro_chasis"));
lbCamionNroMotor.DataBindings.Add(new Binding("Text", dtCamion, "nro_motor"));
lbCamionAltTotal.DataBindings.Add(new Binding("Text", dtCamion, "alt_total")); ;
lbCamionAnchoTot.DataBindings.Add(new Binding("Text", dtCamion, "ancho_total"));
lbCamionLongTotal.DataBindings.Add(new Binding("Text", dtCamion, "long_total"));
lbCamionObservaciones.DataBindings.Add(new Binding("Text", dtCamion, "observaciones"));
lbCamionFechaAlta.DataBindings.Add(new Binding("Text", dtCamion, "fecha_alta"));
lbCamionFechaBaja.DataBindings.Add(new Binding("Text", dtCamion, "fecha_baja"));
}
}
private void btnNuevoCamion_Click(object sender, EventArgs e)
{
new GestionTransporte.frmCargaCamion(conexion, null, actualizarCamiones).ShowDialog();
}
private void btnBajaCamion_Click(object sender, EventArgs e)
{
string dom = dgvCamion.CurrentRow.Cells[0].Value.ToString();
string estado = dgvCamion.CurrentRow.Cells[5].Value.ToString();
string resp = camion.dar_baja(dom, estado);
if (resp == String.Empty)
{
this.carga_camiones_total();
MessageBox.Show("Camion dado de baja");
}
else
MessageBox.Show(resp);
}
private void btnModificarCamion_Click(object sender, EventArgs e)
{
camion = new clsCamion(conexion);
if (dgvCamion.RowCount > 0)
{
string dom = dgvCamion.CurrentRow.Cells[0].Value.ToString();
camion = camion.Retorna_camion(dom);
new GestionTransporte.frmCargaCamion(conexion, camion, actualizarCamiones).ShowDialog();
}
else
MessageBox.Show("NO HAY CAMIONES PARA MODIFICAR");
camion.carga_camiones_total();
}
#endregion
#region TALLER
private void btnMantModificar_Click(object sender, EventArgs e)
{
string estado=dgvMantenimiento.CurrentRow.Cells[5].Value.ToString().Trim();//se utiliza para corrobaorar ,dependiendo del estado ,si se pueden tomar ciertas acciones ,como modificar por ejemplo
if (sender == btnMantModificar)
{
if (estado.Equals("EN TALLER"))
{
taller = new clsMantemimiento(conexion);
string id = dgvMantenimiento.CurrentRow.Cells[0].Value.ToString();
taller = taller.Retorna_Taller(id);
new GestionTransporte.frmCargaTaller(taller.Id_unidad, taller.Tipo, conexion, taller, "MODIFICAR", actualizarTaller,null).ShowDialog();
}
else
{
MessageBox.Show("EL ESTADO DEL PEDIDO DEBE SER 'EN TALLER' PARA PODER MODIFICAR");
}
}
if (sender == btnMantAltaUnidad)
{
if(estado.Equals("EN TALLER")){
DialogResult dialogResult = MessageBox.Show("DESEA MODIFICAR LA DESCRIPCION ANTES DE SER ENTREGADO ?", "?",MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
taller = new clsMantemimiento(conexion);
string id = dgvMantenimiento.CurrentRow.Cells[0].Value.ToString();
taller = taller.Retorna_Taller(id);
new GestionTransporte.frmCargaTaller(taller.Id_unidad, taller.Tipo, conexion, taller, "MODIFICAR", actualizarTaller,"ALTA").ShowDialog();
}
else
{
taller = taller.Retorna_Taller(dgvMantenimiento.CurrentRow.Cells[0].Value.ToString());
if (taller != null && taller.Entregar_Unidad() == string.Empty)
{
carga_acoplados_total();
carga_camiones_total();
Carga_Taller_Total();
MessageBox.Show("OK,ENTREGADO");
}
else
{
MessageBox.Show("ERROR AL INTENTAR DAR DE ALTA");
}
}
}
else
{
MessageBox.Show("EL ESTADO DEL PEDIDO DEBE SER 'EN TALLER'");
}
}
if (sender == btnMantEliminarCarga)
{
if (estado.Equals("EN TALLER"))
{
DialogResult dialogResult = MessageBox.Show( "DESEA MODIFICAR LA DESCRIPCION ANTES DE SER ENTREGADO ?","?", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
taller = new clsMantemimiento(conexion);
string id = dgvMantenimiento.CurrentRow.Cells[0].Value.ToString();
taller = taller.Retorna_Taller(id);
new GestionTransporte.frmCargaTaller(taller.Id_unidad, taller.Tipo, conexion, taller, "MODIFICAR", actualizarTaller,"BAJA").ShowDialog();
}
else
{
taller = taller.Retorna_Taller(dgvMantenimiento.CurrentRow.Cells[0].Value.ToString());
if (taller != null && taller.baja() == string.Empty)
{
Carga_Taller_Total();
carga_camiones_total();
carga_acoplados_total();
MessageBox.Show("CARGA DADA DE BAJA");
}
else
{
MessageBox.Show("ERROR AL INTENTAR DAR DE ALTA");
}
}
}
else
{
MessageBox.Show("EL ESTADO DEL PEDIDO DEBE SER 'EN TALLER'");
}
}
}
void Carga_Taller_Total()
{
dgvMantenimiento.DataSource = taller.listar_Todos();
Columnas_invisibles_taller();
Carga_datos_taller_a_label();
}
public void Verifica_dgv_vacio_Mantenimiento()
{
if (dgvMantenimiento.Rows.Count < 1)
{
btnMantEliminarCarga.Enabled = false;
btnMantModificar.Enabled = false;
btnMantAltaUnidad.Enabled = false;
//MessageBox.Show("NO SE ENCONTRARON RESULTADOS PARA MANTENIMIENTO");
dgvMantenimiento.BackgroundColor = Color.Red;
tbMantTarea.BackColor = Color.DarkGray;
Limpia_Objetos_Cargados_Con_Bindings_Mantenimiento();
}
else
{
btnMantEliminarCarga.Enabled = true;
btnMantModificar.Enabled =true;
btnMantAltaUnidad.Enabled = true;
tbMantTarea.BackColor = Color.LightGreen;
dgvMantenimiento.BackgroundColor = Color.DarkGray;
}
}
void Columnas_invisibles_taller()
{
dgvMantenimiento.Columns[6].Visible = false;
dgvMantenimiento.Columns[7].Visible = false;
dgvMantenimiento.Columns[8].Visible = false;
dgvMantenimiento.Columns[9].Visible = false;
dgvMantenimiento.Columns[10].Visible = false;
dgvMantenimiento.Columns[11].Visible = false;
dgvMantenimiento.Columns[12].Visible = false;
dgvMantenimiento.Columns[13].Visible = false;
}
void Limpia_Objetos_Cargados_Con_Bindings_Mantenimiento(){
lblMantNombreResponsable.Text = string.Empty;
lblMantResponsableDireccion.Text = string.Empty;
lblMantResponsableEstado.Text = string.Empty;
lblMantResponsableLegajo.Text = string.Empty;
lblMantResponsableTel1.Text = string.Empty;
lblMantResponsableTel2.Text = string.Empty;
lblMantUnidadDominio.Text = string.Empty;
tbMantTarea.Text = string.Empty;
}
void Limpia_Bindings_Taller() {
tbMantTarea.DataBindings.Clear();
lblMantNombreResponsable.DataBindings.Clear();
lblMantResponsableTel1.DataBindings.Clear();
lblMantResponsableTel2.DataBindings.Clear();
lblMantResponsableLegajo.DataBindings.Clear();
lblMantResponsableDireccion.DataBindings.Clear();
lblMantUnidadDominio.DataBindings.Clear();
lblMantResponsableEstado.DataBindings.Clear();
}
void Carga_datos_taller_a_label()
{
Limpia_Bindings_Taller();
if (dtTaller!=null)
{
tbMantTarea.DataBindings.Add(new Binding("Text", dtTaller, "TAREA"));
lblMantNombreResponsable.DataBindings.Add(new Binding("Text", dtTaller, "NOMBRE"));
lblMantResponsableTel1.DataBindings.Add(new Binding("Text", dtTaller, "telefono1"));
lblMantResponsableTel2.DataBindings.Add(new Binding("Text", dtTaller, "telefono2"));
lblMantResponsableLegajo.DataBindings.Add(new Binding("Text", dtTaller, "LEGAJO"));
lblMantResponsableDireccion.DataBindings.Add(new Binding("Text", dtTaller, "DIRECCION"));
lblMantUnidadDominio.DataBindings.Add(new Binding("Text", dtTaller, "DOMINIO"));
lblMantResponsableEstado.DataBindings.Add(new Binding("Text", dtTaller, "ESTADO MECANICO"));
}
}
#endregion
#region FUNCIONES COMPARTIDAS, CAMION-ACOPLADO
private void cbCamionListar_SelectedIndexChanged(object sender, EventArgs e)
{
#region cbCamionBuscar/listar
if (sender == cbCamionBuscar)
{
tbCamionBuscar.Clear();
if (cbCamionBuscar.SelectedIndex == 0)
{
tbCamionBuscar.Visible = false;
pnlCamionBuscar.Visible = false;
pnlPesoCargaCamion.Visible = false;
}
if (cbCamionBuscar.SelectedIndex == 1 || cbCamionBuscar.SelectedIndex == 2 || cbCamionBuscar.SelectedIndex == 3)
{
camion.Dt = camion.carga_camiones_total();
tbCamionBuscar.Visible = true;
tbCamionBuscar.Location = new Point(238, 92);
pnlCamionBuscar.Visible = false;
pnlCamionBuscar.Location = new Point(362, 86);
}
if (cbCamionBuscar.SelectedIndex == 4 || cbCamionBuscar.SelectedIndex == 5)
{
tbCamionBuscar.Visible = false;
tbCamionBuscar.Location = new Point(362, 86);
pnlCamionBuscar.Visible = true;
pnlCamionBuscar.Location = new Point(238, 91);
}
if (cbCamionBuscar.SelectedIndex == 6)
{
tbCamionBuscar.Visible = false;
tbCamionBuscar.Location = new Point(362, 86);
pnlCamionBuscar.Visible = false;
pnlCamionBuscar.Location = new Point(238, 91);
pnlPesoCargaCamion.Visible = true;
pnlPesoCargaCamion.Location = new Point(353, 91);
}
}
if (sender == cbCamionListar)
{
switch (cbCamionListar.SelectedIndex)
{
case 0:
dtCamion = camion.carga_camiones_total();
dgvCamion.DataSource = dtCamion;
ColumnasInvisiblesCamion();
Carga_datos_Camion_a_label();
break;
case 1:
dgvCamion.DataSource = camion.Listar_disponibles();
ColumnasInvisiblesCamion();
Carga_datos_Camion_a_label();
break;
case 2:
dgvCamion.DataSource = camion.Listar_dados_de_baja();
ColumnasInvisiblesCamion();
Carga_datos_Camion_a_label();
break;
case 3:
dgvCamion.DataSource = camion.Listar_taller();
ColumnasInvisiblesCamion();
Carga_datos_Camion_a_label();
break;
case 4:
dgvCamion.DataSource = camion.Listar_en_viaje();
ColumnasInvisiblesCamion();
Carga_datos_Camion_a_label();
break;
}
Verifica_dgv_vacio_camion();
}
#endregion
#region cbAcopladoBuscar/listar
if (sender == cbAcopladoBuscar)
{
tbAcopladoBuscar.Clear();
if (cbAcopladoBuscar.SelectedIndex == 0)
{
tbAcopladoBuscar.Visible = false;
pnlAcopladoBuscar.Visible = false;
pnlPesoCargaAcoplado.Visible = false;
}
if (cbAcopladoBuscar.SelectedIndex == 1 || cbAcopladoBuscar.SelectedIndex == 2)
{
acoplado.Dt = acoplado.carga_acoplados_total();
tbAcopladoBuscar.Visible = true;
tbAcopladoBuscar.Location = new Point(883, 92);
pnlAcopladoBuscar.Visible = false;
pnlAcopladoBuscar.Location = new Point(1007, 85);
}
if (cbAcopladoBuscar.SelectedIndex == 3 || cbAcopladoBuscar.SelectedIndex == 4)
{
tbAcopladoBuscar.Visible = false;
tbAcopladoBuscar.Location = new Point(1007, 86);
pnlAcopladoBuscar.Visible = true;
pnlAcopladoBuscar.Location = new Point(883, 91);
}
if (cbAcopladoBuscar.SelectedIndex == 5)
{
tbAcopladoBuscar.Visible = false;
tbAcopladoBuscar.Location = new Point(1007, 86);
pnlAcopladoBuscar.Visible = false;
pnlAcopladoBuscar.Location = new Point(883, 91);
pnlPesoCargaAcoplado.Visible = true;
pnlPesoCargaAcoplado.Location = new Point(998, 91);
}
Verifica_dgv_vacio_acoplado();
}
if (sender == cbAcopladoListar)
{
switch (cbAcopladoListar.SelectedIndex)
{
case 0:
dtAcoplado = acoplado.carga_acoplados_total();
dgvAcoplado.DataSource = dtAcoplado;
ColumnasInvisiblesAcoplado();
Carga_datos_Acoplado_a_label();
break;
case 1:
dtAcoplado = acoplado.Listar_disponibles();
dgvAcoplado.DataSource = dtAcoplado;
ColumnasInvisiblesAcoplado();
Carga_datos_Acoplado_a_label();
break;
case 2:
dgvAcoplado.DataSource = acoplado.Listar_dados_de_baja();
ColumnasInvisiblesAcoplado();
Carga_datos_Acoplado_a_label();
break;
case 3:
dgvAcoplado.DataSource = acoplado.Listar_taller();
ColumnasInvisiblesAcoplado();
Carga_datos_Acoplado_a_label();
break;
case 4:
dgvAcoplado.DataSource = acoplado.Listar_en_viaje();
ColumnasInvisiblesAcoplado();
Carga_datos_Acoplado_a_label();
break;
}
Verifica_dgv_vacio_acoplado();
}
#endregion
#region cbMantenimientoBuscar/listar
if (sender == cbMantenimientoListar)
{
if (cbMantenimientoListar.SelectedIndex == 5 || cbMantenimientoListar.SelectedIndex == 6)
{
tbMantenimientoBuscar.Location = new Point(236, 22);
tbMantenimientoBuscar.Visible = false;
pnlMantDtp.Visible = true;
pnlMantDtp.Location = new Point(372, 48);
}
else if (cbMantenimientoListar.SelectedIndex ==7)
{
tbMantenimientoBuscar.Location = new Point(503, 51);
tbMantenimientoBuscar.Visible = true;
pnlMantDtp.Visible = false;
pnlMantDtp.Location = new Point(236, 22);
}
else
{
tbMantenimientoBuscar.Visible = false;
pnlMantDtp.Visible = false;
}
switch (cbMantenimientoListar.SelectedIndex)
{
case 0:
dtTaller = taller.listar_Todos();
dgvMantenimiento.DataSource = dtTaller;
Columnas_invisibles_taller();
Carga_datos_taller_a_label();
break;
case 1:
dtTaller.Clear();
dtTaller = taller.listar_Proximos__A_Entregar();
dgvMantenimiento.DataSource = dtTaller;
Columnas_invisibles_taller();
Carga_datos_taller_a_label();
break;
case 2:
dtTaller.Clear();
dtTaller = taller.listar_Entregados();
dgvMantenimiento.DataSource = dtTaller;
Columnas_invisibles_taller();
Carga_datos_taller_a_label();
break;
case 3:
dtTaller.Clear();
dtTaller = taller.listar_En_Taller();
dgvMantenimiento.DataSource = dtTaller;
Columnas_invisibles_taller();
Carga_datos_taller_a_label();
break;
case 4:
dtTaller.Clear();
dtTaller = taller.listar_Dados_De_Baja();
dgvMantenimiento.DataSource = dtTaller;
Columnas_invisibles_taller();
Carga_datos_taller_a_label();
break;
case 7:
taller.listar_Todos();
break;
}
Verifica_dgv_vacio_Mantenimiento();
}
#endregion
#region cbViajeBuscar/listar
if (sender == cbViajeBuscar)
{
if(cbViajeBuscar.SelectedIndex==1 || cbViajeBuscar.SelectedIndex == 4)
{
tbViajeBuscar.Clear();
tbViajeBuscar.Visible =true;
pnlViajeBuscar.Visible = false;
tbViajeBuscar.Location = new Point(266, 14);
}
if(cbViajeBuscar.SelectedIndex==2 || cbViajeBuscar.SelectedIndex == 3)
{
tbViajeBuscar.Clear();
tbViajeBuscar.Visible = false;
pnlViajeBuscar.Visible = true;
pnlViajeBuscar.Location = new Point(266, 14);
}
if (cbViajeBuscar.SelectedIndex == 0)
{
tbViajeBuscar.Visible = false;
pnlViajeBuscar.Visible = false;
}
}
if (sender==cbViajeListar)
{
DateTime t;
DateTime actual;
switch (cbViajeListar.SelectedIndex)
{
case 0:
dtViaje= viaje.Listar_todos();
dgvViajes.DataSource = dtViaje;
columnasInvisiblesViaje();
Carga_datos_Viaje_a_Label();
break;
case 1:
dtViaje = viaje.Listar_En_Viaje();
dgvViajes.DataSource = dtViaje;
columnasInvisiblesViaje();
Carga_datos_Viaje_a_Label();
break;
case 2:
dtViaje = viaje.Listar_Pendientes();
dgvViajes.DataSource = dtViaje;
columnasInvisiblesViaje();
Carga_datos_Viaje_a_Label();
break;
case 3:
dtViaje = viaje.Listar_Concluidos();
dgvViajes.DataSource = dtViaje;
columnasInvisiblesViaje();
Carga_datos_Viaje_a_Label();
break;
case 4:
//en este listamos los proximos viajes ,le ponemos por defecto una fecha de un dia anterior al cominezo del viaje y usamos
//la funcion listar viajes por rangos de "fecha de salida"
t = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day - 1, 00, 00, 00);
actual = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
dtViaje = viaje.Listar_Rangos_Salida(t.ToString(), actual.ToString());
dgvViajes.DataSource = dtViaje;
columnasInvisiblesViaje();
Carga_datos_Viaje_a_Label();
break;
case 5:
//en este listamos los proximos viajes (regreso) y usando la funcion de rango de fechas de llegada , usamos
//la fecha actual y un dia mas para saber cuales son las llegas entre el momento actual y el dia posterior
t = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day + 1, 23, 59, 59);
actual = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
dtViaje = viaje.Listar_Fecha_Regreso(actual.ToString(), t.ToString());
dgvViajes.DataSource = dtViaje;
columnasInvisiblesViaje();
Carga_datos_Viaje_a_Label();
break;
case 6:
dtViaje = viaje.Listar_Cancelados();
dgvViajes.DataSource = dtViaje;
columnasInvisiblesViaje();
Carga_datos_Viaje_a_Label();
break;
}
}
#endregion
}
#region tbBusqueda
private void tbCamionBuscar_TextChanged(object sender, EventArgs e)//busca camiones/acoplados desde el textbox segun la opcion que se desea buscar (combobox)
{
if (sender == tbCamionBuscar)
{
switch(cbCamionBuscar.SelectedIndex)
{
case 1:
dtCamion.Clear();
dtCamion = camion.Busqueda_dominio(tbCamionBuscar.Text).ToTable();
dgvCamion.DataSource = dtCamion;
ColumnasInvisiblesCamion();
Carga_datos_Camion_a_label();
break;
case 2:
dtCamion.Clear();
dtCamion = camion.Busqueda_chasis(tbCamionBuscar.Text).ToTable();
dgvCamion.DataSource = dtCamion;
ColumnasInvisiblesCamion();
Carga_datos_Camion_a_label();
break;
case 3:
dtCamion.Clear();
dtCamion=camion.Busqueda_motor(tbCamionBuscar.Text).ToTable();
dgvCamion.DataSource = dtCamion;
ColumnasInvisiblesCamion();
Carga_datos_Camion_a_label();
break;
}
Verifica_dgv_vacio_camion();
}
if (sender == tbAcopladoBuscar)
{
switch (cbAcopladoBuscar.SelectedIndex)
{
case 1:
dtAcoplado.Clear();
dtAcoplado = acoplado.Busqueda_dominio(tbAcopladoBuscar.Text).ToTable();
dgvAcoplado.DataSource = dtAcoplado;
ColumnasInvisiblesAcoplado();
Carga_datos_Acoplado_a_label();
break;
case 2:
dtAcoplado = acoplado.Busqueda_chasis(tbAcopladoBuscar.Text).ToTable();
dgvAcoplado.DataSource = dtAcoplado;
ColumnasInvisiblesAcoplado();
Carga_datos_Acoplado_a_label();
break;
}
Verifica_dgv_vacio_acoplado();
}
if (sender == tbMantenimientoBuscar)
{
dtTaller.Clear();
dtTaller = taller.Busqueda_dominio(tbMantenimientoBuscar.Text).ToTable();
dgvMantenimiento.DataSource = dtTaller;
Columnas_invisibles_taller();
Carga_datos_taller_a_label();
Verifica_dgv_vacio_Mantenimiento();
}
if(sender == tbViajeBuscar)
{
dtViaje.Clear();
switch (cbViajeBuscar.SelectedIndex)
{
case 1:
dtViaje = viaje.Listar_viajes_por_Unidad(tbViajeBuscar.Text);
dgvViajes.DataSource = dtViaje;
columnasInvisiblesViaje();
Carga_datos_Viaje_a_Label();
break;
case 4:
dtViaje = viaje.Listar_Por_Cliente(tbViajeBuscar.Text);
dgvViajes.DataSource = dtViaje;
columnasInvisiblesViaje();
Carga_datos_Viaje_a_Label();
break;
}
}
}
private void dtpCamionBusquedaHasta_ValueChanged(object sender, EventArgs e)//maneja las busquedas de camiones//talleracoplados por fechas
{
#region cambio en los DTP de camion
if (sender == dtpCamionBusquedaCamionDesde || sender == dtpCamionBusquedaHasta)
{
if (cbCamionBuscar.SelectedIndex == 4)
{
if (dtpCamionBusquedaCamionDesde.Value <= dtpCamionBusquedaHasta.Value)
{
dtCamion = camion.Busqueda_fecha_alta(dtpCamionBusquedaCamionDesde.Value.ToString("dd/MM/yyyy"), dtpCamionBusquedaHasta.Value.ToString("dd/MM/yyyy"));
dgvCamion.DataSource = dtCamion;
ColumnasInvisiblesCamion();
Carga_datos_Camion_a_label();
}
}
if (cbCamionBuscar.SelectedIndex == 5)
{
if (dtpCamionBusquedaCamionDesde.Value <= dtpCamionBusquedaHasta.Value)
{
dtCamion = camion.Busqueda_fecha_baja(dtpCamionBusquedaCamionDesde.Value.ToString("dd/MM/yyyy"), dtpCamionBusquedaHasta.Value.ToString("dd/MM/yyyy"));
dgvCamion.DataSource = dtCamion;
ColumnasInvisiblesCamion();
Carga_datos_Camion_a_label();
}
}
Verifica_dgv_vacio_camion();
}
#endregion
#region cambio en los DTP de acoplado
if (sender == dtpAcopladoBuscarDesde || sender == dtpAcopladoBuscarHasta)
{
if (cbAcopladoBuscar.SelectedIndex == 3)
{
if (dtpAcopladoBuscarDesde.Value <= dtpAcopladoBuscarHasta.Value)
{
dtAcoplado = acoplado.Busqueda_fecha_alta(dtpAcopladoBuscarDesde.Value.ToString("dd/MM/yyyy"), dtpAcopladoBuscarHasta.Value.ToString("dd/MM/yyyy"));
dgvAcoplado.DataSource = dtAcoplado;
ColumnasInvisiblesAcoplado();
Carga_datos_Acoplado_a_label();
}
}
if (cbAcopladoBuscar.SelectedIndex == 4)
{
if (dtpAcopladoBuscarDesde.Value <= dtpAcopladoBuscarHasta.Value)
{
dtAcoplado = acoplado.Busqueda_fecha_baja(dtpAcopladoBuscarDesde.Value.ToString("dd/MM/yyyy"), dtpAcopladoBuscarHasta.Value.ToString("dd/MM/yyyy"));
dgvAcoplado.DataSource = dtAcoplado;
ColumnasInvisiblesAcoplado();
Carga_datos_Acoplado_a_label();
}
}
Verifica_dgv_vacio_acoplado();
}
#endregion
#region cambio en los dtp de mantenimiento
if (sender == dtpMantenimientoDesde || sender == dtpMantenimietoHasta)
{
if (cbMantenimientoListar.SelectedIndex == 5)
{
if (dtpMantenimientoDesde.Value <= dtpMantenimietoHasta.Value)
{
dgvMantenimiento.DataSource = taller.Busqueda_fecha_carga(dtpMantenimientoDesde.Value.ToString("dd/MM/yyyy"), dtpMantenimietoHasta.Value.ToString("dd/MM/yyyy"));
Columnas_invisibles_taller();
Carga_datos_taller_a_label();
}
}
if (cbMantenimientoListar.SelectedIndex == 6)
{
dgvMantenimiento.DataSource = taller.Busqueda_fecha_salida_aprox(dtpMantenimientoDesde.Value.ToString("dd/MM/yyyy"), dtpMantenimietoHasta.Value.ToString("dd/MM/yyyy"));
Columnas_invisibles_taller();
Carga_datos_taller_a_label();
}
}
#endregion
#region cambio en los dtp de viaje
if(sender == dtpViajeBuscarDesde || sender == dtpViajeBuscarHasta)
{
if (cbViajeBuscar.SelectedIndex==2)
{
if (dtpViajeBuscarDesde.Value<= dtpViajeBuscarHasta.Value)
{
dtViaje = viaje.Listar_Rangos_Salida(dtpViajeBuscarDesde.Value.ToString("dd/MM/yyyy"), dtpViajeBuscarHasta.Value.ToString("dd/MM/yyyy"));
dgvViajes.DataSource = dtViaje;
columnasInvisiblesViaje();
Carga_datos_Viaje_a_Label();
}
}
if (cbViajeBuscar.SelectedIndex == 3)
{
dtViaje = viaje.Listar_Fecha_Regreso(dtpViajeBuscarDesde.Value.ToString("dd/MM/yyyy"), dtpViajeBuscarHasta.Value.ToString("dd/MM/yyyy"));
dgvViajes.DataSource = dtViaje;
columnasInvisiblesViaje();
Carga_datos_Viaje_a_Label();
}
}
# endregion
}
private void btnSelecMantCamion_Click(object sender, EventArgs e) //AQUI SE LLEVARA A CABO LA APERTURA DE FORM PARA CARGAR CAMION/ACOPLADO A MANTENIMIENTO/REPARACION
{
if (sender == btnSelecMantCamion)
{
if (dgvCamion.CurrentRow.Cells[5].Value.ToString().Equals("EN TALLER"))
{
MessageBox.Show("LA UNIDAD SE ENCUENTRA EN TALLER");
}
else
{
new frmCargaTaller( dgvCamion.CurrentRow.Cells[0].Value.ToString(), "CAMION",conexion,null,"NUEVO",actualizarTaller,null).ShowDialog();
}
}
if (sender == btnSelectManAcoplado)
{
new frmCargaTaller(dgvAcoplado.CurrentRow.Cells[0].Value.ToString(),"ACOPLADO", conexion,null,"NUEVO",actualizarTaller,null).ShowDialog();
}
}
private void tbPesoCargaMin_TextChanged(object sender, EventArgs e)
{
if(sender==tbPesoCargaMinCamion || sender==tbPesoCargaMaxCamion)
{
if (tbPesoCargaMinCamion.Text != String.Empty && tbPesoCargaMaxCamion.Text != String.Empty)
{
dtCamion.Clear();
dtCamion = camion.Busqueda_peso_carga(Convert.ToInt64(tbPesoCargaMinCamion.Text), Convert.ToInt64(tbPesoCargaMaxCamion.Text));
dgvCamion.DataSource = dtCamion;
ColumnasInvisiblesCamion();
Carga_datos_Camion_a_label();
}
Verifica_dgv_vacio_camion();
}
if(sender==tbPesoCargaMinAcoplado || sender==tbPesoCargaMaxAcoplado)
{
if (tbPesoCargaMinAcoplado.Text != String.Empty && tbPesoCargaMaxAcoplado.Text != String.Empty)
{
dtAcoplado.Clear();
dtAcoplado = acoplado.Busqueda_peso_carga(Convert.ToInt64(tbPesoCargaMinAcoplado.Text), Convert.ToInt64(tbPesoCargaMaxAcoplado.Text));
dgvAcoplado.DataSource = dtAcoplado;
ColumnasInvisiblesAcoplado();
Carga_datos_Acoplado_a_label();
}
Verifica_dgv_vacio_acoplado();
}
}
#endregion
#endregion
#region VIAJE
private void btnVerPedidos_Click(object sender, EventArgs e)
{
frmPedido frmPedido = new frmPedido(conexion);
frmPedido.pasaIdFormPrincipal += new frmPedido.idPedido(muestraIdPedido);
frmPedido.ShowDialog();
}
private void muestraIdPedido(String id)
{
idPedido = id;
lbPedidoSeleccionado.Text = "Pedido seleccionado: " + id;
}
private void btnSelecCamion_Click(object sender, EventArgs e)
{
if(idCamion!=null){
idCamion = null;
}
else
{
if (!timer1.Enabled)
timer1.Start();
idCamion = dgvCamion.CurrentRow.Cells[16].Value.ToString();
}
}
private void btnSelecAcoplado1_Click(object sender, EventArgs e)
{
if (idAcoplado1 != null )
{ //si se deseleccion el acoplado uno tambien se deseleccionara el acoplado 2
idAcoplado1 = null;
idAcoplado2 = null;
} else
{
if (!timer1.Enabled)
timer1.Start();
idAcoplado1 = dgvAcoplado.CurrentRow.Cells[17].Value.ToString();
}
}
private void btnSelecAcoplado2_Click(object sender, EventArgs e)
{
if (idAcoplado2 != null)
{
idAcoplado2 = null;
}
else
{
if (!timer1.Enabled)
timer1.Start();
idAcoplado2 = dgvAcoplado.CurrentRow.Cells[17].Value.ToString();
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (idCamion == null && idAcoplado1 == null && idAcoplado2 == null)
{
timer1.Stop();
}
if (idCamion != null)
{
if (btnSelecCamion.Visible)
{
btnSelecCamion.Visible = false;
}
else
{
btnSelecCamion.Visible = true;
}
}
else
{
btnSelecCamion.Visible = true;
}
if (idAcoplado1 != null)
{
if (btnSelecAcoplado1.Visible)
{
btnSelecAcoplado1.Visible = false;
}
else
{
btnSelecAcoplado1.Visible = true;
}
}
else
{
btnSelecAcoplado1.Visible = true;
}
if (idAcoplado2 != null)
{
if (btnSelecAcoplado2.Visible)
{
btnSelecAcoplado2.Visible = false;
}
else
{
btnSelecAcoplado2.Visible = true;
}
}
else
{
btnSelecAcoplado2.Visible = true;
}
}
private void btnNuevoViaje_Click(object sender, EventArgs e)
{
if (btnNuevoViaje == sender)
{
if (idPedido == null || idCamion == null)
{
MessageBox.Show("Falta seleccionar Unidad o Pedido");
}
frmInputBox f = new frmInputBox("Desea agregar alguna observación ? ");
if (f.ShowDialog() == DialogResult.OK)
{
viaje.Observaciones = f.Retorno;
}
else
{
viaje.Observaciones = "-------";
}
pedido = pedido.retorna_pedido(Convert.ToInt32(idPedido));
viaje.Id_pedido = idPedido.ToString();
viaje.Id_camion = idCamion;
viaje.Id_acoplado1 = idAcoplado1;
viaje.Id_acoplado2 = idAcoplado2;
viaje.Fecha_Sal = pedido.Fecha_sal_aprox;
viaje.Fecha_Regre = pedido.Fecha_reg_aprox;
viaje.Estado = "PENDIENTE";
viaje.alta();
MessageBox.Show("VIAJE CARGADO CON EXITO");
this.Carga_Viaje_Total();
}
if (sender == btnModificarViaje)
{
clsAcoplado acoplado2 = new clsAcoplado(conexion);
if (idCamion != null)
camion.Busqueda_id(idCamion);
else
camion = null;
if (idAcoplado1 != null)
acoplado.Busqueda_id(idAcoplado1);
else
acoplado = null;
if (idAcoplado2 != null)
acoplado2.Busqueda_id(idAcoplado2);
else
acoplado2 = null;
string idv = dgvViajes.CurrentRow.Cells[0].Value.ToString();
viaje = viaje.Retorna_Viaje(idv);
new frmModificaViaje(viaje,camion,acoplado,acoplado2,"btnModificarViaje").ShowDialog();
}
if (sender == btnCancelarViaje)
{
clsAcoplado acoplado2 = new clsAcoplado(conexion);
if (idCamion != null)
camion.Busqueda_id(idCamion);
else
camion = null;
if (idAcoplado1 != null)
acoplado.Busqueda_id(idAcoplado1);
else
acoplado = null;
if (idAcoplado2 != null)
acoplado2.Busqueda_id(idAcoplado2);
else
acoplado2 = null;
string idv = dgvViajes.CurrentRow.Cells[0].Value.ToString();
viaje = viaje.Retorna_Viaje(idv);
new frmModificaViaje(viaje, camion, acoplado, acoplado2,"btnCancelarViaje").ShowDialog();
}
}
private void btnCerrarViaje_Click(object sender, EventArgs e)
{
viaje.cerrarViaje(viaje.Retorna_Viaje(dgvViajes.SelectedCells[0].Value.ToString()));
MessageBox.Show("Viaje finalizado con exito");
this.Carga_Viaje_Total();
}
private void Carga_Viaje_Total()
{ dtViaje= viaje.Listar_todos();
dgvViajes.DataSource = dtViaje;
columnasInvisiblesViaje();
Carga_datos_Viaje_a_Label();
}
private void columnasInvisiblesViaje()
{
dgvViajes.Columns[0].Visible = false;
dgvViajes.Columns[3].Visible = false;
dgvViajes.Columns[4].Visible = false;
dgvViajes.Columns[5].Visible = false;
dgvViajes.Columns[8].Visible = false;
dgvViajes.Columns[10].Visible = false;
dgvViajes.Columns[11].Visible = false;
dgvViajes.Columns[12].Visible = false;
dgvViajes.Columns[13].Visible = false;
dgvViajes.Columns[14].Visible = false;
dgvViajes.Columns[15].Visible = false;
dgvViajes.Columns[16].Visible = false;
dgvViajes.Columns[17].Visible = false;
dgvViajes.Columns[18].Visible = false;
dgvViajes.Columns[19].Visible = false;
dgvViajes.Columns[20].Visible = false;
dgvViajes.Columns[21].Visible = false;
dgvViajes.Columns[22].Visible = false;
dgvViajes.Columns[23].Visible = false;
dgvViajes.Columns[24].Visible = false;
dgvViajes.Columns[25].Visible = false;
dgvViajes.Columns[26].Visible = false;
}
private void Carga_datos_Viaje_a_Label()
{
limpiaBindingViaje();
if (dtViaje != null)
{
tbViajeObsViaje.DataBindings.Add(new Binding("Text", dtViaje, "OBSERVACIONES VIAJE"));
tbViajeObsPedido.DataBindings.Add(new Binding("Text", dtViaje, "OBSERVACIONES PEDIDO"));
lbCliente.DataBindings.Add(new Binding("Text", dtViaje, "CLIENTE"));
lbCuil.DataBindings.Add(new Binding("Text", dtViaje, "CUIL CLIENTE"));
lbDominioCamion.DataBindings.Add(new Binding("Text", dtViaje, "DOMINIO CAMION"));
lbMarcaCamion.DataBindings.Add(new Binding("Text", dtViaje, "MARCA CAMION"));
lbModeloCamion.DataBindings.Add(new Binding("Text", dtViaje, "MODELO CAMION"));
lbTipoCamion.DataBindings.Add(new Binding("Text", dtViaje, "TIPO CAMION"));
lbDominioAco1.DataBindings.Add(new Binding("Text", dtViaje, "DOMINIO ACOPLADO"));
lbMarcaAco1.DataBindings.Add(new Binding("Text", dtViaje, "MARCA ACOPLADO"));
lbTipoAco1.DataBindings.Add(new Binding("Text", dtViaje, "TIPO ACOPLADO"));
lbDominioAco2.DataBindings.Add(new Binding("Text", dtViaje, "DOMINIO ACOPLADO1"));
lbMarcaAco2.DataBindings.Add(new Binding("Text", dtViaje, "MARCA ACOPLADO1"));
lbTipoAco2.DataBindings.Add(new Binding("Text", dtViaje, "TIPO ACOPLADO1"));
lbChoferNombre.DataBindings.Add(new Binding("Text", dtViaje, "NOMBRE"));
lbChoferApellido.DataBindings.Add(new Binding("Text", dtViaje, "APELLIDO"));
lbChoferDomicilio.DataBindings.Add(new Binding("Text", dtViaje, "DIRECCION"));
lbChoferCedula.DataBindings.Add(new Binding("Text", dtViaje, "LEGAJO"));
lbChoferTel1.DataBindings.Add(new Binding("Text", dtViaje, "TELEFONO 1"));
lbChoferTel2.DataBindings.Add(new Binding("Text", dtViaje, "TELEFONO 2"));
}
}
private void limpiaBindingViaje()
{
tbViajeObsViaje.DataBindings.Clear();
tbViajeObsPedido.DataBindings.Clear();
lbCliente.DataBindings.Clear();
lbCuil.DataBindings.Clear();
lbDominioCamion.DataBindings.Clear();
lbMarcaCamion.DataBindings.Clear();
lbModeloCamion.DataBindings.Clear();
lbTipoCamion.DataBindings.Clear();
lbDominioAco1.DataBindings.Clear();
lbMarcaAco1.DataBindings.Clear();
lbTipoAco1.DataBindings.Clear();
lbDominioAco2.DataBindings.Clear();
lbMarcaAco2.DataBindings.Clear();
lbTipoAco2.DataBindings.Clear();
lbChoferNombre.DataBindings.Clear();
lbChoferApellido.DataBindings.Clear();
lbChoferDomicilio.DataBindings.Clear();
lbChoferCedula.DataBindings.Clear();
lbChoferTel1.DataBindings.Clear();
lbChoferTel2.DataBindings.Clear();
}
private void limpiaTextboxBinding()
{
tbViajeObsViaje.Text = string.Empty;
tbViajeObsPedido.Text = string.Empty;
lbCliente.Text = String.Empty;
lbCuil.Text = String.Empty;
lbDominioCamion.Text = String.Empty;
lbMarcaCamion.Text = String.Empty;
lbTipoCamion.Text = String.Empty;
lbDominioAco1.Text = String.Empty;
lbTipoAco1.Text = String.Empty;
lbDominioAco2.Text = String.Empty;
lbTipoAco2.Text = String.Empty;
lbChoferNombre.Text = String.Empty;
lbChoferApellido.Text = String.Empty;
lbChoferCedula.Text = String.Empty;
lbChoferDomicilio.Text = String.Empty;
lbChoferTel1.Text = String.Empty;
lbChoferTel2.Text = String.Empty;
}
#endregion
#region CALENDARIO
private void btnCamionCalendar_Click(object sender, EventArgs e)//este evento abre el CALENDARIO que muestra la disponibilidad de las unidades graficamente
{
if(sender == btnCamionCalendar)
{
DataTable data = viaje.Listar_viajes_por_Unidad(dgvCamion.CurrentRow.Cells[0].Value.ToString());
if(data != null)
{
new frmCalendario(data).ShowDialog();
}
else
{
MessageBox.Show("NO SE ENCUENTRA INFORMACION");
}
}
if(sender == btnAcopladoCalendar)
{
DataTable data = viaje.Listar_viajes_por_Unidad(dgvAcoplado.CurrentRow.Cells[0].Value.ToString());
if (data != null)
{
new frmCalendario(data).ShowDialog();
}
else
{
MessageBox.Show("NO SE ENCUENTRA INFORMACION");
}
}
}
#endregion
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
namespace GestionTransporte.clases
{
public class clsPedido
{
#region Atributos y Propiedades
clsLogin usuario;
int id_pedido;
int id_chofer;
string nombre_cliente;
string cuil_cliente;
DateTime fecha_sal_aprox;
DateTime fecha_reg_aprox;
double peso_carga_aprox;
DateTime fecha_pedido;
string observaciones;
string prioridad;
string estado;
DataTable dt;
SqlDataAdapter da;
#region encapsulamiento de propiedades
public int Id_pedido
{
get { return id_pedido; }
set { id_pedido = value; }
}
public int Id_chofer
{
get { return id_chofer; }
set { id_chofer = value; }
}
public string Nombre_cliente
{
get { return nombre_cliente; }
set { nombre_cliente = value; }
}
public string Cuil_cliente
{
get { return cuil_cliente; }
set { cuil_cliente = value; }
}
public DateTime Fecha_sal_aprox
{
get { return fecha_sal_aprox; }
set { fecha_sal_aprox = value; }
}
public DateTime Fecha_reg_aprox
{
get { return fecha_reg_aprox; }
set { fecha_reg_aprox = value; }
}
public double Peso_carga_aprox
{
get { return peso_carga_aprox; }
set { peso_carga_aprox = value; }
}
public DateTime Fecha_pedido
{
get { return fecha_pedido; }
set { fecha_pedido = value; }
}
public string Observaciones
{
get { return observaciones; }
set { observaciones = value; }
}
public string Prioridad
{
get { return prioridad; }
set { prioridad = value; }
}
public string Estado
{
get { return estado; }
set { estado = value; }
}
public DataTable Dt
{
get { return dt; }
set { dt = value; }
}
#endregion
#endregion
public clsPedido(clsLogin usuario)
{
this.usuario = usuario;
Dt = listar_pedidos();
} //Constructor de la clase
public DataTable listar_pedidos()
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = usuario.cnn;
cmd.CommandText = "select p.id_pedido,c.nombre,c.apellido,p.nombre_cliente,p.cuil_cliente,p.fecha_sal_aprox,p.fecha_reg_aprox,p.peso_carga_aprox,p.fecha_pedido,p.observaciones,p.prioridad,p.estado from pedido p JOIN chofer c ON p.id_chofer=c.num_legajo order by id_pedido asc";
cmd.CommandType = CommandType.Text;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
DataTable datatable = new DataTable();
adapter.Fill(datatable);
return datatable;
} //Funcion que carga los pedidos de la BD en un datatable
public DataTable lista_prioridad_alta()
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = usuario.cnn;
cmd.CommandText = "select p.id_pedido,c.nombre,c.apellido,p.nombre_cliente,p.cuil_cliente,p.fecha_sal_aprox,p.fecha_reg_aprox,p.peso_carga_aprox,p.fecha_pedido,p.observaciones,p.prioridad,p.estado from pedido p JOIN chofer c ON p.id_chofer=c.num_legajo where p.prioridad='ALTA' order by id_pedido asc";
cmd.CommandType = CommandType.Text;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
DataTable datatable = new DataTable();
adapter.Fill(datatable);
return datatable;
} //Funcion que lista pedidos por prioridad alta
public DataTable lista_prioridad_normal()
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = usuario.cnn;
cmd.CommandText = "select p.id_pedido,c.nombre,c.apellido,p.nombre_cliente,p.cuil_cliente,p.fecha_sal_aprox,p.fecha_reg_aprox,p.peso_carga_aprox,p.fecha_pedido,p.observaciones,p.prioridad,p.estado from pedido p JOIN chofer c ON p.id_chofer=c.num_legajo where p.prioridad='NORMAL' order by id_pedido asc";
cmd.CommandType = CommandType.Text;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
DataTable datatable = new DataTable();
adapter.Fill(datatable);
return datatable;
} //Funcion que lista pedidos por prioridad normal
public DataTable lista_entregados()
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = usuario.cnn;
cmd.CommandText = "select p.id_pedido,c.nombre,c.apellido,p.nombre_cliente,p.cuil_cliente,p.fecha_sal_aprox,p.fecha_reg_aprox,p.peso_carga_aprox,p.fecha_pedido,p.observaciones,p.prioridad,p.estado from pedido p JOIN chofer c ON p.id_chofer=c.num_legajo where p.estado='ENTREGADO' order by id_pedido asc";
cmd.CommandType = CommandType.Text;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
DataTable datatable = new DataTable();
adapter.Fill(datatable);
return datatable;
} //Funcion que lista pedidos entregados
public DataTable listar_pendientes()
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = usuario.cnn;
cmd.CommandText = "select p.id_pedido,c.nombre,c.apellido,p.nombre_cliente,p.cuil_cliente,p.fecha_sal_aprox,p.fecha_reg_aprox,p.peso_carga_aprox,p.fecha_pedido,p.observaciones,p.prioridad,p.estado from pedido p JOIN chofer c ON p.id_chofer=c.num_legajo where p.estado='PENDIENTE' order by id_pedido asc";
cmd.CommandType = CommandType.Text;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
DataTable datatable = new DataTable();
adapter.Fill(datatable);
return datatable;
} //Funcion que lista pedidos pendientes
public DataTable lista_en_transcurso()
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = usuario.cnn;
cmd.CommandText = "select p.id_pedido,c.nombre,c.apellido,p.nombre_cliente,p.cuil_cliente,p.fecha_sal_aprox,p.fecha_reg_aprox,p.peso_carga_aprox,p.fecha_pedido,p.observaciones,p.prioridad,p.estado from pedido p JOIN chofer c ON p.id_chofer=c.num_legajo where p.estado='EN TRANSCURSO' order by id_pedido asc";
cmd.CommandType = CommandType.Text;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
DataTable datatable = new DataTable();
adapter.Fill(datatable);
return datatable;
} //Funcion que lista pedidos en transcurso
public DataTable lista_cancelados()
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = usuario.cnn;
cmd.CommandText = "select p.id_pedido,c.nombre,c.apellido,p.nombre_cliente,p.cuil_cliente,p.fecha_sal_aprox,p.fecha_reg_aprox,p.peso_carga_aprox,p.fecha_pedido,p.observaciones,p.prioridad,p.estado from pedido p JOIN chofer c ON p.id_chofer=c.num_legajo where p.estado='CANCELADO' order by id_pedido asc";
cmd.CommandType = CommandType.Text;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
DataTable datatable = new DataTable();
adapter.Fill(datatable);
return datatable;
} //Funcion que lista pedidos cancelados
public clsPedido retorna_pedido(int num_pedido)
{
clsPedido pedido = new clsPedido(usuario);
SqlCommand cmd = new SqlCommand();
usuario.cnn.Open();
cmd.Connection = usuario.cnn;
cmd.CommandText = "select p.id_pedido,c.nombre,c.apellido,p.nombre_cliente,p.cuil_cliente,p.fecha_sal_aprox,p.fecha_reg_aprox,p.peso_carga_aprox,p.fecha_pedido,p.observaciones,p.prioridad,p.estado from pedido p JOIN chofer c ON p.id_chofer=c.num_legajo where id_pedido="+num_pedido+" order by id_pedido asc";
cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
pedido.id_pedido = Convert.ToInt32(dr[0]);
pedido.nombre_cliente = dr[3].ToString();
pedido.cuil_cliente = dr[4].ToString();
pedido.fecha_sal_aprox = Convert.ToDateTime(dr[5]);
pedido.fecha_reg_aprox = Convert.ToDateTime(dr[6]);
pedido.peso_carga_aprox = Convert.ToDouble(dr[7]);
pedido.fecha_pedido = Convert.ToDateTime(dr[8]);
pedido.observaciones = dr[9].ToString();
pedido.prioridad = dr[10].ToString();
pedido.estado = dr[11].ToString();
}
usuario.cnn.Close();
return pedido;
} //Funcion que lista pedidos cancelados
public DataView busqueda_numero_pedido(string numPedido)
{
if (numPedido != String.Empty)
{
DataView dv = new DataView(dt);
dv.RowFilter = "id_pedido = " + Convert.ToInt32(numPedido) + " ";
return dv;
}
else
return null;
} //Funcion que filtra pedidos por numero de pedido
public DataView busqueda_cliente(string cliente)
{
DataView dv = new DataView(dt);
dv.RowFilter = "nombre_cliente like '" + cliente + "%' ";
return dv;
} //Funcion que filtra pedidos por cliente
public DataView busqueda_cuil(string cuil)
{
DataView dv = new DataView(dt);
dv.RowFilter = "cuil_cliente like '" + cuil + "%' ";
return dv;
} //Funcion que filtra pedidos por cuil
public DataView busqueda_fechaIngreso(string fecha)
{
DataView dv = new DataView(dt);
dv.RowFilter = "TRY_PARSE(fecha_pedido as datetime) like '" + fecha + "'";
return dv;
} //Funcion que filtra pedidos por fecha de ingreso del pedido al sistema
public DataTable busqueda_rangoFecha(string desde, string hasta)
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("select p.id_pedido,c.nombre,c.apellido,p.nombre_cliente,p.cuil_cliente,p.fecha_sal_aprox,p.fecha_reg_aprox,p.peso_carga_aprox,p.fecha_pedido,p.observaciones,p.prioridad,p.estado from pedido p JOIN chofer c ON p.id_chofer=c.num_legajo where TRY_PARSE(fecha_pedido as datetime) between '" + desde + "' and '" + hasta + "'", usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
} //Funcion que filtra pedidos por rango de fecha
}
}
<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;
using System.Data.SqlClient;
using GestionTransporte.clases;
namespace GestionTransporte
{
public partial class frmLogin : Form
{
clsLogin Conexion;
public frmLogin()
{
InitializeComponent();
Conexion = new clsLogin();
}
private void btnLogear_Click(object sender, EventArgs e)
{
if (!new clsFunciones().Valida_Controles(this))
{
MessageBox.Show("FALTA LLENAR CAMPOS MARCADOS CON COLOR ROJO", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
//Conexion.Servidor = "MANAC\\SQLEXPRESS"; //Conexion Marcos Notebook
//Conexion.Servidor = "DESKTOP-ABTLNM4\\SQLEXPRESS"; //Conexion Pablo PC
Conexion.Servidor = "ASUS-Pablo\\SQLEXPRESS"; //Conexion Pablo Notebook
Conexion.BaseDatos = "gestiontransporte"; //Nombre de la base de datos
Conexion.Usuario = tbUsuario.Text; //Usuario que se logea en SQL server y que tambien existe en tabla login
Conexion.Clave = tbPassword.Text; //Password correspondiente
string res = Conexion.Validar(); //Funcion que valida si la conexion fue o no exitosa.. devuelve un string vacio si fue exitosa
if (res == string.Empty)
{
//SqlConnection con = new SqlConnection(@"Data Source=MANAC\SQLEXPRESS;Initial Catalog=gestiontransporte; User ID = " + tbUsuario.Text + "; Password= " + tbPassword.Text); //Cadena de conexion Marcos Notebook
//SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-ABTLNM4\SQLEXPRESS;Initial Catalog=gestiontransporte; User ID = " + tbUsuario.Text + "; Password= " + tbPassword.Text); //Cadena de conexion Pablo PC
SqlConnection con = new SqlConnection(@"Data Source=ASUS-Pablo\SQLEXPRESS;Initial Catalog=gestiontransporte; User ID = " + tbUsuario.Text + "; Password= " + tb<PASSWORD>.Text); //Cadena de conexion Pablo Notebook
String query = "Select tipo_usuario From login Where usuario='" + tbUsuario.Text + "' and password='" + tbPassword.Text + "' "; //Comprueba que exista en tabla login
SqlCommand command = new SqlCommand(query, con); //Ejecuta la query
con.Open(); //Abre la conexion
SqlDataReader reader = command.ExecuteReader(); //Lee la consulta
if (reader.Read()) //Verifica si hay datos en la consulta
{
String dato = reader.GetString(0); //Guardo el valor obtenido en la query, (0) posicion de la variable en el Select, este caso 0 xq es el unico
if (dato == "admin")
{
this.Hide();
frmAdmin frmMain = new frmAdmin(Conexion);
frmMain.ShowDialog();
//this.ShowDialog();
}
else if (dato == "pedido")
{
this.Hide();
frmPedido frmPedido = new frmPedido(Conexion);
frmPedido.ShowDialog();
this.ShowDialog();
}
else if (dato == "mecanico")
{
this.Hide();
frmMecanico frmMecanico = new frmMecanico(Conexion);
frmMecanico.ShowDialog();
this.ShowDialog();
}
}
tbPassword.Clear();
tbUsuario.Clear();
con.Close(); //Cierra conexion
}
else
MessageBox.Show(res, "E R R O R", MessageBoxButtons.OK, MessageBoxIcon.Error); //Si string es NO vacio, lanza mensaje de error.
}
}
private void tbUsuario_TextChanged(object sender, EventArgs e)
{
new clsFunciones().fondoBlanco_Controles(sender);
}
private void frmLogin_Load(object sender, EventArgs e)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
using System.Collections;
namespace GestionTransporte.clases
{
public class clsModelo_camion
{
#region Atributos y Propiedades
string modelo;
string estado;
clsLogin usuario;
public string Modelo
{
get { return modelo; }
set { modelo = value; }
}
public string Estado
{
get { return estado; }
set { estado = value; }
}
#endregion
public clsModelo_camion(clsLogin usuario)
{
this.usuario = usuario;
} //Constructor de la clase
public string insertar()
{
string respuesta = string.Empty;
SqlCommand cmd = new SqlCommand();
try
{
cmd.Connection = usuario.cnn;
cmd.CommandText = "insert into modelo_camion values ('" + Modelo + "','" + Estado + "');SELECT Scope_Identity();";
cmd.CommandType = CommandType.Text;
usuario.Modo(TipoConexion.Abrir);
string id_insertado = cmd.ExecuteScalar().ToString();
if (id_insertado != null)
{
cmd.CommandText = "insert into auditoria values ('" + (DateTime.Now).ToString() + "','" + usuario.Usuario + "','" + "se inserto el modelo " + Modelo + "')";
cmd.ExecuteNonQuery();
respuesta = string.Empty;
}
else
{
respuesta = "Error al insertar modelo";
}
}
catch (SqlException e)
{
if (e.ErrorCode == -2146232060)
{
respuesta = "YA EXISTE ESE MODELO ";
}
}
usuario.Modo(TipoConexion.Cerrar);
return respuesta;
} //Funcion para insertar nuevo modelo de camion
public string modificar(string vieja)
{
string respuesta;
SqlCommand cmd = new SqlCommand();
try
{
cmd.Connection = usuario.cnn;
cmd.CommandText = "update modelo_camion set modelo='" + Modelo + "' where modelo='" + vieja + "';SELECT Scope_Identity();";
cmd.CommandType = CommandType.Text;
usuario.Modo(TipoConexion.Abrir);
string id_insertado = cmd.ExecuteScalar().ToString();
if (id_insertado != null)
{
cmd.CommandText = "insert into auditoria values ('" + (DateTime.Now).ToString() + "','" + usuario.Usuario + "','" + "se modifico la modelo " + vieja + " a " + Modelo + "')";
cmd.ExecuteNonQuery();
respuesta = string.Empty;
}
else
{
respuesta = "Error al modificar marca";
}
}
catch (SqlException e)
{
respuesta = e.ErrorCode.ToString();
}
usuario.Modo(TipoConexion.Cerrar);
return respuesta;
} //Funcion para modificar un modelo ya insertado
public DataTable ver_modelos()
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = usuario.cnn;
cmd.CommandText = "select modelo as MODELO from modelo_camion order by modelo asc";
cmd.CommandType = CommandType.Text;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
DataTable datatable = new DataTable();
adapter.Fill(datatable);
return datatable;
} //Funcion que retorna los modelos disponibles en BD a un DataTable
public string eliminar(string Modelo)
{
string respuesta;
SqlCommand cmd = new SqlCommand();
try
{
cmd.Connection = usuario.cnn;
cmd.CommandText = "update modelo_camion set modelo='DESAHABILITADO' where estado='" + Modelo + "';SELECT Scope_Identity();";
cmd.CommandType = CommandType.Text;
usuario.Modo(TipoConexion.Abrir);
int id_insertado = cmd.ExecuteNonQuery();
if (id_insertado != 0)
{
cmd.CommandText = "insert into auditoria values ('" + (DateTime.Now).ToString() + "','" + usuario.Usuario + "','" + "elimino el modelo " + Modelo + "')";
cmd.ExecuteNonQuery();
respuesta = string.Empty;
}
else
{
respuesta = "Error al eliminar marca,ya existe una unidad utilizando esta marca";
}
}
catch (SqlException)
{
respuesta = "Error al eliminar marca,ya existe una unidad utilizando esta marca";
}
usuario.Modo(TipoConexion.Cerrar);
return respuesta;
} //Funcion que elimina un modelo
public int retornaID_modelo(string modelo)
{
int retorno = -1;
SqlCommand cmd = new SqlCommand();
usuario.cnn.Open();
cmd.Connection = usuario.cnn;
cmd.CommandText = "select id from modelo_camion where modelo='" + modelo + "' ";
cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
retorno = Convert.ToInt32(dr[0]);
}
usuario.cnn.Close();
return retorno;
} //Funcion que retorna el ID del modelo segun sea su nombre
public String retornaModelo(int id)
{
string retorno = string.Empty;
SqlCommand cmd = new SqlCommand();
usuario.cnn.Open();
cmd.Connection = usuario.cnn;
cmd.CommandText = "select modelo from modelo_camion where id='" + id + "' ";
cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
retorno = dr[0].ToString();
}
usuario.cnn.Close();
return retorno;
} //Funcion que retorna el modelo segun su ID
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GestionTransporte.clases
{
public class Viaje
{
Login usuario;//el usuario trae consigo la coneccion a la bd
Camion camion;
DateTime fecha_salida;
DateTime fecha_entrada;
DateTime fecha_regreso_aprox;
float peso_carga;
string observaciones;
#region encapsulamiento de propiedades
public Camion Camion
{
get { return camion; }
set { camion = value; }
}
public DateTime Fecha_salida
{
get { return fecha_salida; }
set { fecha_salida = value; }
}
public DateTime Fecha_entrada
{
get { return fecha_entrada; }
set { fecha_entrada = value; }
}
public DateTime Fecha_regreso_aprox
{
get { return fecha_regreso_aprox; }
set { fecha_regreso_aprox = value; }
}
public float Peso_carga
{
get { return peso_carga; }
set { peso_carga = value; }
}
public string Observaciones
{
get { return observaciones; }
set { observaciones = value; }
}
#endregion
}
}
<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 GestionTransporte.clases;
using System.Data.SqlClient;
using GestionTransporte.vistas;
namespace GestionTransporte
{
public partial class frmCargaCamion : Form
{
clsCamion camion,camionModifica;
clsMarca_camion marca;
clsModelo_camion modelo;
clsTipo_camion tipo_camion;
clsLogin conexion;
actualizaTipoCamion delegadoTipoCamion;
actualizaMarcaCamion delegadoMarcaCamion;
actualizaModeloCamion delegadoModeloCamion;
delegadoActualizaListaCamiones delegadoActualizaLista;
public frmCargaCamion(clsLogin conexion,clsCamion camionModifica, Delegate actualizarLista) //Delegado que al insertar / modificar unidad actualiza grilla de camiones
{
InitializeComponent();
this.conexion = conexion;
camion = new clsCamion(conexion);
this.camionModifica = camionModifica;
marca = new clsMarca_camion(conexion);
modelo = new clsModelo_camion(conexion);
tipo_camion = new clsTipo_camion(conexion);
delegadoTipoCamion = new actualizaTipoCamion(cargaTipo);
delegadoMarcaCamion = new actualizaMarcaCamion(cargaMarca);
delegadoModeloCamion = new actualizaModeloCamion(cargaModelo);
delegadoActualizaLista = (delegadoActualizaListaCamiones)actualizarLista;
}
private void agregarMarcasToolStripMenuItem_Click(object sender, EventArgs e)
{
new frmGestorDeMarca(conexion,delegadoMarcaCamion).ShowDialog();
}
private void gestionarTipoToolStripMenuItem_Click(object sender, EventArgs e)
{
new frmTipoCamion(conexion, delegadoTipoCamion).ShowDialog();
}
private void cargaTipo()
{
List<String> lista = camion.Retorna_tiposComboBox();
cbTipo.Items.Clear();
cbTipo.Items.Add("SELECCIONE TIPO");
foreach (String item in lista)
{
cbTipo.Items.Add(item);
}
cbTipo.SelectedIndex = 0;
}
private void cargaMarca()
{
List<String> lista = camion.Retorna_marcasComboBox();
cbMarca.Items.Clear();
cbMarca.Items.Add("SELECCIONE MARCA");
foreach (String item in lista)
{
cbMarca.Items.Add(item);
}
cbMarca.SelectedIndex = 0;
}
private void cargaModelo()
{
List<String> lista = camion.Retorna_modeloComboBox();
cbModelo.Items.Clear();
cbModelo.Items.Add("SELECCIONE MODELO");
foreach (String item in lista)
{
cbModelo.Items.Add(item);
}
cbModelo.SelectedIndex = 0;
}
private void frmCargaCamion_Load(object sender, EventArgs e)
{
cargaTipo();
cargaMarca();
cargaModelo();
tbDominio.Enabled = true;
if(camionModifica!=null)
{
string marca_camion=marca.retornaMarca(camionModifica.Marca);
string modelo_camion = modelo.retornaModelo(camionModifica.Modelo);
string tipoCamion=tipo_camion.retornaTipoCamion(camionModifica.Tipo);
tbDominio.Enabled = false;
cbMarca.Enabled = false;
cbModelo.Enabled = false;
cbTipo.Enabled = false;
tbNro_chasis.Enabled = false;
tbNro_motor.Enabled = false;
tbAño.Enabled = false;
tbDominio.Text = camionModifica.Dominio;
cbMarca.SelectedItem = marca_camion;
tbTara.Text = camionModifica.Tara.ToString();
cbModelo.SelectedItem = modelo_camion;
tbAño.Text = camionModifica.Año.ToString();
cbTipo.SelectedItem = tipoCamion;
tbNro_chasis.Text = camionModifica.Nro_chasis;
tbNro_motor.Text = camionModifica.Nro_motor;
tbAlt_total.Text = camionModifica.Alto_total.ToString();
tbAncho_total.Text = camionModifica.Ancho_total.ToString();
tbLong_total.Text = camionModifica.Long_total.ToString();
tbPesoCarga.Text = camionModifica.Peso_carga.ToString();
tbObservaciones.Text = camionModifica.Observacion;
}
}
private void btnGuardar_unidad_Click(object sender, EventArgs e)
{
if (camion.Busqueda_dominio(tbDominio.Text.Trim()).Count> 0 && camionModifica==null)
{
MessageBox.Show("YA EXISTE UNA UNIDAD CON ESE DOMINIO", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
tbDominio.BackColor = Color.OrangeRed;
}
else if (camion.Busqueda_chasis(tbNro_chasis.Text.Trim()).Count > 0 && camionModifica == null)
{
tbDominio.BackColor = Color.White;
MessageBox.Show("YA EXISTE UNA UNIDAD CON ESE Nº CHASIS YA EXISTE", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
tbNro_chasis.BackColor = Color.OrangeRed;
}
else if (camion.Busqueda_motor(tbNro_motor.Text.Trim()).Count > 0 && camionModifica == null)
{
tbDominio.BackColor = Color.White;
tbNro_chasis.BackColor = Color.White;
MessageBox.Show("YA EXISTE UNA UNIDAD CON ESE Nº DE MOTOR YA EXISTE", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
tbNro_motor.BackColor = Color.OrangeRed;
}
else if (!new clsFunciones().Valida_Controles(this))
{
MessageBox.Show("FALTA LLENAR CAMPOS MARCADOS CON COLOR ROJO", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
if (camionModifica != null)
{
int marcaID = marca.retornaID_marca(cbMarca.SelectedItem.ToString().ToUpper().Trim());
int modeloID = modelo.retornaID_modelo(cbModelo.SelectedItem.ToString().ToUpper().Trim());
int tipo_camionID = tipo_camion.retornaID_tipoCamion(cbTipo.SelectedItem.ToString().ToUpper().Trim());
camion.Dominio = tbDominio.Text.ToUpper().Trim();
camion.Marca = marcaID;
camion.Modelo = modeloID;
camion.Año = tbAño.Text.ToUpper().Trim();
camion.Tara = float.Parse(tbTara.Text.ToUpper().Trim());
camion.Tipo = tipo_camionID;
camion.Nro_chasis = tbNro_chasis.Text.ToUpper().Trim();
camion.Nro_motor = tbNro_motor.Text.ToUpper().Trim();
camion.Ancho_total = float.Parse(tbAncho_total.Text.ToUpper().Trim());
camion.Alto_total = float.Parse(tbAlt_total.Text.ToUpper().Trim());
camion.Long_total = float.Parse(tbLong_total.Text.ToUpper().Trim());
camion.Peso_carga = float.Parse(tbPesoCarga.Text.ToUpper().Trim());
camion.Fecha_alta = DateTime.Now.ToString();
camion.Fecha_baja = DateTime.Now.ToString();
camion.Estado = "DISPONIBLE";
camion.Observacion = tbObservaciones.Text.Trim();
camion.modificar(camion.Dominio.ToString().Trim());
delegadoActualizaLista();
MessageBox.Show("CAMION MODIFICADO CON EXITO", "OK!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
int marcaID = marca.retornaID_marca(cbMarca.SelectedItem.ToString().ToUpper().Trim());
int modeloID = modelo.retornaID_modelo(cbModelo.SelectedItem.ToString().ToUpper().Trim());
int tipo_camionID = tipo_camion.retornaID_tipoCamion(cbTipo.SelectedItem.ToString().ToUpper().Trim());
camion.Dominio = tbDominio.Text.ToUpper().Trim();
camion.Marca = marcaID;
camion.Modelo = modeloID;
camion.Año = tbAño.Text.ToUpper().Trim();
camion.Tara = float.Parse(tbTara.Text.ToUpper().Trim());
camion.Tipo = tipo_camionID;
camion.Nro_chasis = tbNro_chasis.Text.ToUpper().Trim();
camion.Nro_motor = tbNro_motor.Text.ToUpper().Trim();
camion.Ancho_total = float.Parse(tbAncho_total.Text.ToUpper().Trim());
camion.Alto_total = float.Parse(tbAlt_total.Text.ToUpper().Trim());
camion.Long_total = float.Parse(tbLong_total.Text.ToUpper().Trim());
camion.Peso_carga = float.Parse(tbPesoCarga.Text.ToUpper().Trim());
camion.Fecha_alta = DateTime.Now.ToString();
camion.Fecha_baja = null;
camion.Estado = "DISPONIBLE";
camion.Observacion = tbObservaciones.Text.Trim();
camion.insertar();
delegadoActualizaLista();
MessageBox.Show("CAMION AÑADIDO CON EXITO", "OK!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
tbDominio.Clear();
cbModelo.SelectedIndex = 0;
tbAño.Clear();
tbTara.Clear();
tbAlt_total.Clear();
tbNro_chasis.Clear();
tbNro_motor.Clear();
tbAncho_total.Clear();
tbLong_total.Clear();
tbPesoCarga.Clear();
tbObservaciones.Clear();
cbMarca.SelectedIndex = 0;
cbTipo.SelectedIndex = 0;
tbDominio.Enabled = true;
cbMarca.Enabled = true;
cbModelo.Enabled = true;
cbTipo.Enabled = true;
tbAño.Enabled = true;
tbNro_motor.Enabled = true;
tbNro_chasis.Enabled = true;
}
}
private void tbAño_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsDigit(e.KeyChar))
{
e.Handled = false;
}
else if (Char.IsControl(e.KeyChar))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
private void tbDominio_TextChanged(object sender, EventArgs e)
{
new clsFunciones().fondoBlanco_Controles(sender);
}
private void gestionModeloToolStripMenuItem_Click(object sender, EventArgs e)
{
new frmGestorModeloCamion(conexion, delegadoModeloCamion).ShowDialog();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
namespace GestionTransporte.clases
{
public class clsChofer
{
#region Atributos y Propiedades
clsLogin usuario;//el usuario trae consigo la coneccion a la bd
int num_legajo;
string nombre;
string apellido;
string dni;
string num_cedula;
string domicilio;
string telefo1;
string telefo2;
string estado;
DataTable dt;
SqlDataAdapter da;
#region encapsulamiento de propiedades
public int Num_legajo
{
get { return num_legajo; }
set { num_legajo = value; }
}
public string Nombre
{
get { return nombre; }
set { nombre = value; }
}
public string Num_cedula
{
get { return num_cedula; }
set { num_cedula = value; }
}
public string Domicilio
{
get { return domicilio; }
set { domicilio = value; }
}
public string Telefo1
{
get { return telefo1; }
set { telefo1 = value; }
}
public string Telefo2
{
get { return telefo2; }
set { telefo2 = value; }
}
public string Estado
{
get { return estado; }
set { estado = value; }
}
public DataTable Dt
{
get { return dt; }
set { dt = value; }
}
#endregion
#endregion
public clsChofer(clsLogin usuario)
{
this.usuario = usuario;
this.dt = carga_lista_chofer();
} //Constructor de la clase
public DataTable carga_lista_chofer()
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("Select num_legajo,nombre,apellido,dni,num_cedula,direccion,telefono1,telefono2,estado from Chofer", usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
} //Funcion que carga todos los datos de BD a un DataTable
public DataView Listar_disponibles()
{
DataTable dtL = this.carga_lista_chofer();
DataView dv = new DataView(dtL);
dv.RowFilter = "estado = 'DISPONIBLE'";
return dv;
} //Funcion que lista todos los choferes disponibles
public DataView Listar_No_disponibles()
{
DataTable dtL = this.carga_lista_chofer();
DataView dv = new DataView(dtL);
dv.RowFilter = "estado = 'NO DISPONIBLE'";
return dv;
} //Funcion que lista todos los choferes no disponibles
public DataView Busqueda_nombre_apellido(string nombre, string apellido)
{
String filtro;
if (nombre == String.Empty)
filtro = "apellido like '" + apellido + "%' ";
else if(apellido==String.Empty)
filtro = "nombre like '" + nombre + "%' ";
else
filtro= "nombre like ' " + nombre + "%' or apellido like '" + apellido + "%' ";
DataView dv = new DataView(dt);
dv.RowFilter = filtro;
return dv;
} //Funcion que filtra choferes por nombre y apellido
public DataView Busqueda_numLegajo(string numLegajo)
{
if (numLegajo != String.Empty)
{
DataView dv = new DataView(dt);
dv.RowFilter = "num_legajo = " + Convert.ToInt32(numLegajo) + " ";
return dv;
}
else
return null;
} //Funcion que filtra choferes por numero de legajo
public DataView Busqueda_dni(string dni)
{
DataView dv = new DataView(dt);
dv.RowFilter = "dni like '" + dni + "%' ";
return dv;
} //Funcion que filtra choferes por dni
}
}<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 GestionTransporte.clases;
namespace GestionTransporte
{
public delegate void actualizaTipoCamion();
public partial class frmTipoCamion : Form
{
clsTipo_camion tipoCamion;
actualizaTipoCamion delegadoTipoCamion;
public frmTipoCamion(clsLogin conexion,Delegate actualiza)
{
InitializeComponent();
this.tipoCamion = new clsTipo_camion(conexion);
delegadoTipoCamion = (actualizaTipoCamion)actualiza;
}
private void btnAgregar_Click(object sender, EventArgs e)
{
string resp;
if (tbAgregar.Text.Trim() == string.Empty)
{
tbAgregar.BackColor = Color.OrangeRed;
MessageBox.Show("FALTA LLENAR CAMPOS MARCADOS CON COLOR ROJO", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}else{
tipoCamion.Tipo = tbAgregar.Text.ToUpper().Trim();
resp = tipoCamion.insertar();
delegadoTipoCamion();
if (resp != String.Empty)
MessageBox.Show(resp);
dgvTipoCamion.DataSource = tipoCamion.ver_tipoCamion();
if (dgvTipoCamion.Rows.Count < 1)
{
tbModificar.Enabled = false;
tbEliminar.Enabled = false;
}
tbAgregar.Clear();
}
if (sender == btnModificar)
{
if (tbModificar.Text.Trim() == string.Empty)
{
tbModificar.BackColor = Color.OrangeRed;
MessageBox.Show("FALTA LLENAR CAMPOS MARCADOS CON COLOR ROJO", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
tbModificar.BackColor=Color.White;
tipoCamion.Tipo = tbModificar.Text.ToUpper().Trim(); ;
resp = tipoCamion.modificar(dgvTipoCamion.SelectedCells[0].Value.ToString());
if (resp != String.Empty)
MessageBox.Show(resp);
dgvTipoCamion.DataSource = tipoCamion.ver_tipoCamion();
}
}
if (sender == btnEliminar)
{
tbAgregar.BackColor = Color.White;
tbModificar.BackColor = Color.White;
tipoCamion.Tipo = tbEliminar.Text;
resp = tipoCamion.eliminar(dgvTipoCamion.SelectedCells[0].Value.ToString());
if (resp != String.Empty)
MessageBox.Show(resp);
else
{
tbEliminar.Clear();
tbModificar.Clear();
}
dgvTipoCamion.DataSource = tipoCamion.ver_tipoCamion();
if (dgvTipoCamion.Rows.Count < 1)
{
tbModificar.Enabled = false;
tbEliminar.Enabled = false;
}
}
}
private void frmTipoCamion_Load(object sender, EventArgs e)
{
dgvTipoCamion.DataSource = tipoCamion.ver_tipoCamion();
if (dgvTipoCamion.Rows.Count < 1)
{
btnModificar.Enabled = false;
btnEliminar.Enabled = false;
}
}
private void dgvTipoCamion_CellClick(object sender, DataGridViewCellEventArgs e)
{
tbModificar.Text = dgvTipoCamion.SelectedCells[0].Value.ToString();
tbEliminar.Text = dgvTipoCamion.SelectedCells[0].Value.ToString();
}
private void dgvTipoCamion_DataSourceChanged(object sender, EventArgs e)
{
if (dgvTipoCamion.RowCount != 0)
{
tbModificar.Text = dgvTipoCamion.SelectedCells[0].Value.ToString();
tbEliminar.Text = dgvTipoCamion.SelectedCells[0].Value.ToString();
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GestionTransporte.clases
{
public class Reparacion
{
Login usuario;//el usuario trae consigo la coneccion a la bd
Camion camion;
int num_legajo;
DateTime entrada_taller;
DateTime salida_taller;
DateTime salida_aprox;
string observaciones;
#region encapsulamiento de propiedades
public Camion Camion
{
get { return camion; }
set { camion = value; }
}
public int Num_legajo
{
get { return num_legajo; }
set { num_legajo = value; }
}
public DateTime Entrada_taller
{
get { return entrada_taller; }
set { entrada_taller = value; }
}
public DateTime Salida_taller
{
get { return salida_taller; }
set { salida_taller = value; }
}
public DateTime Salida_aprox
{
get { return salida_aprox; }
set { salida_aprox = value; }
}
public string Observaciones
{
get { return observaciones; }
set { observaciones = value; }
}
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
namespace GestionTransporte.clases
{
public class clsCamion
{
#region Atributos y Propiedades
clsLogin usuario;//el usuario trae consigo la coneccion a la bd
string id;
string dominio;
int marca;
int modelo;
string año;
float tara;
int tipo;
string nro_chasis;
string nro_motor;
float ancho_total;
float alto_total;
float long_total;
float peso_carga;
string fecha_alta;
string fecha_baja;
string estado;// Disponible,en viaje,dado de baja ,en reparacion etc.
string observacion;
DataTable dt;
SqlDataAdapter da;
#region encapsulamiento de propiedades
public DataTable Dt
{
get { return dt; }
set { dt = value; }
}
public int Modelo
{
get { return modelo; }
set { modelo = value; }
}
public string Id
{
get { return id; }
set { id = value; }
}
public string Dominio
{
get { return dominio; }
set { dominio = value; }
}
public int Marca
{
get { return marca; }
set { marca = value; }
}
public string Año
{
get { return año; }
set { año = value; }
}
public float Tara
{
get { return tara; }
set { tara = value; }
}
public int Tipo
{
get { return tipo; }
set { tipo = value; }
}
public string Nro_chasis
{
get { return nro_chasis; }
set { nro_chasis = value; }
}
public string Nro_motor
{
get { return nro_motor; }
set { nro_motor = value; }
}
public float Ancho_total
{
get { return ancho_total; }
set { ancho_total = value; }
}
public float Alto_total
{
get { return alto_total; }
set { alto_total = value; }
}
public float Long_total
{
get { return long_total; }
set { long_total = value; }
}
public float Peso_carga
{
get { return peso_carga; }
set { peso_carga = value; }
}
public String Fecha_alta
{
get { return fecha_alta; }
set { fecha_alta = value; }
}
public String Fecha_baja
{
get { return fecha_baja; }
set { fecha_baja = value; }
}
public string Estado
{
get { return estado; }
set { estado = value; }
}
public string Observacion
{
get { return observacion; }
set { observacion = value; }
}
#endregion
#endregion
public clsCamion(clsLogin usuario)
{
this.usuario = usuario;
this.dt = carga_camiones_total();
} //Constructor de la clase
public string insertar()
{
string respuesta;
SqlCommand cmd = new SqlCommand();
cmd.Connection = usuario.cnn;
cmd.CommandText = "insert into camion (dominio,marca,tara,modelo,año,tipo,nro_chasis,nro_motor,alt_total,ancho_total,long_total,peso_carga,estado,observaciones,fecha_alta,fecha_baja) values ('" + Dominio + "','" + Marca + "','" + Tara + "','" + Modelo + "','" + Año + "','" + Tipo + "','" + Nro_chasis + "','" + Nro_motor + "','" + Alto_total + "','" + Ancho_total + "','" + Long_total + "','" + Peso_carga + "','" + Estado + "','" + Observacion + "','"+Fecha_alta+"','"+Fecha_baja+"');SELECT Scope_Identity();";
cmd.CommandType = CommandType.Text;
usuario.Modo(TipoConexion.Abrir);
string id_insertado = cmd.ExecuteScalar().ToString();
if (id_insertado != null)
{
cmd.CommandText = "insert into auditoria values ('" + (DateTime.Now).ToString() + "','" + usuario.Usuario + "','" + "se inserto camion id " + id_insertado + "')";
cmd.ExecuteNonQuery();
respuesta = string.Empty;
}
else
{
respuesta = "Error al insertar unidad";
}
usuario.cnn.Close();
return respuesta;
// todas las funciones de abm y otras se ejecutan con la propiedades y el login q pasamos por constructor
} //Funcion insertar un nuevo camion
public string dar_baja(string dom, string estado)
{
string respuesta = String.Empty;
if (estado == "DISPONIBLE")
{
SqlCommand cmd = new SqlCommand();
try
{
cmd.Connection = usuario.cnn;
cmd.CommandText = "update camion set estado='DESAHABILITADO' where dominio='" + dom + "';SELECT Scope_Identity();";
cmd.CommandType = CommandType.Text;
usuario.Modo(TipoConexion.Abrir);
string id_insertado = cmd.ExecuteScalar().ToString();
if (id_insertado != null)
{
cmd.CommandText = "insert into auditoria values ('" + (DateTime.Now).ToString() + "','" + usuario.Usuario + "','" + "se dio de baja camion dominio" + dom + "')";
cmd.ExecuteNonQuery();
}
else
{
respuesta = "Error al dar de baja camion";
}
}
catch (SqlException ex)
{
respuesta = ex.ErrorCode.ToString();
}
usuario.Modo(TipoConexion.Cerrar);
}
else
respuesta = "Error, no se puede desahabilitar. Compruebe que el estado del mismo sea DISPONIBLE";
usuario.cnn.Close();
return respuesta;
} //Funcion para dar de baja un camion
public string modificar(string dominioModifica)
{
string respuesta;
SqlCommand cmd = new SqlCommand();
cmd.Connection = usuario.cnn;
cmd.CommandText = "update camion set marca='" + Marca + "',tara='" + Tara + "',modelo='" + Modelo + "',año='" + Año + "',tipo='" + Tipo + "',nro_chasis='" + Nro_chasis + "',nro_motor='" + Nro_motor + "',alt_total='" + Alto_total + "',ancho_total='" + Ancho_total + "',long_total='" + Long_total + "',peso_carga='" + Peso_carga + "',estado='" + Estado + "',observaciones='" + Observacion + "' where dominio='" + dominioModifica + "';SELECT Scope_Identity();";
cmd.CommandType = CommandType.Text;
usuario.Modo(TipoConexion.Abrir);
string id_insertado = cmd.ExecuteScalar().ToString();
if (id_insertado != null)
{
cmd.CommandText = "insert into auditoria values ('" + (DateTime.Now).ToString() + "','" + usuario.Usuario + "','" + "se modifico camion dominio " + dominioModifica + "')";
cmd.ExecuteNonQuery();
respuesta = string.Empty;
}
else
{
respuesta = "Error al modificar unidad";
}
usuario.cnn.Close();
return respuesta;
// todas las funciones de abm y otras se ejecutan con la propiedades y el login q pasamos por constructor
} //Funcion para modificar algun campo de camion
public DataTable carga_camiones_total()
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("Select c.dominio,m.marca,mc.modelo,c.año,t.tipo,c.estado,c.tara,c.nro_chasis,c.nro_motor,c.alt_total,c.ancho_total,c.long_total,c.peso_carga,c.observaciones,c.fecha_alta,c.fecha_baja,c.id_camion From camion c join marca_camion m on c.marca=m.id join tipo_camion t on c.tipo=t.id join modelo_camion mc on c.modelo=mc.id", usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
} //Carga todos los datos de la BD a un DataTable
public DataView Busqueda_dominio(string dominio)
{
DataView dv = new DataView(dt);
dv.RowFilter = "dominio like '" + dominio + "%'";
return dv;
} //Funcion que filtra camion por dominio
public DataView Busqueda_chasis(string chasis)
{
DataView dv = new DataView(dt);
dv.RowFilter = "nro_chasis like '" + chasis + "%'";
return dv;
} //Funcion que filtra camion por numero chasis
public DataView Busqueda_motor(string motor)
{
DataView dv = new DataView(dt);
dv.RowFilter = "nro_motor like '" + motor + "%'";
return dv;
} //Funcion que filtra camion por numero de motor
public DataTable Busqueda_peso_carga(float cargaMin, float cargaMax)
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("Select c.dominio,m.marca,mc.modelo,c.año,t.tipo,c.estado,c.tara,c.nro_chasis,c.nro_motor,c.alt_total,c.ancho_total,c.long_total,c.peso_carga,c.observaciones,c.fecha_alta,c.fecha_baja,c.id_camion From camion c join marca_camion m on c.marca=m.id join tipo_camion t on c.tipo=t.id join modelo_camion mc on c.modelo=mc.modelo where peso_carga >= '" + cargaMin + "' and peso_carga <= '" + cargaMax + "'", usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
} //Funcion que filtra camion por peso de carga
public DataTable Busqueda_fecha_alta(string desde, string hasta)
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("Select c.dominio,m.marca,mc.modelo,c.año,t.tipo,c.estado,c.tara,c.nro_chasis,c.nro_motor,c.alt_total,c.ancho_total,c.long_total,c.peso_carga,c.observaciones,c.fecha_alta,c.fecha_baja,c.id_camion From camion c join marca_camion m on c.marca=m.id join tipo_camion t on c.tipo=t.id join modelo_camion mc on c.modelo=mc.modelo where TRY_PARSE(c.fecha_alta as datetime) between '" + desde + "' and '" + hasta + "'", usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
} //Funcion que filtra camiones por fecha de alta
public DataTable Busqueda_fecha_baja(string desde, string hasta)
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("Select c.dominio,m.marca,mc.modelo,c.año,t.tipo,c.estado,c.tara,c.nro_chasis,c.nro_motor,c.alt_total,c.ancho_total,c.long_total,c.peso_carga,c.observaciones,c.fecha_alta,c.fecha_baja,c.id_camion From camion c join marca_camion m on c.marca=m.id join tipo_camion t on c.tipo=t.id join modelo_camion mc on c.modelo=mc.modelo where TRY_PARSE(c.fecha_baja as datetime) between '" + desde + "' and '" + hasta + "'", usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
} //Funcion que filtra camiones por fecha de baja
public string retorna_Estado()
{
return Estado;
} //Funcion que retorna estado de la unidad
public List<String> Retorna_marcasComboBox()
{
List<String> lista = new List<string>();
SqlConnection cn = usuario.cnn;
cn.Open();
SqlCommand cmdMarca = new SqlCommand("Select * From marca_camion", cn);
SqlDataReader drMarca = cmdMarca.ExecuteReader();
while (drMarca.Read())
{
lista.Add(drMarca["marca"].ToString());
}
cn.Close();
return lista;
} //Funcion que retorna items para combo box Marca
public List<String> Retorna_tiposComboBox()
{
List<String> lista = new List<string>();
SqlConnection cn = usuario.cnn;
cn.Open();
SqlCommand cmdTipo = new SqlCommand("Select * From tipo_camion", cn);
SqlDataReader drTipo = cmdTipo.ExecuteReader();
while (drTipo.Read())
{
lista.Add(drTipo["tipo"].ToString());
}
cn.Close();
return lista;
} //Funcion que retorna items para combo box Tipos
public List<String> Retorna_modeloComboBox()
{
List<String> lista = new List<string>();
SqlConnection cn = usuario.cnn;
cn.Open();
SqlCommand cmdModelo = new SqlCommand("Select * From modelo_camion", cn);
SqlDataReader drModelo = cmdModelo.ExecuteReader();
while (drModelo.Read())
{
lista.Add(drModelo["modelo"].ToString());
}
cn.Close();
return lista;
} //Funcion que retorna items para combo box Modelos
public clsCamion Retorna_camion(string dom)
{
try
{
clsCamion camion = new clsCamion(usuario);
SqlCommand cmd = new SqlCommand();
usuario.cnn.Open();
cmd.Connection = usuario.cnn;
cmd.CommandText = "Select dominio,marca,modelo,año,tipo,estado,tara,nro_chasis,nro_motor,alt_total,ancho_total,long_total,peso_carga,observaciones,fecha_alta,fecha_baja,id_camion From camion c where c.dominio = '" + dom + "' ";
cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
camion.dominio = dr[0].ToString();
camion.marca = Convert.ToInt32(dr[1]);
camion.modelo = Convert.ToInt32(dr[2]);
camion.año = dr[3].ToString();
camion.tipo = Convert.ToInt32(dr[4]);
camion.Estado = dr[5].ToString();
camion.tara = float.Parse(dr[6].ToString());
camion.nro_chasis = dr[7].ToString();
camion.nro_motor = dr[8].ToString();
camion.alto_total = float.Parse(dr[9].ToString());
camion.ancho_total = float.Parse(dr[10].ToString());
camion.long_total = float.Parse(dr[11].ToString());
camion.Peso_carga = float.Parse(dr[12].ToString());
camion.observacion = dr[13].ToString();
camion.fecha_alta = dr[14].ToString();
camion.fecha_baja = dr[15].ToString();
camion.id = dr[16].ToString();
}
usuario.cnn.Close();
return camion;
}
catch (Exception)
{
return null;
}
}
public clsCamion Busqueda_id(string id)
{
try
{
clsCamion camion = new clsCamion(usuario);
SqlCommand cmd = new SqlCommand();
usuario.cnn.Open();
cmd.Connection = usuario.cnn;
cmd.CommandText = "Select * from camion where id_camion = '" + id + "' ";
cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
camion.dominio = dr[1].ToString();
camion.marca = Convert.ToInt32(dr[2]);
camion.tara = float.Parse(dr[3].ToString());
camion.modelo = Convert.ToInt32(dr[4]);
camion.año = dr[5].ToString();
camion.tipo = Convert.ToInt32(dr[6]);
camion.nro_chasis = dr[7].ToString();
camion.nro_motor = dr[8].ToString();
camion.alto_total = float.Parse(dr[9].ToString());
camion.ancho_total = float.Parse(dr[10].ToString());
camion.long_total = float.Parse(dr[11].ToString());
camion.peso_carga = float.Parse(dr[12].ToString());
camion.Estado = dr[13].ToString();
camion.observacion = dr[14].ToString();
camion.fecha_alta = dr[15].ToString();
camion.fecha_baja = dr[16].ToString();
camion.id = dr[0].ToString();
}
usuario.cnn.Close();
return camion;
}
catch (Exception)
{
return null;
}
}
public DataTable Listar_dados_de_baja()
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("Select c.dominio,m.marca,mc.modelo,c.año,t.tipo,c.estado,c.tara,c.nro_chasis,c.nro_motor,c.alt_total,c.ancho_total,c.long_total,c.peso_carga,c.observaciones,c.fecha_alta,c.fecha_baja,c.id_camion From camion c join marca_camion m on c.marca=m.id join tipo_camion t on c.tipo=t.id join modelo_camion mc on c.modelo=mc.id where c.estado='DADO DE BAJA'", usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
} //Funcion que lista todos los camiones dado de baja
public DataTable Listar_disponibles()
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("Select c.dominio,m.marca,mc.modelo,c.año,t.tipo,c.estado,c.tara,c.nro_chasis,c.nro_motor,c.alt_total,c.ancho_total,c.long_total,c.peso_carga,c.observaciones,c.fecha_alta,c.fecha_baja,c.id_camion From camion c join marca_camion m on c.marca=m.id join tipo_camion t on c.tipo=t.id join modelo_camion mc on c.modelo=mc.id where c.estado='DISPONIBLE'", usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
} //Funcion que lista todos los camiones disponibles
public DataTable Listar_en_viaje()
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("Select c.dominio,m.marca,mc.modelo,c.año,t.tipo,c.estado,c.tara,c.nro_chasis,c.nro_motor,c.alt_total,c.ancho_total,c.long_total,c.peso_carga,c.observaciones,c.fecha_alta,c.fecha_baja,c.id_camion From camion c join marca_camion m on c.marca=m.id join tipo_camion t on c.tipo=t.id join modelo_camion mc on c.modelo=mc.id where c.estado='EN VIAJE'", usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
} //Funcion que lista todos los camiones en viaje
public DataTable Listar_taller()
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("Select c.dominio,m.marca,mc.modelo,c.año,t.tipo,c.estado,c.tara,c.nro_chasis,c.nro_motor,c.alt_total,c.ancho_total,c.long_total,c.peso_carga,c.observaciones,c.fecha_alta,c.fecha_baja,c.id_camion From camion c join marca_camion m on c.marca=m.id join tipo_camion t on c.tipo=t.id join modelo_camion mc on c.modelo=mc.id where c.estado='EN TALLER'", usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
} //Funcion que lista todos los camiones en taller
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
namespace GestionTransporte.clases
{
public class clsAcoplado
{
#region Atributos y Propiedades
clsLogin usuario;//el usuario trae consigo la coneccion a la bd
string id;
string dominio;
int marca;
string modelo;
string año;
float tara;
int tipo;
float alt_total;
string nro_chasis;
float ancho_interior;
float ancho_exterior;
float long_plataforma;
float capacidad_carga;
float cant_de_ejes;
string observaciones;
string fecha_alta;
string fecha_baja;
string estado;// Disponible,en viaje,dado de baja ,en reparacion etc.
DataTable dt;
SqlDataAdapter da;
#region encapsulamiento de propiedades
public DataTable Dt
{
get { return dt; }
set { dt = value; }
}
public string Modelo
{
get { return modelo; }
set { modelo = value; }
}
public string Id
{
get { return id; }
set { id = value; }
}
public string Dominio
{
get { return dominio; }
set { dominio = value; }
}
public int Marca
{
get { return marca; }
set { marca = value; }
}
public string Año
{
get { return año; }
set { año = value; }
}
public float Tara
{
get { return tara; }
set { tara = value; }
}
public int Tipo
{
get { return tipo; }
set { tipo = value; }
}
public float Alt_total
{
get { return alt_total; }
set { alt_total = value; }
}
public string Nro_chasis
{
get { return nro_chasis; }
set { nro_chasis = value; }
}
public float Ancho_interior
{
get { return ancho_interior; }
set { ancho_interior = value; }
}
public float Ancho_exterior
{
get { return ancho_exterior; }
set { ancho_exterior = value; }
}
public float Long_plataforma
{
get { return long_plataforma; }
set { long_plataforma = value; }
}
public float Capacidad_carga
{
get { return capacidad_carga; }
set { capacidad_carga = value; }
}
public float Cant_de_ejes
{
get { return cant_de_ejes; }
set { cant_de_ejes = value; }
}
public String Fecha_alta
{
get { return fecha_alta; }
set { fecha_alta = value; }
}
public String Fecha_baja
{
get { return fecha_baja; }
set { fecha_baja = value; }
}
public string Observaciones
{
get { return observaciones; }
set { observaciones = value; }
}
public string Estado
{
get { return estado; }
set { estado = value; }
}
#endregion
#endregion
public clsAcoplado(clsLogin usuario)
{
this.usuario = usuario;
} //Constructor de la clase Acoplado
public string insertar()
{
string respuesta;
SqlCommand cmd = new SqlCommand();
cmd.Connection = usuario.cnn;
cmd.CommandText = "insert into acoplado (dominio,marca,modelo,año,tara,tipo,alt_total,nro_chasis,ancho_interior,ancho_exterior,long_plataforma,capacidad_carga,cant_ejes,estado,observaciones,fecha_alta,fecha_baja) values ('" + Dominio + "','" + Marca + "','" + Modelo + "','" + Año + "'," + Tara + ",'" + Tipo + "','" + Alt_total + "','" + Nro_chasis + "','" + Ancho_interior + "','" + Ancho_exterior + "','" + Long_plataforma + "','" + Capacidad_carga + "','" + Cant_de_ejes + "','" + Estado + "','" + Observaciones + "','" + Fecha_alta + "','" + Fecha_baja + "');SELECT Scope_Identity();";
cmd.CommandType = CommandType.Text;
usuario.Modo(TipoConexion.Abrir);
string id_insertado = cmd.ExecuteScalar().ToString();
if (id_insertado != null)
{
cmd.CommandText = "insert into auditoria values ('" + (DateTime.Now).ToString() + "','" + usuario.Usuario + "','" + "se inserto acoplado id " + id_insertado + "')";
cmd.ExecuteNonQuery();
respuesta = string.Empty;
}
else
{
respuesta = "Error al insertar unidad";
}
usuario.cnn.Close();
return respuesta;
// todas las funciones de abm y otras se ejecutan con la propiedades y el login q pasamos por constructor
} //Funcion para insertar un nuevo acoplado
public string dar_baja(string dom, string estado)
{
string respuesta=String.Empty;
if (estado == "DISPONIBLE")
{
SqlCommand cmd = new SqlCommand();
try
{
cmd.Connection = usuario.cnn;
cmd.CommandText = "update acoplado set estado='DESAHABILITADO' where dominio='" + dom + "';SELECT Scope_Identity();";
cmd.CommandType = CommandType.Text;
usuario.Modo(TipoConexion.Abrir);
string id_insertado = cmd.ExecuteScalar().ToString();
if (id_insertado != null)
{
cmd.CommandText = "insert into auditoria values ('" + (DateTime.Now).ToString() + "','" + usuario.Usuario + "','" + "se dio de baja acoplado dominio" + dom + "')";
cmd.ExecuteNonQuery();
}
else
{
respuesta = "Error al dar de baja acoplado";
}
}
catch (SqlException ex)
{
respuesta = ex.ErrorCode.ToString();
}
usuario.Modo(TipoConexion.Cerrar);
}
else
respuesta="Error, no se puede desahabilitar. Compruebe que el estado del mismo sea DISPONIBLE";
usuario.cnn.Close();
return respuesta;
} //Funcion para dar baja a un acoplado
public string modificar(string domModifica)
{
string respuesta;
SqlCommand cmd = new SqlCommand();
cmd.Connection = usuario.cnn;
cmd.CommandText = "update acoplado set marca='" + Marca + "',modelo='" + Modelo + "',año='" + Año + "',tara='" + Tara + "',tipo='" + Tipo + "',alt_total='" + Alt_total + "',nro_chasis='" + Nro_chasis + "',ancho_interior='" + Ancho_interior + "',ancho_exterior='" + Ancho_exterior + "',long_plataforma='" + Long_plataforma + "',capacidad_carga='" + Capacidad_carga + "',cant_ejes='" + Cant_de_ejes + "',estado='" + Estado + "',observaciones='" + Observaciones + "' where dominio='" + domModifica + "';SELECT Scope_Identity();";
cmd.CommandType = CommandType.Text;
usuario.Modo(TipoConexion.Abrir);
string id_insertado = cmd.ExecuteScalar().ToString();
//int =
if (id_insertado != null)
{
cmd.CommandText = "insert into auditoria values ('" + (DateTime.Now).ToString() + "','" + usuario.Usuario + "','" + "se modifico acoplado dominio " + domModifica + "')";
cmd.ExecuteNonQuery();
respuesta = string.Empty;
}
else
{
respuesta = "Error al modificar acoplado";
}
usuario.cnn.Close();
return respuesta;
// todas las funciones de abm y otras se ejecutan con la propiedades y el login q pasamos por constructor
} //Funcion para modificar datos de un acoplado ya guardado
public string modificar_estado(string domModifica, string estado)
{
string respuesta;
SqlCommand cmd = new SqlCommand();
cmd.Connection = usuario.cnn;
cmd.CommandText = "update acoplado (estado) set estado='" + estado + "' where dominio='" + domModifica + "');SELECT Scope_Identity();";
cmd.CommandType = CommandType.Text;
usuario.Modo(TipoConexion.Abrir);
string id_insertado = cmd.ExecuteScalar().ToString();
//int =
if (id_insertado != null)
{
cmd.CommandText = "insert into auditoria values ('" + (DateTime.Now).ToString() + "','" + usuario.Usuario + "','" + "se modifico el estado del acoplado dominio : " + domModifica + "')";
cmd.ExecuteNonQuery();
respuesta = string.Empty;
}
else
{
respuesta = "Error al modificar acoplado";
}
usuario.cnn.Close();
return respuesta;
// todas las funciones de abm y otras se ejecutan con la propiedades y el login q pasamos por constructor
} //Funcion que modifica el estado de un acoplado por su dominio
public DataTable carga_acoplados_total()
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("Select a.dominio ,m.marca ,a.modelo ,a.año ,a.tara ,t.tipo ,a.alt_total ,a.nro_chasis ,a.ancho_interior ,a.ancho_exterior ,a.long_plataforma ,a.capacidad_carga ,a.cant_ejes ,a.estado ,a.observaciones ,a.fecha_alta ,a.fecha_baja ,id_acoplado From acoplado a join tipo_acoplado t on a.tipo=t.id join marca_acoplado m on a.marca=m.id", usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
} //Funcion que carga todos los acoplados de la BD a un DataTable
public DataTable carga_data_view()
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("Select a.dominio ,m.marca ,a.modelo ,a.año ,a.tara ,t.tipo ,a.alt_total ,a.nro_chasis ,a.ancho_interior ,a.ancho_exterior ,a.long_plataforma ,a.capacidad_carga ,a.cant_ejes ,a.estado ,a.observaciones ,a.fecha_alta ,a.fecha_baja ,id_acoplado From acoplado a join tipo_acoplado t on a.tipo=t.id join marca_acoplado m on a.marca=m.id", usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
} //Funcion que carga todos los datos de BD a DataView
public DataView Busqueda_dominio(string dominio)
{
DataView dv = new DataView(carga_data_view());
dv.RowFilter = "dominio like '" + dominio + "%'";
return dv;
} //Funcion filtra busqueda por dominio
public DataView Busqueda_chasis(string chasis)
{
DataView dv = new DataView(carga_data_view());
dv.RowFilter = "nro_chasis like '" + chasis + "%'";
return dv;
} //Funcion filtra busqueda por nro chasis
public DataTable Busqueda_fecha_alta(string desde, string hasta)
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("Select a.dominio ,m.marca ,a.modelo ,a.año ,a.tara ,t.tipo ,a.alt_total ,a.nro_chasis ,a.ancho_interior ,a.ancho_exterior ,a.long_plataforma ,a.capacidad_carga ,a.cant_ejes ,a.estado ,a.observaciones ,a.fecha_alta ,a.fecha_baja ,id_acoplado From acoplado a join tipo_acoplado t on a.tipo=t.id join marca_acoplado m on a.marca=m.id where TRY_PARSE(fecha_alta as datetime) between '" + desde + "' and '" + hasta + "'", usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
} //Funcion filtra busqueda por fecha alta
public DataTable Busqueda_fecha_baja(string desde, string hasta)
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("Select a.dominio ,m.marca ,a.modelo ,a.año ,a.tara ,t.tipo ,a.alt_total ,a.nro_chasis ,a.ancho_interior ,a.ancho_exterior ,a.long_plataforma ,a.capacidad_carga ,a.cant_ejes ,a.estado ,a.observaciones ,a.fecha_alta ,a.fecha_baja ,id_acoplado From acoplado a join tipo_acoplado t on a.tipo=t.id join marca_acoplado m on a.marca=m.id where TRY_PARSE(fecha_baja as datetime using 'es-ES') between'" + Convert.ToDateTime(desde) + "' and '" + Convert.ToDateTime(hasta) + "'", usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
} //Funcion filtra busqueda por fecha baja
public DataTable Busqueda_peso_carga(float cargaMin, float cargaMax)
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("Select a.dominio ,m.marca ,a.modelo ,a.año ,a.tara ,t.tipo ,a.alt_total ,a.nro_chasis ,a.ancho_interior ,a.ancho_exterior ,a.long_plataforma ,a.capacidad_carga ,a.cant_ejes ,a.estado ,a.observaciones ,a.fecha_alta ,a.fecha_baja ,id_acoplado From acoplado a join tipo_acoplado t on a.tipo=t.id join marca_acoplado m on a.marca=m.id where capacidad_carga >= '" + cargaMin + "' and capacidad_carga <= '" + cargaMax + "'", usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
} //Funcion que filtra acoplado por peso de carga
public string retorna_Estado()
{
return Estado;
} //Funcion que retorna estado de la unidad
public clsAcoplado Retorna_acoplado(string dom)
{
try
{
clsAcoplado acoplado = new clsAcoplado(usuario);
SqlCommand cmd = new SqlCommand();
usuario.cnn.Open();
cmd.Connection = usuario.cnn;
cmd.CommandText = "Select dominio,marca,modelo,año,tara,tipo,alt_total,nro_chasis,ancho_interior,ancho_exterior,long_plataforma,capacidad_carga,cant_ejes,estado,observaciones,fecha_alta,fecha_baja,id_acoplado From acoplado a where dominio = '" + dom + "' ";
cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
acoplado.dominio = dr[0].ToString();
acoplado.marca = Convert.ToInt32(dr[1]);
acoplado.modelo = dr[2].ToString();
acoplado.año = dr[3].ToString();
acoplado.tara = float.Parse(dr[4].ToString());
acoplado.tipo = Convert.ToInt32(dr[5]);
acoplado.alt_total = float.Parse(dr[6].ToString());
acoplado.nro_chasis = dr[7].ToString();
acoplado.ancho_interior = float.Parse(dr[8].ToString());
acoplado.ancho_exterior = float.Parse(dr[9].ToString());
acoplado.long_plataforma = float.Parse(dr[10].ToString());
acoplado.capacidad_carga = float.Parse(dr[11].ToString());
acoplado.cant_de_ejes = Convert.ToInt32(dr[12].ToString());
acoplado.estado = dr[13].ToString();
acoplado.observaciones = dr[14].ToString();
acoplado.fecha_alta = dr[15].ToString();
acoplado.fecha_baja = dr[16].ToString();
acoplado.id = dr[17].ToString();
}
usuario.cnn.Close();
return acoplado;
}
catch (Exception)
{
return null;
}
} //Funcion que retorna un objeto acoplado completo
public List<String> Retorna_marcasComboBox()
{
List<String> lista = new List<string>();
SqlConnection cn = usuario.cnn;
cn.Open();
SqlCommand cmdMarca = new SqlCommand("Select * From marca_acoplado", cn);
SqlDataReader drMarca = cmdMarca.ExecuteReader();
while (drMarca.Read())
{
lista.Add(drMarca["marca"].ToString());
}
cn.Close();
return lista;
} //Funcion que retorna items para combo box Marca
public List<String> Retorna_tiposComboBox()
{
List<String> lista = new List<string>();
SqlConnection cn = usuario.cnn;
cn.Open();
SqlCommand cmdMarca = new SqlCommand("Select * From tipo_acoplado", cn);
SqlDataReader drMarca = cmdMarca.ExecuteReader();
while (drMarca.Read())
{
lista.Add(drMarca["tipo"].ToString());
}
cn.Close();
return lista;
} //Funcion que retorna items para combo box Marca
public clsAcoplado Busqueda_id(string id)
{
try
{
clsAcoplado acoplado = new clsAcoplado(usuario);
SqlCommand cmd = new SqlCommand();
usuario.cnn.Open();
cmd.Connection = usuario.cnn;
cmd.CommandText = "Select a.dominio ,a.marca ,a.modelo ,a.año ,a.tara ,a.tipo ,a.alt_total ,a.nro_chasis ,a.ancho_interior ,a.ancho_exterior ,a.long_plataforma ,a.capacidad_carga ,a.cant_ejes ,a.estado ,a.observaciones ,a.fecha_alta ,a.fecha_baja ,id_acoplado From acoplado a join tipo_acoplado t on a.tipo=t.id join marca_acoplado m on a.marca=m.id where id_acoplado= '" + id + "' ";
cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
acoplado.dominio = dr[0].ToString();
acoplado.marca = Convert.ToInt32(dr[1]);
acoplado.modelo = dr[2].ToString();
acoplado.año = dr[3].ToString();
acoplado.tara = float.Parse(dr[4].ToString());
acoplado.tipo = Convert.ToInt32(dr[5]);
acoplado.alt_total = float.Parse(dr[6].ToString());
acoplado.nro_chasis = dr[7].ToString();
acoplado.ancho_interior = float.Parse(dr[8].ToString());
acoplado.ancho_exterior = float.Parse(dr[9].ToString());
acoplado.long_plataforma = float.Parse(dr[10].ToString());
acoplado.capacidad_carga = float.Parse(dr[11].ToString());
acoplado.cant_de_ejes = Convert.ToInt32(dr[12].ToString());
acoplado.estado = dr[13].ToString();
acoplado.observaciones = dr[14].ToString();
acoplado.fecha_alta = dr[15].ToString();
acoplado.fecha_baja = dr[16].ToString();
acoplado.id = dr[17].ToString();
}
usuario.cnn.Close();
return acoplado;
}
catch (Exception)
{
return null;
}
} //Funcion que retorna un objeto acoplado completo
public DataTable listar_todo()
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("Select a.dominio ,m.marca ,a.modelo ,a.año ,a.tara ,t.tipo ,a.alt_total ,a.nro_chasis ,a.ancho_interior ,a.ancho_exterior ,a.long_plataforma ,a.capacidad_carga ,a.cant_ejes ,a.estado ,a.observaciones ,a.fecha_alta ,a.fecha_baja ,id_acoplado From acoplado a join tipo_acoplado t on a.tipo=t.id join marca_acoplado m on a.marca=m.id ", usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
} //Funcion que carga a un DataView todo los datos que hay en el DataTable
public DataTable Listar_dados_de_baja()
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("Select a.dominio ,m.marca ,a.modelo ,a.año ,a.tara ,t.tipo ,a.alt_total ,a.nro_chasis ,a.ancho_interior ,a.ancho_exterior ,a.long_plataforma ,a.capacidad_carga ,a.cant_ejes ,a.estado ,a.observaciones ,a.fecha_alta ,a.fecha_baja ,id_acoplado From acoplado a join tipo_acoplado t on a.tipo=t.id join marca_acoplado m on a.marca=m.id where a.estado='DADO DE BAJA'", usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
} //Funcion que lista todos los acoplados dado de baja
public DataTable Listar_disponibles()
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("Select a.dominio ,m.marca ,a.modelo ,a.año ,a.tara ,t.tipo ,a.alt_total ,a.nro_chasis ,a.ancho_interior ,a.ancho_exterior ,a.long_plataforma ,a.capacidad_carga ,a.cant_ejes ,a.estado ,a.observaciones ,a.fecha_alta ,a.fecha_baja ,id_acoplado From acoplado a join tipo_acoplado t on a.tipo=t.id join marca_acoplado m on a.marca=m.id where a.estado='DISPONIBLE'", usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
} //Funcion que lista todos los acoplados disponibles
public DataTable Listar_en_viaje()
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("Select a.dominio ,m.marca ,a.modelo ,a.año ,a.tara ,t.tipo ,a.alt_total ,a.nro_chasis ,a.ancho_interior ,a.ancho_exterior ,a.long_plataforma ,a.capacidad_carga ,a.cant_ejes ,a.estado ,a.observaciones ,a.fecha_alta ,a.fecha_baja ,id_acoplado From acoplado a join tipo_acoplado t on a.tipo=t.id join marca_acoplado m on a.marca=m.id where a.estado='EN VIAJE'", usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
} //Funcion que lista todos los acoplados que estan en viaje
public DataTable Listar_taller()
{
try
{
usuario.Modo(TipoConexion.Abrir);
da = new SqlDataAdapter("Select a.dominio ,m.marca ,a.modelo ,a.año ,a.tara ,t.tipo ,a.alt_total ,a.nro_chasis ,a.ancho_interior ,a.ancho_exterior ,a.long_plataforma ,a.capacidad_carga ,a.cant_ejes ,a.estado ,a.observaciones ,a.fecha_alta ,a.fecha_baja ,id_acoplado From acoplado a join tipo_acoplado t on a.tipo=t.id join marca_acoplado m on a.marca=m.id where a.estado='EN TALLER'", usuario.cnn);
dt = new DataTable();
da.Fill(dt);
usuario.Modo(TipoConexion.Cerrar);
return dt;
}
catch (Exception)
{
return null;
}
} //Funcion que lista todos los acoplados que estan en taller
}
}
<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;
namespace GestionTransporte.vistas
{
public partial class frmInputBox : Form
{
public frmInputBox(string mensaje)
{
InitializeComponent();
this.mensaje = mensaje;
}
string mensaje;
public string Retorno { get; set; }
private void tbPrincipal_TextChanged(object sender, EventArgs e)
{
Retorno = tbPrincipal.Text;
}
private void btnOk_Click(object sender, EventArgs e)
{
if (sender == btnOk)
{
DialogResult = DialogResult.OK;
this.Close();
}
if (sender == btnCancel)
{
Retorno =string.Empty;
DialogResult = DialogResult.Cancel;
this.Close();
}
}
private void frmMessage_Load(object sender, EventArgs e)
{
lblMensaje.Text = mensaje;
}
}
}
<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 GestionTransporte.clases;
namespace GestionTransporte
{
public partial class frmPedido : Form
{
public delegate void idPedido(String id);
public event idPedido pasaIdFormPrincipal;
clsLogin conexion;
clsPedido pedido;
DataTable dtPedido;
public frmPedido(clsLogin conexion)
{
InitializeComponent();
this.conexion = conexion;
pedido = new clsPedido(conexion);
}
private void frmPedido_Load(object sender, EventArgs e)
{
cbPedidoListar.SelectedIndex = 0;
cbPedidoBuscar.SelectedIndex = 0;
tbBuscarPedido.Visible = false;
dtpFechaDesde.Visible = false;
dtpFechaHasta.Visible = false;
dtPedido = pedido.listar_pedidos();
CargaPedidosTotal();
}
private void cbPedidoListar_SelectedIndexChanged(object sender, EventArgs e)
{
if (sender == cbPedidoListar)
{
switch (cbPedidoListar.SelectedIndex)
{
case 0:
dtPedido = pedido.listar_pedidos();
dgvPedidos.DataSource = dtPedido;
ColumnasInvisiblePedidos();
CargaDatosLabel();
break;
case 1:
dtPedido = pedido.lista_prioridad_alta();
dgvPedidos.DataSource = dtPedido;
ColumnasInvisiblePedidos();
CargaDatosLabel();
break;
case 2:
dtPedido = pedido.lista_prioridad_normal();
dgvPedidos.DataSource = dtPedido;
ColumnasInvisiblePedidos();
CargaDatosLabel();
break;
case 3:
dtPedido = pedido.listar_pendientes();
dgvPedidos.DataSource = dtPedido;
ColumnasInvisiblePedidos();
CargaDatosLabel();
break;
case 4:
dtPedido = pedido.lista_entregados();
dgvPedidos.DataSource = dtPedido;
ColumnasInvisiblePedidos();
CargaDatosLabel();
break;
case 5:
dtPedido = pedido.lista_en_transcurso();
dgvPedidos.DataSource = dtPedido;
ColumnasInvisiblePedidos();
CargaDatosLabel();
break;
case 6:
dtPedido = pedido.lista_cancelados();
dgvPedidos.DataSource = dtPedido;
ColumnasInvisiblePedidos();
CargaDatosLabel();
break;
}
VerificaGrillaVacia();
}
if (sender == cbPedidoBuscar)
{
tbBuscarPedido.Clear();
if (cbPedidoBuscar.SelectedIndex == 0)
{
tbBuscarPedido.Visible = false;
dtpFechaDesde.Visible = false;
dtpFechaHasta.Visible = false;
lbDesde.Visible = false;
lbHasta.Visible = false;
}
if (cbPedidoBuscar.SelectedIndex == 1 || cbPedidoBuscar.SelectedIndex == 2 || cbPedidoBuscar.SelectedIndex == 3)
{
tbBuscarPedido.Visible = true;
tbBuscarPedido.Location = new Point(248, 6);
dtpFechaDesde.Visible = false;
dtpFechaHasta.Visible = false;
lbDesde.Visible = false;
lbHasta.Visible = false;
}
if (cbPedidoBuscar.SelectedIndex == 4)
{
dtpFechaDesde.Visible = false;
tbBuscarPedido.Visible = false;
dtpFechaHasta.Visible = true;
lbDesde.Visible = false;
lbHasta.Visible = false;
}
if (cbPedidoBuscar.SelectedIndex == 5)
{
lbDesde.Visible = true;
lbHasta.Visible = true;
dtpFechaDesde.Visible = true;
dtpFechaHasta.Visible = true;
tbBuscarPedido.Visible = false;
}
VerificaGrillaVacia();
}
}
public void VerificaGrillaVacia()
{
if (dgvPedidos.Rows.Count < 1)
{
btnSelectPedido.Enabled = false;
dgvPedidos.BackgroundColor = Color.Red;
LimpiaTBBinding();
}
else
{
btnSelectPedido.Enabled = true;
dgvPedidos.BackgroundColor = Color.DarkGray;
}
}
private void LimpiaTBBinding()
{
lblPedidoNombreChofer.Text = string.Empty;
lblPedidoApellidoChofer.Text = string.Empty;
lbPedidoFechaSalida.Text = string.Empty;
lbPedidoFechaRegreso.Text = string.Empty;
lblPedidoPesoCarga.Text = string.Empty;
lbPedidoObservacion.Text = string.Empty;
}
private void tbBuscarPedido_TextChanged(object sender, EventArgs e)
{
switch (cbPedidoBuscar.SelectedIndex)
{
case 1:
if (tbBuscarPedido.Text != String.Empty)
{
dtPedido.Clear();
dtPedido = pedido.busqueda_numero_pedido(tbBuscarPedido.Text).ToTable();
dgvPedidos.DataSource = dtPedido;
ColumnasInvisiblePedidos();
CargaDatosLabel();
}
break;
case 2:
dtPedido.Clear();
dtPedido = pedido.busqueda_cliente(tbBuscarPedido.Text).ToTable();
dgvPedidos.DataSource = dtPedido;
ColumnasInvisiblePedidos();
CargaDatosLabel();
break;
case 3:
dtPedido.Clear();
dtPedido = pedido.busqueda_cuil(tbBuscarPedido.Text).ToTable();
dgvPedidos.DataSource = dtPedido;
ColumnasInvisiblePedidos();
CargaDatosLabel();
break;
}
}
private void dtpFechaDesde_ValueChanged(object sender, EventArgs e)
{
if (sender == dtpFechaDesde || sender == dtpFechaHasta)
{
if (cbPedidoBuscar.SelectedIndex == 4)
{
dgvPedidos.DataSource = pedido.busqueda_fechaIngreso(dtpFechaHasta.Value.ToString("yyyy-MM-dd"));
ColumnasInvisiblePedidos();
CargaDatosLabel();
}
if (cbPedidoBuscar.SelectedIndex == 5)
{
if (dtpFechaDesde.Value <= dtpFechaHasta.Value)
{
dtPedido = pedido.busqueda_rangoFecha(dtpFechaDesde.Value.ToString("yyyy-MM-dd"), dtpFechaHasta.Value.ToString("yyyy-MM-dd"));
dgvPedidos.DataSource = dtPedido;
ColumnasInvisiblePedidos();
CargaDatosLabel();
}
}
}
}
private void CargaPedidosTotal()
{
CargaDatosADgv();
ColumnasInvisiblePedidos();
CargaDatosLabel();
}
private void ColumnasInvisiblePedidos()
{
dgvPedidos.Columns[1].Visible=false;
dgvPedidos.Columns[2].Visible = false;
dgvPedidos.Columns[5].Visible=false;
dgvPedidos.Columns[6].Visible=false;
dgvPedidos.Columns[7].Visible=false;
dgvPedidos.Columns[9].Visible=false;
}
private void CargaDatosADgv()
{
dtPedido = pedido.listar_pedidos();
dgvPedidos.DataSource = dtPedido;
}
private void LimpiaBindingPedidos()
{
lblPedidoNombreChofer.DataBindings.Clear();
lblPedidoApellidoChofer.DataBindings.Clear();
lbPedidoFechaSalida.DataBindings.Clear();
lbPedidoFechaRegreso.DataBindings.Clear();
lblPedidoPesoCarga.DataBindings.Clear();
lbPedidoObservacion.DataBindings.Clear();
}
private void CargaDatosLabel()
{
LimpiaBindingPedidos();
lblPedidoNombreChofer.DataBindings.Add(new Binding("Text", dtPedido, "nombre"));
lblPedidoApellidoChofer.DataBindings.Add(new Binding("Text", dtPedido, "apellido"));
lbPedidoFechaSalida.DataBindings.Add(new Binding("Text", dtPedido, "fecha_sal_aprox"));
lbPedidoFechaRegreso.DataBindings.Add(new Binding("Text", dtPedido, "fecha_reg_aprox"));
lblPedidoPesoCarga.DataBindings.Add(new Binding("Text", dtPedido, "peso_carga_aprox")); ;
lbPedidoObservacion.DataBindings.Add(new Binding("Text", dtPedido, "observaciones"));
}
private void btnSelectPedido_Click(object sender, EventArgs e)
{
pasaIdFormPrincipal(dgvPedidos.CurrentRow.Cells[0].Value.ToString());
this.Hide();
}
}
}
<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 GestionTransporte.clases;
namespace GestionTransporte.vistas
{
public delegate void actualizaMarcaAcoplado();
public partial class frmGestorMarcaAcoplado : Form
{
clsMarca_acoplado marca;
actualizaMarcaAcoplado delegadoMarcaAcoplado;
public frmGestorMarcaAcoplado(clsLogin conexion, Delegate actualiza)
{
InitializeComponent();
this.marca = new clsMarca_acoplado(conexion);
delegadoMarcaAcoplado = (actualizaMarcaAcoplado)actualiza;
}
private void btnAgregar_Click(object sender, EventArgs e)
{
String resp;
if (sender == btnAgregar)
{
if (tbAgregar.Text.Trim() == string.Empty)
{
tbAgregar.BackColor = Color.OrangeRed;
MessageBox.Show("FALTA LLENAR CAMPOS MARCADOS CON COLOR ROJO", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
tbAgregar.BackColor = Color.White;
marca.Marca = tbAgregar.Text.ToUpper().Trim();
marca.Estado = "HABILITADO";
resp = marca.insertar();
delegadoMarcaAcoplado();
if (resp != String.Empty)
MessageBox.Show(resp);
dgvMarcas.DataSource = marca.ver_marcas();
if (dgvMarcas.Rows.Count < 1)
{
tbModificar.Enabled = false;
tbEliminar.Enabled = false;
}
tbAgregar.Clear();
}
}
if (sender == btnModificar)
{
if (tbModificar.Text.Trim() == string.Empty)
{
tbModificar.BackColor = Color.OrangeRed;
MessageBox.Show("FALTA LLENAR CAMPOS MARCADOS CON COLOR ROJO", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
tbModificar.BackColor = Color.White;
marca.Marca = tbModificar.Text.ToUpper().Trim();
resp = marca.modificar(dgvMarcas.SelectedCells[0].Value.ToString());
delegadoMarcaAcoplado();
if (resp != String.Empty)
MessageBox.Show(resp);
dgvMarcas.DataSource = marca.ver_marcas();
}
}
if (sender == btnEliminar)
{
tbAgregar.BackColor = Color.White;
tbModificar.BackColor = Color.White;
marca.Marca = tbEliminar.Text;
resp = marca.eliminar(dgvMarcas.SelectedCells[0].Value.ToString());
delegadoMarcaAcoplado();
if (resp != String.Empty)
MessageBox.Show(resp);
else
{
tbEliminar.Clear();
tbModificar.Clear();
}
dgvMarcas.DataSource = marca.ver_marcas();
if (dgvMarcas.Rows.Count < 1)
{
tbModificar.Enabled = false;
tbEliminar.Enabled = false;
}
}
}
private void dgvMarcas_CellClick(object sender, DataGridViewCellEventArgs e)
{
tbModificar.Text = dgvMarcas.SelectedCells[0].Value.ToString();
tbEliminar.Text = dgvMarcas.SelectedCells[0].Value.ToString();
}
private void dgvMarcas_DataSourceChanged(object sender, EventArgs e)
{
if (dgvMarcas.RowCount != 0)
{
tbModificar.Text = dgvMarcas.SelectedCells[0].Value.ToString();
tbEliminar.Text = dgvMarcas.SelectedCells[0].Value.ToString();
}
}
}
}
<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;
namespace GestionTransporte
{
public partial class frmMecanico : Form
{
clsLogin conexion;
public frmMecanico(clsLogin conexion)
{
InitializeComponent();
this.conexion = conexion;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GestionTransporte.clases
{
public class Mecanico
{
Login usuario;//el usuario trae consigo la coneccion a la bd
int num_legajo;
string nombre;
string apellido;
string domicilio;
string telefo1;
string telefo2;
string estado;
#region encapsulamiento de propiedades
public int Num_legajo
{
get { return num_legajo; }
set { num_legajo = value; }
}
public string Nombre
{
get { return nombre; }
set { nombre = value; }
}
public string Apellido
{
get { return apellido; }
set { apellido = value; }
}
public string Domicilio
{
get { return domicilio; }
set { domicilio = value; }
}
public string Telefo1
{
get { return telefo1; }
set { telefo1 = value; }
}
public string Telefo2
{
get { return telefo2; }
set { telefo2 = value; }
}
public string Estado
{
get { return estado; }
set { estado = value; }
}
#endregion
}
}
<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 GestionTransporte.clases;
namespace GestionTransporte.vistas
{
public delegate void actualizaModeloCamion();
public partial class frmGestorModeloCamion : Form
{
clsModelo_camion modelo;
actualizaModeloCamion delegadoModeloCamion;
public frmGestorModeloCamion(clsLogin conexion, Delegate actualiza)
{
InitializeComponent();
this.modelo = new clsModelo_camion(conexion);
delegadoModeloCamion = (actualizaModeloCamion)actualiza;
}
private void frmGestorModeloCamion_Load(object sender, EventArgs e)
{
dgvModelo.DataSource = modelo.ver_modelos();
if (dgvModelo.Rows.Count < 1)
{
btnModificar.Enabled = false;
btnEliminar.Enabled = false;
}
}
private void btnAgregar_Click(object sender, EventArgs e)
{
String resp;
if (sender == btnAgregar)
{
if (tbAgregar.Text.Trim() == string.Empty)
{
tbAgregar.BackColor = Color.OrangeRed;
MessageBox.Show("FALTA LLENAR CAMPOS MARCADOS CON COLOR ROJO", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
tbAgregar.BackColor = Color.White;
modelo.Modelo = tbAgregar.Text.ToUpper().Trim();
modelo.Estado = "HABILITADO";
resp = modelo.insertar();
delegadoModeloCamion();
if (resp != String.Empty)
MessageBox.Show(resp);
dgvModelo.DataSource = modelo.ver_modelos();
if (dgvModelo.Rows.Count < 1)
{
tbModificar.Enabled = false;
tbEliminar.Enabled = false;
}
tbAgregar.Clear();
}
}
if (sender == btnModificar)
{
if (tbModificar.Text.Trim() == string.Empty)
{
tbModificar.BackColor = Color.OrangeRed;
MessageBox.Show("FALTA LLENAR CAMPOS MARCADOS CON COLOR ROJO", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
tbModificar.BackColor = Color.White;
modelo.Modelo = tbModificar.Text.ToUpper().Trim();
resp = modelo.modificar(dgvModelo.SelectedCells[0].Value.ToString());
delegadoModeloCamion();
if (resp != String.Empty)
MessageBox.Show(resp);
dgvModelo.DataSource = modelo.ver_modelos();
}
}
if (sender == btnEliminar)
{
tbAgregar.BackColor = Color.White;
tbModificar.BackColor = Color.White;
modelo.Modelo = tbEliminar.Text;
resp = modelo.eliminar(dgvModelo.SelectedCells[0].Value.ToString());
delegadoModeloCamion();
if (resp != String.Empty)
MessageBox.Show(resp);
else
{
tbEliminar.Clear();
tbModificar.Clear();
}
dgvModelo.DataSource = modelo.ver_modelos();
if (dgvModelo.Rows.Count < 1)
{
tbModificar.Enabled = false;
tbEliminar.Enabled = false;
}
}
}
private void dgvModelo_CellClick(object sender, DataGridViewCellEventArgs e)
{
tbModificar.Text = dgvModelo.SelectedCells[0].Value.ToString();
tbEliminar.Text = dgvModelo.SelectedCells[0].Value.ToString();
}
private void dgvModelo_DataSourceChanged(object sender, EventArgs e)
{
if (dgvModelo.RowCount != 0)
{
tbModificar.Text = dgvModelo.SelectedCells[0].Value.ToString();
tbEliminar.Text = dgvModelo.SelectedCells[0].Value.ToString();
}
}
}
}
<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;
using System.Data.SqlClient;//necesario para poder acceder a SQL
namespace GestionTransporte
{
public partial class Form1 : Form
{
clsConexion Conexion;
public Form1()
{
InitializeComponent();
Conexion = new clsConexion();
}
private void btnLogear_Click(object sender, EventArgs e)
{
Conexion.Servidor = "DESKTOP-72D97C1";
Conexion.BaseDatos = "gestiontransporte";
Conexion.Usuario = tbUsuario.Text;
Conexion.Clave = tbPassword.Text;
string res = Conexion.Validar();
if (res == string.Empty)
{
tbPassword.Clear();
tbUsuario.Clear();
this.Hide();
frmPrincipal ofrmMain = new frmPrincipal();
ofrmMain.ShowDialog();
this.ShowDialog();
}
else
MessageBox.Show(res, "E R R O R",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace GestionTransporte
{
public enum TipoConexion
{
Abrir,Cerrar
}
public class clsLogin
{
#region Atributos y Propiedades
public string Servidor;
public string Usuario;
public string Clave;
public string BaseDatos;
public SqlConnection cnn = new SqlConnection();
#endregion
public string Modo(TipoConexion Tipo)
{
string res = string.Empty;
string StrCnn = @"Data Source =" + Servidor + ";Initial Catalog=" + BaseDatos + "; User ID = " + Usuario + "; Password= " + <PASSWORD>;
try
{
if ((cnn.State == System.Data.ConnectionState.Closed) && (Tipo ==
TipoConexion.Abrir))
{
cnn.ConnectionString = StrCnn;
cnn.Open();
}
else
cnn.Close();
}
catch (SqlException ex)
{
res = ex.Message;
}
return res;
} //Funcion que genera una nueva conexion
public string Validar()
{
string res = string.Empty;
string StrCnn = @"Data Source=" + Servidor + ";Initial Catalog=" + BaseDatos + "; User ID = " + Usuario + "; Password= " +
Clave;
try
{
cnn.ConnectionString = StrCnn;
cnn.Open();
cnn.Close();
}
catch (SqlException ex)
{
res = ex.Message;
}
return res;
} //Funcion que valida cadena de conexion
}
}
| e82aa86b883124ec617c8caa96e188f0a84776d3 | [
"C#"
] | 30 | C# | pabloisaac/proyectolabo3 | 805cbcf570d5083d681dca464c6cc64990b200d1 | 47f3fa831fc58cf54eb94ecee21f7fb0d035fcae |
refs/heads/master | <repo_name>ericknajjar/ClickHeroeSaga<file_sep>/Assets/FacebookLoginControler.cs
using Facebook.Unity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class FacebookLoginControler : MonoBehaviour
{
bool _facebookInited = false;
private void Start()
{
FB.Init(() => {
if(FB.IsInitialized)
{
FB.ActivateApp();
_facebookInited = true;
}
});
}
public void OnLogin()
{
FB.LogInWithPublishPermissions(null,(result) =>
{
if (FB.IsLoggedIn)
{
var aToken = AccessToken.CurrentAccessToken;
Debug.Log(aToken.UserId);
StartCoroutine(LoginCorrotine(aToken.UserId, aToken.TokenString));
}
else
{
Debug.Log("User cancelled login");
}
});
}
IEnumerator LoginCorrotine(string facebookUser, string facebookAcessToken)
{
var data = new Dictionary<string, string>
{
{ "facebook_user_id",facebookUser },
{ "facebook_token", facebookAcessToken },
};
string toSend = JsonConvert.SerializeObject(data);
byte[] bytesToSend = Encoding.UTF8.GetBytes(toSend);
Debug.Log($"Sending... {toSend}");
using (UnityWebRequest www = new UnityWebRequest("http://localhost:5000/facebook_login", UnityWebRequest.kHttpVerbPOST))
{
www.SetRequestHeader("Content-Type", "application/json");
www.uploadHandler = new UploadHandlerRaw(bytesToSend);
www.downloadHandler = new DownloadHandlerBuffer();
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
var text = www.downloadHandler.text;
if (www.responseCode == 200)
{
var result = JObject.Parse(text);
ClicksController._userId = result["user_id"].Value<string>();
ClicksController._accessToken = result["token"].Value<string>();
ClicksController._totalClicks = result["clicks"].Value<uint>();
Debug.Log(result);
SceneManager.LoadScene(1);
}
else
{
Debug.LogError($"{www.responseCode}: {text}");
}
}
}
}
}
<file_sep>/Assets/ClicksController.cs
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class ClicksController : MonoBehaviour
{
[SerializeField] Text _display;
public static uint _totalClicks;
public static string _userId;
public static string _accessToken;
void Start()
{
_display.text = _totalClicks.ToString();
}
public void Click()
{
++_totalClicks;
string toShow = _totalClicks.ToString();
_display.text = toShow;
StartCoroutine(SendUpdatedClicks());
}
IEnumerator SendUpdatedClicks()
{
var data = new Dictionary<string, object>
{
{ "user_id", _userId },
{ "token",_accessToken},
{ "clicks",_totalClicks},
};
string toSend = JsonConvert.SerializeObject(data);
byte[] bytesToSend = Encoding.UTF8.GetBytes(toSend);
using (UnityWebRequest www = new UnityWebRequest("http://localhost:5000/set_clicks", UnityWebRequest.kHttpVerbPOST))
{
www.SetRequestHeader("Content-Type", "application/json");
www.uploadHandler = new UploadHandlerRaw(bytesToSend);
www.downloadHandler = new DownloadHandlerBuffer();
yield return www.SendWebRequest();
var text = www.downloadHandler.text;
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else if (www.responseCode != 200)
{
Debug.LogError($"{www.responseCode}: {text}");
}
}
}
}
<file_sep>/Assets/LoginControler.cs
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class LoginControler : MonoBehaviour
{
[SerializeField] InputField _email;
[SerializeField] InputField _password;
public void OnLogin()
{
// Debug.Log($"{_email.text} {_password.text}");
StartCoroutine(LoginCorrotine());
}
IEnumerator LoginCorrotine()
{
var data = new Dictionary<string, string>
{
{ "email", _email.text },
{ "password",_password.text},
};
string toSend = JsonConvert.SerializeObject(data);
byte[] bytesToSend = Encoding.UTF8.GetBytes(toSend);
Debug.Log($"Sending... {toSend}");
using (UnityWebRequest www = new UnityWebRequest("http://localhost:5000/pior_login_do_mundo", UnityWebRequest.kHttpVerbPOST))
{
www.SetRequestHeader("Content-Type", "application/json");
www.uploadHandler = new UploadHandlerRaw(bytesToSend);
www.downloadHandler = new DownloadHandlerBuffer();
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
var text = www.downloadHandler.text;
if (www.responseCode == 200)
{
var result = JObject.Parse(text);
ClicksController._userId = result["user_id"].Value<string>();
ClicksController._accessToken = result["token"].Value<string>();
ClicksController._totalClicks = result["clicks"].Value<uint>();
Debug.Log(result);
SceneManager.LoadScene(1);
}
else
{
Debug.LogError($"{www.responseCode}: {text}");
}
}
}
}
}
<file_sep>/Server/server.py
from flask import Flask
from flask import request, jsonify
from hashlib import sha256
import os
import uuid
import json
import facebook
app = Flask(__name__)
@app.route('/facebook_login', methods=['POST'])
def facebook_login():
data = request.get_json()
facebook_token = data["facebook_token"]
facebook_user_id = data["facebook_user_id"]
graph = facebook.GraphAPI(access_token=facebook_token)
me = graph.get_object(id='me')
if me['id']!=facebook_user_id:
raise Exception()
user_info = login_user(facebook_user_id)
return jsonify(user_info)
@app.route('/set_clicks', methods=['POST'])
def set_clicks():
data = request.get_json()
user_id = data['user_id']
token = data['token']
clicks = data['clicks']
saved_infos = validate_user(user_id,token)
saved_infos['clicks'] = clicks
filename = user_id+'.txt'
f = open(filename, "w")
f.write(json.dumps(saved_infos))
f.close()
return jsonify({})
def validate_user(user_id,token):
filename = user_id+'.txt'
if not os.path.isfile(filename):
raise Exception()
f = open(filename, "r")
file_content = f.read()
f.close()
saved_infos = json.loads(file_content)
if saved_infos['token'] != token:
raise Exception()
return saved_infos
def login_user(facebook_id):
token = str(<KEY>())
user_id = sha256(facebook_id.encode('utf-8')).hexdigest()
filename = "./"+user_id+".txt"
saved_infos = {
"facebook_id" : facebook_id,
"token" : token,
"clicks" : 0
}
if not os.path.isfile(filename):
f = open(filename, "w")
f.write(json.dumps(saved_infos))
f.close()
else:
saved_infos = update_token(filename,token)
return {"token": token,"user_id":user_id, "clicks": saved_infos["clicks"]}
def update_token(filename,new_token):
f = open(filename, "r+")
file_content = f.read()
saved_infos = json.loads(file_content)
saved_infos["token"] = new_token
f.seek(0)
f.write(json.dumps(saved_infos))
f.truncate()
f.close()
return saved_infos
| f8db485f4fd874193148843ae71911711635fc35 | [
"C#",
"Python"
] | 4 | C# | ericknajjar/ClickHeroeSaga | 84634289f3f6315cded8752a4e1267b1b356afc1 | b9e5cc8af93db5694bfd1c77246d43fafc9d3367 |
refs/heads/master | <repo_name>KalluruNarasimha/Narasimha<file_sep>/App/src/com/app/dao/impl/LocationDaoImpl.java
package com.app.dao.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import com.app.dao.ILocationDao;
import com.app.model.Location;
@Repository
public class LocationDaoImpl implements ILocationDao {
@Autowired
private HibernateTemplate ht;
public int SaveLocation(Location loc) {
int locId=(Integer)ht.save(loc);
return locId;
}
public void UpdateLocation(Location loc) {
ht.update(loc);
}
public void DeleteLocation(int locId) {
ht.delete(new Location(locId));
}
public Location getLocationById(int locId) {
Location loc=ht.get(Location.class, locId);
return loc;
}
public List<Location> getAllLocations() {
List<Location> locList=ht.loadAll(Location.class);
return locList;
}
public List<Object[]> getLocTypeAndCount() {
String hql="select locType,Count(locType) from com.app.model.Location group by locType";
@SuppressWarnings("unchecked")
List<Object[]> data=ht.find(hql);
return data;
}
}
<file_sep>/App/src/com/app/Controller/LocationController.java
package com.app.Controller;
import java.util.List;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.app.Util.LocationUtil;
import com.app.model.Location;
import com.app.service.ILocationService;
@Controller
public class LocationController {
@Autowired
private ILocationService service;
@Autowired
private ServletContext sc;
@Autowired
private LocationUtil locutil;
@RequestMapping("regloc")
public String showReg(){
return "LocationRegister";
}
@RequestMapping(value="/saveLoc",method=RequestMethod.POST)
public String insertLoc(@ModelAttribute("location")Location loc,ModelMap map){
int locId=service.SaveLocation(loc);
String info="Save with:"+locId;
map.addAttribute("Msg",info);
return "LocationRegister";
}
@RequestMapping("/getAlllocs")
public String getData(ModelMap map){
List<Location> locs=service.getAllLocations();
map.addAttribute("locs",locs);
return "LocationData";
}
@RequestMapping("deleteLoc")
public String delLoc(@RequestParam("locId")int loc){
service.DeleteLocation(loc);
return "redirect:getAlllocs";
}
@RequestMapping("editLoc")
public String showEdit(@RequestParam("locId")int locId,ModelMap map){
Location loc=service.getLocationById(locId);
map.addAttribute("loc", loc);
return "LocationDataEdit";
}
@RequestMapping(value="updateLoc",method=RequestMethod.POST)
public String updateLoc(@ModelAttribute("location")Location loc){
service.UpdateLocation(loc);
return "redirect:getAlllocs";
}
@RequestMapping("locExcel")
public String doExcelExport(ModelMap map){
List<Location> locList=service.getAllLocations();
map.addAttribute("locList", locList);
return "LocExcelView";
}
@RequestMapping("locPdf")
public String doPdfExport(ModelMap map){
List<Location> locList=service.getAllLocations();
map.addAttribute("locList", locList);
return "LocPdfView";
}
@RequestMapping("/locReport")
public String generateCharts(){
String path=sc.getRealPath("/");
List<Object[]> data=service.getLocTypeAndCount();
locutil.generatePieChart(path,data);
locutil.generateBarChart(path,data);
return"LocationReport";
}
}
<file_sep>/App/src/com/app/filter/LoginCheckFilter.java
package com.app.filter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginCheckFilter implements Filter{
private List<String> uriList=null;
public void init(FilterConfig fc) throws ServletException {
String uristr=fc.getInitParameter("noCheckuri");
StringTokenizer st=new StringTokenizer(uristr,",");
uriList=new ArrayList<String>();
while(st.hasMoreTokens()){
String uri=st.nextToken();
uriList.add(uri);
}
}
public void doFilter(ServletRequest request, ServletResponse responce,
FilterChain fc) throws IOException, ServletException {
try{
HttpServletRequest req=(HttpServletRequest) request;
HttpServletResponse res=(HttpServletResponse) responce;
// cleare check-on logout
res.setHeader("Check-Control","no-cache,no-store,must-revalidate");
res.setHeader("Pragma","no-cache");
res.setDateHeader("Expires",0);
String requri=req.getRequestURI();
boolean flag=uriList.contains(requri);
if(!flag){
// if not in link-do session cheking
// read current session
HttpSession hs=req.getSession(false);
if(hs==null||hs.getAttribute("userName")==null){
((HttpServletResponse) hs).sendRedirect(req.getContextPath()+"/mvc/login");
}
}
}catch(Exception e){
}
// continue same if url exist in link
fc.doFilter(request,responce);
}
public void destroy() {
}
}
<file_sep>/App/src/com/app/Sample.java
package com.app;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class Sample implements Filter{
public void init(FilterConfig fc) throws ServletException {
System.out.println("one time code: create object");
}
public void doFilter(ServletRequest request, ServletResponse responce,
FilterChain fc) throws IOException, ServletException {
System.out.println("Every req....?");
HttpServletRequest req=(HttpServletRequest) request;
System.out.println(req.getRequestURL());
System.out.println(req.getRequestURI());
fc.doFilter(request,responce);
}
public void destroy() {
}
}
| 4bc46b075c4f4dea0b2bbb38bf0659b91a994e7d | [
"Java"
] | 4 | Java | KalluruNarasimha/Narasimha | 806455fa6c76b8784383bb8c986bfc6faed410f2 | 58ca6dee85aa988bca8b6a2e55ed0ec19771e1be |
refs/heads/master | <repo_name>fahreddinsvndr/Movie<file_sep>/app/src/test/java/com/fahreddinsevindir/movie/network/MovieServiceTest.kt
package com.fahreddinsevindir.movie.network
import com.fahreddinsevindir.movie.ZoneDateTimeProvider
import com.fahreddinsevindir.movie.ZoneDateTimeProvider.loadTimeZone
import com.fahreddinsevindir.movie.model.Movie
import com.fahreddinsevindir.movie.model.Movies
import com.fahreddinsevindir.movie.model.adapter.ZonedDateTimeAdapter
import com.squareup.moshi.Moshi
import io.reactivex.rxjava3.observers.TestObserver
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import okio.buffer
import okio.source
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.MatcherAssert.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import retrofit2.Retrofit
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory
import retrofit2.converter.moshi.MoshiConverterFactory
@RunWith(JUnit4::class)
class MovieServiceTest {
private lateinit var service: MovieService
private lateinit var mockWebServer: MockWebServer
@Before
fun init() {
ZoneDateTimeProvider.loadTimeZone()
mockWebServer = MockWebServer()
val moshi = Moshi.Builder()
.add(ZonedDateTimeAdapter())
.build()
service = Retrofit.Builder()
.baseUrl(mockWebServer.url("/"))
.addConverterFactory(MoshiConverterFactory.create(moshi))
.addCallAdapterFactory(RxJava3CallAdapterFactory.create())
.build()
.create(MovieService::class.java)
}
@After
fun cleanup() {
mockWebServer.shutdown()
}
@Test
fun getTrendingMovie() {
enqueueResponse("trending-movies.json")
val testObserver = TestObserver<Movies>()
service.getTrendingMovie(1).subscribe(testObserver)
// random test the values
testObserver.await()
.assertValue {
return@assertValue it.page == 1L
}
.assertValue {
return@assertValue it.totalPages == 1000L
}
.assertComplete()
.assertNoErrors()
// test the request path
val takeRequest = mockWebServer.takeRequest()
assertThat(takeRequest.path, `is`("/trending/all/day?page=1"))
}
private fun enqueueResponse(fileName: String, headers: Map<String, String> = emptyMap()) {
val inputStream = javaClass.classLoader!!.getResourceAsStream("api-response/$fileName")
val source = inputStream.source().buffer()
val mockResponse = MockResponse()
for ((key, value) in headers) {
mockResponse.addHeader(key, value)
}
mockWebServer.enqueue(mockResponse.setBody(source.readString(Charsets.UTF_8)))
}
}<file_sep>/app/src/main/java/com/fahreddinsevindir/movie/ui/cast/PhotoAdapter.kt
package com.fahreddinsevindir.movie.ui.cast
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.fahreddinsevindir.movie.R
import com.fahreddinsevindir.movie.glide.GlideApp
import com.fahreddinsevindir.movie.model.ProfileImage
import kotlinx.android.synthetic.main.item_movie.view.*
class PhotoAdapter : ListAdapter<ProfileImage, PhotoAdapter.PhotoViewHolder>(COMPARATOR) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PhotoViewHolder {
return PhotoViewHolder.from(parent)
}
override fun onBindViewHolder(holder: PhotoViewHolder, position: Int) {
val item = getItem(position)
holder.bind(item)
}
class PhotoViewHolder private constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(item: ProfileImage) {
itemView.let {
GlideApp.with(itemView)
.load("https://image.tmdb.org/t/p/original${item.path}")
.placeholder(R.drawable.ic_image_placeholder)
.error(R.drawable.ic_image_error)
.thumbnail(0.5f)
.into(itemView as ImageView)
}
}
companion object {
fun from(parent: ViewGroup): PhotoViewHolder {
val viewHolder =
LayoutInflater.from(parent.context).inflate(R.layout.item_photo, parent, false)
return PhotoViewHolder(viewHolder)
}
}
}
companion object {
private val COMPARATOR = object : DiffUtil.ItemCallback<ProfileImage>() {
override fun areItemsTheSame(oldItem: ProfileImage, newItem: ProfileImage): Boolean {
return oldItem.path == newItem.path
}
override fun areContentsTheSame(oldItem: ProfileImage, newItem: ProfileImage): Boolean {
return oldItem == newItem
}
}
}
}<file_sep>/app/src/main/java/com/fahreddinsevindir/movie/ui/landing/LandingFragment.kt
package com.fahreddinsevindir.movie.ui.landing
import android.os.Bundle
import android.view.View
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.paging.LoadState
import androidx.recyclerview.widget.LinearLayoutManager
import com.fahreddinsevindir.movie.R
import com.fahreddinsevindir.movie.model.Status
import com.google.android.material.snackbar.Snackbar
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.android.synthetic.main.fragment_landing.*
import kotlinx.android.synthetic.main.layout_error.*
import kotlinx.android.synthetic.main.layout_loading.*
import timber.log.Timber
@AndroidEntryPoint
class LandingFragment : Fragment(R.layout.fragment_landing) {
private lateinit var movieAdapter: MovieAdapter
private val landingViewModel by viewModels<LandingViewModel>()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
movieAdapter = MovieAdapter()
rvMovie.layoutManager = LinearLayoutManager(requireContext())
rvMovie.adapter = movieAdapter.withLoadStateFooter(
MovieFooterStateAdapter {
movieAdapter.retry()
}
)
movieAdapter.addLoadStateListener { loadState ->
srl.isRefreshing = loadState.refresh is LoadState.Loading
llErrorContainer.isVisible = loadState.source.refresh is LoadState.Error
rvMovie.isVisible = !llErrorContainer.isVisible
if (loadState.source.refresh is LoadState.Error){
btnRetry.setOnClickListener {
movieAdapter.retry()
}
llErrorContainer.isVisible = loadState.source.refresh is LoadState.Error
val errorMessage = (loadState.source.refresh as LoadState.Error).error.message
tvErrorMessage.text = errorMessage
}
srl.setOnRefreshListener {
landingViewModel.onRefresh()
}
}
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
landingViewModel.trendingMovies.observe(viewLifecycleOwner, Observer {
movieAdapter.submitData(lifecycle, it)
})
}
} | 9e9734dc7bb77176460f416491a3caf788172ab8 | [
"Kotlin"
] | 3 | Kotlin | fahreddinsvndr/Movie | 44b87237d782648f8e921963873de78f9dc6c392 | 94d2f80d3f0bb3d89d029c7d00ee94fa207fb267 |
refs/heads/master | <file_sep>package resturant.view;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import resturant.model.entity.Address;
import resturant.model.entity.Customer;
import repository.MenuType;
import resturant.sevice.CustomerService;
import resturant.sevice.MenuService;
import resturant.sevice.ResturantServise;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Component
public class CustomerView {
private Scanner scanner = new Scanner(System.in);
private Customer customer = new Customer();
private CustomerService customerService ;
private MenuService menuService ;
private ResturantServise restaurantService ;
@Autowired
public CustomerView(CustomerService customerService,MenuService menuService,ResturantServise resturantServise){
this.customerService=customerService;
this.menuService=menuService;
this.restaurantService=resturantServise;
}
public String getCustomerMobileFromUser() {
System.out.println("Enter Mobile Number: ");
while (!scanner.hasNextLong()) {
System.out.printf("Your input was \"%s\"." +
"\nPlease enter a number:%n", scanner.next());
}
String num = scanner.next();
System.out.println(num);
return num;
}
public String getCustomerFamilyFromUser() {
System.out.println("Enter Your Family: ");
while (true) {
String family = scanner.nextLine();
if (family != null && family.length() > 1) {
return family;
} else if (family == null) {
System.out.println("Invalid input!Try again!");
}
}
}
public int getCodeAreaFromUser() {
System.out.println("Enter Code Area: ");
while (!scanner.hasNextInt()) {
System.out.printf("Your input was \"%s\"." +
"\nPlease enter a number:%n", scanner.next());
}
int num = scanner.nextInt();
System.out.println(num);
return num;
}
public long getPostalCodeFromUser() {
System.out.println("Enter Postal Code: ");
while (!scanner.hasNextLong()) {
System.out.printf("Your input was \"%s\"." +
"\nPlease enter a number:%n", scanner.next());
}
long num = scanner.nextLong();
System.out.println(num);
return num;
}
public String getAddressLocationFromUser() {
System.out.println("Enter Address Location: ");
while (true) {
String addressLocation = scanner.nextLine();
if (addressLocation != null && addressLocation.length() > 1) {
return addressLocation;
} else if (addressLocation == null) {
System.out.println("Invalid input!Try again!");
}
}
}
// public void addCustomerAddress(Customer customer) {
// customer.getAddress().setCodeArea(getCodeAreaFromUser());
// customer.getAddress().setPostalCode(getPostalCodeFromUser());
// customer.getAddress().getCustomerAddress();
// }
/*public Customer setNewCustomer() {
this.customer.setCustomerMobileNumber(getCustomerMobileFromUser());
this.customer.setCustomerFamily(getCustomerFamilyFromUser());
addCustomerAddress(this.customer);
return this.customer;
}*/
public boolean addNewCustomerToRepository(Customer customer) {
if (customerService.addNewCustomer(customer)) {
return true;
}
return false;
}
public void showCustomerMainOptions() {
System.out.println("-------------------Customer Menu");
System.out.println("Select Options:");
System.out.println("1-Show All Restaurant\n" +
"2-Show All Restaurant in your Area\n" +
"3-Show Restaurant With Limited Food Type" +
"4-Back To Main Menu");
}
public int getSelectedOptionFromCustomer(int firsNumber, int lastNumber) {
int selectedOptions = 0;
do {
System.out.println("Enter Your Selected Number: ");
while (!scanner.hasNextInt()) {
System.out.printf("Your input was \"%s\"." +
"\nPlease enter a number between 1 and 4 :%n", scanner.next());
}
selectedOptions = scanner.nextInt();
} while (selectedOptions < firsNumber || selectedOptions > lastNumber);
return selectedOptions;
}
public void BackToMainMenu() {
}
public void showSelectedRestaurantMenu() {
System.out.println("Options:");
System.out.println("1-Select Restaurant\n" +
"2-Back To Customer Menu");
System.out.println("Select 1 or 2 :");
}
public String getRestaurantNameFromCustomer() {
String restaurantName = null;
boolean checkRestaurantName = false;
do {
System.out.println("Enter Your Selected Restaurant Name: ");
restaurantName = scanner.next();
checkRestaurantName = restaurantService.restaurantIsExist(restaurantName);
} while (!checkRestaurantName);
return restaurantName;
}
public void customerPanel() {
this.customer.setPhonenumber(getCustomerMobileFromUser());
Address address=new Address();
this.customer.setAddress(address);
this.customer.getAddress().setCodeArea(getCodeAreaFromUser());
showCustomerMainOptions();
int firstNumber = 1;
int lastNumber = 4;
int selectedOption = getSelectedOptionFromCustomer(firstNumber, lastNumber);
switch (selectedOption) {
case 1:
System.out.println("-------------------Show All Restaurants");
restaurantService.showAllRestaurants();
//Build a method
showSelectedRestaurantMenu();
firstNumber = 1;
lastNumber = 2;
int selectedOptionForRestaurant = getSelectedOptionFromCustomer(firstNumber, lastNumber);
switch (selectedOptionForRestaurant) {
case 1:
String selectedRestaurantName = getRestaurantNameFromCustomer();
//TODO
break;
case 2:
//TODO
}
break;
case 2:
System.out.println("-------------------Show Restaurants By CodeArea");
restaurantService.showRestaurantByCodeArea(this.customer.getAddress().getCodeArea());
//Build a Method
break;
case 3:
System.out.println("-------------------Show Restaurants By MenuType");
List<String> menuType = Stream.of(MenuType.values())
.map(Enum::name)
.collect(Collectors.toList());
System.out.println("Valid Menu Type:");
for (int i = 0; i < menuType.size(); i++) {
System.out.println((i + 1) + "-" + menuType.get(i));
}
boolean checkSelectedMenuType = false;
String selectedMenuType = null;
do {
System.out.println("Select MenuType:");
selectedMenuType = scanner.next();
checkSelectedMenuType = menuService.containsMenuType(selectedMenuType);
} while (!checkSelectedMenuType);
restaurantService.showRestaurantByMenuType(selectedMenuType);
////Build a Method
break;
case 4:
//TODO
}
}
}
<file_sep>package resturant.sevice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import resturant.repository.doa.FoodDoa;
import resturant.model.entity.Food;
import java.util.List;
@Component
public class FoodService {
private FoodDoa foodDoa;
@Autowired
public FoodService(FoodDoa foodDoa) {
this.foodDoa = foodDoa;
}
public boolean addNewFood(Food food) {
if (food != null && food.getName() != null && food.getPrice() > 0) {
foodDoa.create(food);
return true;
}
return false;
}
public Food findFoodByName(String foodName) {
if (foodName != null && foodName != "" && foodName != " ") {
return foodDoa.findByName(foodName);
}
return null;
}
public List<Food> findFoodsListByPrice(long foodPrice) {
if (foodPrice > 0) {
return foodDoa.findByPrice(foodPrice);
}
return null;
}
}
<file_sep>package resturant.model.entity;
import javax.persistence.*;
@Entity
public class Food {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String type;
private double price;
@ManyToOne(cascade = CascadeType.ALL)
private Menu menu;
public Food(Menu menu) {
this.menu = menu;
}
public Food(String name, String type, double price) {
this.name = name;
this.type = type;
this.price = price;
}
public Food(String name, String type, double price, Menu menu) {
this.name = name;
this.type = type;
this.price = price;
this.menu = menu;
}
@Override
public String toString() {
return "Food{" +
"id=" + id +
", name='" + name + '\'' +
", type='" + type + '\'' +
", price=" + price +
", menu=" + menu +
'}';
}
public Food (){}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
<file_sep>package resturant.model.dto;
public class ResturantReportDto {
private String resturantName;
private double totalamount;
private String foodName;
public String getFoodName() {
return foodName;
}
public void setFoodName(String foodName) {
this.foodName = foodName;
}
public double getTotalamount() {
return totalamount;
}
public void setTotalamount(double totalamount) {
this.totalamount = totalamount;
}
public String getResturantName() {
return resturantName;
}
public void setResturantName(String resturantName) {
this.resturantName = resturantName;
}
@Override
public String toString() {
return "ResturantReportDto{" +
"resturantName='" + resturantName + '\'' +
", amount=" + totalamount +
", foodName='" + foodName + '\'' +
'}';
}
}
<file_sep>package resturant.sevice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import resturant.repository.doa.CustomerDoa;
import resturant.model.entity.Customer;
@Component
public class CustomerService {
private CustomerDoa customerDoa;
public CustomerService(){}
@Autowired
public CustomerService(CustomerDoa customerDoa) {
this.customerDoa = customerDoa;
}
public boolean searchCustomers(String phonenumber) {
if(phonenumber!=null && phonenumber.length()>10) return customerDoa.customerExisteance(phonenumber);
return false;
}
public boolean addNewCustomer(Customer customer) {
if (customer != null && customer.getName() != null &&
customer.getPhonenumber() !=null &&
customer.getAddress().getCodeArea() > 0 &&
customer.getAddress().getPostalCode() > 0 &&
customer.getAddress().getCustomerAddress() != null) {
if (!customerIsExist(customer.getPhonenumber())) {
customerDoa.create(customer);
return true;
}
}
return false;
}
public boolean customerIsExist(String mobileNumber) {
return customerDoa.customerExisteance(mobileNumber);
}
}
<file_sep>package resturant.repository.doa;
import org.springframework.stereotype.Component;
import resturant.model.entity.Menu;
import org.hibernate.Session;
import org.hibernate.query.Query;
import repository.MenuType;
import java.util.List;
@Component
public class MenuDao extends GenericDaoImpl<Menu, Integer>{
Session session = DatabaseConnection.getSessionFactory().openSession();
public List<Menu> findManuByType(String menuType) {
session.beginTransaction();
String queryString = "from Menu where menuType=:mType";
Query query = session.createQuery(queryString);
query.setParameter("mType", MenuType.valueOf(menuType));
List<Menu> menus = query.list();
session.getTransaction().commit();
session.close();
return menus;
}
public Menu findByName(String menuName) {
session.beginTransaction();
String queryString = "from Menu where menuName=:mName";
Query query = session.createQuery(queryString);
query.setParameter("mName", menuName);
List<Menu> menus = query.list();
Menu menu=menus.get(0);
session.getTransaction().commit();
session.close();
return menu;
}
}
<file_sep>package resturant.model.entity;
import javax.persistence.*;
@Embeddable
public class Address {
private int codeArea;
private long postalCode;
private String customerAddress;
public Address() {
}
public Address(int codeArea, long postalCode, String customerAddress) {
this.codeArea = codeArea;
this.postalCode = postalCode;
this.customerAddress = customerAddress;
}
public int getCodeArea() {
return codeArea;
}
public void setCodeArea(int codeArea) {
this.codeArea = codeArea;
}
public long getPostalCode() {
return postalCode;
}
public void setPostalCode(long postalCode) {
this.postalCode = postalCode;
}
public String getCustomerAddress() {
return customerAddress;
}
public void setCustomerAddress(String customerAddress) {
this.customerAddress = customerAddress;
}
@Override
public String toString() {
return "Address{" +
"codeArea=" + codeArea +
", postalCode=" + postalCode +
", customerAddress='" + customerAddress + '\'' +
'}';
}
}
<file_sep>package repository;
public enum MenuType {
lunch,dinner,breakfast;
}
| 55894973b2ea73a70be215f160b7a57ad1d0a5da | [
"Java"
] | 8 | Java | fshirafkan/resturantSpringcore | 727eff6127cd1c011717a76bafe7e6984def00f9 | a2f5c0f21005f15193a2e886a8946649218e390b |
refs/heads/main | <file_sep>x=9
y=0
try:
print("error class open")
print(x/y)
t=int(input("enter number"))
print(t)
# print(me)
except ZeroDivisionError as e:
print(" cant divide by 0",e)
except ValueError as e:
print("was not asked for this")
except Exception as e:
print("its just wrong")
finally:
print("error class closed")<file_sep># a=5
# b=2
# k=int(input("enter a number"))
# print(k)
# try:
# print("resource open")
# print(a/b)
# except Exception as e:
# print("hey, you cannot divide a number by 0",e)
# finally:
# print("resource closed")
# writing a program different error exceptions
a=5
b=2
try:
print("resource open")
print(a/b)
k = int(input("enter a number"))
print(k)
except ZeroDivisionError as e:
print("hey, you cannot divide a number by 0",e)
except ValueError as e:
print("invalid input")
except Exception as e:
print("something went wrong")
finally:
print("resource closed")
<file_sep># learning-about-errors<file_sep>a=5
b=0
try:
print(a/b)
except Exception as e:
print("hey you cannot divide a number by zero",e)
print("bye") | 3eb6686b8a140bb3405cd4e90948f3aa1c03922e | [
"Markdown",
"Python"
] | 4 | Python | sudita07/learning-about-errors | 188e8f8f33131213eade0ddc813787adc55914c7 | c63ad9ff2af4d462e34dfea5c80af3b5ed1bb3f4 |
refs/heads/master | <file_sep>package local_Db;
import java.io.Serializable;
import local_Db.DaoSession;
import de.greenrobot.dao.DaoException;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit.
/**
* Entity mapped to table FOTO_DB.
*/
public class FotoDB implements Serializable {
private Long id;
private String titulo;
private String descripcion;
private String archivo;
private Long idOrden;
private Long fotoId;
/** Used to resolve relations */
private transient DaoSession daoSession;
/** Used for active entity operations. */
private transient FotoDBDao myDao;
private OrdenDB ordenDB;
private Long ordenDB__resolvedKey;
public FotoDB() {
}
public FotoDB(Long id) {
this.id = id;
}
public FotoDB(Long id, String titulo, String descripcion, String archivo, Long idOrden, Long fotoId) {
this.id = id;
this.titulo = titulo;
this.descripcion = descripcion;
this.archivo = archivo;
this.idOrden = idOrden;
this.fotoId = fotoId;
}
/** called by internal mechanisms, do not call yourself. */
public void __setDaoSession(DaoSession daoSession) {
this.daoSession = daoSession;
myDao = daoSession != null ? daoSession.getFotoDBDao() : null;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getArchivo() {
return archivo;
}
public void setArchivo(String archivo) {
this.archivo = archivo;
}
public Long getIdOrden() {
return idOrden;
}
public void setIdOrden(Long idOrden) {
this.idOrden = idOrden;
}
public Long getFotoId() {
return fotoId;
}
public void setFotoId(Long fotoId) {
this.fotoId = fotoId;
}
/** To-one relationship, resolved on first access. */
public OrdenDB getOrdenDB() {
Long __key = this.idOrden;
if (ordenDB__resolvedKey == null || !ordenDB__resolvedKey.equals(__key)) {
if (daoSession == null) {
throw new DaoException("Entity is detached from DAO context");
}
OrdenDBDao targetDao = daoSession.getOrdenDBDao();
OrdenDB ordenDBNew = targetDao.load(__key);
synchronized (this) {
ordenDB = ordenDBNew;
ordenDB__resolvedKey = __key;
}
}
return ordenDB;
}
public void setOrdenDB(OrdenDB ordenDB) {
synchronized (this) {
this.ordenDB = ordenDB;
idOrden = ordenDB == null ? null : ordenDB.getId();
ordenDB__resolvedKey = idOrden;
}
}
/** Convenient call for {@link AbstractDao#delete(Object)}. Entity must attached to an entity context. */
public void delete() {
if (myDao == null) {
throw new DaoException("Entity is detached from DAO context");
}
myDao.delete(this);
}
/** Convenient call for {@link AbstractDao#update(Object)}. Entity must attached to an entity context. */
public void update() {
if (myDao == null) {
throw new DaoException("Entity is detached from DAO context");
}
myDao.update(this);
}
/** Convenient call for {@link AbstractDao#refresh(Object)}. Entity must attached to an entity context. */
public void refresh() {
if (myDao == null) {
throw new DaoException("Entity is detached from DAO context");
}
myDao.refresh(this);
}
}
<file_sep>package util.navigation;
/**
* Created by marcoisaac on 5/17/2016.
*/
public interface UpdateList {
public void updateModel(String val, int position);
}
<file_sep>package util.navigation.modelos;
import java.io.Serializable;
import java.util.List;
import local_Db.EquipoDB;
/**
* Created by marcoisaac on 5/11/2016.
*/
public class Equipo implements Serializable {
private Integer idequipo;
private String numeroEquipo;
private int listaNombreEquiposIdlistaNombre;
private String codigoBarras;
private Lugar lugarIdlugar;
private List<Orden> ordenList;
private List<InformacionFabricante> informacionFabricanteList;
public Equipo(String numeroEquipo) {
this.numeroEquipo = numeroEquipo;
}
public Equipo(String numeroEquipo, String codigoBarras, int listaNombreEquiposIdlistaNombre) {
this.numeroEquipo = numeroEquipo;
this.codigoBarras = codigoBarras;
this.listaNombreEquiposIdlistaNombre = listaNombreEquiposIdlistaNombre;
}
public Equipo() {
}
public Integer getIdequipo() {
return idequipo;
}
public void setIdequipo(Integer idequipo) {
this.idequipo = idequipo;
}
public String getNumeroEquipo() {
return numeroEquipo;
}
public void setNumeroEquipo(String numeroEquipo) {
this.numeroEquipo = numeroEquipo;
}
public Lugar getLugarIdlugar() {
return lugarIdlugar;
}
public void setLugarIdlugar(Lugar lugarIdlugar) {
this.lugarIdlugar = lugarIdlugar;
}
public int getListaNombreEquiposIdlistaNombre() {
return listaNombreEquiposIdlistaNombre;
}
public void setListaNombreEquiposIdlistaNombre(int listaNombreEquiposIdlistaNombre) {
this.listaNombreEquiposIdlistaNombre = listaNombreEquiposIdlistaNombre;
}
public String getCodigoBarras() {
return codigoBarras;
}
public void setCodigoBarras(String codigoBarras) {
this.codigoBarras = codigoBarras;
}
public List<Orden> getOrdenList() {
return ordenList;
}
public void setOrdenList(List<Orden> ordenList) {
this.ordenList = ordenList;
}
public List<InformacionFabricante> getInformacionFabricanteList() {
return informacionFabricanteList;
}
public void setInformacionFabricanteList(List<InformacionFabricante> informacionFabricanteList) {
this.informacionFabricanteList = informacionFabricanteList;
}
public EquipoDB transform() {
return null;
}
}
<file_sep>package orden_mode_fragments;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import mantenimiento.mim.com.mantenimiento.R;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import server.RegisterAPI;
import util.navigation.Navigator;
public class ProduceCodeORModeFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private Navigator navigator;
final Handler h = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
showCode();
return false;
}
});
private ProgressDialog dialog;
private EditText caja;
private BarcodeOrderModeConsumer consumer;
public ProduceCodeORModeFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ProduceCodeFragment.
*/
// TODO: Rename and change types and number of parameters
public static ProduceCodeORModeFragment newInstance(String param1, String param2) {
ProduceCodeORModeFragment fragment = new ProduceCodeORModeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_produce_code, container, false);
caja = (EditText) view.findViewById(R.id.show_code);
Button btn = (Button) view.findViewById(R.id.proceed);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
validateCode(caja.getText().toString());
}
});
Button btnScan = (Button) view.findViewById(R.id.scan_code);
btnScan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
readCode();
}
});
dialog = new ProgressDialog(getContext());
dialog.setMessage("Espera un momento...");
dialog.setCanceledOnTouchOutside(false);
dialog.show();
generateCodeFromDB();
return view;
}
private void readCode() {
//launch camera
IntentIntegrator integrator = new IntentIntegrator((Activity) getContext());
integrator.setDesiredBarcodeFormats(IntentIntegrator.ONE_D_CODE_TYPES);
integrator.setPrompt("Scan a barcode");
integrator.setCameraId(0); // Use a specific camera of the device
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(true);
integrator.forSupportFragment(this).initiateScan();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
String toast;
if (result != null) {
if (result.getContents() == null) {
toast = "Cancelado";
} else {
String res = result.getContents();
caja.setText(res);
}
}
}
private void validateCode(String code) {
final ProgressDialog dialog2 = new ProgressDialog(this.getContext());
dialog2.setMessage("validando codigo....");
dialog2.show();
RegisterAPI service = RegisterAPI.Factory.getInstance();
service.validateCode(code).enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if (consumer != null) {
dialog2.dismiss();
if (response.body() != null) {
if (response.body().equals("valido")) {
consumer.barCodeResult(caja.getText().toString());
ProduceCodeORModeFragment.this.navigator.navigate("lugar");
} else {
if (consumer != null) {
Toast.makeText(ProduceCodeORModeFragment.this.getContext(), "codigo invalido", Toast.LENGTH_SHORT).show();
}
}
} else {
if (consumer != null) {
dialog2.dismiss();
Toast.makeText(ProduceCodeORModeFragment.this.getContext(), "hubo un error", Toast.LENGTH_SHORT).show();
}
}
}
}
@Override
public void onFailure(Call<String> call, Throwable throwable) {
if (consumer != null) {
dialog2.dismiss();
Toast.makeText(ProduceCodeORModeFragment.this.getContext(), "hubo un error", Toast.LENGTH_SHORT).show();
}
}
});
}
private void generateCodeFromDB() {
RegisterAPI service = RegisterAPI.Factory.getInstance();
service.getBarCode().enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if (consumer != null) {
if(response.body()!=null) {
caja.setText(response.body());
consumer.barCodeResult(response.body());
dialog.dismiss();
}else{
if (consumer != null) {
dialog.dismiss();
Toast.makeText(ProduceCodeORModeFragment.this.getContext(), "hubo un error", Toast.LENGTH_SHORT).show();
}
}
}
}
@Override
public void onFailure(Call<String> call, Throwable throwable) {
if (consumer != null) {
dialog.dismiss();
Toast.makeText(ProduceCodeORModeFragment.this.getContext(), "hubo un error", Toast.LENGTH_SHORT).show();
}
}
});
}
public void showCode() {
dialog.dismiss();
caja.setText("2131231231");
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof Navigator) {
navigator = (Navigator) context;
consumer = (BarcodeOrderModeConsumer) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement Navigator");
}
}
@Override
public void onDetach() {
super.onDetach();
navigator = null;
consumer = null;
}
public interface BarcodeOrderModeConsumer {
public void barCodeResult(String code);
}
}
<file_sep>package local_Db;
import java.io.Serializable;
import java.util.List;
import local_Db.DaoSession;
import de.greenrobot.dao.DaoException;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit.
/**
* Entity mapped to table LUGAR_DB.
*/
public class LugarDB implements Serializable{
private Long id;
private String nombre;
/** Used to resolve relations */
private transient DaoSession daoSession;
/** Used for active entity operations. */
private transient LugarDBDao myDao;
private List<OrdenDB> ordenDBList;
public LugarDB() {
}
public LugarDB(Long id) {
this.id = id;
}
public LugarDB(Long id, String nombre) {
this.id = id;
this.nombre = nombre;
}
/** called by internal mechanisms, do not call yourself. */
public void __setDaoSession(DaoSession daoSession) {
this.daoSession = daoSession;
myDao = daoSession != null ? daoSession.getLugarDBDao() : null;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
/** To-many relationship, resolved on first access (and after reset). Changes to to-many relations are not persisted, make changes to the target entity. */
public List<OrdenDB> getOrdenDBList() {
if (ordenDBList == null) {
if (daoSession == null) {
throw new DaoException("Entity is detached from DAO context");
}
OrdenDBDao targetDao = daoSession.getOrdenDBDao();
List<OrdenDB> ordenDBListNew = targetDao._queryLugarDB_OrdenDBList(id);
synchronized (this) {
if(ordenDBList == null) {
ordenDBList = ordenDBListNew;
}
}
}
return ordenDBList;
}
/** Resets a to-many relationship, making the next get call to query for a fresh result. */
public synchronized void resetOrdenDBList() {
ordenDBList = null;
}
/** Convenient call for {@link AbstractDao#delete(Object)}. Entity must attached to an entity context. */
public void delete() {
if (myDao == null) {
throw new DaoException("Entity is detached from DAO context");
}
myDao.delete(this);
}
/** Convenient call for {@link AbstractDao#update(Object)}. Entity must attached to an entity context. */
public void update() {
if (myDao == null) {
throw new DaoException("Entity is detached from DAO context");
}
myDao.update(this);
}
/** Convenient call for {@link AbstractDao#refresh(Object)}. Entity must attached to an entity context. */
public void refresh() {
if (myDao == null) {
throw new DaoException("Entity is detached from DAO context");
}
myDao.refresh(this);
}
}
<file_sep>package local_db_activity_fragments;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import local_Db.OrdenDB;
import mantenimiento.mim.com.mantenimiento.R;
import util.navigation.Navigator;
import util.navigation.modelos.Orden;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link OrdenConsumer} interface
* to handle interaction events.
* Use the {@link OrdenInfoFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class OrdenInfoFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private OrdenDB mParam1;
private String mParam2;
private Navigator mListener;
private OrdenConsumer orderConsumer;
private String[] activitiesList = {"mantenimiento", "electrico", "electromecanico", "soldadura", "aislamiento", "construccion", "otro"};
public OrdenInfoFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment OrdenFragment.
*/
// TODO: Rename and change types and number of parameters
public static OrdenInfoFragment newInstance(OrdenDB param1, String param2) {
OrdenInfoFragment fragment = new OrdenInfoFragment();
Bundle args = new Bundle();
args.putSerializable(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = (OrdenDB) getArguments().getSerializable(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.info_orden_local, container, false);
widgetSetUp(view);
return view;
}
private void widgetSetUp(View view) {
final EditText numeroOrden = (EditText) view.findViewById(R.id.numero_orden_loc);
final EditText descripcion = (EditText) view.findViewById(R.id.descripcion_orden_local);
final EditText encargado = (EditText) view.findViewById(R.id.encargado_orden_local);
final Button actividad = (Button) view.findViewById(R.id.actividad_orden_local);
actividad.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Escoge actividad")
.setItems(activitiesList, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
actividad.setText(activitiesList[which]);
}
});
builder.create().show();
}
});
final EditText prioridad = (EditText) view.findViewById(R.id.prioridad_orden_loc);
Button btn = (Button) view.findViewById(R.id.siguiente_orden_local);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (numeroOrden.getText().length() > 0 && encargado.getText().length() > 0
&& descripcion.getText().length() > 0 && actividad.getText().length() > 0
&& prioridad.getText().length() > 0) {
createOrden(numeroOrden.getText().toString(), descripcion.getText().toString(), encargado.getText().toString(), actividad.getText().toString(), prioridad.getText().toString());
mListener.navigate("servicio");
} else {
Toast.makeText(getContext(), "llena todos los datos", Toast.LENGTH_LONG).show();
}
}
});
if (mParam1 != null) {
numeroOrden.setText(mParam1.getNumeroOrden());
descripcion.setText(mParam1.getDescripcion());
encargado.setText(mParam1.getEncargado());
actividad.setText(mParam1.getActividad());
prioridad.setText(mParam1.getPrioridad());
}
}
private void createOrden(String numeroOrden, String descripcion, String encargado, String actividad, String prioridad) {
mParam1.setDescripcion(descripcion);
mParam1.setEncargado(encargado);
mParam1.setNumeroOrden(numeroOrden);
mParam1.setActividad(actividad);
mParam1.setPrioridad(prioridad);
orderConsumer.consumeOrden(mParam1);
}
// TODO: Rename method, update argument and hook method into UI event
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof Navigator) {
mListener = (Navigator) context;
orderConsumer = (OrdenConsumer) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement Navigator");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
orderConsumer = null;
}
public interface OrdenConsumer {
// TODO: Update argument type and name
public void consumeOrden(OrdenDB orden);
}
}
<file_sep>package util.navigation.modelos;
import java.io.Serializable;
/**
* Created by marcoisaac on 5/17/2016.
*/
public class ListaNombreEquipos implements Serializable{
private String nombre;
private int idlistaNombre;
public ListaNombreEquipos(String nombre) {
this.nombre = nombre;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public int getIdlistaNombre() {
return idlistaNombre;
}
public void setIdlistaNombre(int idlistaNombre) {
this.idlistaNombre = idlistaNombre;
}
}
<file_sep>package util.navigation.adapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.io.File;
import java.util.List;
import local_Db.FotoDB;
import local_db_activity_fragments.CameraLocalFragment;
import mantenimiento.mim.com.mantenimiento.LocalDBActivity;
import mantenimiento.mim.com.mantenimiento.R;
import util.navigation.BlackBasket;
import util.navigation.OnclickLink;
import util.navigation.modelos.Foto;
import static android.R.attr.button;
/**
* Created by marcoisaac on 5/11/2016.
*/
public class FotosLocalAdapter extends RecyclerView.Adapter<FotosLocalAdapter.ViewHolder> implements OnclickLink {
private final DisplayMetrics metrics;
private final BlackBasket basket;
private List<FotoDB> mDataset;
private PositionConsumer positon;
private Context context;
public interface PositionConsumer {
public void position(int position);
}
public FotosLocalAdapter(List<FotoDB> myDataset, Context context, BlackBasket basket, PositionConsumer pos) {
mDataset = myDataset;
this.basket = basket;
this.context = context;
positon = pos;
metrics = new DisplayMetrics();
final WindowManager windowManager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(metrics);
}
@Override
public void position(int pos) {
positon.position(pos);
}
@Override
public void positionDialog(int pos) {
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
private final TextView title;
private final TextView descripcion;
private final ImageView image;
private final BlackBasket basket;
private final CheckBox check;
private final Button btnUp;
private final Button btnDown;
public CardView parent;
private OnclickLink link;
public ViewHolder(CardView v, final BlackBasket basket, OnclickLink link, final Context context) {
super(v);
this.parent = v;
v.setOnClickListener(this);
v.setOnLongClickListener(this);
this.basket = basket;
this.link = link;
title = (TextView) v.findViewById(R.id.description_corta);
descripcion = (TextView) v.findViewById(R.id.description_larga);
image = (ImageView) v.findViewById(R.id.imagen_cartita);
check = (CheckBox) v.findViewById(R.id.check_cartas);
check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Toast.makeText(context, "posicion: " + getLayoutPosition(), Toast.LENGTH_SHORT).show();
if (isChecked) {
basket.addElementToBlackList(getLayoutPosition());
} else {
basket.removeFromBlackList(getLayoutPosition());
}
}
});
;
btnUp = (Button) v.findViewById(R.id.up_btn_cell);
btnUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(context, "up", Toast.LENGTH_SHORT).show();
basket.changePosition(getLayoutPosition(),true);
}
});
btnDown = (Button) v.findViewById(R.id.down_btn_cell);
btnDown.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(context, "down", Toast.LENGTH_SHORT).show();
basket.changePosition(getLayoutPosition(),false);
}
});
}
@Override
public void onClick(View v) {
if (!basket.getBoolean()) {
link.position(getLayoutPosition());
} else {
basket.showElementInfo(getLayoutPosition());
}
}
@Override
public boolean onLongClick(View v) {
basket.showCheckBox();
return true;
}
}
@Override
public FotosLocalAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
CardView v = (CardView) LayoutInflater.from(parent.getContext()).inflate(R.layout.cartas, parent, false);
ViewHolder vh = new ViewHolder(v, basket, this, context);
return vh;
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
if (basket.getBoolean()) {
holder.check.setVisibility(View.VISIBLE);
holder.btnUp.setVisibility(View.VISIBLE);
holder.btnDown.setVisibility(View.VISIBLE);
//holder.parent.findViewById(R.id.check_cartas).setVisibility(View.VISIBLE);
//holder.check.setVisibility(View.VISIBLE);
} else {
//holder.parent.findViewById(R.id.check_cartas).setVisibility(View.GONE);
holder.check.setVisibility(View.GONE);
holder.btnUp.setVisibility(View.GONE);
holder.btnDown.setVisibility(View.GONE);
}
if (basket.checkPosition(position)) {
((CheckBox) holder.parent.findViewById(R.id.check_cartas)).setChecked(true);
} else {
((CheckBox) holder.parent.findViewById(R.id.check_cartas)).setChecked(false);
}
FotoDB foto = mDataset.get(position);
holder.title.setText(foto.getTitulo());
holder.descripcion.setText(foto.getDescripcion());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//holder.image.setImageDrawable(context.getDrawable(camarita));
}
File fil = new File(foto.getArchivo());//
if (fil.exists()) {
//Toast.makeText(context, "si existe el archivo", Toast.LENGTH_LONG).show();
Picasso.with(context).load(fil).
resize((int) (metrics.widthPixels)// fil as parameter
, (int) (150)) // instead of Uri was file path in ExpandableCustomAdp
.into(holder.image);
} else {
Toast.makeText(context, "No existe: -> " + fil.getPath(), Toast.LENGTH_LONG).show();
}
}
@Override
public int getItemCount() {
if (mDataset != null) {
return mDataset.size();
} else {
return 0;
}
}
}<file_sep>package util.navigation;
/**
* Created by marcoisaac on 6/14/2016.
*/
public interface CompresConsumer {
public void compresResult(boolean res, int codigo);
}
<file_sep>package util.navigation;
import util.navigation.modelos.ListaNombreEquipos;
/**
* Created by marcoisaac on 5/10/2016.
*/
public interface Navigator {
public void navigate(String addres);
public void tipoEquipo(ListaNombreEquipos tip);
}
<file_sep>package local_db_activity_fragments;
import android.app.Activity;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import data_activity_fragments.FotoDialogFragment;
import data_activity_fragments.ImageViewFragment;
import local_Db.FotoDB;
import mantenimiento.mim.com.mantenimiento.R;
import util.navigation.BlackBasket;
import util.navigation.Modifier;
import util.navigation.Navigator;
import util.navigation.adapter.FotosAdapter;
import util.navigation.adapter.FotosLocalAdapter;
import util.navigation.custom.recycler.RecyclerViewEmpty;
import util.navigation.modelos.Foto;
/**
* A simple {@link Fragment} subclass.
* Use the {@link CameraLocalFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class CameraLocalFragment extends Fragment implements FotosAdapter.PositionConsumer
, FotosLocalAdapter.PositionConsumer, BlackBasket {
private Menu menu;
private boolean control = false;
private final int SELECT_PHOTO = 199;
private final int SELECT_PHOTO_MULTI = 149;
private Boolean showCheck = false;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private Navigator navigator;
private RecyclerViewEmpty mRecyclerView;
private RecyclerViewEmpty.Adapter mAdapter;
private RecyclerViewEmpty.LayoutManager mLayoutManager;
private List<FotoDB> dataList = new ArrayList<>();
//private List<FotoDB> blackList = new ArrayList<>();
private Map<Integer, FotoDB> blackList = new HashMap<>();
private FloatingActionButton floatButton;
private String ruta;
private PhotosConsumer consumer;
public static final int REQUEST_IMAGE_CAPTURE = 4231;
public CameraLocalFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment CameraFragment.
*/
// TODO: Rename and change types and number of parameters
public static CameraLocalFragment newInstance(String param1, String param2, Navigator navigator) {
CameraLocalFragment fragment = new CameraLocalFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof Navigator) {
navigator = (Navigator) context;
consumer = (PhotosConsumer) context;
}
}
@Override
public void onDetach() {
super.onDetach();
consumer = null;
navigator = null;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_camera_local, container, false);
widgetSetUp(view);
dataSetUp();
recyclerSetUp(view);
InputMethodManager inputManager = (InputMethodManager) getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
// check if no view has focus:
inputManager.hideSoftInputFromWindow(container.getWindowToken(), 0);
return view;
}
@Override
public void onStop() {
super.onStop();
if (consumer != null) {
consumer.setPhotosList(dataList);
consumer.setBlackList(blackList);
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.camera_local_menu, menu);
Modifier.changeMenuItemColor(menu);
this.menu = menu;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.camera_foto_local:
cameraIntent();
break;
case R.id.camera_attach_dos:
pickPhoto();
break;
case R.id.delete_camera_local:
purgeList();
showCheckBox();
break;
case R.id.camera_foto_multi_local:
pickMultiple();
break;
}
return super.onOptionsItemSelected(item);
}
private void pickPhoto() {
control = false;
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
private void pickMultiple() {
control = false;
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PHOTO_MULTI);
}
private void dataSetUp() {
if (consumer.getPhotosList() != null) {
dataList = consumer.getPhotosList();
}
}
private void widgetSetUp(View view) {
floatButton = (FloatingActionButton) view.findViewById(R.id.fab_picture_local);
floatButton.setOnClickListener(new FloatingActionButton.OnClickListener() {
@Override
public void onClick(View v) {
cameraIntent();
}
});
}
private File createImageFile() throws IOException {
Random r = new Random();
int i1 = r.nextInt(200 - 70) + 17;
int i2 = r.nextInt(67 - 12) - 6;
int i3 = r.nextInt(89 - 27) - 6;
int i4 = r.nextInt(200 - 70) + 17;
int i5 = r.nextInt(89 - 27) - 6;
String photoTitle = "JPEG_" + i1 + i2 + "uncompressed_" + i3 + i4 + "-" + i5;
File image = new File(Environment. //THIS WORKS
getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
photoTitle + ".jpg");
return image;
}
static final int REQUEST_TAKE_PHOTO = 1;
private void cameraIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getContext().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
ruta = photoFile.getPath();
} catch (IOException ex) {
// Error occurred while creating the File
//...
Toast.makeText(getContext(), "exception in file creation", Toast.LENGTH_LONG).show();
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
} else {
Toast.makeText(getContext(), "no se creo el archivo temporal", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getContext(), "package manager es nulo", Toast.LENGTH_LONG).show();
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_IMAGE_CAPTURE:
imageResult(resultCode);
break;
case SELECT_PHOTO:
if (resultCode == ((Activity) getContext()).RESULT_OK) {
try {
final Uri imageUri = data.getData();
final File imageFile = proccessImageFile(imageUri);
FotoDialogFragment foto = FotoDialogFragment.newInstance(null, null, 0);
foto.show(getFragmentManager(), "dialog");
ruta = imageFile.getAbsolutePath();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
break;
case SELECT_PHOTO_MULTI:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
if (data == null) {
return;
}
if (data.getClipData() != null) {
ClipData mClipData = data.getClipData();
ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
for (int i = 0; i < mClipData.getItemCount(); i++) {
ClipData.Item item = mClipData.getItemAt(i);
Uri uri = item.getUri();
mArrayUri.add(uri);
try {
final File imageFile = proccessImageFile(uri);
ruta = imageFile.getPath();
setPhotoInfo("modificar", "modificar", false);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(this.getContext(), uri.getPath(), Toast.LENGTH_SHORT).show();
}
}
}
break;
}
}
private File proccessImageFile(Uri imageUri) throws IOException {
final InputStream imageStream = ((Activity) getContext()).getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
final File imageFile = createImageFile();
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
OutputStream stream = new FileOutputStream(imageFile);
selectedImage.compress(Bitmap.CompressFormat.JPEG, 100, stream);
stream.flush();
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
notifyChange();
}
}.execute();
return imageFile;
}
private void imageResult(int resultCode) {
if (resultCode == ((Activity) getContext()).RESULT_OK) {
control = true;
FotoDialogFragment foto = FotoDialogFragment.newInstance(null, null, 0);
foto.show(getFragmentManager(), "dialog");
} else if (resultCode == ((Activity) getContext()).RESULT_CANCELED) {
// User cancelled the image capture
if (ruta != null) {
Toast.makeText(getContext(), "borra archivo", Toast.LENGTH_LONG).show();
}
} else {
// Image capture failed, advise user
}
}
private void notifyChange() {
mAdapter.notifyDataSetChanged();
}
private void recyclerSetUp(View view) {
mRecyclerView = (RecyclerViewEmpty) view.findViewById(R.id.fotos_reciclador_local);
mRecyclerView.setEmptyView((TextView) view.findViewById(R.id.empty_view_local_fotos));
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new FotosLocalAdapter(dataList, getContext(), this, this);
mRecyclerView.setAdapter(mAdapter);
}
public void setNavigator(Navigator navigator) {
this.navigator = navigator;
}
public void setPhotoInfo(String title, String descripcion) {
FotoDB current = new FotoDB();
current.setArchivo(ruta);
current.setTitulo(title);
current.setDescripcion(descripcion);
dataList.add(current);
mAdapter.notifyDataSetChanged();
}
public void addElementToBlackList(int position) {
blackList.put(position, dataList.get(position));
}
public void removeFromBlackList(int position) {
blackList.remove(dataList.get(position));
}
@Override
public void showCheckBox() {
MenuItem attachment = menu.findItem(R.id.camera_attach_dos);
MenuItem takePhoto = menu.findItem(R.id.camera_foto_local);
MenuItem delete = menu.findItem(R.id.delete_camera_local);
if (showCheck) {
showCheck = false;
attachment.setVisible(true);
takePhoto.setVisible(true);
delete.setVisible(false);
consumer.setActionMode(false);
} else {
showCheck = true;
attachment.setVisible(false);
takePhoto.setVisible(false);
delete.setVisible(true);
consumer.setActionMode(true);
}
mAdapter.notifyDataSetChanged();
}
@Override
public boolean getBoolean() {
return showCheck;
}
@Override
public void showElementInfo(int layoutPosition) {
String title = dataList.get(layoutPosition).getTitulo();
String descripcion = dataList.get(layoutPosition).getDescripcion();
FotoDialogFragment foto = FotoDialogFragment.newInstance(title, descripcion, layoutPosition);
foto.show(getFragmentManager(), "dialog");
}
@Override
public boolean checkPosition(int position) {
if (blackList.get(position) != null) {
return true;
} else {
return false;
}
}
//change order of given object
@Override
public void changePosition(int position, boolean up) {
if (up) {
if ((position - 1) >= 0) {
FotoDB temp = new FotoDB();
Modifier.cloneFotoDB(temp, dataList.get(position));
Modifier.cloneFotoDB(dataList.get(position), dataList.get(position - 1));
Modifier.cloneFotoDB(dataList.get(position - 1), temp);
mAdapter.notifyDataSetChanged();
}
} else {
if ((position + 1) <= (dataList.size() - 1)) {
FotoDB temp = new FotoDB();
Modifier.cloneFotoDB(temp, dataList.get(position));
Modifier.cloneFotoDB(dataList.get(position), dataList.get(position + 1));
Modifier.cloneFotoDB(dataList.get(position + 1), temp);
mAdapter.notifyDataSetChanged();
}
}
}
public void setPhotoInfo(String title, String descripcion, boolean call) {
FotoDB current = new FotoDB();
current.setArchivo(ruta);
current.setTitulo(title);
current.setDescripcion(descripcion);
dataList.add(current);
}
public void purgeList() {
for (Map.Entry<Integer, FotoDB> entry : blackList.entrySet()) {
Integer key = entry.getKey();
FotoDB ft = entry.getValue();
dataList.remove(ft);
}
mAdapter.notifyDataSetChanged();
}
@Override
public void position(int position) {
ImageViewFragment dialog = ImageViewFragment.newInstance(dataList.get(position).getArchivo(), null);
dialog.show(getFragmentManager(), "imgDialog");
}
public void closeActionMode() {
showCheckBox();
}
public void editModel(String title, String descripcion, int posicion) {
FotoDB foto = dataList.get(posicion);
foto.setDescripcion(descripcion);
foto.setTitulo(title);
mAdapter.notifyDataSetChanged();
}
public interface PhotosConsumer {
public void setPhotosList(List<FotoDB> list);
public void setBlackList(Map<Integer, FotoDB> blackList);
public List<FotoDB> getPhotosList();
public void setActionMode(boolean mode);
public boolean isActionMode();
}
}
<file_sep>package local_Db;
import java.io.Serializable;
import local_Db.DaoSession;
import de.greenrobot.dao.DaoException;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit.
/**
* Entity mapped to table HISTORIAL_DETALLES_DB.
*/
public class HistorialDetallesDB implements Serializable{
private Long id;
private Integer idhistorial;
private String parametro;
private String valor;
private Long ordenId;
private Long hitorialId;
/** Used to resolve relations */
private transient DaoSession daoSession;
/** Used for active entity operations. */
private transient HistorialDetallesDBDao myDao;
private OrdenDB ordenDB;
private Long ordenDB__resolvedKey;
public HistorialDetallesDB() {
}
public HistorialDetallesDB(String parametro, String valor) {
this.parametro = parametro;
this.valor = valor;
}
public HistorialDetallesDB(Long id) {
this.id = id;
}
public HistorialDetallesDB(Long id, Integer idhistorial, String parametro, String valor, Long ordenId, Long hitorialId) {
this.id = id;
this.idhistorial = idhistorial;
this.parametro = parametro;
this.valor = valor;
this.ordenId = ordenId;
this.hitorialId = hitorialId;
}
/** called by internal mechanisms, do not call yourself. */
public void __setDaoSession(DaoSession daoSession) {
this.daoSession = daoSession;
myDao = daoSession != null ? daoSession.getHistorialDetallesDBDao() : null;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getIdhistorial() {
return idhistorial;
}
public void setIdhistorial(Integer idhistorial) {
this.idhistorial = idhistorial;
}
public String getParametro() {
return parametro;
}
public void setParametro(String parametro) {
this.parametro = parametro;
}
public String getValor() {
return valor;
}
public void setValor(String valor) {
this.valor = valor;
}
public Long getOrdenId() {
return ordenId;
}
public void setOrdenId(Long ordenId) {
this.ordenId = ordenId;
}
public Long getHitorialId() {
return hitorialId;
}
public void setHitorialId(Long hitorialId) {
this.hitorialId = hitorialId;
}
/** To-one relationship, resolved on first access. */
public OrdenDB getOrdenDB() {
Long __key = this.ordenId;
if (ordenDB__resolvedKey == null || !ordenDB__resolvedKey.equals(__key)) {
if (daoSession == null) {
throw new DaoException("Entity is detached from DAO context");
}
OrdenDBDao targetDao = daoSession.getOrdenDBDao();
OrdenDB ordenDBNew = targetDao.load(__key);
synchronized (this) {
ordenDB = ordenDBNew;
ordenDB__resolvedKey = __key;
}
}
return ordenDB;
}
public void setOrdenDB(OrdenDB ordenDB) {
synchronized (this) {
this.ordenDB = ordenDB;
ordenId = ordenDB == null ? null : ordenDB.getId();
ordenDB__resolvedKey = ordenId;
}
}
/** Convenient call for {@link AbstractDao#delete(Object)}. Entity must attached to an entity context. */
public void delete() {
if (myDao == null) {
throw new DaoException("Entity is detached from DAO context");
}
myDao.delete(this);
}
/** Convenient call for {@link AbstractDao#update(Object)}. Entity must attached to an entity context. */
public void update() {
if (myDao == null) {
throw new DaoException("Entity is detached from DAO context");
}
myDao.update(this);
}
/** Convenient call for {@link AbstractDao#refresh(Object)}. Entity must attached to an entity context. */
public void refresh() {
if (myDao == null) {
throw new DaoException("Entity is detached from DAO context");
}
myDao.refresh(this);
}
}
<file_sep>package util.navigation.async_tasks;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import com.itextpdf.text.DocumentException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import local_Db.EquipoDB;
import local_Db.FotoDB;
import local_Db.HistorialDetallesDB;
import local_Db.LugarDB;
import local_Db.OrdenDB;
import report_generator.ReporteEnvasado;
/**
* Created by marcoisaac on 6/7/2016.
*/
public class ReportBuilder extends AsyncTask<Void, Void, Boolean> {
private Context context;
private OrdenDB orden;
private List<HistorialDetallesDB> observaciones;
private List<FotoDB> fotos;
private EquipoDB equipo;
private LugarDB lugar;
private byte[] imageBytes;
public ReportBuilder(Context context, OrdenDB orden, List<HistorialDetallesDB> observaciones, List<FotoDB> fotos, EquipoDB equipo, LugarDB lugar, byte[] imageBytes) throws IOException, FileNotFoundException, DocumentException {
this.orden = orden;
this.equipo = equipo;
this.lugar = lugar;
this.fotos = fotos;
this.imageBytes = imageBytes;
this.observaciones = observaciones;
this.context = context;
}
@Override
protected Boolean doInBackground(Void... params) {
try {
new ReporteEnvasado(context, orden, observaciones, fotos, equipo, lugar, imageBytes);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} catch (DocumentException e) {
e.printStackTrace();
return false;
}
}
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
if (context != null) {
if (aBoolean) {
Toast.makeText(context, "reporte creado", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "hubo algun error", Toast.LENGTH_LONG).show();
}
}
}
}
<file_sep>package register_activity_fragments;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import mantenimiento.mim.com.mantenimiento.R;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import server.RegisterAPI;
import util.navigation.Navigator;
import util.navigation.OnclickLink;
import util.navigation.adapter.TipoAdapter;
import util.navigation.custom.recycler.RecyclerViewEmpty;
import util.navigation.modelos.ListaNombreEquipos;
public class TypeFragment extends Fragment implements OnclickLink {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private Navigator navigator;
private RecyclerViewEmpty mRecyclerView;
private RecyclerViewEmpty.Adapter mAdapter;
private RecyclerViewEmpty.LayoutManager mLayoutManager;
private List<ListaNombreEquipos> list = new ArrayList<>();
;
final Handler handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
dataSetUp();
dialog.dismiss();
return false;
}
});
private ProgressDialog dialog;
public TypeFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment TypeFragment.
*/
// TODO: Rename and change types and number of parameters
public static TypeFragment newInstance(String param1, String param2) {
TypeFragment fragment = new TypeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_type, container, false);
//dataSetUp();
loadData();
recyclerSetUp(view);
return view;
}
private void loadData() {
dialog = new ProgressDialog(getContext());
dialog.setMessage("Cargando categorias...");
dialog.setCanceledOnTouchOutside(false);
dialog.show();
RegisterAPI service = RegisterAPI.Factory.getInstance();
service.getListNombreEquipos().enqueue(new Callback<List<ListaNombreEquipos>>() {
@Override
public void onResponse(Call<List<ListaNombreEquipos>> call, Response<List<ListaNombreEquipos>> response) {
dialog.dismiss();
if (response.body() != null) {
if (list.size() > 0) {
list.clear();
}
for (int i = 0; i < response.body().size(); i++) {
list.add(response.body().get(i));
}
mAdapter.notifyDataSetChanged();
} else {
if (getContext() != null) {
Toast.makeText(getContext(), "hubo algun error", Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onFailure(Call<List<ListaNombreEquipos>> call, Throwable throwable) {
if (getContext() != null) {
Toast.makeText(getContext(), "hubo algun error", Toast.LENGTH_LONG).show();
}
}
});
}
private void dataSetUp() {
if (list.size() > 0) {
list.clear();
}
list.add(new ListaNombreEquipos("motor"));
list.add(new ListaNombreEquipos("cadena"));
list.add(new ListaNombreEquipos("sprocket"));
mAdapter.notifyDataSetChanged();
}
private void recyclerSetUp(View view) {
mRecyclerView = (RecyclerViewEmpty) view.findViewById(R.id.tipos_list);
mRecyclerView.setEmptyView((TextView) view.findViewById(R.id.empty_view_tipos));
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new TipoAdapter(list, getContext(), this);
mRecyclerView.setAdapter(mAdapter);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof Navigator) {
navigator = (Navigator) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement PortableDialogConsumer");
}
}
@Override
public void onDetach() {
super.onDetach();
navigator = null;
}
@Override
public void position(int pos) {
navigator.tipoEquipo(list.get(pos));
navigator.navigate("info");
}
@Override
public void positionDialog(int pos) {
}
}
<file_sep>package server;
import java.util.List;
import java.util.concurrent.TimeUnit;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
import retrofit2.http.Path;
import retrofit2.http.Query;
import util.navigation.WorkServer;
import util.navigation.modelos.Equipo;
import util.navigation.modelos.Foto;
import util.navigation.modelos.HistorialDetalles;
import util.navigation.modelos.InformacionFabricante;
import util.navigation.modelos.ListaNombreEquipos;
import util.navigation.modelos.Orden;
/**
* Service used to register an equipment into the DB
* Created by marcoisaac on 5/19/2016.
*/
public interface OrdenAPI {
//public static final String BASE_URL = "http://mantenimiento-contactres.rhcloud.com/MantenimientoRest/webresources/";
//public static final String BASE_URL = "http://env-5002349.jl.serv.net.mx/rest/webresources/";
//public static final String BASE_URL = "http://cemex-5266592.jl.serv.net.mx/rest/webresources/";
public class Factory {
private static OrdenAPI service;
public static OrdenAPI getInstance() {
//if (service == null) {
final OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.build();
Retrofit retrofit = new Retrofit.Builder()
//.baseUrl(instance.getBASE_URL())
.baseUrl(WorkServer.BASE_URL)
.client(okHttpClient)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
service = retrofit.create(OrdenAPI.class);
return service;
// } else {
// return service;
//}
}
}
// FOR RETRIEVE DATA
@GET("com.mim.entities.equipo/{code}")
public Call<Equipo> getEquipmentByCodeBar(@Path("code") String codigo);
@GET("com.mim.entities.informacionfabricante/factoryList/{id}")
public Call<List<InformacionFabricante>> getFactoryList(@Path("id") int equipoId);
@GET("com.mim.entities.historialdetalles/history/{id}")
public Call<List<HistorialDetalles>> getHistorialDetalles(@Path("id") int idEquipo);
@GET("com.mim.entities.listanombreequipos/nombre/{id}")
public Call<ListaNombreEquipos> getNombreEquipo(@Path("id") int id);
// DATA PERSIST
@POST("com.mim.entities.orden/sube")
public Call<Orden> persistOrder(@Body Orden orden);
@GET("com.mim.entities.orden/mark/{numero}")
public Call<Orden> markOrder(@Path("numero") int id);
@POST("com.mim.entities.historialdetalles/lista/{orden}")
public Call<HistorialDetalles> persistHistoryList(@Path("orden") int orden, @Body List<HistorialDetalles> historyList);
@POST("com.mim.entities.fotos/objetos/{id}")
public Call<Foto> persistPhotoObjects(@Path("id") int id, @Body List<Foto> list);
//upload picture
@Multipart
@POST("com.mim.entities.fotos/prime")
public Call<ResponseBody> uploadImage2(@Part("id") String id, @Part("file") RequestBody imagen);
}<file_sep>package register_activity_fragments;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import mantenimiento.mim.com.mantenimiento.R;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import server.LugarAPI;
import util.navigation.Modifier;
import util.navigation.Navigator;
import util.navigation.OnclickLink;
import util.navigation.SerialListHolder;
import util.navigation.WorkServer;
import util.navigation.modelos.Lugar;
import org.apache.commons.io.*;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link Navigator} interface
* to handle interaction events.
* Use the {@link ChooseLineFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ChooseLineFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnclickLink link;
private Navigator mListener;
private List<Lugar> dataList;
private LineDialogFragment dialog;
private Button btn;
private LineConsumer lineConsumer;
private String nombre = null;
private boolean control = false;
private ProgressDialog pg;
public ChooseLineFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ChooseLineFragment.
*/
// TODO: Rename and change types and number of parameters
public static ChooseLineFragment newInstance(String param1, String param2) {
ChooseLineFragment fragment = new ChooseLineFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
setHasOptionsMenu(true);
dataSetUp();
View view = inflater.inflate(R.layout.fragment_choose_line, container, false);
widgetSetUp(view);
return view;
}
private void widgetSetUp(View view) {
btn = (Button) view.findViewById(R.id.choose_line_register);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog = LineDialogFragment.newInstance(new SerialListHolder(dataList), null);
dialog.show(ChooseLineFragment.this.getFragmentManager(), "fotoRep");
}
});
Button next = (Button) view.findViewById(R.id.siguiente_register);
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (control) {
mListener.navigate("tipo");
}
}
});
}
private void dataSetUp() {
File file = null;
switch (WorkServer.POSICION) {
case 0:
file = new File(Environment. //THIS WORKS
getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
"cerveceria.txt");
break;
case 1:
file = new File(Environment. //THIS WORKS
getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
"concretos.txt");
break;
}
dataList = new ArrayList<>();
readList(file);
}
private void readList(File file) {
String content;
if (file.exists()) {
try {
//FileUtils.writeStringToFile(file, "porque?", "UTF-8");
content = FileUtils.readFileToString(file, "UTF-8");
if (content.length() > 0) {
Gson gson = new Gson();
Type listType = new TypeToken<List<Lugar>>() {
}.getType();
List<Lugar> lugaresList = gson.fromJson(content, listType);
dataList.clear();
dataList.addAll(lugaresList);
//for (Lugar l : lugaresList) {
// Toast.makeText(ChooseLineFragment.this.getContext(), l.getNombre(), Toast.LENGTH_SHORT).show();
//}
}
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
file.createNewFile();
syncList();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.choose_line_menu, menu);
Modifier.changeMenuItemColor(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.choose_line_sync:
Context context = ChooseLineFragment.this.getContext();
if (context != null) {
pg = new ProgressDialog(context);
pg.setMessage("espera un momento...");
pg.setCanceledOnTouchOutside(false);
pg.show();
syncList();
}
break;
}
return super.onOptionsItemSelected(item);
}
private void syncList() {
LugarAPI.Factory.getInstance().getLugaresList().enqueue(new Callback<List<Lugar>>() {
@Override
public void onResponse(Call<List<Lugar>> call, Response<List<Lugar>> response) {
List<Lugar> body = response.body();
if (body != null) {
Context context = ChooseLineFragment.this.getContext();
if (context == null) {
return;
}
if(pg!=null) {
pg.hide();
}
Gson gson = new Gson();
String json = gson.toJson(body);
File file = null;
switch (WorkServer.POSICION) {
case 0:
file = new File(Environment. //THIS WORKS
getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
"cerveceria.txt");
break;
case 1:
file = new File(Environment. //THIS WORKS
getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
"concretos.txt");
break;
}
try {
FileUtils.writeStringToFile(file, json, "UTF-8");
//Toast.makeText(context, json, Toast.LENGTH_SHORT).show();
dataList.clear();
dataList.addAll(body);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call<List<Lugar>> call, Throwable throwable) {
Context context = ChooseLineFragment.this.getContext();
if (context == null) {
return;
}
Toast.makeText(context, "hubo algun error", Toast.LENGTH_LONG).show();
if(pg!=null) {
pg.hide();
}
}
});
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof Navigator) {
mListener = (Navigator) context;
lineConsumer = (LineConsumer) context;
link = (OnclickLink) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement Navigator");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
lineConsumer = null;
link = null;
}
public void setSelectedLine(int selectedLine) {
control = true;
dialog.dismiss();
nombre = dataList.get(selectedLine).getNombre();
btn.setText(nombre);
lineConsumer.consumeLine(nombre);
}
public interface LineConsumer {
public void consumeLine(String name);
}
}
<file_sep>package register_activity_fragments;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import mantenimiento.mim.com.mantenimiento.R;
import util.navigation.Modifier;
import util.navigation.Navigator;
import util.navigation.OnclickLink;
import util.navigation.SerialListHolder;
import util.navigation.adapter.RegisterAdapter;
import util.navigation.modelos.Equipo;
import util.navigation.modelos.HistorialDetalles;
import util.navigation.modelos.InformacionFabricante;
import util.navigation.modelos.ListaNombreEquipos;
/**
* A simple {@link Fragment} subclass.
* Use the {@link InfoFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class InfoFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private ListaNombreEquipos mParam1;
private List<InformacionFabricante> dataList;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private EditText numeroField;
private Equipo equipo = new Equipo();
private Navigator navigator;
private OnclickLink link;
private RegisterConsumer regCon;
public InfoFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment EquipmentFragment.
*/
// TODO: Rename and change types and number of parameters
public static InfoFragment newInstance(ListaNombreEquipos param1, SerialListHolder param2) {
InfoFragment fragment = new InfoFragment();
Bundle args = new Bundle();
args.putSerializable(ARG_PARAM1, param1);
args.putSerializable(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = (ListaNombreEquipos) getArguments().getSerializable(ARG_PARAM1);
dataList = ((SerialListHolder) getArguments().getSerializable(ARG_PARAM2)).getInformacionFabricantes();
}
setHasOptionsMenu(true);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
navigator = (Navigator) context;
link = (OnclickLink) context;
regCon = (RegisterConsumer) context;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
List<InformacionFabricante> filtered = new ArrayList<>();
for (int i = 0; i < dataList.size(); i++) {
InformacionFabricante gen = dataList.get(i);
// if (gen.isShow()) {
filtered.add(gen);
// }
}
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.register_equipment, container, false);
widgetSetUp(view);
recyclerSetUp(view, filtered);
return view;
}
private void testData() {
dataList = new ArrayList<>();
dataList.add(new InformacionFabricante("Amperaje"));
dataList.add(new InformacionFabricante("Voltaje"));
dataList.add(new InformacionFabricante("Res"));
dataList.add(new InformacionFabricante("Nema"));
dataList.add(new InformacionFabricante("Nema"));
dataList.add(new InformacionFabricante("Nema"));
dataList.add(new InformacionFabricante("Nema"));
dataList.add(new InformacionFabricante("Nema"));
}
private void widgetSetUp(View view) {
numeroField = (EditText) view.findViewById(R.id.info_numero_equipo);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.register_menu, menu);
//PARA CAMBIAR DE COLOR LOS MENU_ITEM
Modifier.changeMenuItemColor(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.enviar_register:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Warn");
builder.setMessage("Registrar equipo?");
builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (numeroField.getText().length() > 0) {
regCon.register(dataList, numeroField.getText().toString());
} else {
Toast.makeText(InfoFragment.this.getContext(), "escribe numero equipo", Toast.LENGTH_LONG).show();
}
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//TODO
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
break;
}
return super.onOptionsItemSelected(item);
}
private void recyclerSetUp(View view, List<InformacionFabricante> filtered) {
mRecyclerView = (RecyclerView) view.findViewById(R.id.generales_register);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(getContext());
mRecyclerView.setLayoutManager(mLayoutManager);
// specify an adapter (see also next example)
mAdapter = new RegisterAdapter(filtered, getFragmentManager(), link);
mRecyclerView.setAdapter(mAdapter);
}
public void setNavigator(Navigator navigator) {
this.navigator = navigator;
}
public void setValor(String valor, int current) {
//para cerrar keyboard
getActivity().getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
// end cerrar
dataList.get(current).setValor(valor);
mAdapter.notifyDataSetChanged();
}
@Override
public void onDestroy() {
super.onDestroy();
}
public interface RegisterConsumer {
public void register(List<InformacionFabricante> infoList, String numeroEquipo);
}
}
<file_sep>package data_activity_fragments;
import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import mantenimiento.mim.com.mantenimiento.R;
import menu_inicio.MainMenuFragment;
import util.navigation.Navigator;
import util.navigation.WorkServer;
import util.navigation.modelos.Orden;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link OrdenConsumer} interface
* to handle interaction events.
* Use the {@link OrdenFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class OrdenFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private Navigator mListener;
private OrdenConsumer orderConsumer;
private String[] activitiesList = {"mantenimiento", "electrico", "electromecanico", "soldadura", "aislamiento", "construccion", "otro"};
public OrdenFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment OrdenFragment.
*/
// TODO: Rename and change types and number of parameters
public static OrdenFragment newInstance(String param1, String param2) {
OrdenFragment fragment = new OrdenFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_orden, container, false);
widgetSetUp(view);
return view;
}
private void widgetSetUp(View view) {
final EditText numeroOrden = (EditText) view.findViewById(R.id.numero_orden);
if (mParam1 != null) {
numeroOrden.setText(mParam1);
}
final EditText descripcion = (EditText) view.findViewById(R.id.descripcion_orden);
final EditText encargado = (EditText) view.findViewById(R.id.encargado_orden);
final Button actividad = (Button) view.findViewById(R.id.actividad_orden);
actividad.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Escoge actividad")
.setItems(activitiesList, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
actividad.setText(activitiesList[which]);
}
});
builder.create().show();
}
});
final EditText prioridad = (EditText) view.findViewById(R.id.prioridad_orden);
Button btn = (Button) view.findViewById(R.id.siguiente_orden);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (numeroOrden.getText().length() > 0 && encargado.getText().length() > 0
&& descripcion.getText().length() > 0 && !actividad.getText().equals("selecciona..")
&& prioridad.getText().length() > 0) {
createOrden(numeroOrden.getText().toString(), descripcion.getText().toString(), encargado.getText().toString(), actividad.getText().toString(), prioridad.getText().toString());
mListener.navigate("servicio");
} else {
Toast.makeText(getContext(), "llena todos los datos", Toast.LENGTH_LONG).show();
}
}
});
}
private void createOrden(String numeroOrden, String descripcion, String encargado, String actividad, String prioridad) {
Orden orden = new Orden();
orden.setDescripcion(descripcion);
orden.setEncargado(encargado);
orden.setNumeroOrden(numeroOrden);
orden.setActividad(actividad);
orden.setPrioridad(prioridad);
orderConsumer.consumeOrden(orden);
}
// TODO: Rename method, update argument and hook method into UI event
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof Navigator) {
mListener = (Navigator) context;
orderConsumer = (OrdenConsumer) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement Navigator");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
orderConsumer = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OrdenConsumer {
// TODO: Update argument type and name
public void consumeOrden(Orden orden);
}
}
| af6f753b6058bed44864072a4a425e3323163eca | [
"Java"
] | 18 | Java | robbStarkTFG4/Mantenimiento | 53a0c7579d3432f76cb406e0887eec367cf62929 | daacd7090d8b3e78f655b9a2907d9fe708e6ee4f |
refs/heads/master | <file_sep>using Tida.Canvas.Contracts;
using Tida.Canvas.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tida.Canvas.Events {
///// <summary>
///// 通知绘制对象集合,鼠标移动的预处理事件参数;
///// </summary>
//public class DrawObjectsMouseMoveEventArgs : DrawObjectsInteractionEventArgs<MouseMoveEventArgs> {
// public DrawObjectsMouseMoveEventArgs(MouseMoveEventArgs eventArgs, IEnumerable<DrawObject> drawObjects) : base(eventArgs, drawObjects) {
// }
//}
}
<file_sep>using Tida.Canvas.Contracts;
using Tida.Canvas.Input;
using Tida.Geometry.Primitives;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tida.Canvas.Events {
///// <summary>
///// 通知绘制对象集合,鼠标被按下的预处理事件参数;
///// </summary>
//public class DrawObjectsMouseDownEventArgs : DrawObjectsInteractionEventArgs<MouseDownEventArgs> {
// public DrawObjectsMouseDownEventArgs(MouseDownEventArgs mouseDownEventArgs, IEnumerable<DrawObject> drawObjects):base(mouseDownEventArgs, drawObjects) {
// }
//}
}
| 798d91a8455e02e4d5a4ccb06ed420953d7dd549 | [
"C#"
] | 2 | C# | Smathon1/Tida.CAD | 930a4df7e1fdaab776a5d79537bf10dbd9eb4004 | b97832331978a539984a7287aee941bec0facbb8 |
refs/heads/master | <repo_name>cubernice/complex<file_sep>/src/org/ant/demo/FunctionDemo.java
package org.ant.demo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class FunctionDemo {
private static Log log = LogFactory.getLog(FunctionDemo.class);
public void saySomething(String words){
log.info("command is coming " + System.currentTimeMillis());
System.out.println(words);
}
}
<file_sep>/build.xml
<?xml version="1.0"?>
<project name="complex" default="compile" basedir="D:\build\ant\workspace\complex">
<property file="build.properties"/>
<path id="all.classpath">
<pathelement path="${outputdir}"/>
<fileset dir="${lib}">
<include name="**/*.jar"/>
</fileset>
</path>
<target name="init">
<mkdir dir="${outputdir}"/>
<mkdir dir="${packagedir}"/>
</target>
<target name="compile" depends="init">
<copydir src="${config}" dest="${outputdir}"/>
<javac srcdir="${src}:${srcMain}" destdir="${outputdir}">
<classpath refid="all.classpath"/>
</javac>
</target>
<target name="package" depends="compile">
<mkdir dir="${packagedir}\lib"/>
<jar jarfile="${packagedir}\lib\${ant.project.name}-${version}.jar" basedir="${outputdir}"/>
</target>
<target name="clean">
<delete dir="outputdir"/>
<delete dir="packgedir"/>
</target>
<target name="run" depends="package">
<java classname="org.ant.demo.App" >
<classpath refid="all.classpath"/>
</java>
</target>
<target name="partCompile">
<javac srcdir="${destdir}" destdir="${outputdir}">
<classpath refid="all.classpath"/>
</javac>
</target>
</project><file_sep>/bin/log4j.properties
log4j.rootLogger=info,stdout,InfoAppender,ErrorAppender
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{MM-dd HH:mm:ss.SSS} %c %-5p - %m%n
log4j.appender.InfoAppender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.InfoAppender.File=dmz_info.log
log4j.appender.InfoAppender.Append = true
log4j.appender.InfoAppender.threshold = INFO
log4j.appender.InfoAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.InfoAppender.layout.ConversionPattern=%d{MM-dd HH:mm:ss.SSS} %c %-5p - %m%n
log4j.logger.ErrorAppender.access=ERROR
log4j.appender.ErrorAppender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.ErrorAppender.File=dmz_error.log
log4j.appender.ErrorAppender.Append = true
log4j.appender.ErrorAppender.threshold = ERROR
log4j.appender.ErrorAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.ErrorAppender.layout.ConversionPattern=%d{MM-dd HH:mm:ss.SSS} %c %-5p - %m%n
log4j.additivity.netty.dmz.HttpDmzServerHandler=false
log4j.logger.com.asiainfo.sh.out.exe.Sc2PlatHttpServlet=info,stdout,intflog
log4j.appender.intflog=org.apache.log4j.DailyRollingFileAppender
log4j.appender.intflog.File=dmz-intf.log
log4j.appender.intflog.Append=true
log4j.appender.intflog.threshold = INFO
log4j.appender.intflog.layout=org.apache.log4j.PatternLayout
log4j.appender.intflog.layout.ConversionPattern=%d{MM-dd HH:mm:ss.SSS} %c %-5p - %m%n
log4j.additivity.netty.dmz.Util4Trans=false
log4j.logger.com.asiainfo.sh.out.exe.Sc2PlatHttpServlet=info,stdout,intflog
log4j.appender.intflog=org.apache.log4j.DailyRollingFileAppender
log4j.appender.intflog.File=dmz-do.log
log4j.appender.intflog.Append=true
log4j.appender.intflog.threshold = INFO
log4j.appender.intflog.layout=org.apache.log4j.PatternLayout
log4j.appender.intflog.layout.ConversionPattern=%d{MM-dd HH:mm:ss.SSS} %c %-5p - %m%n
| 8f8828d62c522575f7411f22b110258e5fd358ef | [
"Java",
"Ant Build System",
"INI"
] | 3 | Java | cubernice/complex | 0bc9b70636b3103e0f136e0e6fa2587e8c737b88 | a49acc1d36e17768b93ccbec0259efb8d274f70d |
refs/heads/main | <file_sep># Open Targets: Platform-output-support overview
Platform Output Support (POS) is the third component in the back-end data and infrastructure generation pipeline.
POS is an automatic and unified place to perform a release of OT Platform to the public. The other two components are Platform Input Support (PIS) and the ETL.
POS will be responsible for:
* Infrastructure task
* Publishing datasets in different services
* Data validation
>**terraform**: Infrastructure deployment for the release. Span off an Elasticsearch Server and loads the data into it.
Eg. deployment_context.tfvars
```
config_release_name = "pos"
config_gcp_default_region = "europe-west1"
config_gcp_default_zone = "europe-west1-d"
config_project_id = "open-targets-eu-dev"
config_gs_etl = "open-targets-data-releases/21.04/output"
config_vm_elastic_search_vcpus = "4"
config_vm_elastic_search_mem = "20480"
config_vm_elastic_search_version = "7.9.0"
config_vm_elastic_search_boot_disk_size = 350
config_vm_pos_machine_type = "n1-standard-8"
config_vm_pos_boot_image = "debian-10"
```
Commands:
```
gcloud auth application-default login
terraform init
terraform plan -var-file="deployment_context.tfvars"
```
# Copyright
Copyright 2018-2021 Open Targets
<NAME> <br>
European Bioinformatics Institute - EMBL-EBI <br>
GSK <br>
Sanofi <br>
Wellcome Sanger Institute <br>
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.
https://github.com/opentargets/platform-output-support.git
<file_sep>#!/bin/bash
# Startup script for Elastic Search VM Instance
echo "---> [LAUNCH] POS support VM"
sudo apt update && sudo apt -y install python3-pip
sudo pip3 install elasticsearch-loader
echo "test cinzia"
echo $ELASTICSEARCH_URI
echo $$ELASTICSEARCH_URI
echo $strin
| b0b0b66e1f842e7c0bca360d452781d50239ef98 | [
"Markdown",
"Shell"
] | 2 | Markdown | mbdebian/platform-output-support | fbad63158a26994737ef6156cd99b217cc9dd554 | 75a80334914d22faf90d93ae26991113b68bce68 |
refs/heads/master | <file_sep>package fi.observis.jsweet.issue;
public class ImplementationA8 implements InterfaceA<ImplementationB8>{
public void methodA(ImplementationB8 implementationB) {
implementationB.method();
}
}
<file_sep>package fi.observis.jsweet.issue;
public class ImplementationA1 implements InterfaceA<ImplementationB1>{
public void methodA(ImplementationB1 implementationB) {
implementationB.method();
}
}
<file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>fi.observis.jsweet</groupId>
<artifactId>issue-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<profiles>
<profile>
<id>jsweet</id>
<build>
<resources>
<resource>
<directory>src/main/java/</directory>
</resource>
</resources>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.bsc.maven</groupId>
<artifactId>maven-processor-plugin</artifactId>
<version>3.3.1</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<fork>true</fork>
</configuration>
</plugin>
<plugin>
<groupId>org.jsweet</groupId>
<artifactId>jsweet-maven-plugin</artifactId>
<version>2.0.1-SNAPSHOT</version>
<configuration>
<experimentalDecorators>true</experimentalDecorators>
<tsOut>target/ts/</tsOut>
<outDir>target/js/</outDir>
<targetVersion>ES5</targetVersion>
<sourceMap>true</sourceMap>
<module>commonjs</module>
</configuration>
<executions>
<execution>
<id>generate-js</id>
<phase>generate-sources</phase>
<goals>
<goal>jsweet</goal>
</goals>
</execution>
<execution>
<id>clean</id>
<phase>clean</phase>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<dependencies>
<!-- jSweet -->
<dependency>
<groupId>org.jsweet</groupId>
<artifactId>jsweet-core</artifactId>
<version>6-SNAPSHOT</version>
</dependency>
</dependencies>
</project><file_sep>package fi.observis.jsweet.issue;
public class ImplementationA4 implements InterfaceA<ImplementationB4>{
public void methodA(ImplementationB4 implementationB) {
implementationB.method();
}
}
<file_sep>package fi.observis.jsweet.issue;
public class ImplementationA3 implements InterfaceA<ImplementationB3>{
public void methodA(ImplementationB3 implementationB) {
implementationB.method();
}
}
<file_sep>package fi.observis.jsweet.issue;
import jsweet.lang.Interface;
@Interface
public interface InterfaceB {
public void method();
}
<file_sep>package fi.observis.jsweet.issue;
public class ImplementationA7 implements InterfaceA<ImplementationB7>{
public void methodA(ImplementationB7 implementationB) {
implementationB.method();
}
}
<file_sep>package fi.observis.jsweet.issue;
public class ImplementationA15 implements InterfaceA<ImplementationB15>{
public void methodA(ImplementationB15 implementationB) {
implementationB.method();
}
}
<file_sep>package fi.observis.jsweet.issue;
public class ImplementationA6 implements InterfaceA<ImplementationB6>{
public void methodA(ImplementationB6 implementationB) {
implementationB.method();
}
}
| d4ed4cf09ac392d689bfc3b381131286de0f5184 | [
"Java",
"Maven POM"
] | 9 | Java | Smiche/jsweet-issue-example | b0ccd1a167ce81a440cbf780302209fe44b86cdc | fba1b5ef30469fae3a7b46bbda687f1d5b564fb1 |
refs/heads/master | <file_sep>package com.figengungor.bakingapp_udacity.data;
import com.figengungor.bakingapp_udacity.data.model.Recipe;
import com.figengungor.bakingapp_udacity.data.remote.BakingService;
import com.figengungor.bakingapp_udacity.data.remote.BakingServiceFactory;
import java.util.List;
import retrofit2.Callback;
/**
* Created by figengungor on 4/17/2018.
*/
public class DataManager {
private static DataManager instance;
private BakingService bakingService;
private DataManager() {
this.bakingService = BakingServiceFactory.createService();
}
public static DataManager getInstance() {
if (instance == null) instance = new DataManager();
return instance;
}
public void getRecipes(Callback<List<Recipe>> callback) {
bakingService.getRecipes().enqueue(callback);
}
}
<file_sep>## Baking App (Bake Me)

Fourth project(P3) for Android Nanodegree by Udacity.
#### What Will I Learn?
In this project I will:
* Use MediaPlayer/Exoplayer to display videos.
* Handle error cases in Android.
* Add a widget to your app experience.
* Leverage a third-party library in your app.
* Use Fragments to create a responsive design that works on phones and tablets.
#### App Description
Your task is to create a Android Baking App that will allow Udacity’s resident baker-in-chief, Miriam, to share her recipes with the world. You will create an app that will allow a user to select a recipe and see video-guided steps for how to complete it.
The JSON file contains the recipes' instructions, ingredients, videos and images you will need to complete this project. Don’t assume that all steps of the recipe have a video. Some may have a video, an image, or no visual media at all.
One of the skills you will demonstrate in this project is how to handle unexpected input in your data -- professional developers often cannot expect polished JSON data when building an app.
### Screenshots
Phone (Nexus 5X)

Tablet (Nexus 7)

Tablet (Nexus 10 & Widget on Phone)

### Credits
#### Libraries
[Retrofit](https://github.com/square/retrofit)
[Picasso](https://github.com/square/picasso)
[ViewModel and LiveData](https://developer.android.com/topic/libraries/architecture/adding-components.html)
[Materialish Progress](https://github.com/pnikosis/materialish-progress)
[Butterknife](https://github.com/JakeWharton/butterknife)
[Parceler](https://github.com/johncarl81/parceler)
[ExoPlayer](https://github.com/google/ExoPlayer)
[Espresso](https://developer.android.com/training/testing/espresso/)
[Stetho](https://github.com/facebook/stetho)
[SimpleTagImageView](https://github.com/wujingchao/SimpleTagImageView)
#### Icons
App Icon made by [Freepik](https://www.flaticon.com/authors/mynamepong) from www.flaticon.com
## License
Copyright 2018 <NAME>
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.<file_sep>package com.figengungor.bakingapp_udacity.ui.recipeDetail;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.figengungor.bakingapp_udacity.R;
import com.figengungor.bakingapp_udacity.data.model.Ingredient;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by figengungor on 4/18/2018.
*/
public class IngredientAdapter extends RecyclerView.Adapter<IngredientAdapter.IngredientViewHolder> {
List<Ingredient> ingredients;
public IngredientAdapter(List<Ingredient> ingredients) {
this.ingredients = ingredients;
}
@NonNull
@Override
public IngredientViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new IngredientViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_ingredient, parent, false));
}
@Override
public void onBindViewHolder(@NonNull IngredientViewHolder holder, int position) {
holder.bindItem(ingredients.get(position));
}
@Override
public int getItemCount() {
if (ingredients != null) return ingredients.size();
return 0;
}
class IngredientViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.ingredientInfoTv)
TextView ingredientInfoTv;
public IngredientViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
public void bindItem(Ingredient ingredient) {
ingredientInfoTv.setText(itemView.getContext().getString(R.string.ingredient,
String.valueOf(ingredient.getQuantity()), ingredient.getMeasure(), ingredient.getIngredient()));
}
}
}
<file_sep>package com.figengungor.bakingapp_udacity.data.remote;
import com.figengungor.bakingapp_udacity.data.model.Recipe;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
/**
* Created by figengungor on 4/17/2018.
*/
public interface BakingService {
@GET("/topher/2017/May/59121517_baking/baking.json")
Call<List<Recipe>> getRecipes();
}
<file_sep>package com.figengungor.bakingapp_udacity.ui.recipeDetail;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.figengungor.bakingapp_udacity.R;
import com.figengungor.bakingapp_udacity.data.model.Step;
import org.parceler.Parcels;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by figengungor on 4/19/2018.
*/
public class StepsFragment extends Fragment implements StepAdapter.ItemListener {
@BindView(R.id.stepsRv)
RecyclerView stepsRv;
private static final String ARG_STEPS = "steps";
private static final String KEY_SELECTED_STEP_INDEX = "selected_step_index";
List<Step> steps;
OnInteractionListener callback;
StepAdapter adapter;
int selectedStepIndex = 0;
interface OnInteractionListener {
void onStepClicked(int stepIndex);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
steps = Parcels.unwrap(getArguments().getParcelable(ARG_STEPS));
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_steps, container, false);
ButterKnife.bind(this, view);
adapter = new StepAdapter(steps, this);
stepsRv.setAdapter(adapter);
stepsRv.setNestedScrollingEnabled(false);
if (savedInstanceState != null) {
selectedStepIndex = savedInstanceState.getInt(KEY_SELECTED_STEP_INDEX);
adapter.setSelectedStep(selectedStepIndex);
}
return view;
}
public static StepsFragment newInstance(List<Step> steps) {
Bundle args = new Bundle();
args.putParcelable(ARG_STEPS, Parcels.wrap(steps));
StepsFragment fragment = new StepsFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
callback = (OnInteractionListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ "must implement OnInteractionListener");
}
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
outState.putInt(KEY_SELECTED_STEP_INDEX, selectedStepIndex);
}
@Override
public void onItemClick(int stepIndex) {
selectedStepIndex = stepIndex;
adapter.setSelectedStep(stepIndex);
callback.onStepClicked(stepIndex);
}
public void resetStep() {
adapter.setSelectedStep(-1);
selectedStepIndex = -1;
}
public void setSelectedStep(int selectedStepIndex) {
adapter.setSelectedStep(selectedStepIndex);
this.selectedStepIndex = selectedStepIndex;
}
}
<file_sep>package com.figengungor.bakingapp_udacity.ui.recipes;
import android.arch.lifecycle.ViewModelProvider;
import com.figengungor.bakingapp_udacity.data.DataManager;
/**
* Created by figengungor on 4/17/2018.
*/
public class RecipesViewModelFactory implements ViewModelProvider.Factory {
DataManager dataManager;
public RecipesViewModelFactory(DataManager dataManager) {
this.dataManager = dataManager;
}
@Override
public RecipesViewModel create(Class modelClass) {
return new RecipesViewModel(dataManager);
}
}
<file_sep>package com.figengungor.bakingapp_udacity;
import android.content.Context;
import android.content.Intent;
import android.support.test.InstrumentationRegistry;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.figengungor.bakingapp_udacity.data.model.Recipe;
import com.figengungor.bakingapp_udacity.data.model.Step;
import com.figengungor.bakingapp_udacity.ui.recipeDetail.RecipeDetailActivity;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.parceler.Parcels;
import java.util.ArrayList;
import static android.support.test.InstrumentationRegistry.getInstrumentation;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
/**
* Created by figengungor on 4/30/2018.
*/
@RunWith(AndroidJUnit4.class)
public class RecipeDetailActivityTest {
@Rule
public ActivityTestRule<RecipeDetailActivity> mActivityTestRule =
new ActivityTestRule<RecipeDetailActivity>(RecipeDetailActivity.class){
@Override
protected Intent getActivityIntent() {
Context targetContext = InstrumentationRegistry.getInstrumentation()
.getTargetContext();
Intent result = new Intent(targetContext, RecipeDetailActivity.class);
Recipe recipe = new Recipe();
recipe.setName("Nutella");
ArrayList<Step> steps = new ArrayList<>();
Step step = new Step();
step.setDescription("Description");
step.setShortDescription("Short Description");
step.setThumbnailURL("");
step.setVideoURL("");
steps.add(new Step());
recipe.setSteps(steps);
result.putExtra(RecipeDetailActivity.EXTRA_RECIPE, Parcels.wrap(recipe));
return result;
}
};
@Test
public void initialSetup_loadAllFragmentsAccordingToDeviceType() {
boolean isTablet = getInstrumentation().getTargetContext().getResources().getBoolean(R.bool.isTablet);
if (isTablet) {
onView(withId(R.id.ingredientsContainerFl)).check(matches(isDisplayed()));
onView(withId(R.id.stepsContainerFl)).check(matches(isDisplayed()));
onView(withId(R.id.stepDetailContainerFl)).check(matches(isDisplayed()));
} else {
onView(withId(R.id.ingredientsContainerFl)).check(matches(isDisplayed()));
onView(withId(R.id.stepsContainerFl)).check(matches(isDisplayed()));
}
}
}
<file_sep>package com.figengungor.bakingapp_udacity.ui.stepDetail;
import android.content.Context;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.figengungor.bakingapp_udacity.R;
import com.figengungor.bakingapp_udacity.data.model.Step;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.ui.SimpleExoPlayerView;
import com.google.android.exoplayer2.upstream.BandwidthMeter;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.upstream.TransferListener;
import com.google.android.exoplayer2.util.Util;
import com.squareup.picasso.Picasso;
import org.parceler.Parcels;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* Created by figengungor on 4/20/2018.
*/
//https://github.com/yusufcakmak/ExoPlayerSample
public class StepDetailFragment extends Fragment{
@BindView(R.id.playerView)
SimpleExoPlayerView playerView;
@BindView(R.id.descriptionTv)
TextView descriptionTv;
@BindView(R.id.descriptionContainerCv)
CardView descriptionContainerCv;
@BindView(R.id.previousStepBtn)
ImageButton previousStepBtn;
@BindView(R.id.nextStepBtn)
ImageButton nextStepBtn;
@BindView(R.id.stepNoTv)
TextView stepNoTv;
@BindView(R.id.thumbnailIv)
ImageView thumbnailIv;
@OnClick(R.id.previousStepBtn)
void onPreviousStepBtnClicked() {
callback.onPreviousStepClicked(stepIndex);
}
@OnClick(R.id.nextStepBtn)
void onNextStepBtnClicked() {
callback.onNextStepClicked(stepIndex);
}
private static final String TAG = StepDetailFragment.class.getSimpleName();
private static final String ARG_STEPS = "steps";
private static final String ARG_STEP_INDEX = "step_index";
List<Step> steps;
int stepIndex;
Step step;
private static final String RESUME_POSITION = "resume_position";
private static final String SHOULD_PLAY = "should_play";
private SimpleExoPlayer player;
private DataSource.Factory mediaDataSourceFactory;
private DefaultTrackSelector trackSelector;
private BandwidthMeter bandwidthMeter;
private OnInteractionListener callback;
private long resumePosition = C.TIME_UNSET;
private boolean shouldAutoPlay = true;
public interface OnInteractionListener {
void onPreviousStepClicked(int stepIndex);
void onNextStepClicked(int stepIndex);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
steps = Parcels.unwrap(getArguments().getParcelable(ARG_STEPS));
stepIndex = getArguments().getInt(ARG_STEP_INDEX);
step = steps.get(stepIndex);
if (!TextUtils.isEmpty(step.getVideoURL())) {
bandwidthMeter = new DefaultBandwidthMeter();
mediaDataSourceFactory = new DefaultDataSourceFactory(getContext(), Util.getUserAgent(getContext(), "BakeMe"), (TransferListener<? super DataSource>) bandwidthMeter);
}
if (savedInstanceState != null) {
resumePosition = savedInstanceState.getLong(RESUME_POSITION);
shouldAutoPlay = savedInstanceState.getBoolean(SHOULD_PLAY);
}
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_step_detail, container, false);
ButterKnife.bind(this, view);
setupUI();
return view;
}
private void setupUI() {
descriptionContainerCv.setCardBackgroundColor(Color.TRANSPARENT);
descriptionContainerCv.setCardElevation(0);
descriptionTv.setText(step.getDescription());
displayStepNavigationUI();
displayThumbnailIfNoVideo();
}
void displayStepNavigationUI() {
stepNoTv.setText(getString(R.string.stepNo, stepIndex));
int stepSize = steps.size();
if (stepIndex == stepSize - 1)
nextStepBtn.setVisibility(View.INVISIBLE);
else {
nextStepBtn.setVisibility(View.VISIBLE);
}
if (stepIndex == 0) {
previousStepBtn.setVisibility(View.INVISIBLE);
} else {
previousStepBtn.setVisibility(View.VISIBLE);
}
}
void displayThumbnailIfNoVideo() {
if (TextUtils.isEmpty(step.getVideoURL())) {
thumbnailIv.setVisibility(View.VISIBLE);
if (TextUtils.isEmpty(step.getThumbnailURL())) {
Picasso.with(getContext()).load(R.drawable.placeholder)
.into(thumbnailIv);
} else {
Picasso.with(getContext()).load(step.getThumbnailURL())
.error(R.drawable.placeholder)
.placeholder(R.drawable.placeholder)
.into(thumbnailIv);
}
} else {
thumbnailIv.setVisibility(View.GONE);
}
}
public static StepDetailFragment newInstance(List<Step> steps, int stepIndex) {
Bundle args = new Bundle();
args.putParcelable(ARG_STEPS, Parcels.wrap(steps));
args.putInt(ARG_STEP_INDEX, stepIndex);
StepDetailFragment fragment = new StepDetailFragment();
fragment.setArguments(args);
return fragment;
}
private void initializePlayer() {
playerView.requestFocus();
trackSelector = new DefaultTrackSelector();
player = ExoPlayerFactory.newSimpleInstance(getContext(), trackSelector);
playerView.setPlayer(player);
DefaultExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
MediaSource mediaSource = new ExtractorMediaSource(Uri.parse(step.getVideoURL()),
mediaDataSourceFactory, extractorsFactory, null, null);
player.prepare(mediaSource);
player.setPlayWhenReady(shouldAutoPlay);
if (resumePosition != C.TIME_UNSET) player.seekTo(resumePosition);
}
private void releasePlayer() {
if (player != null) {
Log.d(TAG, "releasePlayer: "+ resumePosition);
player.release();
player = null;
trackSelector = null;
}
}
/*Starting with API level 24 Android supports multiple windows. As our app can be visible but not
active in split window mode, we need to initialize the player in onStart. Before API level 24
we wait as long as possible until we grab resources, so we wait until onResume before
initializing the player.
https://codelabs.developers.google.com/codelabs/exoplayer-intro/#2
*/
@Override
public void onStart() {
super.onStart();
if (!TextUtils.isEmpty(step.getVideoURL())) {
if (Util.SDK_INT > 23) {
initializePlayer();
}
}
}
@Override
public void onResume() {
super.onResume();
if (!TextUtils.isEmpty(step.getVideoURL())) {
if ((Util.SDK_INT <= 23 || player == null)) {
initializePlayer();
}
}
}
@Override
public void onPause() {
super.onPause();
if (!TextUtils.isEmpty(step.getVideoURL())) {
shouldAutoPlay = player.getPlayWhenReady();
resumePosition = player.getCurrentPosition();
if (Util.SDK_INT <= 23) {
releasePlayer();
}
}
}
@Override
public void onStop() {
super.onStop();
if (!TextUtils.isEmpty(step.getVideoURL())) {
if (Util.SDK_INT > 23) {
releasePlayer();
}
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
callback = (OnInteractionListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ "must implement OnInteractionListener");
}
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
outState.putLong(RESUME_POSITION, resumePosition);
Log.d(TAG, "onSaveInstanceState: " + resumePosition);
outState.putBoolean(SHOULD_PLAY, shouldAutoPlay);
}
}
<file_sep>package com.figengungor.bakingapp_udacity;
import android.content.Context;
import android.content.Intent;
import android.support.test.InstrumentationRegistry;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.figengungor.bakingapp_udacity.data.model.Step;
import com.figengungor.bakingapp_udacity.ui.stepDetail.StepDetailActivity;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.parceler.Parcels;
import java.util.ArrayList;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static org.hamcrest.Matchers.not;
/**
* Created by figengungor on 5/1/2018.
*/
@RunWith(AndroidJUnit4.class)
public class StepDetailActivityTest {
@Rule
public ActivityTestRule<StepDetailActivity> mActivityTestRule =
new ActivityTestRule<StepDetailActivity>(StepDetailActivity.class){
@Override
protected Intent getActivityIntent() {
Context targetContext = InstrumentationRegistry.getInstrumentation()
.getTargetContext();
Intent result = new Intent(targetContext, StepDetailActivity.class);
ArrayList<Step> steps = new ArrayList<>();
Step step = new Step();
step.setDescription("Description");
step.setShortDescription("Short Description");
step.setThumbnailURL("");
step.setVideoURL("");
steps.add(new Step());
steps.add(new Step());
steps.add(new Step());
result.putExtra(StepDetailActivity.EXTRA_STEPS, Parcels.wrap(steps));
result.putExtra(StepDetailActivity.EXTRA_STEP_INDEX, 0);
result.putExtra(StepDetailActivity.EXTRA_RECIPE_NAME, "Nutella");
return result;
}
};
@Test
public void setupLayout_loadFragment(){
onView(withId(R.id.stepDetailContainerFl)).check(matches(isDisplayed()));
}
@Test
public void stepIndexZero_onlyNextBtnIsVisible(){
onView(withId(R.id.nextStepBtn)).check(matches(isDisplayed()));
onView(withId(R.id.previousStepBtn)).check(matches(not((isDisplayed()))));
}
@Test
public void clickNextBtnWhenIndexIsZero_nextAndPreviousButtonsAreVisible(){
onView(withId(R.id.nextStepBtn)).perform(click());
onView(withId(R.id.nextStepBtn)).check(matches(isDisplayed()));
onView(withId(R.id.previousStepBtn)).check(matches(isDisplayed()));
}
@Test
public void clickNextBtnUntilLastStep_onlyPreviousBtnIsVisible(){
onView(withId(R.id.nextStepBtn)).perform(click());
onView(withId(R.id.nextStepBtn)).perform(click());
onView(withId(R.id.nextStepBtn)).check(matches(not((isDisplayed()))));
onView(withId(R.id.previousStepBtn)).check(matches(isDisplayed()));
}
}
<file_sep>package com.figengungor.bakingapp_udacity.widget;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;
import com.figengungor.bakingapp_udacity.R;
import com.figengungor.bakingapp_udacity.data.model.Ingredient;
import com.figengungor.bakingapp_udacity.data.model.Recipe;
import java.util.ArrayList;
import java.util.List;
public class ListWidgetService extends RemoteViewsService {
@Override
public RemoteViewsFactory onGetViewFactory(Intent intent) {
return (new ListRemoteViewsFactory(this.getApplicationContext(), intent));
}
}
class ListRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {
private List<Ingredient> ingredients;
private Context context = null;
private int appWidgetId;
public ListRemoteViewsFactory(Context context, Intent intent) {
this.context = context;
appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
}
private void setIngredientsData() {
Recipe recipe = BakingWidgetProviderConfigureActivity.loadRecipePref(context, appWidgetId);
if (recipe != null) {
ingredients = recipe.getIngredients();
} else {
ingredients = new ArrayList<>();
}
}
@Override
public void onCreate() {
setIngredientsData();
}
@Override
public void onDataSetChanged() {
setIngredientsData();
}
@Override
public void onDestroy() {
}
@Override
public int getCount() {
if (ingredients.size() > 0) return ingredients.size();
return 0;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public RemoteViews getViewAt(int position) {
final RemoteViews remoteView = new RemoteViews(
context.getPackageName(), R.layout.item_ingredient_widget);
Ingredient ingredient = ingredients.get(position);
remoteView.setTextViewText(R.id.ingredientInfoTv, context.getString(R.string.ingredient,
String.valueOf(ingredient.getQuantity()), ingredient.getMeasure(), ingredient.getIngredient()));
return remoteView;
}
@Override
public RemoteViews getLoadingView() {
return null;
}
@Override
public int getViewTypeCount() {
return 1;
}
}<file_sep>apply plugin: 'com.android.application'
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.figengungor.bakingapp_udacity"
minSdkVersion 17
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
ext {
supportLibraryVersion = '27.1.1'
constraintLayoutVersion = '1.1.0'
picassoVersion = '2.5.2'
retrofitVersion = '2.3.0'
okHttp3Version = '3.9.1'
archComponentsVersion = '1.1.1'
materialishProgressVersion = '1.7'
butterknifeVersion = '8.8.1'
parcelerVersion = '1.1.9'
stethoVersion = '1.5.0'
exoplayerVersion = 'r2.5.2'
espressoVersion = '3.0.2'
simpleTagImageViewVersion = '1.0.1'
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
//Support Library
implementation "com.android.support:appcompat-v7:$supportLibraryVersion"
implementation "com.android.support:design:$supportLibraryVersion"
implementation "com.android.support:recyclerview-v7:$supportLibraryVersion"
implementation "com.android.support:cardview-v7:$supportLibraryVersion"
implementation "com.android.support.constraint:constraint-layout:$constraintLayoutVersion"
//Retrofit
implementation "com.squareup.retrofit2:retrofit:$retrofitVersion"
implementation "com.squareup.retrofit2:converter-gson:$retrofitVersion"
implementation "com.squareup.okhttp3:logging-interceptor:$okHttp3Version"
//Picasso
implementation "com.squareup.picasso:picasso:$picassoVersion"
//ViewModel and LiveData
implementation "android.arch.lifecycle:extensions:$archComponentsVersion"
//Materialish Progress
implementation "com.pnikosis:materialish-progress:$materialishProgressVersion"
//Butterknife
implementation "com.jakewharton:butterknife:$butterknifeVersion"
implementation 'com.android.support.constraint:constraint-layout:1.1.0'
annotationProcessor "com.jakewharton:butterknife-compiler:$butterknifeVersion"
//Parceler
implementation "org.parceler:parceler-api:$parcelerVersion"
annotationProcessor "org.parceler:parceler:$parcelerVersion"
//ExoPlayer
implementation "com.google.android.exoplayer:exoplayer:$exoplayerVersion"
//Espresso Idling Resource
implementation "com.android.support.test.espresso:espresso-idling-resource:$espressoVersion"
//Stetho
implementation "com.facebook.stetho:stetho:$stethoVersion"
//SimpleTagImageView
implementation "net.wujingchao.android.view:simple-tag-imageview:$simpleTagImageViewVersion"
//Test
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test:rules:1.0.2'
androidTestImplementation "com.android.support.test.espresso:espresso-core:$espressoVersion"
androidTestImplementation "com.android.support.test.espresso:espresso-contrib:$espressoVersion"
androidTestImplementation "com.android.support:support-annotations:$supportLibraryVersion"
androidTestImplementation "com.android.support.test.espresso:espresso-intents:$espressoVersion"
}
| 2b1ebffccd1e054381d701b1bbb4c5366d39c1f5 | [
"Markdown",
"Java",
"Gradle"
] | 11 | Java | figengungor/bakingApp_Udacity | 3298d4cf45f616adf61fb38f9b8e0fdc9f43633f | 88780e8fab62cb5652b3797fac4ca4291eb1e27a |
refs/heads/master | <repo_name>onereallylongname/Space_Invaders<file_sep>/README.md
# Space_Invaders
My take on space invaders using p5.
<file_sep>/lib/sounds.js
function Sounds() {
this.sounds = {};
this.addSound = function(env, osc, soundName, freq, attackLevel, attackTime, susPercent, decayTime, releaseTime) {
var releaseLevel = 0;
this.sounds[soundName] = {
'env': env,
'osc': osc,
'freq': freq,
'other': [attackTime, decayTime, susPercent, releaseTime, attackLevel, releaseLevel]
};
}
this.play = function(soundName) {
if (soundOn) {
var ts = this.sounds[soundName];
ts.env.setADSR(ts.other[0], ts.other[1], ts.other[2], ts.other[3]);
ts.env.setRange(ts.other[4], ts.other[5]);
ts['osc'].amp(this.sounds[soundName]['env']);
ts['osc'].start();
ts['osc'].freq(this.sounds[soundName]['freq']);
ts['osc'].pan(map(ship.x, 0, width,-0.85, 0.85));
ts['env'].play();
}
}
}
<file_sep>/lib/invader.js
function Invader0(x, y) {
this.x = x;
this.y = y;
this.r = [8, 4, 4];
this.cx = [0, -10, 10];
this.cy = [0, 20, 20];
this.partsHP = [20, 6, 6];
this.partsDim = [[-8, -6, -3, -6, -3, -2, 3, -2, 3, -6, 8, -6, 8, 8, -8, 8], [-3, -3, 3, -3, 3, 3, -3, 3], [-3, -3, 3, -3, 3, 3, -3, 3]];
this.counter = 0;
this.damaged = 0;
this.damagedV = 0;
this.dl = 5;
this.fallV = 0;
this.env;
this.show = function () {
push();
for (var i = 0; i < this.r.length; i++) {
push();
beginShape();
translate(this.x + this.cx[i], this.y + this.cy[i]);
fill(0,(150*this.partsHP[i]/50)+50, 5500 * this.fallV);
for(var j = 0; j < this.partsDim[i].length; j += 2){
vertex(this.partsDim[i][j], this.partsDim[i][j+1]);
}
endShape(CLOSE);
pop();
}
if(this.damaged > 0){
this.damaged--;
textSize(10);
fill(250, 50, 50);
text(String(round(this.damagedV*100)/100), this.x + this.dl, this.y - this.damaged/8);
}
pop();
}
this.move = function (dirx, diry) {
var rrr = 0.2 * sin(0.05*this.counter) + this.fallV;
this.x = clamp(this.x + dirx + random(-50 * this.fallV, this.fallV*50), 0, width);
this.y += diry + rrr;
var ii = -1;
for (var i = 1; i < this.cx.length; i++) {
this.cx[i] -= rrr*0.7 * pow(ii,i);
}
if (this.y > height){
gameOver = true;
state = 'showGameOver';
}
}
this.removePart = function (id0, id1) {
if(this.partsHP[id1] < 0){
sound.play('Invader');
myPoints += this.r[id1]*10;
this.r.splice(id1, 1);
this.cx.splice(id1, 1);
this.cy.splice(id1, 1);
this.partsHP.splice(id1, 1);
this.partsDim.splice(id1, 1);
if(this.r.length == 0){
invaders.splice(id0, 1);
}
if(this.r.length == 1){
this.fallV = 0.01;
}
this.drop();
}
}
this.doDamage = function(dd, i, j) {
this.partsHP[j] -= dd;
this.removePart(i, j);
this.damaged = 50;
this.damagedV = dd;
this.dl = random(8);
}
this.update = function (dirx, diry) {
this.move(dirx, diry);
this.show();
this.counter++;
}
this.drop = function () {
console.log(rnum);
drops.push(new Drops(this.x, this.y));
}
}
<file_sep>/lib/shot.js
function Shot(x, y, momento, pirce, s = 8, pSkill = 1, pMult = 1) {
this. momento = momento;
this.moveSpeed = s;
this.pirce = pirce;
this.pirced = -1;
this.damage = ((this.moveSpeed/20 + abs(this.momento)/10) + pSkill + pirce/10) * pMult ;
this.r = ((this.damage*0.001 - 1)*(this.damage*0.001 - 1)) + 2 ;
this.x = x - this.r/2;
this.y = y - this.r/2;
this.show = function () {
fill(150, 50, 50);
rect(this.x, this.y , this.r, 1.5*this.r);
}
this.move = function () {
this.x += 0.5*this.momento;
this.y -= this.moveSpeed;
}
this.colide = function(id) {
if(this.y < 0){
this.removeShot(id, false);
}else {
for (var i = invaders.length-1; i >= 0; i--) {
for (var j = invaders[i].r.length-1; j >= 0; j--) {
if (dist(invaders[i].cx[j] + invaders[i].x, invaders[i].cy[j] + invaders[i].y, this.x, this.y) <= invaders[i].r[j] + this.r){
shotOnTarget +=1;
invaders[i].doDamage(this.damage, i, j);
if(this.pirced != i*j){
this.pirce -= 1;
this.damage -= this.pirce;
this.pirced = i*j;
}
if(this.pirce < 1 ){
this.removeShot(id, true);
}
}
}
}
}
}
this.update = function (id) {
this.move();
this.show();
this.colide(id);
}
this.removeShot = function(id, onTarget){
shots.splice(id,1);
if(onTarget){
shotOnTarget +=1;
myPoints += 10;
}else{
myPoints -= 5;
shotOffTarget += 1;
}
}
}
<file_sep>/lib/ship.js
function Ship() {
this.x = width/2;
this.vel = 0;
this.acc = 0.15;
this.friction = 0.05;
this.y = height - 15;
this.cooldown = 10;
this.cooldownCount = 0;
this.hp = 100;
this.lazer = false;
this.pirce = 0;
this.pMult = 1.05;
this.pSkill = 1;
this.extrass = 3;
this.luck = 0;
this.r = 8;
this.show = function () {
var rrr = random(1);
if(this.lazer){
push();
stroke(190, 45, 20, 160);
line(this.x , this.y , this.x + (rrr*5 - 2.5) + this.vel / (2*this.friction) , 0);
pop();
}
fill(50, 50, 240);
rect(this.x - 3, this.y - rrr - 4 , 6, 14);
rect(this.x - 9, this.y - rrr , 18, 10);
}
this.move = function () {
this.x = mod(this.x + this.vel, width);
}
this.update = function () {
var ld = keyIsDown(LEFT_ARROW);
var rd = keyIsDown(RIGHT_ARROW);
var plusVel = 0;
//if(!rd && !ld){
// }
if (rd) {
plusVel = this.acc;//clamp(this.vel + this.acc, 0, 3);
}
if(ld) {
plusVel = -1 * this.acc;// clamp(this.vel - this.acc, -3, 0);
}
this.vel += clamp(-1 * this.vel * this.friction + plusVel, -2, 2);
if(keyIsDown(32)) {
if(this.cooldownCount >= this.cooldown){
shots.push(new Shot(this.x, this.y, this.vel, this.pirce, this.extrass, this.pSkill, this.pMult));
sound.play('Shot0');
sound.play('Shot');
this.cooldownCount = 0;
}
}
if(this.cooldownCount < this.cooldown){
this.cooldownCount++;
}
shotAcuracy = shotOnTarget/(shotOnTarget+shotOffTarget);
this.calcLuck();
this.calcPSkill();
this.move();
this.show();
}
this.addPUP = function (type, val) {
console.log(type,val);
}
this.calcLuck = function(){
this.luck = 4 * shotAcuracy * shotAcuracy - 4 * shotAcuracy + 1;
}
this.calcPSkill = function(){
this.pSkill = shotAcuracy * shotAcuracy * 2.5 + 1;
}
this.cahngeFriction = function(val){
this.friction = clamp(this.friction + val,0.01, 0.1);
}
this.cahngeCooldown = function(val){
this.cooldown = clamp(this.cooldown + val, 2, 15);
}
this.cahngeHP = function(val){
this.hp = clamp(this.hp + val, -1, 500);
}
this.cahngePirce = function(val){
this.pirce = clamp(this.pirce + val, 0, 6);
}
this.cahngePMult = function(val){
this.pMult = clamp(this.pMult + val, 0.5, 2);
}
this.cahngeExtrass = function(val){
this.extrass = clamp(this.extrass + val, 3, 10);
}
}
| 8d6776ee604fe85fafd086740bf9db8ae7e88c26 | [
"Markdown",
"JavaScript"
] | 5 | Markdown | onereallylongname/Space_Invaders | 67dfae64d2c422d713063b3b0de60c220c9aaaa8 | 784c9a84e2b5dea9ba5c5aee8191ffd1bb86884d |
refs/heads/master | <repo_name>tfursten/IBD-2N<file_sep>/src/Main2.cpp
#include "Main.h"
int main(int ac, char** av)
{
namespace po = boost::program_options;
using namespace std;
static int nGenerations, nMaxX, nMaxY, nOffspring;
unsigned int seed;
static float fSigma, param;
string dist_name, bound, infile, outfileName;
bool f;
ostringstream out;
try
{
po::options_description generic("General Options");
generic.add_options()
("help", "Produce help message")
;
po::options_description config("Configuration");
config.add_options()
("maxX,x", po::value<int>(&nMaxX)->default_value(100),"Set X dimension")
("maxY,y", po::value<int>(&nMaxY)->default_value(100),"Set Y dimension")
("generations,g", po::value<int>(&nGenerations)->default_value(10), "Set number of Generations to run after burn-in")
("offspring,o", po::value<int>(&nOffspring)->default_value(10), "Set number of offspring per individual")
("distribution,d", po::value<string>(&dist_name)->default_value("triangular"), "Set Dispersal Distribution")
("sigma,s", po::value<float>(&fSigma)->default_value(2.0), "Set dispersal parameter")
("output_file,f", po::value<string>(&outfileName)->default_value(string("data")),"Output File Name")
("seed", po::value<unsigned int>(&seed)->default_value(0), "Set PRNG seed, 0 to create random seed")
("landscape", po::value<string>(&bound)->default_value(string("torus")),"Set boundary conditions: torus or rectangular")
("sparam", po::value<float>(¶m)->default_value(0),"Extra Parameter for dispersal")
("fast", po::value<bool>(&f)->default_value(true),"Use fast dispersal when available")
;
po::options_description hidden("Hidden Options");
hidden.add_options()
("input-file", po::value<string>(&infile), "input file")
;
po::options_description cmdline_options;
cmdline_options.add(generic).add(config).add(hidden);
po::options_description config_file_options;
config_file_options.add(config);
po::options_description visible("Allowed Options");
visible.add(generic).add(config);
po::positional_options_description p;
p.add("input-file", 1);
po::variables_map vm;
po::store(po::command_line_parser(ac,av).options(cmdline_options).positional(p).run(), vm);
po::notify(vm);
if (vm.count("help"))
{
cout << visible << "\n";
return 0;
}
if (!infile.empty())
{
ifstream ifs(infile.c_str());
if (!ifs)
{
cout << "can not open config file: "<< infile << "\n";
return 0;
}
else
{
po::store(parse_config_file(ifs, config_file_options), vm);
po::notify(vm);
}
}
out << "X dimension set to " << nMaxX << ".\n"
<< "Y dimension set to " << nMaxX << ".\n"
<< "Run for " << nGenerations << " generations.\n"
<< "Collect population every " << nPopSample << " Generation(s).\n"
<< "Number of Offspring set to " << nOffspring << ".\n"
<< "Dispersal parameter set to " << fSigma << ".\n"
<< "Landscape set to " << bound << ".\n"
}
catch(exception& e)
{
cout<< e.what() << "\n";
return 1;
}
nMaxY = nMaxX; //override maxY, landscape needs to be square at the moment
string param_file = outfileName+"_settings.txt";
cout << "Parameters saved to: " << param_file << endl;
ofstream pout;
pout.open(param_file);
pout << out.str();
cout << out.str();
//Initialize Population
clock_t start = clock();
Population pop(pout);
pop.initialize(nMaxX,nMaxY,nOffspring,fSigma,seed,\
dist_name, bound, param, f);
//Run Simulation
pop.evolve(nBurnIn, nGenerations);
clock_t end = clock();
float seconds = (float)(end-start)/ CLOCKS_PER_SEC;
cout << "TIME: " << seconds << endl;
pout << "TIME: " << seconds << endl;
pout.close();
return 0;
}
<file_sep>/src/Main.cpp
#include "Main.h"
int main(int ac, char** av)
{
namespace po = boost::program_options;
using namespace std;
static int nGenerations, nMaxX, nMaxY, nOffspring, nBurnIn, nSample, ndClass, nPairs, nMarkers, nAlleles;
unsigned int seed;
//static double dMut;
static vector<double> vdMut;
static double dSigma;
static float param;
bool f;
string dist_name, infile, outfileName, mut_type;
bool verbose;
ostringstream out;
try
{
po::options_description generic("General Options");
generic.add_options()
("help", "Produce help message")
;
po::options_description config("Configuration");
config.add_options()
("maxX,x", po::value<int>(&nMaxX)->default_value(100),"Set X dimension")
("maxY,y", po::value<int>(&nMaxY)->default_value(100),"Set Y dimension")
("generations,g", po::value<int>(&nGenerations)->default_value(10), "Set number of Generations to run after burn-in")
("offspring,o", po::value<int>(&nOffspring)->default_value(10), "Set number of offspring per individual")
("markers,m", po::value<int>(&nMarkers)->default_value(1), "Set number of markers")
("mut", po::value<vector<double>>(&vdMut)->multitoken()->default_value(vector<double>(1,0.0001),"0.0001"), "Set mutation rates")
("distribution,d", po::value<string>(&dist_name)->default_value("triangular"), "Set Dispersal Distribution")
("sigma,s", po::value<double>(&dSigma)->default_value(2.0), "Set dispersal parameter")
("burn,b", po::value<int>(&nBurnIn)->default_value(0),"Set Burn-in Period")
("sample,t", po::value<int>(&nSample)->default_value(1),"Sample every n generations after burn-in")
("output_file,f", po::value<string>(&outfileName)->default_value(string("data")),"Output File Name")
("seed", po::value<unsigned int>(&seed)->default_value(0), "Set PRNG seed, 0 to create random seed")
("verbose", po::value<bool>(&verbose)->default_value(false),"Print data to screen")
("sparam", po::value<float>(¶m)->default_value(0),"Extra Parameter for dispersal")
("fast", po::value<bool>(&f)->default_value(true),"Use fast dispersal when available")
("ndistClass", po::value<int>(&ndClass)->default_value(20),"Number of distance classes for Nb estimate")
("nPairs", po::value<int>(&nPairs)->default_value(20),"Number of pairs for Nb estimate")
("mut-type", po::value<string>(&mut_type)->default_value(string("IAM")),"Mutation Model (IAM, KAM or SMM)")
("nAllele", po::value<int>(&nAlleles)->default_value(20),"Number of alleles under SMM and KAM")
;
po::options_description hidden("Hidden Options");
hidden.add_options()
("input-file", po::value<string>(&infile), "input file")
;
po::options_description cmdline_options;
cmdline_options.add(generic).add(config).add(hidden);
po::options_description config_file_options;
config_file_options.add(config);
po::options_description visible("Allowed Options");
visible.add(generic).add(config);
po::positional_options_description p;
p.add("input-file", 1);
po::variables_map vm;
po::store(po::command_line_parser(ac,av).options(cmdline_options).positional(p).run(), vm);
po::notify(vm);
if (vm.count("help"))
{
cout << visible << "\n";
return 0;
}
if (!infile.empty())
{
ifstream ifs(infile.c_str());
if (!ifs)
{
cout << "can not open config file: "<< infile << "\n";
return 0;
}
else
{
po::store(parse_config_file(ifs, config_file_options), vm);
po::notify(vm);
}
}
if((int)(vdMut.size())!=nMarkers){
if(int(vdMut.size()) == 1){
vdMut.resize(nMarkers);
fill(vdMut.begin(),vdMut.end(),vdMut[0]);
}
else{
throw;
}
if(2*nPairs*ndClass > nMaxX*nMaxY){
cout << "Sample size is larger than population size" << endl;
throw;
}
if(mut_type != "IAM" && mut_type != "SMM" && mut_type != "KAM"){
cout << "Not a valid mutation model" << endl;
throw;
}
}
out << "X dimension set to " << nMaxX << ".\n"
<< "Y dimension set to " << nMaxX << ".\n"
<< "Run for " << nGenerations << " generations.\n"
<< "Burn " << nBurnIn << " generation(s).\n"
<< "Collect data every " << nSample << " Generation(s).\n"
<< "Number of Offspring set to " << nOffspring << ".\n"
<< "Number of markers set to " << nMarkers << ".\n"
<< "Dispersal parameter set to " << dSigma << ".\n"
<< "Number of distances classes for Nb estimate set to " << ndClass << ".\n"
<< "Number of pairs collected for Nb estimate set to " << nPairs << ".\n"
<< "Mutation model set to " << mut_type << ".\n";
if(mut_type == "SMM" || mut_type == "KAM")
out << "Number of alleles set to " << nAlleles << ".\n";
out << "Mutation rate(s) set to ";
for(auto i=vdMut.begin();i!=vdMut.end();++i){
out << *i << " ";
}
out<<".\n";
}
catch(exception& e)
{
cout<< e.what() << "\n";
return 1;
}
nMaxY = nMaxX; //override maxY, landscape needs to be square at the moment
string param_file = outfileName+"_settings.txt";
string nb_data = outfileName+"_nb.txt";
cout << "Parameters saved to: " << param_file << endl;
cout << "Nb size estimation data saved to: " << nb_data << endl;
ofstream pout;
ofstream nbout;
pout.open(param_file);
nbout.open(nb_data);
pout << out.str();
cout << out.str();
//Initialize Population
clock_t start = clock();
Population pop(pout, nbout, verbose);
pop.initialize(nMaxX,nMaxY,nOffspring,nMarkers,dSigma,vdMut,seed, nSample,\
dist_name, param, f, ndClass, nPairs, mut_type, nAlleles);
//Run Simulation
pop.evolve(nBurnIn, nGenerations);
clock_t end = clock();
float seconds = (float)(end-start)/ CLOCKS_PER_SEC;
cout << "TIME: " << seconds << endl;
pout << "TIME: " << seconds << endl;
pout.close();
nbout.close();
return 0;
}
<file_sep>/src/Pop.cpp
#include "Pop.h"
//urandom dev/urandom if it exists use it else use create random seed
using namespace std;
// random seed generator
inline unsigned int create_random_seed() {
unsigned int v;
//ifstream urandom("/dev/urandom", ios::in|ios::binary);
//if(urandom.good()) {
//urandom >> v;
//} else {
v = static_cast<unsigned int>(getpid());
v += ((v << 15) + (v >> 3)) + 0x6ba658b3; // Spread 5-decimal PID over 32-bit number
v^=(v<<17);
v^=(v>>13);
v^=(v<<5);
v += static_cast<unsigned int>(time(NULL));
v^=(v<<17);
v^=(v>>13);
v^=(v<<5);
//}
return (v == 0) ? 0x6a27d958 : (v & 0x7FFFFFFF); // return at most a 31-bit seed
}
inline xyCoord i2xy(int i, int mx, int my)
{
assert(0 <= i && i < mx*my);
return make_pair((i/my),(i%my));
}
inline int xy2i(int x, int y, int mx, int my) {
assert(0 <= x && x < mx);
assert(0 <= y && y < my);
return x*my+y;
}
inline int xy2i(xyCoord xy, int mx, int my) {
return xy2i(xy.first,xy.second,mx,my);
}
void Population::initialize(int nMaxX, int nMaxY, int nOffspring, int nMarkers, double dSigma, vector<double> vdMut,
unsigned int seed, int nSample,
string dist_name, float param, bool fast, int nclass, int npairs,
string mut_type, int nAlleles)
{
ostringstream out;
//set Random seed
if (seed)
out << "User set PRNG seed to: " << seed << ".\n";
else {
seed = create_random_seed();
out << "Using Generated PRNG Seed: "<< seed << endl;
}
m_myrand.seed(seed);
m_nMaxX = nMaxX;
m_nMaxY = nMaxY;
m_nOffspring = nOffspring;
m_nDistClass = nclass;
m_nPairs = npairs;
if(mut_type == "IAM")
mutate = &Population::mutate_iam;
else if(mut_type == "SMM")
mutate = &Population::mutate_smm;
else if(mut_type == "KAM")
mutate = &Population::mutate_kam;
m_nAlleles = nAlleles;
m_vdMut = vdMut;
m_dTotMut = 1.0;
for(vector<double>::iterator it = m_vdMut.begin();it!=m_vdMut.end();++it){
m_dTotMut *= (1-*it);
}
m_dTotMut = -log(m_dTotMut);
for(vector<double>::iterator it = m_vdMut.begin();it!=m_vdMut.end();++it){
*it = *it/m_dTotMut;
}
alias_mut.create(m_vdMut.begin(),m_vdMut.end());
m_nIndividuals = nMaxX * nMaxY;
m_nTotGametes = m_nIndividuals * m_nOffspring;
m_nAlleleID = 0;
m_nMarkers = nMarkers;
m_nMutCount = setMutCount();
m_nSample = nSample;
m_dSigma = dSigma;
disp.initialize(dist_name, m_nMaxX, m_nMaxY, fast, "torus", dSigma, param);
out << "Dispersal distribution set to " << disp.getName() << ".\n" ;
out << "Extra parameter set to " << param << ".\n";
if(mut_type == "IAM"){
// Initialize Population: each individual has unique allele
for(int iii=0; iii<m_nIndividuals; iii++) {
gam h1;
gam h2;
gam h3 (m_nMarkers,0);
for(int jjj=0; jjj<m_nMarkers; jjj++){
h1.push_back(m_nAlleleID++);
h2.push_back(m_nAlleleID++);
}
xyCoord xy = i2xy(iii, m_nMaxX, m_nMaxY);
m_vPop1.emplace_back(xy,1,h1,h2,iii,iii);
m_vPop2.emplace_back(xy,0,h3,h3,0,0);
}
}
else{
for(int iii=0; iii<m_nIndividuals; iii++) {
gam h1;
gam h2;
gam h3 (m_nMarkers,0);
for(int jjj=0; jjj<m_nMarkers; jjj++){
h1.push_back(m_myrand.get_uint(m_nAlleles));
h2.push_back(m_myrand.get_uint(m_nAlleles));
}
xyCoord xy = i2xy(iii, m_nMaxX, m_nMaxY);
m_vPop1.emplace_back(xy,1,h1,h2,iii,iii);
m_vPop2.emplace_back(xy,0,h3,h3,0,0);
}
}
//write settings to screen and file
cout << out.str();
pout << out.str();
//Sampling scheme index list
for(int xxx=0; xxx<30; xxx++){
for(int yyy=0; yyy<30; yyy++){
m_vSample.push_back(xy2i(xxx, yyy, m_nMaxX, m_nMaxY));
}
}
}
int Population::setMutCount() {
return floor(rand_exp(m_myrand, m_dTotMut));
}
//Each mutational event creates a new allele unlike any other allele currently in the population
//so that identity in state for two or more alleles is always an indication of identity by descent.
void Population::mutate_iam(gam & gamete)
{
gamete[alias_mut(m_myrand.get_uint64())] = m_nAlleleID ++;
}
void Population::mutate_smm(gam & gamete)
{
uint64_t n = m_myrand.get_uint64();
int pos = alias_mut(n);
if((n>>32) %2)
gamete[pos] = (gamete[pos]==m_nAlleles-1 ? gamete[pos]-1 : gamete[pos]+1);
else
gamete[pos] = (gamete[pos]==0 ? 1 : gamete[pos]-1);
}
void Population::mutate_kam(gam & gamete)
{
gamete[alias_mut(m_myrand.get_uint64())] = m_myrand.get_uint(m_nAlleles);
}
void Population::evolve(int m_nBurnIn, int m_nGenerations)
{
//run burn-in period
for(int ggg=0;ggg<m_nBurnIn;++ggg)
{
for(int parent=0; parent<m_nIndividuals;parent++)
{
disperse_step(parent);
}
mutation_step();
for(int offspring=0; offspring<m_nIndividuals; offspring++)
{
reproduction_step(offspring);
}
swap(m_vPop1,m_vPop2);
}
//outfile headers
nbout << "Gen\tX\tY\t";
for(int m=1; m <= m_nMarkers; m++){
nbout << "M" << m << (m==m_nMarkers ? "\n" : "\t");
}
for(int ggg=0;ggg<m_nGenerations;++ggg)
{
for(int parent=0; parent<m_nIndividuals;parent++)
{
disperse_step(parent);
}
mutation_step();
for(int offspring=0; offspring<m_nIndividuals;offspring++)
{
reproduction_step(offspring);
}
if (ggg % m_nSample == 0)
sampleNb(ggg);
//}
//if (ggg % m_nPopSample == 0)
// samplePop();
swap(m_vPop1,m_vPop2);
}
//sampleDist();
}
void Population::disperse_step(int parent)
{
individual &parentHere = m_vPop1[parent];
//check if there is a parent here
if(parentHere.nWeight_1 == 0 || parentHere.nWeight_2 == 0){
parentHere.nWeight_1 = 0;
parentHere.nWeight_2 = 0;
parentHere.parent_count.clear();
parentHere.raw_count = 0;
parentHere.last_parent = -1;
return;
}
//clear out weight/counts for next generation
parentHere.nWeight_1 = 0;
parentHere.nWeight_2 = 0;
parentHere.parent_count.clear();
parentHere.last_parent = -1;
parentHere.raw_count = 0;
for (int off=0; off<m_nOffspring; off++)
{
//disperse
int nNewCell = disp(m_myrand,parentHere.xy.first, parentHere.xy.second);
//cout << "NEW CELL: " << nNewCell << endl;
//for absorbing boundary: check if individual dispersed off the grid
if (nNewCell == -1)
{
//mutate(parentHere.nAllele);
continue;
}
individual &parentThere = m_vPop2[nNewCell];
unsigned int nSeedWeight = m_myrand.get_uint32();
//cout << "Seed Weight Outter" << nSeedWeight << endl;
//Count how many unique parents are competing for cell
if(parent > parentThere.last_parent){
parentThere.raw_count ++;
parentThere.last_parent = parent;
parentThere.parent_count.push_back(1);
}
else{
parentThere.parent_count.back()++;
}
//competition for cell
unsigned int min_weight = min(parentThere.nWeight_1, parentThere.nWeight_2);
//cout << parentThere.nWeight_1 << " " << parentThere.nWeight_2 << endl;
bool replace1 = (parentThere.nWeight_1 <= parentThere.nWeight_2 ? 0 : 1);
if(nSeedWeight > min_weight)
{
// cout << "MIN WEIGHT: " << min_weight << endl;
// cout << "SEED WEIGHT: " << nSeedWeight << endl;
// cout << "IN" << replace << endl;
if(replace1){
// cout << "R2" << endl;
parentThere.nWeight_2 = nSeedWeight;
parentThere.nParent_2 = parent;
parentThere.ngameteID_2 = parent*m_nOffspring + off;
}
else{
// cout << "R1" << endl;
parentThere.nWeight_1 = nSeedWeight;
parentThere.nParent_1 = parent;
parentThere.ngameteID_1 = parent*m_nOffspring + off;
// cout << parentThere.nWeight_1 << endl;
}
}
}
}
void Population::mutation_step(){
//Make a map of gamete ID's that need a mutation
//it is possible to draw the same gamete twice
m_mMutations.clear();
if(m_nMutCount >= m_nTotGametes){
m_nMutCount -= m_nTotGametes;
return;
}
int count = m_nMutCount;
int n=0;
while(count<m_nTotGametes){
n = m_nTotGametes - count;
std::map<int,int>::iterator it;
it = m_mMutations.find(count);
if (it !=m_mMutations.end())
it->second += 1;
else
m_mMutations[count] = 1;
//m_vMutation.push_back(count);
count+= setMutCount();
}
m_nMutCount = count - n;
}
gam Population::make_gamete(gam &parent1, gam &parent2){
vector< gam > genotype;
gam newGamete;
genotype.push_back(parent1);
genotype.push_back(parent2);
//use top 32 bits
uint64_t r = m_myrand.get_uint64() >> 32;
if(m_nMarkers < 32){
for(int m=0; m<m_nMarkers; m++){
newGamete.push_back(genotype[r&1][m]);
r >>= 1;
}
}
else{
for(int m=0; m<m_nMarkers; m++){
if(!m%32)
r = m_myrand.get_uint64() >> 32;
newGamete.push_back(genotype[r&1][m]);
r >>= 1;
}
}
return newGamete;
}
void Population::reproduction_step(int offspring)
{
individual & offspringHere = m_vPop2[offspring];
//make sure 2 gametes landed in cell
//cout << offspringHere.nWeight_1 << " " << offspringHere.nWeight_2 << endl;
if(offspringHere.nWeight_1 == 0 || offspringHere.nWeight_2 == 0){
cout << "WARNING: INCOMPLETELY FILLED CELL" << endl;
return;
}
//generate a gamete from both parents
individual & parent1 = m_vPop1[offspringHere.nParent_1];
individual & parent2 = m_vPop1[offspringHere.nParent_2];
offspringHere.vgamete_1 = make_gamete(parent1.vgamete_1,parent1.vgamete_2);
offspringHere.vgamete_2 = make_gamete(parent2.vgamete_1,parent2.vgamete_2);
//check for mutation on both gametes
std::map<int,int>::iterator it;
it = m_mMutations.find(offspringHere.ngameteID_1);
if(it != m_mMutations.end()){
for(int iii=0; iii<it->second; iii++){
(this->*mutate)(offspringHere.vgamete_1);
}
}
it = m_mMutations.find(offspringHere.ngameteID_2);
if(it != m_mMutations.end()){
for(int iii=0; iii<it->second; iii++){
(this->*mutate)(offspringHere.vgamete_2);
}
}
}
double minEuclideanDist(xyCoord xy1, xyCoord xy2, int mx, int my){
double dx = abs(1.0*(xy1.first - xy2.first));
double dy = abs(1.0*(xy1.second - xy2.second));
dx = (dx < mx*0.5) ? dx : mx-dx;
dy = (dy < my*0.5) ? dy : my-dy;
return (dx*dx+dy*dy);
}
float Population::nbSize(vector<int> & counts){
assert(!counts.empty);
int tot = 0;
int psum = 0;
for(std::vector<int>::iterator it = counts.begin(); it != counts.end(); ++it){
tot += *it;
psum += *it * *it;
}
return 1/(psum/(float)(tot*tot));
}
void Population::sampleNb(int gen){
vector<map<int,int>> alleles (m_nMarkers);
vector<int> vN(m_nDistClass,0);
for(vector<int>::iterator it = m_vSample.begin(); it != m_vSample.end(); ++it){
individual ind1 = m_vPop2[*it];
if(ind1.nWeight_1==0 || ind1.nWeight_2==0)
continue;
nbout << gen << "\t" << ind1.xy.first << "\t" << ind1.xy.second << "\t";
for(int m=0; m<m_nMarkers; m++){
nbout << ind1.vgamete_1[m] << "/" << ind1.vgamete_2[m]
<< ((m<m_nMarkers-1) ? "\t": "\n");
}
}
}
/*
void Population::sampleNb(int gen){
vector<map<int,int>> alleles (m_nMarkers);
vector<individual> pop(m_vPop2);
random_shuffle(pop.begin(),pop.end());
vector<int> vN(m_nDistClass,0);
while(pop.size()){
individual ind1 = pop[0];
if(ind1.nWeight_1==0 || ind1.nWeight_2==0){
pop.erase(pop.begin());
continue;
}
int x1 = ind1.xy.first;
int y1 = ind1.xy.second;
bool found = false;
for(unsigned int i = 1; i < pop.size(); i++){
individual ind2 = pop[i];
if(ind2.nWeight_1==0 || ind2.nWeight_2==0){
continue;
}
int x2 = ind2.xy.first;
int y2 = ind2.xy.second;
int d;
if(x1 == x2)
d = abs(y1-y2);
else if(y1 == y2)
d = abs(x1-x2);
else continue;
if(d > m_nDistClass || vN[d-1] >= m_nPairs)
continue;
double sig1 = minEuclideanDist(ind1.xy,m_vPop1[ind1.nParent_1].xy, m_nMaxX, m_nMaxY);
double sig2 = minEuclideanDist(ind1.xy,m_vPop1[ind1.nParent_2].xy, m_nMaxX, m_nMaxY);
double sig3 = minEuclideanDist(ind2.xy,m_vPop1[ind2.nParent_1].xy, m_nMaxX, m_nMaxY);
double sig4 = minEuclideanDist(ind2.xy,m_vPop1[ind2.nParent_2].xy, m_nMaxX, m_nMaxY);
nbout << gen << "\t"<< x1 <<"\t"<< y1
<< "\t" << nbSize(ind1.parent_count) << "\t" << ind1.raw_count << "\t"
<< sig1 << "\t" << sig2 << "\t";
for(int m=0; m<m_nMarkers; m++){
nbout << ind1.vgamete_1[m] << "/" << ind1.vgamete_2[m]
<< ((m<m_nMarkers-1) ? "\t": "\n");
if(verbose){
alleles[m][ind1.vgamete_1[m]] ++;
//alleles[m][ind1.vgamete_2[m]] ++;
}
}
nbout << gen << "\t" << x2 << "\t" << y2
<< "\t" << nbSize(ind2.parent_count) << "\t" << ind2.raw_count << "\t"
<< sig3 << "\t" << sig4 << "\t";
for(int m=0; m<m_nMarkers; m++){
nbout << ind2.vgamete_1[m] << "/" << ind2.vgamete_2[m]
<< ((m<m_nMarkers-1) ? "\t": "\n");
if(verbose){
alleles[m][ind2.vgamete_1[m]] ++;
//alleles[m][ind2.vgamete_2[m]] ++;
}
}
vN[d-1] += 1;
pop.erase(pop.begin()+i);
pop.erase(pop.begin());
found = true;
break;
}
if(!found)
pop.erase(pop.begin());
}
if(verbose){
cout << "Gen: " << gen << " Ko: ";
pout << "Gen: " << gen << " Ko: ";
for(int m=0; m <m_nMarkers; m++){
cout << alleles[m].size() << ((m<m_nMarkers-1) ? " " : "\n");
pout << alleles[m].size() << ((m<m_nMarkers-1) ? " " : "\n");
}
}
}
*/
<file_sep>/src/Pop.h
#ifndef POP_H_INCLUDED
#define POP_H_INCLUDED
#include <vector>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <cmath>
#include <unistd.h>
#include <map>
#include <boost/foreach.hpp>
#include <algorithm>
#include "xorshift64.h"
#include "rexp.h"
#include "disperse.h"
#include "disk.h"
#include "aliastable.h"
typedef pair<int,int> xyCoord;
typedef vector<int> gam;
struct individual
{
unsigned int nWeight_1;
unsigned int nWeight_2;
gam vgamete_1;
gam vgamete_2;
int nParent_1;
int nParent_2;
int ngameteID_1;
int ngameteID_2;
xyCoord xy;
int raw_count;
vector<int> parent_count;
int last_parent;
individual(xyCoord x, unsigned int weight,gam & gamete_1,gam &gamete_2, int parent_1, int parent_2) {
nWeight_1 = weight;
nWeight_2 = weight;
vgamete_1 = gamete_1;
vgamete_2 = gamete_2;
nParent_1 = parent_1;
nParent_2 = parent_2;
ngameteID_1 = 0;
ngameteID_2 = 0;
xy = x;
raw_count = 0;
last_parent = -1;
}
};
class Population
{
private:
int m_nMaxX;
int m_nMaxY;
std::string m_sBound;
int m_nOffspring;
double m_dSigma;
double m_dTotMut;
int m_nMutCount;
int m_nIndividuals;
int m_nMarkers;
int m_nSample;
int m_nDistClass;
int m_nPairs;
int m_nTotGametes;
int m_nAlleles;
xorshift64 m_myrand;
std::ofstream & pout;
std::ofstream & nbout;
bool verbose;
Dispersal disp;
alias_table alias_mut;
map<int,int> m_mMutations;
std::vector<double> m_vdMut;
std::vector<int> m_vSample;
std::vector<individual> m_vPop1;
std::vector<individual> m_vPop2;
int m_nAlleleID;
int setMutCount();
void disperse_step(int parent);
void mutation_step();
void reproduction_step(int offspring);
void mutate_iam(gam & gamete);
void mutate_smm(gam & gamete);
void mutate_kam(gam & gamete);
void sampleIBD(int gen);
void samplePop();
void sampleDist();
void sampleNb(int gen);
float nbSize(vector<int> & counts);
gam make_gamete(gam &parent1, gam &parent2);
protected:
int(Population::*disperse)(int,int);
void(Population::*mutate)(gam &gamete);
public:
Population(std::ofstream &p,std::ofstream &nb, bool v): pout(p), nbout(nb), verbose(v) {};
void initialize(int nMaxX, int nMaxY, int nOffspring, int nMarkers, double dSigma,
vector<double> vdMut, unsigned int seed, int nSample,
string dist_name, float param,
bool fast, int nclass, int npairs, string mut_type, int nAlleles);
void evolve(int m_nGenerations, int m_nBurnIn);
};
#endif // POP_H_INCLUDED
| 2922ba0b2335630145ba5a36edd80bf1fa1c66b7 | [
"C++"
] | 4 | C++ | tfursten/IBD-2N | 0d075e03f065dc465c9eb10df00dd89d6f994bf9 | 57ed84f5b2270e5c242e2e0ea68f3961bf35d4bb |
refs/heads/master | <file_sep># spring-eureka-hystrix-zuul-microservice
<file_sep>package com.fahrul.eureka.client1;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient(value="${feign.name}", url="${feign.url}")
public interface MyFeignClient {
@GetMapping
String client2Response();
}
<file_sep>
spring.application.name=eureka-client-3
server.port=8003 | 1e371836be411e6f8448fe15f1e04dd9d68c4d61 | [
"Markdown",
"Java",
"INI"
] | 3 | Markdown | fahrul87/spring-eureka-hystrix-zuul-microservice | 53ed5b9dd7f6992dd1ddb62d48b643fd61eee89e | 760eb096748cd1c5cb3ba706d0bb79ea4e28a95c |
refs/heads/master | <file_sep>
def #roll
puts #roll
expect(#roll).to be_a(Interger)
expect(#roll).to be > 0
expect(#roll).to be < 7
expect(#roll).to be rand(1..6)
end
| a6cc006ca16faa02a12d918c790561054f05465e | [
"Ruby"
] | 1 | Ruby | James-Mellow/dice-roll-ruby-online-web-prework | 9b782ee88f4f61535ed6caff7a141fda377b1d13 | 611bbd27c89d277424b30fda68bca08cee7caaec |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.